better locking
[dd2d.git] / render.d
blobd7792253731c3039d3c32f89961bc6e2e7af17ba
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 render is aliced;
20 //version = dont_use_vsync;
22 private:
23 import core.atomic;
24 import core.thread;
25 import core.time;
27 import std.concurrency;
29 import iv.glbinds;
30 import glutils;
31 import console;
32 import wadarc;
34 import iv.vfs.augs;
36 import d2dmap;
37 import d2dadefs;
38 import d2dimage;
39 import d2dfont;
40 import dacs;
42 import d2dunigrid;
44 // `map` is there
45 import dengapi;
47 import d2dparts;
50 // ////////////////////////////////////////////////////////////////////////// //
51 import arsd.color;
52 import arsd.png;
55 // ////////////////////////////////////////////////////////////////////////// //
56 public __gshared bool cheatNoDoors = false;
57 public __gshared bool cheatNoWallClip = false;
60 // ////////////////////////////////////////////////////////////////////////// //
61 public __gshared SimpleWindow sdwindow;
64 public enum vlWidth = 800;
65 public enum vlHeight = 800;
66 __gshared int scale = 2;
68 public int getScale () nothrow @trusted @nogc { pragma(inline, true); return scale; }
71 // ////////////////////////////////////////////////////////////////////////// //
72 __gshared bool levelLoaded = false;
75 // ////////////////////////////////////////////////////////////////////////// //
76 __gshared bool scanlines = false;
77 __gshared bool doLighting = true;
78 __gshared bool gamePaused = false;
79 __gshared bool rConsoleVisible = false;
80 __gshared int rConsoleHeight = 16*3;
81 shared bool editMode = false;
82 shared bool vquitRequested = false;
84 public @property bool inEditMode () nothrow @trusted @nogc { import core.atomic; return atomicLoad(editMode); }
85 @property void inEditMode (bool v) nothrow @trusted @nogc { import core.atomic; atomicStore(editMode, v); }
87 public @property bool quitRequested () nothrow @trusted @nogc { import core.atomic; return atomicLoad(vquitRequested); }
88 public @property bool conVisible () nothrow @trusted @nogc { return rConsoleVisible; }
91 // ////////////////////////////////////////////////////////////////////////// //
92 __gshared char[] concmdbuf;
93 __gshared uint concmdbufpos;
94 private import core.sync.mutex : Mutex;
95 shared static this () { concmdbuf.length = 65536; }
97 __gshared char[4096] concli = 0;
98 __gshared uint conclilen = 0;
100 __gshared char[4096][128] concmdhistory = void;
101 __gshared int conhisidx = -1;
102 shared static this () { foreach (ref hb; concmdhistory) hb[] = 0; }
104 __gshared int conskiplines = 0;
107 const(char)[] conhisAt (int idx) {
108 if (idx < 0 || idx >= concmdhistory.length) return null;
109 const(char)[] res = concmdhistory.ptr[idx][];
110 usize pos = 0;
111 while (pos < res.length && res.ptr[pos]) ++pos;
112 return res[0..pos];
116 int conhisFind (const(char)[] cmd) {
117 while (cmd.length && cmd[$-1] <= 32) cmd = cmd[0..$-1];
118 if (cmd.length > concmdhistory.ptr[0].length) cmd = cmd[0..concmdhistory.ptr[0].length];
119 if (cmd.length == 0) return -1;
120 foreach (int idx; 0..cast(int)concmdhistory.length) {
121 auto c = conhisAt(idx);
122 while (c.length > 0 && c[$-1] <= 32) c = c[0..$-1];
123 if (c == cmd) return idx;
125 return -1;
129 void conhisAdd (const(char)[] cmd) {
130 while (cmd.length && cmd[$-1] <= 32) cmd = cmd[0..$-1];
131 if (cmd.length > concmdhistory.ptr[0].length) cmd = cmd[0..concmdhistory.ptr[0].length];
132 if (cmd.length == 0) return;
133 auto idx = conhisFind(cmd);
134 if (idx >= 0) {
135 // remove command
136 foreach (immutable c; idx+1..concmdhistory.length) concmdhistory.ptr[c-1][] = concmdhistory.ptr[c][];
138 // make room
139 foreach (immutable c; 1..concmdhistory.length; reverse) concmdhistory.ptr[c][] = concmdhistory.ptr[c-1][];
140 concmdhistory.ptr[0][] = 0;
141 concmdhistory.ptr[0][0..cmd.length] = cmd[];
145 void concmdAdd (const(char)[] s) {
146 if (s.length) {
147 if (concmdbuf.length-concmdbufpos < s.length+1) {
148 concmdbuf.assumeSafeAppend.length += s.length-(concmdbuf.length-concmdbufpos)+512;
150 if (concmdbufpos > 0 && concmdbuf[concmdbufpos-1] != '\n') concmdbuf.ptr[concmdbufpos++] = '\n';
151 concmdbuf[concmdbufpos..concmdbufpos+s.length] = s[];
152 concmdbufpos += s.length;
156 // `null`: no more
157 void concmdDoAll () {
158 if (concmdbufpos == 0) return;
159 scope(exit) concmdbufpos = 0;
160 auto ebuf = concmdbufpos;
161 const(char)[] s = concmdbuf[0..concmdbufpos];
162 for (;;) {
163 while (s.length) {
164 auto cmd = conGetCommand(s);
165 if (cmd is null) break;
166 try {
167 conExecute(cmd);
168 } catch (Exception e) {
169 conwriteln("***ERROR: ", e.msg);
172 if (concmdbufpos <= ebuf) break;
173 s = concmdbuf[ebuf..concmdbufpos];
174 ebuf = concmdbufpos;
179 void concliChar (char ch) {
180 __gshared int prevWasEmptyAndTab = 0;
182 cbufLock();
183 scope(exit) cbufUnlock();
184 //conLastChange = 0;
186 // autocomplete
187 if (ch == 9) {
188 if (conclilen == 0) {
189 if (++prevWasEmptyAndTab < 2) return;
190 } else {
191 prevWasEmptyAndTab = 0;
193 if (conclilen > 0) {
194 string minPfx = null;
195 // find longest command
196 foreach (auto name; conByCommand) {
197 if (name.length >= conclilen && name.length > minPfx.length && name[0..conclilen] == concli[0..conclilen]) minPfx = name;
199 //conwriteln("longest command: [", minPfx, "]");
200 // find longest prefix
201 foreach (auto name; conByCommand) {
202 if (name.length < conclilen) continue;
203 if (name[0..conclilen] != concli[0..conclilen]) continue;
204 usize pos = 0;
205 while (pos < name.length && pos < minPfx.length && minPfx.ptr[pos] == name.ptr[pos]) ++pos;
206 if (pos < minPfx.length) minPfx = minPfx[0..pos];
208 if (minPfx.length > concli.length) minPfx = minPfx[0..concli.length];
209 //conwriteln("longest prefix : [", minPfx, "]");
210 if (minPfx.length >= conclilen) {
211 // wow!
212 bool doRet = (minPfx.length > conclilen);
213 conLastChange = 0;
214 concli[0..minPfx.length] = minPfx[];
215 conclilen = cast(uint)minPfx.length;
216 if (conclilen < concli.length && conHasCommand(minPfx)) {
217 concli.ptr[conclilen++] = ' ';
218 doRet = true;
220 if (doRet) return;
223 // nope, print all available commands
224 bool needDelimiter = true;
225 foreach (auto name; conByCommand) {
226 if (conclilen > 0) {
227 if (name.length < conclilen) continue;
228 if (name[0..conclilen] != concli[0..conclilen]) continue;
230 if (needDelimiter) { conwriteln("----------------"); needDelimiter = false; }
231 conwriteln(name);
233 return;
235 // process other keys
236 prevWasEmptyAndTab = 0;
237 // remove last char
238 if (ch == 8) {
239 if (conclilen > 0) { conLastChange = 0; --conclilen; }
240 return;
242 // execute command
243 if (ch == 13) {
244 if (conskiplines) { conskiplines = 0; conLastChange = 0; }
245 if (conclilen > 0) {
246 conLastChange = 0;
247 conhisidx = -1;
248 conhisAdd(concli[0..conclilen]);
249 concmdAdd(concli[0..conclilen]);
250 conclilen = 0;
252 return;
254 // ^Y
255 if (ch == 25) {
256 if (conclilen > 0) { conLastChange = 0; conclilen = 0; }
257 return;
259 // up
260 if (ch == '\x01') {
261 ++conhisidx;
262 auto cmd = conhisAt(conhisidx);
263 if (cmd.length == 0) {
264 --conhisidx;
265 } else {
266 concli[0..cmd.length] = cmd[];
267 conclilen = cast(uint)cmd.length;
268 conLastChange = 0;
270 return;
272 // down
273 if (ch == '\x02') {
274 --conhisidx;
275 auto cmd = conhisAt(conhisidx);
276 if (cmd.length == 0 && conhisidx < -1) {
277 ++conhisidx;
278 } else {
279 concli[0..cmd.length] = cmd[];
280 conclilen = cast(uint)cmd.length;
281 conLastChange = 0;
283 return;
285 // page up
286 if (ch == '\x03') {
287 int lnx = (rConsoleHeight-4)/conCharHeight-2;
288 if (lnx < 1) lnx = 1;
289 conskiplines += lnx;
290 conLastChange = 0;
291 return;
293 // page down
294 if (ch == '\x04') {
295 if (conskiplines > 0) {
296 int lnx = (rConsoleHeight-4)/conCharHeight-2;
297 if (lnx < 1) lnx = 1;
298 if ((conskiplines -= lnx) < 0) conskiplines = 0;
299 conLastChange = 0;
301 return;
303 // other
304 if (ch < ' ' || ch > 127) return;
305 if (conclilen >= concli.length) return;
306 concli.ptr[conclilen++] = ch;
307 conLastChange = 0;
311 // ////////////////////////////////////////////////////////////////////////// //
312 shared static this () {
313 conRegVar!doLighting("r_lighting", "dynamic lighting");
314 conRegVar!gamePaused("g_pause", "pause game");
315 conRegVar!rConsoleVisible("r_console", "console visibility");
316 conRegVar!rConsoleHeight(16*3, vlHeight, "r_conheight");
317 rConsoleHeight = vlHeight-vlHeight/3;
318 rConsoleHeight = vlHeight/2;
319 conRegVar!frameInterpolation("r_interpolation", "interpolate camera and sprite movement");
320 conRegVar!scale(1, 2, "r_scale");
321 conRegFunc!({
322 cheatNoDoors = !cheatNoDoors;
323 if (cheatNoDoors) conwriteln("player ignores doors"); else conwriteln("player respects doors");
324 })("nodoorclip", "ignore doors");
325 conRegFunc!({
326 cheatNoWallClip = !cheatNoWallClip;
327 if (cheatNoWallClip) conwriteln("player ignores walls"); else conwriteln("player respects walls");
328 })("nowallclip", "ignore walls");
329 conRegFunc!({
330 import core.atomic;
331 atomicStore(vquitRequested, true);
332 })("quit", "quit game");
333 conRegFunc!((const(char)[] msg, int pauseMsecs=3000, bool noreplace=false) {
334 char[256] buf;
335 auto s = buf.conFormatStr(msg);
336 if (s.length) postAddMessage(s, pauseMsecs, noreplace);
337 })("hudmsg", "show hud message; hudmsg msg [pausemsecs [noreplace]]");
341 // ////////////////////////////////////////////////////////////////////////// //
342 // interpolation
343 __gshared ubyte[] prevFrameActorsData;
344 __gshared uint[65536] prevFrameActorOfs; // uint.max-1: dead; uint.max: last
345 __gshared MonoTime lastthink = MonoTime.zero; // for interpolator
346 __gshared MonoTime nextthink = MonoTime.zero;
347 __gshared bool frameInterpolation = true;
350 // ////////////////////////////////////////////////////////////////////////// //
351 // attached lights
352 struct AttachedLightInfo {
353 enum Type {
354 Point,
355 Ambient,
357 Type type;
358 int x, y;
359 int w, h; // for ambient lights
360 float r, g, b;
361 bool uncolored;
362 int radius;
365 __gshared AttachedLightInfo[65536] attachedLights;
366 __gshared uint attachedLightCount = 0;
369 // ////////////////////////////////////////////////////////////////////////// //
370 enum MaxLightRadius = 255;
373 // ////////////////////////////////////////////////////////////////////////// //
374 // for light
375 __gshared FBO[MaxLightRadius+1] fboDistMap;
376 __gshared FBO fboOccluders;
377 __gshared Shader shadToPolar, shadBlur, shadBlurOcc, shadAmbient;
378 __gshared TrueColorImage editorImg;
379 __gshared FBO fboEditor;
380 __gshared FBO fboConsole;
381 __gshared Texture texSigil;
383 __gshared FBO fboLevel, fboLevelLight, fboOrigBack, fboLMaskSmall;
384 __gshared Shader shadScanlines;
385 __gshared Shader shadLiquidDistort;
388 // ////////////////////////////////////////////////////////////////////////// //
389 // call once!
390 public void initOpenGL () {
391 gloStackClear();
393 glEnable(GL_TEXTURE_2D);
394 glDisable(GL_LIGHTING);
395 glDisable(GL_DITHER);
396 glDisable(GL_BLEND);
397 glDisable(GL_DEPTH_TEST);
399 // create shaders
400 shadScanlines = new Shader("scanlines", loadTextFile("shaders/srscanlines.frag"));
402 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("shaders/srliquid_distort.frag"));
403 shadLiquidDistort.exec((Shader shad) {
404 shad["texLqMap"] = 0;
407 // lights
408 shadToPolar = new Shader("light_trace", loadTextFile("shaders/srlight_trace.frag"));
409 shadToPolar.exec((Shader shad) {
410 shad["texOcc"] = 0;
411 shad["texOccFull"] = 2;
412 shad["texOccSmall"] = 3;
415 shadBlur = new Shader("light_blur", loadTextFile("shaders/srlight_blur.frag"));
416 shadBlur.exec((Shader shad) {
417 shad["texDist"] = 0;
418 shad["texBg"] = 1;
419 shad["texOcc"] = 2;
420 shad["texOccSmall"] = 3;
423 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("shaders/srlight_blur_occ.frag"));
424 shadBlurOcc.exec((Shader shad) {
425 shad["texLMap"] = 0;
426 shad["texBg"] = 1;
427 shad["texOcc"] = 2;
428 shad["texOccSmall"] = 3;
431 shadAmbient = new Shader("light_ambient", loadTextFile("shaders/srlight_ambient.frag"));
432 shadAmbient.exec((Shader shad) {
433 shad["texBg"] = 1;
434 shad["texOcc"] = 2;
435 shad["texOccSmall"] = 3;
438 fboOccluders = new FBO(MaxLightRadius*2, MaxLightRadius*2, Texture.Option.Clamp, Texture.Option.Linear);
439 //TODO: this sux!
440 foreach (int sz; 2..MaxLightRadius+1) {
441 fboDistMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp, Texture.Option.Linear); // create 1d distance map FBO
444 editorImg = new TrueColorImage(vlWidth, vlHeight);
445 editorImg.imageData.colors[] = Color(0, 0, 0, 0);
446 fboEditor = new FBO(vlWidth, vlHeight, Texture.Option.Nearest);
448 texSigil = new Texture("console/sigil_of_baphomet.png", Texture.Option.Nearest);
449 fboConsole = new FBO(vlWidth, vlHeight, Texture.Option.Nearest);
450 loadConFont();
452 // setup matrices
453 glMatrixMode(GL_MODELVIEW);
454 glLoadIdentity();
456 loadSmFont();
457 loadBfFont();
458 loadAllMonsterGraphics();
462 // ////////////////////////////////////////////////////////////////////////// //
463 __gshared ulong conLastChange = 0;
465 void renderConsoleFBO () {
466 enum XOfs = 2;
467 if (conLastChange == cbufLastChange) return;
468 cbufLock();
469 scope(exit) cbufUnlock();
470 // rerender console
471 conLastChange = cbufLastChange;
472 //foreach (auto s; conbufLinesRev) stdout.writeln(s, "|");
473 int skipLines = conskiplines;
474 fboConsole.exec((FBO me) {
475 bindTexture(0);
476 orthoCamera(me.width, me.height);
477 // clear it
478 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
479 glClear(GL_COLOR_BUFFER_BIT);
481 glDisable(GL_BLEND);
482 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
483 glRectf(0, 0, me.width-1, me.height-1);
485 // text
486 glEnable(GL_BLEND);
487 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
488 // draw sigil
489 glColor4f(1.0f, 1.0f, 1.0f, 0.2f);
490 drawAtXY(texSigil, (me.width-texSigil.width)/2, (vlHeight-rConsoleHeight)/2+(me.height-texSigil.height)/2);
491 // draw command line
492 int y = me.height-conCharHeight-2;
494 glPushMatrix();
495 scope(exit) glPopMatrix();
496 glTranslatef(XOfs, y, 0);
497 int w = conCharWidth('>');
498 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
499 conDrawChar('>');
500 uint spos = conclilen;
501 while (spos > 0) {
502 char ch = concli.ptr[spos-1];
503 if (w+conCharWidth(ch) > me.width-XOfs*2-12) break;
504 w += conCharWidth(ch);
505 --spos;
507 glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
508 foreach (char ch; concli[spos..conclilen]) conDrawChar(ch);
509 // cursor
510 bindTexture(0);
511 glColor4f(1.0f, 0.5f, 0.0f, 1.0f);
512 glRectf(0, 0, 12, 16);
513 y -= conCharHeight;
515 // draw console text
516 glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
517 glPushMatrix();
518 scope(exit) glPopMatrix();
519 glTranslatef(XOfs, y, 0);
520 foreach (auto line; conbufLinesRev) {
521 if (line.length == 0) {
522 if (skipLines-- <= 0) {
523 glPopMatrix();
524 glPushMatrix();
525 y -= conCharHeight;
526 glTranslatef(XOfs, y, 0);
528 } else {
529 usize pos = line.length;
530 for (;;) {
531 int w = 0;
532 usize sp = pos;
533 while (sp > 0) {
534 char ch = line[sp-1];
535 if (w+conCharWidth(ch) > me.width-XOfs*2) break;
536 w += conCharWidth(ch);
537 --sp;
539 if (skipLines-- <= 0) {
540 foreach (immutable p; sp..pos) conDrawChar(line[p]);
541 glPopMatrix();
542 glPushMatrix();
543 y -= conCharHeight;
544 glTranslatef(XOfs, y, 0);
546 if (sp == 0 || y < 0) break;
547 pos = sp;
550 if (y < 0) break;
556 // ////////////////////////////////////////////////////////////////////////// //
557 // should be called when OpenGL is initialized
558 void loadMap (string mapname) {
559 mapscripts.runUnloading(); // "map unloading" script
560 clearMapScripts();
562 if (map !is null) map.clear();
563 map = new LevelMap(mapname);
564 curmapname = mapname;
566 ugInit(map.width*TileSize, map.height*TileSize);
568 map.oglBuildMega();
569 mapTilesChanged = 0;
571 if (fboLevel !is null) fboLevel.clear();
572 if (fboLevelLight !is null) fboLevelLight.clear();
573 if (fboOrigBack !is null) fboOrigBack.clear();
574 if (fboLMaskSmall !is null) fboLMaskSmall.clear();
576 fboLevel = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // final level render will be here
577 fboLevelLight = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // level lights will be rendered here
578 fboOrigBack = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest/*, Texture.Option.Depth*/); // background+foreground
579 fboLMaskSmall = new FBO(map.width, map.height, Texture.Option.Nearest); // small lightmask
581 shadToPolar.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize-1, map.height*TileSize-1); });
582 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
583 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
584 shadAmbient.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
586 glActiveTexture(GL_TEXTURE0+0);
587 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
588 orthoCamera(vlWidth, vlHeight);
590 Actor.resetStorage();
592 setupMapScripts();
593 mapscripts.runInit();
594 loadMapMonsters();
595 dotInit();
596 mapscripts.runLoaded();
598 // save first snapshot
599 if (prevFrameActorsData.length == 0) prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
600 prevFrameActorOfs[] = uint.max; // just for fun
601 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
603 levelLoaded = true;
605 { import core.memory : GC; GC.collect(); }
609 // ////////////////////////////////////////////////////////////////////////// //
610 //FIXME: optimize!
611 __gshared uint mapTilesChanged = 0;
614 //WARNING! this can be called only from DACS, so we don't have to sync it!
615 public void mapDirty (uint layermask) { mapTilesChanged |= layermask; }
618 void rebuildMapMegaTextures () {
619 //fbo.replaceTexture
620 //mapTilesChanged = false;
621 //map.clearMegaTextures();
622 map.oglBuildMega(mapTilesChanged);
623 mapTilesChanged = 0;
624 dotsAwake(); // let dormant dots fall
628 // ////////////////////////////////////////////////////////////////////////// //
629 // messages
630 struct Message {
631 enum Phase { FadeIn, Stay, FadeOut }
632 Phase phase;
633 int alpha;
634 int pauseMsecs;
635 MonoTime removeTime;
636 char[256] text;
637 usize textlen;
640 //private import core.sync.mutex : Mutex;
642 __gshared Message[128] messages;
643 __gshared uint messagesUsed = 0;
645 //__gshared Mutex messageLock;
646 //shared static this () { messageLock = new Mutex(); }
649 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
650 //messageLock.lock();
651 //scope(exit) messageLock.unlock();
652 if (msgtext.length == 0) return;
653 conwriteln(msgtext);
654 if (pauseMsecs <= 50) return;
655 if (messagesUsed == messages.length) {
656 // remove top message
657 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
658 messages.ptr[0].alpha = 255;
659 --messagesUsed;
661 // quick replace
662 if (!noreplace && messagesUsed == 1) {
663 switch (messages.ptr[0].phase) {
664 case Message.Phase.FadeIn:
665 messages.ptr[0].phase = Message.Phase.FadeOut;
666 break;
667 case Message.Phase.Stay:
668 messages.ptr[0].phase = Message.Phase.FadeOut;
669 messages.ptr[0].alpha = 255;
670 break;
671 default:
674 auto msg = messages.ptr+messagesUsed;
675 ++messagesUsed;
676 msg.phase = Message.Phase.FadeIn;
677 msg.alpha = 0;
678 msg.pauseMsecs = pauseMsecs;
679 // copy text
680 if (msgtext.length > msg.text.length) {
681 msg.text = msgtext[0..msg.text.length];
682 msg.textlen = msg.text.length;
683 } else {
684 msg.text[0..msgtext.length] = msgtext[];
685 msg.textlen = msgtext.length;
690 void doMessages (MonoTime curtime) {
691 //messageLock.lock();
692 //scope(exit) messageLock.unlock();
694 if (messagesUsed == 0) return;
695 glEnable(GL_BLEND);
696 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
698 Message* msg;
700 again:
701 msg = messages.ptr;
702 final switch (msg.phase) {
703 case Message.Phase.FadeIn:
704 if ((msg.alpha += 10) >= 255) {
705 msg.phase = Message.Phase.Stay;
706 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
707 goto case; // to stay
709 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
710 break;
711 case Message.Phase.Stay:
712 if (msg.removeTime <= curtime) {
713 msg.alpha = 255;
714 msg.phase = Message.Phase.FadeOut;
715 goto case; // to fade
717 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
718 break;
719 case Message.Phase.FadeOut:
720 if ((msg.alpha -= 10) <= 0) {
721 if (--messagesUsed == 0) return;
722 // remove this message
723 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
724 goto again;
726 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
727 break;
730 smDrawText(10, 10, msg.text[0..msg.textlen]);
734 // ////////////////////////////////////////////////////////////////////////// //
735 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
737 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
738 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
739 mixin(Actor.FieldGetMixin!("x", int));
740 mixin(Actor.FieldGetMixin!("y", int));
741 mixin(Actor.FieldGetMixin!("s", int));
742 mixin(Actor.FieldGetMixin!("radius", int));
743 mixin(Actor.FieldGetMixin!("height", int));
744 mixin(Actor.FieldGetMixin!("flags", uint));
745 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
746 mixin(Actor.FieldGetMixin!("zAnimidx", int));
747 mixin(Actor.FieldGetMixin!("dir", uint));
748 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
749 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
750 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
752 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
753 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
754 mixin(Actor.FieldGetPtrMixin!("x", int));
755 mixin(Actor.FieldGetPtrMixin!("y", int));
756 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
757 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
758 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
759 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
760 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
761 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
762 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
765 // ////////////////////////////////////////////////////////////////////////// //
766 __gshared int vportX0, vportY0, vportX1, vportY1;
769 // ////////////////////////////////////////////////////////////////////////// //
770 void renderLightAmbient() (int lightX, int lightY, int lightW, int lightH, in auto ref SVec4F lcol) {
771 //conwriteln("!!!000: (", lightX, ",", lightY, ")-(", lightW, ",", lightH, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
772 if (lightW < 1 || lightH < 1) return;
773 int lightX1 = lightX+lightW-1;
774 int lightY1 = lightY+lightH-1;
775 // clip light to viewport
776 if (lightX < vportX0) lightX = vportX0;
777 if (lightY < vportY0) lightY = vportY0;
778 if (lightX1 > vportX1) lightX1 = vportX1;
779 if (lightY1 > vportY1) lightY1 = vportY1;
780 // is this light visible?
781 //conwriteln("!!!001: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
782 if (lightX1 < lightX || lightY1 < lightY || lightX > vportX1 || lightY > vportY1 || lightX1 < vportX0 || lightY1 < vportY0) return;
783 //conwriteln("!!!002: (", lightX, ",", lightY, ")-(", lightX1, ",", lightY1, "): r=", cast(uint)(255.0f*lcol.r), "; g=", cast(uint)(255.0f*lcol.g), "; b=", cast(uint)(255.0f*lcol.b), "; a=", cast(uint)(255.0f*lcol.a));
785 fboLevelLight.exec({
786 bindTexture(0);
787 glEnable(GL_BLEND);
788 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
789 //glDisable(GL_BLEND);
790 orthoCamera(map.width*TileSize, map.height*TileSize);
791 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
792 shadAmbient.exec((Shader shad) {
793 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
794 //shad["lightPos"] = SVec2F(lightX, lightY);
795 glRectf(lightX, lightY, lightX1, lightY1);
801 // ////////////////////////////////////////////////////////////////////////// //
802 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
803 if (lightRadius < 2) return;
804 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
805 int lightSize = lightRadius*2;
806 // is this light visible?
807 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*TileSize || lightY-lightRadius >= map.height*TileSize) return;
809 // out of viewport -- do nothing
810 if (lightX+lightRadius < vportX0 || lightY+lightRadius < vportY0) return;
811 if (lightX-lightRadius > vportX1 || lightY-lightRadius > vportY1) return;
813 if (lightX >= 0 && lightY >= 0 && lightX < map.width*TileSize && lightY < map.height*TileSize &&
814 map.teximgs[map.LightMask].imageData.colors.ptr[lightY*(map.width*TileSize)+lightX].a > 190) return;
816 // common color for all the following
817 glDisable(GL_BLEND);
818 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
820 // build 1d distance map to fboShadowMapId
821 fboDistMap.ptr[lightRadius].exec({
822 // no need to clear it, shader will take care of that
823 shadToPolar.exec((Shader shad) {
824 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
825 shad["lightPos"] = SVec2F(lightX, lightY);
826 orthoCamera(lightSize, 1);
827 // it doesn't matter what we will draw here, so just draw filled rect
828 glRectf(0, 0, lightSize, 1);
832 // build light texture for blending
833 fboOccluders.exec({
834 // no need to clear it, shader will take care of that
835 // debug
836 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
837 //glClear(GL_COLOR_BUFFER_BIT);
838 shadBlur.exec((Shader shad) {
839 shad["lightTexSize"] = SVec2F(lightSize, MaxLightRadius*2); // x: size of distmap; y: size of this texture
840 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
841 shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
842 orthoCamera(fboOccluders.tex.width, fboOccluders.tex.height);
843 //drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
844 bindTexture(fboDistMap.ptr[lightRadius].tex.tid);
845 glBegin(GL_QUADS);
846 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, 0); // top-left
847 glTexCoord2f(1.0f, 0.0f); glVertex2i(lightSize, 0); // top-right
848 glTexCoord2f(1.0f, 1.0f); glVertex2i(lightSize, lightSize); // bottom-right
849 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, lightSize); // bottom-left
850 glEnd();
854 // blend light texture
855 fboLevelLight.exec({
856 glEnable(GL_BLEND);
857 //glDisable(GL_BLEND);
858 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
859 orthoCamera(fboLevelLight.tex.width, fboLevelLight.tex.height);
860 //drawAtXY(fboOccluders.tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
861 float occe = 1.0f*lightSize/(MaxLightRadius*2);
862 float occs = 1.0f-occe;
863 int x0 = lightX-lightRadius+0;
864 int y1 = lightY-lightRadius+0;
865 int x1 = lightX+lightRadius-1+1;
866 int y0 = lightY+lightRadius-1+1;
867 bindTexture(fboOccluders.tex.tid);
868 glBegin(GL_QUADS);
870 glTexCoord2f(0.0f, 0.0f); glVertex2i(x0, y0); // top-left
871 glTexCoord2f(occe, 0.0f); glVertex2i(x1, y0); // top-right
872 glTexCoord2f(occe, occe); glVertex2i(x1, y1); // bottom-right
873 glTexCoord2f(0.0f, occe); glVertex2i(x0, y1); // bottom-left
875 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
876 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
877 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
878 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
879 glEnd();
881 bindTexture(0);
882 glRectf(x0, y0, x1, y1);
884 // and blend it again, with the shader that will touch only occluders
885 shadBlurOcc.exec((Shader shad) {
886 //shad["lightTexSize"] = SVec2F(lightSize, lightSize);
887 shad["lightTexSize"] = SVec2F(lightSize, fboOccluders.tex.height);
888 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
889 shad["lightPos"] = SVec2F(lightX, lightY);
890 //shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
891 bindTexture(fboOccluders.tex.tid);
892 glBegin(GL_QUADS);
893 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
894 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
895 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
896 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
897 glEnd();
898 //drawAtXY(fboOccluders.tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
904 // ////////////////////////////////////////////////////////////////////////// //
905 __gshared int testLightX = vlWidth/2, testLightY = vlHeight/2;
906 __gshared bool testLightMoved = false;
907 //__gshared int mapOfsX, mapOfsY;
908 //__gshared bool movement = false;
909 __gshared float iLiquidTime = 0.0;
910 //__gshared bool altMove = false;
913 void renderScene (MonoTime curtime) {
914 //enum BackIntens = 0.05f;
915 enum BackIntens = 0.0f;
917 gloStackClear();
918 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
919 if (gamePaused || inEditMode) atob = 1.0f;
920 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
923 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
924 int curfp = cast(int)((curtime-lastthink).total!"msecs");
925 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
929 int mofsx, mofsy; // camera offset, will be set in background layer builder
931 if (mapTilesChanged != 0) rebuildMapMegaTextures();
933 // build background layer
934 fboOrigBack.exec({
935 //glDisable(GL_BLEND);
936 //glClearDepth(1.0f);
937 //glDepthFunc(GL_LESS);
938 //glDepthFunc(GL_NEVER);
939 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
940 glClear(GL_COLOR_BUFFER_BIT/*|GL_DEPTH_BUFFER_BIT*/);
941 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
942 orthoCamera(map.width*TileSize, map.height*TileSize);
944 glEnable(GL_BLEND);
945 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
946 // draw sky
948 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
949 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
950 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
951 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
953 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*TileSize, map.MapSize*TileSize);
954 // draw background
955 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
956 // draw distorted liquid areas
957 shadLiquidDistort.exec((Shader shad) {
958 shad["iDistortTime"] = iLiquidTime;
959 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
961 // monsters, items; we'll do linear interpolation here
962 glColor3f(1.0f, 1.0f, 1.0f);
963 //glEnable(GL_DEPTH_TEST);
964 attachedLightCount = 0;
966 // who cares about memory?!
967 // draw order: players, items, monsters, other
968 static struct DrawInfo {
969 ActorDef adef;
970 ActorId aid;
971 int actorX, actorY;
972 @disable this (this); // no copies
974 enum { Pixels, Players, Items, Monsters, Other }
975 __gshared DrawInfo[65536][4] drawlists;
976 __gshared uint[4] dlpos;
977 DrawInfo camchickdi;
979 dlpos[] = 0;
981 Actor.forEach((ActorId me) {
982 //me.fprop_0drawlistpos = 0;
983 if (auto adef = findActorDef(me)) {
984 uint dlnum = Other;
985 switch (adef.classtype.get) {
986 case "monster": dlnum = (adef.classname.get != "Player" ? Monsters : Players); break;
987 case "item": dlnum = Items; break;
988 default: dlnum = Other; break;
990 if (me.fget_flags&AF_PIXEL) dlnum = Pixels;
991 int actorX, actorY; // current actor position
993 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
994 if (frameInterpolation && ofs < uint.max-1 && (me.fget_flags&AF_TELEPORT) == 0 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
995 import core.stdc.math : roundf;
996 auto xptr = prevFrameActorsData.ptr+ofs;
997 int ox = xptr.fgetp_x;
998 int nx = me.fget_x;
999 int oy = xptr.fgetp_y;
1000 int ny = me.fget_y;
1001 actorX = cast(int)(ox+roundf((nx-ox)*atob));
1002 actorY = cast(int)(oy+roundf((ny-oy)*atob));
1003 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
1004 } else {
1005 actorX = me.fget_x;
1006 actorY = me.fget_y;
1009 if (me.id == cameraChick.id) {
1010 camchickdi.adef = adef;
1011 camchickdi.aid = me;
1012 camchickdi.actorX = actorX;
1013 camchickdi.actorY = actorY;
1015 // draw sprite
1016 if ((me.fget_flags&AF_NODRAW) == 0) {
1017 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
1018 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
1019 auto dl = drawlists.ptr[dlnum].ptr+dlpos.ptr[dlnum];
1020 ++dlpos.ptr[dlnum];
1021 dl.adef = adef;
1022 dl.aid = me;
1023 dl.actorX = actorX;
1024 dl.actorY = actorY;
1026 // process attached lights
1027 if ((me.fget_flags&AF_NOLIGHT) == 0) {
1028 uint alr = me.fget_attLightRGBX;
1029 bool isambient = (me.fget_classtype.get == "light" && me.fget_classname.get == "Ambient");
1030 if ((alr&0xff) >= 4 || (isambient && me.fget_radius >= 1 && me.fget_height >= 1)) {
1031 //if (isambient) conwriteln("isambient: ", isambient, "; x=", me.fget_x, "; y=", me.fget_y, "; w=", me.fget_radius, "; h=", me.fget_height);
1032 // yep, add it
1033 auto li = attachedLights.ptr+attachedLightCount;
1034 ++attachedLightCount;
1035 li.type = (!isambient ? AttachedLightInfo.Type.Point : AttachedLightInfo.Type.Ambient);
1036 li.x = actorX+me.fget_attLightXOfs;
1037 li.y = actorY+me.fget_attLightYOfs;
1038 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
1039 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
1040 li.uncolored = true;
1041 } else {
1042 li.g = ((alr>>16)&0xff)/255.0f;
1043 li.b = ((alr>>8)&0xff)/255.0f;
1044 li.uncolored = false;
1046 li.radius = (alr&0xff);
1047 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
1048 if (isambient) {
1049 li.w = me.fget_radius;
1050 li.h = me.fget_height;
1054 } else {
1055 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
1059 // draw actor lists
1060 foreach_reverse (uint dlnum; 0..drawlists.length) {
1061 if (dlnum == Pixels) continue;
1062 auto dl = drawlists.ptr[dlnum].ptr;
1063 if (dlnum == Players) dl += dlpos.ptr[dlnum]-1;
1064 foreach (uint idx; 0..dlpos.ptr[dlnum]) {
1065 auto me = dl.aid;
1066 if (auto isp = dl.adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
1067 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
1068 isp.drawAtXY(dl.actorX, dl.actorY);
1070 if (dlnum != Players) ++dl; else --dl;
1073 // draw pixels
1074 if (dlpos[Pixels]) {
1075 bindTexture(0);
1076 bool pointsStarted = false;
1077 Color lastColor = Color(0, 0, 0, 0);
1078 auto dl = drawlists.ptr[Pixels].ptr;
1079 foreach (uint idx; 0..dlpos.ptr[Pixels]) {
1080 auto me = dl.aid;
1081 auto s = me.fget_s;
1082 if (s < 0 || s > 255) continue; //FIXME
1083 Color clr = d2dpal.ptr[s&0xff];
1084 if (clr.a == 0) continue;
1085 if (clr != lastColor) {
1086 if (pointsStarted) glEnd();
1087 glColor4f(clr.r/255.0f, clr.g/255.0f, clr.b/255.0f, clr.a/255.0f);
1088 lastColor = clr;
1089 pointsStarted = false;
1091 if (!pointsStarted) {
1092 glBegin(GL_POINTS);
1093 pointsStarted = true;
1095 glVertex2i(dl.actorX, dl.actorY);
1096 ++dl;
1098 if (pointsStarted) {
1099 glEnd();
1100 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1104 // camera movement
1105 if (/*altMove || movement ||*/ scale == 1 || !cameraChick.valid) {
1106 mofsx = 0;
1107 mofsy = 0;
1108 vportX0 = 0;
1109 vportY0 = 0;
1110 vportX1 = map.width*TileSize;
1111 vportY1 = map.height*TileSize;
1112 } else {
1113 int tiltHeight = /*getMapViewHeight()*/(vlHeight/scale)/4;
1114 int vy = cameraChick.looky!int;
1115 if (vy < -tiltHeight) vy = -tiltHeight; else if (vy > tiltHeight) vy = tiltHeight;
1116 int swdt = vlWidth/scale;
1117 int shgt = vlHeight/scale;
1118 int x = camchickdi.actorX-swdt/2;
1119 int y = (camchickdi.actorY+vy)-shgt/2;
1120 if (x < 0) x = 0; else if (x >= map.width*TileSize-swdt) x = map.width*TileSize-swdt-1;
1121 if (y < 0) y = 0; else if (y >= map.height*TileSize-shgt) y = map.height*TileSize-shgt-1;
1122 mofsx = x*2;
1123 mofsy = y*2;
1124 vportX0 = mofsx/scale;
1125 vportY0 = mofsy/scale;
1126 vportX1 = vportX0+vlWidth/scale;
1127 vportY1 = vportY0+vlHeight/scale;
1130 //glDisable(GL_DEPTH_TEST);
1131 // draw dots
1132 dotDraw(atob);
1133 // do liquid coloring
1134 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
1135 // foreground -- hide secrets, draw lifts and such
1136 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
1139 enum r = 255;
1140 enum g = 0;
1141 enum b = 0;
1142 enum a = 255;
1143 bindTexture(0);
1144 glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
1145 glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
1146 if (cameraChick.valid) {
1147 glBegin(GL_POINTS);
1148 glVertex2i(camchickdi.actorX, camchickdi.actorY-70);
1149 glEnd();
1150 //glRectf(camchickdi.actorX, camchickdi.actorY-70, camchickdi.actorX+4, camchickdi.actorY-70+4);
1152 //glRectf(0, 0, 300, 300);
1153 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1159 if (doLighting) {
1160 glDisable(GL_BLEND);
1161 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1163 // make smaller occluder texture, so we can trace faster
1164 //assert(fboLMaskSmall.tex.width == map.width);
1165 //assert(fboLMaskSmall.tex.height == map.height);
1166 fboLMaskSmall.exec({
1167 orthoCamera(map.width, map.height);
1168 drawAtXY(map.texgl.ptr[map.LightMask].tid, 0, 0, map.width, map.height, mirrorY:true);
1171 // clear light layer
1172 fboLevelLight.exec({
1173 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1174 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
1175 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
1176 glClear(GL_COLOR_BUFFER_BIT);
1179 // texture 1 is background
1180 glActiveTexture(GL_TEXTURE0+1);
1181 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
1182 // texture 2 is occluders
1183 glActiveTexture(GL_TEXTURE0+2);
1184 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
1185 // texture 3 is small occluder map
1186 glActiveTexture(GL_TEXTURE0+3);
1187 glBindTexture(GL_TEXTURE_2D, fboLMaskSmall.tex.tid);
1188 // done texture assign
1189 glActiveTexture(GL_TEXTURE0+0);
1192 enum LYOfs = 1;
1194 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1195 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1196 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1197 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1198 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1199 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1200 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1201 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1202 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1203 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1205 renderLight(24*TileSize+4, (24+18)*TileSize-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
1207 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1210 foreach (; 0..1) {
1211 // attached lights
1212 foreach (ref li; attachedLights[0..attachedLightCount]) {
1213 if (li.type == AttachedLightInfo.Type.Ambient) {
1214 //conwriteln("ambient: x=", li.x, "; y=", li.y, "; w=", li.w, "; h=", li.h);
1215 // ambient light
1216 if (li.uncolored) {
1217 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(0.0f, 0.0f, 0.0f, li.r));
1218 } else {
1219 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(li.r, li.g, li.b, 1.0f));
1221 } else if (li.type == AttachedLightInfo.Type.Point) {
1222 // point light
1223 if (li.uncolored) {
1224 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
1225 } else {
1226 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
1233 if (testLightMoved) {
1234 testLightX = testLightX/scale+mofsx/scale;
1235 testLightY = testLightY/scale+mofsy/scale;
1236 testLightMoved = false;
1238 foreach (immutable _; 0..1) {
1239 renderLight(testLightX, testLightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
1243 glActiveTexture(GL_TEXTURE0+1);
1244 glBindTexture(GL_TEXTURE_2D, 0);
1245 glActiveTexture(GL_TEXTURE0+2);
1246 glBindTexture(GL_TEXTURE_2D, 0);
1247 glActiveTexture(GL_TEXTURE0+3);
1248 glBindTexture(GL_TEXTURE_2D, 0);
1249 glActiveTexture(GL_TEXTURE0+0);
1252 // draw scaled level
1254 shadScanlines.exec((Shader shad) {
1255 shad["scanlines"] = scanlines;
1256 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1257 glClear(GL_COLOR_BUFFER_BIT);
1258 orthoCamera(vlWidth, vlHeight);
1259 //orthoCamera(map.width*TileSize*scale, map.height*TileSize*scale);
1260 //glMatrixMode(GL_MODELVIEW);
1261 //glLoadIdentity();
1262 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
1263 // somehow, FBO objects are mirrored; wtf?!
1264 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1265 //glLoadIdentity();
1270 fboLevelLight.exec({
1271 smDrawText(map.width*TileSize/2, map.height*TileSize/2, "Testing...");
1276 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1278 glDisable(GL_BLEND);
1281 fboOrigBack.exec({
1282 //auto img = smfont.ptr[0x39];
1283 auto img = fftest;
1284 if (img !is null) {
1285 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
1286 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
1293 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
1294 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1295 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1296 glDrawBuffers(1, buffers.ptr);
1301 orthoCamera(vlWidth, vlHeight);
1302 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
1303 drawAtXY(tex, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1305 if (levelLoaded) {
1306 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1307 //orthoCamera(map.width*TileSize, map.height*TileSize);
1308 glEnable(GL_BLEND);
1309 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1310 hudScripts.runDraw();
1313 //drawAtXY(map.texgl.ptr[map.LightMask].tid, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1314 //drawAtXY(fboLMaskSmall.tex.tid, 0, 0, map.width*TileSize, map.height*TileSize);
1316 if (inEditMode) {
1317 glEnable(GL_BLEND);
1318 //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1319 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1320 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1321 editorUpdateImage();
1322 fboEditor.tex.setFromImage(editorImg);
1323 drawAtXY(fboEditor.tex, 0, 0);
1324 glDisable(GL_BLEND);
1327 doMessages(curtime);
1329 if (rConsoleVisible) {
1330 renderConsoleFBO();
1331 orthoCamera(vlWidth, vlHeight);
1332 glEnable(GL_BLEND);
1333 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1334 glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
1335 drawAtXY(fboConsole.tex, 0, rConsoleHeight-vlHeight, mirrorY:true);
1340 // ////////////////////////////////////////////////////////////////////////// //
1341 // returns time slept
1342 int sleepAtMaxMsecs (int msecs) {
1343 if (msecs > 0) {
1344 import core.sys.posix.signal : timespec;
1345 import core.sys.posix.time : nanosleep;
1346 timespec ts = void, tpassed = void;
1347 ts.tv_sec = 0;
1348 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
1349 nanosleep(&ts, &tpassed);
1350 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
1351 } else {
1352 return 0;
1357 // ////////////////////////////////////////////////////////////////////////// //
1358 mixin(import("editor.d"));
1361 // ////////////////////////////////////////////////////////////////////////// //
1362 // rendering thread
1363 shared int diedie = 0;
1365 enum D2DFrameTime = 55; // milliseconds
1366 enum MinFrameTime = 1000/60; // ~60 FPS
1368 public void renderThread (Tid starterTid) {
1369 enum BoolOptVarMsgMixin(string varname) =
1370 "if (msg.toggle) msg.value = !"~varname~";\n"~
1371 "if ("~varname~" != msg.value) "~varname~" = msg.value; else msg.showMessage = false;\n";
1373 send(starterTid, 42);
1374 try {
1375 MonoTime curtime = MonoTime.currTime;
1377 lastthink = curtime; // for interpolator
1378 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1379 MonoTime nextvframe = curtime;
1381 enum MaxFPSFrames = 16;
1382 float frtimes = 0.0f;
1383 int framenum = 0;
1384 int prevFPS = -1;
1385 int hushFrames = 6; // ignore first `hushFrames` frames overtime
1386 MonoTime prevFrameStartTime = curtime;
1388 bool vframeWasLost = false;
1390 void resetFrameTimers () {
1391 MonoTime curtime = MonoTime.currTime;
1392 lastthink = curtime; // for interpolator
1393 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1394 nextvframe = curtime;
1397 void loadNewLevel (string name) {
1399 if (levelLoaded) {
1400 conwriteln("ERROR: can't load new levels yet");
1401 return;
1404 if (name.length == 0) {
1405 conwriteln("ERROR: can't load empty level!");
1407 conwriteln("loading map '", name, "'");
1408 loadMap(name);
1409 resetFrameTimers();
1412 conRegFunc!({
1413 string mn = genNextMapName(0);
1414 if (mn.length) {
1415 nextmapname = null; // clear "exit" flag
1416 loadNewLevel(mn);
1417 } else {
1418 conwriteln("can't skip level");
1420 })("skiplevel", "skip current level");
1422 conRegFunc!({
1423 inEditMode = !inEditMode;
1424 if (inEditMode) sdwindow.hideCursor(); else sdwindow.showCursor();
1425 })("ed_toggle", "toggle editor");
1427 conRegFunc!({
1428 if (inEditMode) {
1429 inEditMode = false;
1430 sdwindow.showCursor();
1432 })("ed_exit", "exit from editor");
1434 conRegFunc!((string mapname) {
1435 nextmapname = null; // clear "exit" flag
1436 loadNewLevel(mapname);
1437 })("map", "load map");
1439 void receiveMessages () {
1440 for (;;) {
1441 import core.time : Duration;
1442 //conwriteln("rendering thread: waiting for messages...");
1443 auto got = receiveTimeout(
1444 Duration.zero, // don't wait
1445 (TMsgMessage msg) {
1446 addMessage(msg.text[0..msg.textlen], msg.pauseMsecs, msg.noreplace);
1448 (TMsgTestLightMove msg) {
1449 testLightX = msg.x;
1450 testLightY = msg.y;
1451 testLightMoved = true;
1453 (TMsgMouseEvent msg) { editorMouseEvent(msg); },
1454 (TMsgKeyEvent msg) { editorKeyEvent(msg); },
1455 (TMsgChar msg) { concliChar(msg.ch); },
1456 (Variant v) {
1457 conwriteln("WARNING: unknown thread message received and ignored");
1460 if (!got) {
1461 // no more messages
1462 //conwriteln("rendering thread: no more messages");
1463 break;
1466 if (nextmapname.length) {
1467 string mn = nextmapname;
1468 nextmapname = null; // clear "exit" flag
1469 loadNewLevel(mn);
1473 void processConsoleCommands () {
1474 cbufLock();
1475 scope(exit) cbufUnlock();
1476 concmdDoAll();
1479 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1480 bool doThinkFrame () {
1481 if (curtime >= nextthink) {
1482 lastthink = curtime;
1483 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
1484 if (levelLoaded) {
1485 // save snapshot and other data for interpolator
1486 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
1487 if (!gamePaused && !inEditMode) {
1488 // process actors
1489 doActorsThink();
1490 dotThink();
1493 // some timing
1494 auto tm = MonoTime.currTime;
1495 int thinkTime = cast(int)((tm-curtime).total!"msecs");
1496 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
1497 curtime = tm;
1498 return true;
1499 } else {
1500 return false;
1504 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1505 bool doVFrame () {
1506 version(dont_use_vsync) {
1507 // timer
1508 enum doCheckTime = true;
1509 } else {
1510 // vsync
1511 __gshared bool prevLost = false;
1512 bool doCheckTime = vframeWasLost;
1513 if (vframeWasLost) {
1514 if (!prevLost) {
1515 { import core.stdc.stdio; printf("frame was lost!\n"); }
1517 prevLost = true;
1518 } else {
1519 prevLost = false;
1522 if (doCheckTime) {
1523 if (curtime < nextvframe) return false;
1524 version(dont_use_vsync) {
1525 if (curtime > nextvframe) {
1526 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
1527 if (overtime > 2500) {
1528 if (hushFrames) {
1529 --hushFrames;
1530 } else {
1531 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
1537 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
1538 bool ctset = false;
1540 sdwindow.mtLock();
1541 scope(exit) sdwindow.mtUnlock();
1542 ctset = sdwindow.setAsCurrentOpenGlContextNT;
1544 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1545 if (ctset) {
1546 // render scene
1547 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
1548 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1549 processConsoleCommands();
1550 if (levelLoaded) {
1551 renderScene(curtime);
1552 } else {
1553 //renderLoading(curtime);
1555 sdwindow.mtLock();
1556 scope(exit) sdwindow.mtUnlock();
1557 sdwindow.swapOpenGlBuffers();
1558 glFinish();
1559 sdwindow.releaseCurrentOpenGlContext();
1560 vframeWasLost = false;
1561 } else {
1562 vframeWasLost = true;
1563 { import core.stdc.stdio; printf("xframe was lost!\n"); }
1565 curtime = MonoTime.currTime;
1566 return true;
1569 for (;;) {
1570 if (sdwindow.closed) break;
1571 if (atomicLoad(diedie) > 0) break;
1573 curtime = MonoTime.currTime;
1574 auto fstime = curtime;
1576 doThinkFrame(); // this will fix curtime if necessary
1577 if (doVFrame()) {
1578 if (!vframeWasLost) {
1579 // fps
1580 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
1581 prevFrameStartTime = curtime;
1582 frtimes += frameTime;
1583 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
1584 import std.string : format;
1585 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
1586 if (newFPS != prevFPS) {
1587 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
1588 prevFPS = newFPS;
1590 framenum = 0;
1591 frtimes = 0.0f;
1596 curtime = MonoTime.currTime;
1598 // now sleep until next "video" or "think" frame
1599 if (nextthink > curtime && nextvframe > curtime) {
1600 // let's decide
1601 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
1602 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
1603 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
1604 sleepAtMaxMsecs(sleepTime);
1605 //curtime = MonoTime.currTime;
1608 } catch (Throwable e) {
1609 // here, we are dead and fucked (the exact order doesn't matter)
1610 import core.stdc.stdlib : abort;
1611 import core.stdc.stdio : fprintf, stderr;
1612 import core.memory : GC;
1613 GC.disable(); // yeah
1614 thread_suspendAll(); // stop right here, you criminal scum!
1615 auto s = e.toString();
1616 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
1617 abort(); // die, you bitch!
1619 import core.stdc.stdio;
1620 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1621 import std.stdio : stderr;
1622 writeln(
1623 for (;;) {
1624 if (sdwindow.closed) break;
1625 if (atomicLoad(diedie) > 0) break;
1626 sleepAtMaxMsecs(100);
1630 atomicStore(diedie, 2);
1634 // ////////////////////////////////////////////////////////////////////////// //
1635 __gshared Tid renderTid;
1636 shared bool renderThreadStarted = false;
1639 public void startRenderThread () {
1640 if (!cas(&renderThreadStarted, false, true)) {
1641 assert(0, "render thread already started!");
1643 renderTid = spawn(&renderThread, thisTid);
1644 setMaxMailboxSize(renderTid, 1024, OnCrowding.throwException); //FIXME
1645 // wait for "i'm ready" signal
1646 receive(
1647 (int ok) {
1648 if (ok != 42) assert(0, "wtf?!");
1651 conwriteln("rendering thread started");
1655 // ////////////////////////////////////////////////////////////////////////// //
1656 public void closeWindow () {
1657 if (atomicLoad(diedie) != 2) {
1658 atomicStore(diedie, 1);
1659 while (atomicLoad(diedie) != 2) {}
1661 if (!sdwindow.closed) {
1662 flushGui();
1663 sdwindow.close();
1668 // ////////////////////////////////////////////////////////////////////////// //
1669 // thread messages
1672 // ////////////////////////////////////////////////////////////////////////// //
1673 struct TMsgMouseEvent {
1674 MouseEventType type;
1675 int x, y;
1676 int dx, dy;
1677 MouseButton button; /// See $(LREF MouseButton)
1678 int modifierState; /// See $(LREF ModifierState)
1681 public void postMouseEvent() (in auto ref MouseEvent evt) {
1682 if (!atomicLoad(renderThreadStarted)) return;
1683 TMsgMouseEvent msg;
1684 msg.type = evt.type;
1685 msg.x = evt.x;
1686 msg.y = evt.y;
1687 msg.dx = evt.dx;
1688 msg.dy = evt.dy;
1689 msg.button = evt.button;
1690 msg.modifierState = evt.modifierState;
1691 send(renderTid, msg);
1695 // ////////////////////////////////////////////////////////////////////////// //
1696 struct TMsgKeyEvent {
1697 Key key;
1698 uint hardwareCode;
1699 bool pressed;
1700 dchar character;
1701 uint modifierState;
1704 public void postKeyEvent() (in auto ref KeyEvent evt) {
1705 if (!atomicLoad(renderThreadStarted)) return;
1706 TMsgKeyEvent msg;
1707 msg.key = evt.key;
1708 msg.pressed = evt.pressed;
1709 msg.character = evt.character;
1710 msg.modifierState = evt.modifierState;
1711 send(renderTid, msg);
1715 // ////////////////////////////////////////////////////////////////////////// //
1716 struct TMsgTestLightMove {
1717 int x, y;
1720 public void postTestLightMove (int x, int y) {
1721 if (!atomicLoad(renderThreadStarted)) return;
1722 auto msg = TMsgTestLightMove(x, y);
1723 send(renderTid, msg);
1727 // ////////////////////////////////////////////////////////////////////////// //
1728 struct TMsgMessage {
1729 char[256] text;
1730 uint textlen;
1731 int pauseMsecs;
1732 bool noreplace;
1735 public void postAddMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
1736 if (!atomicLoad(renderThreadStarted)) return;
1737 if (msgtext.length > TMsgMessage.text.length) msgtext = msgtext[0..TMsgMessage.text.length];
1738 TMsgMessage msg;
1739 msg.textlen = cast(uint)msgtext.length;
1740 if (msg.textlen) msg.text[0..msg.textlen] = msgtext[0..msg.textlen];
1741 msg.pauseMsecs = pauseMsecs;
1742 msg.noreplace = noreplace;
1743 send(renderTid, msg);
1747 // ////////////////////////////////////////////////////////////////////////// //
1748 struct TMsgChar {
1749 char ch;
1752 public void postChar (char ch) {
1753 if (!atomicLoad(renderThreadStarted)) return;
1754 TMsgChar msg;
1755 msg.ch = ch;
1756 send(renderTid, msg);
1760 // ////////////////////////////////////////////////////////////////////////// //
1761 public void concmd (const(char)[] cmd) {
1762 //if (!atomicLoad(renderThreadStarted)) return;
1763 cbufLock();
1764 scope(exit) cbufUnlock();
1765 concmdAdd(cmd);