Subversion Repositories eduke32

Rev

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