splash particles
[dd2d.git] / dengapi.d
blobe9e863209ea043826109d13ea58a80d74bcce9db
1 /* DooM2D: Midnight on the Firing Line
2 * coded by Ketmar // Invisible Vector <ketmar@ketmar.no-ip.org>
3 * Understanding is not required. Only obedience.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18 module dengapi is aliced;
20 private:
21 import core.atomic;
22 import core.thread;
23 import core.time;
25 import iv.glbinds;
26 import glutils;
27 import console;
28 import wadarc;
30 import d2dmap;
31 import d2dadefs;
32 import d2dgfx;
33 import dacs;
35 import d2dunigrid;
38 // ////////////////////////////////////////////////////////////////////////// //
39 private extern (C) void _d_print_throwable (Throwable t);
42 // ////////////////////////////////////////////////////////////////////////// //
43 import arsd.color;
44 import arsd.png;
47 // ////////////////////////////////////////////////////////////////////////// //
48 public {
49 enum PLK_UP = (1<<0);
50 enum PLK_DOWN = (1<<1);
51 enum PLK_LEFT = (1<<2);
52 enum PLK_RIGHT = (1<<3);
53 enum PLK_FIRE = (1<<4);
54 enum PLK_JUMP = (1<<5);
55 enum PLK_USE = (1<<6);
58 __gshared uint plrKeysLast;
59 __gshared uint plrKeyState;
62 public void plrKeyDown (uint plidx, uint mask) {
63 if (mask == 0 || plidx > 0) return;
64 plrKeysLast |= mask;
65 plrKeyState |= mask;
69 public void plrKeyUp (uint plidx, uint mask) {
70 if (mask == 0 || plidx > 0) return;
71 plrKeyState &= ~mask;
75 public void plrKeyUpDown (uint plidx, uint mask, bool down) {
76 if (down) plrKeyDown(plidx, mask); else plrKeyUp(plidx, mask);
80 void plrKeysFix (uint plidx) {
81 if (plidx > 0) return;
82 //conwritefln!"plrKeyState=0x%02x; plrKeysLast=0x%02x"(plrKeyState, plrKeysLast);
83 foreach (uint n; 0..12) {
84 if ((plrKeyState&(1<<n)) == 0) plrKeysLast &= ~(1<<n);
89 // ////////////////////////////////////////////////////////////////////////// //
90 void updateActorClasses (int iteration) {
91 foreach (string ctype; dacsClassTypes(iteration)) {
92 foreach (auto mod; dacsClassModules(ctype, iteration)) {
93 auto adef = registerActorDef(mod.rmoduletype.classtype, mod.rmoduletype.classname);
94 conwriteln("found info for actor '", mod.rmoduletype.classtype, ":", mod.rmoduletype.classname, "'");
96 auto animInitFn = FuncPool.findByFQMG(mod.name~".initializeAnim", ":void");
97 if (animInitFn !is null) adef.setAnimInitFunc(animInitFn);
100 auto initFn = FuncPool.findByFQMG(mod.name~".initialize", ":void:Actor");
101 if (initFn !is null) adef.setInitFunc(initFn);
104 auto thinkFn = FuncPool.findByFQMG(mod.name~".think", ":void:Actor");
105 if (thinkFn !is null) adef.setThinkFunc(thinkFn);
112 // ////////////////////////////////////////////////////////////////////////// //
113 private string modLoader (string modname) {
114 static string getTextFile (string fname) {
115 try {
116 auto res = loadTextFile(fname);
117 conwriteln("loading DACS module file '", fname, "' (", res.length, " bytes)");
118 if (res is null) res = "";
119 return res;
120 } catch (Exception) {}
121 return null;
124 string res;
126 //res = getTextFile(modname~".dacs");
127 //if (res !is null) return res;
129 res = getTextFile("scripts/"~modname~".dacs");
130 if (res !is null) return res;
131 assert(res is null);
133 string[] parts = ["scripts"];
134 string mn = modname;
135 while (mn.length > 0) {
136 int pos = 0;
137 if (mn[0] >= 'A' && mn[0] <= 'Z') ++pos;
138 while (pos < mn.length && (mn[pos] < 'A' || mn[pos] > 'Z')) ++pos;
139 if (mn[0] >= 'A' && mn[0] <= 'Z') {
140 parts ~= cast(char)(mn[0]+32)~mn[1..pos];
141 } else {
142 parts ~= mn[0..pos];
144 mn = mn[pos..$];
147 import std.array : join;
148 string path = parts.join("/")~".dacs";
149 res = getTextFile(path);
150 if (res !is null) return res;
151 assert(res is null);
153 assert(res is null);
154 throw new Exception("module '"~modname~"' not found");
158 __gshared int modIteration = 0;
160 public void loadWadScripts () {
161 if (moduleLoader is null) moduleLoader = (string modname) => modLoader(modname);
162 string[] mainmods;
163 try {
164 import std.array : split;
165 auto t = loadTextFile("scripts/dacsmain.txt");
166 foreach (string line; t.split('\n')) {
167 while (line.length && line[0] <= ' ') line = line[1..$];
168 if (line.length == 0 || line[0] == ';') continue;
169 while (line.length && line[$-1] <= ' ') line = line[0..$-1];
170 mainmods ~= line;
172 } catch (Exception e) { return; }
173 try {
174 //conwriteln("loading main DACS module '", mainmod, "'");
175 auto iter = modIteration++;
176 conwriteln("iteration=", iter);
177 foreach (string mod; mainmods) {
178 parseModule(mod, iter);
180 conwriteln("calling parseComplete; iteration=", iter);
181 parseComplete();
182 updateActorClasses(iter);
183 } catch (CompilerException e) {
184 _d_print_throwable(e);
185 conwriteln("PARSE ERROR: ", e.file, " at ", e.line);
186 conwriteln(e.toString);
187 assert(0);
192 public void scriptLoadingComplete () {
193 setupDAPI();
194 dacsFinalizeCompiler();
198 // ////////////////////////////////////////////////////////////////////////// //
199 public __gshared LevelMap map;
200 //public __gshared DACSVM dvm;
201 public __gshared uint prngSyncSeed = 0x29a;
202 public __gshared uint prngSeed = 0x29a; // unsynced
205 // ////////////////////////////////////////////////////////////////////////// //
206 // Park-Miller-Carta Pseudo-Random Number Generator, based on David G. Carta paper
207 // 31 bit of randomness
208 // seed is previous result, as usual
209 public uint prngR31next (uint seed) {
210 if (seed == 0) seed = 0x29a;
211 uint lo = 16807*(seed&0xffff);
212 uint hi = 16807*(seed>>16);
213 lo += (hi&0x7fff)<<16;
214 lo += hi>>15;
215 //if (lo > 0x7fffffff) lo -= 0x7fffffff; // should be >=, actually
216 lo = (lo&0x7FFFFFFF)+(lo>>31); // same as previous code, but branch-less
217 return lo;
221 // "synced" random, using common seed for all players
222 public uint syncrandu31 () {
223 pragma(inline, true);
224 return (prngSyncSeed = prngR31next(prngSyncSeed));
228 // "unsynced" random, seed isn't saved
229 public uint unsyncrandu31 () {
230 pragma(inline, true);
231 return (prngSeed = prngR31next(prngSeed));
235 // ////////////////////////////////////////////////////////////////////////// //
236 version(dacs_use_vm) {
237 // this is VAT function, argument order is reversed
238 void doWrite(bool donl) (FuncPool.FuncInfo fi, DACSVM vm) {
239 import std.stdio;
240 auto count = vm.popInt();
241 while (count-- > 0) {
242 auto type = vm.popInt();
243 switch (cast(VATArgType)type) {
244 case VATArgType.Int: write(vm.popInt()); break;
245 case VATArgType.Uint: write(vm.popUint()); break;
246 case VATArgType.Float: write(vm.popFloat()); break;
247 case VATArgType.StrId: write(StrId(vm.popUint()).get); break;
248 case VATArgType.ActorId: write("<actor>"); vm.popUint(); break; //TODO
249 default: write("<invalid-type>"); vm.popUint(); break; //TODO
252 static if (donl) writeln();
253 // push dummy return value
254 vm.pushInt(0);
256 } else {
257 extern(C) void doWrite(bool donl) (uint argc, ...) {
258 import core.vararg;
259 import std.stdio;
260 mainloop: while (argc >= 2) {
261 argc -= 2;
262 int tp = va_arg!int(_argptr);
263 switch (tp) {
264 case VATArgType.Int:
265 auto v = va_arg!int(_argptr);
266 write(v);
267 break;
268 case VATArgType.Uint:
269 auto v = va_arg!uint(_argptr);
270 write(v);
271 break;
272 case VATArgType.Float:
273 auto v = va_arg!float(_argptr);
274 write(v);
275 break;
276 case VATArgType.StrId:
277 auto v = StrId(va_arg!uint(_argptr)).get;
278 write(v);
279 break;
280 case VATArgType.ActorId:
281 auto v = ActorId(va_arg!uint(_argptr));
282 write("<actor:", v.valid, ":", v.id, ">");
283 //write("<actor>");
284 break;
285 default: write("<invalid-type>"); break mainloop;
288 static if (donl) writeln();
293 // ////////////////////////////////////////////////////////////////////////// //
294 void animClearFrames (StrId classtype, StrId classname, StrId state) {
295 auto adef = findActorDef(classtype.get, classname.get);
296 if (adef is null) throw new Exception("animClearFrames: actor '"~classtype.get~":"~classname.get~"' not found!");
297 adef.clearFrames(state);
301 void animAddFrame (StrId classtype, StrId classname, StrId state, uint dir, StrId sprname) {
302 auto adef = findActorDef(classtype.get, classname.get);
303 if (adef is null) throw new Exception("animAddFrame: actor '"~classtype.get~":"~classname.get~"' not found!");
304 if (dir != 0) dir = 1; //TODO: process mirror flag here
305 adef.addFrame(state, dir, sprname);
309 // ////////////////////////////////////////////////////////////////////////// //
310 void setupDAPI () {
311 conwriteln("setting up D API");
313 FuncPool["write"] = &doWrite!false;
314 FuncPool["writeln"] = &doWrite!true;
316 FuncPool["syncrandu31"] = &syncrandu31;
318 FuncPool["animClearFrames"] = &animClearFrames;
319 FuncPool["animAddFrame"] = &animAddFrame;
321 FuncPool["actorSetAnimation"] = function void (ActorId me, StrId state) {
322 if (!me.valid) return;
323 if (auto adef = findActorDef(me.classtype!string, me.classname!string)) {
324 me.zAnimstate = state;
325 me.zAnimidx = 0;
329 //FuncPool["getPlayer"] = function ActorId () { assert(0); };
330 //FuncPool["isPlayer"] = function int (ActorId me) { return (me == players.ptr[0] ? 1 : 0); };
332 FuncPool["getPlayerCount"] = function int () => 1;
334 FuncPool["getPlayerActor"] = function ActorId (uint pnum) {
335 if (pnum == 1) return players.ptr[0];
336 return ActorId(0);
339 FuncPool["getPlayerButtons"] = function uint (uint pidx) { return (pidx == 1 ? plrKeysLast : 0); };
341 FuncPool["mapGetTypeTile"] = function int (int x, int y) {
342 return (map !is null && x >= 0 && y >= 0 && x < map.width && y < map.height ? map.tiles.ptr[LevelMap.Type].ptr[y*map.width+x] : 0);
345 FuncPool["mapGetTile"] = function int (uint layer, int x, int y) {
346 return (map !is null && x >= 0 && y >= 0 && x < map.width && y < map.height && layer >= 0 && layer <= 1 ? map.tiles.ptr[LevelMap.Front+layer].ptr[y*map.width+x] : 0);
349 FuncPool["mapSetTypeTile"] = function void (int x, int y, int tid) {
350 if (map is null || x < 0 || y < 0 || x >= map.width || y >= map.height || tid < 0 || tid > 255) return;
351 auto p = map.tiles.ptr[LevelMap.Type].ptr+y*map.width+x;
352 if (*p != tid) {
353 *p = cast(ubyte)tid;
354 import xmain_d2d : mapDirty;
355 mapDirty();
359 FuncPool["mapSetTile"] = function void (uint layer, int x, int y, int tid) {
360 if (map is null || layer < 0 || layer > 1 || x < 0 || y < 0 || x >= map.width || y >= map.height || tid < 0 || tid > 255) return;
361 auto p = map.tiles.ptr[LevelMap.Front+layer].ptr+y*map.width+x;
362 if (*p != tid) {
363 *p = cast(ubyte)tid;
364 import xmain_d2d : mapDirty;
365 mapDirty();
369 FuncPool["mapGetWaterTexture"] = function int (int fg) {
370 if (fg < 0 || fg >= map.wallnames.length) return 0;
371 switch (map.wallnames.ptr[fg]) {
372 case "_water_0": return 1;
373 case "_water_1": return 2;
374 case "_water_2": return 3;
375 default:
377 return 0;
380 FuncPool["getMapViewHeight"] = function int () {
381 import xmain_d2d : vlWidth, vlHeight, scale;
382 return vlHeight/scale;
385 FuncPool["setMapViewPos"] = function void (int x, int y) {
386 import xmain_d2d : setMapViewPos;
387 setMapViewPos(x, y);
390 FuncPool["actorsOverlap"] = function int (ActorId a, ActorId b) { return (actorsOverlap(a, b) ? 1 : 0); };
392 FuncPool["actorRemove"] = function void (ActorId me) { Actor.remove(me); };
394 FuncPool["rewindTouchList"] = &rewindTouchList;
395 FuncPool["getNextTouchListItem"] = &getNextTouchListItem;
397 FuncPool["getCheatNoDoors"] = function int () { import xmain_d2d : cheatNoDoors; return (cheatNoDoors ? 1 : 0); };
399 FuncPool["addMessage"] = function void (string text, int pause, bool noreplace) {
400 import xmain_d2d : addMessage;
401 addMessage(text, pause, noreplace);
404 import d2dparts : dotAddBlood, dotAddSpark, dotAddWater;
406 FuncPool["dotAddBlood"] = &dotAddBlood;
407 FuncPool["dotAddSpark"] = &dotAddSpark;
408 FuncPool["dotAddWater"] = &dotAddWater;
410 function void (int x, int y, int xv, int yv, int n, int color) {
411 conwriteln("dotAddWater: x=", x, "; y=", y, "; xv=", xv, "; yv=", yv, "; n=", n, "; color=", color);
412 dotAddWater(x, y, xv, yv, n, color);
418 public void registerAPI () {
419 //Actor.actorSize += 256;
420 conwriteln("actor size is ", Actor.actorSize, " bytes");
422 version(dacs_use_vm) FuncPool.vm = new DACSVM();
423 //dvm = new DACSVM();
425 // initialize actor animation
426 ActorDef.forEach((adef) => adef.callAnimInit());
428 conwriteln("API registered");
432 // ////////////////////////////////////////////////////////////////////////// //
433 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
434 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
435 mixin(Actor.FieldGetMixin!("x", int));
436 mixin(Actor.FieldGetMixin!("y", int));
437 mixin(Actor.FieldGetMixin!("dir", uint));
438 mixin(Actor.FieldGetMixin!("height", int));
439 mixin(Actor.FieldGetMixin!("radius", int));
440 mixin(Actor.FieldGetMixin!("flags", uint));
441 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
442 mixin(Actor.FieldGetMixin!("zAnimidx", int));
444 mixin(Actor.FieldSetMixin!("zAnimidx", int));
447 public bool actorsOverlap (ActorId a, ActorId b) {
448 if (!a.valid || !b.valid) return false;
449 if (a.id == b.id) return false; // no self-overlap
451 int ax = a.fget_x;
452 int bx = b.fget_x;
453 int ar = a.fget_radius;
454 int br = b.fget_radius;
456 if (ax-ar > bx+br || ax+ar < bx-br) return false;
458 int ay = a.fget_y;
459 int by = b.fget_y;
460 int ah = a.fget_height;
461 int bh = b.fget_height;
463 //return (ay > by-bh && ay-ah < by);
464 return (by-bh <= ay && by >= ay-ah);
468 // ////////////////////////////////////////////////////////////////////////// //
469 __gshared ActorId[2] players;
471 public void loadMapMonsters () {
472 assert(map !is null);
473 ugClear();
474 players[] = ActorId(0);
475 //conwriteln(players[0].valid, "; ", players[0].id);
476 foreach (ref thing; map.things) {
477 if (thing.dmonly) continue;
478 if (auto did = thing.type in d2dactordefsById) {
479 //if (did.classtype == "item") continue;
480 if (did.classtype == "playerstart") {
481 if (thing.type == 1 || thing.type == 2) {
482 int pnum = thing.type-1;
483 if (!players[pnum].valid) {
484 auto aid = Actor.alloc;
485 aid.classtype = StrPool.intern("monster");
486 aid.classname = StrPool.intern("Player");
487 aid.plrnum = cast(uint)(pnum+1);
488 aid.state = StrPool.MNST_SLEEP;
489 aid.x = cast(int)thing.x;
490 aid.y = cast(int)thing.y;
491 aid.dir = cast(uint)(thing.right ? 1 : 0);
492 auto adef = findD2DActorDef(thing.type);
493 if (adef is null) assert(0);
494 adef.callInit(aid);
495 if ((aid.flags!uint&AF_NOCOLLISION) == 0) ugActorModify!true(aid);
496 players[pnum] = aid;
497 conwriteln("player #", pnum+1, " aid is ", aid.id);
498 //FIXME: HACK!
500 if (pnum == 0) {
501 import xmain_d2d : setMapViewPos;
502 setMapViewPos(aid.x!int, aid.y!int);
507 continue;
510 auto adef = findD2DActorDef(thing.type);
511 if (adef is null) {
512 if (auto did = thing.type in d2dactordefsById) {
513 conwriteln("ignoring D2D thing '", did.classtype.get, ":", did.classname.get, "'");
514 } else {
515 conwriteln("ignoring unknown D2D thing with mapid ", thing.type);
517 continue;
519 // load graphics (we'll load all graphics)
520 //adef.loadGraphics();
521 // create actor and initialize it
522 auto aid = Actor.alloc;
523 aid.classtype = StrPool.intern(adef.classtype);
524 aid.classname = StrPool.intern(adef.classname);
525 //conwriteln("found '", aid.classtype.get, ":", aid.classname.get, "'");
526 if (auto did = thing.type in d2dactordefsById) {
527 assert(did.classtype == adef.classtype);
528 assert(did.classname == adef.classname);
529 conwriteln("mapid=", thing.type, "; ", adef.classtype, ":", adef.classname, "; id=", aid.id);
530 assert(aid.classtype!string == adef.classtype);
531 assert(aid.classname!string == adef.classname);
532 } else {
533 assert(0);
535 aid.state = StrPool.MNST_SLEEP;
536 aid.x = cast(int)thing.x;
537 aid.y = cast(int)thing.y;
538 aid.dir = cast(uint)(thing.right ? 1 : 0);
539 //if (aid.classtype!string == "item" && aid.x!int < 64) { aid.x = 92; aid.y = aid.y!int-16; conwriteln("!!!"); }
540 adef.callInit(aid);
541 if ((aid.flags!uint&AF_NOCOLLISION) == 0) ugActorModify!true(aid);
544 // create switches
545 foreach (ref sw; map.switches) {
546 if (sw.type == 0) continue; // just in case
547 auto swname = getD2DSwitchClassName(sw.type);
548 if (swname.length == 0) {
549 conwriteln("unknown switch type ", sw.type);
550 continue;
552 if (auto adef = findActorDef("switch", swname)) {
553 auto aid = Actor.alloc;
554 aid.classtype = StrPool.intern("switch");
555 aid.classname = StrPool.intern(swname);
556 // nocollision, 'cause collision checking will be processed in switch thinker, but other actors should not touch switches
557 aid.flags = AF_NOCOLLISION|AF_NOGRAVITY|AF_NOONTOUCH|AF_NODRAW|AF_NOLIGHT|AF_NOANIMATE;
558 aid.x = sw.x*8;
559 aid.y = sw.y*8;
560 aid.switchabf = (sw.a<<16)|(sw.b<<8)|sw.flags;
561 adef.callInit(aid);
562 if ((aid.flags!uint&AF_NOCOLLISION) == 0) ugActorModify!true(aid); // just in case
563 } else {
564 conwriteln("switch definition 'switch:", swname, "' not found");
568 ActorDef.forEach((adef) {
569 conwriteln("loading graphics for '", adef.classtype.get, ":", adef.classname.get, "'");
570 adef.loadGraphics();
572 //Actor.dumpActors();
574 conwriteln("initial snapshot size: ", Actor.snapshotSize, " bytes");
578 // ////////////////////////////////////////////////////////////////////////// //
579 __gshared uint[65536] touchList; // aids
580 __gshared uint[] realTouchList;
581 __gshared uint realTouchListIndex = uint.max;
582 __gshared ActorId curThinkingActor;
583 __gshared bool touchListAllowed = false;
586 // dacs API
587 void rewindTouchList () {
588 if (!touchListAllowed) return;
589 realTouchListIndex = 0;
590 realTouchList = ugActorHitList(curThinkingActor, touchList[]);
594 // dacs API
595 ActorId getNextTouchListItem () {
596 if (!touchListAllowed) return ActorId(0);
597 if (realTouchListIndex == uint.max) rewindTouchList();
598 while (realTouchListIndex < realTouchList.length) {
599 auto aid = ActorId(realTouchList.ptr[realTouchListIndex]);
600 ++realTouchListIndex;
601 if (aid.valid && (aid.flags!uint&AF_NOONTOUCH) == 0) return aid;
603 return ActorId(0);
607 public void doActorsThink () {
608 //FIXME
609 //static uint fflags = uint.max;
610 //if (fflags == uint.max) fflags = Actor.fields["flags"].ofs;
612 // we have too much memory!
613 __gshared uint[65536] validActorsList;
615 touchListAllowed = true;
616 scope(exit) touchListAllowed = false;
617 foreach (uint xid; Actor.getValidList(validActorsList[])) {
618 auto me = ActorId(xid);
619 if (me.valid) {
620 auto flags = me.fget_flags;
621 if ((flags&AF_NOCOLLISION) == 0) ugActorModify!false(me); // remove from grid
622 if (auto adef = findActorDef(me)) {
623 if ((flags&AF_NOTHINK) == 0) {
624 realTouchListIndex = uint.max;
625 curThinkingActor = me;
626 adef.callThink(me);
627 //if (me.x!int < 32) conwriteln("actor: ", me.id, "; attLightRGBX=", me.attLightRGBX!uint);
628 if (!me.valid) continue; // we are dead
629 flags = me.fget_flags; // in case script updated flags
631 if ((flags&AF_NOANIMATE) == 0) {
632 int aidx = me.fget_zAnimidx;
633 int nidx = adef.nextAnimIdx(me.fget_zAnimstate, me.fget_dir, aidx);
634 //conwriteln("actor ", me.id, " (", me.classtype!string, me.classname!string, "): state=", me.zAnimstate!string, "; aidx=", aidx, "; nidx=", nidx);
635 me.fset_zAnimidx = nidx;
636 //assert(me.fget_zAnimidx == nidx);
638 // put back to grid
639 if ((flags&AF_NOCOLLISION) == 0) ugActorModify!true(me);
643 plrKeysFix(0);
644 //{ import std.stdio : stdout; stdout.writeln("========================================="); }
645 //Actor.dumpActors();