Subversion Repositories eduke32

Rev

Rev 4456 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
3868 helixhorne 1
Lunatic User Manual
2
===================
3
Helixhorned <contact: Duke4.net forums>
4
:max-width: 56em
5
:numbered:
6
:icons:
4032 helixhorne 7
:toc:
4153 helixhorne 8
:toclevels: 3
3868 helixhorne 9
 
4113 helixhorne 10
:language: lua
3868 helixhorne 11
 
3942 helixhorne 12
[red]*DRAFT DRAFT DRAFT*
13
 
14
Lunatic is in preview stage. Modifications or TCs may be started, but must not
15
be released. The interfaces (including constants, functions, methods *and
16
structure members*) described in this document may be assumed to not change
17
significantly until release, but *undocumented API may change without further
18
notice*.
19
 
20
[red]*DRAFT DRAFT DRAFT*
21
 
3868 helixhorne 22
Introduction
23
------------
24
 
25
Language
26
--------
27
:Lua51: http://www.lua.org/about.html
28
:Lua51Ref: http://www.lua.org/manual/5.1/
29
:PiL: http://www.lua.org/docs.html
30
 
31
:LuaJIT: http://luajit.org
32
:LuaJIText: http://luajit.org/extensions.html
33
 
34
The base language for writing Lunatic user code is {Lua51}[Lua 5.1].  It is
35
extensively documented in a {Lua51Ref}[Reference Manual], as well as described
36
more broadly and accessibly in the {PiL}[Programming in Lua] books.
37
// TODO: describe Lua a bit
38
 
39
Because Lunatic is implemented using {LuaJIT}[LuaJIT], a just-in-time compiler
40
for the Lua language, some {LuaJIText}[extensions] to the core language are
41
automatically available. They may be used if no compatibility with Rio Lua 5.1
3895 helixhorne 42
is desired.footnote:[Not all extensions from LuaJIT are available, since some
43
like the FFI are targeted at C programmers rather than scripting coders.]
3868 helixhorne 44
 
45
NOTE: The length operator (`#`) for table arguments should be taken to be
46
defined by the http://www.lua.org/manual/5.2/manual.html#3.4.6[stricter wording
47
of Lua 5.2].
48
 
49
 
50
Environment and Usage
51
---------------------
52
 
53
Lunatic aims to provide a _safe_ scripting environment for EDuke32. Thus, not
54
all of Lua's functionality is available in Lunatic, and some is slightly
55
altered to play well with being embedded into a game, or to prevent commonly
56
occurring mistakes.
57
 
58
.Differences from default Lua environment
3930 helixhorne 59
- Creating new variables in the global environment is forbidden.
60
- Referencing a non-existent variable (i.e. one that has value *nil*) is an
61
  error.
3868 helixhorne 62
 
63
EDuke32 can load multiple Lunatic _modules_ when starting up. This is always
3956 helixhorne 64
done after translating CON code to Lua and loading it. Such modules must reside
65
in files named `*.lua` (case-sensitive) and should be passed directly, without
66
any option letters, at the command line. Directory separators must be forward
3868 helixhorne 67
slashes.
68
 
4053 helixhorne 69
The command-line option `-Lopts=strict` enables errors on certain conditions
70
that may indicate problems in user Lua or CON code. Currently, strict mode
71
checks for
72
 
73
* Accesses to <<sprite,sprites>> not in the game world
74
* Indexing the tables returned by <<require,`require("DEFS")`>> and the like
75
  with nonexistent keys. This may indicate a missing file from a bundle
76
  belonging together.
77
 
3868 helixhorne 78
.Invocation example
79
====================
80
`eduke32 -nologo MYTC.CON -mx addition.con test.lua weapons/nuke.lua -v1 -l1`
81
====================
82
 
4109 helixhorne 83
If the OS environment variable `LUNATIC_TIMING_BASEFN` is defined, EDuke32 will
4202 helixhorne 84
write out aggregate timing results for actors and events in a comma-separated
3956 helixhorne 85
value format, obtained by suffixing the base name with ```.actors.csv`'' and
86
```.events.csv`''.
3868 helixhorne 87
 
3956 helixhorne 88
 
3868 helixhorne 89
Global Environment
90
------------------
91
 
92
When a Lua module is loaded, its global environment contains both selected
93
functions from core Lua, as well as Lunatic's own pre-defined variables.
94
These allow access and manipulation of EDuke32 engine and game data.
95
 
4036 helixhorne 96
[icon="din_w_explosive.png"]
3868 helixhorne 97
CAUTION: If an attempt is made to create a new variable in the global
98
environment or to assign any value to an existing variable, the behavior is
99
undefined.
100
 
4147 helixhorne 101
For convenience of debugging from the command line (using the `lua` OSD
102
command), the global environment contains a table `d` which is initially
103
empty. It should only be used to temporarily store values of interest in a
104
debugging session and should never be referenced from actual script code.
105
 
3868 helixhorne 106
Lua functions
107
~~~~~~~~~~~~~
108
 
109
The following base Lua functions are available in Lunatic's global environment:
110
 
111
`assert`, *`error`*, `ipairs`, `pairs`, `pcall`, *`print`*, *`module`*, `next`,
112
*`require`*, `select`, `tostring`, `tonumber`, `type`, `unpack`, `xpcall`.
113
 
114
The bold ones add functionality or behave slightly differently, described below.
115
Additionally, `printf` is provided for convenience.
116
 
3907 helixhorne 117
[[error]] *`error(message [, level])`*::
3868 helixhorne 118
In Lunatic, errors also print to the on-screen display (OSD) and are written to
119
the log (unless a maximum error count is exceeded). These also have a
120
_backtrace_ added. Additionally, errors not caught by a `pcall` result a
121
permanent message to appear on the screen, containing the source file name and
122
line number.
123
 
4570 helixhorne 124
*`print(str)`*::
125
Prints a single message to the OSD and the log. Color codes available in
3887 helixhorne 126
EDuke32 (e.g. `^10` for dark red) are interpreted. Overriding `tostring` has no
127
effect on Lunatic's `print` as it uses the initial, built-in `tostring`
128
function instead of looking it up in the global environment.
3868 helixhorne 129
 
130
*`printf(fmt, ...)`*::
131
Calls `print` with the result of `string.format(fmt, ...)`.
132
 
4035 helixhorne 133
[[modules]]
3868 helixhorne 134
Writing and using modules
135
~~~~~~~~~~~~~~~~~~~~~~~~~
136
 
137
In Lunatic, like in Lua, a _module_ is a conceptually a sort of package that
138
unites related bits of functionality. Language-wise, it is simply a Lua
139
table holding its contents, as described and motivated at length in
4105 helixhorne 140
_Programming in Lua_ (second edition).
3868 helixhorne 141
 
142
The ``creation'' and ``usage'' sides of the modularity concept are reflected in
143
two functions known from Lua 5.1, `module` and `require`. The former is a
144
convenient way of separating the _import_, potential _gamevar_, and main body
145
sections when writing a package. It is not required to use `module`, but it is
146
the only way to declare _game variables_, that is, variables that EDuke32
147
stores within savegames, recreating their values when they are loaded.
148
 
149
The other side of the coin, `require`, is also used like in Lua: ``including''
150
a named module is requested by passing its name to `require`. This searches for
151
a matching module, loading and running it if the request happens for the first
152
time.
153
 
4035 helixhorne 154
[[require]]
3868 helixhorne 155
==== The function `require(modname, ...)`
156
 
3870 helixhorne 157
Attempts to find a Lua or Lunatic module named `modname`. The name can refer to
158
a _built-in_ module, of which the following ones are allowed:
3868 helixhorne 159
 
160
* The http://bitop.luajit.org/[`bit`] module for bitwise operations
161
* `math`, `string` and `table`, base modules from Lua
162
* Lua's `os` module, containing a single function, `clock`. Like the
163
  <<timing_funcs,timing functions>>, it should only be used to profile bits of
164
  code.
3925 helixhorne 165
* Modules provided by Lunatic, which are described in <<ext_api,their own
3868 helixhorne 166
  section>>.
167
 
168
If `modname` does not designate a built-in module, Lunatic first replaces every
169
dot contained in it with a directory separator. Then, it looks for a file with
170
that base name suffixed with `.lua` in the EDuke32 search path (virtual file
171
system, GRP, ZIP). Using directory separators directly is not allowed.
172
 
3893 helixhorne 173
The loaded module is protected so that write accesses to its table yield
3895 helixhorne 174
errors. Unlike in Lua, our `require` does not return *true* when a module is
175
requested that has not yet finished loading (that is, the inclusion chain
3868 helixhorne 176
contains a loop). Instead, an error is raised.
177
 
3895 helixhorne 178
Lunatic's `require` allows passing additional arguments to the module to load.
179
On the module side, they can be obtained by examining the vararg expression
3925 helixhorne 180
``++\...++'' at file scope. Given a definition of `args` as `{...}`, its first
181
element `args[1]` would contain `modname` and the following entries the values
182
passed in addition to `require`. This feature is useful for parametrizing a
183
module: for example, the module could provide a way alter the starting tile
184
number of an actor it defines.
3868 helixhorne 185
 
3925 helixhorne 186
Issuing `require` for some special names listed below has a predefined meaning
187
that cannot be overridden by the user.
3868 helixhorne 188
 
3925 helixhorne 189
* `CON.DEFS`: returns a table mapping labels ++define++d from CON to their
3956 helixhorne 190
values. Values pre-defined by the system are not included.
3895 helixhorne 191
 
3925 helixhorne 192
* `CON.ACTION`: returns a table mapping labels of ++action++s defined from CON
193
  to immutable <<con_action,`con.action`>> objects.
194
 
195
* `CON.MOVE`: returns a table mapping labels of ++move++s defined from CON
196
  to immutable <<con_move,`con.move`>> objects.
197
 
198
* `CON.AI`: returns a table mapping labels of ++ai++s defined from CON
199
  to immutable <<con_ai,`con.ai`>> objects.
200
 
201
* `end_gamevars`: used to mark the end of a gamevar block, described below.
202
 
203
 
3868 helixhorne 204
==== The `module()` function
205
 
206
Initiates a _module_ environment by creating a new empty table and setting it
4054 helixhorne 207
as the global environment of the chunk. Subsequently creating global variables
208
will place them into this ``hidden'' table. Assuming no subsequent *`return`*
209
is placed at file scope, this table will be the one obtained by a `require` for
210
the module at the client side.
3868 helixhorne 211
 
4113 helixhorne 212
[source]
4054 helixhorne 213
.Example file using using `module`
214
----------
215
-- Import section: cache everything the module needs into locals
216
local print = print
217
local gameactor = gameactor
218
local MYDEFS = require("MyEnemyDefs", 1200)  -- see next example
219
 
220
-- After this, the global environment will be swept clean!
221
module(...)
222
 
223
-- Our enemy at last
224
gameactor{ MYDEFS.tilenum, strength=MYDEFS.strength,
225
    function(aci)
226
        print("My tilenum is "..sprite[aci].picnum.." and I "
227
              ..(MYDEFS.canfly and "can" or "can't").." fly")
228
    end
229
}
230
----------
231
 
232
Unlike Lua 5.1, our `module` takes neither a name argument nor ``option''
233
varargs. A Lunatic file may have at most one call to `module`, which (if there
234
is one) *must* be called at file scope.
235
 
236
If the Lua file doesn't need to register any game variables, it is also
237
possible to return its table directly instead of using `module`. However, due
238
to the way modules are loaded, a trailing *`return`* statement must be wrapped
239
in a *`do`*...*`end`* block, like this:
240
 
4113 helixhorne 241
.Example module `MyEnemyDefs.lua` explicitly returning a table
242
[source]
4054 helixhorne 243
----------
244
local args = { ... }
245
do return {
246
   tilenum = args[1] or 1000,
247
   strength = 100,
248
   canfly = true,
249
}
250
end
251
----------
252
 
3868 helixhorne 253
===== Game variables
254
 
3893 helixhorne 255
Lunatic has a special mechanism to mark variables that represent persistent
256
state and whose values should be stored in savegames. If such variables are
257
desired, they must be initialized between the `module` call in a Lua file and a
3895 helixhorne 258
closing `require("end_gamevars")`.footnote:[The reason that the initialization
259
has to happen between the `module` and the `require('end_gamevars')` is that on
260
savegame loading, gamevars are restored from the latter.] These variables may
261
also be *`local`*.
3868 helixhorne 262
 
3895 helixhorne 263
Game variables may take on only values of types that Lunatic knows how to
264
serialize into savegames. These are the following:
3868 helixhorne 265
 
3908 helixhorne 266
* Booleans, numbers, and strings, collectively called the _basic types_
4202 helixhorne 267
* Custom Lunatic types that are labeled _serializable_ in their documentation
3908 helixhorne 268
* Tables, but with the following restrictions on their contents:
269
** A table key may only be of basic type.
4202 helixhorne 270
** A table value may be (a reference to) any serializable object, but tables
3908 helixhorne 271
    or Lunatic objects that are so referenced *must* have originated in the
3925 helixhorne 272
    gamevar section of the same module. Beyond that, there are no restrictions
273
    on the table topology.
3868 helixhorne 274
 
4036 helixhorne 275
[icon="din_w_collapse.png"]
4202 helixhorne 276
CAUTION: If a gamevar contains a value that is not serializable at any point
3925 helixhorne 277
in the execution, the behavior is undefined. Note that in particular, gamevars
278
are not allowed to take on the value *nil*.
3895 helixhorne 279
 
280
// TODO: example?
281
 
3868 helixhorne 282
// TODO: the rest
283
 
3956 helixhorne 284
[[gv]]
285
The `gv` variable
3868 helixhorne 286
~~~~~~~~~~~~~~~~~~~
287
 
288
Some constants, global C variables, and miscellaneous functions and structures
289
are accessible via the global `gv` variable.
290
 
291
Constants
292
^^^^^^^^^
293
`gv.MAXSECTORS`, `gv.MAXWALLS`, `gv.MAXSPRITES`::
294
The hard engine limits on the number of sectors, walls, and sprites. These
295
constants *must* be used instead of any literal numeric values because they
296
can change depending on how EDuke32 was configured and built.
297
 
4198 helixhorne 298
`gv.CEILING`, `gv.FLOOR`, `gv.BOTH_CF`::
299
Constants permissible to the <<sectorsofbunch_1,`sectorsofbunch`>> iterator.
300
 
3868 helixhorne 301
//////////
302
`gv.MAXSTATUS`, `gv.MAXTILES`, `gv.MAXSPRITESONSCREEN`::
303
TODO
304
 
4198 helixhorne 305
`gv.MAXBUNCHES`::
3868 helixhorne 306
TODO
307
//////////
308
 
309
`gv.CLIPMASK0`::
310
A clipping (collision detection) mask specifying to consider only _blocking_
311
walls and sprites.
312
 
313
`gv.CLIPMASK1`::
314
A clipping (collision detection) mask specifying to consider only _hitscan
3942 helixhorne 315
sensitive_ walls and sprites. The set bits of `CLIPMASK1` and `CLIPMASK0` are
4202 helixhorne 316
disjoint.
3868 helixhorne 317
 
4032 helixhorne 318
[[gv_REND]] `gv.REND`::
319
A mapping of names to values representing rendering modes: `CLASSIC`,
320
`POLYMOST`, `POLYMER`.
321
 
3868 helixhorne 322
// Game-side
3930 helixhorne 323
[[gv_GTICSPERSEC]] `gv.GTICSPERSEC`::
4202 helixhorne 324
The number of times in a second each actor executes its code and updates its
3930 helixhorne 325
position (``game tics'').
326
 
4032 helixhorne 327
[[gv_GET]] `gv.GET`::
328
A mapping of names to inventory indices: `STEROIDS`, `SHIELD`, `SCUBA`,
329
`HOLODUKE`, `JETPACK`, `DUMMY1`, `ACCESS`, `HEATS`, `DUMMY2`, `FIRSTAID`,
330
`BOOTS`.
3868 helixhorne 331
 
4032 helixhorne 332
`gv.GET_MAX`::
333
The maximum permissible inventory index plus one.
3868 helixhorne 334
 
4032 helixhorne 335
[[gv_WEAPON]] `gv.WEAPON`::
336
A mapping of names to weapon indices: `KNEE`, `PISTOL`, `SHOTGUN`, `CHAINGUN`,
337
`RPG`, `HANDBOMB`, `SHRINKER`, `DEVISTATOR`, `TRIPBOMB`, `FREEZE`,
338
`HANDREMOTE`, `GROW`. Note that ```DEVISTATOR`'' is misspelled.
3930 helixhorne 339
 
4032 helixhorne 340
`gv.MAX_WEAPONS`::
341
The maximum permissible weapon index plus one.
342
 
3868 helixhorne 343
//////////
344
`gv.MAXPLAYERS`::
345
TODO
346
//////////
347
 
4262 helixhorne 348
`gv.LUNATIC_CLIENT`::
349
 
350
A constant indicating which program Lua is embedded into. It can be compared
351
for (in)equality with:
352
+
353
* `gv.LUNATIC_CLIENT_EDUKE32`
354
* `gv.LUNATIC_CLIENT_MAPSTER32`
355
+
356
(Mapster32 supports a subset of Lunatic that is not documented and subject to
357
change at any time.)
358
 
3868 helixhorne 359
Variables
360
^^^^^^^^^
361
 
3925 helixhorne 362
`gv.numsectors` (read-only)::
363
The total number of sectors in the currently loaded map.
364
 
365
`gv.numwalls` (read-only)::
366
The total number of walls in the currently loaded map.
367
 
368
[[totalclock]] `gv.totalclock` (read-only)::
3868 helixhorne 369
The current value of the engine timer that increments at a rate of 120 per
370
second under default settings. (Thus, one game tic corresponds to four
371
`totalclock` increments.) When staying within one ``mode'' such as in-menu or
372
in-game, it is guaranteed to not decrease. However, going from one mode to
373
another may produce discontinuities.
374
 
3930 helixhorne 375
`gv.gametic` (read-only)::
376
The number of <<gv_GTICSPERSEC,game tics>> that have elapsed since starting the
377
current level. This value is guaranteed to not decrease during a game, and is
378
restored from savegames.
379
 
3868 helixhorne 380
`gv.screenpeek` (read-only)::
381
The player index of the player from whose position the scene is being displayed.
382
 
3930 helixhorne 383
`gv.rendmode` (read-only)::
384
The current rendering mode as a value that can be compared against those in
385
<<gv_REND,`gv.REND`>>.
386
 
3868 helixhorne 387
`gv.hudweap`::
388
A structure containing information about the currently displayed HUD weapon.
389
Contains the following members, which are set from C before entering
390
`EVENT_DISPLAYWEAPONS`: `cur`, `count`, `gunposx`, `gunposy`, `lookhalfang`,
391
`lookhoriz`, `shade`.
392
// TODO: describe
393
 
3887 helixhorne 394
`gv.cam`::
395
A structure that, prior to entering `EVENT_DISPLAYROOMS`, is populated with the
396
position and orientation of the ``camera'' from which the scene would be drawn.
397
Contains the following members: `pos`, `dist`, `clock`, `ang`, `horiz`, `sect`.
398
// TODO: describe
399
 
4032 helixhorne 400
// TODO: g_logoFlags?
3868 helixhorne 401
 
4032 helixhorne 402
[[gv_RETURN]] `gv.RETURN`::
403
A special variable that is used by the game to pass specific values to game
404
events, or to examine values passed back from events and act upon them
4035 helixhorne 405
accordingly. Refer to <<Appendix_event_RETURN,Appendix B>> for a list of how the various
4032 helixhorne 406
events interpret this variable.
407
 
3868 helixhorne 408
Functions
409
^^^^^^^^^
3925 helixhorne 410
 
4053 helixhorne 411
`gv.getangle(x, y)`::
412
Returns an approximation of the angle between the line segments (0,0)->(1,0)
413
and (0,0)->(`x`,`y`) in BUILD angle units in the range [0 .. 2047].
414
 
4217 helixhorne 415
[[krand]] `gv.krand()`::
3925 helixhorne 416
Returns one value from the global engine-side pseudo-random number generator
3930 helixhorne 417
in the integer range [0{nbsp}..{nbsp}65535].
3925 helixhorne 418
 
4217 helixhorne 419
[[timing_funcs]] `gv.getticks()`, `gv.gethiticks()`::
3868 helixhorne 420
Each of these functions return a number that increases at a rate of 1 per
421
millisecond. Their only intended application is to profile bits of code; they
422
should not be used to control the game world. The two functions differ in their
423
precision: `getticks()` always returns integral values, while the result of
3935 helixhorne 424
`gethiticks()` also has an unspecified precision in the fractional part. (It
3868 helixhorne 425
can be expected to give a time precision of at least one microsecond.)
426
 
427
`gv.doQuake(gametics [, snd])`::
428
Requests from the game to perform the ``quake'' effect that shakes the screen
429
etc. for the next `gametics` game tics. If a sound index `snd` is passed, also
430
start playing that sound.
431
// TODO: Play sound how? ("globalsound")
432
 
433
`gv.currentEpisode()`::
4260 helixhorne 434
Returns the one-based number of the episode currently being played.
435
 
3868 helixhorne 436
`gv.currentLevel()`::
4260 helixhorne 437
Returns the one-based number of the level currently being played.
3868 helixhorne 438
 
3925 helixhorne 439
[[Lunatic_structures]]
3868 helixhorne 440
Lunatic structures
441
~~~~~~~~~~~~~~~~~~
442
 
443
The primary means of effecting game state in Lunatic is via _composite
444
variables_ defined in the global environment. These provide direct, but
445
restricted, access to C _structure arrays_ of the EDuke32 engine or game.
446
 
4036 helixhorne 447
[icon="din_w_toxic.png"]
3868 helixhorne 448
CAUTION: If an attempt is made to access any composite variable outside of
449
event or actor code, the behavior is undefined.
450
 
451
Composite variables can be used in various ways. All of them allow indexing
452
with an integer value from `0` to some maximum (sometimes the size of the array
453
minus one, but occasionally less). For example, the code snippet
4113 helixhorne 454
[source]
3868 helixhorne 455
----------
456
local sec = sector[0]
457
----------
458
gets a _reference_ to the first sector of the loaded map into the local `sec`.
459
This reference can then be used to both read and write its members.
460
 
461
Various structures also provide _methods_ in Lunatic to modify their state,
462
usable with Lua's `v:func(args...)` syntax. Building on the previous example,
4113 helixhorne 463
[source]
3868 helixhorne 464
----------
465
local cz = sec:ceilingzat(wall[sec.wallptr])
466
----------
467
would get into `cz` the ceiling z position at the first sector's first
468
wall-point.
469
 
470
Finally, some composite variables offer _static data_, which can contain
471
functions or tables of constants. These are accessed using the dot notation on
472
the composite variable, *not* its constituents. For instance, the following can
473
be used to change the sector number of the sprite with index `i` manually:
4113 helixhorne 474
[source]
3868 helixhorne 475
----------
476
sprite.changesect(i, sectnum)
477
----------
478
 
479
 
480
Type of structure members
481
^^^^^^^^^^^^^^^^^^^^^^^^^
482
 
483
In the following, some structure members will be annotated with their _integer
484
type_, for example _`i16`_ or _`u8`_. The letter _`i`_ denotes a _signed_
485
integer whereas a _`u`_ designates an _unsigned_ one. The number following that
486
letter indicates the _bit width_ of that integer.
487
 
488
.Representable values
489
* A member of signed integer type and bit width _B_ can contain any whole
490
number from --2^_B_--1^ to 2^_B_--1^--1. +
491
 
492
* A member of unsigned integer type and bit width _B_ can contain any whole
493
number from 0 to 2^_B_^--1.
494
 
3895 helixhorne 495
[[int_assignment]]
3868 helixhorne 496
.Assignment
3956 helixhorne 497
1. If an assignment to a member having signed integer type is made, the
498
   ``right-hand side'' value must be a number in the closed interval
499
   [--2^31^ .. 2^31^--1].
3868 helixhorne 500
 
3956 helixhorne 501
2. If an assignment to a member having unsigned integer type and bit width _B_
502
   is made, the ``right-hand side'' value must be in the closed interval
503
   [--2^31^ .. 2^31^--1] if _B_ is less than 32, or in [0 .. 2^32^--1] otherwise.
3868 helixhorne 504
 
3956 helixhorne 505
3. If the appropriate requirements hold, an assignment from a Lua number to a
506
   member having integer type begins by discarding the fractional part
507
   (``truncation'').  Otherwise, the behavior is undefined. +
3868 helixhorne 508
 
3956 helixhorne 509
4. If the truncated value is outside the range of representable values for the
510
   corresponding integer type of bit width _B_, the final value is obtained by
511
   successively adding or subtracting 2^B^, until the value falls inside that
512
   range.
3868 helixhorne 513
 
3906 helixhorne 514
//////////
515
NOTE to self: this is stricter than C99 (which has first truncation, then range
516
check). Also, it may be tempting to assign 0x80000000 to an int32_t to mean
517
INT32_MIN, but this is wrong because it's out of range.
518
Also see:
519
http://lua-users.org/lists/lua-l/2011-09/msg00534.html
520
//////////
521
 
3868 helixhorne 522
.Examples
523
1. Assignments to _`u8`_ member `visibility`
524
* `sec.visibility=3.94159` results the member to contain the integer `3`
525
* `sec.visibility=1/0` is undefined (attempt to assign an infinity)
526
* `sec.visibility=-1` results the member to contain the integer `255`
527
 
528
2. Assignments to _`i16`_ member `lotag`
529
* `sec.lotag=32768` results the member to contain `-32768`
530
* `sec.lotag=2^32` is undefined
531
 
4044 helixhorne 532
[[bit_fields]]
3868 helixhorne 533
Bit fields
534
^^^^^^^^^^
535
 
536
Some structures contain members that represent a collection of _flags_, for
537
example `sprite[].cstat` or `actor[].flags`. These flags can be toggled by
538
setting or clearing their respective _bits_ (integer numbers that are powers of
539
two).
540
 
541
For convenience, Lunatic provides alternative names for some of these members,
542
together with methods to examine or modify any number of bits of such a member
543
in one expression.  Whenever there is such an alternative name available, it is
544
declared as having type _`bitfield`_ in the listings of the structure members.
545
 
546
===== methods of the _`bitfield`_ type
547
 
548
`bf:set(bits)`::
549
_Sets_ (toggles to an ``on'' state in a boolean sense) those bits of `bf`
550
that are set in `bits`.
551
 
552
`bf:clear(bits)`::
553
_Clears_ (toggles to an ``off'' state in a boolean sense) those bits of `bf`
554
that are set in `bits`.
555
 
556
`bf:flip(bits)`::
3906 helixhorne 557
_Flips_ those bits of `bf` that are set in `bits`, that is, reverses their
3868 helixhorne 558
boolean state.
559
 
560
`bf:test(bits)`::
561
Returns a boolean that indicates whether `bf` has *any* of the bits set in
562
`bits` set.
563
 
3930 helixhorne 564
`bf:mask(bits)`::
565
Returns a number containing the bits of `bf` bitwise ANDed with those in
566
`bits`.
567
 
3868 helixhorne 568
.Examples
569
==========
570
After the lines setting sprite `i` to 33% translucent and blocking,
4113 helixhorne 571
[source]
3868 helixhorne 572
----------
573
local CS = sprite.CSTAT
574
local spr = sprite[i]
575
spr.cstat = CS.TRANS1 + CS.BLOCK
576
----------
577
one could proceed as follows for the sake of example:
578
 
4224 helixhorne 579
[source]
580
----------
581
spr.cstatbits:set(CS.TRANS2)  -- make the sprite 66% translucent now
582
spr.cstatbits:flip(CS.BLOCK + CS.HITSCAN)  -- make it hitscan-sensitive and non-blocking
583
local isflipped = spr.cstatbits:test(CS.FLIP_BITMASK)  -- is it x- or y-flipped? (no)
584
----------
3868 helixhorne 585
==========
586
 
3956 helixhorne 587
Engine-side composites
588
^^^^^^^^^^^^^^^^^^^^^^
3868 helixhorne 589
 
590
The composite variables described in this subsection provide access to
591
engine-side structures. The first three, `sector`, `wall`, and `sprite`,
592
are part of a BUILD map saved to disk. The other ones only exist when
593
running the game.
594
 
595
===== `sector`
596
Accessible from `0` to `gv.numsectors-1`. Each element has the following
597
members:
598
 
599
`wallptr`, `wallnum` (read-only)::
600
The index of the sector's first wall and the number of walls in the sector,
601
respectively.
602
 
603
_`u8`_ `visibility`::
4437 helixhorne 604
Determines the amount of distance fading. The sector `visibility` member is
605
biased: linear visibility is determined from it by adding 16 and taking the
606
result mod 16. This linear visibility's interpretation is that larger values
607
correspond to a steeper ``darkening'' (or fogging) attenuation with
608
distance. Linear visibility 0 -- corresponding to `sector[].visibility` of 240
609
-- means no attenuation with distance.
3868 helixhorne 610
 
4456 helixhorne 611
_`u8`_ `fogpal`::
612
In the OpenGL modes that don't use per-pixel shade table lookups, setting
613
`fogpal` to a non-zero value overrides the fog color of the sector to that of
614
the corresponding pal number. These are either expected to have been defined
615
using DEF tokens `fogpal` or `makepalookup`, or created by EDuke32 at startup.
616
 
3868 helixhorne 617
_`i16`_ `lotag`, `hitag`, `extra`::
618
General-purpose ``tags'' provided for game programming. They may be used by
3956 helixhorne 619
various EDuke32 sector effects, so it is not recommended to use them in
3868 helixhorne 620
scripting code.
621
 
622
In addition to the members described above, each sector has two sets of members
623
for its ceiling and floor. A sector reference can be indexed with the strings
624
`ceiling` or `floor` to get references to the respective ``parts'', or one can
625
access the consituent members by prefixing `ceiling` or `floor` to the base
626
member names given below.
627
 
628
.Different ways of accessing the same member
629
==========
630
After the code lines
4113 helixhorne 631
[source]
3868 helixhorne 632
----------
633
local sec = sector[0]
634
local ceil = sec.ceiling
635
----------
636
the following expressions all denote the same location, both if read or written
637
to: `sec.ceilingheinum`, `ceil.heinum`, `sector[0].ceiling.heinum`,
638
`sector[0].ceilingheinum`.
639
==========
640
 
641
In the following, `cf` will stand for a ceiling or floor reference, while `sec`
642
will label a sector reference.
643
 
644
`cf.picnum` (read-only)::
645
The tile number of the ceiling or floor.
646
 
3895 helixhorne 647
[[cf_stat]] _`u16`_ `cf.stat`, {nbsp} _`bitfield`_ `cf.statbits`::
4202 helixhorne 648
A bit field holding various flags about how the ceiling or floor should be
3868 helixhorne 649
displayed, how collision detection should be handled, etc.
650
The <<sector_STAT,`sector.STAT`>>
651
object should be used to obtain the values for applicable flags.
652
 
653
_`i16`_ `cf.heinum`::
3930 helixhorne 654
If `cf.stat` has bit `sector.STAT.SLOPE` set, the tangent of the slope angle,
3868 helixhorne 655
multiplied by 4096.  Positive values make the ceiling or floor slope towards
656
the floor, negative ones slope upward.
657
 
3895 helixhorne 658
[[cf_z]] _`i32`_ `cf.z`::
3868 helixhorne 659
The BUILD z coordinate (scaled by 16 compared to the x and y directions) of the
660
pivoting line of the ceiling or floor.
661
 
662
`cf.bunch` (read-only)::
663
The ``bunch'' number of the ceiling or floor used for True Room over Room. One
664
bunch comprises _N_ ceilings and _M_ floors (_N_ &ge; 1, _M_ &ge; 1) such that
665
each set covers the same planar, connected area.
666
 
667
_`i8`_ `cf.shade`::
668
The shade of the ceiling or floor. Larger values mean a more darker appearance.
669
 
670
_`u8`_ `cf.pal`::
671
The ``palette swap'' index of the ceiling or floor.
672
 
673
_`u8`_ `cf.xpanning`, `cf.ypanning`::
674
The panning values of the ceiling or floor. One full cycle is covered by values
675
from `0` to `255`.
676
 
4207 helixhorne 677
===== ceiling-or-floor methods
678
 
679
`cf:set_picnum(tilenum)`::
680
Set the tile number of the ceiling-or-floor `cf`.
681
 
3868 helixhorne 682
===== `sector` methods
683
 
4195 helixhorne 684
`sec:set_ceilingpicnum(tilenum)`, {nbsp} `sec:set_floorpicnum(tilenum)`::
4207 helixhorne 685
Set the tile number of the ceiling or the floor.
3868 helixhorne 686
 
4195 helixhorne 687
[[sec_cfz_at]] `sec:ceilingzat(pos)`, {nbsp} `sec:floorzat(pos)`::
3868 helixhorne 688
Return the z coordinate of sector `sec`'s ceiling or floor at position `pos`,
689
which can be anything indexable with the strings `x` and `y`.
690
 
4053 helixhorne 691
`sec:zrangeat(pos, walldist, clipmask)` -> `hit`::
3868 helixhorne 692
 
4053 helixhorne 693
Given a starting point `pos` assumed to be contained in the sector, calculate
694
the z coordinates of the objects that would be first hit by a quadratic,
695
floor-aligned sprite pointing parallel to the grid and having side length
696
`2*walldist`, when travelling in a straight line up- and downwards.
697
+
698
The argument `clipmask` is a number specifying which objects should be checked
699
for collision: its least significant 16 bits are bitwise-ANDed with
700
`wall[].cstat` values, while the high 16 bits are ANDed with
701
`sprite[].cstat`. Whenever the so masked values are non-zero, the objects are
702
considered for collision.
703
+
704
The method returns an immutable structure `hit`, containing the sub-structures
705
`c` and `f` (for movement upwards and downwards, respectively) with the
706
following members:
707
+
708
* `spritep`: a boolean signifying whether a sprite was hit
709
* `num`: if `spritep` is true, the index of the hit sprite, otherwise the index
710
  of the hit ceiling/floor's sector
711
* `z`: the z coordinate of where the sprite would end up on collision
712
 
3868 helixhorne 713
===== `sector` static data
714
 
715
[[sector_STAT]] `sector.STAT`::
3925 helixhorne 716
Provides a mapping of symbolic names to values applicable to
717
<<cf_stat,`cf.stat`>>.  These name single bits:
3868 helixhorne 718
`PARALLAX`, `SLOPE`, `SWAPXY`, `SMOOSH`, `FLIPX`, `FLIPY`, `RELATIVE`, `MASK`,
719
`TRANS1`, `TRANS2`, `BLOCK`, `HITSCAN`, while the following denote _bit masks_:
720
`FLIP_BITMASK`, `ORIENT_BITMASK`, `TRANS_BITMASK`.
721
 
3910 helixhorne 722
[[sector_UPDATE_FLAGS]] `sector.UPDATE_FLAGS`::
3956 helixhorne 723
Contains flags permissible to <<updatesector,`updatesector`>> and other sector
724
updating functions. `BREADTH`, `Z`.
3910 helixhorne 725
 
3868 helixhorne 726
'''
3895 helixhorne 727
[[wall]]
3868 helixhorne 728
===== `wall`
729
Accessible from `0` to `gv.numwalls-1`. Each element has the following
730
members:
731
 
4032 helixhorne 732
_`i32`_ `x`, `y`::
3868 helixhorne 733
The 2D coordinates or this wall point. Should not be set directly.
734
 
3895 helixhorne 735
`z` (read-only)::
736
Always yields `0`. The primary purpose of this field is to make wall references
737
permissible as arguments to <<vector_types,`xmath` vector>> operations.
738
 
3868 helixhorne 739
`point2` (read-only)::
740
The index of the second wall point.
741
 
3910 helixhorne 742
[[nextwall]] `nextwall`, `nextsector` (read-only)::
3868 helixhorne 743
If the wall is ``white'', these members equal `-1`. For ``red'' walls, they
744
contain the wall and sector indices (respectively) of the wall on the other side.
745
 
746
`upwall`, `dnwall` (read-only)::
747
For walls constrained by TROR extension, the upper and lower neighbor walls,
748
respectively. Any of them may be `-1`, meaning that the wall is not attached to
749
a neighbor in this direction.
750
 
3895 helixhorne 751
[[wall_cstat]] _`u16`_ `cstat`, {nbsp} _`bitfield`_ `cstatbits`::
4202 helixhorne 752
A bit field holding various flags about how the wall should be
3868 helixhorne 753
displayed, how collision detection should be handled, etc.
754
The <<wall_CSTAT,`wall.CSTAT`>>
755
object should be used to obtain the values for applicable flags.
756
 
757
[[wall_picnum]]`picnum` (read-only)::
758
The tile number of the non-masked portion of the wall. If
759
`wall.CSTAT.BOTTOMSWAP` is set on this wall's `.cstat`, it is only displayed in
760
the upper portion. (The lower portion takes it from this wall's `.nextwall`
761
then; this will be labeled _use-other-bottom_ in the following.)
762
 
763
`overpicnum` (read-only)::
764
The tile number of the masked portion of the wall, i.e. that which is drawn if
765
this wall's `.cstat` has bit `wall.CSTAT.MASK` or `wall.CSTAT.ONEWAY` set.
766
 
767
_`i8`_ `shade` (<<wall_picnum,_use-other-bottom_>>)::
3925 helixhorne 768
The shade of the wall for both non-masked and masked portions. Larger values
769
mean a more darker appearance.
3868 helixhorne 770
 
771
_`u8`_ `pal` (<<wall_picnum,_use-other-bottom_>>)::
772
The ``palette swap'' index of the wall.
773
 
774
_`u8`_ `xrepeat`, `yrepeat`::
775
Values that are proportional to the number of times that the wall's texture
776
repeats in each direction per given wall length/height. A value of `8` renders
777
64 texels across a length of 1024 x/y map units or a height of 16384 z units.
778
 
779
_`u8`_ `xpanning`, `ypanning` (<<wall_picnum,_use-other-bottom_>>)::
780
The panning values of both masked and non-masked portions of the wall. One full
781
cycle is covered by values from `0` to `255`.
782
 
783
_`i16`_ `lotag`, `hitag`, `extra`::
784
General-purpose ``tags'' provided for game programming. They may be used by
785
various EDuke32 effects internally, so it is advised to do some research before
786
claiming them for oneself.
787
 
788
===== `wall` methods
789
 
790
`wal:set_picnum(tilenum)`, `wal:set_overpicnum(tilenum)`::
791
Set the tile number of the wall or its masked portion.
792
 
793
===== `wall` static functions
794
 
795
`wall.dragto(i, pos)`::
796
Set the position of the point of the wall with index `i` to `pos`, which can be
797
anything indexable with `x` and `y`. This function is the preferred way of
798
changing wall coordinates, since it takes care to reposition dependent wall
799
points, too.
800
 
801
===== `wall` static data
802
 
803
[[wall_CSTAT]] `wall.CSTAT`::
3925 helixhorne 804
Provides a mapping of symbolic names to values applicable to
805
<<wall_cstat,`wall[i].cstat`>>.  These name single bits:
3868 helixhorne 806
`BLOCK`, `BOTTOMSWAP`, `ALIGNBOTTOM`, `FLIPX`, `MASK`, `ONEWAY`, `HITSCAN`,
807
`TRANS1`, `FLIPY`, `TRANS2`,
808
while the following denote _bit masks_:
809
`FLIP_BITMASK`, `TRANS_BITMASK`.
810
 
811
'''
3925 helixhorne 812
[[sprite]]
3868 helixhorne 813
===== `sprite`
814
 
815
The `sprite` composite is accessible with indices from `0` to
816
`gv.MAXSPRITES-1`, but accesses to sprites that do not exist in the game world
817
have no meaning. Each element has the following members:
818
 
4032 helixhorne 819
_`i32`_ `x`, `y`, `z`::
3868 helixhorne 820
The BUILD coordinates of the sprite. It is not advisable to set these directly.
821
 
822
//////////
823
_`i16`_ `ang`::
824
TODO (make set_ang() out of that which always ANDs with 2047?)
825
//////////
826
 
3895 helixhorne 827
[[sprite_cstat]] _`u16`_ `cstat`, {nbsp} _`bitfield`_ `cstatbits`::
4202 helixhorne 828
A bit field holding various flags about how the sprite should be
3868 helixhorne 829
displayed, how collision detection should be handled, etc.
830
The <<sprite_CSTAT,`sprite.CSTAT`>>
831
object should be used to obtain the values for applicable flags.
832
 
833
`picnum` (read-only)::
4053 helixhorne 834
The tile number of the sprite, also used to determine which actor code is run
3868 helixhorne 835
if this sprite has a `statnum` of `actor.STAT.ACTOR`.
836
 
837
_`i8`_ `shade`::
838
The shade of the sprite. This may not be the shade that this sprite is
839
ultimately drawn with, though.
840
 
841
_`u8`_ `pal`::
842
The ``palette swap'' index of the sprite. This may not be the palette swap that
843
this sprite is ultimately drawn with, though.
844
 
4337 helixhorne 845
_`u8`_ `blend`::
846
The blending table index of the sprite. See
847
<<blending_table_interfaces,Blending table interfaces>> for more details.
848
 
3868 helixhorne 849
_`u8`_ `clipdist`::
4437 helixhorne 850
In the engine, this member is used in the `clipmove()` function: it controls
851
the distance at which another moving object is considered to be in collision
852
with this *view-aligned* and *stationary* sprite.footnote:[The `clipmove()`
853
function is called for the moving object. The stationary one is a candidate for
854
collision out of potentially many.] It does *not* control the inverse case: the
855
distance at which the moving object is considered in collision with the
856
stationary one is determined by the `walldist` argument to `clipmove()`. +
857
More precisely, it designates half the side-length of the bounding square
858
divided by 4. Thus, a value of `255` keeps moving objects away from this one at
859
a max-norm distance footnote:[The max-norm distance between points
860
_p_~1~=(x~1~, y~1~) and _p_~2~=(x~2~, y~2~) is defined as max(abs(x~2~ --
861
x~1~), abs(y~2~ -- y~1~)).]  of at least 1020 BUILD x/y units.
862
+
863
In the Duke3D game code, it is also used to determine said `walldist` argument
864
for certain `clipmove()` calls, i.e. to control (1/8^th^ of) the base side
865
length of the moving sprite's clipping cuboid: this is the case for
866
+
867
* user actors declared as `actor.FLAGS.enemy` or `actor.FLAGS.enemystayput` in
868
  the Lua `gameactor` call (or which were provided the corresponsing flags for
869
  CON's `useractor`) having an `xrepeat` less than or equal to 60, or
870
* non-enemies that are either not projectiles, or projectiles that have a
871
  certain projectile bit set (*TODO*; these are not yet documented.)
872
 
4217 helixhorne 873
// ^ XXX: clipshapes? Also, clipdist is effective for moving sprites (A_MoveSprite()).
3868 helixhorne 874
 
875
_`u8`_ `xrepeat`, `yrepeat`::
876
The size of the sprite in each dimension. For wall- and floor- aligned sprites,
877
a value of `64` means a width of 16 x/y BUILD units or a height of 256 z BUILD
878
units per texel.
879
 
880
`sectnum` (read-only)::
881
The index of the sector that this sprite is currently contained in.
882
 
3887 helixhorne 883
[[sprite_statnum]] `statnum` (read-only)::
3868 helixhorne 884
The current _status number_ of this sprite. Applicable values are contained in
3887 helixhorne 885
<<actor_STAT,`actor.STAT`>>.
3868 helixhorne 886
 
887
`owner` (read-only)::
888
The index of the sprite from which this sprite was spawned. If this sprite is
889
not a ``child'' of another one, then `owner` is the index of this sprite itself.
890
//Occasionally, game effects may use this member for their particular purposes,
891
//so research is recommended before claiming it for oneself.
892
 
893
_`i16`_ `xvel`, `zvel`::
4053 helixhorne 894
For actors and other moving sprite kinds, the horizontal and vertical
3930 helixhorne 895
components of the current velocity. See the description of
896
<<con_move,`con.move`>> for more details.
3868 helixhorne 897
 
4230 helixhorne 898
_`i16`_ `yvel` (read-only)::
899
A member used for different purposes by Duke3D. Setting it is only allowed
900
through the `set_yvel` method.
3868 helixhorne 901
 
902
_`i16`_ `lotag`, `hitag`, `extra`::
903
General-purpose ``tags'' provided for game programming. They may be used by
904
hard-coded actors internally, so it is advised to do some research before
905
claiming them for oneself.
906
 
907
===== `sprite` methods
908
 
909
`spr:set_picnum(tilenum)`::
4230 helixhorne 910
Sets the tile number of sprite `spr` to `tilenum`. It is disallowed to issue
911
`set_picnum` on an `APLAYER` sprite or change the tile number of a sprite to
912
`APLAYER`.
3868 helixhorne 913
 
4230 helixhorne 914
`spr:set_yvel(yvel)`::
915
Sets the `yvel` member of sprite `spr` to `yvel`. It is disallowed to issue
916
`set_yvel` on an `APLAYER` sprite. Further restrictions are reserved.
917
 
4053 helixhorne 918
`spr:getheightofs()` -> `height`, `offset`::
919
Returns the `height` and z `offset` of sprite `spr` in BUILD z units. Adding the
920
`offset` to `spr.z` yields the z coordinate at the bottom of the
921
sprite. Subtracting from that the `height` results the z coordinate at its
3942 helixhorne 922
top. However, the per-tile z offset is not taken into account.
3930 helixhorne 923
 
3956 helixhorne 924
`spr:setpos(pos [, newsect])`::
925
Unconditionally sets the position of `spr` to `pos`, which can be anything
926
indexable with `x`, `y` and `z`. Thus, in effect a shorthand for
927
+
4113 helixhorne 928
[source]
3956 helixhorne 929
----------
930
spr.x, spr.y, spr.z = pos.x, pos.y, pos.z
931
----------
932
+
933
If `newsect` is passed, additionally calls `spr:changesect(newsect)`. +
934
Returns `spr`.
935
 
936
`spr:changesect(sectnum)`::
937
An alternative way to call
938
+<<sprite_changesect,sprite.changesect>>(_index_of_spr_, sectnum)+, where
939
_`index_of_spr`_ is the sprite index corresponding to `spr`.  This method is
940
provided for convenience, but may be slower than the static function
941
`changesect`.
942
 
943
`spr:updatesect([flags])`::
944
An alternative way to call
945
+<<sprite_updatesect,sprite.updatesect>>(_index_of_spr_, flags)+, where
946
_`index_of_spr`_ is the sprite index corresponding to `spr`.  This method is
947
provided for convenience, but may be slower than the static function
948
`updatesect`.
949
 
4047 helixhorne 950
===== `sprite` iterators
3956 helixhorne 951
 
4047 helixhorne 952
+*for* i *in* sprite.all()+::
953
Iterates over all sprites currently in the game world.
954
 
3887 helixhorne 955
===== `sprite` static functions
956
 
957
`sprite.changestat(i, statnum)`::
958
Allows to manually change the status number of the sprite with index `i` to
3956 helixhorne 959
`statnum`. If `i` is an invalid sprite index or the index of a sprite not in
960
the game world, or `statnum` is an invalid status number, an error is thrown.
3887 helixhorne 961
 
3956 helixhorne 962
[[sprite_changesect]] `sprite.changesect(i, sectnum)`::
963
Allows to manually change the sector number of the sprite with index `i` to
964
`sectnum`. If `i` is an invalid sprite index or the index of a sprite not in
965
the game world, or `sectnum` is an invalid sector index, an error is thrown.
966
 
967
[[sprite_updatesect]] `sprite.updatesect(i [, flags])`::
968
Updates the sector number of the sprite with index `i`, in effect setting
969
`sprite[i]`'s sector number to the result of
970
+
4113 helixhorne 971
[source]
3956 helixhorne 972
----------
973
updatesector(sprite[i].pos, sprite[i].sectnum, flags)
974
----------
975
+
976
If the <<updatesector,`updatesector`>> call returns `-1`, the sprite's sector
977
number remains unchanged. +
978
Returns the result of the `updatesector` call.
979
 
3868 helixhorne 980
===== `sprite` overridden operators
981
 
3895 helixhorne 982
[[sprite_power]] `spr^zofs`::
983
Returns an <<vector_types,`xmath.ivec3`>> object that contains the position of
984
this sprite, diminished by `zofs` in the z direction. Because in BUILD, z
985
coordinates increase toward the floor, the `^` can be thought of as ``raise the
986
sprite by `zofs` units''.
3868 helixhorne 987
 
988
===== `sprite` static data
989
 
990
[[sprite_CSTAT]] `sprite.CSTAT`::
3925 helixhorne 991
Provides a mapping of symbolic names to values applicable to
992
<<sprite_cstat,`sprite[i].cstat`>>.  These name single bits:
3868 helixhorne 993
`BLOCK`, `TRANS1`, `XFLIP`, `YFLIP`, `ALIGNWALL`, `ALIGNFLOOR`, `ONESIDE`,
4206 helixhorne 994
`CENTER`, `HITSCAN`, `TRANS2`, `INVISIBLE`,
3868 helixhorne 995
while the following denote _bit masks_: `ALIGN_BITMASK`, `TRANS_BITMASK`.
996
 
997
===== `spriteext`
998
 
3942 helixhorne 999
Accessible with the same indices and with the same restrictions as
1000
<<sprite,`sprite`>>.
3868 helixhorne 1001
 
3956 helixhorne 1002
//`angoff`::
1003
//The BUILD angle that is added to that of a drawn voxel or model.
3868 helixhorne 1004
 
3956 helixhorne 1005
// XXX: needs better wording to express this: tspr->ang + spriteext[tspr->owner].angoff
3942 helixhorne 1006
 
3868 helixhorne 1007
 
3956 helixhorne 1008
Game-side composites
1009
^^^^^^^^^^^^^^^^^^^^
1010
 
4217 helixhorne 1011
[[actor]]
3887 helixhorne 1012
===== `actor`
3868 helixhorne 1013
 
3925 helixhorne 1014
The `actor` composite holds various run-time data about a sprite.  Like
1015
<<sprite,`sprite`>>, it is accessible with indices from `0` to
1016
`gv.MAXSPRITES-1`, but accesses to actors that do not exist in the game world
3956 helixhorne 1017
have no meaning. Each element has the following members:
3925 helixhorne 1018
 
3942 helixhorne 1019
_`u16`_ `movflags`, {nbsp} _`bitfield`_ `movflagsbits`::
1020
The actor's current <<actor_MOVFLAGS,movement flags>>.
1021
 
4217 helixhorne 1022
[[actor_methods]]
3887 helixhorne 1023
===== `actor` methods
3868 helixhorne 1024
 
3930 helixhorne 1025
The following methods query or set properties related to
1026
<<actions_moves_ais,actor behavior>>.
1027
 
3925 helixhorne 1028
`a:set_action(act)`::
1029
Sets the action of actor `a` to `act`, which may be either an object returned
1030
by <<con_action,`con.action`>> or a number 0 or 1. Resets the actor's _action
1031
count_ and current frame offset to 0.
1032
 
1033
`a:has_action(act)`::
1034
Returns a boolean of whether the current action of actor `a` is `act`, which
1035
can be any value permissible to `a:set_action()`. For composite action objects,
1036
equality is established using its hidden ID, not the public members. Refer to
1037
<<actions_moves_ais,Actions&#44; moves and AIs>> for further details.
1038
 
1039
`a:set_action_delay()`::
1040
Overrides the <<action_delay,`delay`>> of the current action of actor `a`
1041
without changing the action's ID.
1042
 
1043
`a:set_count(count)`::
1044
Sets the actor's _execution count_ to `count`. The execution count of an actor
1045
increments after each time its <<gameactor,callback function>> has run once.
1046
 
1047
`a:get_count()`::
1048
Returns the actor's execution count.
1049
 
1050
`a:reset_acount()`::
1051
Resets the _action count_ of the actor to 0. The action count is incremented on
1052
each frame advance of the actor's current action. Also see the
1053
<<action_delay,`delay`>> argument to `con.action`.
1054
 
1055
`a:get_acount()`::
1056
Returns the actor's action count.
1057
 
1058
`a:set_move(mov [, movflags])`::
1059
Sets the move of actor `a` to `mov`, which may be either an object returned by
1060
<<con_move,`con.move`>> or a number 0 or 1. See the <<gameactor_move,`move`>>
1061
argument to `gameactor` for further details. If <<actor_MOVFLAGS,`movflags`>>
1062
is omitted, it defaults to 0.
1063
+
1064
The `set_move` method resets the actor's execution count. Also, if `moveflags`
1065
has bit <<actor_MOVFLAGS,`actor.MOVFLAGS.randomangle`>> set and the actor is
1066
not an enemy or a live enemy, its `sprite[].ang` value is set to a ``random''
1067
value using <<krand,`gv.krand`>>.
1068
 
1069
`a:has_move(mov)`::
1070
Returns a boolean of whether the current move of actor `a` is `mov`, which can
1071
be any value permissible to `a:set_move()`. Like with `a:has_action()`,
1072
equality is established using the move ID in case a composite one is passed.
1073
 
1074
`a:set_hvel(hvel)`::
1075
Overrides the <<con_move,horizontal velocity>> of the actor's current move to
1076
`hvel` without changing its ID.
1077
 
1078
`a:set_vvel(vvel)`::
1079
Overrides the <<con_move,vertical velocity>> of the actor's current move to
1080
`vvel` without changing its ID.
1081
 
1082
`a:set_ai(ai)`::
1083
Sets the AI of actor `a` to `ai`, which must be an object returned by
1084
<<con_ai,`con.ai`>>. In addition to setting the current AI ID of the actor,
1085
`a:set_ai(ai)` is equivalent to the sequence
1086
+
4113 helixhorne 1087
[source]
3925 helixhorne 1088
----------
1089
a:set_action(ai.act)
1090
a:set_move(ai.mov, ai.movflags)
1091
----------
1092
 
1093
`a:has_ai(ai)`::
1094
Returns a boolean of whether the current AI of actor `a` is `ai`.
1095
 
3930 helixhorne 1096
Various methods query whether the last movement step of the actor made it
1097
collide with another object, or allow getting this object's index then.
1098
 
1099
`a:checkhit()`::
1100
Returns a boolean of whether the actor hit any object in the world, including
1101
ceilings and floors.
1102
// TODO: This needs verification:
1103
// Staying motionless on the ground is considered as ``hitting'' it, too.
1104
 
1105
`a:checkbump()`::
1106
Returns a boolean of whether the actor bumped into another actor or a wall.
1107
 
1108
`a:hitwall()`::
1109
If the actor hit a wall with the last movement, returns that wall's
1110
index. Otherwise, returns *nil*.
1111
 
1112
`a:hitsprite()`::
1113
If the actor hit a sprite with the last movement, returns that sprite's
1114
index. Otherwise, returns *nil*.
1115
 
3925 helixhorne 1116
// TODO: set_picnum, set_owner?
1117
 
4217 helixhorne 1118
[[actor_static_functions]]
3925 helixhorne 1119
===== `actor` static functions
1120
 
1121
`actor.fall(i)`::
1122
Causes the actor with index `i` to fall in a ``hard-coded'', not further
1123
specified fashion.
1124
 
4217 helixhorne 1125
[[actor_static_data]]
3887 helixhorne 1126
===== `actor` static data
3868 helixhorne 1127
 
3887 helixhorne 1128
[[actor_STAT]]
1129
`actor.STAT`::
1130
Provides a mapping of symbolic names to values applicable as sprite
1131
<<sprite_statnum,status numbers>>. +
1132
`DEFAULT`, `ACTOR`, `ZOMBIEACTOR`, `EFFECTOR`, `PROJECTILE`, `MISC`,
1133
`STANDABLE`, `LOCATOR`, `ACTIVATOR`, `TRANSPORT`, `PLAYER`, `FX`, `FALLER`,
1134
`DUMMYPLAYER`, `LIGHT`.
1135
 
1136
[[actor_FLAGS]] `actor.FLAGS`::
1137
Contains symbolic names of values applicable to <<gameactor,`gameactor`>>'s
1138
`flags` input argument, most of which are described there. +
1139
`SHADOW`, `NVG`, `NOSHADE`, `NOPAL`, `NOEVENTS`, `NOLIGHT`,
4371 helixhorne 1140
`USEACTIVATOR`, `NOCLIP`, `SMOOTHMOVE`, `NOTELEPORT`, `NODAMAGEPUSH`.
3887 helixhorne 1141
 
1142
//`BADGUY`,
1143
 
3925 helixhorne 1144
[[actor_MOVFLAGS]] `actor.MOVFLAGS`::
1145
Contains symbolic names of values applicable <<gameactor,`gameactor`>>'s
1146
`movflags` input argument, `actor[]:set_move()`, and the like. +
4378 helixhorne 1147
* `faceplayer`, `geth`, `getv`, `randomangle`, `faceplayerslow`, `spin`,
1148
  `faceplayersmart`, `fleeenemy`, `seekplayer`, `furthestdir`,
1149
  `dodgebullet`, all naming single bits
1150
* `jumptoplayer_bits`: the bitwise-OR of *two* bits, one of which is `faceplayer`
1151
* `jumptoplayer_only`: the same as `jumptoplayer_bits`, but without the `faceplayer` bit set
1152
* `jumptoplayer`: [red]*deprecated*
3925 helixhorne 1153
 
3956 helixhorne 1154
'''
4217 helixhorne 1155
[[player]]
3887 helixhorne 1156
===== `player`
1157
 
3942 helixhorne 1158
Accessible with the index 0 and any nonnegative `pli` index passed to a
1159
<<gameactor,game actor>> or event callback function.
1160
 
3956 helixhorne 1161
.Arrays with named elements
1162
The structures obtained by indexing `player` contain arrays whose elements may
1163
be referred to either by index of by a particular name. Thus, the array can be
1164
thought to be overlaid with a structure containing as many members as the array
1165
has elements, all having the element's type.
1166
 
1167
Currently, there are with two kinds of names: weapon names and inventory
3969 helixhorne 1168
names. They will be marked using notation like this:
3956 helixhorne 1169
 
1170
==========
1171
_`i16`_ +ammo_amount[_weapon_]+
1172
 
1173
means that the structure member `ammo_amount` is an array with named elements,
1174
themselves being of signed 16-bit integer type. The array can be indexed with
1175
valid weapon numbers, or weapon names. In the following (constructed) example,
1176
the first player's current pistol ammo count is set to that of the currently
1177
selected weapon:
4113 helixhorne 1178
[source]
3956 helixhorne 1179
----------
1180
local ps = player[0]
1181
ps.ammo_amount.PISTOL = ps.ammo_amount[ps.curr_weapon]
1182
----------
1183
==========
1184
 
4032 helixhorne 1185
The inventory names are the same as the keys of <<gv_GET,`gv.GET`>>, those for
1186
the weapons coincide with the keys of <<gv_WEAPON,`gv.WEAPON`>>.
3956 helixhorne 1187
 
4184 helixhorne 1188
.Boolean members
3956 helixhorne 1189
 
4184 helixhorne 1190
Player members marked _`bool`_ in the listing below yield Lua true or false on
1191
reading and expect one of these values when assigned to.
1192
 
1193
 
4217 helixhorne 1194
[[player_members]]
4184 helixhorne 1195
===== `player` members
1196
 
3942 helixhorne 1197
<<vector_types,_`xmath.ivec3`_>> `vel`::
1198
The vector of the player's current velocity, accounted each time a player's
1199
input is processed. The x and y components are in BUILD x/y units per game tic,
1200
scaled by 2^14^. The z component is given in BUILD z units per game
1201
tic. Processing a player's input and other EDuke32 game code may change `vel`
1202
``behind a user's back'' in a further unspecified fashion.
1203
 
1204
_`i32`_ `runspeed`::
1205
The factor, scaled by 2^16^, with which the player's current horizontal
1206
velocity is multiplied before calculating its new position. On various
3956 helixhorne 1207
occasions, the ultimate scaled factor is the difference of `runspeed` and at
1208
most 8192.
3942 helixhorne 1209
 
3969 helixhorne 1210
`curr_weapon`::
3956 helixhorne 1211
The index of the player's currently selected weapon.
3942 helixhorne 1212
 
4217 helixhorne 1213
_`u16`_ `gotweapon`, {nbsp} _`bitfield`_ `gotweaponbits`::
1214
 
1215
Indicates whether each weapon is in the possession of the player. If bit 2^`w`^
1216
is set for a <<gv_WEAPON,weapon index>> `w`, the player has got this
1217
weapon. The player methods `has_weapon`, `give_weapon` and `take_weapon` can be
1218
used to query or modify this member.
1219
 
4184 helixhorne 1220
_`i16`_ +ammo_amount[_weapon_]+::
3956 helixhorne 1221
 
4184 helixhorne 1222
The current ammo amount for each weapon.
1223
 
1224
_`i16`_ +max_ammo_amount[_weapon_]+::
1225
 
1226
The maximum ammo amount for each weapon. Because `ammo_amount` amount and
1227
`max_ammo_amount` are writable without restriction, it is the user's
1228
responsibility to make sure that the former never exceeds the latter and that
1229
both are non-negative at all times. Otherwise, erratic behavior may ensue.
1230
 
1231
_`bool`_ `jetpack_on`, {nbsp} `scuba_on`, {nbsp} `heat_on`::
1232
 
1233
Whether the player currently has the jetpack, scuba gear, or night vision
1234
goggles activated, respectively.
1235
 
4437 helixhorne 1236
:wiki_predef_gamevars: http://wiki.eduke32.com/wiki/Category:Pre-defined_gamevars
4184 helixhorne 1237
 
4437 helixhorne 1238
_`weapondata_t`_ +weapon[_weapon_]+::
1239
 
1240
A struct containing information about the behavior each of weapon for this
4448 helixhorne 1241
player. In CON, these are available as separate gamevars named
4437 helixhorne 1242
{wiki_predef_gamevars}[`WEAPONx_*`] for weapon indices `x` and members `*`.
1243
 
1244
[float]
1245
==== _`weapondata_t`_ members
1246
 
1247
In Lunatic, some members of the _`weapondata_t`_ structure are checked when
1248
being assigned to and issue an error on attempting to set them to an invalid
1249
value. All these members assume *zero* to mean the neutral/no-op value (instead
1250
of --1, as would seem more logical), and consequently, Lunatic only allows
1251
values greater or equal zero to be assigned to them.
1252
 
1253
// TODO: workslike + flags
1254
 
1255
* `clip`
1256
* `reload`
1257
* `firedelay`
1258
* `totaltime`
1259
* `holddelay`
1260
* `flags`
1261
* `shoots` (checked)
1262
* `spawntime`
1263
* `spawn` (checked)
1264
* `shotsperburst`
1265
* `initialsound` (checked)
1266
* `firesound` (checked)
1267
* `sound2time`  [gray]#// This is a time number, not a sound number#
1268
* `sound2sound` (checked)
1269
* `reloadsound1` (checked)
1270
* `reloadsound2` (checked)
1271
* `selectsound` (checked)
1272
* `flashcolor`
1273
 
4217 helixhorne 1274
[[player_methods]]
3893 helixhorne 1275
===== `player` methods
1276
 
4217 helixhorne 1277
`ps:has_weapon(widx)`::
1278
Returns a boolean of whether player `ps` has got the weapon with index `widx`.
1279
 
1280
`ps:give_weapon(widx)`::
1281
Adds the weapon given by index `widx` to player `ps`'s possession without
1282
changing the currently held one.
1283
 
1284
`ps:take_weapon(widx)`::
1285
Removes the weapon given by index `widx` from player `ps`'s possession. If an
1286
attempt is made to remove the currently selected weapon, the behavior is
1287
undefined.
1288
 
3893 helixhorne 1289
`ps:fadecol(fadefrac, r, g, b [, speed [, prio]])`::
1290
 
1291
Initiates a tinting that linearly fades over time and is blended with the whole
1292
screen contents whenever player `ps`'s view is displayed.footnote:[The behavior
1293
is unspecified should more than one player's view be displayed at one time.]
1294
The first argument `fadefrac` specifies the starting blending coefficient; `r`,
1295
`g` and `b` specify the intensities of the red, green and blue color
1296
components, respectively.
1297
+
1298
Both `fadefrac` and the component intensities are first clamped to the range
3969 helixhorne 1299
[0.0 .. 1.0]. The resulting values are interpreted as a proportion, 0.0 meaning
3893 helixhorne 1300
no blending/no color and 1.0 meaning full blending/full
1301
color.footnote:[Currently, for implementation reasons, a value of 1.0 results
1302
in only _almost_ full blending or presence of the specified color component.]
1303
+
1304
The fourth, optional argument `speed` controls the rate at which the tinting
1305
diminishes. At a value of `1` (the default), a tint with a `fadefrac` of 0.5
1306
finishes in approximately one second.
1307
+
1308
The last, optional argument `prio` must be an integer in the range [`-128`
1309
.. `127`], the default being `0`. When a `fadecol` is issued in the presence of
1310
another tint fading in progress, and the `prio` given by the arriving `fadecol`
1311
is greater or equal than the `prio` of the ongoing one, the latter is canceled
1312
and the arriving fading is initiated in its place. (There is no support for
1313
tint fades that overlap in time.)
1314
+
4036 helixhorne 1315
[icon="din_w_crushing.png"]
3893 helixhorne 1316
CAUTION: If Lunatic code that uses `fadecol` is loaded together with CON code
1317
that writes to the player's `pals` members directly at any point, the behavior
1318
is undefined.
1319
 
4217 helixhorne 1320
[[player_iterators]]
3930 helixhorne 1321
===== `player` iterators
1322
 
1323
+*for* i *in* player.all()+::
1324
Iterates over the indices of all active players.
1325
 
3942 helixhorne 1326
// ===== `projectile`
3887 helixhorne 1327
 
1328
===== `g_tile`
1329
 
3942 helixhorne 1330
An array of size `gv.MAXTILES`. Currently, access with numeric indices by the
1331
user is [red]#disallowed# for `g_tile` and its elements have [red]#no public
1332
members#.
1333
 
3887 helixhorne 1334
===== `g_tile` static data
1335
 
3906 helixhorne 1336
`g_tile.sizx`, {nbsp} `g_tile.sizy`::
3887 helixhorne 1337
Arrays indexable with tile numbers [`0` .. `gv.MAXTILES-1`] that hold the
1338
horizontal and vertical texel sizes of each tile.
1339
 
1340
 
3868 helixhorne 1341
Lunatic functions
1342
~~~~~~~~~~~~~~~~~
3889 helixhorne 1343
 
4035 helixhorne 1344
[[engine_iterators]]
3910 helixhorne 1345
Engine-side iterators
1346
^^^^^^^^^^^^^^^^^^^^^
3889 helixhorne 1347
 
1348
+*for* w *in* wallsofsect(sectnum)+::
1349
Iterates over the indices of all walls of the sector with index `sectnum`.
1350
 
3930 helixhorne 1351
+*for* s *in* spritesofstat(statnum [, maydelete])+::
1352
Iterates over the indices of all sprites with status number `statnum`. If
1353
`maydelete` is omitted or false, there must be no deletion of any sprite while
1354
the loop is active. If `maydelete` is true, deleting sprites inside the loop is
1355
allowed. Inserting sprites is always allowed.
3889 helixhorne 1356
 
3930 helixhorne 1357
+*for* s *in* spritesofsect(sectnum [, maydelete])+::
3925 helixhorne 1358
Iterates over the indices of all sprites contained in the sector with index
3930 helixhorne 1359
`sectnum` with the same meaning for `maydelete` as with `spritesofstat`.
3889 helixhorne 1360
 
4198 helixhorne 1361
[[sectorsofbunch_1]] +*for* s *in* sectorsofbunch(bunchnum, cf)+::
1362
 
1363
Iterates over the indices of the sectors whose ceiling's or floor's bunch
1364
equals `bunchnum`, selected by passing `gv.CEILING` or `gv.FLOOR`
1365
(respectively) to `cf`.
1366
 
1367
[[sectorsofbunch_2]] +*for* s, what *in* sectorsofbunch(bunchnum, gv.BOTH_CF)+::
1368
Iterates over the indices of the sectors whose ceiling's and floor's bunch
1369
equals `bunchnum`.  On each iteration, `what` is one of the strings `'ceiling'`
1370
or `'floor'`, denoting whether it's the ceiling or floor of sector `s` that has
1371
the given bunch number.
1372
 
3910 helixhorne 1373
Sector containment functions
1374
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1375
 
1376
`inside(pos, sectnum)`::
1377
Returns a boolean of whether the position `pos` (which can be anything
1378
indexable with `x` and `y`) is considered inside the sector with number
1379
`sectnum`, which must be valid. The `z` component is not taken into account.
1380
 
3938 helixhorne 1381
===== Sector updating
1382
 
3910 helixhorne 1383
A number of engine functions take a position `pos` and a starting sector number
1384
`sectnum` and try to find a sector that contains `pos`, assuming it started out
1385
in `sectnum`.footnote:[Note that this is different from CON's `updatesector`,
1386
which takes the starting sector to be the one of the _current sprite_.]
1387
 
1388
If a valid sector numeric is passed for `sectnum`, these functions first check
4070 helixhorne 1389
whether that sector already contains `pos` (i.e. the position stays in the same
1390
sector) and then attempt to search neighboring sectors. Unless breadth-first
1391
search is requested (see below), if the passed `sectnum` is `-1`, all sectors
1392
are searched in an unspecified order.
3910 helixhorne 1393
 
4070 helixhorne 1394
On success, these functions return the sector number of the ``updated'' sector,
1395
otherwise `-1`.
3938 helixhorne 1396
 
4070 helixhorne 1397
[[updatesector]]
1398
`updatesector(pos, sectnum [, flags])`::
3910 helixhorne 1399
 
1400
Searches for a sector containing `pos`, which can be anything indexable with
1401
`x` and `y`. Thus, the `z` component is not taken into account. If `sectnum` is
1402
a valid sector number, first all its neighboring walls
1403
(<<nextwall,`wall[].nextwall`>>, ``red wall links'') are searched, falling back
1404
to a linear search on failure.
1405
+
1406
However, this strategy can be problematic if the position passes multiple thin
1407
sectors that overlap another, potentially unrelated sector (for example, in a
1408
TROR or sector-over-sector construction). If such a sector is passed without an
1409
`updatesector` call ever made when it contains the position, the next call may
1410
not find the real sector (as it is now two nextwall links away from the initial
1411
one), and wrongly suggest the overlapping one instead.
1412
+
1413
For this reason, the optional argument `flags` accepts
1414
<<sector_UPDATE_FLAGS,`sector.UPDATE_FLAGS.BREADTH`>>, instructing
1415
`updatesector` to look for matching sectors in a _breadth-first_ search
1416
starting from `sectnum`, and following all nextwall links. With this strategy,
1417
there is *no* fallback to a linear search if no matching sector is found.
3956 helixhorne 1418
+
1419
Passing `sector.UPDATE_FLAGS.Z` to `flags` makes the sector updating behave as
1420
if `updatesectorz` was called. This is mainly useful if `updatesector` is
1421
called via the <<sprite_updatesect,sector updating functions>> of sprites.
3910 helixhorne 1422
 
1423
`updatesectorz(pos, sectnum)`::
1424
 
1425
Searches for a sector containing `pos`, which can be any value indexable with
1426
`x`, `y` and `z`. Thus, it additionally takes the `z` component into account by
1427
checking against the bounds that would be returned using a sector's
4070 helixhorne 1428
<<sec_cfz_at,`ceilingzat`/`floorzat`>> methods.
3910 helixhorne 1429
+
1430
The `updatesectorz` function first checks the initial sector for containment of
1431
`pos`, then it tries any TROR neighbors of `sectnum`. Finally, it proceeds like
1432
`updatesector` as far as the searching order is concerned.
1433
 
4070 helixhorne 1434
===== Collision detection and related functions
1435
 
1436
[[hitscan]]
1437
`hitscan(pos, sectnum, ray, clipmask)`::
1438
 
1439
Starting from the position `pos` (which is assumed to be contained in
1440
`sectnum`), the `hitscan` function determines the object that would be first
1441
hit by a ray emanating from `pos` into the direction given by `ray`. Both `pos`
1442
and `ray` may be any object indexable with `x`, `y` and `z`, but the components
1443
are <<int_assignment,converted>> to signed 32-bit integers prior to being
1444
passed to the actual engine function. Note that `ray` is interpreted in BUILD
1445
scaling: the z component has 16 times the precision for a given game-world
1446
length compared to x or y.
1447
+
1448
The `clipmask` argument determines what objects are considered being hittable
1449
by the ray and is expected to be an integral number. It is interpreted as two
1450
separate bit masks: the low 16 bits for walls and the high 16 bits for
1451
sprites. Each time there is a potential collision, the respective mask is ANDed
1452
with the `cstat` member of the object, and if the result is non-zero, the ray
1453
is considered having hit the object.
1454
+
1455
The `hitscan` function returns an object with information about the hit object
1456
(if any) as well as the position of its intersection with the ray. It contains
1457
the following members:
1458
+
1459
* `sector`: The sector number of the hit object, or `-1` if no object was
1460
  hit. Thus, testing it for being greater or equal to zero is a quick way of
1461
  finding out whether any object (ceiling/floor, wall, or sprite) was hit at
1462
  all.footnote:[It is recommended to carry out this check for the sake of
1463
  cautiousness: while proper `hitscan` invocations should always hit something,
1464
  the function may come up empty in certain corner cases (such as a starting
1465
  position outside of the designated sector).]
1466
* `wall`: If a wall was hit, its index. Otherwise, `-1`.
1467
* `sprite`: If a sprite was hit, its index. Otherwise, `-1`.
1468
* `pos`: The position that is the intersection of the emanated ray with the hit
1469
   object, indexable with `x`, `y` and `z`. Undefined if no object was hit.
1470
 
3910 helixhorne 1471
//////////
3868 helixhorne 1472
cansee
1473
hitscan
1474
neartag
1475
sectorsofbunch
3910 helixhorne 1476
//////////
3868 helixhorne 1477
 
3887 helixhorne 1478
Customizing the game
1479
^^^^^^^^^^^^^^^^^^^^
3868 helixhorne 1480
 
3887 helixhorne 1481
In Lunatic, there are two main ways of customizing the game's behavior. Both
1482
involve the user providing functions that are _called back_ at certain points
1483
in the execution of EDuke32. Game _actors_ are simply sprites that run a
1484
particular piece of code based on their tile number each game tic, unless they
1485
are in a ``dormant'' state. Game _events_ are invoked at predetermined points
1486
in the program flow.
1487
 
1488
To register custom actor and event code with the game (and define additional
1489
actor information), Lunatic provides two functions in the global environment,
1490
`gameactor` and `gameevent`. As their sole argument, they take a table
1491
containing the appropriate data.
1492
 
1493
[[gameactor]]
1494
===== The function `gameactor{tilenum [, ...], func}`
1495
 
3933 helixhorne 1496
:Lua51_FunctionCalls: http://www.lua.org/manual/5.1/manual.html#2.5.8
1497
 
3887 helixhorne 1498
Registers custom code for the actor given by tile number `tilenum`. For each
1499
non-sleeping actor, the function `func` is called every game tic with three
1500
input arguments: `func(aci, pli, dist)`.
1501
 
1502
* `aci`: the sprite number of the actor invoking `func`
1503
* `pli`: the index of the player that is nearest to this actor
3889 helixhorne 1504
* `dist`: the 3D Manhattan distance
3895 helixhorne 1505
  footnoteref:[mhdist_def,The Manhattan distance between points
1506
  _p_~1~=(x~1~&#44; y~1~&#44; z~1~) and _p_~2~=(x~2~&#44; y~2~&#44; z~2~) is
1507
  defined as abs(x~2~ -- x~1~) + abs(y~2~ -- y~1~) + abs(z~2~ -- z~1~).]
3889 helixhorne 1508
  between actor `aci` and player `pli`
3887 helixhorne 1509
 
3895 helixhorne 1510
// NOTE: &#44; is the comma; the footnote would be truncated at it otherwise.
1511
// For a related issue, see
1512
// http://www.methods.co.nz/asciidoc/faq.html#_why_am_i_having_trouble_getting_nested_macros_to_work
1513
 
3887 helixhorne 1514
Additionally, `gameactor` accepts optional input arguments. They can be
4202 helixhorne 1515
specified positionally by following `tilenum`, or be given as values to string
3887 helixhorne 1516
keys of the argument table. Each such input argument may be provided in at most
1517
one of these two forms. Furthermore, `func` may be provided as value to the
1518
key `'func'` as well.
1519
 
3933 helixhorne 1520
[[gameactor_flags]]
3887 helixhorne 1521
`[2] flags`::
1522
A number that controls both certain aspects of the `gameactor` call as well as
3895 helixhorne 1523
the run-time behavior of the actor itself. A couple of bits for the latter type
1524
are listed in <<actor_FLAGS,`actor.FLAGS`>>, abbreviated `AF` in the following.
3887 helixhorne 1525
+
1526
These values describe the ``type'' of the actor: `AF.enemy`, `AF.enemystayput`
1527
and `AF.rotfixed`. Except for `enemystayput`, they name single bits
1528
(`enemystayput` implies `enemy`).
1529
+
1530
In Lunatic, game actors can be _chained_, that is, a callback function can be
1531
either appended to the end of an already registered one, or prefixed at its
1532
front. In this case, a previous `gameactor` call must have taken place for that
1533
actor (this may have happened from a CON `useractor` block, which gets
1534
translated to `gameactor`). Moreover, this mechanism allows to add run-time
1535
flags to the actor in question.
1536
+
3933 helixhorne 1537
Chaining two callback functions is achieved by creating a new one that calls
1538
the first one, followed by a {Lua51_FunctionCalls}[tail call] of the second
3942 helixhorne 1539
one. This has certain implications if control is transferred non-locally, for
1540
example by using <<nlcf,`con.longjmp`>>.
3933 helixhorne 1541
+
3887 helixhorne 1542
Several flags in `AF` are provided to control how a `gameactor` invocation
4374 helixhorne 1543
handles chaining. In all cases, the actor tile flags are bitwise-ORed with the
1544
existing ones.
3887 helixhorne 1545
+
4374 helixhorne 1546
* `AF.replace`: Replace the callback function. This is the way CON's
1547
  `useractor` behaves and is also the Lunatic default.
1548
* `AF.replace_soft`: deprecated alias for `AF.replace`
1549
* `AF.replace_hard`: [red]*deprecated*
1550
* `AF.chain_beg`: Prepend the provided `func` to the existing callback function.
1551
* `AF.chain_end`: Append the provided `func` to the existing callback function.
3925 helixhorne 1552
+
1553
The following members all default to 0 if omitted.
1554
+
3887 helixhorne 1555
`[3] strength`::
3925 helixhorne 1556
The initial strength or health of the actor.
3887 helixhorne 1557
 
1558
`[4] action`::
3925 helixhorne 1559
The initial action of the actor. May be either an object returned by
1560
<<con_action,`con.action`>>, or the numbers 0 or 1. Both represent actions with
1561
that ID, but all public members set to 0.
3887 helixhorne 1562
 
3925 helixhorne 1563
[[gameactor_move]] `[5] move`::
1564
The initial move of the actor. May be either an object returned by
1565
<<con_move,`con.move`>>, or the numbers 0 or 1. Both represent moves with that
1566
ID, but all public members set to 0. A move of 0 disables the usual actor
3930 helixhorne 1567
movement, even if its `hvel` or `vvel` subsequently get overridden (and the
3925 helixhorne 1568
corresponding `movflags` set).
3887 helixhorne 1569
 
1570
`[6] movflags`::
3925 helixhorne 1571
The actor's initial movement flags. Applicable bits are available in the
1572
<<actor_MOVFLAGS,`actor.MOVFLAGS`>> object.
3868 helixhorne 1573
 
3887 helixhorne 1574
===== The function `gameevent{evtlabel [, flags], func}`
3868 helixhorne 1575
 
3887 helixhorne 1576
:wiki: http://wiki.eduke32.com
1577
:wiki_eventlist: http://wiki.eduke32.com/wiki/EDuke32_event_list
1578
 
1579
Registers custom code to be run at specific points in the program.  The first
1580
argument `evtlabel` should be a string naming the event. A complete
1581
{wiki_eventlist}[list of events] can be found at the {wiki}[EDuke32 wiki]. The
1582
label may be stripped of the leading ```EVENT_`'', so that e.g. `EVENT_JUMP`
1583
and simply `JUMP` denote the same event.
1584
 
1585
The arguments `flags` and `func` can alternatively be passed as values to the
1586
same-named keys of the input argument table to `gameevent`. Like with
1587
`gameactor`, each may be provided in at most one of the two forms.
1588
 
1589
The callback `func` is invoked with the same arguments and meaning as for
1590
<<gameactor,`gameactor`>>, but certain events are run in contexts where no
1591
meaningful `aci` and/or `pli` value can be assigned. In this case, `func`
1592
receives `-1` for the respective input arguments.
1593
 
3889 helixhorne 1594
Like with actors, game events may be chained or replaced by passing an
1595
appropriate `flags` value. However, it is not necessary for an event to be
1596
already defined when chaining is requested. In that case, it is simply
1597
registered initially.  Permissible values for these flags are provided in
1598
`actor.FLAGS` as well (abbreviated `AF` here):
3887 helixhorne 1599
 
1600
* `AF.replace`: Replace any previously defined event code with the given one.
4202 helixhorne 1601
* `AF.chain_beg`: Prepend the provided `func` to the existing callback
3887 helixhorne 1602
  function. This is the behavior of CON's `onevent`.
4202 helixhorne 1603
* `AF.chain_end`: Append the provided `func` to the existing callback
3887 helixhorne 1604
  function. This is the default.
1605
 
1606
// TODO: RETURN handling...
1607
 
1608
 
3868 helixhorne 1609
[[ext_api]]
1610
Extended API (Lunatic modules)
1611
------------------------------
1612
 
3889 helixhorne 1613
The `xmath` module
1614
~~~~~~~~~~~~~~~~~~
1615
 
3906 helixhorne 1616
Mathematical functions
1617
^^^^^^^^^^^^^^^^^^^^^^
1618
 
3930 helixhorne 1619
:BitOpUndefined: http://bitop.luajit.org/semantics.html#undefined
1620
 
3889 helixhorne 1621
Lunatic, being a Lua-based scripting system, provides the user with a single
1622
numeric data type that variables can contain on the Lua side --
4202 helixhorne 1623
double-precision floating point.footnote:[In LuaJIT, variables additionally can
3889 helixhorne 1624
take on ``boxed'' 64-bit integer numeric types, but these should not be used
1625
for numeric calculations.]  However, since BUILD, and in turn, EDuke32, almost
1626
exclusively use integer types to represent quantities such as angles or carry
1627
out e.g. trigonometrical calculations, there is a need for convenient
1628
interoperability between the two ``worlds''.
1629
 
3906 helixhorne 1630
Two pairs of functions calculate the trigonometric sine and cosine, both
1631
accepting a BUILD angle as input argument, but differing in the scaling of
1632
their result. Using these functions is recommended over Lua's `math.sin` or
1633
`math.cos` in cases where the argument is a BUILD angle in the first place, for
1634
example because it is read from an engine or game structure. The computation is
1635
both faster (because it is essentially only a bitwise-AND operation followed by
1636
a table lookup) and the results have the symmetry expected from the
1637
mathematical counterparts.
1638
 
1639
`xmath.sinb(bang)`, {nbsp} `xmath.cosb(bang)`::
3930 helixhorne 1640
Returns the sine/cosine of the given BUILD angle `bang`, which can be any whole
1641
number in [--2^31^{nbsp}..{nbsp}2^31^--1].footnote:[Passing fractional values
1642
is possible, but discouraged. See the relevant {BitOpUndefined}[subsection] of
1643
the BitOp documentation for more details.] In BUILD, one full cycle is covered
1644
by values from 0 to 2047; in other words, an angle of 2048 corresponds to 360
3906 helixhorne 1645
degrees.
1646
+
1647
The `sinb` and `cosb` functions return values in the range [--1 .. 1], just
1648
like their mathematical counterparts.
1649
+
4202 helixhorne 1650
The following guarantees are made for `sinb` whenever its argument expression
3906 helixhorne 1651
is permissible:
1652
+
1653
* `sinb(-a) == -sinb(a)` (point symmetry around the origin)
1654
* `sinb(a + i*2048) == sinb(a)`, where `i` is any whole number (periodicity)
1655
* `sinb(1024 - a) == sinb(a)` (mirror symmetry around `a`=512)
1656
* `sinb(a - 1024) == -sinb(a)` (point symmetry around `a`=1024)
1657
* The value for `cosb(a)` is derived as `sinb(a + 512)`.
1658
 
1659
`xmath.ksin(bang)`, {nbsp} `xmath.kcos(bang)`::
1660
Returns the sine/cosine of the given BUILD angle `bang`, multiplied with 16384
1661
and rounded towards zero. The same guarantees as for the `sinb`/`cosb` pair
1662
apply.
1663
 
3942 helixhorne 1664
`xmath.angvec(ang)`::
1665
Returns a <<vector_types,`vec3`>> with the components `math.cos(ang)`,
1666
`math.sin(ang)` and 0 for x, y and z, respectively.
1667
 
1668
`xmath.bangvec(bang)`::
1669
Returns a <<vector_types,`vec3`>> with the components `xmath.cosb(bang)`,
1670
`xmath.sinb(bang)` and 0 for x, y and z, respectively.
1671
 
4070 helixhorne 1672
`xmath.kangvec(bang [, z])`::
1673
Returns an <<vector_types,`ivec3`>> with the components `xmath.kcos(bang)`,
1674
`xmath.ksin(bang)` for x and y, respectively. The z component can be passed in
1675
the optional argument `z`, which defaults to 0 if omitted.
1676
 
3906 helixhorne 1677
`xmath.dist(pos1, pos2)`::
1678
Returns an approximation of the 3D Euclidean distance between points `pos1` and
1679
`pos2`, both of which can be any object indexable with `x`, `y` and `z`.
1680
<<cf_z,BUILD z units>> are assumed.
1681
 
1682
`xmath.ldist(pos1, pos2)`::
1683
Returns an approximation of the 2D Euclidean distance between points `pos1` and
1684
`pos2`, both of which can be any object indexable with `x` and `y`.
1685
 
3930 helixhorne 1686
[[xmath_rotate]] `xmath.rotate(point, bang [, pivot])`::
1687
Returns as an <<vector_types,`xmath.vec3`>> the position of `point` rotated
1688
around the line parallel to the z axis going through `pivot` by `bang` BUILD
1689
angle units in the mathematically negative (clockwise) direction. The arguments
1690
`point` and `pivot` can be anything indexable with `x`, `y` and `z`. The z
1691
component of the result is the difference between that of `point` and
1692
`pivot`. If `pivot` is omitted, it defaults to the origin vector containing
1693
zeros for all components.
1694
 
3906 helixhorne 1695
[[vector_types]]
4202 helixhorne 1696
The types `xmath.vec3` and `xmath.ivec3` [_serializable_]
3914 helixhorne 1697
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
3906 helixhorne 1698
 
3889 helixhorne 1699
Another purpose of the `xmath` module is to provide _vector_ types that allow
3895 helixhorne 1700
writing concise and clear code involving geometrical calculations. There are
1701
two types, both containing three components (`x`, `y` and `z`), but differing
1702
in their numeric type. For the most part, `vec3` should be used, whose
1703
components are Lua numbers, i.e. floating point. The other type, `ivec3`, is
1704
part of some game structures, and consequently uses 32-bit integers for its
1705
components. With minor differences, the `vec3` and `ivec3` types share the same
1706
operations and methods.
1707
 
1708
The constructors of the vector types can be called in several ways. In the
1709
following, they are only described for `vec3`. The conventions for `ivec3` are
1710
completely analogous, but since their creation involves a number type
1711
conversion, the rules about <<int_assignment,assignment to integer types>>
1712
apply.
1713
 
1714
`v = xmath.vec3([x [, y [, z]]])`::
1715
Create a 3-element vector `v` by passing the `x`, `y` and `z` components
1716
separately. Trailing components can be omitted, in which case they are
1717
initialized to 0.
1718
 
1719
`v = xmath.vec3(t)`::
1720
Create a 3-element vector `v` by passing `t`, which can be any variable
1721
indexable with the strings `x`, `y` and `z` (and yielding numbers for these
1722
lookups). For example, `t` can be another (`i`)`vec3`, a `sprite` or even
1723
<<wall,`wall`>> reference, as each of them can be indexed with these three
1724
keys.
1725
 
1726
Since the vector types are compound objects, they are always passed around by
1727
reference. For example, consider executing
4113 helixhorne 1728
[source]
3895 helixhorne 1729
----------
4189 helixhorne 1730
v = xmath.vec3(0, 10)
3895 helixhorne 1731
w = v
4189 helixhorne 1732
w.y = 20
3895 helixhorne 1733
----------
4189 helixhorne 1734
After this code, the expression `v.y` yields 20 instead of the initial value
1735
10.
3895 helixhorne 1736
 
1737
===== Operations for `vec3` and `ivec3`
1738
 
1739
In the following, `v` denotes a `vec3` or `ivec3` object reference while `t`
1740
denotes any object indexable with `x`, `y` and `z`. Note that for binary
1741
operations, Lua looks for overridden operators in the left operand first and
1742
the right one next.  So, where `t` appears on the left hand side of an
1743
arithmetic expression, it is assumed that `t`'s type does not overload the
1744
corresponding operation or provides the same semantics. Arithmetic operations
1745
always return a (reference to a) new `vec3` object, even if any or both of the
1746
operands have `ivec3` type.
1747
 
1748
`v + t`, {nbsp} `t + v`::
1749
Returns a new `vec3` object whose components are the sum of the respective
1750
components of `v` and `t`.
1751
 
1752
`v - t`, {nbsp} `t - v`::
1753
Returns a new `vec3` object whose components are the difference of the
1754
respective components of `v` and `t` (in the first case) or `t` and `v` (in the
1755
second case).
1756
 
1757
`-v`::
1758
Returns a new `vec3` object with the components of `v` negated.
1759
 
1760
`a*v`, {nbsp} `v*a`::
3906 helixhorne 1761
For a scalar number `a`, returns a new `vec3` object whose components are those
4202 helixhorne 1762
of `v` multiplied with `a`.
3895 helixhorne 1763
 
1764
`v/a`::
1765
For a scalar number `a`, returns a new `vec3` object whose components are those
1766
of `v` divided by `a`.
1767
 
1768
`v^zofs`::
1769
Returns an object of the same type as `v` and with the same components, except
1770
that `v.z` is diminished by `zofs`. Also see the <<sprite_power,power
1771
operation>> for `sprite` objects.
1772
 
1773
`tostring(v)`::
1774
Returns a string representation of `v` for display purposes: ```vec3`'' or
1775
```ivec3`'', followed by the components of `v` in parentheses.
1776
 
1777
===== Methods for `vec3` and `ivec3`
1778
 
1779
`v:len()`::
1780
Returns the Euclidean length of `v` in three dimensions.
1781
 
1782
`v:lensq()`::
1783
Returns the squared Euclidean length of `v` in three dimensions.
1784
 
1785
`v:len2()`::
1786
Returns the Euclidean length of `v`, taking only the `x` and `y` components
1787
into account.
1788
 
1789
`v:len2sq()`::
1790
Returns the squared Euclidean length of `v`, taking only the `x` and `y`
1791
components into account.
1792
 
1793
`v:mhlen()`::
1794
Returns the length of `v` calculated using the Manhattan distance
1795
footnoteref:[mhdist_def] in three dimensions between the origin and the
1796
endpoint.
1797
 
1798
`v:toivec3()`::
1799
Returns a new `ivec3` object with the same components as `v`, but converted
1800
<<int_assignment,to integers>>.
1801
 
1802
`v:touniform()`::
1803
Returns a new vector of the same type as `v` which has the same `x` and `y`
1804
components as `v`, but the `z` element divided by 16 (if `v` is a `vec3`) or
1805
arithmetically right-shifted by 4 (if `v` is an
3906 helixhorne 1806
`ivec3`).footnote:[Right-shifting by 4 can be seen as a division by 16 with
1807
subsequent rounding to an integer towards negative infinity.] Also see the
1808
description of the ceiling/floor <<cf_z,`z` member>>.
3895 helixhorne 1809
 
1810
`v:tobuild()`::
1811
Returns a new vector of the same type as `v` which has the same `x` and `y`
1812
components as `v`, but the `z` element multiplied with 16.
3925 helixhorne 1813
 
3930 helixhorne 1814
`v:rotate(bang [, pivot])`::
1815
Equivalent to +<<xmath_rotate,xmath.rotate>>(v, bang [, pivot])+.
3925 helixhorne 1816
 
3930 helixhorne 1817
 
3925 helixhorne 1818
The `con` module -- game control
1819
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1820
 
1821
The `con` module on one hand provides functionality to control certain aspects
1822
of the game, such as defining game-side animations for actors. On the other
3933 helixhorne 1823
hand, it hosts various functions that are familiar from CON, although sometimes
1824
under a different name.
3925 helixhorne 1825
 
1826
[[actions_moves_ais]]
1827
Actions, moves and AIs -- customizing actor behavior
1828
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1829
 
1830
In CON, three aspects of an actor can changed using a mechanism that is
1831
syntactically similar for each. _Actions_ carry information about a particular
1832
animation for an actor, such as how many frames it contains. _Moves_ define the
1833
potential motion characteristics of an actor. Finally, _AIs_ are aggregates of
1834
an action and a move, plus _movement flags_ that toggle certain movement
1835
aspects.
1836
 
1837
At file scope, one first defines each of these composites using directives such
1838
as `action`, and inside code blocks to be executed at game time, one instructs
1839
the game to use a particular composite by passing the chosen label to the
1840
same-named command (i.e. `action` for our example).
1841
 
1842
Lunatic provides a similar mechanism, but the main difference from CON is that
1843
the definition functions merely return the composite structures, without
1844
registering them under any particular name. Thus, it is up to the user to
1845
organize them, for example by storing those for each class in a separate table
1846
indexed by chosen names. Similar to CON, the creation functions may only be
1847
called when the game is not yet running.
1848
 
1849
Actor behavior composites contain an additional ``hidden'' ID. Each invocation
1850
of a creation function such as `con.action` returns a composite with a unique
1851
ID per composite type. This ID is used to compare for equality in actor methods
1852
such as `actor[]:has_action()`. All returned composites are immutable.
1853
 
1854
[[con_action]]
1855
===== The function `con.action{ ... }`
1856
 
1857
:wiki_action: http://wiki.eduke32.com/wiki/Action
1858
:Lua51_TableConstructors: http://www.lua.org/manual/5.1/manual.html#2.5.7
1859
 
1860
Returns a new _action_ composite created with the given values. The
1861
`con.action` function expects a single table as input argument, each of whose
1862
keys denote an action member. Each member may be provided by an index in the
1863
table or its name, but not both. Members may be omitted, in which case they
1864
default to either 0 or 1.
1865
 
1866
Refer to the {Lua51_TableConstructors}[Table Constructors] subsection of the
1867
Lua 5.1 Reference Manual for the syntax and semantics of table initialization.
1868
 
1869
`[1] startframe`::
1870
The offset of the starting frame of the animation, relative to the
1871
`sprite[].picnum` of an actor (i.e. the tile number, selecting which actor code
1872
is run).
1873
 
1874
`[2] numframes` (default: 1)::
1875
The total number of frames in the animation.
1876
 
1877
`[3] viewtype` (default: 1)::
1878
The number of consecutive tiles used to construct one frame of the animation,
1879
as viewed from different angles. Valid values are 1, 3, 5, 7 and 8. In
1880
addition, -5 and -7 are allowed, which behave like the corresponding positive
4209 helixhorne 1881
++viewtype++s, but effectively mirror the actor around the vertical axis. This
1882
can be useful if tile data is available that has the opposite orientation of
1883
what EDuke32 uses.  See the {wiki_action}[Action entry] in the EDuke32 wiki for
1884
how the views are constructed for different `viewtype` values.
3925 helixhorne 1885
 
1886
`[4] incval` (default: 1)::
4217 helixhorne 1887
The value to add the actor's _current frame_ on each frame advance. May be --1,
3925 helixhorne 1888
0, or 1.
1889
// In the wild, sometimes other values, too.
1890
 
1891
[[action_delay]] `[5] delay`::
1892
Roughly, the number of <<totalclock,`gv.totalclock`>> time units (120 per
1893
second) after which a frame is advanced, at a granularity of one game tic (30
1894
per second, corresponding to a `delay` difference of 4).footnote:[The reason
1895
for the granularity is due to the implementation: each execution of an actor's
1896
code increments its hidden ``action tics'' counter by four (= 120/30).]
1897
 
1898
// TODO: the above can be more precise. State in terms of floor(delay/4).
1899
 
1900
.Equivalent `action` definitions
1901
==========
1902
Each of the following calls return an action with the same public members:
4113 helixhorne 1903
[source]
3925 helixhorne 1904
----------
1905
con.action{0, 4, delay=20}
1906
con.action{0, 4, 1, 1, 20}
1907
con.action{startframe=0, numframes=4, viewtype=1, incval=1, delay=20}
1908
----------
1909
==========
1910
 
1911
[[con_move]]
1912
===== The function `con.move{ ... }`
1913
 
1914
Returns a new _move_ composite created with the given values, expecting a
1915
single table as input argument. The same conventions as with `con.action` apply
1916
for the following members:
1917
 
1918
`[1] hvel`::
1919
The (most often) doubled horizontal velocity of the actor, in BUILD x/y units
1920
per game tic. An actor's `sprite[].xvel` will approach this value in an
1921
``exponential'' fashion, halving the difference between the current velocity
1922
and this goal velocity each movement update from the actor execution loop. For
1923
most objects, `sprite[].xvel` is then further halved to yield the ultimate
1924
velocity. Only effective when the actor's `movflags` has
1925
<<actor_MOVFLAGS,`actor.MOVFLAGS.geth`>> is set.
1926
 
1927
`[2] vvel`::
1928
The (most often) doubled horizontal velocity of the actor, in BUILD x/y (*not*
1929
z) units per game tic. An actor's `sprite[].zvel` will approach 16 times this
1930
value in an ``exponential'' fashion. For most objects, `sprite[].zvel` is then
1931
further halved to yield the ultimate velocity.  Only effective when the actor's
1932
`movflags` has <<actor_MOVFLAGS,`actor.MOVFLAGS.getv`>> is set.
1933
 
1934
[[con_ai]]
1935
===== The function `con.ai([action [, move [, movflags]]])`
1936
 
1937
The `con.ai` function differs from `con.action` and `con.move` in that it is of
1938
``second order'', i.e. it accepts two composites as input arguments, returning
1939
an _AI_ object containing these. Also, it is called with three positional,
1940
optional arguments. Like for <<gameactor,`gameactor`>>, the numbers 0 and 1 are
1941
permissible for `action` and `move`. Applicable bits for `movflags` are
1942
available in the <<actor_MOVFLAGS,`actor.MOVFLAGS`>> object.
3933 helixhorne 1943
 
1944
[[nlcf]]
1945
Non-local control flow
1946
^^^^^^^^^^^^^^^^^^^^^^
1947
 
1948
Two functions in the `con` module make the executed function abort early,
1949
jumping directly to the end of the innermost event or actor callback
1950
``block''. They are used to implement among others CON's `killit` and
4032 helixhorne 1951
(confusingly named) `return` commands. If these functions are used when none of
1952
the mentioned callback functions are active, the behavior is undefined.
3933 helixhorne 1953
 
1954
`con.longjmp()`::
1955
Silently transfers control to the end of the innermost actor or event callback
1956
block, to the same point an `error()` call would do. Note that since callback
1957
<<gameactor_flags,chaining>> is achieved by creating a new function for each
4032 helixhorne 1958
function pair, calling both unprotected, issuing a `con.longjmp()` inside any
1959
``part'' of a chain aborts the whole block -- functions in the chain that are
1960
called later will not be reached. In contrast, returning from one function
3933 helixhorne 1961
transfers control to the beginning of the next in the chain if it exists.
4032 helixhorne 1962
+
1963
.`con.longjmp` with chained events
1964
==========
1965
The following two chained `EVENT_JUMP` definitions,
4113 helixhorne 1966
[source]
4032 helixhorne 1967
----------
1968
gameevent{"JUMP", function(_, pli)
1969
    print("jump:first")
1970
    if (player[pli].curr_weapon==gv.WEAPON.PISTOL) then
1971
        return
1972
    end
1973
    print("aborting")
1974
    con.longjmp()
1975
end}
3933 helixhorne 1976
 
4032 helixhorne 1977
gameevent{"JUMP", function()  -- second function in EVENT_JUMP chain
1978
    print("jump:second")
1979
end}
1980
----------
1981
would print ```jump:first`'' and ```jump:second`'' when holding a
1982
pistol. Otherwise, ```jump:first`'' and ```aborting`'' would be printed and the
1983
second chained callback function would not be reached.
1984
==========
1985
 
3933 helixhorne 1986
`con.killit()`::
1987
Silently transfers control to the end of the active actor callback block,
1988
notifying the game to delete the executing actor's sprite. If `con.killit` is
1989
called while no execution of actor code is active, the behavior is undefined.
3942 helixhorne 1990
 
1991
Per-actor variables
1992
^^^^^^^^^^^^^^^^^^^
1993
 
1994
// XXX: this text is too implementation-centric
1995
 
1996
Since in EDuke32, sprites in general exist in the world only for a limited
1997
duration, it is wasteful to allocate an array of fixed size `gv.MAXSPRITES` for
1998
the purpose of a variable that holds a value for each actor sprite. On the Lua
1999
side, one could use a plain table, but for actors that are created and
2000
destroyed during the course of a game, this would accumulate ``garbage'' --
2001
values for sprites that have been deleted. Moreover, per-actor variables tend
2002
to be ``topical'', one such variable being potentially only used for a very
2003
specific actor tile. For this reason, per-actor variables are implemented in a
2004
``sparse'' fashion in Lunatic, but provide to the user the illusion of having a
3956 helixhorne 2005
value for every sprite index. They are also ``cleaned'' at unspecified
3942 helixhorne 2006
intervals.
2007
 
4044 helixhorne 2008
[[con_actorvar]]
3942 helixhorne 2009
===== The type `con.actorvar(defaultval)` [_serializable_]
2010
 
2011
Creates and returns a new per-actor variable with default value `defaultval`
2012
which can be indexed for reading or assignment in the range
3956 helixhorne 2013
[0{nbsp}..{nbsp}`gv.MAXSPRITES-1`], but access to it is subject to the same
2014
restrictions as to <<sprite,`sprite`>> and other per-sprite structures.
3942 helixhorne 2015
 
3956 helixhorne 2016
When a sprite is created using `con.insertsprite` or `con.spawn`, its value at
2017
the index of this new sprite is cleared (reset to `defaultval`). After a sprite
2018
has been deleted, the value of a per-actor variable is indeterminate -- it may
2019
be cleared by Lunatic at any point.
3942 helixhorne 2020
 
2021
Per-actor variables may contain values of any permitted type, which currently
3956 helixhorne 2022
are boolean and number. Mixing values of different types is allowed: per-actor
2023
variables are heterogenous containers.
3942 helixhorne 2024
 
2025
Sprite insertion
2026
^^^^^^^^^^^^^^^^
2027
 
3956 helixhorne 2028
In Lunatic, there are two functions that insert a sprite into the game world.
2029
They mainly differ in how they are used, and to which extent they imply
2030
``hard-coded'' behavior.
3942 helixhorne 2031
 
4218 helixhorne 2032
===== The function `con.insertsprite{tilenum, pos, sectnum [, statnum [, owner]] [key=val...]}`
3942 helixhorne 2033
 
2034
Inserts a new sprite into the game with the properties given as input
3956 helixhorne 2035
arguments. If the world already contains the maximum number of sprites
2036
(<<gv,`gv.MAXSPRITES`>>), currently the game is aborted and EDuke32
2037
exits.footnote:[This is subject to change and must not be relied on.]
2038
Otherwise, relevant per-sprite data for the newly inserted sprite is
2039
cleared. No additional ``hard-wired'' C code is run.
3942 helixhorne 2040
 
4201 helixhorne 2041
Returns the index of the inserted sprite.
3942 helixhorne 2042
 
4218 helixhorne 2043
The function `con.insertsprite` can be used in one of two forms:
3942 helixhorne 2044
 
4218 helixhorne 2045
* In the `table-call` form specified above, a single table is passed whose
2046
values are taken as the actual arguments. The first three, `tilenum`, `pos` and
2047
`sectnum`, are passed positionally. All other input arguments are passed as
2048
key-value pairs, but `owner` and `statnum` may be provided either positionally
2049
or as key/value pair.
2050
 
2051
* Passing only the three to five positional arguments is also directly
2052
  possible. For example, all of the following calls are equivalent:
2053
+
2054
[source]
2055
----------
2056
local i = con.insertsprite(tile, pos, sect, stat, ow)  -- direct-call
2057
local i = con.insertsprite{tile, pos, sect, stat, ow}  -- table-call
2058
local i = con.insertsprite{tile, pos, sect, statnum=stat, owner=ow}  -- table-call with 2 k/v args
2059
local i = con.insertsprite{tile, pos, sect, stat, owner=ow}  -- table-call with one k/v arg
2060
----------
2061
 
2062
The five main arguments are as follows:
2063
 
3942 helixhorne 2064
`[1]` (`tilenum`)::
2065
The tile number of the sprite to insert.
2066
 
2067
`[2]` (`pos`)::
2068
The position at which to insert the sprite (anything indexable with `x`, `y` and `z`).
2069
 
2070
`[3]` (`sectnum`)::
2071
The index of the sector in which to insert the sprite.
2072
 
4218 helixhorne 2073
`[4] statnum` (default: `actor.STAT.DEFAULT`)::
2074
The initial status number of the inserted sprite.
2075
 
2076
`[5] owner` (default: see below)::
3942 helixhorne 2077
The index of the sprite that is in some sense the ``parent'' of the newly
4218 helixhorne 2078
created one. If omitted, it is set to the index of the newly spawned sprite.
3942 helixhorne 2079
 
4218 helixhorne 2080
These keys are permissible as optional input arguments in the table-call form,
2081
corresponding to the same-named <<sprite,`sprite`>> members:
3942 helixhorne 2082
 
4218 helixhorne 2083
* `shade`, `ang`, `xvel`, `zvel` (default: 0)
2084
* `xrepeat` and `yrepeat` (default: 48)
3942 helixhorne 2085
 
2086
===== The function `con.spawn(tilenum, parentspritenum)`
2087
 
2088
Spawns a new sprite with tile number `tilenum` from a given ``parent'' sprite
3956 helixhorne 2089
with index `parentspritenum`, which must be valid. The sprite is spawned at the
4032 helixhorne 2090
same position as its parent and its `owner` member is set to
3956 helixhorne 2091
`parentspritenum`. Additional ``hard-wired'' code dependent on `tilenum` may be
4032 helixhorne 2092
run afterwards, possibly modifying the sprite.
3942 helixhorne 2093
 
2094
Returns the index of the spawned sprite on success.
4032 helixhorne 2095
 
4201 helixhorne 2096
===== The function `con.shoot(tilenum, parentspritenum [, zvel])`
4032 helixhorne 2097
 
4201 helixhorne 2098
Attempts to shoot a projectile with tile number `tilenum` from the sprite with
2099
index `parentspritenum`. The z velocity can be overridden by passing `zvel`.
2100
 
2101
// TODO: document how zvel is interpreted
2102
 
4217 helixhorne 2103
Returns the index of the spawned sprite on success, or --1 otherwise.
4201 helixhorne 2104
 
2105
 
4239 helixhorne 2106
The `engine` module
2107
~~~~~~~~~~~~~~~~~~~
2108
 
4307 helixhorne 2109
Base palette interfaces
2110
^^^^^^^^^^^^^^^^^^^^^^^
4239 helixhorne 2111
 
2112
The 8-bit (``classic'') Build renderer operates in indexed-color mode: the
2113
pixels of the frame buffer do not contain red/green/blue values themselves, but
2114
only indexes into a color table with 256 entries, the _base palette_.
2115
**********
2116
latexmath:[$\mathrm{ColorComponent} := \mathbb{N}_{64}$] {nbsp}
2117
[gray]#// Build's base palettes have 6 bits of precision per color component# +
2118
latexmath:[$\mathrm{ColorIndex} := \mathbb{N}_{256}$] +
2119
latexmath:[$\mathrm{basepal}: \: \mathrm{ColorIndex} \rightarrow \mathrm{ColorComponent}^3$] +
2120
**********
2121
 
4307 helixhorne 2122
The following functions provide a bridge between color indices and their
2123
corresponding color components.
2124
 
2125
`r, g, b = engine.getrgb(i)`::
2126
Returns the red, green and blue color components of the default base palette
2127
for color index `i`. The color components are in the range [0 .. 63].
2128
+
2129
If `i` is 255, `r`, `g` and `b` are all returned as 0, even if the actual base
2130
palette may contain different values for that index.
2131
 
4308 helixhorne 2132
`i = engine.nearcolor(r, g, b [, lastokcol])`::
4307 helixhorne 2133
 
4308 helixhorne 2134
Given the red, green and blue components `r`, `g` and `b` of a query color,
2135
returns the color index `i` whose color in the default base palette is closest
2136
to the query color. ``Closeness'' is established using an Euclidean distance
2137
with a weighting on the color components.
2138
+
2139
The optional argument `lastokcol` can be used to restrict the range of color
2140
indices to search: the returned color index is guaranteed to be in the range
2141
[0{nbsp}..{nbsp}`lastokcol`]. It defaults 255, so that all colors are
2142
searched.footnote:[For example, it may be desirable to omit ``fullbright''
2143
colors from being returned. The shade table loaded from Duke3D's PALETTE.DAT
2144
makes color indices 240--254 fullbright, so passing 239 to `lastokcol` achieves
2145
the mentioned filtering.]
2146
 
4337 helixhorne 2147
[[shade_table_interfaces]]
4307 helixhorne 2148
Shade table interfaces
2149
^^^^^^^^^^^^^^^^^^^^^^
2150
 
4239 helixhorne 2151
To implement shading and visibility attenuation, Build maintains tables mapping
2152
pairs of a color index and a shade level (Duke3D's table uses 32 such
2153
gradients) to a color index representing the darkness-faded color. Each such
2154
table is called shade or _palookup_ table.
2155
**********
2156
latexmath:[$\mathrm{ShadeLevel} := \mathbb{N}_{\mathrm{Numshades}}$] +
2157
latexmath:[$\mathrm{palookup}: \: \mathrm{ShadeLevel} \times
2158
  \mathrm{ColorIndex} \rightarrow \mathrm{ColorIndex}$]
2159
**********
2160
 
2161
When a pixel is about to be drawn, a palookup table chosen depending on the
2162
object's `pal` is consulted to determine its ultimate color index (in the
2163
absence of blending with the translucency table or see-through texels). Given a
2164
texel's color index as latexmath:[$i_{\mathrm{in}}$], the resulting pixel's one
2165
latexmath:[$i_{\mathrm{out}}$] is computed as
2166
 
2167
==========
4337 helixhorne 2168
latexmath:[$s_1 = \mathrm{shade} + C \cdot \mathrm{visdist}$] +
4239 helixhorne 2169
latexmath:[$s_2 = \mathrm{clamp}(s_1, \: 0, \: \mathrm{Numshades}-1)$] +
2170
latexmath:[$\mathrm{shade_index} = \mathrm{round}(s_2)$] +
2171
latexmath:[$i_{\mathrm{out}} = \mathrm{palookup}(\mathrm{shade_index}, i_{\mathrm{in}})$] {nbsp}
2172
[gray]#// This is only a table lookup, palookup[shade_index][latexmath:[$i_{\mathrm{in}}$]]# +
2173
==========
2174
 
4337 helixhorne 2175
Here, latexmath:[$C$] is a positive constant and
4239 helixhorne 2176
latexmath:[$\mathrm{visdist}$] is the product of a. the distance of an object's
2177
sampled pixel to the view plane with b. the object's
2178
``visibility''.footnote:[Visibility would be more appropriately called
2179
``anti-visibility'' or ``co-visibility'': greater values make objects appear
2180
more faded for the same distance. Also, the visibility that is meant here has
2181
the origin at 0, unlike `sector[].visibility`.] Thus, shade and visibility are
4337 helixhorne 2182
inherently confounded in the 8-bit mode and the ultimate shade_index is bounded
2183
below by (the minimum of latexmath:[$\mathrm{Numshades}-1$] and) the shade of
2184
the object.
4239 helixhorne 2185
 
2186
===== Examples of effects using shade tables
2187
 
2188
While palookup tables are primarily used for shading and visibility
2189
attenuation, they can be set up in other ways to yield different effects with
2190
respect to how pixels of objects farther away are drawn. For example:
2191
 
2192
* Distance fading with fog. For a fog color latexmath:[$\mathbf{c} = (c_r, c_g,
2193
  c_b)$], the table is set up so that for a source color index latexmath:[$i$]
2194
  and a shade level sh, palookup[sh][latexmath:[$i$]] contains a color index
2195
  whose color is close to that of latexmath:[$i$] blended with
2196
  latexmath:[$\mathbf{c}$], +
2197
  +
2198
  {nbsp} latexmath:[$\frac{\mathrm{sh} + 0.5}{\mathrm{Numshades}} \cdot
2199
  \mathrm{basepal}(i) +
2200
  \frac{\mathrm{Numshades}-\mathrm{sh}+0.5}{\mathrm{Numshades}} \cdot
2201
  \mathbf{c}$]. +
2202
  +
2203
  Note that distance fading to black can be seen as a special case of this
2204
  fogging effect. However, Duke3D's base shade table (i.e. the table for pal
2205
  0) is *not* constructed in this way.
2206
 
2207
* Color index remapping. Given a mapping latexmath:[$m: \: \mathrm{ColorIndex}
2208
  \rightarrow \mathrm{ColorIndex}$], the table is set up so that for each shade
2209
  level sh, the 256 color indices are selected or reordered in the same way:
2210
  for all color indices latexmath:[$i$],
2211
  palookup[sh][latexmath:[$i$]]{nbsp}={nbsp}original_palookup[sh][latexmath:[$m(i)$]]. +
2212
  For example, pal 21 remaps the fifth and sixth blocks of consecutive
2213
  16-tuples of color indices (a ramp of blue colors) to the fourth and 14^th^
2214
  such blocks (red colors, the first one part of a 32-color ramp).
2215
 
2216
* ``Fullbright'' colors -- those that aren't affected by distance -- with index
2217
  latexmath:[$i$] are achieved by setting palookup[sh][latexmath:[$i$]] to
2218
  palookup[0][latexmath:[$i$]] for each shade sh.
2219
 
4262 helixhorne 2220
===== Shade table functions
4239 helixhorne 2221
 
4262 helixhorne 2222
`sht = engine.shadetab()`::
2223
 
2224
Creates and returns a new shade table object `sht` with all entries initialized
2225
to zero. This object can be indexed once with a shade index from 0 to 31,
2226
yielding a reference to an array of 256 8-bit unsigned integers. Thus, shade
2227
table objects can be used just as indicated in the notation above: `sht[sh][i]`
2228
is the resulting color index for shade `sh` and input color index `i`.
2229
 
2230
`sht = engine.getshadetab(palnum)`::
2231
 
2232
Returns a new shade table object `sht` containing the values for the palookup
2233
table of pal `palnum`, provided it is not an alias for the default one (see
2234
below). Modifying the returned `sht` does not alter the actual engine-side
2235
shade table. An unspecified number of pal indices are reserved from the end of
2236
the hard limit 255; attempting to retrieve a shade table for a reserved pal
2237
raises as error.
2238
+
2239
At engine initialization, the shade tables for all non-zero pal numbers are
2240
aliased to the default pal 0 one. Subsequently, custom palookup tables are
2241
either loaded from LOOKUP.DAT, created by appropriate DEF directives (`fogpal`
2242
or `makepalookup`), or assigned using `engine.setshadetab`. If the table for
2243
pal `palnum` is aliased to the default one when `getshadetab` is called, *nil*
2244
is returned.
2245
 
4307 helixhorne 2246
[[engine_setshadetab]] `engine.setshadetab(palnum, sht)`::
4262 helixhorne 2247
 
2248
Copies the shade table `sht` to the engine-side palookup table for pal
2249
`palnum`. An error is issued if an attempt is made to copy to a reserved
2250
`palnum`.
2251
+
2252
When running in EDuke32, there are additional restrictions:
2253
+
2254
* A `palnum` for which a shade table has already been registered (that is, one
2255
  which is *not* aliased to the default one) cannot be re-assigned to.
2256
+
2257
* `setshadetab` may only be called at first initialization time, that is, when
2258
  the value of `LUNATIC_FIRST_TIME` is *true*. (`LUNATIC_FIRST_TIME` is a
2259
  variable in the global environment that indicates whether the Lua game state
2260
  is created for the very first time and the game is not yet running.)
2261
 
2262
===== Shade table methods
2263
 
2264
`newsht = sht:remap16(tab)`::
2265
 
4332 helixhorne 2266
Returns a new shade table with consecutive runs of 16 values of every 256-tuple
2267
of `sht` remapped as specified by `tab`. Specifically, `tab` must be a table
2268
whose keys in [0 .. 15] may be set to values in [0 .. 15]. For a shade index
2269
`sh` and a color index `i`, the returned shade table `newsht` then has
4262 helixhorne 2270
+
4332 helixhorne 2271
==========
2272
`newsht[sh][i]` = `sht[sh][newi]`,
2273
==========
2274
+
2275
where
2276
+
2277
==========
2278
`newi` = `16*tab[math.floor(i/16)] + i%16` {nbsp} [gray]#// if `tab[math.floor(i/16)]` is non-*nil*# +
2279
`newi` = `i` {nbsp} [gray]#// otherwise#
2280
==========
2281
+
4262 helixhorne 2282
.Example
2283
[source]
2284
----------
4332 helixhorne 2285
-- Creates a shade table with the same remapping as pal 21 (blue -> red) and
2286
-- registers it under pal 22, overwriting its previous contents.
2287
local newsht = engine.getshadetab(0):remap16({[4]=13, [5]=8})
2288
engine.setshadetab(22, newsht)
4262 helixhorne 2289
----------
2290
 
4337 helixhorne 2291
[[blending_table_interfaces]]
4307 helixhorne 2292
Blending table interfaces
2293
^^^^^^^^^^^^^^^^^^^^^^^^^
4262 helixhorne 2294
 
4307 helixhorne 2295
EDuke32 supports installing multiple blending tables used by the 8-bit
2296
renderer. A blending (or translucency) table is used whenever an object with
2297
the ``translucent'' bit set is drawn, and maps pairs of color indices to a
2298
blended color index.
2299
**********
2300
latexmath:[$\mathrm{transluc}: \: \mathrm{ColorIndex} \times
2301
  \mathrm{ColorIndex} \rightarrow \mathrm{ColorIndex}$]
2302
**********
2303
 
2304
Given a background color index `bi` and a color index of an incoming foreground
2305
fragment `fi` (usually obtained by looking up a shade table), when `fi` is
2306
different from 255, the resulting color index is
2307
==========
2308
`transluc[bi][fi]`
2309
==========
2310
if the ``reverse translucency'' bit is clear, and
2311
==========
2312
`transluc[fi][bi]`
2313
==========
2314
if reverse tranlucency is set. If the fragment sampled from the foreground
2315
object has color index 255, it is discarded: translucent rendering is always
2316
``masking''.
2317
 
2318
Currently, only sprites support rendering with custom blending tables, by
2319
setting their `.blend` member to the number of a blending table.
2320
 
2321
 
2322
===== Blending table functions
2323
 
2324
`tab = engine.blendtab()`::
2325
 
2326
Creates and returns a new blending table object `tab` with all entries initialized
2327
to zero. This object can be indexed once with a color index from 0 to 255,
2328
yielding a reference to an array of 256 8-bit unsigned integers. Thus, blending
2329
table objects can be used just as indicated in the notation above: `tab[i][j]`
2330
is the blended color index for input color indices `i` and `j`.
2331
 
2332
`tab = engine.getblendtab(blendnum)`::
2333
 
2334
Returns a new blending table object `tab` containing the values for the
2335
engine-side translucency table numbered `blendnum`, or *nil* if no blending
2336
table with that number is registered. Modifying the returned `tab` does not
2337
alter the actual engine-side blending table.
2338
//+
2339
//At engine initialization, the default translucency table (with number 0) is
2340
//loaded from PALETTE.DAT.
2341
 
2342
`engine.setblendtab(blendnum, tab)`::
2343
 
2344
Copies the blending table `tab` to the engine-side translucency table with
2345
number `blendnum`.
2346
+
2347
Similar to <<engine_setshadetab,`engine.setshadetab`>>, there are certain
2348
restrictions when running in EDuke32:
2349
+
2350
* A `blendnum` for which a table has already been registered cannot be
2351
  re-assigned to.
2352
+
2353
* `setblendtab` may only be called at first initialization time, that is, when
2354
  the value of `LUNATIC_FIRST_TIME` is *true*.
2355
 
4312 helixhorne 2356
Mapster32-only functions
2357
^^^^^^^^^^^^^^^^^^^^^^^^
4307 helixhorne 2358
 
4312 helixhorne 2359
===== `engine.savePaletteDat(filename [, palnum [, blendnum [, moreblends]]])` -> `ok, errmsg`
2360
 
2361
Writes out a full PALETTE.DAT-formatted file named `filename` with the base
2362
shade table numbered `palnum` and the base translucency table numbered
2363
`blendnum`, both defaulting to 0.
2364
 
2365
Passing `moreblends` allows to specify additional blending tables to store in
2366
EDuke32's extended PALETTE.DAT format. These must have previously been
2367
registered with `engine.setblendtab`. The `moreblends` argument must be a
2368
sequence table with each element being either
2369
 
2370
* a blending table number in the range [1{nbsp}..{nbsp}255]
2371
* a table `t` containing a pair of such numbers, in which case it is taken to
2372
  mean the inclusive range [`t[1]`{nbsp}..{nbsp}`t[2]`]
2373
 
2374
There must be no duplicate blending table numbers.
2375
 
2376
The function returns a status `ok` which is *true* on success and *nil* on
2377
failure. In the latter case, `errmsg` is a diagnostic error message.
2378
 
4336 helixhorne 2379
===== `engine.saveLookupDat(filename, lookups)` -> `ok, errmsg`
4312 helixhorne 2380
 
4336 helixhorne 2381
Writes out a LOOKUP.DAT-formatted file named `filename` with the lookup tables
2382
specified by `lookups` at the beginning and the five additional base palettes
2383
at the end.
2384
 
2385
The `lookups` argument is interpreted analogously to the `moreblends` argument
2386
of `engine.savePaletteDat` (with the numbers being palookup numbers instead of
2387
blending table numbers) and the return values `ok` and `errmsg` have the same
2388
meaning as well.
2389
 
2390
 
4147 helixhorne 2391
The `fs` module -- virtual file system facilities
2392
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2393
 
4153 helixhorne 2394
[float]
2395
==== `files = fs.listpath(path, mask)`
4147 helixhorne 2396
 
4189 helixhorne 2397
Returns a sequence table `files` of file names that can be found in a directory
2398
constructed as concatenation of any directory in the search path with `path`,
2399
and matching the wildcard `mask`. Currently, neither ZIP nor GRP files
2400
registered as file containers with EDuke32 are searched.
4147 helixhorne 2401
 
4189 helixhorne 2402
The `path` argument must separate directories by forward slashes (`/`). If no
2403
suffix is desired (i.e. the directories in the search path themselves are to be
2404
searched), `'/'` should be passed.
4147 helixhorne 2405
 
4189 helixhorne 2406
The file name `mask` is applied case-insensitively for the 26 characters of the
2407
basic Latin alphabet. It may contain the following meta-characters which are
2408
interpreted in a special way:
2409
 
2410
* a `*` matches any (potentially empty) sequence of characters
2411
* a `?` matches any single character
2412
 
2413
While the match with `mask` proceeds case-insensitively, file names are
2414
returned named exactly like on the file system. However, names differing only
2415
in case appear exactly once in the output list.
2416
 
2417
NOTE: For portability, it is crucial that `path` is specified with the same
2418
case as the actual directory on the file system.
2419
 
2420
.Example
2421
 
2422
Suppose the search path contains two directories `foo` and `bar` with the
2423
following file listing:
2424
----------
2425
foo/
2426
  myhouse1.MAP
2427
  myhouse2.map
2428
 
2429
bar/
2430
  MYHOUSE1.map
2431
  MYHOUSE10.MAP
2432
  README.txt
2433
----------
2434
 
2435
Then a query with
2436
[source]
2437
----------
2438
fs.listpath("/", "myhouse?.map")
2439
----------
2440
will return a table with
2441
these strings:
2442
 
2443
* `myhouse1.MAP` or `MYHOUSE1.map`, but not both
2444
* `myhouse2.map`
2445
 
2446
 
4032 helixhorne 2447
/////////////////
2448
APPENDICES FOLLOW
2449
/////////////////
2450
 
2451
:numbered!:
2452
 
2453
[appendix]
4035 helixhorne 2454
[[Appendix_Howto_read_PIL]]
2455
How to read _Programming in Lua_
2456
--------------------------------
2457
 
2458
:PiL50: http://www.lua.org/pil/contents.html
2459
 
2460
On the Lua homepage, the first edition of _Programming in Lua_ is
2461
{PiL50}[available] online. While targeting Lua 5.0, it still remains applicable
2462
to Lua 5.1 to a large extent. This section gives hints for reading it when
2463
learning to code for Lunatic.
2464
 
2465
[float]
2466
==== http://www.lua.org/pil/p1.html[Preface]
2467
 
4202 helixhorne 2468
May be interesting to get an idea of the philosophy behind Lua.
4035 helixhorne 2469
http://www.lua.org/pil/p1.3.html[A Few Typographical Conventions] should be
2470
read to be familiar with them.
2471
 
2472
[float]
2473
==== http://www.lua.org/pil/1.html[1 -- Getting Started]
2474
 
2475
Mentions the stand-alone Lua interpreter. When none is available, a LuaJIT
2476
stand-alone binary can be used for experimentation as well.
2477
 
2478
[float]
2479
==== http://www.lua.org/pil/1.1.html[1.1 -- Chunks]
2480
 
2481
Introduces chunks as the basic ``blocks'' of Lua code and notes how whitespace
2482
is treated. Mentions `dofile`, which is not available in Lunatic
2483
(<<require,`require`>> is preferred).
2484
 
2485
[float]
2486
==== http://www.lua.org/pil/1.2.html[1.2 -- Global Variables]
2487
 
2488
Section may be read, but usage of *`local`* variables is strongly recommended
4202 helixhorne 2489
whenever possible. Also, trying to read a non-existent global or to write any
4035 helixhorne 2490
value to the global environment gives an error in Lunatic (except that global
2491
writes are allowed in in <<modules,module>> context, i.e. after `module(...)`).
2492
 
2493
[float]
2494
==== http://www.lua.org/pil/1.3.html[_1.3 -- Some Lexical Conventions_]
2495
 
2496
Must read.
2497
 
2498
[float]
2499
==== http://www.lua.org/pil/2.html[_2 -- Types and Values_]
2500
 
2501
Must read, also subsections. However, ``2.7 -- Userdata and Threads'' is
2502
not relevant.
2503
 
2504
[float]
2505
==== http://www.lua.org/pil/3.html[_3 -- Expressions_]
2506
 
2507
Must read, also all subsections.
2508
 
2509
[float]
2510
==== http://www.lua.org/pil/4.html[_4 -- Statements_]
2511
 
2512
Must read, also all subsections.
2513
 
2514
[float]
2515
==== http://www.lua.org/pil/5.htmlhttp://www.lua.org/pil/5.html[_5 -- Functions_]
2516
 
2517
Must read, also all subsections. Subsection 5.2 mentions `io.write`, which is
2518
not available in Lunatic.
2519
 
2520
[float]
2521
==== http://www.lua.org/pil/6.html[6 -- More about Functions]
2522
 
2523
May be read (subsections as well) for a more complete understanding of
2524
functions in Lua, as well as the utility of lexical scoping.
2525
 
2526
[float]
2527
==== http://www.lua.org/pil/7.html[_7 -- Iterators and the Generic_ `for`]
2528
 
2529
May be read (subsections as well), but for basic programming, the knowledge of
2530
how to merely use (as opposed to write) iterators such as
2531
<<engine_iterators,`spritesofsect`>> suffices.
2532
 
2533
[float]
2534
==== http://www.lua.org/pil/8.3.html[8.3 -- Errors]
2535
 
2536
May be read. Provides guidelines on how to write error handling (status code
2537
vs. error).
2538
 
2539
[float]
2540
==== http://www.lua.org/pil/8.4.html[8.4 -- Error Handling and Exceptions]
2541
 
2542
May be read. Discusses protected calls, which should be used sparingly.
2543
 
2544
[float]
2545
==== http://www.lua.org/pil/11.html[_11 -- Data Structures_]
2546
 
2547
May be read, also subsections. The most relevant subsections are
2548
http://www.lua.org/pil/11.1.html[11.1 -- Arrays],
2549
http://www.lua.org/pil/11.5.html[11.5 -- Sets and Bags] and to some extent,
2550
http://www.lua.org/pil/11.6.html[11.6 -- String Buffers]. The way ``11.2 --
2551
Matrices and Multi-Dimensional Arrays'' suggests to construct matrices is
2552
rather memory-intensive; also it and ``11.3 -- Linked Lists'' and ``11.4 --
2553
Queues and Double Queues'' are not relevant to simple Lunatic coding.
2554
 
2555
[float]
2556
==== http://www.lua.org/pil/15.html[15 -- Packages]
2557
 
2558
Lua package system received various additions in 5.1, so the PiL first
2559
edition's section is out-of-sync. For Lunatic, the <<modules,modules>> section
2560
of this manual should be consulted.
2561
 +
2562
 +
2563
(The rest of Part II deals with advanced concepts not needed for simple Lunatic
2564
coding.)
2565
 
2566
[float]
2567
==== http://www.lua.org/pil/19.3.html[19.3 -- Sort]
2568
 
2569
May be read if needed.
2570
 
2571
[float]
2572
==== http://www.lua.org/pil/20.html[20 -- The String Library]
2573
 
2574
May be skimmed (also subsections), though ultimately the Lua Reference should
2575
be consulted for the exact semantics.
2576
 
2577
[appendix]
2578
[[Appendix_event_RETURN]]
4032 helixhorne 2579
Game event `RETURN` usage
2580
-------------------------
2581
 
2582
The following list notes how the special <<gv_RETURN,`gv.RETURN`>> variable
2583
(known simply as `RETURN` from CON) is treated for the various events. The game
2584
may either pass some value to a particular event as additional information, or
2585
it can examine `RETURN` after the event has finished, invoking some behavior
2586
conditional on its value. If an event is not listed here, its usage of `RETURN`
2587
is unspecified.
2588
 
2589
[float]
2590
Receives zero, checks for non-zero
2591
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2592
 
2593
These events get passed a value of 0 for `RETURN`, and after finishing, check
2594
it for being non-zero, in which case some hard-coded behavior is suppressed:
2595
 
2596
`AIMDOWN`, `AIMUP`, `CROUCH`, `DISPLAYSBAR`, `DISPLAYWEAPON`, `DOFIRE`,
2597
`DRAWWEAPON`, `FIRE`, `HOLODUKEOFF`, `HOLODUKEON`, `HOLSTER`, `INCURDAMAGE`,
2598
`INVENTORY`, `JUMP`, `LOOKDOWN`, `LOOKLEFT`, `LOOKRIGHT`, `LOOKUP`,
2599
`QUICKKICK`, `RETURNTOCENTER`, `SOARDOWN`, `SOARUP`, `SWIMDOWN`, `SWIMUP`,
2600
`TURNAROUND`, `USEJETPACK`, `USEMEDKIT`, `USENIGHTVISION`, `USESTEROIDS`.
2601
 
2602
`KILLIT` (deprecated from Lua)::
2603
    If non-zero, the pending sprite deletion is aborted.
2604
 
2605
`DISPLAYROOMS`::
2606
    Don't draw scene if `RETURN` is 1. Values other than 0 and 1 are
2607
    reserved.
2608
 
2609
`PRESSEDFIRE`, `USE`::
2610
    If non-zero, the ``fire'' or ``use'' shared key bits are cleared
2611
    (respectively).
2612
 
2613
[float]
2614
Game considers post-event `RETURN` an index
2615
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
2616
 
2617
For some events, the game examines `RETURN` after they have finished, and
2618
potentially uses its value as some kind of index.
2619
 
2620
`CHANGEMENU` (deprecated from Lua)::
2621
    Receives and examines `RETURN` as a menu index to change to.
2622
 
2623
`DISPLAYCROSSHAIR`::
2624
    Receives 0. If the post-event `RETURN` equals 1, no crosshair is drawn. If
2625
    it is greater than one, `RETURN` is the tile index of the crosshair to be
2626
    displayed. The value 0 makes it draw using the `CROSSHAIR` tile.
2627
 
2628
`GETLOADTILE`::
2629
    Receives and examines `RETURN` as a background tile for the loading screen.
2630
    A negative value suppresses drawing it and running the subsequent
2631
    `EVENT_DISPLAYLOADINGSCREEN` entirely.
2632
 
2633
`GETMENUTILE`::
2634
    Receives and examines `RETURN` as a background tile for the menu.
2635
 
2636
`SOUND`::
2637
    Receives and examines `RETURN` as an index of a sound to start playing.
2638
 
2639
[float]
2640
Cheat events
2641
~~~~~~~~~~~~
2642
The cheat events receive a hard-coded, item-dependent target amount in
2643
`RETURN`. It can be overridden to a different value to make the respective
2644
cheat give a different ``full'' amount. A negative value is ignored.
2645
 
2646
`CHEATGETSTEROIDS`, `CHEATGETHEAT`, `CHEATGETBOOT`, `CHEATGETSHIELD`,
2647
`CHEATGETSCUBA`, `CHEATGETHOLODUKE`, `CHEATGETJETPACK`, `CHEATGETFIRSTAID`.
2648
 
2649
[float]
4206 helixhorne 2650
`EVENT_DAMAGEHPLANE`
2651
~~~~~~~~~~~~~~~~~~~~
2652
 
2653
Triggered when a ceiling or a floor (collectively called ``hplane'') is
4208 helixhorne 2654
determined as being damaged. The event receives `RETURN` in the variable
2655
`gv.RETURN` as well as the third, `dist` argument to the event
2656
<<gameactor,callback function>>.footnote:[Passing `RETURN` in the `dist`
2657
argument serves the possibility to create chained callbacks for
2658
`EVENT_DAMAGEHPLANE`. Otherwise, once `gv.RETURN` were assigned to, there would
2659
be no way to obtain its original value in subsequent chained callbacks.] This
2660
value can be decoded into two parts by passing it to
2661
`sector.damagehplane_whatsect`:
4206 helixhorne 2662
 
2663
[source]
2664
----------
4208 helixhorne 2665
function(aci, pli, RETURN)
2666
   local what, sectnum = sector.damagehplane_whatsect(RETURN)
2667
   -- (...)
4206 helixhorne 2668
----------
2669
Then,
2670
 
2671
* `what` is one of the strings `'ceiling'` or `'floor'` and
2672
* `sectnum` is the sector whose hplane is considered to be damaged.
2673
 
4208 helixhorne 2674
When `EVENT_DAMAGEHPLANE` is left, `gv.RETURN` is examined to determine the
4206 helixhorne 2675
further action. It may be one of three values given by `sector.DAMAGEHPLANE`
2676
(abbreviated `DHP` in the following):
2677
 
2678
* `DHP.SUPPRESS`: the hard-wired code that would subsequently be run is
2679
  suppressed entirely
2680
 
2681
* `DHP.DEFAULT`: The default code for hplane damaging is run. For floors, it
2682
  does nothing. For ceilings, it checks whether it has a tile number in a
2683
  hard-coded set of values depicting a breakable light. In that case, the tile
2684
  number is changed to the ``broken'' version and a ``glass breaking'' effect
2685
  consisting of playing a sound and spawning glass sprites is started. Also,
2686
  certain code related to SE3 and SE12 effects is run.
2687
 
2688
* `DHP.GLASSBREAK`: The light-breaking effect described above is run
2689
  unconditionally, but *without* changing the hplane's tile number, which is
2690
  assumed to have been done by the event.
2691
 
2692
If value last assigned to `RETURN` is not one in the above-mentioned set when
2693
`EVENT_DAMAGEHPLANE` is left, the behavior is undefined.
2694
 
2695
 
2696
[float]
4032 helixhorne 2697
TODO
2698
~~~~
2699
`CHANGEWEAPON`, `CHECKFLOORDAMAGE`, `CHECKTOUCHDAMAGE`, `NEXTWEAPON`,
2700
`PREVIOUSWEAPON`, `SELECTWEAPON`, `WEAPKEY*`.