Subversion Repositories eduke32

Rev

Rev 4515 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2611 helixhorne 1
-- INTERNAL
2034 helixhorne 2
-- definitions of BUILD and game types for the Lunatic Interpreter
3
 
3256 helixhorne 4
local require = require
2034 helixhorne 5
local ffi = require("ffi")
2863 helixhorne 6
local ffiC = ffi.C
2034 helixhorne 7
 
3821 helixhorne 8
-- Lua C API functions.
9
local CF = CF
10
 
3247 helixhorne 11
local bit = bit
3891 helixhorne 12
local coroutine = coroutine
3056 helixhorne 13
local string = string
14
local table = table
3253 helixhorne 15
local math = math
3256 helixhorne 16
 
17
local assert = assert
18
local error = error
3642 helixhorne 19
local getfenv = getfenv
3597 helixhorne 20
local getmetatable = getmetatable
3256 helixhorne 21
local ipairs = ipairs
22
local loadstring = loadstring
23
local pairs = pairs
24
local rawget = rawget
25
local rawset = rawset
3597 helixhorne 26
local select = select
3256 helixhorne 27
local setmetatable = setmetatable
28
local setfenv = setfenv
29
local tonumber = tonumber
3319 helixhorne 30
local tostring = tostring
3256 helixhorne 31
local type = type
32
 
3914 helixhorne 33
-- Create a new module for passing stuff to other modules.
34
local lprivate = {}
35
require("package").loaded.lprivate = lprivate
36
 
3641 helixhorne 37
require("jit.opt").start("maxmcode=10240")  -- in KiB
38
 
3056 helixhorne 39
-- The "gv" global will provide access to C global *scalars* and safe functions.
3406 helixhorne 40
-- NOTE: This exposes C library functions from e.g. the global C namespace, but
41
-- without their declarations, they will be sitting there like a stone.
42
local gv_ = {}
3409 helixhorne 43
-- [key]=<boolean> forbids, [key]=<non-boolean (e.g. table, function)> overrides
3406 helixhorne 44
local gv_access = {}
2786 helixhorne 45
 
2842 helixhorne 46
-- This is for declarations of arrays or pointers which should not be
3060 helixhorne 47
-- accessible through the "gv" global. The "defs_common" module will
3056 helixhorne 48
-- use this function.
3060 helixhorne 49
--
3530 helixhorne 50
-- Notes: do not declare multiple scalars on one line (this is bad:
51
-- "int32_t a, b"). Do not name array arguments (or add a space
3227 helixhorne 52
-- between the identifier and the '[' instead).
3512 helixhorne 53
function decl(str, ...)
3227 helixhorne 54
    -- NOTE that the regexp also catches non-array/non-function identifiers
55
    -- like "user_defs ud;"
2786 helixhorne 56
    for varname in string.gmatch(str, "([%a_][%w_]*)[[(;]") do
3406 helixhorne 57
        if (ffiC._DEBUG_LUNATIC ~= 0) then
58
            print("FORBID "..varname)
59
        end
60
        gv_access[varname] = true
2786 helixhorne 61
    end
62
 
3512 helixhorne 63
    ffi.cdef(str, ...)
2786 helixhorne 64
end
65
 
4147 helixhorne 66
lprivate.decl = decl
67
 
4236 helixhorne 68
ffi.cdef[[
69
enum {
70
    LUNATIC_CLIENT_MAPSTER32 = 0,
71
    LUNATIC_CLIENT_EDUKE32 = 1,
72
 
73
    LUNATIC_CLIENT = LUNATIC_CLIENT_EDUKE32
74
}
75
]]
76
 
3320 helixhorne 77
-- Load the definitions common to the game's and editor's Lua interface.
3056 helixhorne 78
local defs_c = require("defs_common")
3256 helixhorne 79
local cansee = defs_c.cansee
3248 helixhorne 80
local strip_const = defs_c.strip_const
3253 helixhorne 81
local setmtonce = defs_c.setmtonce
2317 helixhorne 82
 
3319 helixhorne 83
-- Must be after loading "defs_common" which redefines "print" to use
84
-- OSD_Printf()
3642 helixhorne 85
local print, printf = print, defs_c.printf
3253 helixhorne 86
 
3319 helixhorne 87
 
3056 helixhorne 88
---=== EDuke32 game definitions ===---
2668 helixhorne 89
 
3564 helixhorne 90
local INV_NAMES = {
91
    "STEROIDS",
92
    "SHIELD",
93
    "SCUBA",
94
    "HOLODUKE",
95
    "JETPACK",
96
    "DUMMY1",
97
    "ACCESS",
98
    "HEATS",
99
    "DUMMY2",
100
    "FIRSTAID",
101
    "BOOTS",
102
}
103
 
104
local WEAPON_NAMES = {
105
    "KNEE",
106
    "PISTOL",
107
    "SHOTGUN",
108
    "CHAINGUN",
109
    "RPG",
110
    "HANDBOMB",
111
    "SHRINKER",
112
    "DEVISTATOR",
113
    "TRIPBOMB",
114
    "FREEZE",
115
    "HANDREMOTE",
116
    "GROW",
117
}
118
 
2317 helixhorne 119
---- game structs ----
2786 helixhorne 120
 
4030 helixhorne 121
lprivate.GET = defs_c.conststruct(INV_NAMES)
122
lprivate.WEAPON = defs_c.conststruct(WEAPON_NAMES)
2786 helixhorne 123
 
4030 helixhorne 124
ffi.cdef([[
2786 helixhorne 125
enum {
4030 helixhorne 126
    GET_MAX = 11,
127
    MAX_WEAPONS = 12,
2786 helixhorne 128
    MAXPLAYERS = 16,
3928 helixhorne 129
    GTICSPERSEC = 30,  // The real number of movement updates per second
2786 helixhorne 130
};
3564 helixhorne 131
]])
2786 helixhorne 132
 
3227 helixhorne 133
ffi.cdef[[
2864 helixhorne 134
struct action {
135
    int16_t startframe, numframes;
136
    int16_t viewtype, incval, delay;
137
};
138
 
139
struct move {
140
    int16_t hvel, vvel;
141
};
142
 
3463 helixhorne 143
#pragma pack(push,1)
2864 helixhorne 144
typedef struct { int32_t id; struct move mv; } con_move_t;
145
typedef struct { int32_t id; struct action ac; } con_action_t;
3463 helixhorne 146
#pragma pack(pop)
2864 helixhorne 147
 
2869 helixhorne 148
typedef struct {
149
    int32_t id;
150
    con_action_t act;
151
    con_move_t mov;
152
    int32_t movflags;
153
} con_ai_t;
3227 helixhorne 154
]]
2869 helixhorne 155
 
3928 helixhorne 156
defs_c.bitint_new_struct_type("int16_t", "SBit16")
3643 helixhorne 157
defs_c.bitint_new_struct_type("int32_t", "SBit32")
3928 helixhorne 158
defs_c.bitint_new_struct_type("uint32_t", "UBit32")
3643 helixhorne 159
 
3227 helixhorne 160
-- Struct template for actor_t. It already has 'const' fields (TODO: might need
161
-- to make more 'const'), but still has array members exposed, so is unsuited
162
-- for external exposure.
163
local ACTOR_STRUCT = [[
3968 helixhorne 164
struct {
3864 helixhorne 165
    const int32_t t_data[10];
2869 helixhorne 166
    const struct move mv;
167
    const struct action ac;
3922 helixhorne 168
    const uint16_t actiontics;
2864 helixhorne 169
 
3643 helixhorne 170
]]..defs_c.bitint_member("SBit32", "flags")..[[
3314 helixhorne 171
    vec3_t bpos; //12b
3261 helixhorne 172
    int32_t floorz,ceilingz,lastvx,lastvy; //16b
173
    int32_t lasttransport; //4b
174
 
3253 helixhorne 175
    const int16_t picnum;
176
    int16_t ang, extra;
177
    const int16_t owner;
3928 helixhorne 178
    // NOTE: not to be confused with .movflags:
179
]]..defs_c.bitint_member("SBit16", "_movflag")..[[
180
    int16_t tempang, timetosleep;
2193 helixhorne 181
 
3874 helixhorne 182
    int16_t stayputsect;
3253 helixhorne 183
    const int16_t dispicnum;
3922 helixhorne 184
    // Movement flags, sprite[i].hitag in C-CON.
185
    // XXX: more research where it was used in EDuke32's C code? (also .lotag <-> actiontics)
186
    // XXX: what if CON code knew of the above implementation detail?
187
]]..defs_c.bitint_member("UBit16", "movflags")..[[
188
    int16_t cgg;
3559 helixhorne 189
 
190
    const int16_t lightId, lightcount, lightmaxrange;
3932 helixhorne 191
    // NOTE: on 32-bit, C's lightptr+filler <=> this dummy:
3559 helixhorne 192
    const union { intptr_t ptr; uint64_t dummy; } _light;
3227 helixhorne 193
}
2786 helixhorne 194
]]
2193 helixhorne 195
 
3435 helixhorne 196
local bcarray = require("bcarray")
197
 
3445 helixhorne 198
local bcheck = require("bcheck")
199
local check_sector_idx, check_tile_idx = bcheck.sector_idx, bcheck.tile_idx
3526 helixhorne 200
local check_sprite_idx = bcheck.sprite_idx
3445 helixhorne 201
local check_weapon_idx, check_inventory_idx = bcheck.weapon_idx, bcheck.inventory_idx
202
local check_sound_idx = bcheck.sound_idx
3883 helixhorne 203
local check_number = bcheck.number
3954 helixhorne 204
local check_type = bcheck.type
3445 helixhorne 205
 
3564 helixhorne 206
bcarray.new("int16_t", 64, "loogie", "int16_x_64")  -- TODO: randomize member names
207
bcarray.new("int16_t", ffiC.MAX_WEAPONS, "weapon", "int16_x_MAX_WEAPONS", WEAPON_NAMES)
208
bcarray.new("int16_t", ffiC.GET_MAX, "inventory", "int16_x_GET_MAX", INV_NAMES)
3435 helixhorne 209
 
3530 helixhorne 210
-- NOTE: writing e.g. "ps.jetpack_on" in Lua when "ps.jetpack_on~=0" was meant
211
-- is probably one of the most commonly committed errors, so we make it a bool
212
-- type instead of uint8_t. The only issue is that if CON coders used these
213
-- fields to store more than just one bit, we're in trouble.
214
-- This will need to be documented and frozen for release.
3227 helixhorne 215
local DUKEPLAYER_STRUCT = [[
3458 helixhorne 216
__attribute__((packed)) struct {
2786 helixhorne 217
    vec3_t pos, opos, vel, npos;
218
    int32_t bobposx, bobposy;
219
    int32_t truefz, truecz, player_par;
220
    int32_t randomflamex, exitx, exity;
221
    int32_t runspeed, max_player_health, max_shield_amount;
3109 helixhorne 222
    int32_t autostep, autostep_sbw;
2786 helixhorne 223
 
224
    uint32_t interface_toggle_flag;
225
 
3409 helixhorne 226
    int32_t pipebombControl, pipebombLifetime, pipebombLifetimeVar;
227
    int32_t tripbombControl, tripbombLifetime, tripbombLifetimeVar;
228
 
3366 helixhorne 229
    int32_t zrange;
230
    int16_t angrange, autoaimang;
231
 
2786 helixhorne 232
    uint16_t max_actors_killed, actors_killed;
4217 helixhorne 233
]]..defs_c.bitint_member("UBit16", "gotweapon")..[[
234
    uint16_t zoom;
3227 helixhorne 235
 
3435 helixhorne 236
    int16_x_64 loogiex;
237
    int16_x_64 loogiey;
2786 helixhorne 238
    int16_t sbs, sound_pitch;
239
 
3253 helixhorne 240
    int16_t ang, oang, angvel;
3653 helixhorne 241
    const<S> int16_t cursectnum;
3253 helixhorne 242
    int16_t look_ang, last_extra, subweapon;
3435 helixhorne 243
    int16_x_MAX_WEAPONS max_ammo_amount;
244
    int16_x_MAX_WEAPONS ammo_amount;
245
    int16_x_GET_MAX inv_amount;
3653 helixhorne 246
    const<I-> int16_t wackedbyactor;
3652 helixhorne 247
    int16_t pyoff, opyoff;
2786 helixhorne 248
 
249
    int16_t horiz, horizoff, ohoriz, ohorizoff;
3253 helixhorne 250
    const int16_t newowner;
251
    int16_t jumping_counter, airleft;
3498 helixhorne 252
    int16_t fta;
3653 helixhorne 253
    const<Q> int16_t ftq;
254
    const int16_t access_wallnum, access_spritenum;
2786 helixhorne 255
    int16_t got_access, weapon_ang, visibility;
3249 helixhorne 256
    int16_t somethingonplayer, on_crane;
257
    const int16_t i;
3253 helixhorne 258
    const int16_t one_parallax_sectnum;
2786 helixhorne 259
    int16_t random_club_frame, one_eighty_count;
3653 helixhorne 260
    const<I-> int16_t dummyplayersprite;
3254 helixhorne 261
    int16_t extra_extra8;
262
    int16_t actorsqu, timebeforeexit;
3653 helixhorne 263
    const<X-> int16_t customexitsound;
3254 helixhorne 264
    int16_t last_pissed_time;
3227 helixhorne 265
 
3435 helixhorne 266
    int16_x_MAX_WEAPONS weaprecs;
2786 helixhorne 267
    int16_t weapon_sway, crack_time, bobcounter;
268
 
269
    int16_t orotscrnang, rotscrnang, dead_flag;   // JBF 20031220: added orotscrnang
270
    int16_t holoduke_on, pycount;
2854 helixhorne 271
    int16_t transporter_hold;
2786 helixhorne 272
 
273
    uint8_t max_secret_rooms, secret_rooms;
274
    uint8_t frag, fraggedself, quick_kick, last_quick_kick;
3530 helixhorne 275
    uint8_t return_to_center;
276
    bool reloading;
3444 helixhorne 277
    const uint8_t weapreccnt;
2786 helixhorne 278
    uint8_t aim_mode, auto_aim, weaponswitch, movement_lock, team;
3652 helixhorne 279
    uint8_t tipincs, hbomb_hold_delay;
3653 helixhorne 280
    const<P> uint8_t frag_ps;
3652 helixhorne 281
    uint8_t kickback_pic;
2786 helixhorne 282
 
3530 helixhorne 283
    uint8_t gm;
284
    bool on_warping_sector;
285
    uint8_t footprintcount, hurt_delay;
286
    bool hbomb_on, jumping_toggle, rapid_fire_hold, on_ground;
3516 helixhorne 287
    // NOTE: there's array indexing with inven_icon, but always after a
288
    // bound check:
3530 helixhorne 289
    uint8_t inven_icon, buttonpalette;
290
    bool over_shoulder_on;
291
    uint8_t show_empty_weapon;
2786 helixhorne 292
 
3530 helixhorne 293
    bool jetpack_on, spritebridge;
294
    uint8_t lastrandomspot;  // unused
295
    bool scuba_on;
296
    uint8_t footprintpal;
297
    bool heat_on;
298
    uint8_t invdisptime;
2786 helixhorne 299
 
3530 helixhorne 300
    bool holster_weapon;
301
    uint8_t falling_counter, footprintshade;
3652 helixhorne 302
    uint8_t refresh_inventory;
3817 helixhorne 303
    const<W> uint8_t last_full_weapon;
2786 helixhorne 304
 
4179 helixhorne 305
    const uint8_t toggle_key_flag;
3530 helixhorne 306
    uint8_t knuckle_incs, knee_incs, access_incs;
2786 helixhorne 307
    uint8_t walking_snd_toggle, palookup, hard_landing, fist_incs;
308
 
4179 helixhorne 309
    int8_t numloogs, loogcnt;
310
    const int8_t scream_voice;
3653 helixhorne 311
    const<W-> int8_t last_weapon;
4179 helixhorne 312
    const int8_t cheat_phase;
313
    int8_t weapon_pos;
3653 helixhorne 314
    const<W-> int8_t wantweaponfire;
315
    const<W> int8_t curr_weapon;
2786 helixhorne 316
 
4260 helixhorne 317
    const uint8_t palette;
3444 helixhorne 318
    palette_t _pals;
3893 helixhorne 319
    int8_t _palsfadespeed, _palsfadenext, _palsfadeprio, _padding2;
3227 helixhorne 320
 
3407 helixhorne 321
    // NOTE: In C, the struct type has no name. We only have it here to define
322
    // a metatype later.
323
    const weaponaccess_t weapon;
324
    const int8_t _padding;
3227 helixhorne 325
}
2786 helixhorne 326
]]
2854 helixhorne 327
 
3469 helixhorne 328
local PROJECTILE_STRUCT = [[
329
struct {
330
    int32_t workslike, cstat;
331
    int32_t hitradius, range, flashcolor;
332
    const int16_t spawns;
3865 helixhorne 333
    const int16_t sound, isound;
334
    int16_t vel;
3469 helixhorne 335
    const int16_t decal, trail;
336
    int16_t tnum, drop;
3865 helixhorne 337
    int16_t offset, bounces;
338
    const int16_t bsound;
3469 helixhorne 339
    int16_t toffset;
340
    int16_t extra, extra_rand;
341
    int8_t sxrepeat, syrepeat, txrepeat, tyrepeat;
342
    int8_t shade, xrepeat, yrepeat, pal;
343
    int8_t movecnt;
344
    uint8_t clipdist;
3866 helixhorne 345
    int8_t filler[2];
346
    int32_t userdata;
3469 helixhorne 347
}
348
]]
349
 
3574 helixhorne 350
-- KEEPINSYNC weapondata_mt below.
351
local WEAPONDATA_STRUCT = "struct {"..table.concat(con_lang.wdata_members, ';').."; }"
352
 
3227 helixhorne 353
local randgen = require("randgen")
2786 helixhorne 354
 
3227 helixhorne 355
local ma_rand = randgen.new(true)  -- initialize to "random" (time-based) seed
356
local ma_count = nil
357
 
358
local function ma_replace_array(typestr, neltstr)
359
    local nelts = tonumber(neltstr)
360
    if (nelts==nil) then
361
        nelts = ffiC[neltstr]
362
        assert(type(nelts)=="number")
363
    end
364
 
365
    local strtab = { "const ", typestr.." " }
366
    for i=1,nelts do
367
        local ch1 = 97 + (ma_rand:getu32() % 25)  -- 'a'..'z'
3435 helixhorne 368
        strtab[i+2] = string.format("_%c%x%s", ch1, ma_count, (i<nelts) and "," or ";")
3227 helixhorne 369
        ma_count = ma_count+1
370
    end
371
 
372
    return table.concat(strtab)
373
end
374
 
3653 helixhorne 375
---=== Protection of scalars in (currently only) DukePlayer_t struct. ===---
376
-- This is more convenient than writing dozens of set-member methods.
377
local prot_scalar_chkfunc = {
378
    S = check_sector_idx,
379
    I = check_sprite_idx,
380
 
381
    P = bcheck.player_idx,
382
    W = check_weapon_idx,
383
    X = check_sound_idx,
384
    Q = bcheck.quote_idx,
385
}
386
 
387
local DukePlayer_prot_allowneg = {}  -- [<member name>] = true if setting <0 allowed
388
local DukePlayer_prot_chkfunc = {}  -- [<member name>] = <checking function>
389
 
390
local function ma_replace_scalar(what, typestr, membname)
391
    DukePlayer_prot_chkfunc[membname] = assert(prot_scalar_chkfunc[what:sub(1,1)])
392
    DukePlayer_prot_allowneg[membname] = (what:sub(2)=="-")
393
    return ma_replace_array(typestr, 1)
394
end
395
 
3227 helixhorne 396
-- Converts a template struct definition to an external one, in which arrays
397
-- have been substituted by randomly named scalar fields.
3653 helixhorne 398
-- <also_scalars>: also handle protected scalars like "const<W-> ..." etc.
399
local function mangle_arrays(structstr, also_scalars)
3227 helixhorne 400
    ma_count = 0
401
    -- NOTE: regexp only works for non-nested arrays and for one array per line.
3653 helixhorne 402
    structstr = structstr:gsub("const%s+([%w_]+)[^\n]+%[([%w_]+)%];", ma_replace_array)
403
 
404
    if (also_scalars) then
405
        -- One protected scalar per line, too.
406
        structstr = structstr:gsub("const<(.-)>%s+([%w_]-)%s+([%w_]-);", ma_replace_scalar)
407
    end
408
 
409
    return structstr
3227 helixhorne 410
end
411
 
3653 helixhorne 412
--print(mangle_arrays(DUKEPLAYER_STRUCT, true))
3227 helixhorne 413
 
3392 helixhorne 414
--- default defines etc.
415
local con_lang = require("con_lang")
416
 
3227 helixhorne 417
ffi.cdef([[
3407 helixhorne 418
typedef struct { int32_t _p; } weaponaccess_t;
419
 
2786 helixhorne 420
typedef struct {
3928 helixhorne 421
]]..defs_c.bitint_member("UBit32", "bits")..[[
2786 helixhorne 422
    int16_t fvel, svel; // 4b
423
    int8_t avel, horz; // 2b
424
    int8_t extbits, filler; // 2b
425
} input_t;
426
 
3458 helixhorne 427
typedef
428
]].. mangle_arrays(ACTOR_STRUCT) ..[[
429
actor_t;
430
 
431
typedef
3653 helixhorne 432
]].. mangle_arrays(DUKEPLAYER_STRUCT, true) ..[[
3458 helixhorne 433
DukePlayer_t;
434
 
3463 helixhorne 435
typedef __attribute__((packed)) struct {
2786 helixhorne 436
    DukePlayer_t *ps;
437
    input_t *sync;
438
 
439
    int32_t netsynctime;
440
    int16_t ping, filler;
441
    int32_t pcolor, pteam;
442
    uint8_t frags[MAXPLAYERS], wchoice[MAX_WEAPONS];
443
 
3109 helixhorne 444
    char vote, gotvote, pingcnt, playerquitflag, ready;
2786 helixhorne 445
    char user_name[32];
446
    uint32_t revision;
447
} playerdata_t;
3259 helixhorne 448
 
449
typedef struct {
3408 helixhorne 450
    int32_t cur, count;
451
    int32_t gunposx, lookhalfang;
452
    int32_t gunposy, lookhoriz;
453
    int32_t shade;
454
} hudweapon_t;
455
 
3469 helixhorne 456
typedef
3590 helixhorne 457
]].. WEAPONDATA_STRUCT ..[[
458
weapondata_t;
459
 
460
typedef
3469 helixhorne 461
]].. PROJECTILE_STRUCT ..[[
462
projectile_t;
3259 helixhorne 463
 
464
typedef struct {
3939 helixhorne 465
    uint32_t _flags;  // XXX: do we want to have this accessible at game time?
4291 helixhorne 466
    int32_t _cacherange;
3562 helixhorne 467
    const projectile_t _defproj;
3259 helixhorne 468
} tiledata_t;
2291 helixhorne 469
 
3405 helixhorne 470
typedef struct {
471
    vec3_t pos;
472
    int32_t dist, clock;
473
    int16_t ang, horiz;
3887 helixhorne 474
    int16_t sect;  // NOTE: protected in camera_mt's __newindex
3405 helixhorne 475
} camera_t;
476
 
2319 helixhorne 477
enum
478
{
479
    MAXMOUSEBUTTONS = 10,
480
    MAXMOUSEAXES = 2,
481
    MAXJOYBUTTONS = (32+4),
482
    MAXJOYAXES = 8,
483
    NUMGAMEFUNCTIONS = 56,
4472 hendricks2 484
    MAXRIDECULE = 10,
485
    MAXRIDECULELENGTH = 40,
486
    MAXSAVEGAMES = 10,
487
    MAXSAVEGAMENAME = 22,
488
    MAXPWLOCKOUT = 128,
489
    MAXRTSNAME = 128,
2319 helixhorne 490
};
2298 helixhorne 491
 
492
typedef struct {
493
    int32_t const_visibility,uw_framerate;
494
    int32_t camera_time,folfvel,folavel,folx,foly,fola;
495
    int32_t reccnt,crosshairscale;
496
 
497
    int32_t runkey_mode,statusbarscale,mouseaiming,weaponswitch,drawweapon;   // JBF 20031125
498
    int32_t democams,color,msgdisptime,statusbarmode;
499
    int32_t m_noexits,noexits,autovote,automsg,idplayers;
500
    int32_t team, viewbob, weaponsway, althud, weaponscale, textscale;
501
 
502
    int32_t entered_name,screen_tilting,shadows,fta_on,executions,auto_run;
503
    int32_t coords,tickrate,levelstats,m_coop,coop,screen_size,lockout,crosshair;
504
    int32_t playerai,angleinterpolation,obituaries;
505
 
506
    int32_t respawn_monsters,respawn_items,respawn_inventory,recstat,monsters_off,brightness;
507
    int32_t m_respawn_items,m_respawn_monsters,m_respawn_inventory,m_recstat,m_monsters_off,detail;
508
    int32_t m_ffire,ffire,m_player_skill,m_level_number,m_volume_number,multimode;
509
    int32_t player_skill,level_number,volume_number,m_marker,marker,mouseflip;
510
 
511
    int32_t configversion;
512
 
513
    int16_t pause_on,from_bonus;
514
    int16_t camerasprite,last_camsprite;
515
    int16_t last_level,secretlevel, bgstretch;
516
 
517
    struct {
518
        int32_t UseJoystick;
519
        int32_t UseMouse;
520
        int32_t AutoAim;
521
        int32_t ShowOpponentWeapons;
522
        int32_t MouseDeadZone,MouseBias;
523
        int32_t SmoothInput;
524
 
525
        // JBF 20031211: Store the input settings because
526
        // (currently) jmact can't regurgitate them
2319 helixhorne 527
        int32_t MouseFunctions[MAXMOUSEBUTTONS][2];
528
        int32_t MouseDigitalFunctions[MAXMOUSEAXES][2];
529
        int32_t MouseAnalogueAxes[MAXMOUSEAXES];
530
        int32_t MouseAnalogueScale[MAXMOUSEAXES];
531
        int32_t JoystickFunctions[MAXJOYBUTTONS][2];
532
        int32_t JoystickDigitalFunctions[MAXJOYAXES][2];
533
        int32_t JoystickAnalogueAxes[MAXJOYAXES];
534
        int32_t JoystickAnalogueScale[MAXJOYAXES];
535
        int32_t JoystickAnalogueDead[MAXJOYAXES];
536
        int32_t JoystickAnalogueSaturate[MAXJOYAXES];
537
        uint8_t KeyboardKeys[NUMGAMEFUNCTIONS][2];
2298 helixhorne 538
 
539
        //
540
        // Sound variables
541
        //
542
        int32_t FXDevice;
543
        int32_t MusicDevice;
4004 helixhorne 544
        int32_t MasterVolume;
2298 helixhorne 545
        int32_t FXVolume;
546
        int32_t MusicVolume;
547
        int32_t SoundToggle;
548
        int32_t MusicToggle;
549
        int32_t VoiceToggle;
550
        int32_t AmbienceToggle;
551
 
552
        int32_t NumVoices;
553
        int32_t NumChannels;
554
        int32_t NumBits;
555
        int32_t MixRate;
556
 
557
        int32_t ReverseStereo;
558
 
559
        //
560
        // Screen variables
561
        //
562
 
563
        int32_t ScreenMode;
564
 
565
        int32_t ScreenWidth;
566
        int32_t ScreenHeight;
567
        int32_t ScreenBPP;
568
 
569
        int32_t ForceSetup;
570
        int32_t NoAutoLoad;
571
 
3516 helixhorne 572
        const int32_t scripthandle;
2298 helixhorne 573
        int32_t setupread;
574
 
575
        int32_t CheckForUpdates;
576
        int32_t LastUpdateCheck;
577
        int32_t useprecache;
578
    } config;
579
 
580
    char overhead_on,last_overhead,showweapons;
581
    char god,warp_on,cashman,eog,showallmap;
2454 helixhorne 582
    char show_help,scrollmode,noclip;
4472 hendricks2 583
    char ridecule[MAXRIDECULE][MAXRIDECULELENGTH];
584
    char savegame[MAXSAVEGAMES][MAXSAVEGAMENAME];
585
    char pwlockout[MAXPWLOCKOUT],rtsname[MAXRTSNAME];
2298 helixhorne 586
    char display_bonus_screen;
587
    char show_level_text;
588
} user_defs;
3512 helixhorne 589
 
590
typedef struct {
591
    int32_t partime, designertime;
592
    char *name, *filename, *musicfn, *alt_musicfn;
593
    void *savedstate;
594
} map_t;
2786 helixhorne 595
]])
2193 helixhorne 596
 
3931 helixhorne 597
bcarray.new("weapondata_t", ffiC.MAX_WEAPONS, "weapon", "weapondata_x_MAX_WEAPONS", WEAPON_NAMES)
4112 helixhorne 598
bcarray.new("int32_t", con_lang.MAXSESSIONVARS, "sessionvar", "int32_x_MAXSESSIONVARS")
3931 helixhorne 599
 
3409 helixhorne 600
-- EXTERNALLY EXPOSED GAME VARIABLES
601
ffi.cdef[[
602
const int32_t screenpeek;
603
hudweapon_t hudweap;
3556 helixhorne 604
int32_t g_logoFlags;
3409 helixhorne 605
]]
606
 
607
-- INTERNAL VARIABLES/FUNCTIONS
3516 helixhorne 608
decl("map_t MapInfo[$*$];", con_lang.MAXVOLUMES+1, con_lang.MAXLEVELS)
3872 helixhorne 609
decl("char EpisodeNames[$][33];", con_lang.MAXVOLUMES)
3512 helixhorne 610
 
2786 helixhorne 611
decl[[
4285 helixhorne 612
const int32_t myconnectindex;
4031 helixhorne 613
int32_t g_RETURN;
3787 helixhorne 614
int32_t g_elCONSize;
615
char *g_elCON;
616
void El_SetCON(const char *conluacode);
4118 helixhorne 617
void El_OnError(const char *str);
3787 helixhorne 618
 
3891 helixhorne 619
char *g_elSavecode;
620
void El_FreeSaveCode(void);
4119 helixhorne 621
const char *(*El_SerializeGamevars)(int32_t *slenptr, int32_t levelnum);
622
int32_t (*El_RestoreGamevars)(const char *savecode);
4370 helixhorne 623
int32_t (*El_GetLabelValue)(const char *label);
3796 helixhorne 624
 
3512 helixhorne 625
const char *s_buildRev;
2786 helixhorne 626
const char *g_sizes_of_what[];
627
int32_t g_sizes_of[];
4236 helixhorne 628
int32_t g_elFirstTime;
3320 helixhorne 629
int32_t g_elCallDepth;
3821 helixhorne 630
int32_t block_deletesprite;
3788 helixhorne 631
const char **g_elModules;
3516 helixhorne 632
char g_modDir[];
4112 helixhorne 633
int32_x_MAXSESSIONVARS g_elSessionVar;
2319 helixhorne 634
actor_t actor[MAXSPRITES];
3406 helixhorne 635
camera_t g_camera;
2298 helixhorne 636
user_defs ud;
2786 helixhorne 637
playerdata_t g_player[MAXPLAYERS];
3477 helixhorne 638
DukePlayer_t *g_player_ps[MAXPLAYERS];
3931 helixhorne 639
weapondata_x_MAX_WEAPONS g_playerWeapon[MAXPLAYERS];
3848 helixhorne 640
weapondata_t g_weaponOverridden[MAX_WEAPONS];
3943 helixhorne 641
int16_t WeaponPickupSprites[MAX_WEAPONS];
3345 helixhorne 642
tiledata_t g_tile[MAXTILES];
3463 helixhorne 643
projectile_t ProjectileData[MAXTILES];
644
projectile_t SpriteProjectile[MAXSPRITES];
2923 helixhorne 645
 
3830 helixhorne 646
int32_t g_noResetVars;
647
void (*A_ResetVars)(int32_t iActor);
648
 
3847 helixhorne 649
// Used from lunacon.lua for dynamic {tile,sound} remapping:
3568 helixhorne 650
struct
651
{
652
    const char *str;
653
    int32_t *dynvalptr;
654
    const int16_t staticval;
3847 helixhorne 655
} g_dynTileList[], g_dynSoundList[];
3568 helixhorne 656
 
3357 helixhorne 657
char *ScriptQuotes[];
658
 
2923 helixhorne 659
const int32_t playerswhenstarted;
3324 helixhorne 660
int16_t g_spriteDeleteQueueSize;
661
int16_t BlimpSpawnSprites[15];
3343 helixhorne 662
int32_t g_scriptVersion;
3409 helixhorne 663
const int32_t g_currentFrameRate;
3431 helixhorne 664
const int32_t g_currentMenu;
3480 helixhorne 665
uint16_t g_earthquakeTime;
3928 helixhorne 666
uint32_t g_moveThingsCount;
3516 helixhorne 667
char CheatKeys[2];
3247 helixhorne 668
 
3520 helixhorne 669
// Must not have functions here that may call events directly or
670
// indirectly. See lunatic_game.c.
3519 helixhorne 671
 
3247 helixhorne 672
int32_t A_IncurDamage(int32_t sn);  // not bound-checked!
3487 helixhorne 673
int32_t G_CheckActivatorMotion(int32_t lotag);
3254 helixhorne 674
int32_t A_Dodge(spritetype *s);
3491 helixhorne 675
int32_t A_MoveSprite(int32_t spritenum, const vec3_t *change, uint32_t cliptype);
3357 helixhorne 676
void P_DoQuote(int32_t q, DukePlayer_t *p);
3523 helixhorne 677
void P_SetGamePalette(DukePlayer_t *player, uint8_t palid, int32_t set);
3504 helixhorne 678
void G_AddUserQuote(const char *daquote);
3357 helixhorne 679
void G_ClearCameraView(DukePlayer_t *ps);
3480 helixhorne 680
void G_DrawTileGeneric(int32_t x, int32_t y, int32_t zoom, int32_t tilenum,
681
                       int32_t shade, int32_t orientation, int32_t p);
3487 helixhorne 682
void G_InitTimer(int32_t ticspersec);
683
void G_GetTimeDate(int32_t *vals);
684
int32_t G_ToggleWallInterpolation(int32_t w, int32_t doset);
3491 helixhorne 685
int32_t G_StartTrack(int32_t level);
3640 helixhorne 686
int32_t VM_CheckSquished2(int32_t i, int32_t snum);
3656 helixhorne 687
void M_ChangeMenu(int32_t cm);
3366 helixhorne 688
 
3504 helixhorne 689
const char *KB_ScanCodeToString(uint8_t scancode);
690
 
3366 helixhorne 691
int32_t A_CheckAnySoundPlaying(int32_t i);
692
int32_t S_CheckSoundPlaying(int32_t i, int32_t num);
3373 helixhorne 693
void S_StopEnvSound(int32_t num, int32_t i);
3431 helixhorne 694
int32_t FX_StopAllSounds(void);
695
void S_ChangeSoundPitch(int32_t num, int32_t i, int32_t pitchoffset);
3501 helixhorne 696
 
697
int32_t minitext_(int32_t x,int32_t y,const char *t,int32_t s,int32_t p,int32_t sb);
698
void G_DrawTXDigiNumZ(int32_t starttile, int32_t x,int32_t y,int32_t n,int32_t s,int32_t pal,
699
                      int32_t cs,int32_t x1, int32_t y1, int32_t x2, int32_t y2, int32_t z);
700
int32_t G_PrintGameText(int32_t f,  int32_t tile, int32_t x,  int32_t y,  const char *t,
701
                        int32_t s,  int32_t p,    int32_t o,
702
                        int32_t x1, int32_t y1,   int32_t x2, int32_t y2, int32_t z);
3845 helixhorne 703
typedef struct {
704
    int32_t x, y;
705
} vec2_t;
706
vec2_t G_ScreenText(const int32_t font,
707
                    int32_t x, int32_t y, const int32_t z, const int32_t blockangle, const int32_t charangle,
4428 helixhorne 708
                    const char *str, const int32_t shade, int32_t pal, int32_t o, int32_t alpha,
3845 helixhorne 709
                    int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween, const int32_t f,
710
                    const int32_t x1, const int32_t y1, const int32_t x2, const int32_t y2);
711
vec2_t G_ScreenTextSize(const int32_t font,
712
                        int32_t x, int32_t y, const int32_t z, const int32_t blockangle,
713
                        const char *str, const int32_t o,
714
                        int32_t xspace, int32_t yline, int32_t xbetween, int32_t ybetween,
715
                        const int32_t f,
716
                        int32_t x1, int32_t y1, int32_t x2, int32_t y2);
717
 
3794 helixhorne 718
void G_SaveMapState(void);
719
void G_RestoreMapState(void);
2193 helixhorne 720
]]
721
 
2837 helixhorne 722
decl[[
723
int32_t kopen4loadfrommod(const char *filename, char searchfirst);
3343 helixhorne 724
 
3388 helixhorne 725
char **g_scriptModules;
726
int32_t g_scriptModulesNum;
727
 
3343 helixhorne 728
const char *G_ConFile(void);
729
void G_DoGameStartup(const int32_t *params);
3406 helixhorne 730
int32_t C_DefineSound(int32_t sndidx, const char *fn, int32_t args [5]);
3373 helixhorne 731
void C_DefineMusic(int32_t vol, int32_t lev, const char *fn);
3357 helixhorne 732
void C_DefineQuote(int32_t qnum, const char *qstr);
3373 helixhorne 733
void C_DefineVolumeName(int32_t vol, const char *name);
3375 helixhorne 734
void C_DefineSkillName(int32_t skill, const char *name);
3373 helixhorne 735
void C_DefineLevelName(int32_t vol, int32_t lev, const char *fn,
736
                       int32_t partime, int32_t designertime,
737
                       const char *levelname);
3463 helixhorne 738
void C_DefineProjectile(int32_t j, int32_t what, int32_t val);
3516 helixhorne 739
void C_DefineGameFuncName(int32_t idx, const char *name);
3826 helixhorne 740
void C_DefineGameType(int32_t idx, int32_t flags, const char *name);
3516 helixhorne 741
int32_t C_SetDefName(const char *name);
4143 helixhorne 742
void C_SetCfgName(const char *cfgname);
3533 helixhorne 743
 
744
int32_t SCRIPT_GetNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t *number);
745
void SCRIPT_PutNumber(int32_t scripthandle, const char *sectionname, const char *entryname, int32_t number,
746
                      int32_t hexadecimal, int32_t defaultvalue);
2837 helixhorne 747
]]
748
 
2857 helixhorne 749
 
2863 helixhorne 750
-- http://lua-users.org/wiki/SandBoxes says "potentially unsafe"
751
-- as it allows to see implementations of functions.
752
--local string_dump = string.dump
753
string.dump = nil
754
 
755
 
2786 helixhorne 756
-- sanity-check struct type sizes
3109 helixhorne 757
local good = true
3865 helixhorne 758
for i=0,10 do
3109 helixhorne 759
    local what = ffi.string(ffiC.g_sizes_of_what[i])
760
    local fsz = ffi.sizeof(what)
761
    local csz = ffiC.g_sizes_of[i]
3407 helixhorne 762
    if (ffiC._DEBUG_LUNATIC ~= 0) then
763
        print(i..": "..what..": C sizeof = "..tostring(csz)..", FFI sizeof = "..tostring(fsz))
764
    end
3109 helixhorne 765
    if (fsz ~= csz) then
766
        good = false;
767
    end
2786 helixhorne 768
end
769
 
3109 helixhorne 770
if (not good) then
771
    error("Some sizes don't match between C and LuaJIT/FFI.")
772
end
2864 helixhorne 773
 
3109 helixhorne 774
 
3477 helixhorne 775
--== "player" global, needed by the "control" module ==--
776
 
4209 helixhorne 777
local player_static_members = defs_c.static_members_tab()
3477 helixhorne 778
 
4047 helixhorne 779
--[[
3843 helixhorne 780
player_static_members._INPUT_BITS = defs_c.conststruct
3477 helixhorne 781
{
782
    JUMP =                      1,
783
    CROUCH =                    2,
784
    FIRE =                      4,
785
    AIM_UP =                    8,
786
    AIM_DOWN =                 16,
787
    RUNNING =                  32,
788
    LOOK_LEFT =                64,
789
    LOOK_RIGHT =              128,
790
    -- weapons...
791
    STEROIDS =               4096,
792
    LOOK_UP =                8192,
793
    LOOK_DOWN =             16384,
794
    NIGHTVISION =           32768,
795
    MEDKIT =                65536,
796
    RESERVED =             131072,
797
    CENTER_VIEW =          262144,
798
    HOLSTER_WEAPON =       524288,
799
    INVENTORY_LEFT =      1048576,
800
    PAUSE =               2097152,
801
    QUICK_KICK =          4194304,
802
    AIM_MODE =            8388608,
803
    HOLODUKE =           16777216,
804
    JETPACK =            33554432,
805
    QUIT =               67108864,
806
    INVENTORY_RIGHT =   134217728,
807
    TURN_AROUND =       268435456,
808
    OPEN =              536870912,
809
    INVENTORY =        1073741824,
810
    ESC =              2147483648,
3253 helixhorne 811
}
812
 
3843 helixhorne 813
player_static_members._INPUT_EXT_BITS = defs_c.conststruct
3477 helixhorne 814
{
3597 helixhorne 815
    MOVE_FORWARD =  1,
816
    MOVE_BACKWARD = 2,
817
    STRAFE_LEFT =   4,
818
    STRAFE_RIGHT =  8,
819
    TURN_LEFT =    16,
820
    TURN_RIGHT =   32,
3477 helixhorne 821
}
4047 helixhorne 822
--]]
3477 helixhorne 823
 
3928 helixhorne 824
local band = bit.band
825
local lsh = bit.lshift
826
 
827
do
828
    -- player.all() iterator
829
    local function iter_allplayers(_nil, pli)
830
        if (pli+1 < ffiC.playerswhenstarted) then
831
            return pli+1
832
        end
833
    end
834
 
835
    function player_static_members.all()
836
        return iter_allplayers, nil, -1
837
    end
838
 
839
    -- player.holdskey(pli, keyname)
840
    local KEYS = {  -- SK_CROUCH etc. -- "sync keys"
841
        CROUCH = lsh(1,1),
842
        RUN = lsh(1,5),
843
        OPEN = lsh(1,29),
844
    }
845
 
846
    function player_static_members.holdskey(pli, keyname)
847
        bcheck.player_idx(pli)
848
        if (KEYS[keyname] == nil) then
849
            error("invalid key name: "..tostring(keyname), 2)
850
        end
851
 
852
        return ffiC.g_player[pli].sync.bitsbits:test(KEYS[keyname])
853
    end
854
end
855
 
856
local player_holdskey = player_static_members.holdskey
857
 
3597 helixhorne 858
-- Actor flags
4209 helixhorne 859
local actor_static_members = defs_c.static_members_tab()
3597 helixhorne 860
do
861
    local our_SFLAG = {}
862
    local ext_SFLAG = con_lang.labels[4]  -- external actor flags only
863
    local USER_MASK = 0
864
 
865
    for name, flag in pairs(ext_SFLAG) do
866
        our_SFLAG[name:sub(7)] = flag  -- strip "SFLAG_"
867
        USER_MASK = bit.bor(USER_MASK, flag)
868
    end
869
 
870
    -- Add a couple of convenience defines.
871
    our_SFLAG.enemy = con_lang.SFLAG.SFLAG_BADGUY
872
    our_SFLAG.enemystayput = con_lang.SFLAG.SFLAG_BADGUY + con_lang.SFLAG.SFLAG_BADGUYSTAYPUT
873
    our_SFLAG.rotfixed = con_lang.SFLAG.SFLAG_ROTFIXED
874
 
3629 helixhorne 875
    -- Callback function chaining control flags.
4374 helixhorne 876
    our_SFLAG.replace = 0x08000000
877
    our_SFLAG.replace_soft = 0x08000000  -- compat
878
    our_SFLAG.replace_hard = 0x08000000  -- compat, deprecated
3829 helixhorne 879
    our_SFLAG.chain_beg = 0x20000000
880
    our_SFLAG.chain_end = 0x40000000
3873 helixhorne 881
    our_SFLAG._CHAIN_MASK_ACTOR = 0x78000000
882
    our_SFLAG._CHAIN_MASK_EVENT = 0x68000000
3629 helixhorne 883
 
3597 helixhorne 884
    -- XXX: CON doesn't export BADGUYSTAYPUT or ROTFIXED SFLAGs, but they are considered
885
    -- external for Lunatic.
886
    our_SFLAG.USER_MASK = bit.bor(USER_MASK, our_SFLAG.enemystayput, our_SFLAG.rotfixed)
887
 
888
    actor_static_members.FLAGS = defs_c.conststruct(our_SFLAG)
3860 helixhorne 889
 
890
    -- Sprite status numbers. Kept in 'actor', because it's more of a game-side
891
    -- concept (event though status lists are implemented in the engine), and
892
    -- to prevent confusion with sprite.CSTAT.
893
    local our_STAT = {}
894
 
895
    for name, statnum in pairs(con_lang.STAT) do
896
        -- Strip 'STAT_'.
897
        our_STAT[name:sub(6)] = statnum
898
    end
899
 
900
    actor_static_members.STAT = defs_c.conststruct(our_STAT)
3887 helixhorne 901
 
3917 helixhorne 902
    actor_static_members.MOVFLAGS = defs_c.conststruct
903
    {
904
        -- NOTE: no underscores, like in DEFS.CON.
905
        faceplayer = 1,
906
        geth = 2,
907
        getv = 4,
908
        randomangle = 8,
909
        faceplayerslow = 16,
910
        spin = 32,
911
        faceplayersmart = 64,
912
        fleeenemy = 128,
4378 helixhorne 913
        jumptoplayer_only = 256,
914
        jumptoplayer_bits = 257,  -- NOTE: two bits set!
3917 helixhorne 915
        jumptoplayer = 257,
916
        seekplayer = 512,
917
        furthestdir = 1024,
918
        dodgebullet = 4096,
919
    }
3597 helixhorne 920
end
921
 
3924 helixhorne 922
function actor_static_members.fall(i)
923
    check_sprite_idx(i)
924
    CF.VM_FallSprite(i)
925
end
926
 
3821 helixhorne 927
-- Delete sprite with index <i>.
928
function actor_static_members.delete(i)
929
    check_sprite_idx(i)
930
 
931
    if (ffiC.sprite[i].statnum == ffiC.MAXSTATUS) then
932
        error("Attempt to delete a sprite already not in the game world", 2)
933
    end
934
 
935
    if (ffiC.block_deletesprite ~= 0) then
936
        error("Attempt to delete sprite in EVENT_EGS", 2)
937
    end
938
 
3826 helixhorne 939
    -- TODO_MP
3821 helixhorne 940
    if (ffiC.g_player_ps[0].i == i) then
941
        error("Attempt to delete player 0's APLAYER sprite", 2)
942
    end
943
 
944
    CF.A_DeleteSprite(i)
945
end
946
 
4209 helixhorne 947
local tile_static_members = defs_c.static_members_tab()
3597 helixhorne 948
do
949
    tile_static_members.sizx = defs_c.creategtab(ffiC.tilesizx, ffiC.MAXTILES, "tilesizx[]")
950
    tile_static_members.sizy = defs_c.creategtab(ffiC.tilesizy, ffiC.MAXTILES, "tilesizy[]")
951
end
3562 helixhorne 952
 
3529 helixhorne 953
-- XXX: error message will say "g_player_ps"
3477 helixhorne 954
player = setmtonce({}, defs_c.GenStructMetatable("g_player_ps", "playerswhenstarted", player_static_members))
955
 
3345 helixhorne 956
-- needed by "control"
3597 helixhorne 957
actor = setmtonce({}, defs_c.GenStructMetatable("actor", "MAXSPRITES", actor_static_members))
3829 helixhorne 958
-- Some bitwise NOTs of various actor flag masks.
959
local BNOT = {
960
    USER_MASK = bit.bnot(actor.FLAGS.USER_MASK),
3873 helixhorne 961
    CHAIN_MASK_ACTOR = bit.bnot(actor.FLAGS._CHAIN_MASK_ACTOR),
962
    CHAIN_MASK_EVENT = bit.bnot(actor.FLAGS._CHAIN_MASK_EVENT),
3829 helixhorne 963
}
3345 helixhorne 964
 
3463 helixhorne 965
local projectile = defs_c.creategtab(ffiC.ProjectileData, ffiC.MAXTILES, "projectile[]")
3562 helixhorne 966
local g_tile = setmtonce({}, defs_c.GenStructMetatable("g_tile", "MAXTILES", tile_static_members))
3463 helixhorne 967
 
2864 helixhorne 968
--== Custom operations for BUILD data structures ==--
3345 helixhorne 969
-- Among other things, declares struct action and struct move, and their
970
-- ID-wrapped types con_action_t and con_move_t
2871 helixhorne 971
local con = require("control")
3887 helixhorne 972
local isenemytile = con.isenemytile
2864 helixhorne 973
 
3427 helixhorne 974
-- Add game-side metamethods to "spritetype" and register it with "metatype"
3452 helixhorne 975
local spr_mt_index_add = {
976
    isenemy = function(s)
3887 helixhorne 977
        return isenemytile(s.picnum)
3452 helixhorne 978
    end,
979
}
980
defs_c.finish_spritetype(spr_mt_index_add)
3427 helixhorne 981
 
3916 helixhorne 982
-- Check a literal numeric action or move value.
2923 helixhorne 983
local function check_literal_am(am, typename)
2869 helixhorne 984
    if (type(am) ~= "number") then
2923 helixhorne 985
        error("bad argument: expected number or "..typename, 3)
2869 helixhorne 986
    end
987
 
3916 helixhorne 988
    -- Negative values are generated as con.action/con.move IDs.
2869 helixhorne 989
    if (not (am >= 0 and am <= 32767)) then
990
        error("bad argument: expected number in [0 .. 32767]", 3)
991
    end
992
end
993
 
3437 helixhorne 994
-- An unrestricted actor_t pointer, for internal use:
3458 helixhorne 995
local actor_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(ACTOR_STRUCT)))
996
local player_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(DUKEPLAYER_STRUCT)))
3469 helixhorne 997
local projectile_ptr_ct = ffi.typeof("$ *", ffi.typeof(strip_const(PROJECTILE_STRUCT)))
3954 helixhorne 998
-- An unrestricted weapondata_t pointer, but with the member names stripped of
999
-- the leading underscore, too:
3590 helixhorne 1000
local weapondata_ptr_ct = ffi.typeof("$ *", ffi.typeof((strip_const(WEAPONDATA_STRUCT):gsub(" _"," "))))
2872 helixhorne 1001
 
3916 helixhorne 1002
local con_action_ct = ffi.typeof("const con_action_t")
1003
local con_move_ct = ffi.typeof("const con_move_t")
1004
local con_ai_ct = ffi.typeof("const con_ai_t")
1005
 
1006
-- All-zero bare action and move.
1007
local nullac, nullmv = ffi.new("const struct action"), ffi.new("const struct move")
1008
-- All-zero action and move with IDs. Mostly for CON support.
1009
local literal_act = { [0]=con_action_ct(0), [1]=con_action_ct(1) }
1010
local literal_mov = { [0]=con_move_ct(0), [1]=con_move_ct(1) }
1011
 
3466 helixhorne 1012
local function get_actor_idx(a)
1013
    local i = ffi.cast(actor_ptr_ct, a)-ffi.cast(actor_ptr_ct, ffiC.actor)
3964 helixhorne 1014
--    assert(not (i >= ffiC.MAXSPRITES+0ULL))
3466 helixhorne 1015
    return i
1016
end
1017
 
2864 helixhorne 1018
local actor_mt = {
1019
    __index = {
2869 helixhorne 1020
        -- action
2864 helixhorne 1021
        set_action = function(a, act)
2872 helixhorne 1022
            a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1023
 
2872 helixhorne 1024
            if (ffi.istype(con_action_ct, act)) then
2864 helixhorne 1025
                a.t_data[4] = act.id
1026
                a.ac = act.ac
1027
            else
2923 helixhorne 1028
                check_literal_am(act, "action")
2864 helixhorne 1029
                a.t_data[4] = act
1030
                a.ac = nullac
1031
            end
2869 helixhorne 1032
 
1033
            a.t_data[2] = 0
1034
            a.t_data[3] = 0
2864 helixhorne 1035
        end,
1036
 
2869 helixhorne 1037
        has_action = function(a, act)
2872 helixhorne 1038
            a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1039
 
2872 helixhorne 1040
            if (ffi.istype(con_action_ct, act)) then
2869 helixhorne 1041
                return (a.t_data[4]==act.id)
1042
            else
2923 helixhorne 1043
                check_literal_am(act, "action")
2869 helixhorne 1044
                return (a.t_data[4]==act)
1045
            end
1046
        end,
1047
 
1048
        -- count
3843 helixhorne 1049
        set_count = function(a, count)
1050
            ffi.cast(actor_ptr_ct, a).t_data[0] = count
2869 helixhorne 1051
        end,
1052
 
1053
        get_count = function(a)
2872 helixhorne 1054
            return ffi.cast(actor_ptr_ct, a).t_data[0]
2869 helixhorne 1055
        end,
1056
 
1057
        -- action count
1058
        reset_acount = function(a)
2872 helixhorne 1059
            ffi.cast(actor_ptr_ct, a).t_data[2] = 0
2869 helixhorne 1060
        end,
1061
 
1062
        get_acount = function(a)
2872 helixhorne 1063
            return ffi.cast(actor_ptr_ct, a).t_data[2]
2869 helixhorne 1064
        end,
1065
 
3918 helixhorne 1066
        -- Override action delay. The action ID is kept.
1067
        set_action_delay = function(a, delay)
1068
            ffi.cast(actor_ptr_ct, a).ac.delay = delay
1069
        end,
1070
 
2869 helixhorne 1071
        -- move
1072
        set_move = function(a, mov, movflags)
2872 helixhorne 1073
            a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1074
 
2872 helixhorne 1075
            if (ffi.istype(con_move_ct, mov)) then
2869 helixhorne 1076
                a.t_data[1] = mov.id
2864 helixhorne 1077
                a.mv = mov.mv
1078
            else
2923 helixhorne 1079
                check_literal_am(mov, "move")
2869 helixhorne 1080
                a.t_data[1] = mov
2864 helixhorne 1081
                a.mv = nullmv
1082
            end
2869 helixhorne 1083
 
1084
            a.t_data[0] = 0
3922 helixhorne 1085
            a.movflags = movflags or 0
3887 helixhorne 1086
            local spr = ffiC.sprite[get_actor_idx(a)]
2869 helixhorne 1087
 
3887 helixhorne 1088
            if (not spr:isenemy() or spr.extra > 0) then
3922 helixhorne 1089
                if (bit.band(a.movflags, 8) ~= 0) then  -- random_angle
3887 helixhorne 1090
                    spr.ang = bit.band(ffiC.krand(), 2047)
1091
                end
1092
            end
2864 helixhorne 1093
        end,
2869 helixhorne 1094
 
1095
        has_move = function(a, mov)
2872 helixhorne 1096
            a = ffi.cast(actor_ptr_ct, a)
3916 helixhorne 1097
 
2872 helixhorne 1098
            if (ffi.istype(con_move_ct, mov)) then
2869 helixhorne 1099
                return (a.t_data[1]==mov.id)
1100
            else
2923 helixhorne 1101
                check_literal_am(mov, "move")
2869 helixhorne 1102
                return (a.t_data[1]==mov)
1103
            end
1104
        end,
1105
 
3918 helixhorne 1106
        -- Override velocity, keeping move ID.
1107
        set_hvel = function(a, hvel)
1108
            ffi.cast(actor_ptr_ct, a).mv.hvel = hvel
1109
        end,
1110
 
1111
        set_vvel = function(a, vvel)
1112
            ffi.cast(actor_ptr_ct, a).mv.vvel = vvel
1113
        end,
1114
 
2869 helixhorne 1115
        -- ai
1116
        set_ai = function(a, ai)
1117
            local oa = a
2872 helixhorne 1118
            a = ffi.cast(actor_ptr_ct, a)
2869 helixhorne 1119
 
1120
            -- TODO: literal number AIs?
2923 helixhorne 1121
            if (not ffi.istype(con_ai_ct, ai)) then
1122
                error("bad argument: expected ai", 2)
1123
            end
2869 helixhorne 1124
 
3916 helixhorne 1125
            -- NOTE: compare with gameexec.c, "CON_AI:"
2869 helixhorne 1126
            a.t_data[5] = ai.id
1127
 
1128
            oa:set_action(ai.act)
1129
            oa:set_move(ai.mov, ai.movflags)
1130
 
3924 helixhorne 1131
            -- Already reset with set_move():
1132
--            a.t_data[0] = 0
2869 helixhorne 1133
        end,
1134
 
1135
        has_ai = function(a, ai)
2872 helixhorne 1136
            a = ffi.cast(actor_ptr_ct, a)
2869 helixhorne 1137
 
2872 helixhorne 1138
            if (ffi.istype(con_ai_ct, ai)) then
2869 helixhorne 1139
                return (a.t_data[5]==ai.id)
1140
            else
2923 helixhorne 1141
                check_literal_am(ai, "ai")
2869 helixhorne 1142
                return (a.t_data[5]==ai)
1143
            end
1144
        end,
3259 helixhorne 1145
 
1146
        -- Getters/setters.
3920 helixhorne 1147
        _get_t_data = function(a, idx)
3964 helixhorne 1148
            if (not (idx >= 0 and idx < 10)) then
3916 helixhorne 1149
                error("invalid t_data index "..idx, 2)
3259 helixhorne 1150
            end
1151
            return ffi.cast(actor_ptr_ct, a).t_data[idx]
1152
        end,
3446 helixhorne 1153
 
1154
        _set_t_data = function(a, idx, val)
3964 helixhorne 1155
            if (not (idx >= 0 and idx < 10)) then
3916 helixhorne 1156
                error("invalid t_data index "..idx, 2)
3446 helixhorne 1157
            end
1158
            ffi.cast(actor_ptr_ct, a).t_data[idx] = val
1159
        end,
3454 helixhorne 1160
 
1161
        set_picnum = function(a, picnum)
3650 helixhorne 1162
            if (not (picnum < 0)) then
3626 helixhorne 1163
                check_tile_idx(picnum)
1164
            end
3454 helixhorne 1165
            ffi.cast(actor_ptr_ct, a).picnum = picnum
1166
        end,
1167
 
1168
        set_owner = function(a, owner)
1169
            -- XXX: is it permissible to set to -1?
1170
            check_sprite_idx(owner)
1171
            ffi.cast(actor_ptr_ct, a).owner = owner
1172
        end,
3928 helixhorne 1173
 
1174
        --- Custom methods ---
1175
 
1176
        -- Checkers for whether the movement update made the actor hit
1177
        -- something.
1178
 
1179
        checkhit = function(a)
1180
            -- Check whether we hit *anything*, including ceiling/floor.
1181
            return a._movflagbits:test(49152)
1182
        end,
1183
 
1184
        checkbump = function(a)
1185
            -- Check whether we bumped into a wall or sprite.
1186
            return (a._movflagbits:mask(49152) >= 32768)
1187
        end,
1188
 
1189
        hitwall = function(a)
1190
            if (a._movflagbits:mask(49152) == 32768) then
1191
                return a._movflagbits:mask(32767)
1192
            end
1193
        end,
1194
 
1195
        hitsprite = function(a)
1196
            if (a._movflagbits:mask(49152) == 49152) then
1197
                return a._movflagbits:mask(32767)
1198
            end
1199
        end,
1200
 
1201
        -- NOTE: no 'hitsector' or 'hitceiling' / 'hitfloor' for now because
1202
        -- more research is needed as to what the best way of checking c/f is.
2864 helixhorne 1203
    },
1204
}
3466 helixhorne 1205
 
1206
local function actor_index_index(a, key)
1207
    -- actor[].proj gets an actor's projectile ([gs]etthisprojectile in CON)
1208
    if (key=="proj") then
1209
        return ffiC.SpriteProjectile[get_actor_idx(a)]
1210
    end
1211
end
1212
 
1213
setmtonce(actor_mt.__index, { __index = actor_index_index })
2864 helixhorne 1214
ffi.metatype("actor_t", actor_mt)
1215
 
1216
 
3407 helixhorne 1217
--- PER-PLAYER WEAPON SETTINGS
3954 helixhorne 1218
local wd_sound_member = {}
1219
for _, declstr in pairs(con_lang.wdata_members) do
1220
    local member = declstr:match("const int32_t _(.*sound)$")
1221
    if (member) then
1222
        wd_sound_member[member] = true
1223
        if (ffiC._DEBUG_LUNATIC ~= 0) then
1224
            printf("weapondata_t member %s denotes a sound", member)
1225
        end
1226
    end
1227
end
1228
 
3407 helixhorne 1229
local weapondata_mt = {
3595 helixhorne 1230
    __index = function(wd, member)
1231
        -- Handle protected members that are renamed (e.g. shoots/_shoots).
3653 helixhorne 1232
        return ffi.cast(weapondata_ptr_ct, wd)[0][member]
3595 helixhorne 1233
    end,
1234
 
3407 helixhorne 1235
    __newindex = function(wd, member, val)
3848 helixhorne 1236
        -- Set to 'true' if we set a tile or sound member.
1237
        local didit = false
1238
 
3954 helixhorne 1239
        check_type(member, "string")  -- MEMBER_IS_STRING
3883 helixhorne 1240
        check_number(val)
1241
 
3954 helixhorne 1242
        if (wd_sound_member[member]) then  -- XXX: sound2time is a time, not a sound
3574 helixhorne 1243
            if (val < 0) then
3954 helixhorne 1244
                val = 0  -- Set to 0 if negative (e.g. CrackDown).
3574 helixhorne 1245
            else
1246
                check_sound_idx(val)
1247
            end
3848 helixhorne 1248
            didit = true
3463 helixhorne 1249
        elseif (member=="workslike") then
1250
            check_weapon_idx(val)
3574 helixhorne 1251
        elseif (member=="spawn" or member=="shoots") then
1252
            if (val < 0) then
1253
                -- Set to 0 if oob (e.g. CrackDown). This is a bit problematic
1254
                -- for .shoots because it's used unconditionally except in one
1255
                -- case (see player.c).
1256
                val = 0
1257
            else
1258
                check_tile_idx(val)
1259
            end
3848 helixhorne 1260
            didit = true
3463 helixhorne 1261
        end
3392 helixhorne 1262
 
3954 helixhorne 1263
        -- DEBUG:
1264
--        printf("assigning %s to weapon's %s", tostring(val), member)
3848 helixhorne 1265
 
3954 helixhorne 1266
        -- NOTE: we're indexing a *pointer* with the user-supplied 'member',
1267
        -- which could be dangerouns if it could be a number. However, we have
1268
        -- assured that is is not in MEMBER_IS_STRING above.
1269
        ffi.cast(weapondata_ptr_ct, wd)[member] = val
1270
 
3848 helixhorne 1271
        if (didit and ffiC.g_elCallDepth==0) then
1272
            -- Signal that we overrode this member at CON translation time.
1273
 
1274
            -- Get weapon index as pointer difference first. PLAYER_0.
3931 helixhorne 1275
            local wi = ffi.cast(weapondata_ptr_ct, wd)
1276
                     - ffi.cast(weapondata_ptr_ct, ffiC.g_playerWeapon)
3964 helixhorne 1277
            assert(wi >= 0 and wi < ffiC.MAX_WEAPONS)
3848 helixhorne 1278
 
1279
            -- Set g_weaponOverridden[wi][member], but without invoking
1280
            -- weapondata_t's __newindex metamethod (i.e. us)!
1281
            ffi.cast(weapondata_ptr_ct, ffiC.g_weaponOverridden[wi])[member] = 1
1282
        end
3407 helixhorne 1283
    end,
1284
}
1285
ffi.metatype("weapondata_t", weapondata_mt)
3392 helixhorne 1286
 
3407 helixhorne 1287
local weaponaccess_mt = {
3931 helixhorne 1288
    -- Syntax like "player[0].weapon.KNEE.shoots" possible because
1289
    -- g_playerWeapon[] is declared as an array of corresponding bcarray types
1290
    -- for us.
3407 helixhorne 1291
    __index = function(wa, key)
3931 helixhorne 1292
        if (type(key)~="number" and type(key)~="string") then
1293
            error("must access weapon either by number or by name")
3407 helixhorne 1294
        end
3392 helixhorne 1295
 
3931 helixhorne 1296
        return ffiC.g_playerWeapon[wa._p][key]
3407 helixhorne 1297
    end,
1298
}
1299
ffi.metatype("weaponaccess_t", weaponaccess_mt)
3392 helixhorne 1300
 
3893 helixhorne 1301
 
1302
local function clamp(num, min, max)
1303
    return num < min and min
1304
        or num > max and max
1305
        or num
1306
end
1307
 
1308
local function clamp0to1(num)
1309
    check_number(num, 4)
1310
    return clamp(num, 0, 1)
1311
end
1312
 
3247 helixhorne 1313
local player_mt = {
1314
    __index = {
3249 helixhorne 1315
        -- CON-like addammo/addweapon, but without the non-local control flow
1316
        -- (returns true if weapon's ammo was at the max. instead).
3253 helixhorne 1317
        addammo = con._addammo,
1318
        addweapon = con._addweapon,
3254 helixhorne 1319
 
3390 helixhorne 1320
        stomp = con._pstomp,
3253 helixhorne 1321
 
3928 helixhorne 1322
        holdskey = function(p, keyname)
1323
            -- XXX: on invalid <keyname>, error will point to this next line:
1324
            return player_holdskey(p.weapon._p, keyname)
3433 helixhorne 1325
        end,
1326
 
3928 helixhorne 1327
        has_weapon = function(p, weap)
4217 helixhorne 1328
            return p.gotweaponbits:test(lsh(1,weap))
3928 helixhorne 1329
        end,
1330
 
3444 helixhorne 1331
        give_weapon = function(p, weap)
4217 helixhorne 1332
            p.gotweaponbits:set(lsh(1,weap))
3444 helixhorne 1333
        end,
1334
 
1335
        take_weapon = function(p, weap)
4217 helixhorne 1336
            p.gotweaponbits:clear(lsh(1,weap))
3444 helixhorne 1337
        end,
1338
 
1339
        -- Give or take weapon, for implementation of CON's .gotweapon access.
1340
        _gt_weapon = function(p, weap, give_p)
1341
            if (give_p ~= 0) then
1342
                p:give_weapon(weap)
1343
            else
1344
                p:take_weapon(weap)
1345
            end
1346
        end,
1347
 
3924 helixhorne 1348
        whack = function(p, no_return_to_center)
3254 helixhorne 1349
            p.horiz = p.horiz + 64
3390 helixhorne 1350
            if (not no_return_to_center) then
1351
                p.return_to_center = 9
1352
            end
3928 helixhorne 1353
            local n = bit.arshift(128-band(ffiC.krand(),255), 1)
3254 helixhorne 1354
            p.rotscrnang = n
1355
            p.look_ang = n
1356
        end,
1357
 
3893 helixhorne 1358
        -- External, improved 'palfrom'.
1359
        -- <speed>: possibly fractional speed of tint fading, in pals.f decrements per gametic.
1360
        --          XXX: exposes internals.
1361
        -- <prio>: a value from -128 to 127, higher ones trump lower or equal ones
1362
        fadecol = function(p, fadefrac, r, g, b, speed, prio)
1363
            -- Validate inargs: clamp f,r,g,b to [0 .. 1] first and multiply by
1364
            -- 63 for the internal handling.
1365
            fadefrac = clamp0to1(fadefrac)*63
1366
            -- NOTE: a fadefrac of now <1 is allowed, e.g. for clearing the tint.
1367
            r = clamp0to1(r)*63
1368
            g = clamp0to1(g)*63
1369
            b = clamp0to1(b)*63
1370
 
1371
            if (speed ~= nil) then
1372
                check_number(speed)
1373
                -- Clamp to sensible values; the speed is stored in an int8_t
1374
                -- (see below).
1375
                speed = clamp(speed, 1/128, 127)
1376
            else
1377
                speed = 1
1378
            end
1379
 
1380
            if (prio ~= nil) then
1381
                check_number(prio)
1382
 
1383
                if (not (prio >= -128 and prio < 127)) then
1384
                    error("invalid argument #6 (priority): must be in [-128 .. 127]", 2)
1385
                end
1386
            else
1387
                prio = 0
1388
            end
1389
 
1390
            -- Check if a currently active tint has higher priority.
1391
            if (p._pals.f > 0 and p._palsfadeprio > prio) then
1392
                return
1393
            end
1394
 
1395
            -- The passed tint can be applied now.
1396
            p:_palfrom(fadefrac, r, g, b)
1397
            p._palsfadeprio = prio
1398
 
1399
            -- Calculate .palsfade{speed,next}
1400
            if (speed >= 1) then
1401
                -- Will round to the nearest integer ("banker's
1402
                -- rounding"). NOTE: This is not correct for all numbers, see
1403
                -- http://blog.frama-c.com/index.php?post/2013/05/02/nearbyintf1
1404
                p._palsfadespeed = speed + 0.5
1405
                p._palsfadenext = 0
1406
            else
1407
                -- NOTE: Values that round to 0 have are equivalent behavior to
1408
                -- passing a <speed> of 1.
1409
                local negspeedrecip = -((1/speed) + 0.5)  -- [-128.5 .. 1/127+0.5]
1410
                p._palsfadespeed = negspeedrecip
1411
                p._palsfadenext = negspeedrecip
1412
            end
1413
        end,
1414
 
1415
        -- INTERNAL and CON-only.
3253 helixhorne 1416
        _palfrom = function(p, f, r,g,b)
3444 helixhorne 1417
            local pals = p._pals
3927 helixhorne 1418
            -- Assume that CON's palfrom starts with prio 0 and speed 0.
1419
            if (pals.f == 0 or p._palsfadeprio <= 0) then
1420
                pals.f = f
1421
                pals.r, pals.g, pals.b = r, g, b
1422
                p._palsfadespeed, p._palsfadenext = 0, 0
1423
            end
3253 helixhorne 1424
        end,
3247 helixhorne 1425
    },
3653 helixhorne 1426
 
1427
    __newindex = function(p, key, val)
1428
        -- Write access to protected player members.
1429
 
1430
        local allowneg = DukePlayer_prot_allowneg[key]
1431
        assert(type(allowneg)=="boolean")
1432
 
1433
        if (allowneg==false or not (val < 0)) then
1434
            DukePlayer_prot_chkfunc[key](val)
1435
        end
1436
        ffi.cast(player_ptr_ct, p)[key] = val
1437
    end,
3247 helixhorne 1438
}
3477 helixhorne 1439
 
1440
local function player_index_index(p, key)
1441
    if (key=="_input") then
1442
        return ffiC.g_player[p.weapon._p].sync[0]
1443
    end
3653 helixhorne 1444
 
1445
    -- Read access to protected player members.
1446
    return ffi.cast(player_ptr_ct, p)[0][key]
3477 helixhorne 1447
end
1448
 
1449
setmtonce(player_mt.__index, { __index = player_index_index })
3247 helixhorne 1450
ffi.metatype("DukePlayer_t", player_mt)
1451
 
3865 helixhorne 1452
local function GenProjectileSetFunc(Member, checkfunc)
1453
    return function(self, idx)
1454
        if (not (idx == -1)) then
1455
            checkfunc(idx)
3469 helixhorne 1456
        end
3865 helixhorne 1457
        ffi.cast(projectile_ptr_ct, self)[Member] = idx
3469 helixhorne 1458
    end
1459
end
1460
 
1461
local projectile_mt = {
1462
    __index = {
3865 helixhorne 1463
        set_spawns = GenProjectileSetFunc("spawns", check_tile_idx),
1464
        set_decal = GenProjectileSetFunc("decal", check_tile_idx),
1465
        set_trail = GenProjectileSetFunc("trail", check_tile_idx),
1466
 
1467
        set_sound = GenProjectileSetFunc("sound", check_sound_idx),
1468
        set_isound = GenProjectileSetFunc("isound", check_sound_idx),
1469
        set_bsound = GenProjectileSetFunc("bsound", check_sound_idx),
3469 helixhorne 1470
    },
1471
}
1472
ffi.metatype("projectile_t", projectile_mt)
1473
 
3473 helixhorne 1474
local user_defs_mt = {
1475
    __index = {
1476
        set_screen_size = function(ud, screen_size)
1477
            -- TODO: modify .statusbarmode accordingly
1478
            ud.screen_size = screen_size
1479
        end,
1480
 
1481
        set_volume_number = function(ud, volume_number)
3843 helixhorne 1482
            -- NOTE: allow volume_number==MAXVOLUMES.
1483
            if (not (volume_number==con_lang.MAXVOLUMES)) then
1484
                bcheck.volume_idx(volume_number)
1485
            end
3473 helixhorne 1486
            ud.volume_number = volume_number
1487
        end,
3826 helixhorne 1488
 
4567 helixhorne 1489
        set_m_volume_number = function(ud, volume_number)
1490
            -- NOTE: allow volume_number==MAXVOLUMES.
1491
            if (not (volume_number==con_lang.MAXVOLUMES)) then
1492
                bcheck.volume_idx(volume_number)
1493
            end
1494
            ud.m_volume_number = volume_number
1495
        end,
1496
 
3826 helixhorne 1497
        set_level_number = function(ud, level_number)
1498
            bcheck.level_idx(level_number)
1499
            ud.level_number = level_number
1500
        end,
3473 helixhorne 1501
    },
1502
}
1503
ffi.metatype("user_defs", user_defs_mt)
1504
 
3409 helixhorne 1505
--- CUSTOM "gv" VARIABLES
3406 helixhorne 1506
local camera_mt = {
1507
    -- TODO: "set position" method, which also updates the sectnum
1508
    __index = ffiC.g_camera,
1509
    __newindex = function(_, key, val)
1510
        if (key=="sect") then
3445 helixhorne 1511
            check_sector_idx(val)
3406 helixhorne 1512
        end
1513
        ffiC.g_camera[key] = val
1514
    end,
1515
}
1516
 
3435 helixhorne 1517
gv_access.cam = setmtonce({}, camera_mt)
3473 helixhorne 1518
gv_access._ud = ffiC.ud
3406 helixhorne 1519
 
3601 helixhorne 1520
-- Support for some CON global system gamevars. RETURN handled separately.
1521
gv_access._csv = ffi.new "struct { int32_t LOTAG, HITAG, TEXTURE; }"
3466 helixhorne 1522
 
3928 helixhorne 1523
gv_access.REND = defs_c.conststruct
1524
{
1525
    CLASSIC = 0,
1526
    POLYMOST = 3,
1527
    POLYMER = 4,
1528
}
1529
 
4030 helixhorne 1530
gv_access.WEAPON = lprivate.WEAPON
1531
gv_access.GET = lprivate.GET
1532
 
3475 helixhorne 1533
function gv_access._get_yxaspect()
1534
    return ffiC.yxaspect
1535
end
1536
 
3480 helixhorne 1537
function gv_access._get_viewingrange()
1538
    return ffiC.viewingrange
1539
end
1540
 
3431 helixhorne 1541
function gv_access._currentFramerate()
3409 helixhorne 1542
    return ffiC.g_currentFrameRate
1543
end
1544
 
3431 helixhorne 1545
function gv_access._currentMenu()
1546
    return ffiC.g_currentMenu
1547
end
1548
 
3656 helixhorne 1549
function gv_access._changeMenu(cm)
1550
    ffiC.M_ChangeMenu(cm)
1551
end
1552
 
3498 helixhorne 1553
function gv_access._set_guniqhudid(id)
1554
    local MAXUNIQHUDID = 256  -- KEEPINSYNC build.h
3964 helixhorne 1555
    if (not (id >= 0 and id < MAXUNIQHUDID)) then
3498 helixhorne 1556
        error("invalid unique HUD ID "..id)
1557
    end
1558
    ffiC.guniqhudid = id
1559
end
1560
 
3409 helixhorne 1561
function gv_access.currentEpisode()
4260 helixhorne 1562
    return ffiC.ud.volume_number + 1
3409 helixhorne 1563
end
1564
 
1565
function gv_access.currentLevel()
4260 helixhorne 1566
    return ffiC.ud.level_number + 1
3409 helixhorne 1567
end
1568
 
3480 helixhorne 1569
function gv_access.doQuake(gametics, snd)
1570
    ffiC.g_earthquakeTime = gametics
1571
    if (snd ~= nil) then
1572
        con._globalsound(ffiC.screenpeek, snd)
1573
    end
1574
end
1575
 
3366 helixhorne 1576
-- Declare all con_lang.labels constants in the global FFI namespace.
2863 helixhorne 1577
for i=1,#con_lang.labels do
3597 helixhorne 1578
    if (getmetatable(con_lang.labels[i]) ~= "noffiC") then
1579
        local strbuf = {"enum {"}
1580
        for label, val in pairs(con_lang.labels[i]) do
1581
            strbuf[#strbuf+1] = string.format("%s = %d,", label, val)
1582
        end
1583
        strbuf[#strbuf+1] = "};"
2762 helixhorne 1584
 
3597 helixhorne 1585
        ffi.cdef(table.concat(strbuf))
2762 helixhorne 1586
    end
1587
end
1588
 
1589
 
2648 helixhorne 1590
---=== Set up restricted global environment ===---
1591
 
2828 helixhorne 1592
local allowed_modules = {
1593
    coroutine=coroutine, bit=bit, table=table, math=math, string=string,
2855 helixhorne 1594
 
1595
    os = {
3935 helixhorne 1596
        clock = function() return gv_.gethiticks()*0.001 end,
2855 helixhorne 1597
    },
1598
 
3227 helixhorne 1599
    randgen = randgen,
4236 helixhorne 1600
    engine = require("engine"),
2858 helixhorne 1601
    stat = require("stat"),
2862 helixhorne 1602
    bitar = require("bitar"),
3489 helixhorne 1603
    xmath = require("xmath"),
4147 helixhorne 1604
    fs = require("fs"),
2864 helixhorne 1605
 
1606
    con = con,
2828 helixhorne 1607
}
1608
 
3914 helixhorne 1609
do
1610
    local ctype_cansave = {}
1611
 
1612
    -- Register as "serializeable" the type of cdata object <v>.
1613
    local function reg_serializable_cv(v)
1614
        assert(type(v)=="cdata")
1615
        assert(type(v._serialize)=="function")
1616
        -- NOTE: tonumber() on a ctype cdata object gets its LuaJIT-internal
1617
        -- ID, the one that would be shown with tostring(), e.g.
1618
        -- ctype<struct 95>
1619
        ctype_cansave[tonumber(ffi.typeof(v))] = true
1620
    end
1621
 
1622
    function lprivate.cansave_cdata(v)
1623
        return type(v)=="cdata" and ctype_cansave[tonumber(ffi.typeof(v))]
1624
    end
1625
 
1626
    reg_serializable_cv(allowed_modules.xmath.vec3())
1627
    reg_serializable_cv(allowed_modules.xmath.ivec3())
1628
end
1629
 
3597 helixhorne 1630
-- Protect base modules.
3917 helixhorne 1631
local function basemod_newidx()
3870 helixhorne 1632
    error("modifying base module table forbidden", 2)
1633
end
2828 helixhorne 1634
 
3870 helixhorne 1635
for modname, themodule in pairs(allowed_modules) do
1636
    local mt = {
1637
        __index = themodule,
3917 helixhorne 1638
        __newindex = basemod_newidx,
3870 helixhorne 1639
    }
3597 helixhorne 1640
 
3870 helixhorne 1641
    allowed_modules[modname] = setmtonce({}, mt)
2828 helixhorne 1642
end
1643
 
3642 helixhorne 1644
 
3796 helixhorne 1645
---=== Module stuff ===---
1646
 
1647
local package_loaded = {}  -- [<modname>] = false/true/table
3642 helixhorne 1648
local modname_stack = {}  -- [<depth>]=string
1649
local module_gamevars = {}  -- [<modname>] = { <gvname1>, <gvname2>, ... }
3858 helixhorne 1650
local module_gvlocali = {}  -- [<modname>] = { <localidx_beg>, <localidx_end> }
3891 helixhorne 1651
local module_thread = {}  -- [<modname>] = <module_thread>
3642 helixhorne 1652
 
1653
local function getcurmodname(thisfuncname)
1654
    if (#modname_stack == 0) then
1655
        error("'"..thisfuncname.."' must be called at the top level of a require'd file", 3)
1656
        -- ... as opposed to "at runtime".
2837 helixhorne 1657
    end
1658
 
3642 helixhorne 1659
    return modname_stack[#modname_stack]
2837 helixhorne 1660
end
1661
 
3642 helixhorne 1662
 
2837 helixhorne 1663
local function errorf(level, fmt, ...)
1664
    local errmsg = string.format(fmt, ...)
1665
    error(errmsg, level+1)
1666
end
1667
 
3734 helixhorne 1668
local function readintostr_mod(fn)
3736 helixhorne 1669
    -- TODO: g_loadFromGroupOnly?
1670
    local fd = ffiC.kopen4loadfrommod(fn, 0)
1671
    if (fd < 0) then
1672
        return nil
1673
    end
1674
 
1675
    return defs_c.readintostr(fd)
2854 helixhorne 1676
end
1677
 
3642 helixhorne 1678
 
3858 helixhorne 1679
local debug = require("debug")
1680
 
1681
-- Get the number of active locals in the function that calls the function
1682
-- calling this one.
1683
local function getnumlocals(l)
1684
    -- 200 is the max. number of locals at one level
1685
    for i=1,200 do
1686
        -- level:
1687
        -- 0 is getlocal() itself.
3891 helixhorne 1688
        -- 1 is this function (getnumlocals).
3858 helixhorne 1689
        -- 2 is the function calling getnumlocals()
1690
        -- 3 is the function calling that one.
1691
        if (debug.getlocal(3, i) == nil) then
1692
            return i-1
1693
        end
1694
    end
1695
end
1696
 
3928 helixhorne 1697
local function error_on_nil_read(_, varname)
1698
    error("attempt to read nil variable '"..varname.."'", 2)
1699
end
1700
 
3642 helixhorne 1701
local required_module_mt = {
3928 helixhorne 1702
    __index = error_on_nil_read,
1703
 
3642 helixhorne 1704
    __newindex = function()
1705
        error("modifying module table forbidden", 2)
1706
    end,
3928 helixhorne 1707
 
3642 helixhorne 1708
    __metatable = true,
1709
}
1710
 
3891 helixhorne 1711
-- Will contain a function to restore gamevars when running from savegame
1712
-- restoration. See SAVEFUNC_ARGS for its arguments.
1713
local g_restorefunc = nil
1714
 
1715
-- Local gamevar restoration function run from
1716
-- our_require('end_gamevars') <- [user module].
1717
local function restore_local(li, lval)
1718
    -- level:
1719
    -- 0 is getlocal() itself.
1720
    -- 1 is this function (restore_local).
1721
    -- 2 is the function calling restore_local(), the savecode.
1722
    -- 3 is the function calling the savecode, our_require.
1723
    -- 4 is the function calling our_require, the module function.
1724
    if (ffiC._DEBUG_LUNATIC ~= 0) then
1725
        printf("Restoring index #%d (%s) with value %s",
1726
               li, debug.getlocal(4, li), tostring(lval))
1727
    end
1728
 
1729
    assert(debug.setlocal(4, li, lval))
1730
end
1731
 
2828 helixhorne 1732
-- The "require" function accessible to Lunatic code.
1733
-- Base modules in allowed_modules are wrapped so that they cannot be
2837 helixhorne 1734
-- modified, user modules are searched in the EDuke32 search
3390 helixhorne 1735
-- path.  Also, our require
1736
--  * never messes with the global environment, it only returns the module.
1737
--  * allows passing varargs beyond the name to the module.
1738
local function our_require(modname, ...)
3734 helixhorne 1739
    local ERRLEV = 5
1740
 
3642 helixhorne 1741
    -- Check module name is valid first.
1742
    -- TODO: restrict valid names?
3788 helixhorne 1743
    if (type(modname) ~= "string" or #modname==0) then
1744
        error("module name must be a nonempty string", 2)
3642 helixhorne 1745
    end
2828 helixhorne 1746
 
3966 helixhorne 1747
    -- For _LUNATIC_DBG
1748
    if (modname:match("^_LUNATIC") and ffiC._DEBUG_LUNATIC == 0) then
1749
        return nil
1750
    end
1751
 
3642 helixhorne 1752
    -- Handle the section between module() and require("end_gamevars").
1753
    if (modname == "end_gamevars") then
1754
        local thismodname = getcurmodname("require")
1755
 
1756
        if (module_gamevars[thismodname] ~= nil) then
1757
            error("\"require 'end_gamevars'\" must be called at most once per require'd file", 2)
1758
        end
1759
 
1760
        local gvnames = {}
1761
 
1762
        for name in pairs(getfenv(2)) do
3857 helixhorne 1763
            gvnames[#gvnames+1] = name
3642 helixhorne 1764
            if (ffiC._DEBUG_LUNATIC ~= 0) then
1765
                printf("MODULE %s GAMEVAR %s", thismodname, name)
1766
            end
1767
        end
1768
 
1769
        module_gamevars[thismodname] = gvnames
3858 helixhorne 1770
        local gvmodi = module_gvlocali[thismodname]
1771
        gvmodi[2] = getnumlocals()
3642 helixhorne 1772
 
3858 helixhorne 1773
        if (ffiC._DEBUG_LUNATIC ~= 0) then
3891 helixhorne 1774
            local numlocals = gvmodi[2]-gvmodi[1]+1
1775
            if (numlocals > 0) then
1776
                printf("Module '%s' has %d locals, index %d to %d",
1777
                       thismodname, numlocals, gvmodi[1], gvmodi[2])
1778
            end
3858 helixhorne 1779
        end
1780
 
3891 helixhorne 1781
        -- Potentially restore gamevars.
1782
        if (g_restorefunc) then
1783
            local modtab = package_loaded[thismodname]
1784
            assert(type(modtab)=="table")
1785
            -- SAVEFUNC_ARGS.
1786
            g_restorefunc(thismodname, modtab, restore_local)
1787
        end
1788
 
1789
        -- Return whether we're NOT running from a savegame restore in the
1790
        -- second outarg. (Lunatic-private!)
1791
        return nil, (g_restorefunc==nil)
3642 helixhorne 1792
    end
1793
 
1794
    -- See whether it's a base module name.
2837 helixhorne 1795
    if (allowed_modules[modname] ~= nil) then
1796
        return allowed_modules[modname]
2828 helixhorne 1797
    end
1798
 
3642 helixhorne 1799
    --- Search user modules...
2837 helixhorne 1800
 
3867 helixhorne 1801
    if (modname:find("[/\\]")) then
1802
        error("Module name must not contain directory separators", ERRLEV-1)
1803
    end
1804
    -- Instead, dots are translated to directory separators. For EDuke32's
3894 helixhorne 1805
    -- virtual file system, this is always a forward slash. Keep the original
1806
    -- module name for passing to the module function.
1807
    local omodname = modname
3867 helixhorne 1808
    modname = modname:gsub("%.", "/")
1809
 
3530 helixhorne 1810
    local omod = package_loaded[modname]
1811
    if (omod ~= nil) then
3642 helixhorne 1812
        if (omod==false) then
3530 helixhorne 1813
            error("Loop while loading modules", ERRLEV-1)
1814
        end
1815
 
2837 helixhorne 1816
        -- already loaded
3642 helixhorne 1817
        assert(omod==true or type(omod)=="table")
3530 helixhorne 1818
        return omod
2837 helixhorne 1819
    end
1820
 
3343 helixhorne 1821
    local modfn = modname .. ".lua"
3734 helixhorne 1822
    local str = readintostr_mod(modfn)
3343 helixhorne 1823
    if (str == nil) then
1824
        errorf(ERRLEV-1, "Couldn't open file \"%s\"", modfn)
1825
    end
2837 helixhorne 1826
 
3891 helixhorne 1827
    -- Implant code that yields the module thread just before it would return
1828
    -- otherwise.
1829
    str = str.."\nrequire('coroutine').yield()"
1830
 
3804 helixhorne 1831
    local modfunc, errmsg = loadstring(str, modfn)
2837 helixhorne 1832
    if (modfunc == nil) then
2857 helixhorne 1833
        errorf(ERRLEV-1, "Couldn't load \"%s\": %s", modname, errmsg)
2837 helixhorne 1834
    end
1835
 
3642 helixhorne 1836
    package_loaded[modname] = false  -- 'not yet loaded'
2863 helixhorne 1837
    table.insert(modname_stack, modname)
2837 helixhorne 1838
 
3891 helixhorne 1839
    -- Run the module code in a separate Lua thread!
1840
    local modthread = coroutine.create(modfunc)
3894 helixhorne 1841
    local ok, retval = coroutine.resume(modthread, omodname, ...)
2840 helixhorne 1842
 
3891 helixhorne 1843
    if (not ok) then
3916 helixhorne 1844
        errorf(ERRLEV-1, "Failed running \"%s\": %s\n%s", modname,
1845
               retval, debug.traceback(modthread))
3891 helixhorne 1846
    end
1847
 
2863 helixhorne 1848
    table.remove(modname_stack)
2840 helixhorne 1849
 
2863 helixhorne 1850
    local modtab = package_loaded[modname]
1851
 
3891 helixhorne 1852
    if (type(modtab) ~= "table") then
1853
        -- The module didn't call our 'module'. Check if it returned a table.
1854
        -- In that case, the coroutine has finished its main function and has
1855
        -- not reached our implanted 'yield'.
1856
        if (coroutine.status(modthread)=="dead" and type(retval)=="table") then
1857
            modtab = retval
1858
            package_loaded[modname] = modtab
1859
        else
1860
            package_loaded[modname] = true
1861
        end
1862
    end
1863
 
2863 helixhorne 1864
    if (type(modtab) == "table") then
3891 helixhorne 1865
        -- Protect module table in any case (i.e. either if the module used our
1866
        -- 'module' or if it returned a table).
3642 helixhorne 1867
        setmetatable(modtab, required_module_mt)
2837 helixhorne 1868
    end
1869
 
3891 helixhorne 1870
    local gvmodi = module_gvlocali[modname]
1871
 
3965 helixhorne 1872
    if (gvmodi and gvmodi[2] and gvmodi[2]>=gvmodi[1]) then
3891 helixhorne 1873
        if (coroutine.status(modthread)=="suspended") then
1874
            -- Save off the suspended thread so that we may get its locals later on.
1875
            -- It is never resumed, but only ever used for debug.getlocal().
1876
            module_thread[modname] = modthread
1877
 
1878
            if (ffiC._DEBUG_LUNATIC ~= 0) then
1879
                printf("Keeping coroutine for module \"%s\"", modname)
1880
            end
1881
        end
1882
    end
1883
 
2840 helixhorne 1884
    return modtab
2828 helixhorne 1885
end
1886
 
2837 helixhorne 1887
 
2839 helixhorne 1888
local module_mt = {
3928 helixhorne 1889
    __index = error_on_nil_read,
2839 helixhorne 1890
}
1891
 
2863 helixhorne 1892
-- Our 'module' replacement doesn't get the module name from the function args
1893
-- since a malicious user could remove other loaded modules this way.
3642 helixhorne 1894
-- Also, our 'module' takes no varargs ("option functions" in Lua).
2863 helixhorne 1895
-- TODO: make transactional?
1896
local function our_module()
3642 helixhorne 1897
    if (#modname_stack == 0) then
2863 helixhorne 1898
        error("'module' must be called at the top level of a require'd file", 2)
3642 helixhorne 1899
        -- ... as opposed to "at runtime".
2863 helixhorne 1900
    end
2837 helixhorne 1901
 
3642 helixhorne 1902
    local modname = getcurmodname("module")
1903
 
3891 helixhorne 1904
    if (package_loaded[modname]) then
3642 helixhorne 1905
        error("'module' must be called at most once per require'd file", 2)
1906
    end
1907
 
2863 helixhorne 1908
    local M = setmetatable({}, module_mt)
2837 helixhorne 1909
    package_loaded[modname] = M
1910
    -- change the environment of the function which called us:
2863 helixhorne 1911
    setfenv(2, M)
3858 helixhorne 1912
 
1913
    module_gvlocali[modname] = { getnumlocals()+1 }
2837 helixhorne 1914
end
1915
 
2838 helixhorne 1916
-- overridden 'error' that always passes a string to the base 'error'
1917
local function our_error(errmsg, level)
1918
    if (type(errmsg) ~= "string") then
2863 helixhorne 1919
        error("error using 'error': error message must be a string", 2)
2838 helixhorne 1920
    end
1921
 
1922
    if (level) then
1923
        if (type(level) ~= "number") then
2863 helixhorne 1924
            error("error using 'error': error level must be a number", 2)
2838 helixhorne 1925
        end
1926
 
2863 helixhorne 1927
        error(errmsg, level==0 and 0 or level+1)
2838 helixhorne 1928
    end
1929
 
2863 helixhorne 1930
    error(errmsg, 2)
2838 helixhorne 1931
end
1932
 
3390 helixhorne 1933
 
1934
-- _G tweaks -- pull in only 'safe' stuff
1935
local G_ = {}  -- our soon-to-be global environment
1936
 
2074 helixhorne 1937
G_.assert = assert
2863 helixhorne 1938
G_.error = our_error
2074 helixhorne 1939
G_.ipairs = ipairs
2863 helixhorne 1940
G_.pairs = pairs
1941
G_.pcall = pcall
3319 helixhorne 1942
G_.print = print
2863 helixhorne 1943
G_.module = our_module
2074 helixhorne 1944
G_.next = next
2863 helixhorne 1945
G_.require = our_require
2074 helixhorne 1946
G_.select = select
2863 helixhorne 1947
G_.tostring = tostring
1948
G_.tonumber = tonumber
2074 helixhorne 1949
G_.type = type
2863 helixhorne 1950
G_.unpack = unpack
1951
G_.xpcall = xpcall
1952
G_._VERSION = _VERSION
2074 helixhorne 1953
 
2863 helixhorne 1954
-- Available through our 'require':
1955
-- bit, coroutine, math, string, table
1956
 
1957
-- Not available:
1958
-- collectgarbage, debug, dofile, gcinfo (DEPRECATED), getfenv, getmetatable,
1959
-- jit, load, loadfile, loadstring, newproxy (NOT STD?), package, rawequal,
1960
-- rawget, rawset, setfenv, setmetatable
1961
 
2074 helixhorne 1962
G_._G = G_
1963
 
3629 helixhorne 1964
-- Chain together two functions taking 3 input args.
1965
local function chain_func3(func1, func2)
1966
    if (func1==nil or func2==nil) then
1967
        return assert(func1 or func2)
1968
    end
1969
 
1970
    -- Return a function that runs <func1> first and then tail-calls <func2>.
1971
    return function(aci, pli, dist)
1972
        func1(aci, pli, dist)
1973
        return func2(aci, pli, dist)
1974
    end
1975
end
1976
 
3916 helixhorne 1977
-- Determines the last numeric index of a table using *pairs*, so that in
1978
-- arg-lists with "holes" (e.g. {1, 2, nil, function() end}) are handled
1979
-- properly.
3873 helixhorne 1980
local function ourmaxn(tab)
1981
    local maxi = 0
3916 helixhorne 1982
    for i in pairs(tab) do
1983
        if (type(i)=="number") then
1984
            maxi = math.max(i, maxi)
1985
        end
3873 helixhorne 1986
    end
4375 helixhorne 1987
    assert(tab[maxi] ~= nil)
3873 helixhorne 1988
    return maxi
1989
end
1990
 
3829 helixhorne 1991
-- Running for the very first time?
1992
local g_firstRun = (ffiC.g_elCONSize == 0)
1993
 
3629 helixhorne 1994
-- Actor functions, saved for actor chaining
1995
local actor_funcs = {}
3937 helixhorne 1996
-- Event functions, saved for event chaining
1997
local event_funcs = {}
3629 helixhorne 1998
 
3937 helixhorne 1999
-- Per-actor sprite animation callbacks
2000
local animsprite_funcs = {}
2001
 
3315 helixhorne 2002
local gameactor_internal = gameactor_internal  -- included in lunatic.c
3937 helixhorne 2003
local gameevent_internal = gameevent_internal  -- included in lunatic.c
2004
 
2005
local function animate_all_sprites()
2006
    for i=0,ffiC.spritesortcnt-1 do
2007
        local tspr = ffiC.tsprite[i]
2008
 
2009
        if (tspr.owner < ffiC.MAXSPRITES+0ULL) then
2010
            local spr = tspr:getspr()
2011
            local animfunc = animsprite_funcs[spr.picnum]
2012
 
2013
            if (animfunc) then
2014
                animfunc(tspr)
2015
            end
2016
        end
2017
    end
2018
end
2019
 
2020
 
4375 helixhorne 2021
function check_arg_number(name, argpos, val)
2022
    if (type(val) ~= "number") then
2023
        errorf(3, "invalid '%s' argument (#%d) to gameactor: must be a number", name, argpos)
2024
    end
2025
end
2026
 
3873 helixhorne 2027
-- gameactor{tilenum [, flags [, strength [, action [, move [, movflags]]]]], func}
2028
-- Every arg may be positional OR key=val (with the name indicated above as key),
2029
-- but not both.
2030
local function our_gameactor(args)
3541 helixhorne 2031
    bcheck.top_level("gameactor")
3320 helixhorne 2032
 
3873 helixhorne 2033
    if (type(args)~="table") then
2034
        error("invalid gameactor call: must be passed a table")
2035
    end
2036
 
2037
    local tilenum = args[1]
3315 helixhorne 2038
    if (type(tilenum) ~= "number") then
2039
        error("invalid argument #1 to gameactor: must be a number", 2)
2040
    end
3964 helixhorne 2041
    if (not (tilenum >= 0 and tilenum < ffiC.MAXTILES)) then
3597 helixhorne 2042
        error("invalid argument #1 to gameactor: must be a tile number [0..gv.MAXTILES-1]", 2)
3315 helixhorne 2043
    end
3597 helixhorne 2044
 
3873 helixhorne 2045
    local lastargi = ourmaxn(args)
2046
    local func = args[lastargi]
2047
    if (type(func) ~= "function") then
2048
        func = args.func
2049
        lastargi = 1/0
3315 helixhorne 2050
    end
3873 helixhorne 2051
    if (type(func) ~= "function") then
3928 helixhorne 2052
        error("invalid gameactor call: must provide a function with last numeric arg or .func", 2)
3320 helixhorne 2053
    end
3315 helixhorne 2054
 
3873 helixhorne 2055
    local flags = (lastargi > 2 and args[2]) or args.flags or 0
4375 helixhorne 2056
    check_arg_number("flags", 2, flags)
3597 helixhorne 2057
 
3629 helixhorne 2058
    local AF = actor.FLAGS
3928 helixhorne 2059
    local chainflags = band(flags, AF._CHAIN_MASK_ACTOR)
2060
    flags = band(flags, BNOT.CHAIN_MASK_ACTOR)
3629 helixhorne 2061
 
2062
    if (chainflags == 0) then
4374 helixhorne 2063
        -- Default chaining behavior: don't, replace the old actor instead.
2064
        chainflags = AF.replace
3928 helixhorne 2065
    elseif (band(chainflags, chainflags-1) ~= 0) then
3829 helixhorne 2066
        error("invalid chaining control flags to gameactor", 2)
3629 helixhorne 2067
    end
2068
 
4374 helixhorne 2069
    local replacep = (chainflags==AF.replace)
3629 helixhorne 2070
    if (not replacep and not actor_funcs[tilenum]) then
2071
        error("attempt to chain code to nonexistent actor tile "..tilenum, 2)
2072
    end
2073
 
3928 helixhorne 2074
    local flags_rbits = band(flags, BNOT.USER_MASK)
3597 helixhorne 2075
    if (flags_rbits ~= 0) then
3873 helixhorne 2076
        error("invalid 'flags' argument (#2) to gameactor: must not set reserved bits (0x"
3597 helixhorne 2077
              ..(bit.tohex(flags_rbits))..")", 2)
2078
    end
2079
 
3873 helixhorne 2080
    local strength = ((lastargi > 3 and args[3]) or args.strength) or (replacep and 0 or nil)
3629 helixhorne 2081
    if (replacep or strength~=nil) then
4375 helixhorne 2082
        check_arg_number("strength", 3, strength)
3315 helixhorne 2083
    end
2084
 
3916 helixhorne 2085
    local act = ((lastargi > 4 and args[4]) or args.action) or (replacep and literal_act[0] or nil)
3629 helixhorne 2086
    if (replacep or act ~= nil) then
3916 helixhorne 2087
        if (type(act)=="number" and (act==0 or act==1)) then
2088
            act = literal_act[act]
2089
        elseif (not ffi.istype(con_action_ct, act)) then
2090
            error("invalid 'action' argument (#4) to gameactor: must be an action", 2)
3629 helixhorne 2091
        end
3315 helixhorne 2092
    end
2093
 
3916 helixhorne 2094
    local mov = ((lastargi > 5 and args[5]) or args.move) or (replacep and literal_mov[0] or nil)
3629 helixhorne 2095
    if (replacep or mov ~= nil) then
3916 helixhorne 2096
        if (type(mov)=="number" and (mov==0 or mov==1)) then
2097
            mov = literal_mov[mov]
2098
        elseif (not ffi.istype(con_move_ct, mov)) then
2099
            error("invalid 'move' argument (#5) to gameactor: must be a move", 2)
3629 helixhorne 2100
        end
3315 helixhorne 2101
    end
2102
 
3873 helixhorne 2103
    local movflags = ((lastargi > 6 and args[6]) or args.movflags) or (replacep and 0 or nil)
3629 helixhorne 2104
    if (replacep or movflags ~= nil) then
4375 helixhorne 2105
        check_arg_number("movflags", 6, movflags)
3315 helixhorne 2106
    end
2107
 
3937 helixhorne 2108
    -- Register a potentially passed drawn sprite animation callback function.
2109
    -- TODO: allow registering without main actor execution callback.
2110
    local animfunc = args.animate
2111
    if (animfunc ~= nil) then
2112
        if (type(animfunc) ~= "function") then
2113
            error("invalid 'animate' argument to gameactor: must be a function", 2)
2114
        end
2115
 
2116
        animsprite_funcs[tilenum] = replacep and func
2117
            or (chainflags==AF.chain_beg) and chain_func3(animfunc, animsprite_funcs[tilenum])
2118
            or (chainflags==AF.chain_end) and chain_func3(animsprite_funcs[tilenum], animfunc)
2119
            or assert(false)
2120
 
2121
        -- Register our EVENT_ANIMATEALLSPRITES only now so that it is not
2122
        -- called if there are no 'animate' definitions.
4515 hendricks2 2123
        gameevent_internal(97, animate_all_sprites)  -- EVENT_ANIMATEALLSPRITES
3937 helixhorne 2124
    end
2125
 
4374 helixhorne 2126
    -- All good, bitwise-OR the tile bits and register the actor!
2127
    ffiC.g_tile[tilenum]._flags = bit.bor(ffiC.g_tile[tilenum]._flags, flags)
3597 helixhorne 2128
 
3629 helixhorne 2129
    local newfunc = replacep and func
2130
        or (chainflags==AF.chain_beg) and chain_func3(func, actor_funcs[tilenum])
2131
        or (chainflags==AF.chain_end) and chain_func3(actor_funcs[tilenum], func)
2132
        or assert(false)
2133
 
2134
    gameactor_internal(tilenum, strength, act, mov, movflags, newfunc)
2135
    actor_funcs[tilenum] = newfunc
3315 helixhorne 2136
end
2137
 
3320 helixhorne 2138
 
3873 helixhorne 2139
-- gameevent{<event idx or string> [, flags], <event function>}
2140
local function our_gameevent(args)
3872 helixhorne 2141
    bcheck.top_level("gameevent")
2142
 
3873 helixhorne 2143
    if (type(args)~="table") then
2144
        error("invalid gameevent call: must be passed a table")
2145
    end
2146
 
2147
    local event = args[1]
2148
 
3320 helixhorne 2149
    if (type(event) == "string") then
2150
        if (event:sub(1,6) ~= "EVENT_") then
2151
            event = "EVENT_"..event
2152
        end
3380 helixhorne 2153
        local eventidx = con_lang.EVENT[event]
3320 helixhorne 2154
        if (eventidx == nil) then
2155
            errorf(2, "gameevent: invalid event label %q", event)
2156
        end
2157
        event = eventidx
2158
    end
2159
    if (type(event) ~= "number") then
3629 helixhorne 2160
        error("invalid argument #1 to gameevent: must be a number or event label", 2)
3320 helixhorne 2161
    end
3964 helixhorne 2162
    if (not (event >= 0 and event < con_lang.MAXEVENTS)) then
3320 helixhorne 2163
        error("invalid argument #1 to gameevent: must be an event number (0 .. MAXEVENTS-1)", 2)
2164
    end
2165
 
3629 helixhorne 2166
    local AF = actor.FLAGS
3320 helixhorne 2167
 
3873 helixhorne 2168
    -- Kind of CODEDUP from our_gameactor.
2169
    local lastargi = ourmaxn(args)
2170
    local func = args[lastargi]
2171
    if (type(func) ~= "function") then
2172
        func = args.func
2173
        lastargi = 1/0
2174
    end
2175
    if (type(func) ~= "function") then
2176
        error("invalid gameevent call: must provide a function with last numeric arg or .func", 2)
2177
    end
2178
 
3629 helixhorne 2179
    -- Event chaining: in Lunatic, chaining at the *end* is the default.
3873 helixhorne 2180
    local flags = (lastargi > 2 and args[2]) or args.flags or AF.chain_end
2181
    if (type(flags) ~= "number") then
2182
        error("invalid 'flags' argument (#2) to gameevent: must be a number", 2)
3320 helixhorne 2183
    end
2184
 
3928 helixhorne 2185
    if (band(flags, BNOT.CHAIN_MASK_EVENT) ~= 0) then
3873 helixhorne 2186
        error("invalid 'flags' argument to gameevent: must not set reserved bits", 2)
3629 helixhorne 2187
    end
2188
 
3873 helixhorne 2189
    local newfunc = (flags==AF.replace) and func
3629 helixhorne 2190
        or (flags==AF.chain_beg) and chain_func3(func, event_funcs[event])
2191
        or (flags==AF.chain_end) and chain_func3(event_funcs[event], func)
2192
        or assert(false)
2193
 
3320 helixhorne 2194
    gameevent_internal(event, newfunc)
2195
    event_funcs[event] = newfunc
2196
end
2197
 
2650 helixhorne 2198
--- non-default data and functions
3320 helixhorne 2199
G_.gameevent = our_gameevent
3315 helixhorne 2200
G_.gameactor = our_gameactor
3463 helixhorne 2201
-- These come from above:
2202
G_.player = player
2203
G_.actor = actor
2204
G_.projectile = projectile
3562 helixhorne 2205
G_.g_tile = g_tile
2650 helixhorne 2206
 
4236 helixhorne 2207
G_.LUNATIC_FIRST_TIME = (ffiC.g_elFirstTime ~= 0)
2208
 
4147 helixhorne 2209
-- A table that can be used for temporary data when debugging from the OSD.
2210
G_.d = {}
2650 helixhorne 2211
 
4147 helixhorne 2212
 
3790 helixhorne 2213
---=== Lunatic translator setup ===---
2650 helixhorne 2214
 
3790 helixhorne 2215
read_into_string = readintostr_mod  -- for lunacon
2216
local lunacon = require("lunacon")
2217
 
2218
local concode, lineinfo
2650 helixhorne 2219
 
3787 helixhorne 2220
--- Get Lua code for CON (+ mutator) code.
3788 helixhorne 2221
if (g_firstRun) then
3787 helixhorne 2222
    -- Compiling CON for the first time.
3388 helixhorne 2223
    local confn = { ffi.string(ffiC.G_ConFile()) }
2224
 
2225
    local nummods = ffiC.g_scriptModulesNum
2226
    if (nummods > 0) then
2227
        assert(ffiC.g_scriptModules ~= nil)
2228
 
2229
        for i=1,nummods do
2230
            confn[i+1] = ffi.string(ffiC.g_scriptModules[i-1])
2231
        end
2232
    end
2233
 
3535 helixhorne 2234
    concode, lineinfo = lunacon.compile(confn)
2235
 
3390 helixhorne 2236
    if (concode == nil) then
2237
        error("Failure compiling CON code, exiting.", 0)
2238
    end
3558 helixhorne 2239
    assert(lineinfo)
3535 helixhorne 2240
 
3787 helixhorne 2241
    -- Back up the translated code on the C side.
2242
    assert(type(concode)=="string")
2243
    ffiC.El_SetCON(concode)
2244
else
2245
    -- CON was already compiled.
2246
    concode = ffi.string(ffiC.g_elCON, ffiC.g_elCONSize)
3790 helixhorne 2247
    lineinfo = lunacon.get_lineinfo(concode)
3787 helixhorne 2248
end
2249
 
3790 helixhorne 2250
if (ffiC._DEBUG_LUNATIC ~= 0) then
2251
    -- XXX: lineinfo of 2nd up time has one line less.
2252
    printf("CON line info has %d Lua lines", #lineinfo.llines)
2253
end
2254
 
3787 helixhorne 2255
do
3535 helixhorne 2256
    -- Translate one Lua line number to a CON file name + line number
2257
    local function transline(lnum)
2258
        return string.format("%s:%d", lineinfo:getfline(tonumber(lnum)))
2259
    end
2260
 
2261
    -- Register the function that tweaks an error message, looking out for
2262
    -- errors from CON and translating the line numbers.
2263
    local function tweak_traceback_msg(errmsg)
2264
        return errmsg:gsub('%[string "CON"%]:([0-9]+)', transline)
2265
    end
2266
 
4142 helixhorne 2267
    lprivate.tweak_traceback_msg = tweak_traceback_msg
2268
 
3535 helixhorne 2269
    set_tweak_traceback_internal(tweak_traceback_msg)
3343 helixhorne 2270
end
2271
 
3796 helixhorne 2272
-- XXX: May still be require'd from user code, we don't want that (at least not
2273
-- under this name).
2274
local CON_MODULE_NAME = "_CON\0"
2275
 
2276
-- Set up Lunatic gamevar serialization.
2277
do
2278
    local savegame = require("savegame")
2279
 
4119 helixhorne 2280
    -- Callback for: const char *(int32_t *slenptr, int32_t levelnum);
2281
    ffiC.El_SerializeGamevars = function(slenptr, levelnum)
3796 helixhorne 2282
        local sb = savegame.savebuffer()
2283
 
3891 helixhorne 2284
        -- Module name, module table, restore_local. See SAVEFUNC_ARGS.
2285
        sb:addraw("local N,M,F=...")
2286
        -- A local to temporarily hold module locals.
2287
        sb:addraw("local L")
3796 helixhorne 2288
 
3891 helixhorne 2289
        -- XXX: System gamevars? Most of them ought to be saved with C data.
3796 helixhorne 2290
        for modname, modvars in pairs(module_gamevars) do
3908 helixhorne 2291
            sb:startmod(modname)
3891 helixhorne 2292
 
2293
            -- Handle global gamevars first.
3796 helixhorne 2294
            for i=1,#modvars do
2295
                local varname = modvars[i]
4140 helixhorne 2296
                local excludedVars = modname==CON_MODULE_NAME and varname=="_V" and
2297
                    package_loaded[CON_MODULE_NAME]._V._IS_NORESET_GAMEVAR or nil
2298
 
3796 helixhorne 2299
                -- Serialize gamevar named 'varname' from module named 'modname'.
2300
                -- XXX: May error. This will terminate EDuke32 since this callback
2301
                -- is run unprotected.
4140 helixhorne 2302
                if (sb:add("M."..varname, package_loaded[modname][varname], excludedVars)) then
3796 helixhorne 2303
                    -- We couldn't serialize that gamevar.
2304
                    slenptr[0] = -1
2305
                    -- Signal which gamevar that was.
2306
                    return (modname==CON_MODULE_NAME and "<CON>" or modname).."."..varname
2307
                end
2308
            end
3891 helixhorne 2309
 
2310
            local modthread = module_thread[modname]
2311
 
2312
            if (modthread) then
2313
                -- Handle local gamevars.
2314
                local gvmodi = module_gvlocali[modname]
2315
 
2316
                for li=gvmodi[1],gvmodi[2] do
2317
                    -- Serialize local with index <li>. Get its value first.
2318
                    local lname, lval = debug.getlocal(modthread, 1, li)
2319
 
2320
                    if (sb:add("L", lval)) then
2321
                        -- We couldn't serialize that gamevar.
2322
                        slenptr[0] = -1
2323
                        return "local "..modname.."."..lname
2324
                    end
2325
 
4118 helixhorne 2326
                    -- Emit code to call restore_local.
3891 helixhorne 2327
                    sb:addrawf("F(%d,L)", li)
2328
                end
2329
            end
2330
 
3908 helixhorne 2331
            sb:endmod()
3796 helixhorne 2332
        end
2333
 
2334
        -- Get the whole code as a string.
2335
        local savecode = sb:getcode()
2336
 
2337
        if (ffiC._DEBUG_LUNATIC ~= 0) then
2338
            -- Dump the code if Lunatic debugging is enabled and there is a
2339
            -- LUNATIC_SAVECODE_FN variable in the environment.
2340
            local os = require("os")
2341
            local fn = os.getenv("LUNATIC_SAVECODE_FN")
2342
 
2343
            if (fn ~= nil) then
4119 helixhorne 2344
                if (levelnum >= 0) then
2345
                    fn = fn .. levelnum
2346
                end
2347
 
3796 helixhorne 2348
                local io = require("io")
2349
                local f = io.open(fn, "w")
2350
 
2351
                if (f ~= nil) then
2352
                    f:write(savecode)
2353
                    f:close()
2354
                    printf("Wrote Lunatic gamevar restoration code to \"%s\".", fn)
2355
                end
2356
            end
2357
        end
2358
 
2359
        -- Set the size of the code and return the code to C.
2360
        slenptr[0] = #savecode
2361
        return savecode
2362
    end
2363
end
2364
 
2648 helixhorne 2365
-- change the environment of this chunk to the table G_
2827 helixhorne 2366
-- NOTE: all references to global variables from this point on
2367
-- (also in functions created after this point) refer to G_ !
2648 helixhorne 2368
setfenv(1, G_)
2369
 
2863 helixhorne 2370
-- Print keys and values of a table.
2648 helixhorne 2371
local function printkv(label, table)
3060 helixhorne 2372
    print("========== Keys and values of "..label.." ("..tostring(table)..")")
2863 helixhorne 2373
    for k,v in pairs(table) do
3343 helixhorne 2374
        print(k .. ": " .. tostring(v))
2648 helixhorne 2375
    end
3343 helixhorne 2376
    print("----------")
2648 helixhorne 2377
end
2378
 
2710 helixhorne 2379
--printkv('_G AFTER SETFENV', _G)
2648 helixhorne 2380
 
2381
 
2382
---=== Restricted access to C variables from Lunatic ===---
2383
 
2298 helixhorne 2384
-- error(..., 2) is to blame the caller and get its line numbers
2294 helixhorne 2385
 
3928 helixhorne 2386
-- Map of 'gv' variable names to C ones.
2387
local varnameMap = {
2388
    gametic = "g_moveThingsCount",
4031 helixhorne 2389
    RETURN = "g_RETURN",
4112 helixhorne 2390
    _sessionVar = "g_elSessionVar",
3928 helixhorne 2391
}
2392
 
2393
gv_access.gametic = true
4031 helixhorne 2394
gv_access.RETURN = true
4112 helixhorne 2395
gv_access._sessionVar = true
3928 helixhorne 2396
 
2044 helixhorne 2397
local tmpmt = {
3597 helixhorne 2398
    __index = function(_, key)
3406 helixhorne 2399
        if (gv_access[key] == nil) then
3928 helixhorne 2400
            -- Read access allowed.
3406 helixhorne 2401
            return ffiC[key]
3928 helixhorne 2402
        elseif (type(gv_access[key])~="boolean") then
2403
            -- Overridden 'gv' pseudo-member...
3406 helixhorne 2404
            return gv_access[key]
3928 helixhorne 2405
        elseif (varnameMap[key]) then
2406
            -- Variable known under a different name on the C side.
2407
            return ffiC[varnameMap[key]]
3406 helixhorne 2408
        end
2409
        error("access forbidden", 2)
2410
    end,
3556 helixhorne 2411
 
3597 helixhorne 2412
    __newindex = function(_, key, val)
3593 helixhorne 2413
        if (gv_access[key] == nil) then
4030 helixhorne 2414
            -- Variables declared 'const' are handled by LuaJIT.
3556 helixhorne 2415
            ffiC[key] = val
4031 helixhorne 2416
        elseif (varnameMap[key]) then
2417
            ffiC[varnameMap[key]] = val
3556 helixhorne 2418
        else
2419
            error("write access forbidden", 2)
2420
        end
2421
    end,
2044 helixhorne 2422
}
3597 helixhorne 2423
gv = setmtonce(gv_, tmpmt)
2044 helixhorne 2424
 
3060 helixhorne 2425
-- This will create 'sprite', 'wall', etc. HERE, i.e. in the environment of this chunk
2426
defs_c.create_globals(_G)
2863 helixhorne 2427
 
2648 helixhorne 2428
-- REMOVE this for release
3966 helixhorne 2429
if (ffiC._DEBUG_LUNATIC ~= 0) then
2430
    local DBG_ = {}
2431
    DBG_.debug = require("debug")
2432
    DBG_.printkv = printkv
2433
    DBG_.loadstring = loadstring
2434
    DBG_.oom = function()
2435
        local s = "1"
2436
        for i=1,math.huge do
2437
            s = s..s
2438
        end
3380 helixhorne 2439
    end
2611 helixhorne 2440
 
3966 helixhorne 2441
    -- Test reading from all struct members
2442
    DBG_.testmembread = function()
2443
        for _1, sac in pairs { con_lang.StructAccessCode, con_lang.StructAccessCode2 } do
2444
            for what, labels in pairs(sac) do
2445
                if (what~="tspr") then
2446
                    for _3, membaccode in pairs(labels) do
2447
                        if (type(membaccode)=="table") then
2448
                            membaccode = membaccode[1]
2449
                        end
2450
                        if (membaccode) then
2451
                            local codestr = [[
3650 helixhorne 2452
do
2453
    local _bit,_math=require'bit',require'math'
4209 helixhorne 2454
    local _con=require'con'
3650 helixhorne 2455
    local _band,_gv=_bit.band,gv
2456
local tmp=]]..
4375 helixhorne 2457
                            membaccode:gsub("^_gud%(_pli%)", "_con._get_userdef(0)"):gsub("%%s","0").." end"
3966 helixhorne 2458
                            local code = assert(loadstring(codestr))
2459
                            code()
2460
                        end
3475 helixhorne 2461
                    end
2462
                end
2463
            end
2464
        end
2465
    end
3966 helixhorne 2466
 
2467
    allowed_modules._LUNATIC_DBG = DBG_
3475 helixhorne 2468
end
2611 helixhorne 2469
 
2648 helixhorne 2470
---=== Finishing environment setup ===---
2611 helixhorne 2471
 
2710 helixhorne 2472
--printkv('_G AFTER DECLS', _G)
2193 helixhorne 2473
 
4047 helixhorne 2474
local index_error_mt = {
2475
    __index = function(_, key)
2476
        error("attempt to read undeclared variable '"..key.."'", 2)
2477
    end,
2193 helixhorne 2478
 
4047 helixhorne 2479
    __metatable = true,
2480
}
2481
 
2310 helixhorne 2482
-- PiL 14.2 continued
2648 helixhorne 2483
-- We need this at the end because we were previously doing just that!
4047 helixhorne 2484
setmetatable(G_, index_error_mt)
3642 helixhorne 2485
 
3967 helixhorne 2486
local global_mt = {
2487
    __index = G_,
2488
 
2489
    __newindex = function()
2490
        error("attempt to write into the global environment")
2491
    end,
2492
 
2493
    __metatable = true,
2494
}
2495
 
2648 helixhorne 2496
-- Change the environment of the running Lua thread so that everything
2497
-- what we've set up will be available when this chunk is left.
3473 helixhorne 2498
-- In particular, we need the globals defined after setting this chunk's
2648 helixhorne 2499
-- environment earlier.
3967 helixhorne 2500
setfenv(0, setmetatable({}, global_mt))
3343 helixhorne 2501
 
3891 helixhorne 2502
do
2503
    -- If we're running from a savegame restoration, create the restoration
2504
    -- function. Must be here, after the above setfenv(), because it must be
2505
    -- created in this protected ('user') context!
2506
    local cstr = ffiC.g_elSavecode
2507
    if (cstr~=nil) then
2508
        local restorecode = ffi.string(cstr)
2509
        ffiC.El_FreeSaveCode()
2510
 
2511
        g_restorefunc = assert(loadstring(restorecode))
2512
    end
2513
end
2514
 
4119 helixhorne 2515
-- Restore CON gamevars from loadmapstate.
2516
-- TODO: non-user-defined gamevars.
2517
-- TODO: savegames.
2518
-- int32_t El_RestoreGamevars(const char *)
2519
ffiC.El_RestoreGamevars = function(savecode)
2520
    savecode = ffi.string(savecode)
2521
    local restorefunc = assert(loadstring(savecode))
2522
    restorefunc(CON_MODULE_NAME, package_loaded[CON_MODULE_NAME], nil)
2523
    return 0
2524
end
2525
 
3788 helixhorne 2526
-- Run the CON code translated into Lua.
4370 helixhorne 2527
if (assert(concode ~= nil)) then
3343 helixhorne 2528
    local confunc, conerrmsg = loadstring(concode, "CON")
2529
    if (confunc == nil) then
3558 helixhorne 2530
        error("Failure loading translated CON code: "..conerrmsg, 0)
3343 helixhorne 2531
    end
3796 helixhorne 2532
 
3891 helixhorne 2533
    -- Emulate our 'require' for the CON module when running it, for
2534
    -- our_module() which is called from the generated Lua code.
2535
    table.insert(modname_stack, CON_MODULE_NAME)
3917 helixhorne 2536
    local conlabels, conaction, conmove, conai = confunc()
3891 helixhorne 2537
    table.remove(modname_stack)
3870 helixhorne 2538
 
3917 helixhorne 2539
    local function protect_con_table(tab)
4047 helixhorne 2540
        -- NOTE: Some of our code specifically excepts the name tables to be
2541
        -- indexable with nonexistent keys. See e.g. control.c: _A_SpawnGlass()
4050 helixhorne 2542
        if (ffiC._LUNATIC_STRICT ~= 0) then
2543
            tab = setmetatable(tab, index_error_mt)
2544
        end
3917 helixhorne 2545
        return setmtonce({}, { __index=tab, __newindex=basemod_newidx })
2546
    end
3871 helixhorne 2547
 
3917 helixhorne 2548
    -- Set up CON.* modules, providing access to diffenrent kinds of labels
2549
    -- defined in CON from Lua. See CONCODE_RETURN in lunacon.lua.
2550
    allowed_modules["CON.DEFS"] = protect_con_table(conlabels)
2551
    allowed_modules["CON.ACTION"] = protect_con_table(conaction)
2552
    allowed_modules["CON.MOVE"] = protect_con_table(conmove)
2553
    allowed_modules["CON.AI"] = protect_con_table(conai)
2554
 
3871 helixhorne 2555
    -- Propagate potentially remapped defines to the control module.
2556
    con._setuplabels(conlabels)
4370 helixhorne 2557
 
4376 helixhorne 2558
    local function getLabelValue(str, doupper)
2559
        return conlabels[doupper and string.upper(str) or str]
2560
    end
2561
 
4370 helixhorne 2562
    ffiC.El_GetLabelValue = function(label)
2563
        local str = ffi.string(label)
4376 helixhorne 2564
        local ok, val = pcall(getLabelValue, str, false)
2565
        if (not ok or type(val)~="number") then
2566
            ok, val = pcall(getLabelValue, str, true)
2567
        end
2568
        return (ok and type(val)=="number") and val or bit.tobit(0x80000000)
4370 helixhorne 2569
    end
3343 helixhorne 2570
end
3788 helixhorne 2571
 
2572
-- When starting a map, load Lua modules given on the command line.
2573
if (not g_firstRun) then
2574
    local i=0
2575
    while (ffiC.g_elModules[i] ~= nil) do
3867 helixhorne 2576
        -- Get the module name and strip the trailing extension.
2577
        local modname = ffi.string(ffiC.g_elModules[i]):gsub("%.lua$","")
2578
 
2579
        if (modname:find("%.")) then
2580
            -- Because they will be replaced by dirseps in our_require().
2581
            error("Dots are not permitted in module names", 0)
2582
        end
2583
        -- Allow forward slashes in module names from the cmdline.
2584
        our_require((modname:gsub("%.lua$",""):gsub("/",".")))
2585
 
3788 helixhorne 2586
        i = i+1
2587
    end
4236 helixhorne 2588
 
2589
    ffiC.g_elFirstTime = 0
3788 helixhorne 2590
end