aboutsummaryrefslogtreecommitdiff
path: root/lib/lua/src/liolib.c
blob: 649f9a5951553ee2f1dcade252c9c209f1f49bf0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/*
** $Id: liolib.c,v 2.73.1.4 2010/05/14 15:33:51 roberto Exp $
** Standard I/O (and system) library
** See Copyright Notice in lua.h
*/


#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define liolib_c
#define LUA_LIB

#include "lua.h"

#include "lauxlib.h"
#include "lualib.h"



#define IO_INPUT	1
#define IO_OUTPUT	2


static const char *const fnames[] = {"input", "output"};


static int pushresult (lua_State *L, int i, const char *filename) {
  int en = errno;  /* calls to Lua API may change this value */
  if (i) {
    lua_pushboolean(L, 1);
    return 1;
  }
  else {
    lua_pushnil(L);
    if (filename)
      lua_pushfstring(L, "%s: %s", filename, strerror(en));
    else
      lua_pushfstring(L, "%s", strerror(en));
    lua_pushinteger(L, en);
    return 3;
  }
}


static void fileerror (lua_State *L, int arg, const char *filename) {
  lua_pushfstring(L, "%s: %s", filename, strerror(errno));
  luaL_argerror(L, arg, lua_tostring(L, -1));
}


#define tofilep(L)	((FILE **)luaL_checkudata(L, 1, LUA_FILEHANDLE))


static int io_type (lua_State *L) {
  void *ud;
  luaL_checkany(L, 1);
  ud = lua_touserdata(L, 1);
  lua_getfield(L, LUA_REGISTRYINDEX, LUA_FILEHANDLE);
  if (ud == NULL || !lua_getmetatable(L, 1) || !lua_rawequal(L, -2, -1))
    lua_pushnil(L);  /* not a file */
  else if (*((FILE **)ud) == NULL)
    lua_pushliteral(L, "closed file");
  else
    lua_pushliteral(L, "file");
  return 1;
}


static FILE *tofile (lua_State *L) {
  FILE **f = tofilep(L);
  if (*f == NULL)
    luaL_error(L, "attempt to use a closed file");
  return *f;
}



/*
** When creating file handles, always creates a `closed' file handle
** before opening the actual file; so, if there is a memory error, the
** file is not left opened.
*/
static FILE **newfile (lua_State *L) {
  FILE **pf = (FILE **)lua_newuserdata(L, sizeof(FILE *));
  *pf = NULL;  /* file handle is currently `closed' */
  luaL_getmetatable(L, LUA_FILEHANDLE);
  lua_setmetatable(L, -2);
  return pf;
}


/*
** function to (not) close the standard files stdin, stdout, and stderr
*/
static int io_noclose (lua_State *L) {
  lua_pushnil(L);
  lua_pushliteral(L, "cannot close standard file");
  return 2;
}


/*
** function to close 'popen' files
*/
static int io_pclose (lua_State *L) {
  FILE **p = tofilep(L);
  int ok = lua_pclose(L, *p);
  *p = NULL;
  return pushresult(L, ok, NULL);
}


/*
** function to close regular files
*/
static int io_fclose (lua_State *L) {
  FILE **p = tofilep(L);
  int ok = (fclose(*p) == 0);
  *p = NULL;
  return pushresult(L, ok, NULL);
}


static int aux_close (lua_State *L) {
  lua_getfenv(L, 1);
  lua_getfield(L, -1, "__close");
  return (lua_tocfunction(L, -1))(L);
}


static int io_close (lua_State *L) {
  if (lua_isnone(L, 1))
    lua_rawgeti(L, LUA_ENVIRONINDEX, IO_OUTPUT);
  tofile(L);  /* make sure argument is a file */
  return aux_close(L);
}


static int io_gc (lua_State *L) {
  FILE *f = *tofilep(L);
  /* ignore closed files */
  if (f != NULL)
    aux_close(L);
  return 0;
}


static int io_tostring (lua_State *L) {
  FILE *f = *tofilep(L);
  if (f == NULL)
    lua_pushliteral(L, "file (closed)");
  else
    lua_pushfstring(L, "file (%p)", f);
  return 1;
}


static int io_open (lua_State *L) {
  const char *filename = luaL_checkstring(L, 1);
  const char *mode = luaL_optstring(L, 2, "r");
  FILE **pf = newfile(L);
  *pf = fopen(filename, mode);
  return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
}


/*
** this function has a separated environment, which defines the
** correct __close for 'popen' files
*/
static int io_popen (lua_State *L) {
  const char *filename = luaL_checkstring(L, 1);
  const char *mode = luaL_optstring(L, 2, "r");
  FILE **pf = newfile(L);
  *pf = lua_popen(L, filename, mode);
  return (*pf == NULL) ? pushresult(L, 0, filename) : 1;
}


static int io_tmpfile (lua_State *L) {
  FILE **pf = newfile(L);
  *pf = tmpfile();
  return (*pf == NULL) ? pushresult(L, 0, NULL) : 1;
}


static FILE *getiofile (lua_State *L, int findex) {
  FILE *f;
  lua_rawgeti(L, LUA_ENVIRONINDEX, findex);
  f = *(FILE **)lua_touserdata(L, -1);
  if (f == NULL)
    luaL_error(L, "standard %s file is closed", fnames[findex - 1]);
  return f;
}


static int g_iofile (lua_State *L, int f, const char *mode) {
  if (!lua_isnoneornil(L, 1)) {
    const char *filename = lua_tostring(L, 1);
    if (filename) {
      FILE **pf = newfile(L);
      *pf = fopen(filename, mode);
      if (*pf == NULL)
        fileerror(L, 1, filename);
    }
    else {
      tofile(L);  /* check that it's a valid file handle */
      lua_pushvalue(L, 1);
    }
    lua_rawseti(L, LUA_ENVIRONINDEX, f);
  }
  /* return current value */
  lua_rawgeti(L, LUA_ENVIRONINDEX, f);
  return 1;
}


static int io_input (lua_State *L) {
  return g_iofile(L, IO_INPUT, "r");
}


static int io_output (lua_State *L) {
  return g_iofile(L, IO_OUTPUT, "w");
}


static int io_readline (lua_State *L);


static void aux_lines (lua_State *L, int idx, int toclose) {
  lua_pushvalue(L, idx);
  lua_pushboolean(L, toclose);  /* close/not close file when finished */
  lua_pushcclosure(L, io_readline, 2);
}


static int f_lines (lua_State *L) {
  tofile(L);  /* check that it's a valid file handle */
  aux_lines(L, 1, 0);
  return 1;
}


static int io_lines (lua_State *L) {
  if (lua_isnoneornil(L, 1)) {  /* no arguments? */
    /* will iterate over default input */
    lua_rawgeti(L, LUA_ENVIRONINDEX, IO_INPUT);
    return f_lines(L);
  }
  else {
    const char *filename = luaL_checkstring(L, 1);
    FILE **pf = newfile(L);
    *pf = fopen(filename, "r");
    if (*pf == NULL)
      fileerror(L, 1, filename);
    aux_lines(L, lua_gettop(L), 1);
    return 1;
  }
}


/*
** {======================================================
** READ
** =======================================================
*/


static int read_number (lua_State *L, FILE *f) {
  lua_Number d;
  if (fscanf(f, LUA_NUMBER_SCAN, &d) == 1) {
    lua_pushnumber(L, d);
    return 1;
  }
  else {
    lua_pushnil(L);  /* "result" to be removed */
    return 0;  /* read fails */
  }
}


static int test_eof (lua_State *L, FILE *f) {
  int c = getc(f);
  ungetc(c, f);
  lua_pushlstring(L, NULL, 0);
  return (c != EOF);
}


static int read_line (lua_State *L, FILE *f) {
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  for (;;) {
    size_t l;
    char *p = luaL_prepbuffer(&b);
    if (fgets(p, LUAL_BUFFERSIZE, f) == NULL) {  /* eof? */
      luaL_pushresult(&b);  /* close buffer */
      return (lua_objlen(L, -1) > 0);  /* check whether read something */
    }
    l = strlen(p);
    if (l == 0 || p[l-1] != '\n')
      luaL_addsize(&b, l);
    else {
      luaL_addsize(&b, l - 1);  /* do not include `eol' */
      luaL_pushresult(&b);  /* close buffer */
      return 1;  /* read at least an `eol' */
    }
  }
}


static int read_chars (lua_State *L, FILE *f, size_t n) {
  size_t rlen;  /* how much to read */
  size_t nr;  /* number of chars actually read */
  luaL_Buffer b;
  luaL_buffinit(L, &b);
  rlen = LUAL_BUFFERSIZE;  /* try to read that much each time */
  do {
    char *p = luaL_prepbuffer(&b);
    if (rlen > n) rlen = n;  /* cannot read more than asked */
    nr = fread(p, sizeof(char), rlen, f);
    luaL_addsize(&b, nr);
    n -= nr;  /* still have to read `n' chars */
  } while (n > 0 && nr == rlen);  /* until end of count or eof */
  luaL_pushresult(&b);  /* close buffer */
  return (n == 0 || lua_objlen(L, -1) > 0);
}


static int g_read (lua_State *L, FILE *f, int first) {
  int nargs = lua_gettop(L) - 1;
  int success;
  int n;
  clearerr(f);
  if (nargs == 0) {  /* no arguments? */
    success = read_line(L, f);
    n = first+1;  /* to return 1 result */
  }
  else {  /* ensure stack space for all results and for auxlib's buffer */
    luaL_checkstack(L, nargs+LUA_MINSTACK, "too many arguments");
    success = 1;
    for (n = first; nargs-- && success; n++) {
      if (lua_type(L, n) == LUA_TNUMBER) {
        size_t l = (size_t)lua_tointeger(L, n);
        success = (l == 0) ? test_eof(L, f) : read_chars(L, f, l);
      }
      else {
        const char *p = lua_tostring(L, n);
        luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
        switch (p[1]) {
          case 'n':  /* number */
            success = read_number(L, f);
            break;
          case 'l':  /* line */
            success = read_line(L, f);
            break;
          case 'a':  /* file */
            read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
            success = 1; /* always success */
            break;
          default:
            return luaL_argerror(L, n, "invalid format");
        }
      }
    }
  }
  if (ferror(f))
    return pushresult(L, 0, NULL);
  if (!success) {
    lua_pop(L, 1);  /* remove last result */
    lua_pushnil(L);  /* push nil instead */
  }
  return n - first;
}


static int io_read (lua_State *L) {
  return g_read(L, getiofile(L, IO_INPUT), 1);
}


static int f_read (lua_State *L) {
  return g_read(L, tofile(L), 2);
}


static int io_readline (lua_State *L) {
  FILE *f = *(FILE **)lua_touserdata(L, lua_upvalueindex(1));
  int sucess;
  if (f == NULL)  /* file is already closed? */
    luaL_error(L, "file is already closed");
  sucess = read_line(L, f);
  if (ferror(f))
    return luaL_error(L, "%s", strerror(errno));
  if (sucess) return 1;
  else {  /* EOF */
    if (lua_toboolean(L, lua_upvalueindex(2))) {  /* generator created file? */
      lua_settop(L, 0);
      lua_pushvalue(L, lua_upvalueindex(1));
      aux_close(L);  /* close it */
    }
    return 0;
  }
}

/* }====================================================== */


static int g_write (lua_State *L, FILE *f, int arg) {
  int nargs = lua_gettop(L) - 1;
  int status = 1;
  for (; nargs--; arg++) {
    if (lua_type(L, arg) == LUA_TNUMBER) {
      /* optimization: could be done exactly as for strings */
      status = status &&
          fprintf(f, LUA_NUMBER_FMT, lua_tonumber(L, arg)) > 0;
    }
    else {
      size_t l;
      const char *s = luaL_checklstring(L, arg, &l);
      status = status && (fwrite(s, sizeof(char), l, f) == l);
    }
  }
  return pushresult(L, status, NULL);
}


static int io_write (lua_State *L) {
  return g_write(L, getiofile(L, IO_OUTPUT), 1);
}


static int f_write (lua_State *L) {
  return g_write(L, tofile(L), 2);
}


static int f_seek (lua_State *L) {
  static const int mode[] = {SEEK_SET, SEEK_CUR, SEEK_END};
  static const char *const modenames[] = {"set", "cur", "end", NULL};
  FILE *f = tofile(L);
  int op = luaL_checkoption(L, 2, "cur", modenames);
  long offset = luaL_optlong(L, 3, 0);
  op = fseek(f, offset, mode[op]);
  if (op)
    return pushresult(L, 0, NULL);  /* error */
  else {
    lua_pushinteger(L, ftell(f));
    return 1;
  }
}


static int f_setvbuf (lua_State *L) {
  static const int mode[] = {_IONBF, _IOFBF, _IOLBF};
  static const char *const modenames[] = {"no", "full", "line", NULL};
  FILE *f = tofile(L);
  int op = luaL_checkoption(L, 2, NULL, modenames);
  lua_Integer sz = luaL_optinteger(L, 3, LUAL_BUFFERSIZE);
  int res = setvbuf(f, NULL, mode[op], sz);
  return pushresult(L, res == 0, NULL);
}



static int io_flush (lua_State *L) {
  return pushresult(L, fflush(getiofile(L, IO_OUTPUT)) == 0, NULL);
}


static int f_flush (lua_State *L) {
  return pushresult(L, fflush(tofile(L)) == 0, NULL);
}


static const luaL_Reg iolib[] = {
  {"close", io_close},
  {"flush", io_flush},
  {"input", io_input},
  {"lines", io_lines},
  {"open", io_open},
  {"output", io_output},
  {"popen", io_popen},
  {"read", io_read},
  {"tmpfile", io_tmpfile},
  {"type", io_type},
  {"write", io_write},
  {NULL, NULL}
};


static const luaL_Reg flib[] = {
  {"close", io_close},
  {"flush", f_flush},
  {"lines", f_lines},
  {"read", f_read},
  {"seek", f_seek},
  {"setvbuf", f_setvbuf},
  {"write", f_write},
  {"__gc", io_gc},
  {"__tostring", io_tostring},
  {NULL, NULL}
};


static void createmeta (lua_State *L) {
  luaL_newmetatable(L, LUA_FILEHANDLE);  /* create metatable for file handles */
  lua_pushvalue(L, -1);  /* push metatable */
  lua_setfield(L, -2, "__index");  /* metatable.__index = metatable */
  luaL_register(L, NULL, flib);  /* file methods */
}


static void createstdfile (lua_State *L, FILE *f, int k, const char *fname) {
  *newfile(L) = f;
  if (k > 0) {
    lua_pushvalue(L, -1);
    lua_rawseti(L, LUA_ENVIRONINDEX, k);
  }
  lua_pushvalue(L, -2);  /* copy environment */
  lua_setfenv(L, -2);  /* set it */
  lua_setfield(L, -3, fname);
}


static void newfenv (lua_State *L, lua_CFunction cls) {
  lua_createtable(L, 0, 1);
  lua_pushcfunction(L, cls);
  lua_setfield(L, -2, "__close");
}


LUALIB_API int luaopen_io (lua_State *L) {
  createmeta(L);
  /* create (private) environment (with fields IO_INPUT, IO_OUTPUT, __close) */
  newfenv(L, io_fclose);
  lua_replace(L, LUA_ENVIRONINDEX);
  /* open library */
  luaL_register(L, LUA_IOLIBNAME, iolib);
  /* create (and set) default files */
  newfenv(L, io_noclose);  /* close function for default files */
  createstdfile(L, stdin, IO_INPUT, "stdin");
  createstdfile(L, stdout, IO_OUTPUT, "stdout");
  createstdfile(L, stderr, 0, "stderr");
  lua_pop(L, 1);  /* pop environment for default files */
  lua_getfield(L, -1, "popen");
  newfenv(L, io_pclose);  /* create environment for 'popen' */
  lua_setfenv(L, -2);  /* set fenv for 'popen' */
  lua_pop(L, 1);  /* pop 'popen' */
  return 1;
}

>if (lua_istable(L, 2)) { co->m_physics_override_speed = getfloatfield_default(L, 2, "speed", co->m_physics_override_speed); co->m_physics_override_jump = getfloatfield_default(L, 2, "jump", co->m_physics_override_jump); co->m_physics_override_gravity = getfloatfield_default(L, 2, "gravity", co->m_physics_override_gravity); co->m_physics_override_sneak = getboolfield_default(L, 2, "sneak", co->m_physics_override_sneak); co->m_physics_override_sneak_glitch = getboolfield_default(L, 2, "sneak_glitch", co->m_physics_override_sneak_glitch); co->m_physics_override_sent = false; } else { // old, non-table format if(!lua_isnil(L, 2)){ co->m_physics_override_speed = lua_tonumber(L, 2); co->m_physics_override_sent = false; } if(!lua_isnil(L, 3)){ co->m_physics_override_jump = lua_tonumber(L, 3); co->m_physics_override_sent = false; } if(!lua_isnil(L, 4)){ co->m_physics_override_gravity = lua_tonumber(L, 4); co->m_physics_override_sent = false; } } return 0; } // set_animation(self, frame_range, frame_speed, frame_blend) int ObjectRef::l_set_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if(co == NULL) return 0; // Do it v2f frames = v2f(1, 1); if(!lua_isnil(L, 2)) frames = read_v2f(L, 2); float frame_speed = 15; if(!lua_isnil(L, 3)) frame_speed = lua_tonumber(L, 3); float frame_blend = 0; if(!lua_isnil(L, 4)) frame_blend = lua_tonumber(L, 4); co->setAnimation(frames, frame_speed, frame_blend); return 0; } // set_local_animation(self, {stand/idle}, {walk}, {dig}, {walk+dig}, frame_speed) int ObjectRef::l_set_local_animation(lua_State *L) { //NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; // Do it v2s32 frames[4]; for (int i=0;i<4;i++) { if(!lua_isnil(L, 2+1)) frames[i] = read_v2s32(L, 2+i); } float frame_speed = 30; if(!lua_isnil(L, 6)) frame_speed = lua_tonumber(L, 6); if (!getServer(L)->setLocalPlayerAnimations(player, frames, frame_speed)) return 0; lua_pushboolean(L, true); return 0; } // set_eye_offset(self, v3f first pv, v3f third pv) int ObjectRef::l_set_eye_offset(lua_State *L) { //NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; // Do it v3f offset_first = v3f(0, 0, 0); v3f offset_third = v3f(0, 0, 0); if(!lua_isnil(L, 2)) offset_first = read_v3f(L, 2); if(!lua_isnil(L, 3)) offset_third = read_v3f(L, 3); // Prevent abuse of offset values (keep player always visible) offset_third.X = rangelim(offset_third.X,-10,10); offset_third.Z = rangelim(offset_third.Z,-5,5); /* TODO: if possible: improve the camera colision detetion to allow Y <= -1.5) */ offset_third.Y = rangelim(offset_third.Y,-10,15); //1.5*BS if (!getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third)) return 0; lua_pushboolean(L, true); return 0; } // set_bone_position(self, std::string bone, v3f position, v3f rotation) int ObjectRef::l_set_bone_position(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if(co == NULL) return 0; // Do it std::string bone = ""; if(!lua_isnil(L, 2)) bone = lua_tostring(L, 2); v3f position = v3f(0, 0, 0); if(!lua_isnil(L, 3)) position = read_v3f(L, 3); v3f rotation = v3f(0, 0, 0); if(!lua_isnil(L, 4)) rotation = read_v3f(L, 4); co->setBonePosition(bone, position, rotation); return 0; } // set_attach(self, parent, bone, position, rotation) int ObjectRef::l_set_attach(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ObjectRef *parent_ref = checkobject(L, 2); ServerActiveObject *co = getobject(ref); ServerActiveObject *parent = getobject(parent_ref); if(co == NULL) return 0; if(parent == NULL) return 0; // Do it std::string bone = ""; if(!lua_isnil(L, 3)) bone = lua_tostring(L, 3); v3f position = v3f(0, 0, 0); if(!lua_isnil(L, 4)) position = read_v3f(L, 4); v3f rotation = v3f(0, 0, 0); if(!lua_isnil(L, 5)) rotation = read_v3f(L, 5); co->setAttachment(parent->getId(), bone, position, rotation); return 0; } // set_detach(self) int ObjectRef::l_set_detach(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if(co == NULL) return 0; // Do it co->setAttachment(0, "", v3f(0,0,0), v3f(0,0,0)); return 0; } // set_properties(self, properties) int ObjectRef::l_set_properties(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ServerActiveObject *co = getobject(ref); if(co == NULL) return 0; ObjectProperties *prop = co->accessObjectProperties(); if(!prop) return 0; read_object_properties(L, 2, prop); co->notifyObjectPropertiesModified(); return 0; } /* LuaEntitySAO-only */ // setvelocity(self, {x=num, y=num, z=num}) int ObjectRef::l_setvelocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; v3f pos = checkFloatPos(L, 2); // Do it co->setVelocity(pos); return 0; } // getvelocity(self) int ObjectRef::l_getvelocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it v3f v = co->getVelocity(); pushFloatPos(L, v); return 1; } // setacceleration(self, {x=num, y=num, z=num}) int ObjectRef::l_setacceleration(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // pos v3f pos = checkFloatPos(L, 2); // Do it co->setAcceleration(pos); return 0; } // getacceleration(self) int ObjectRef::l_getacceleration(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it v3f v = co->getAcceleration(); pushFloatPos(L, v); return 1; } // setyaw(self, radians) int ObjectRef::l_setyaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; float yaw = luaL_checknumber(L, 2) * core::RADTODEG; // Do it co->setYaw(yaw); return 0; } // getyaw(self) int ObjectRef::l_getyaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it float yaw = co->getYaw() * core::DEGTORAD; lua_pushnumber(L, yaw); return 1; } // settexturemod(self, mod) int ObjectRef::l_settexturemod(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it std::string mod = luaL_checkstring(L, 2); co->setTextureMod(mod); return 0; } // setsprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2, // select_horiz_by_yawpitch=false) int ObjectRef::l_setsprite(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it v2s16 p(0,0); if(!lua_isnil(L, 2)) p = read_v2s16(L, 2); int num_frames = 1; if(!lua_isnil(L, 3)) num_frames = lua_tonumber(L, 3); float framelength = 0.2; if(!lua_isnil(L, 4)) framelength = lua_tonumber(L, 4); bool select_horiz_by_yawpitch = false; if(!lua_isnil(L, 5)) select_horiz_by_yawpitch = lua_toboolean(L, 5); co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch); return 0; } // DEPRECATED // get_entity_name(self) int ObjectRef::l_get_entity_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it std::string name = co->getName(); lua_pushstring(L, name.c_str()); return 1; } // get_luaentity(self) int ObjectRef::l_get_luaentity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); LuaEntitySAO *co = getluaobject(ref); if(co == NULL) return 0; // Do it luaentity_get(L, co->getId()); return 1; } /* Player-only */ // is_player(self) int ObjectRef::l_is_player(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); lua_pushboolean(L, (player != NULL)); return 1; } // is_player_connected(self) int ObjectRef::l_is_player_connected(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); lua_pushboolean(L, (player != NULL && player->peer_id != 0)); return 1; } // get_player_name(self) int ObjectRef::l_get_player_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL){ lua_pushlstring(L, "", 0); return 1; } // Do it lua_pushstring(L, player->getName()); return 1; } // get_look_dir(self) int ObjectRef::l_get_look_dir(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL) return 0; // Do it float pitch = player->getRadPitch(); float yaw = player->getRadYaw(); v3f v(cos(pitch)*cos(yaw), sin(pitch), cos(pitch)*sin(yaw)); push_v3f(L, v); return 1; } // get_look_pitch(self) int ObjectRef::l_get_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL) return 0; // Do it lua_pushnumber(L, player->getRadPitch()); return 1; } // get_look_yaw(self) int ObjectRef::l_get_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL) return 0; // Do it lua_pushnumber(L, player->getRadYaw()); return 1; } // set_look_pitch(self, radians) int ObjectRef::l_set_look_pitch(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if(co == NULL) return 0; float pitch = luaL_checknumber(L, 2) * core::RADTODEG; // Do it co->setPitch(pitch); return 1; } // set_look_yaw(self, radians) int ObjectRef::l_set_look_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if(co == NULL) return 0; float yaw = luaL_checknumber(L, 2) * core::RADTODEG; // Do it co->setYaw(yaw); return 1; } // set_breath(self, breath) int ObjectRef::l_set_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if(co == NULL) return 0; u16 breath = luaL_checknumber(L, 2); // Do it co->setBreath(breath); co->m_breath_not_sent = true; return 0; } // get_breath(self) int ObjectRef::l_get_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); PlayerSAO* co = getplayersao(ref); if(co == NULL) return 0; // Do it u16 breath = co->getBreath(); lua_pushinteger (L, breath); return 1; } // set_inventory_formspec(self, formspec) int ObjectRef::l_set_inventory_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL) return 0; std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; getServer(L)->reportInventoryFormspecModified(player->getName()); lua_pushboolean(L, true); return 1; } // get_inventory_formspec(self) -> formspec int ObjectRef::l_get_inventory_formspec(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL) return 0; std::string formspec = player->inventory_formspec; lua_pushlstring(L, formspec.c_str(), formspec.size()); return 1; } // get_player_control(self) int ObjectRef::l_get_player_control(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL){ lua_pushlstring(L, "", 0); return 1; } // Do it PlayerControl control = player->getPlayerControl(); lua_newtable(L); lua_pushboolean(L, control.up); lua_setfield(L, -2, "up"); lua_pushboolean(L, control.down); lua_setfield(L, -2, "down"); lua_pushboolean(L, control.left); lua_setfield(L, -2, "left"); lua_pushboolean(L, control.right); lua_setfield(L, -2, "right"); lua_pushboolean(L, control.jump); lua_setfield(L, -2, "jump"); lua_pushboolean(L, control.aux1); lua_setfield(L, -2, "aux1"); lua_pushboolean(L, control.sneak); lua_setfield(L, -2, "sneak"); lua_pushboolean(L, control.LMB); lua_setfield(L, -2, "LMB"); lua_pushboolean(L, control.RMB); lua_setfield(L, -2, "RMB"); return 1; } // get_player_control_bits(self) int ObjectRef::l_get_player_control_bits(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if(player == NULL){ lua_pushlstring(L, "", 0); return 1; } // Do it lua_pushnumber(L, player->keyPressed); return 1; } // hud_add(self, form) int ObjectRef::l_hud_add(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; HudElement *elem = new HudElement; elem->type = (HudElementType)getenumfield(L, 2, "hud_elem_type", es_HudElementType, HUD_ELEM_TEXT); lua_getfield(L, 2, "position"); elem->pos = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); lua_pop(L, 1); lua_getfield(L, 2, "scale"); elem->scale = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); lua_pop(L, 1); elem->name = getstringfield_default(L, 2, "name", ""); elem->text = getstringfield_default(L, 2, "text", ""); elem->number = getintfield_default(L, 2, "number", 0); elem->item = getintfield_default(L, 2, "item", 0); elem->dir = getintfield_default(L, 2, "dir", 0); lua_getfield(L, 2, "alignment"); elem->align = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); lua_pop(L, 1); lua_getfield(L, 2, "offset"); elem->offset = lua_istable(L, -1) ? read_v2f(L, -1) : v2f(); lua_pop(L, 1); lua_getfield(L, 2, "world_pos"); elem->world_pos = lua_istable(L, -1) ? read_v3f(L, -1) : v3f(); lua_pop(L, 1); u32 id = getServer(L)->hudAdd(player, elem); if (id == (u32)-1) { delete elem; return 0; } lua_pushnumber(L, id); return 1; } // hud_remove(self, id) int ObjectRef::l_hud_remove(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; u32 id = -1; if (!lua_isnil(L, 2)) id = lua_tonumber(L, 2); if (!getServer(L)->hudRemove(player, id)) return 0; lua_pushboolean(L, true); return 1; } // hud_change(self, id, stat, data) int ObjectRef::l_hud_change(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; u32 id = !lua_isnil(L, 2) ? lua_tonumber(L, 2) : -1; if (id >= player->hud.size()) return 0; HudElementStat stat = HUD_STAT_NUMBER; if (!lua_isnil(L, 3)) { int statint; std::string statstr = lua_tostring(L, 3); stat = string_to_enum(es_HudElementStat, statint, statstr) ? (HudElementStat)statint : HUD_STAT_NUMBER; } void *value = NULL; HudElement *e = player->hud[id]; if (!e) return 0; switch (stat) { case HUD_STAT_POS: e->pos = read_v2f(L, 4); value = &e->pos; break; case HUD_STAT_NAME: e->name = lua_tostring(L, 4); value = &e->name; break; case HUD_STAT_SCALE: e->scale = read_v2f(L, 4); value = &e->scale; break; case HUD_STAT_TEXT: e->text = lua_tostring(L, 4); value = &e->text; break; case HUD_STAT_NUMBER: e->number = lua_tonumber(L, 4); value = &e->number; break; case HUD_STAT_ITEM: e->item = lua_tonumber(L, 4); value = &e->item; break; case HUD_STAT_DIR: e->dir = lua_tonumber(L, 4); value = &e->dir; break; case HUD_STAT_ALIGN: e->align = read_v2f(L, 4); value = &e->align; break; case HUD_STAT_OFFSET: e->offset = read_v2f(L, 4); value = &e->offset; break; case HUD_STAT_WORLD_POS: e->world_pos = read_v3f(L, 4); value = &e->world_pos; break; } getServer(L)->hudChange(player, id, stat, value); lua_pushboolean(L, true); return 1; } // hud_get(self, id) int ObjectRef::l_hud_get(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; u32 id = lua_tonumber(L, -1); if (id >= player->hud.size()) return 0; HudElement *e = player->hud[id]; if (!e) return 0; lua_newtable(L); lua_pushstring(L, es_HudElementType[(u8)e->type].str); lua_setfield(L, -2, "type"); push_v2f(L, e->pos); lua_setfield(L, -2, "position"); lua_pushstring(L, e->name.c_str()); lua_setfield(L, -2, "name"); push_v2f(L, e->scale); lua_setfield(L, -2, "scale"); lua_pushstring(L, e->text.c_str()); lua_setfield(L, -2, "text"); lua_pushnumber(L, e->number); lua_setfield(L, -2, "number"); lua_pushnumber(L, e->item); lua_setfield(L, -2, "item"); lua_pushnumber(L, e->dir); lua_setfield(L, -2, "dir"); push_v3f(L, e->world_pos); lua_setfield(L, -2, "world_pos"); return 1; } // hud_set_flags(self, flags) int ObjectRef::l_hud_set_flags(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; u32 flags = 0; u32 mask = 0; bool flag; const EnumString *esp = es_HudBuiltinElement; for (int i = 0; esp[i].str; i++) { if (getboolfield(L, 2, esp[i].str, flag)) { flags |= esp[i].num * flag; mask |= esp[i].num; } } if (!getServer(L)->hudSetFlags(player, flags, mask)) return 0; lua_pushboolean(L, true); return 1; } // hud_set_hotbar_itemcount(self, hotbar_itemcount) int ObjectRef::l_hud_set_hotbar_itemcount(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; s32 hotbar_itemcount = lua_tonumber(L, 2); if (!getServer(L)->hudSetHotbarItemcount(player, hotbar_itemcount)) return 0; lua_pushboolean(L, true); return 1; } // hud_set_hotbar_image(self, name) int ObjectRef::l_hud_set_hotbar_image(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; std::string name = lua_tostring(L, 2); getServer(L)->hudSetHotbarImage(player, name); return 1; } // hud_set_hotbar_selected_image(self, name) int ObjectRef::l_hud_set_hotbar_selected_image(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; std::string name = lua_tostring(L, 2); getServer(L)->hudSetHotbarSelectedImage(player, name); return 1; } // set_sky(self, bgcolor, type, list) int ObjectRef::l_set_sky(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; video::SColor bgcolor(255,255,255,255); if (!lua_isnil(L, 2)) bgcolor = readARGB8(L, 2); std::string type = luaL_checkstring(L, 3); std::vector<std::string> params; if (lua_istable(L, 4)) { int table = lua_gettop(L); lua_pushnil(L); while (lua_next(L, table) != 0) { // key at index -2 and value at index -1 if (lua_isstring(L, -1)) params.push_back(lua_tostring(L, -1)); else params.push_back(""); // removes value, keeps key for next iteration lua_pop(L, 1); } } if (type == "skybox" && params.size() != 6) throw LuaError("skybox expects 6 textures"); if (!getServer(L)->setSky(player, bgcolor, type, params)) return 0; lua_pushboolean(L, true); return 1; } // override_day_night_ratio(self, brightness=0...1) int ObjectRef::l_override_day_night_ratio(lua_State *L) { ObjectRef *ref = checkobject(L, 1); Player *player = getplayer(ref); if (player == NULL) return 0; bool do_override = false; float ratio = 0.0f; if (!lua_isnil(L, 2)){ do_override = true; ratio = luaL_checknumber(L, 2); } if (!getServer(L)->overrideDayNightRatio(player, do_override, ratio)) return 0; lua_pushboolean(L, true); return 1; } ObjectRef::ObjectRef(ServerActiveObject *object): m_object(object) { //infostream<<"ObjectRef created for id="<<m_object->getId()<<std::endl; } ObjectRef::~ObjectRef() { /*if(m_object) infostream<<"ObjectRef destructing for id=" <<m_object->getId()<<std::endl; else infostream<<"ObjectRef destructing for id=unknown"<<std::endl;*/ } // Creates an ObjectRef and leaves it on top of stack // Not callable from Lua; all references are created on the C side. void ObjectRef::create(lua_State *L, ServerActiveObject *object) { ObjectRef *o = new ObjectRef(object); //infostream<<"ObjectRef::create: o="<<o<<std::endl; *(void **)(lua_newuserdata(L, sizeof(void *))) = o; luaL_getmetatable(L, className); lua_setmetatable(L, -2); } void ObjectRef::set_null(lua_State *L) { ObjectRef *o = checkobject(L, -1); o->m_object = NULL; } void ObjectRef::Register(lua_State *L) { lua_newtable(L); int methodtable = lua_gettop(L); luaL_newmetatable(L, className); int metatable = lua_gettop(L); lua_pushliteral(L, "__metatable"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); // hide metatable from Lua getmetatable() lua_pushliteral(L, "__index"); lua_pushvalue(L, methodtable); lua_settable(L, metatable); lua_pushliteral(L, "__gc"); lua_pushcfunction(L, gc_object); lua_settable(L, metatable); lua_pop(L, 1); // drop metatable luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // drop methodtable // Cannot be created from Lua //lua_register(L, className, create_object); } const char ObjectRef::className[] = "ObjectRef"; const luaL_reg ObjectRef::methods[] = { // ServerActiveObject luamethod(ObjectRef, remove), luamethod(ObjectRef, getpos), luamethod(ObjectRef, setpos), luamethod(ObjectRef, moveto), luamethod(ObjectRef, punch), luamethod(ObjectRef, right_click), luamethod(ObjectRef, set_hp), luamethod(ObjectRef, get_hp), luamethod(ObjectRef, get_inventory), luamethod(ObjectRef, get_wield_list), luamethod(ObjectRef, get_wield_index), luamethod(ObjectRef, get_wielded_item), luamethod(ObjectRef, set_wielded_item), luamethod(ObjectRef, set_armor_groups), luamethod(ObjectRef, set_physics_override), luamethod(ObjectRef, set_animation), luamethod(ObjectRef, set_bone_position), luamethod(ObjectRef, set_attach), luamethod(ObjectRef, set_detach), luamethod(ObjectRef, set_properties), // LuaEntitySAO-only luamethod(ObjectRef, setvelocity), luamethod(ObjectRef, getvelocity), luamethod(ObjectRef, setacceleration), luamethod(ObjectRef, getacceleration), luamethod(ObjectRef, setyaw), luamethod(ObjectRef, getyaw), luamethod(ObjectRef, settexturemod), luamethod(ObjectRef, setsprite), luamethod(ObjectRef, get_entity_name), luamethod(ObjectRef, get_luaentity), // Player-only luamethod(ObjectRef, is_player), luamethod(ObjectRef, is_player_connected), luamethod(ObjectRef, get_player_name), luamethod(ObjectRef, get_look_dir), luamethod(ObjectRef, get_look_pitch), luamethod(ObjectRef, get_look_yaw), luamethod(ObjectRef, set_look_yaw), luamethod(ObjectRef, set_look_pitch), luamethod(ObjectRef, get_breath), luamethod(ObjectRef, set_breath), luamethod(ObjectRef, set_inventory_formspec), luamethod(ObjectRef, get_inventory_formspec), luamethod(ObjectRef, get_player_control), luamethod(ObjectRef, get_player_control_bits), luamethod(ObjectRef, hud_add), luamethod(ObjectRef, hud_remove), luamethod(ObjectRef, hud_change), luamethod(ObjectRef, hud_get), luamethod(ObjectRef, hud_set_flags), luamethod(ObjectRef, hud_set_hotbar_itemcount), luamethod(ObjectRef, hud_set_hotbar_image), luamethod(ObjectRef, hud_set_hotbar_selected_image), luamethod(ObjectRef, set_sky), luamethod(ObjectRef, override_day_night_ratio), luamethod(ObjectRef, set_local_animation), luamethod(ObjectRef, set_eye_offset), {0,0} };