sprite loader moved to separate module
[dd2d.git] / dengapi.d
blobfe1b8228c16be0892693d3e6910172860b1cc58f
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 d2dsprite;
34 import dacs;
36 import d2dunigrid;
37 import render;
40 // ////////////////////////////////////////////////////////////////////////// //
41 private extern (C) void _d_print_throwable (Throwable t);
44 // ////////////////////////////////////////////////////////////////////////// //
45 import arsd.color;
46 import arsd.png;
49 // ////////////////////////////////////////////////////////////////////////// //
50 public __gshared ActorId cameraChick;
53 // ////////////////////////////////////////////////////////////////////////// //
54 public void addInternalActorFields () {
55 // &0xffff: position in drawlist
56 // (>>16)&0xff: drawlist index
57 //Actor.addField("0drawlistpos", Actor.Field.Type.Uint);
61 // ////////////////////////////////////////////////////////////////////////// //
62 public {
63 enum PLK_UP = (1<<0);
64 enum PLK_DOWN = (1<<1);
65 enum PLK_LEFT = (1<<2);
66 enum PLK_RIGHT = (1<<3);
67 enum PLK_FIRE = (1<<4);
68 enum PLK_JUMP = (1<<5);
69 enum PLK_USE = (1<<6);
72 __gshared uint plrKeysLast;
73 __gshared uint plrKeyState;
76 public void plrKeyDown (uint plidx, uint mask) {
77 if (mask == 0 || plidx > 0) return;
78 plrKeysLast |= mask;
79 plrKeyState |= mask;
83 public void plrKeyUp (uint plidx, uint mask) {
84 if (mask == 0 || plidx > 0) return;
85 plrKeyState &= ~mask;
89 public void plrKeyUpDown (uint plidx, uint mask, bool down) {
90 if (down) plrKeyDown(plidx, mask); else plrKeyUp(plidx, mask);
94 void plrKeysFix (uint plidx) {
95 if (plidx > 0) return;
96 //conwritefln!"plrKeyState=0x%02x; plrKeysLast=0x%02x"(plrKeyState, plrKeysLast);
97 foreach (uint n; 0..12) {
98 if ((plrKeyState&(1<<n)) == 0) plrKeysLast &= ~(1<<n);
103 // ////////////////////////////////////////////////////////////////////////// //
104 void updateActorClasses () {
105 foreach (string ctype; dacsClassTypes) {
106 foreach (auto mod; dacsClassModules(ctype)) {
107 if (mod.rmoduletype.classtype == "map") {
108 // map scripts, not here
109 } else {
110 auto adef = registerActorDef(mod.rmoduletype.classtype, mod.rmoduletype.classname);
111 conwriteln("found info for actor '", mod.rmoduletype.classtype, ":", mod.rmoduletype.classname, "'");
113 auto animInitFn = FuncPool.findByFQMG(mod.name~".initializeAnim", ":void");
114 if (animInitFn !is null) adef.setAnimInitFunc(animInitFn);
117 auto initFn = FuncPool.findByFQMG(mod.name~".initialize", ":void:Actor");
118 if (initFn !is null) adef.setInitFunc(initFn);
121 auto thinkFn = FuncPool.findByFQMG(mod.name~".think", ":void:Actor");
122 if (thinkFn !is null) adef.setThinkFunc(thinkFn);
130 // ////////////////////////////////////////////////////////////////////////// //
131 private string modLoader (string modname) {
132 static string getTextFile (string fname) {
133 try {
134 auto res = loadTextFile(fname);
135 conwriteln("loading DACS module file '", fname, "' (", res.length, " bytes)");
136 if (res is null) res = "";
137 return res;
138 } catch (Exception) {}
139 return null;
142 string res;
144 //res = getTextFile(modname~".dacs");
145 //if (res !is null) return res;
147 res = getTextFile("scripts/"~modname~".dacs");
148 if (res !is null) return res;
149 assert(res is null);
151 string[] parts = ["scripts"];
152 string mn = modname;
153 while (mn.length > 0) {
154 int pos = 0;
155 if (mn[0] >= 'A' && mn[0] <= 'Z') ++pos;
156 while (pos < mn.length && (mn[pos] < 'A' || mn[pos] > 'Z')) ++pos;
157 if (mn[0] >= 'A' && mn[0] <= 'Z') {
158 parts ~= cast(char)(mn[0]+32)~mn[1..pos];
159 } else {
160 parts ~= mn[0..pos];
162 mn = mn[pos..$];
165 import std.array : join;
166 string path = parts.join("/")~".dacs";
167 res = getTextFile(path);
168 if (res !is null) return res;
169 assert(res is null);
171 assert(res is null);
172 throw new Exception("module '"~modname~"' not found");
176 __gshared string[] dacsModules;
178 public void registerWadScripts () {
179 try {
180 import std.array : split;
181 auto t = loadTextFile("scripts/dacsmain.txt");
182 foreach (string line; t.split('\n')) {
183 while (line.length && line[0] <= ' ') line = line[1..$];
184 if (line.length == 0 || line[0] == ';' || line[0] == '#') continue;
185 while (line.length && line[$-1] <= ' ') line = line[0..$-1];
186 import std.algorithm : canFind;
187 if (!dacsModules.canFind(line)) dacsModules ~= line;
189 } catch (Exception e) { return; }
193 public void loadWadScripts () {
194 if (moduleLoader is null) moduleLoader = (string modname) => modLoader(modname);
195 try {
196 //conwriteln("loading main DACS module '", mainmod, "'");
197 foreach (string mod; dacsModules) parseModule(mod);
198 parseComplete();
199 updateActorClasses();
200 setupDAPI();
201 dacsFinalizeCompiler();
202 } catch (CompilerException e) {
203 _d_print_throwable(e);
204 conwriteln("PARSE ERROR: ", e.file, " at ", e.line);
205 conwriteln(e.toString);
206 assert(0);
211 // ////////////////////////////////////////////////////////////////////////// //
212 public __gshared LevelMap map;
213 //public __gshared DACSVM dvm;
214 public __gshared uint prngSyncSeed = 0x29a;
215 public __gshared uint prngSeed = 0x29a; // unsynced
216 public __gshared string curmapname;
217 public __gshared string nextmapname; // nonempty: go to next level
219 struct MapScripts {
220 FuncPool.FuncInfo fiInit; // called after level map is loaded
221 FuncPool.FuncInfo fiLoaded; // called after mosters set
222 FuncPool.FuncInfo fiUnloading; // called before level is unloaded (i.e. player finished the level)
223 FuncPool.FuncInfo fiPreThink; // called before monster think
224 FuncPool.FuncInfo fiPostThink; // called after monster think
226 void runInit () { if (fiInit !is null) fiInit(); }
227 void runLoaded () { if (fiLoaded !is null) fiLoaded(); }
228 void runUnloading () { if (fiUnloading !is null) fiUnloading(); }
229 void runPreThink () { if (fiPreThink !is null) fiPreThink(); }
230 void runPostThink () { if (fiPostThink !is null) fiPostThink(); }
233 public __gshared MapScripts mapscripts;
236 // generate next map name for exit
237 public string genNextMapName (int lnum) {
238 import std.algorithm : endsWith;
239 import std.path;
240 string ext;
241 string nn = curmapname;
242 if (nn.endsWith(".d2m")) {
243 ext = ".d2m";
244 nn = nn[0..$-4];
246 if (nn[$-1] < '0' || nn[$-1] > '9') return null;
247 uint mapnum = 0, mmul = 1;
248 while (nn.length > 0 && nn[$-1] >= '0' && nn[$-1] <= '9') {
249 mapnum += (nn[$-1]-'0')*mmul;
250 mmul *= 10;
251 nn = nn[0..$-1];
253 ++mapnum;
254 if (lnum > 0 && lnum < 100) mapnum = lnum;
255 if (mapnum > 99) return null; // alas
256 import std.string : format;
257 return "%s%02u%s".format(nn, mapnum, ext);
261 public void clearMapScripts () {
262 mapscripts = mapscripts.init; // remove old scripts
266 public void setupMapScripts () {
267 void setupFromModule(T) (T mod) {
268 mapscripts.fiInit = FuncPool.findByFQMG(mod.name~".initialize", ":void");
269 mapscripts.fiLoaded = FuncPool.findByFQMG(mod.name~".loaded", ":void");
270 mapscripts.fiUnloading = FuncPool.findByFQMG(mod.name~".unloading", ":void");
271 mapscripts.fiPreThink = FuncPool.findByFQMG(mod.name~".prethink", ":void");
272 mapscripts.fiPostThink = FuncPool.findByFQMG(mod.name~".postthink", ":void");
275 import std.path : baseName, setExtension;
276 clearMapScripts();
277 string mapname = curmapname.baseName.setExtension("");
278 foreach (string ctype; dacsClassTypes) {
279 foreach (auto mod; dacsClassModules(ctype)) {
280 if (mod.rmoduletype.classtype != "map") continue;
281 if (mod.rmoduletype.classname != mapname) continue;
282 conwriteln("found module for map '", mapname, "'");
283 setupFromModule(mod);
284 return;
287 // not found, try "unnamed map"
288 foreach (string ctype; dacsClassTypes) {
289 foreach (auto mod; dacsClassModules(ctype)) {
290 if (mod.rmoduletype.classtype != "map") continue;
291 if (mod.rmoduletype.classname != " ") continue;
292 conwriteln("using module for unknownmap '", mapname, "'");
293 setupFromModule(mod);
294 return;
300 // ////////////////////////////////////////////////////////////////////////// //
301 // Park-Miller-Carta Pseudo-Random Number Generator, based on David G. Carta paper
302 // 31 bit of randomness
303 // seed is previous result, as usual
304 public uint prngR31next (uint seed) {
305 if (seed == 0) seed = 0x29a;
306 uint lo = 16807*(seed&0xffff);
307 uint hi = 16807*(seed>>16);
308 lo += (hi&0x7fff)<<16;
309 lo += hi>>15;
310 //if (lo > 0x7fffffff) lo -= 0x7fffffff; // should be >=, actually
311 lo = (lo&0x7FFFFFFF)+(lo>>31); // same as previous code, but branch-less
312 return lo;
316 // "synced" random, using common seed for all players
317 public uint syncrandu31 () {
318 pragma(inline, true);
319 return (prngSyncSeed = prngR31next(prngSyncSeed));
323 // "unsynced" random, seed isn't saved
324 public uint unsyncrandu31 () {
325 pragma(inline, true);
326 return (prngSeed = prngR31next(prngSeed));
330 // ////////////////////////////////////////////////////////////////////////// //
331 version(dacs_use_vm) {
332 // this is VAT function, argument order is reversed
333 void doWrite(bool donl) (FuncPool.FuncInfo fi, DACSVM vm) {
334 import std.stdio;
335 auto count = vm.popInt();
336 while (count-- > 0) {
337 auto type = vm.popInt();
338 switch (cast(VATArgType)type) {
339 case VATArgType.Int: write(vm.popInt()); break;
340 case VATArgType.Uint: write(vm.popUint()); break;
341 case VATArgType.Float: write(vm.popFloat()); break;
342 case VATArgType.StrId: write(StrId(vm.popUint()).get); break;
343 case VATArgType.ActorId: write("<actor>"); vm.popUint(); break; //TODO
344 default: write("<invalid-type>"); vm.popUint(); break; //TODO
347 static if (donl) writeln();
348 // push dummy return value
349 vm.pushInt(0);
351 } else {
352 extern(C) void doWrite(bool donl) (uint argc, ...) {
353 import core.vararg;
354 import std.stdio;
355 mainloop: while (argc >= 2) {
356 argc -= 2;
357 int tp = va_arg!int(_argptr);
358 switch (tp) {
359 case VATArgType.Int:
360 auto v = va_arg!int(_argptr);
361 write(v);
362 break;
363 case VATArgType.Uint:
364 auto v = va_arg!uint(_argptr);
365 write(v);
366 break;
367 case VATArgType.Float:
368 auto v = va_arg!float(_argptr);
369 write(v);
370 break;
371 case VATArgType.StrId:
372 auto v = StrId(va_arg!uint(_argptr)).get;
373 write(v);
374 break;
375 case VATArgType.ActorId:
376 auto v = ActorId(va_arg!uint(_argptr));
377 write("<actor:", v.valid, ":", v.id, ">");
378 //write("<actor>");
379 break;
380 default: write("<invalid-type>"); break mainloop;
383 static if (donl) writeln();
388 // ////////////////////////////////////////////////////////////////////////// //
389 void animClearFrames (StrId classtype, StrId classname, StrId state) {
390 auto adef = findActorDef(classtype.get, classname.get);
391 if (adef is null) throw new Exception("animClearFrames: actor '"~classtype.get~":"~classname.get~"' not found!");
392 adef.clearFrames(state);
396 void animAddFrame (StrId classtype, StrId classname, StrId state, uint dir, StrId sprname) {
397 auto adef = findActorDef(classtype.get, classname.get);
398 if (adef is null) throw new Exception("animAddFrame: actor '"~classtype.get~":"~classname.get~"' not found!");
399 if (dir != 0) dir = 1; //TODO: process mirror flag here
400 adef.addFrame(state, dir, sprname);
404 // ////////////////////////////////////////////////////////////////////////// //
405 void setupDAPI () {
406 conwriteln("setting up D API");
408 FuncPool["write"] = &doWrite!false;
409 FuncPool["writeln"] = &doWrite!true;
411 FuncPool["syncrandu31"] = &syncrandu31;
413 FuncPool["animClearFrames"] = &animClearFrames;
414 FuncPool["animAddFrame"] = &animAddFrame;
416 FuncPool["actorSetAnimation"] = function void (ActorId me, StrId state) {
417 if (!me.valid) return;
418 if (auto adef = findActorDef(me.classtype!string, me.classname!string)) {
419 me.zAnimstate = state;
420 me.zAnimidx = 0;
424 //FuncPool["getPlayer"] = function ActorId () { assert(0); };
425 //FuncPool["isPlayer"] = function int (ActorId me) { return (me == players.ptr[0] ? 1 : 0); };
427 FuncPool["getPlayerCount"] = function int () => 1;
429 FuncPool["getPlayerActor"] = function ActorId (uint pnum) {
430 if (pnum == 1) return players.ptr[0];
431 return ActorId(0);
434 FuncPool["getPlayerButtons"] = function uint (uint pidx) { return (pidx == 1 ? plrKeysLast : 0); };
436 FuncPool["mapGetTypeTile"] = function int (int x, int y) {
437 int res = 0;
438 if (map !is null && x >= 0 && y >= 0 && x < map.width && y < map.height) {
439 res = map.tiles.ptr[LevelMap.Type].ptr[y*map.width+x];
440 if (res != LevelMap.TILE_ACTTRAP) res &= 0x7f;
442 return res;
445 FuncPool["mapGetTile"] = function int (uint layer, int x, int y) {
446 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);
449 FuncPool["mapSetTypeTile"] = function void (int x, int y, int tid) {
450 if (map is null || x < 0 || y < 0 || x >= map.width || y >= map.height || tid < 0 || tid > 255) return;
451 auto p = map.tiles.ptr[LevelMap.Type].ptr+y*map.width+x;
452 if (*p != tid) {
453 *p = cast(ubyte)tid;
454 import render : mapDirty;
455 mapDirty((1<<LevelMap.Type)|(1<<LevelMap.LightMask));
459 FuncPool["mapSetTile"] = function void (uint layer, int x, int y, int tid) {
460 if (map is null || layer < 0 || layer > 1 || x < 0 || y < 0 || x >= map.width || y >= map.height || tid < 0 || tid > 255) return;
461 auto p = map.tiles.ptr[LevelMap.Front+layer].ptr+y*map.width+x;
462 if (*p != tid) {
463 *p = cast(ubyte)tid;
464 import render : mapDirty;
465 if (layer == 0) {
466 // front
467 mapDirty((1<<LevelMap.Front)|(1<<LevelMap.AllLiquids)|(1<<LevelMap.LiquidMask));
468 } else {
469 // back
470 mapDirty((1<<LevelMap.Back)|(1<<LevelMap.AllLiquids)|(1<<LevelMap.LiquidMask));
475 FuncPool["mapGetWaterTexture"] = function int (int fg) {
476 if (fg < 0 || fg >= map.wallnames.length) return 0;
477 switch (map.wallnames.ptr[fg]) {
478 case "_water_0": return 1;
479 case "_water_1": return 2;
480 case "_water_2": return 3;
481 default:
483 return 0;
486 FuncPool["getMapViewHeight"] = function int () {
487 import render : vlWidth, vlHeight, getScale;
488 return vlHeight/getScale;
491 FuncPool["actorsOverlap"] = function int (ActorId a, ActorId b) { return (actorsOverlap(a, b) ? 1 : 0); };
493 FuncPool["actorRemove"] = function void (ActorId me) {
494 if (me.valid) {
495 if ((me.fget_flags&AF_NOCOLLISION) == 0) ugActorModify!false(me); // remove from grid
496 Actor.remove(me);
500 FuncPool["rewindTouchList"] = &rewindTouchList;
501 FuncPool["getNextTouchListItem"] = &getNextTouchListItem;
503 FuncPool["actorListRewind"] = &xactorListRewind;
504 FuncPool["actorListNext"] = &xactorListNext;
506 FuncPool["getCheatNoDoors"] = function int () { import render : cheatNoDoors; return (cheatNoDoors ? 1 : 0); };
507 FuncPool["getCheatNoWallClip"] = function int () { import render : cheatNoWallClip; return (cheatNoWallClip ? 1 : 0); };
508 FuncPool["getCheatNoCeilClip"] = function int () { return 0; };
509 FuncPool["getCheatNoLiftClip"] = function int () { return 0; };
511 FuncPool["addMessage"] = function void (string text, int pause, bool noreplace) {
512 import render : postAddMessage;
513 postAddMessage(text, pause, noreplace);
516 import d2dparts : dotAddBlood, dotAddSpark, dotAddWater;
518 FuncPool["dotAddBlood"] = &dotAddBlood;
519 FuncPool["dotAddSpark"] = &dotAddSpark;
520 FuncPool["dotAddWater"] = &dotAddWater;
522 function void (int x, int y, int xv, int yv, int n, int color) {
523 conwriteln("dotAddWater: x=", x, "; y=", y, "; xv=", xv, "; yv=", yv, "; n=", n, "; color=", color);
524 dotAddWater(x, y, xv, yv, n, color);
528 FuncPool["gactLevelExit"] = function void (int lnum) {
529 if (nextmapname.length == 0) {
530 string nmname = genNextMapName(lnum);
531 if (nmname.length == 0) assert(0, "no level!");
532 nextmapname = nmname;
536 FuncPool["actorSpawn"] = &actorSpawn;
538 // return previous one
539 FuncPool["setCameraChick"] = function ActorId (ActorId act) {
540 auto res = cameraChick;
541 cameraChick = act;
542 return res;
545 FuncPool["MapWidth"] = function int () { return (map !is null ? map.width : 1); };
546 FuncPool["MapHeight"] = function int () { return (map !is null ? map.height : 1); };
550 public void registerAPI () {
551 //Actor.actorSize += 256;
552 conwriteln("actor size is ", Actor.actorSize, " bytes");
554 version(dacs_use_vm) FuncPool.vm = new DACSVM();
555 //dvm = new DACSVM();
557 // initialize actor animation
558 ActorDef.forEach((adef) => adef.callAnimInit());
560 conwriteln("API registered");
564 // ////////////////////////////////////////////////////////////////////////// //
565 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
566 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
567 mixin(Actor.FieldGetMixin!("x", int));
568 mixin(Actor.FieldGetMixin!("y", int));
569 mixin(Actor.FieldGetMixin!("dir", uint));
570 mixin(Actor.FieldGetMixin!("height", int));
571 mixin(Actor.FieldGetMixin!("radius", int));
572 mixin(Actor.FieldGetMixin!("flags", uint));
573 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
574 mixin(Actor.FieldGetMixin!("zAnimidx", int));
576 mixin(Actor.FieldSetMixin!("zAnimidx", int));
579 public bool actorsOverlap (ActorId a, ActorId b) {
580 if (!a.valid || !b.valid) return false;
581 if (a.id == b.id) return false; // no self-overlap
583 int ax = a.fget_x;
584 int bx = b.fget_x;
585 int ar = a.fget_radius;
586 int br = b.fget_radius;
588 if (ax-ar > bx+br || ax+ar < bx-br) return false;
590 int ay = a.fget_y;
591 int by = b.fget_y;
592 int ah = a.fget_height;
593 int bh = b.fget_height;
595 //return (ay > by-bh && ay-ah < by);
596 return (by-bh <= ay && by >= ay-ah);
600 // ////////////////////////////////////////////////////////////////////////// //
601 public __gshared ActorId[2] players;
604 public void loadAllMonsterGraphics () {
605 ActorDef.forEach((adef) {
606 conwriteln("loading graphics for '", adef.classtype.get, ":", adef.classname.get, "'");
607 adef.loadGraphics();
609 //Actor.dumpActors();
610 realiseSpriteAtlases();
614 ActorId actorSpawn (StrId classtype, StrId classname, int x, int y, uint dir) {
615 auto adef = findActorDef(classtype, classname);
616 if (adef is null) return ActorId(0);
617 auto aid = Actor.alloc;
618 aid.classtype = classtype;
619 aid.classname = classname;
620 aid.state = StrPool.MNST_SLEEP;
621 aid.x = x;
622 aid.y = y;
623 aid.dir = (dir ? 1 : 0);
624 adef.callInit(aid);
625 if ((aid.fget_flags&AF_NOCOLLISION) == 0) ugActorModify!true(aid);
626 return aid;
630 public void loadMapMonsters () {
631 assert(map !is null);
632 ugClear();
633 players[] = ActorId(0);
634 //conwriteln(players[0].valid, "; ", players[0].id);
635 foreach (ref thing; map.things) {
636 if (thing.dmonly) continue;
637 auto did = (thing.type&0x7fff) in d2dactordefsById;
638 if (did !is null && did.classtype == "playerstart") {
639 if ((thing.type&0x7fff) == 1 || (thing.type&0x7fff) == 2) {
640 int pnum = thing.type-1;
641 if (!players[pnum].valid) {
642 auto aid = Actor.alloc;
643 aid.classtype = StrPool.intern("monster");
644 aid.classname = StrPool.intern("Player");
645 aid.plrnum = cast(uint)(pnum+1);
646 aid.state = StrPool.MNST_SLEEP;
647 aid.x = cast(int)thing.x;
648 aid.y = cast(int)thing.y;
649 aid.dir = cast(uint)(thing.right ? 1 : 0);
650 auto adef = findD2DActorDef(thing.type);
651 if (adef is null) assert(0);
652 adef.callInit(aid);
653 if ((aid.fget_flags&AF_NOCOLLISION) == 0) ugActorModify!true(aid);
654 players[pnum] = aid;
655 conwriteln("player #", pnum+1, " aid is ", aid.id);
658 continue;
660 auto adef = findD2DActorDef(thing.type&0x7fff);
661 if (adef is null) {
662 if (did !is null) {
663 conwriteln("ignoring D2D thing '", did.classtype.get, ":", did.classname.get, "'");
664 } else {
665 conwriteln("ignoring unknown D2D thing with mapid ", thing.type);
667 continue;
669 // create actor and initialize it
670 auto aid = Actor.alloc;
671 aid.classtype = StrPool.intern(adef.classtype);
672 aid.classname = StrPool.intern(adef.classname);
673 //conwriteln("found '", aid.classtype.get, ":", aid.classname.get, "'");
674 if (did !is null) {
675 assert(did.classtype == adef.classtype);
676 assert(did.classname == adef.classname);
677 conwriteln("mapid=", thing.type, "; ", adef.classtype, ":", adef.classname, "; id=", aid.id);
678 assert(aid.classtype!string == adef.classtype);
679 assert(aid.classname!string == adef.classname);
680 } else {
681 assert(0);
683 aid.state = StrPool.MNST_SLEEP;
684 aid.x = cast(int)thing.x;
685 aid.y = cast(int)thing.y;
686 aid.dir = cast(uint)(thing.right ? 1 : 0);
687 if (thing.type&0x8000) aid.flags = aid.fget_flags|AF_NOGRAVITY;
688 //if (aid.classtype!string == "item" && aid.x!int < 64) { aid.x = 92; aid.y = aid.y!int-16; conwriteln("!!!"); }
689 adef.callInit(aid);
690 if ((aid.fget_flags&AF_NOCOLLISION) == 0) ugActorModify!true(aid);
693 // create switches
694 foreach (ref sw; map.switches) {
695 if (sw.type == 0) continue; // just in case
696 auto swname = getD2DSwitchClassName(sw.type);
697 if (swname.length == 0) {
698 conwriteln("unknown switch type ", sw.type);
699 continue;
701 if (auto adef = findActorDef("switch", swname)) {
702 auto aid = Actor.alloc;
703 aid.classtype = StrPool.intern("switch");
704 aid.classname = StrPool.intern(swname);
705 // nocollision, 'cause collision checking will be processed in switch thinker, but other actors should not touch switches
706 aid.flags = /*AF_NOCOLLISION|*/AF_NOGRAVITY|/*AF_NOONTOUCH|*/AF_NODRAW|AF_NOLIGHT|AF_NOANIMATE;
707 aid.x = sw.x*TileSize;
708 aid.y = sw.y*TileSize;
709 aid.switchabf = (sw.a<<16)|(sw.b<<8)|sw.flags;
710 // should be enough
711 aid.radius = 16;
712 aid.height = 16;
713 adef.callInit(aid);
714 if ((aid.fget_flags&AF_NOCOLLISION) == 0) ugActorModify!true(aid); // just in case
715 } else {
716 conwriteln("switch definition 'switch:", swname, "' not found");
720 conwriteln("initial snapshot size: ", Actor.snapshotSize, " bytes");
724 // ////////////////////////////////////////////////////////////////////////// //
725 __gshared ActorId[65536] xactorList; // aids
726 __gshared uint xactorListCount, xactorListIndex = uint.max;
729 // dacs API
730 void xactorListRewind () {
731 if (!touchListAllowed) return; // it's ok to reuse it here
732 xactorListCount = xactorListIndex = 0;
733 Actor.forEach((ActorId me) {
734 if (me.fget_classtype != StrPool.X_X) xactorList.ptr[xactorListCount++] = me;
739 // dacs API
740 ActorId xactorListNext () {
741 if (!touchListAllowed) return ActorId(0); // it's ok to reuse it here
742 if (xactorListIndex == uint.max) xactorListRewind();
743 while (xactorListIndex < xactorListCount) {
744 auto aid = xactorList.ptr[xactorListIndex];
745 ++xactorListIndex;
746 if (aid.fget_classtype == StrPool.X_X) continue;
747 return aid;
749 return ActorId(0);
753 // ////////////////////////////////////////////////////////////////////////// //
754 __gshared uint[65536] touchList; // aids
755 __gshared uint[] realTouchList;
756 __gshared uint realTouchListIndex = uint.max;
757 __gshared ActorId curThinkingActor;
758 __gshared bool touchListAllowed = false;
761 // dacs API
762 void rewindTouchList () {
763 if (!touchListAllowed) return;
764 realTouchListIndex = 0;
765 realTouchList = ugActorHitList(curThinkingActor, touchList[]);
769 // dacs API
770 ActorId getNextTouchListItem () {
771 if (!touchListAllowed) return ActorId(0);
772 if (realTouchListIndex == uint.max) rewindTouchList();
773 while (realTouchListIndex < realTouchList.length) {
774 auto aid = ActorId(realTouchList.ptr[realTouchListIndex]);
775 ++realTouchListIndex;
776 if (aid.fget_classtype == StrPool.X_X) continue;
777 if (aid.valid && (aid.fget_flags&AF_NOONTOUCH) == 0) return aid;
779 return ActorId(0);
783 public void doActorsThink () {
784 // we have too much memory!
785 __gshared uint[65536] validActorsList;
786 __gshared ActorId[65536] postponedDeath;
787 __gshared uint pdcount;
789 touchListAllowed = true;
790 scope(exit) touchListAllowed = false;
791 pdcount = 0;
792 mapscripts.runPreThink();
793 foreach (uint xid; Actor.getValidList(validActorsList[])) {
794 auto me = ActorId(xid);
795 if (me.valid) {
796 if (me.fget_classtype == StrPool.X_X) { postponedDeath.ptr[pdcount++] = me; continue; }
797 auto flags = me.fget_flags;
798 if ((flags&AF_NOCOLLISION) == 0) ugActorModify!false(me); // remove from grid
799 if (auto adef = findActorDef(me)) {
800 if ((flags&AF_NOTHINK) == 0) {
801 realTouchListIndex = uint.max;
802 xactorListIndex = uint.max;
803 curThinkingActor = me;
804 adef.callThink(me);
805 //if (me.x!int < 32) conwriteln("actor: ", me.id, "; attLightRGBX=", me.attLightRGBX!uint);
806 if (!me.valid) continue; // we are dead
807 if (me.fget_classtype == StrPool.X_X) { postponedDeath.ptr[pdcount++] = me; continue; }
808 flags = me.fget_flags; // in case script updated flags
810 if ((flags&AF_NOANIMATE) == 0) {
811 int aidx = me.fget_zAnimidx;
812 int nidx = adef.nextAnimIdx(me.fget_zAnimstate, me.fget_dir, aidx);
813 //conwriteln("actor ", me.id, " (", me.classtype!string, me.classname!string, "): state=", me.zAnimstate!string, "; aidx=", aidx, "; nidx=", nidx);
814 me.fset_zAnimidx = nidx;
815 //assert(me.fget_zAnimidx == nidx);
817 // put back to grid
818 if ((flags&AF_NOCOLLISION) == 0) ugActorModify!true(me);
822 mapscripts.runPostThink();
823 // process scheduled death
824 foreach (ActorId aid; postponedDeath[0..pdcount]) {
825 /*if ((flags&AF_NOCOLLISION) == 0)*/ ugActorModify!false(aid); // remove from grid
826 Actor.remove(aid);
828 // reset player keys
829 plrKeysFix(0);
830 //{ import std.stdio : stdout; stdout.writeln("========================================="); }
831 //Actor.dumpActors();