code:
// Custom style file for GNU Source-highlight, derived from its default.style

bgcolor "white"; // the background color for documents
context gray; // the color for context lines (when specified with line ranges)

keyword darkblue b; // for language keywords
string "#116611" f; // for strings and chars
specialchar pink f; // for special chars, e.g., \n, \t, \\
comment "#444444" i, noref; // for comments
cbracket red; // for block brackets (e.g. {, })

repo_name: orochi/nblood

license: mit


code:
----------------------------------------------------------------------------
-- LuaJIT compiler dump module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module can be used to debug the JIT compiler itself. It dumps the
-- code representations and structures used in various compiler stages.
--
-- Example usage:
--
--   luajit -jdump -e "local x=0; for i=1,1e6 do x=x+i end; print(x)"
--   luajit -jdump=im -e "for i=1,1000 do for j=1,1000 do end end" | less -R
--   luajit -jdump=is myapp.lua | less -R
--   luajit -jdump=-b myapp.lua
--   luajit -jdump=+aH,myapp.html myapp.lua
--   luajit -jdump=ixT,myapp.dump myapp.lua
--
-- The first argument specifies the dump mode. The second argument gives
-- the output file name. Default output is to stdout, unless the environment
-- variable LUAJIT_DUMPFILE is set. The file is overwritten every time the
-- module is started.
--
-- Different features can be turned on or off with the dump mode. If the
-- mode starts with a '+', the following features are added to the default
-- set of features; a '-' removes them. Otherwise the features are replaced.
--
-- The following dump features are available (* marks the default):
--
--  * t  Print a line for each started, ended or aborted trace (see also -jv).
--  * b  Dump the traced bytecode.
--  * i  Dump the IR (intermediate representation).
--    r  Augment the IR with register/stack slots.
--    s  Dump the snapshot map.
--  * m  Dump the generated machine code.
--    x  Print each taken trace exit.
--    X  Print each taken trace exit and the contents of all registers.
--    a  Print the IR of aborted traces, too.
--
-- The output format can be set with the following characters:
--
--    T  Plain text output.
--    A  ANSI-colored text output
--    H  Colorized HTML + CSS output.
--
-- The default output format is plain text. It's set to ANSI-colored text
-- if the COLORTERM variable is set. Note: this is independent of any output
-- redirection, which is actually considered a feature.
--
-- You probably want to use less -R to enjoy viewing ANSI-colored text from
-- a pipe or a file. Add this to your ~/.bashrc: export LESS="-R"
--
------------------------------------------------------------------------------

-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20003, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc
local traceinfo, traceir, tracek = jutil.traceinfo, jutil.traceir, jutil.tracek
local tracemc, tracesnap = jutil.tracemc, jutil.tracesnap
local traceexitstub, ircalladdr = jutil.traceexitstub, jutil.ircalladdr
local bit = require("bit")
local band, shl, shr = bit.band, bit.lshift, bit.rshift
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, char, rep = string.byte, string.char, string.rep
local type, tostring = type, tostring
local stdout, stderr = io.stdout, io.stderr

-- Load other modules on-demand.
local bcline, disass

-- Active flag, output file handle and dump mode.
local active, out, dumpmode

------------------------------------------------------------------------------

local symtabmt = { __index = false }
local symtab = {}
local nexitsym = 0

-- Fill nested symbol table with per-trace exit stub addresses.
local function fillsymtab_tr(tr, nexit)
  local t = {}
  symtabmt.__index = t
  if jit.arch == "mips" or jit.arch == "mipsel" then
    t[traceexitstub(tr, 0)] = "exit"
    return
  end
  for i=0,nexit-1 do
    local addr = traceexitstub(tr, i)
    t[addr] = tostring(i)
  end
  local addr = traceexitstub(tr, nexit)
  if addr then t[addr] = "stack_check" end
end

-- Fill symbol table with trace exit stub addresses.
local function fillsymtab(tr, nexit)
  local t = symtab
  if nexitsym == 0 then
    local ircall = vmdef.ircall
    for i=0,#ircall do
      local addr = ircalladdr(i)
      if addr ~= 0 then t[addr] = ircall[i] end
    end
  end
  if nexitsym == 1000000 then -- Per-trace exit stubs.
    fillsymtab_tr(tr, nexit)
  elseif nexit > nexitsym then -- Shared exit stubs.
    for i=nexitsym,nexit-1 do
      local addr = traceexitstub(i)
      if addr == nil then -- Fall back to per-trace exit stubs.
	fillsymtab_tr(tr, nexit)
	setmetatable(symtab, symtabmt)
	nexit = 1000000
	break
      end
      t[addr] = tostring(i)
    end
    nexitsym = nexit
  end
  return t
end

local function dumpwrite(s)
  out:write(s)
end

-- Disassemble machine code.
local function dump_mcode(tr)
  local info = traceinfo(tr)
  if not info then return end
  local mcode, addr, loop = tracemc(tr)
  if not mcode then return end
  if not disass then disass = require("jit.dis_"..jit.arch) end
  out:write("---- TRACE ", tr, " mcode ", #mcode, "\n")
  local ctx = disass.create(mcode, addr, dumpwrite)
  ctx.hexdump = 0
  ctx.symtab = fillsymtab(tr, info.nexit)
  if loop ~= 0 then
    symtab[addr+loop] = "LOOP"
    ctx:disass(0, loop)
    out:write("->LOOP:\n")
    ctx:disass(loop, #mcode-loop)
    symtab[addr+loop] = nil
  else
    ctx:disass(0, #mcode)
  end
end

------------------------------------------------------------------------------

local irtype_text = {
  [0] = "nil",
  "fal",
  "tru",
  "lud",
  "str",
  "p32",
  "thr",
  "pro",
  "fun",
  "p64",
  "cdt",
  "tab",
  "udt",
  "flt",
  "num",
  "i8 ",
  "u8 ",
  "i16",
  "u16",
  "int",
  "u32",
  "i64",
  "u64",
  "sfp",
}

local colortype_ansi = {
  [0] = "%s",
  "%s",
  "%s",
  "\027[36m%s\027[m",
  "\027[32m%s\027[m",
  "%s",
  "\027[1m%s\027[m",
  "%s",
  "\027[1m%s\027[m",
  "%s",
  "\027[33m%s\027[m",
  "\027[31m%s\027[m",
  "\027[36m%s\027[m",
  "\027[34m%s\027[m",
  "\027[34m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
  "\027[35m%s\027[m",
}

local function colorize_text(s, t)
  return s
end

local function colorize_ansi(s, t)
  return format(colortype_ansi[t], s)
end

local irtype_ansi = setmetatable({},
  { __index = function(tab, t)
      local s = colorize_ansi(irtype_text[t], t); tab[t] = s; return s; end })

local html_escape = { ["<"] = "<", [">"] = ">", ["&"] = "&", }

local function colorize_html(s, t)
  s = gsub(s, "[<>&]", html_escape)
  return format('%s', irtype_text[t], s)
end

local irtype_html = setmetatable({},
  { __index = function(tab, t)
      local s = colorize_html(irtype_text[t], t); tab[t] = s; return s; end })

local header_html = [[

]]

local colorize, irtype

-- Lookup tables to convert some literals into names.
local litname = {
  ["SLOAD "] = setmetatable({}, { __index = function(t, mode)
    local s = ""
    if band(mode, 1) ~= 0 then s = s.."P" end
    if band(mode, 2) ~= 0 then s = s.."F" end
    if band(mode, 4) ~= 0 then s = s.."T" end
    if band(mode, 8) ~= 0 then s = s.."C" end
    if band(mode, 16) ~= 0 then s = s.."R" end
    if band(mode, 32) ~= 0 then s = s.."I" end
    t[mode] = s
    return s
  end}),
  ["XLOAD "] = { [0] = "", "R", "V", "RV", "U", "RU", "VU", "RVU", },
  ["CONV  "] = setmetatable({}, { __index = function(t, mode)
    local s = irtype[band(mode, 31)]
    s = irtype[band(shr(mode, 5), 31)].."."..s
    if band(mode, 0x400) ~= 0 then s = s.." trunc"
    elseif band(mode, 0x800) ~= 0 then s = s.." sext" end
    local c = shr(mode, 14)
    if c == 2 then s = s.." index" elseif c == 3 then s = s.." check" end
    t[mode] = s
    return s
  end}),
  ["FLOAD "] = vmdef.irfield,
  ["FREF  "] = vmdef.irfield,
  ["FPMATH"] = vmdef.irfpm,
}

local function ctlsub(c)
  if c == "\n" then return "\\n"
  elseif c == "\r" then return "\\r"
  elseif c == "\t" then return "\\t"
  else return format("\\%03d", byte(c))
  end
end

local function fmtfunc(func, pc)
  local fi = funcinfo(func, pc)
  if fi.loc then
    return fi.loc
  elseif fi.ffid then
    return vmdef.ffnames[fi.ffid]
  elseif fi.addr then
    return format("C:%x", fi.addr)
  else
    return "(?)"
  end
end

local function formatk(tr, idx)
  local k, t, slot = tracek(tr, idx)
  local tn = type(k)
  local s
  if tn == "number" then
    if k == 2^52+2^51 then
      s = "bias"
    else
      s = format("%+.14g", k)
    end
  elseif tn == "string" then
    s = format(#k > 20 and '"%.20s"~' or '"%s"', gsub(k, "%c", ctlsub))
  elseif tn == "function" then
    s = fmtfunc(k)
  elseif tn == "table" then
    s = format("{%p}", k)
  elseif tn == "userdata" then
    if t == 12 then
      s = format("userdata:%p", k)
    else
      s = format("[%p]", k)
      if s == "[0x00000000]" then s = "NULL" end
    end
  elseif t == 21 then -- int64_t
    s = sub(tostring(k), 1, -3)
    if sub(s, 1, 1) ~= "-" then s = "+"..s end
  else
    s = tostring(k) -- For primitives.
  end
  s = colorize(format("%-4s", s), t)
  if slot then
    s = format("%s @%d", s, slot)
  end
  return s
end

local function printsnap(tr, snap)
  local n = 2
  for s=0,snap[1]-1 do
    local sn = snap[n]
    if shr(sn, 24) == s then
      n = n + 1
      local ref = band(sn, 0xffff) - 0x8000 -- REF_BIAS
      if ref < 0 then
	out:write(formatk(tr, ref))
      elseif band(sn, 0x80000) ~= 0 then -- SNAP_SOFTFPNUM
	out:write(colorize(format("%04d/%04d", ref, ref+1), 14))
      else
	local m, ot, op1, op2 = traceir(tr, ref)
	out:write(colorize(format("%04d", ref), band(ot, 31)))
      end
      out:write(band(sn, 0x10000) == 0 and " " or "|") -- SNAP_FRAME
    else
      out:write("---- ")
    end
  end
  out:write("]\n")
end

-- Dump snapshots (not interleaved with IR).
local function dump_snap(tr)
  out:write("---- TRACE ", tr, " snapshots\n")
  for i=0,1000000000 do
    local snap = tracesnap(tr, i)
    if not snap then break end
    out:write(format("#%-3d %04d [ ", i, snap[0]))
    printsnap(tr, snap)
  end
end

-- Return a register name or stack slot for a rid/sp location.
local function ridsp_name(ridsp, ins)
  if not disass then disass = require("jit.dis_"..jit.arch) end
  local rid, slot = band(ridsp, 0xff), shr(ridsp, 8)
  if rid == 253 or rid == 254 then
    return (slot == 0 or slot == 255) and " {sink" or format(" {%04d", ins-slot)
  end
  if ridsp > 255 then return format("[%x]", slot*4) end
  if rid < 128 then return disass.regname(rid) end
  return ""
end

-- Dump CALL* function ref and return optional ctype.
local function dumpcallfunc(tr, ins)
  local ctype
  if ins > 0 then
    local m, ot, op1, op2 = traceir(tr, ins)
    if band(ot, 31) == 0 then -- nil type means CARG(func, ctype).
      ins = op1
      ctype = formatk(tr, op2)
    end
  end
  if ins < 0 then
    out:write(format("[0x%x](", tonumber((tracek(tr, ins)))))
  else
    out:write(format("%04d (", ins))
  end
  return ctype
end

-- Recursively gather CALL* args and dump them.
local function dumpcallargs(tr, ins)
  if ins < 0 then
    out:write(formatk(tr, ins))
  else
    local m, ot, op1, op2 = traceir(tr, ins)
    local oidx = 6*shr(ot, 8)
    local op = sub(vmdef.irnames, oidx+1, oidx+6)
    if op == "CARG  " then
      dumpcallargs(tr, op1)
      if op2 < 0 then
	out:write(" ", formatk(tr, op2))
      else
	out:write(" ", format("%04d", op2))
      end
    else
      out:write(format("%04d", ins))
    end
  end
end

-- Dump IR and interleaved snapshots.
local function dump_ir(tr, dumpsnap, dumpreg)
  local info = traceinfo(tr)
  if not info then return end
  local nins = info.nins
  out:write("---- TRACE ", tr, " IR\n")
  local irnames = vmdef.irnames
  local snapref = 65536
  local snap, snapno
  if dumpsnap then
    snap = tracesnap(tr, 0)
    snapref = snap[0]
    snapno = 0
  end
  for ins=1,nins do
    if ins >= snapref then
      if dumpreg then
	out:write(format("....              SNAP   #%-3d [ ", snapno))
      else
	out:write(format("....        SNAP   #%-3d [ ", snapno))
      end
      printsnap(tr, snap)
      snapno = snapno + 1
      snap = tracesnap(tr, snapno)
      snapref = snap and snap[0] or 65536
    end
    local m, ot, op1, op2, ridsp = traceir(tr, ins)
    local oidx, t = 6*shr(ot, 8), band(ot, 31)
    local op = sub(irnames, oidx+1, oidx+6)
    if op == "LOOP  " then
      if dumpreg then
	out:write(format("%04d ------------ LOOP ------------\n", ins))
      else
	out:write(format("%04d ------ LOOP ------------\n", ins))
      end
    elseif op ~= "NOP   " and op ~= "CARG  " and
	   (dumpreg or op ~= "RENAME") then
      local rid = band(ridsp, 255)
      if dumpreg then
	out:write(format("%04d %-6s", ins, ridsp_name(ridsp, ins)))
      else
	out:write(format("%04d ", ins))
      end
      out:write(format("%s%s %s %s ",
		       (rid == 254 or rid == 253) and "}" or
		       (band(ot, 128) == 0 and " " or ">"),
		       band(ot, 64) == 0 and " " or "+",
		       irtype[t], op))
      local m1, m2 = band(m, 3), band(m, 3*4)
      if sub(op, 1, 4) == "CALL" then
	local ctype
	if m2 == 1*4 then -- op2 == IRMlit
	  out:write(format("%-10s  (", vmdef.ircall[op2]))
	else
	  ctype = dumpcallfunc(tr, op2)
	end
	if op1 ~= -1 then dumpcallargs(tr, op1) end
	out:write(")")
	if ctype then out:write(" ctype ", ctype) end
      elseif op == "CNEW  " and op2 == -1 then
	out:write(formatk(tr, op1))
      elseif m1 ~= 3 then -- op1 != IRMnone
	if op1 < 0 then
	  out:write(formatk(tr, op1))
	else
	  out:write(format(m1 == 0 and "%04d" or "#%-3d", op1))
	end
	if m2 ~= 3*4 then -- op2 != IRMnone
	  if m2 == 1*4 then -- op2 == IRMlit
	    local litn = litname[op]
	    if litn and litn[op2] then
	      out:write("  ", litn[op2])
	    elseif op == "UREFO " or op == "UREFC " then
	      out:write(format("  #%-3d", shr(op2, 8)))
	    else
	      out:write(format("  #%-3d", op2))
	    end
	  elseif op2 < 0 then
	    out:write("  ", formatk(tr, op2))
	  else
	    out:write(format("  %04d", op2))
	  end
	end
      end
      out:write("\n")
    end
  end
  if snap then
    if dumpreg then
      out:write(format("....              SNAP   #%-3d [ ", snapno))
    else
      out:write(format("....        SNAP   #%-3d [ ", snapno))
    end
    printsnap(tr, snap)
  end
end

------------------------------------------------------------------------------

local recprefix = ""
local recdepth = 0

-- Format trace error message.
local function fmterr(err, info)
  if type(err) == "number" then
    if type(info) == "function" then info = fmtfunc(info) end
    err = format(vmdef.traceerr[err], info)
  end
  return err
end

-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
  if what == "stop" or (what == "abort" and dumpmode.a) then
    if dumpmode.i then dump_ir(tr, dumpmode.s, dumpmode.r and what == "stop")
    elseif dumpmode.s then dump_snap(tr) end
    if dumpmode.m then dump_mcode(tr) end
  end
  if what == "start" then
    if dumpmode.H then out:write('
\n') end
    out:write("---- TRACE ", tr, " ", what)
    if otr then out:write(" ", otr, "/", oex) end
    out:write(" ", fmtfunc(func, pc), "\n")
  elseif what == "stop" or what == "abort" then
    out:write("---- TRACE ", tr, " ", what)
    if what == "abort" then
      out:write(" ", fmtfunc(func, pc), " -- ", fmterr(otr, oex), "\n")
    else
      local info = traceinfo(tr)
      local link, ltype = info.link, info.linktype
      if link == tr or link == 0 then
	out:write(" -> ", ltype, "\n")
      elseif ltype == "root" then
	out:write(" -> ", link, "\n")
      else
	out:write(" -> ", link, " ", ltype, "\n")
      end
    end
    if dumpmode.H then out:write("
\n\n") else out:write("\n") end
  else
    out:write("---- TRACE ", what, "\n\n")
  end
  out:flush()
end

-- Dump recorded bytecode.
local function dump_record(tr, func, pc, depth, callee)
  if depth ~= recdepth then
    recdepth = depth
    recprefix = rep(" .", depth)
  end
  local line
  if pc >= 0 then
    line = bcline(func, pc, recprefix)
    if dumpmode.H then line = gsub(line, "[<>&]", html_escape) end
  else
    line = "0000 "..recprefix.." FUNCC      \n"
    callee = func
  end
  if pc <= 0 then
    out:write(sub(line, 1, -2), "         ; ", fmtfunc(func), "\n")
  else
    out:write(line)
  end
  if pc >= 0 and band(funcbc(func, pc), 0xff) < 16 then -- ORDER BC
    out:write(bcline(func, pc+1, recprefix)) -- Write JMP for cond.
  end
end

------------------------------------------------------------------------------

-- Dump taken trace exits.
local function dump_texit(tr, ex, ngpr, nfpr, ...)
  out:write("---- TRACE ", tr, " exit ", ex, "\n")
  if dumpmode.X then
    local regs = {...}
    if jit.arch == "x64" then
      for i=1,ngpr do
	out:write(format(" %016x", regs[i]))
	if i % 4 == 0 then out:write("\n") end
      end
    else
      for i=1,ngpr do
	out:write(format(" %08x", regs[i]))
	if i % 8 == 0 then out:write("\n") end
      end
    end
    if jit.arch == "mips" or jit.arch == "mipsel" then
      for i=1,nfpr,2 do
	out:write(format(" %+17.14g", regs[ngpr+i]))
	if i % 8 == 7 then out:write("\n") end
      end
    else
      for i=1,nfpr do
	out:write(format(" %+17.14g", regs[ngpr+i]))
	if i % 4 == 0 then out:write("\n") end
      end
    end
  end
end

------------------------------------------------------------------------------

-- Detach dump handlers.
local function dumpoff()
  if active then
    active = false
    jit.attach(dump_texit)
    jit.attach(dump_record)
    jit.attach(dump_trace)
    if out and out ~= stdout and out ~= stderr then out:close() end
    out = nil
  end
end

-- Open the output file and attach dump handlers.
local function dumpon(opt, outfile)
  if active then dumpoff() end

  local colormode = os.getenv("COLORTERM") and "A" or "T"
  if opt then
    opt = gsub(opt, "[TAH]", function(mode) colormode = mode; return ""; end)
  end

  local m = { t=true, b=true, i=true, m=true, }
  if opt and opt ~= "" then
    local o = sub(opt, 1, 1)
    if o ~= "+" and o ~= "-" then m = {} end
    for i=1,#opt do m[sub(opt, i, i)] = (o ~= "-") end
  end
  dumpmode = m

  if m.t or m.b or m.i or m.s or m.m then
    jit.attach(dump_trace, "trace")
  end
  if m.b then
    jit.attach(dump_record, "record")
    if not bcline then bcline = require("jit.bc").line end
  end
  if m.x or m.X then
    jit.attach(dump_texit, "texit")
  end

  if not outfile then outfile = os.getenv("LUAJIT_DUMPFILE") end
  if outfile then
    out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
  else
    out = stdout
  end

  m[colormode] = true
  if colormode == "A" then
    colorize = colorize_ansi
    irtype = irtype_ansi
  elseif colormode == "H" then
    colorize = colorize_html
    irtype = irtype_html
    out:write(header_html)
  else
    colorize = colorize_text
    irtype = irtype_text
  end

  active = true
end

-- Public module functions.
module(...)

on = dumpon
off = dumpoff
start = dumpon -- For -j command line option.


code:
{
engine_main_arrays_are_static;
engine_v8;

saveboard_maptext;
loadboard_maptext;

sector;
wall;
sprite;
tsprite;
spriteext;

Numsprites;
numsectors;
numwalls;
numyaxbunches;
spritesortcnt;
guniqhudid;

qsetmode;
rendmode;
totalclock;
randomseed;
xdim;
ydim;
windowxy1;
windowxy2;
yxaspect;
viewingrange;

sectorofwall_noquick;
getceilzofslopeptr;
getflorzofslopeptr;
getzsofslopeptr;
spriteheightofsptr;

changespritesect;
changespritestat;

headspritesect;
headspritestat;
prevspritesect;
prevspritestat;
nextspritesect;
nextspritestat;
tilesiz;
picanm;

show2dsector;

headsectbunch;
nextsectbunch;

krand;
ksqrt;
inside;
getangle;
Mulscale;
cansee;
hitscan;
dragpoint;
neartag;
getzrange;
clipmovex;
rotatesprite_;
setaspect;

getclosestcol_lim;
palookup;
palette;
getblendtab;
setblendtab;
setpalookup;

kopen4load;
kfilelength;
kclose;
kread;
klseek;

dist;
ldist;

updatesector;
updatesectorz;
updatesectorbreadth;

getticks;
gethiticks;
OSD_Printf;

Bcrc32;

luaJIT_BC__defs_editor;
luaJIT_BC_defs_common;
luaJIT_BC_engine_maptext;
luaJIT_BC_engine;
luaJIT_BC_bcarray;
luaJIT_BC_bcheck;
luaJIT_BC_bitar;
luaJIT_BC_xmath;
luaJIT_BC_v;
luaJIT_BC_dump;
luaJIT_BC_dis_x86;
luaJIT_BC_dis_x64;

g_argv;

_getnumber16;
getstring_simple;
listsearchpath;
LM_Register;
LM_Clear;

basepaltable;
};


code:
{
engine_main_arrays_are_static;
engine_v8;

saveboard_maptext;
loadboard_maptext;

sector;
wall;
sprite;
tsprite;
spriteext;

Numsprites;
numsectors;
numwalls;
numyaxbunches;
spritesortcnt;
guniqhudid;

qsetmode;
rendmode;
totalclock;
randomseed;
xdim;
ydim;
windowxy1;
windowxy2;
yxaspect;
viewingrange;

sectorofwall_noquick;
getceilzofslopeptr;
getflorzofslopeptr;
getzsofslopeptr;
spriteheightofsptr;

changespritesect;
changespritestat;

headspritesect;
headspritestat;
prevspritesect;
prevspritestat;
nextspritesect;
nextspritestat;
tilesiz;
picanm;

show2dsector;

headsectbunch;
nextsectbunch;

krand;
ksqrt;
inside;
getangle;
Mulscale;
cansee;
hitscan;
dragpoint;
neartag;
getzrange;
clipmovex;
rotatesprite_;
setaspect;

getclosestcol_lim;
palookup;
palette;
getblendtab;
setblendtab;
setpalookup;

kopen4load;
kfilelength;
kclose;
kread;
klseek;

pathsearchmode;
klistfree;
klistpath;

dist;
ldist;

updatesector;
updatesectorz;
updatesectorbreadth;

getticks;
gethiticks;
OSD_Printf;

Bcrc32;

luaJIT_BC_defs_common;
luaJIT_BC_engine_maptext;
luaJIT_BC_engine;

g_argv;

g_elCONSize;
g_elCON;
El_SetCON;
El_OnError;

basepaltable;

g_elSavecode;
El_FreeSaveCode;
El_SerializeGamevars;
El_RestoreGamevars;
El_GetLabelValue;

s_buildRev;
g_sizes_of_what;
g_sizes_of;
g_elFirstTime;
g_elCallDepth;
block_deletesprite;
myconnectindex;
g_RETURN;
g_elModules;
g_modDir;
g_elSessionVar;

g_mapInfo;
g_volumeNames;

kopen4loadfrommod;

g_scriptModules;
g_scriptModulesNum;

G_ConFile;
G_DoGameStartup;
C_DefineSound;
C_DefineMusic;
C_DefineQuote;
C_DefineVolumeName;
C_DefineVolumeFlags;
C_UndefineVolume;
C_DefineSkillName;
C_UndefineSkill;
C_DefineLevelName;
C_UndefineLevel;
C_DefineProjectile;
C_DefineGameFuncName;
C_DefineGameType;
C_SetDefName;
C_SetCfgName;

SCRIPT_GetNumber;
SCRIPT_PutNumber;

actor;
g_camera;
ud;
g_player;
g_player_ps;
g_playerWeapon;
g_weaponOverridden;
WeaponPickupSprites;
g_tile;
SpriteProjectile;

g_noResetVars;
A_ResetVars;

g_dynTileList;
g_dynSoundList;

apStrings;

screenpeek;
hudweap;
g_mostConcurrentPlayers;
g_deleteQueueSize;
g_blimpSpawnItems;
g_scriptVersion;
g_frameRate;
g_currentMenu;
g_earthquakeTime;
g_moveThingsCount;
CheatKeys;
g_logoFlags;

luaJIT_BC_lunacon;
luaJIT_BC_con_lang;
luaJIT_BC_randgen;
luaJIT_BC_stat;
luaJIT_BC_bitar;
luaJIT_BC_control;
luaJIT_BC_bcarray;
luaJIT_BC_bcheck;
luaJIT_BC_xmath;
luaJIT_BC__defs_game;
luaJIT_BC_v;
luaJIT_BC_dump;
luaJIT_BC_dis_x86;
luaJIT_BC_dis_x64;
luaJIT_BC_lunasave;
luaJIT_BC_fs;

rand_jkiss_u32;
rand_jkiss_dbl;

A_IncurDamage;
G_CheckActivatorMotion;
A_Dodge;
A_MoveSpriteClipdist;
P_DoQuote;
P_SetGamePalette;
G_AddUserQuote;
G_ClearCameraView;
VM_DrawTileGeneric;
G_InitTimer;
G_GetTimeDate;
G_ToggleWallInterpolation;
G_StartTrack;
VM_CheckSquished2;
Menu_Change;

KB_ScanCodeToString;

A_CheckAnySoundPlaying;
S_CheckSoundPlaying;
S_StopEnvSound;
S_StopAllSounds;
S_ChangeSoundPitch;
S_GetMusicPosition;
S_SetMusicPosition;

minitext_;
G_DrawTXDigiNumZ;
G_PrintGameText;
G_ScreenText;
G_ScreenTextSize;
G_PrintYourTime;
G_PrintParTime;
G_PrintDesignerTime;
G_PrintBestTime;

G_UpdateScreenArea;
G_SaveMapState;
G_RestoreMapState;
G_FreeMapState;
};


code:
local ffi = require("ffi")
local C = ffi.C

local bcarray = require("bcarray")

local assert = assert
local error = error
local ipairs = ipairs
local type = type

local decl = assert(decl)  -- comes from above (_defs_game.lua or defs_m32.lua)

local ismapster32 = (C.LUNATIC_CLIENT == C.LUNATIC_CLIENT_MAPSTER32)

----------

decl[[
const int32_t qsetmode;
int32_t getclosestcol_lim(int32_t r, int32_t g, int32_t b, int32_t lastokcol);
char *palookup[256];  // MAXPALOOKUPS
uint8_t palette[768];
uint8_t *basepaltable[];

const char *getblendtab(int32_t blend);
void setblendtab(int32_t blend, const char *tab);

int32_t setpalookup(int32_t palnum, const uint8_t *shtab);
]]

if (ismapster32) then
    ffi.cdef[[
int32_t _getnumber16(const char *namestart, int32_t num, int32_t maxnumber, char sign, const char *(func)(int32_t));
const char *getstring_simple(const char *querystr, const char *defaultstr, int32_t maxlen, int32_t completion);

typedef const char *(*luamenufunc_t)(void);
void LM_Register(const char *name, luamenufunc_t funcptr, const char *description);
void LM_Clear(void);
]]
end

----------

-- The API table
local engine = {}

local shtab_t  -- forward-decl

local function cast_u8ptr(sth)
    return ffi.cast("uint8_t *", sth)
end

local shtab_methods = {
    -- Remap consecutive blocks of 16 color indices and return this new shade
    -- table.
    --
    -- <idxs16>: table with idxs16[0] .. idxs16[15] >= 0 and <= 15
    --  (i.e. 0-based indices of such 16-tuples)
    --
    -- For example, the table
    --  { [0]=0,1, 2,3, 5,4, 6,7, 8,13, 10,11, 12,9, 14,15 }
    -- TODO (...)
    remap16 = function(sht, idxs16)
        if (type(idxs16) ~= "table") then
            error("invalid argument #2: must be a table", 2)
        end

        for i=0,15 do
            local idx = idxs16[i]
            if (not (idx==nil or type(idx)=="number" and idx >= 0 and idx <= 15)) then
                error("invalid reordering table: elements must be numbers in [0 .. 15], or nil", 2)
            end
        end

        local newsht = shtab_t()
        for sh=0,31 do
            for i=0,15 do
                ffi.copy(cast_u8ptr(newsht[sh]) + 16*i,
                         cast_u8ptr(sht[sh]) + 16*(idxs16[i] or i), 16)
            end
        end
        return newsht
    end,
}

local function shtab_mt__index(sht, idx)
    local method = shtab_methods[idx]
    if (method) then
        return method
    end
end

local pal256_t = bcarray.new("uint8_t", 256, "color index 256-tuple")
local SIZEOF_PAL256 = ffi.sizeof(pal256_t)

-- The shade table type, effectively a bound-checked uint8_t [32][256]:
shtab_t = bcarray.new(pal256_t, 32, "shade table", nil, nil, { __index = shtab_mt__index })
local SIZEOF_SHTAB = ffi.sizeof(shtab_t)

local blendtab_t = bcarray.new(pal256_t, 256, "blending table")
local SIZEOF_BLENDTAB = ffi.sizeof(blendtab_t)

local RESERVEDPALS = 8  -- KEEPINSYNC build.h: assure that ours is >= theirs
engine.RESERVEDPALS = RESERVEDPALS

local MAXBLENDTABS = 256  -- KEEPINSYNC build.h

local function check_palidx(i)
    if (type(i) ~= "number" or not (i >= 0 and i <= 255-RESERVEDPALS)) then
        error("invalid argument #1: palette swap index must be in the range [0 .. "..255-RESERVEDPALS.."]", 3)
    end
end

local function check_blendidx(i)
    if (type(i) ~= "number" or not (i >= 0 and i <= MAXBLENDTABS-1)) then
        error("invalid argument #1: blending table index must be in the range [0 .. ".. MAXBLENDTABS-1 .."]", 3)
    end
end

local function err_uncommon_shade_table(ret)
    if (ret == -1) then
        error("loaded engine shade tables don't have 32 gradients of shade", 3)
    end
end

local function palookup_isdefault(palnum)  -- KEEPINSYNC engine.c
    return (C.palookup[palnum] == nil or (palnum ~= 0 and C.palookup[palnum] == C.palookup[0]))
end

function engine.shadetab()
    return shtab_t()
end

function engine.blendtab()
    return blendtab_t()
end

function engine.getshadetab(palidx)
    check_palidx(palidx)
    if (palookup_isdefault(palidx)) then
        return nil
    end

    local ret = C.setpalookup(palidx, nil)
    err_uncommon_shade_table(ret)

    local sht = shtab_t()
    ffi.copy(sht, C.palookup[palidx], SIZEOF_SHTAB)
    return sht
end

function engine.getblendtab(blendidx)
    check_blendidx(blendidx)

    local ptr = C.getblendtab(blendidx)
    if (ptr == nil) then
        return nil
    end

    local tab = blendtab_t()
    ffi.copy(tab, ptr, SIZEOF_BLENDTAB)
    return tab
end

local function check_first_time()
    if (not ismapster32 and C.g_elFirstTime == 0) then
        error("may be called only while LUNATIC_FIRST_TIME is true", 3)
    end
end

function engine.setshadetab(palidx, shtab)
    check_first_time()
    check_palidx(palidx)

    if (not ffi.istype(shtab_t, shtab)) then
        error("invalid argument #2: must be a shade table obtained by shadetab()", 2)
    end

    if (not ismapster32 and not palookup_isdefault(palidx)) then
        error("attempt to override already defined shade table", 2)
    end

    local ret = C.setpalookup(palidx, cast_u8ptr(shtab))
    err_uncommon_shade_table(ret)
end

function engine.setblendtab(blendidx, tab)
    check_first_time()
    check_blendidx(blendidx)

    if (not ffi.istype(blendtab_t, tab)) then
        error("invalid argument #2: must be a blending table obtained by blendtab()", 2)
    end

    if (not ismapster32 and C.getblendtab(blendidx) ~= nil) then
        error("attempt to override already defined blending table", 2)
    end

    C.setblendtab(blendidx, cast_u8ptr(tab))
end

local function check_colcomp(a)
    if (type(a) ~= "number" or not (a >= 0 and a < 256)) then
        error("color component must be in the range [0 .. 256)", 3)
    end
end

-- TODO: other base palettes?
function engine.getrgb(colidx)
    if (type(colidx) ~= "number" or not (colidx >= 0 and colidx <= 255)) then
        error("color index must be in the range [0 .. 255]", 2)
    end

    -- NOTE: In the game, palette[255*{0..2}] is set to 0 in
    -- G_LoadExtraPalettes() via G_Startup(). However, that's after Lua state
    -- initialization (i.e. when LUNATIC_FIRST_TIME would be true), and in the
    -- editor, it's never changed from the purple color. Therefore, I think
    -- it's more useful to always return the fully black color here.
    if (colidx == 255) then
        return 0, 0, 0
    end

    local rgbptr = C.palette + 3*colidx
    return rgbptr[0], rgbptr[1], rgbptr[2]
end

function engine.nearcolor(r, g, b, lastokcol)
    check_colcomp(r)
    check_colcomp(g)
    check_colcomp(b)

    if (lastokcol == nil) then
        lastokcol = 255
    elseif (type(lastokcol)~="number" or not (lastokcol >= 0 and lastokcol <= 255)) then
        error("invalid argument #4 <lastokcol>: must be in the range [0 .. 255]", 2)
    end

    return C.getclosestcol_lim(r, g, b, lastokcol)
end

---------- Mapster32-only functions ----------

if (ismapster32) then
    local io = require("io")
    local math = require("math")
    local string = require("string")

    ffi.cdef[[size_t fwrite(const void * restrict ptr, size_t size, size_t nmemb, void * restrict stream);]]

    local function validate_more_blendtabs(moreblends, kindname, gettabfunc)
        if (moreblends == nil) then
            return nil, nil
        end

        -- Additional blending tables: validate <moreblends> table.
        if (type(moreblends) ~= "table") then
            error("invalid argument #4: must be a table", 3)
        end

        local haveblend = { [0]=true }
        local blendnumtab, blendptrtab = {}, {}

        for i=1,#moreblends do
            local tmp = moreblends[i]
            local blendspec = (type(tmp) == "number") and { tmp, tmp } or tmp

            if (not (type(blendspec) == "table" and #blendspec == 2)) then
                error("invalid argument #4: must contain numbers or 2-tables", 3)
            end

            local blend1, blend2 = math.floor(blendspec[1]), math.floor(blendspec[2])

            if (not (type(blend1)=="number" and blend1 >= 1 and blend1 <= 255 and
                     type(blend2)=="number" and blend2 >= 1 and blend2 <= 255)) then
                error("invalid argument #4: "..kindname.." table numbers must be in [1 .. 255]", 3)
            end

            for bi=blend1,blend2 do
                if (haveblend[bi]) then
                    error("invalid argument #4: duplicate "..kindname.." table number "..bi, 3)
                end
                haveblend[bi] = true

                local ptr = gettabfunc(bi)
                if (ptr == nil) then
                    error("invalid argument #4: "..kindname.." table for number "..bi.." is void", 3)
                end

                blendnumtab[#blendnumtab+1] = bi
                blendptrtab[#blendptrtab+1] = ptr
            end
        end

        assert(#blendnumtab <= 255)
        return blendnumtab, blendptrtab
    end

    -- ok, errmsg, nummoreblends = engine.savePaletteDat(
    --  filename [, palnum [, blendnum [, moreblends [, lognumalphatabs]]]])
    function engine.savePaletteDat(filename, palnum, blendnum, moreblends, lognumalphatabs)
        local sht = engine.getshadetab(palnum or 0)
        local tab = engine.getblendtab(blendnum or 0)

        if (sht == nil) then
            return nil, "no shade table with number "..palnum
        elseif (tab == nil) then
            return nil, "no blending table with number "..blendnum
        end

        local blendnumtab, blendptrtab = validate_more_blendtabs(
            moreblends, "blending", C.getblendtab)

        if (lognumalphatabs ~= nil) then
            if (not (type(lognumalphatabs)=="number" and lognumalphatabs >= 1 and lognumalphatabs <= 7)) then
                error("invalid argument #5: must be a number in [1 .. 7]", 2)
            end
        end

        local f, errmsg = io.open(filename, "wb+")
        if (f == nil) then
            return nil, errmsg
        end

        local truncpal = pal256_t()
        ffi.copy(truncpal, C.palette, SIZEOF_PAL256)
        for i=0,255 do
            truncpal[i] = bit.rshift(truncpal[i], 2)
        end

        local n1 = C.fwrite(truncpal, 3, 256, f)
        f:write("\032\000")  -- int16_t numshades
        local n3 = C.fwrite(sht, 256, 32, f)
        local n4 = C.fwrite(tab, 256, 256, f)

        if (n1 ~= 256 or n3 ~= 32 or n4 ~= 256) then
            return nil, "failed writing classic PALETTE.DAT data"
        end

        if (blendnumtab ~= nil) then
            f:write("MoreBlendTab")
            f:write(string.char(#blendnumtab))

            for i=1,#blendnumtab do
                f:write(string.char(blendnumtab[i]))
                if (C.fwrite(blendptrtab[i], 256, 256, f) ~= 256) then
                    return nil, "failed writing additional blending table"
                end
            end

            if (lognumalphatabs ~= nil) then
                -- XXX: no checking whether these blending tables 1 to
                -- 1<<lognumalphatabs have been written.
                f:write(string.char(lognumalphatabs))
            end
        end

        f:close()

        return true, nil, (blendnumtab ~= nil) and #blendnumtab or 0
    end

    -- ok, errmsg, numlookups = engine.saveLookupDat(filename, lookups)
    function engine.saveLookupDat(filename, lookups)
        if (lookups == nil) then
            -- set to an invalid value, validate_more_blendtabs will error
            lookups = 0
        end

        local lookupnumtab, lookupptrtab = validate_more_blendtabs(
            lookups, "lookup", engine.getshadetab)

        local f, errmsg = io.open(filename, "wb+")
        if (f == nil) then
            return nil, errmsg
        end

        f:write(string.char(#lookupnumtab))

        for i=1,#lookupnumtab do
            f:write(string.char(lookupnumtab[i]))
            if (C.fwrite(lookupptrtab[i], 1, 256, f) ~= 256) then
                return nil, "failed writing lookup table"
            end
        end

        -- Write five base palettes
        for i=1,5 do
            local bpi = (i==3 or i==4) and 4+3-i or i

            local truncbasepal = pal256_t()
            ffi.copy(truncbasepal, C.basepaltable[bpi], SIZEOF_PAL256)
            for j=0,255 do
                truncbasepal[j] = bit.rshift(truncbasepal[j], 2)
            end

            if (C.fwrite(truncbasepal, 1, 768, f) ~= 768) then
                return nil, "failed writing base palette"
            end
        end

        f:close()

        return true, nil, #lookupnumtab
    end

    local hexmap = {
        [0] = 0, -14,  -- 0, 1: gray ramp
        14, 0,  -- 2, 3: skin color ramp
        0, 14,  -- 4, 5: blue ramp (second part first)
        14, 0,  -- 6, 7: nightvision yellow/green
        14,  -- 8: red first part...
        8,   -- 9: yellow (slightly more red than green)
        14, 0,  -- 10, 11: almost gray ramp, but with a slight red hue
        8,   -- 12: "dirty" orange
        0,   -- 13: ...red second part
        8,   -- 14: blue-purple-red
    }

    -- Setup base palette 1 (water) to contain one color for each consecutive
    -- 16-tuple (which I'm calling a 'hex' for brevity), except for the last
    -- one with the fullbrights.
    function engine.setupDebugBasePal()
        for i=0,14 do
            local ptr = C.basepaltable[1] + 3*(16*i)
            local src = C.basepaltable[0] + 3*(16*i) + 3*hexmap[i]
            local r, g, b = src[0], src[1], src[2]

            for j=0,15 do
                local dst = ptr + 3*j
                dst[0], dst[1], dst[2] = r, g, b
            end
        end
    end

    function engine.linearizeBasePal()
        for _, begi in ipairs{0, 32, 96, 160} do
            local ptr = C.basepaltable[0] + 3*begi
            local refcol = ptr + 3*31

            for i=0,30 do
                for c=0,2 do
                    ptr[3*i + c] = i*refcol[c]/31
                end
            end
        end

        for _, begi in ipairs{128, 144, 192, 208, 224} do
            local ptr = C.basepaltable[0] + 3*begi

            for i=0,3*15+2 do
                ptr[i] = 0
            end
        end
    end

    -- Interfaces to Mapster32's status bar menu

    local pcall = pcall

    function engine.clearMenu()
        C.LM_Clear()
    end

    function engine.registerMenuFunc(name, func, description)
        if (type(name) ~= "string") then
            error("invalid argument #1: must be a string", 2)
        end
        if (type(func) ~= "function") then
            error("invalid argument #2: must be a function", 2)
        end
        if (description~=nil and type(description)~="string") then
            error("invalid argument #3: must be nil or a string", 2)
        end

        local safefunc = function()
            local ok, errmsg = pcall(func)
            if (not ok) then
                return errmsg
            end
        end

        C.LM_Register(name, safefunc, description)
    end

    engine.GETNUMFLAG = {
        NEG_ALLOWED = 1,
        AUTOCOMPL_NAMES = 2,
        AUTOCOMPL_TAGLAB = 4,
        RET_M1_ON_CANCEL = 8,

        NEXTFREE = 16,
    }

    function engine.getnumber16(namestart, num, maxnumber, flags)
        if (C.qsetmode == 200) then
            error("getnumber16 must be called from 2D mode", 2)
        end
        if (type(namestart)~="string") then
            error("invalid argument #1: must be a string", 2)
        end

        return C._getnumber16(namestart, num, maxnumber, flags or 8, nil)  -- RET_M1_ON_CANCEL
    end

    function engine.getstring(querystr)
        if (type(querystr) ~= "string") then
            error("invalid argument #2: must be a string", 2)
        end
        local cstr = C.getstring_simple(querystr, nil, 0, 0)
        return cstr~=nil and ffi.string(cstr) or nil
    end
end

-- Done!
return engine


code:
-- MAPTEXT
-- Lunatic: routines for reading and writing map-text.

local ffi = require("ffi")
local ffiC = ffi.C

local assert = assert
local loadstring = loadstring
local pairs = pairs
local pcall = pcall
local print = print
local setfenv = setfenv
local tonumber = tonumber
local type = type

local readintostr = assert(string.readintostr)

local io = require("io")
local string = require("string")

ffi.cdef[[
int32_t (*saveboard_maptext)(const char *filename, const vec3_t *dapos, int16_t daang, int16_t dacursectnum);
int32_t (*loadboard_maptext)(int32_t fil, vec3_t *dapos, int16_t *daang, int16_t *dacursectnum);
]]

--== COMMON ==--

local sector_members = {
    -- Mandatory positional members first, [pos]=<name>.
    "ceilingz", "floorz",
    "ceilingpicnum", "floorpicnum",
    "ceilingshade", "floorshade";

    -- If other positional members are to be added, they must be optional
    -- for backwards compatibility.

    -- Optional key/value members next.
    B = { "ceilingbunch", -1 }, b = { "floorbunch", -1 },  -- default: -1
    F = "ceilingstat", f = "floorstat",  -- default: 0
    H = "ceilingheinum", h = "floorheinum",
    P = "ceilingpal", p = "floorpal",
    X = "ceilingxpanning", x = "floorxpanning",
    Y = "ceilingypanning", y = "floorypanning",

    v = "visibility",
    _ = "fogpal",
    o = "lotag", i = "hitag", e = { "extra", -1 }
}

-- Defines the order in which the members are written out. A space denotes that
-- a newline should appear in the output. KEEPINSYNC with sector_members.
local sector_ord = { mand="12 34 56 ", opt="Bb Ff Hh Pp Xx Yy v _ oie" }

-- KEEPINSYNC with sector_members.
local sector_default = ffi.new("const sectortype", { ceilingbunch=-1, floorbunch=-1, extra=-1 })

local wall_members = {
    -- mandatory
    "point2",  -- special: 0, 1 or 2 in map-text
    "x", "y",
    "nextwall",
    "picnum",
    "shade",
    "xrepeat", "yrepeat",
    "xpanning", "ypanning";

    -- optional
    f = "cstat",
    m = "overpicnum", b = "blend",
    p = "pal",
    w = { "upwall", -1 }, W = { "dnwall", -1 },
    o = "lotag", i = "hitag", e = { "extra", -1 }
}

local wall_ord = { mand="1 23 4 5 6 78 90 ", opt="f mb p wW oie" }
local wall_default = ffi.new("const walltype", { extra = -1, upwall=-1, dnwall=-1 })

local sprite_members = {
    -- mandatory
    "x", "y", "z",
    "ang",
    "sectnum",
    "picnum",
    "cstat",
    "shade",
    "xrepeat", "yrepeat",

    -- optional
    p = "pal",
    c = { "clipdist", 32 },
    b = "blend",
    x = "xoffset", y = "yoffset",
    s = "statnum",
    w = { "owner", -1 },
    X = "xvel", Y = "yvel", Z = "zvel",
    o = "lotag", i = "hitag", e = { "extra", -1 }
}

local sprite_ord = { mand="123 4 5 6 7 8 90 ", opt="p c b xy s w XYZ oie" }
local sprite_default = ffi.new("const spritetype", { clipdist=32, owner=-1, extra=-1 })

--== SAVING ==--

local function write_struct(f, struct, members, ord)
    -- Write mandatory members first.
    local str = ord.mand:gsub(".",
        function(s)
            local num = (s=="0") and 10 or tonumber(s)
            return (s==" ") and "\n" or (struct[members[num]]..",")
        end)
    f:write("{"..str)

    local havesth = false

    -- Write optional members next.
    str = ord.opt:gsub(".",
        function(s)
            if (s==" ") then
                local ohavesth = havesth
                havesth = false
                return ohavesth and "\n" or ""
            end

            local memb = members[s]
            local mname = (type(memb)=="table") and memb[1] or memb
            local mdefault = (type(memb)=="table") and memb[2] or 0

            local val = struct[mname]

            if (val~=mdefault) then
                havesth = true
                return s.."="..val..","
            else
                return ""
            end
        end)

    local neednl = (#str>0 and str:sub(-1)~="\n")
    f:write(str..(neednl and "\n" or "").."},\n")
end

-- common
local function check_bad_point2()
    local lastloopstart = 0

    for i=0,ffiC.numwalls-1 do
        local p2 = ffiC.wall[i].point2

        if (not (p2 == i+1 or (p2 ~= i and p2 == lastloopstart))) then
            -- If we hit this, the map is seriously corrupted!
            print(string.format("INTERNAL ERROR: wall[%d].point2=%d invalid", i, p2))
            return true
        end

        if (p2 ~= i+1) then
            lastloopstart = i+1
        end
    end
end

local function lastwallofsect(s)
    return ffiC.sector[s].wallptr + ffiC.sector[s].wallnum - 1
end

-- In map-text, instead of saving wall[].point2, we store whether a particular
-- wall is the last one in its loop instead: the on-disk wall[i].point2 is
--  * 2 if wall i is last of its sector (no need to save sector's .wallnum),
--  * 1 if wall i is last of its loop,
--  * 0 otherwise.
-- This function prepares saving to map-text by tweaking the wall[].point2
-- members in-place.
local function save_tweak_point2()
    -- Check first.
    if (check_bad_point2()) then
        return true
    end

    -- Do it for real.
    local lastloopstart = 0
    local cursect, curlastwall = 0, lastwallofsect(0)

    for i=0,ffiC.numwalls-1 do
        local wal = ffiC.wall[i]

        if (wal.point2 == i+1) then
            wal.point2 = 0
        else
            -- Wall i is last point in loop.

            if (i==curlastwall) then
                -- ... and also last wall of sector.
                cursect = cursect+1
                curlastwall = lastwallofsect(cursect)

                wal.point2 = 2
            else
                wal.point2 = 1
            end

            lastloopstart = i+1
        end
    end
end

-- Common: restore tweaked point2 members to actual wall indices.
-- If <alsosectorp> is true, also set sector's .wallptr and .wallnum members.
local function restore_point2(alsosectorp)
    local lastloopstart = 0
    local cursect, curfirstwall = 0, 0

    for i=0,ffiC.numwalls-1 do
        local wal = ffiC.wall[i]
        local islast = (wal.point2~=0)

        if (not islast) then
            wal.point2 = i+1
        else
            -- Wall i is last point in loop.

            if (alsosectorp and wal.point2 == 2) then
                -- ... and also last wall of sector.

                if (cursect==ffiC.MAXSECTORS) then
                    return true  -- Too many sectors.
                end

                ffiC.sector[cursect].wallptr = curfirstwall
                ffiC.sector[cursect].wallnum = i-curfirstwall+1
                cursect = cursect+1
                curfirstwall = i+1
            end

            wal.point2 = lastloopstart
            lastloopstart = i+1
        end
    end
end

local function saveboard_maptext(filename, pos, ang, cursectnum)
    assert(ffiC.numsectors > 0)

    -- First, temporarily tweak wall[].point2.
    if (save_tweak_point2()) then
        return -1
    end

    -- We open in binary mode so that newlines get written out as one byte even
    -- on Windows.
    local f, msg = io.open(ffi.string(filename), "wb")

    if (f == nil) then
        print(string.format("Couldn't open \"%s\" for writing: %s\n", filename, msg))
        restore_point2(false)
        return -1
    end

    -- Write header.
    f:write(string.format("--EDuke32 map\n"..
            "return {\n"..
            "version=10,\n\n"..

            "pos={%d,%d,%d},\n"..
            "sectnum=%d,\n"..
            "ang=%d,\n\n",

            pos.x, pos.y, pos.z,
            cursectnum,
            ang))

    -- Sectors.
    f:write("sector={\n")
    for i=0,ffiC.numsectors-1 do
        write_struct(f, ffiC.sector[i], sector_members, sector_ord)
    end
    f:write("},\n\n")

    -- Walls.
    f:write("wall={\n")
    for i=0,ffiC.numwalls-1 do
        write_struct(f, ffiC.wall[i], wall_members, wall_ord)
    end
    f:write("},\n\n")

    -- Sprites.
    f:write("sprite={\n")
    for i=0,ffiC.MAXSPRITES-1 do
        if (ffiC.sprite[i].statnum ~= ffiC.MAXSTATUS) then
            write_struct(f, ffiC.sprite[i], sprite_members, sprite_ord)
        end
    end
    f:write("},\n\n")

    f:write("}\n");

    -- Done.
    f:close()
    restore_point2(false)
    return 0
end

--== LOADING ==--

local function isnum(v)
    return (type(v)=="number")
end

local function istab(v)
    return (type(v)=="table")
end

-- Checks whether <tab> is a table all values of <tab> are of type <extype>.
local function allxtab(tab, extype)
    if (not istab(tab)) then
        return false
    end

    for _,val in pairs(tab) do
        if (type(val) ~= extype) then
            return false
        end
    end

    return true
end

-- Is table of all numbers?
local function allnumtab(tab) return allxtab(tab, "number") end
-- Is table of all tables?
local function alltabtab(tab) return allxtab(tab, "table") end

-- Is table of tables of all numbers? Additionally, each must contain exactly
-- as many mandatory positional entries as given by the <members> table.
local function tabofnumtabs(tab, members)
    for i=1,#tab do
        if (not allnumtab(tab[i])) then
            return false
        end

        local nummand = #members  -- number of mandatory entries
        if (#tab[i] ~= nummand) then
            return false
        end
    end

    return true
end

-- Read data from Lua table <stab> into C struct <cs>, using the struct
-- description <members>.
-- Returns true on error.
local function read_struct(cs, stab, members, defaults)
    -- Clear struct to default values.
    ffi.copy(cs, defaults, ffi.sizeof(defaults))

    -- Read mandatory positional members.
    for i=1,#members do
        cs[members[i]] = stab[i]
    end

    -- Read optional key/value members.
    for k,val in pairs(stab) do
        if (members[k]==nil) then
            -- No such member abbreviation for the given struct.
            return true
        end

        local memb = istab(members[k]) and members[k][1] or members[k]
        cs[memb] = val
    end
end

local RETERR = -4

local function loadboard_maptext(fil, posptr, angptr, cursectnumptr)
    -- Read the whole map-text as string.
    local str = readintostr(fil)

    if (str == nil) then
        return RETERR
    end

    -- Strip all one-line comments (currently, only the header).
    str = str:gsub("%-%-.-\n", "")

    --- Preliminary (pseudo-syntactical) validation ---

    -- Whitelist approach: map-text may only contain certain characters. This
    -- excludes various potentially 'bad' operations (such as calling a
    -- function) in one blow. Also, this assures (by exclusion) that the Lua
    -- code contains no long comments, strings, or function calls.
    if (not str:find("^[ A-Za-z_0-9{},%-\n=]+$")) then
        return RETERR-1
    end

    -- The map-text code must return a single table.
    if (not str:find("^return %b{}\n$")) then
        return RETERR-2
    end

    local func, errmsg = loadstring(str, "maptext")
    if (func == nil) then
        print("Error preloading map-text Lua code: "..errmsg)
        return RETERR-3
    end

    -- Completely empty the function's environment as an additional safety
    -- measure, then run the chunk protected! (XXX: currently a bit pointless
    -- because of the asserts below.)
    local ok, map = pcall(setfenv(func, {}))
    if (not ok) then
        print("Error executing map-text Lua code: "..map)
        return RETERR-4
    end

    assert(istab(map))
    -- OK, now 'map' contains the map data.

    --- Structural validation ---

    -- Check types.
    if (not isnum(map.version) or not allnumtab(map.pos) or #map.pos~=3 or
        not isnum(map.sectnum) or not isnum(map.ang))
    then
        return RETERR-5
    end

    if (not (map.version <= 10)) then
        return RETERR-6
    end

    local msector, mwall, msprite = map.sector, map.wall, map.sprite

    if (not alltabtab(msector) or not alltabtab(mwall) or not alltabtab(msprite)) then
        return RETERR-7
    end

    if (not tabofnumtabs(msector, sector_members) or
        not tabofnumtabs(mwall, wall_members) or
        not tabofnumtabs(msprite, sprite_members))
    then
        return RETERR-8
    end

    local numsectors, numwalls, numsprites = #msector, #mwall, #msprite
    local sector, wall, sprite = ffiC.sector, ffiC.wall, ffiC.sprite

    if (numsectors == 0 or numsectors > ffiC.MAXSECTORS or
        numwalls > ffiC.MAXWALLS or numsprites > ffiC.MAXSPRITES)
    then
        return RETERR-9
    end

    --- From here on, start filling out C structures. ---

    ffiC.numsectors = numsectors
    ffiC.numwalls = numwalls

    -- Header.
    posptr.x = map.pos[1]
    posptr.y = map.pos[2]
    posptr.z = map.pos[3]

    angptr[0] = map.ang
    cursectnumptr[0] = map.sectnum

    -- Sectors.
    for i=0,numsectors-1 do
        if (read_struct(sector[i], msector[i+1], sector_members, sector_default)) then
            return RETERR-10
        end
    end

    -- Walls.
    for i=0,numwalls-1 do
        if (read_struct(wall[i], mwall[i+1], wall_members, wall_default)) then
            return RETERR-11
        end
    end

    -- Sprites.
    for i=0,numsprites-1 do
        if (read_struct(sprite[i], msprite[i+1], sprite_members, sprite_default)) then
            return RETERR-12
        end
    end

    -- XXX: need to consistency-check much more here! Basically, all of
    -- astub.c's CheckMapCorruption() for corruption level >=4?
    -- See NOTNICE below.

    --- Tweakery: mostly setting dependent members. ---

    -- sector[]: .wallptr calculated from .wallnum.
    local numw = 0
    for i=0,numsectors-1 do
        assert(numw >= 0 and numw < numwalls)  -- NOTNICE, cheap check instead of real one.
        sector[i].wallptr = numw
        numw = numw + sector[i].wallnum
    end

    -- .point2 in {0, 1} --> wall index, sector[].wallptr/.wallnum
    if (restore_point2(true)) then
        return RETERR-13
    end

    -- Check .point2 at least.
    if (check_bad_point2()) then
        return RETERR-14
    end

    -- wall[]: .nextsector calculated by using engine's sectorofwall_noquick()
    for i=0,numwalls-1 do
        local nw = wall[i].nextwall

        if (nw >= 0) then
            assert(nw >= 0 and nw < numwalls)  -- NOTNICE
            wall[i].nextsector = ffiC.sectorofwall_noquick(nw)
        else
            wall[i].nextsector = -1
        end
    end

    -- All OK, return the number of sprites for further engine loading code.
    return numsprites
end

-- Register our Lua functions as callbacks from C.
ffiC.saveboard_maptext = saveboard_maptext
ffiC.loadboard_maptext = loadboard_maptext


code:
-- Virtual file system facilities for Lunatic

local ffi = require("ffi")
local C = ffi.C

local decl = require("lprivate").decl

local assert = assert
local error = error
local type = type

----------

decl[[
int32_t pathsearchmode;

typedef struct _CACHE1D_FIND_REC {
	char *name;
	int32_t type, source;
	struct _CACHE1D_FIND_REC *next, *prev, *usera, *userb;
} CACHE1D_FIND_REC;

void klistfree(CACHE1D_FIND_REC *rec);
CACHE1D_FIND_REC *klistpath(const char *path, const char *mask, int32_t type);
]]

-- The API table
local fs = {}

local CACHE1D = ffi.new[[
struct {
	static const int FIND_FILE = 1;
	static const int FIND_DIR = 2;
	static const int FIND_DRIVE = 4;
	static const int FIND_NOCURDIR = 8;

	static const int OPT_NOSTACK = 0x100;

	// the lower the number, the higher the priority
	static const int SOURCE_DRIVE = 0;
	static const int SOURCE_CURDIR = 1;
	static const int SOURCE_PATH = 2;  // + path stack depth
	static const int SOURCE_ZIP = 0x7ffffffe;
	static const int SOURCE_GRP = 0x7fffffff;
}
]]

-- files = fs.listpath(path, mask)
-- TODO: filter by 'source' (path, zip and/or grp)
-- TODO: directories too, so that one can list them recursively, for example
function fs.listpath(path, mask)
    if (type(path)~="string") then
        -- TODO: maybe also allow nil
        error("Invalid argument #1: must be a string", 2)
    end

    if (type(mask) ~= "string") then
        error("Invalid argument #2: must be a string", 2)
    end

    -- Normalization, for portability's sake

    if (path:find("\\")) then
        error("Invalid argument #1: must not contain backslashes", 2)
    end

    if (mask:find("[\\/]")) then
        error("Invalid argument #2: must not contain back or forward slashes", 2)
    end

    local opsm = C.pathsearchmode
    C.pathsearchmode = 0
    local rootrec = C.klistpath(path, mask, CACHE1D.FIND_FILE + CACHE1D.FIND_NOCURDIR)
    C.pathsearchmode = opsm

    if (rootrec == nil) then
        -- XXX: may have failed hard or just no matching files
        return {}
    end

    local files = {}

    local rec = rootrec
    while (rec ~= nil) do
        assert(rec.name ~= nil)
        files[#files+1] = ffi.string(rec.name)
        rec = rec.next
    end

    C.klistfree(rootrec)

    return files
end

return fs


code:
#!/bin/sh

if [ -z "$1" ]; then
    # S or G can be used to display SETGLOBALs or GETGLOBALs, respectively
    echo "Usage: $0 [S|G] <files.lua...>"
    exit 1;
fi

GS=

if [ "$1" = G ]; then
    GS=G
    shift
elif [ "$1" = S ]; then
    GS=S
    shift
fi

# Lua 5.2 required to parse ::label:: / goto generated by LunaCON.
LUAC=luac

for f in "$@"; do
    if [ ! -f "$f" ]; then
        echo "$f: No such file"
        exit 2
    fi
    echo "[$f]"
    # Strip LuaJIT specific syntax first. Run luac and extract interesting lines.
    sed -r -e "s/[0-9]+U?LL/0/g" "$f" | $LUAC -p -l - | grep "${GS}ETTABUP.*; _ENV " |
        # Reformat them.
        sed -e 's/.*\[\(.*\)\].*\([SG]ET\)TABUP.*"\(.*\)".*/\1: \2 \3/' |
        # Mark where the new module environment starts.
        sed -e 's/GET module/& ____________________/'
    echo
done