console font made smaller and converted to koi8
[dd2d.git] / render.d
bloba9e88d3c39b1fc754a3026eb8dd52005a6f1fca0
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);
521 void putLine(T) (auto ref T line, usize pos=0) {
522 if (y+conCharHeight <= 0) return;
523 int w = XOfs;
524 usize sp = pos;
525 while (sp < line.length) {
526 char ch = line[sp++];
527 int cw = conCharWidth(ch);
528 if ((w += cw) > me.width-XOfs) { w -= cw; --sp; break; }
530 if (sp < line.length) putLine(line, sp); // recursive put tail
531 // draw line
532 if (skipLines-- <= 0) {
533 while (pos < sp) conDrawChar(line[pos++]);
534 glPopMatrix();
535 glPushMatrix();
536 y -= conCharHeight;
537 glTranslatef(XOfs, y, 0);
541 foreach (auto line; conbufLinesRev) {
542 putLine(line);
543 if (y+conCharHeight <= 0) break;
549 // ////////////////////////////////////////////////////////////////////////// //
550 // should be called when OpenGL is initialized
551 void loadMap (string mapname) {
552 mapscripts.runUnloading(); // "map unloading" script
553 clearMapScripts();
555 if (map !is null) map.clear();
556 map = new LevelMap(mapname);
557 curmapname = mapname;
559 ugInit(map.width*TileSize, map.height*TileSize);
561 map.oglBuildMega();
562 mapTilesChanged = 0;
564 if (fboLevel !is null) fboLevel.clear();
565 if (fboLevelLight !is null) fboLevelLight.clear();
566 if (fboOrigBack !is null) fboOrigBack.clear();
567 if (fboLMaskSmall !is null) fboLMaskSmall.clear();
569 fboLevel = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // final level render will be here
570 fboLevelLight = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest); // level lights will be rendered here
571 fboOrigBack = new FBO(map.width*TileSize, map.height*TileSize, Texture.Option.Nearest/*, Texture.Option.Depth*/); // background+foreground
572 fboLMaskSmall = new FBO(map.width, map.height, Texture.Option.Nearest); // small lightmask
574 shadToPolar.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize-1, map.height*TileSize-1); });
575 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
576 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
577 shadAmbient.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*TileSize, map.height*TileSize); });
579 glActiveTexture(GL_TEXTURE0+0);
580 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
581 orthoCamera(vlWidth, vlHeight);
583 Actor.resetStorage();
585 setupMapScripts();
586 mapscripts.runInit();
587 loadMapMonsters();
588 dotInit();
589 mapscripts.runLoaded();
591 // save first snapshot
592 if (prevFrameActorsData.length == 0) prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
593 prevFrameActorOfs[] = uint.max; // just for fun
594 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
596 levelLoaded = true;
598 { import core.memory : GC; GC.collect(); }
602 // ////////////////////////////////////////////////////////////////////////// //
603 //FIXME: optimize!
604 __gshared uint mapTilesChanged = 0;
607 //WARNING! this can be called only from DACS, so we don't have to sync it!
608 public void mapDirty (uint layermask) { mapTilesChanged |= layermask; }
611 void rebuildMapMegaTextures () {
612 //fbo.replaceTexture
613 //mapTilesChanged = false;
614 //map.clearMegaTextures();
615 map.oglBuildMega(mapTilesChanged);
616 mapTilesChanged = 0;
617 dotsAwake(); // let dormant dots fall
621 // ////////////////////////////////////////////////////////////////////////// //
622 // messages
623 struct Message {
624 enum Phase { FadeIn, Stay, FadeOut }
625 Phase phase;
626 int alpha;
627 int pauseMsecs;
628 MonoTime removeTime;
629 char[256] text;
630 usize textlen;
633 //private import core.sync.mutex : Mutex;
635 __gshared Message[128] messages;
636 __gshared uint messagesUsed = 0;
638 //__gshared Mutex messageLock;
639 //shared static this () { messageLock = new Mutex(); }
642 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
643 //messageLock.lock();
644 //scope(exit) messageLock.unlock();
645 if (msgtext.length == 0) return;
646 conwriteln(msgtext);
647 if (pauseMsecs <= 50) return;
648 if (messagesUsed == messages.length) {
649 // remove top message
650 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
651 messages.ptr[0].alpha = 255;
652 --messagesUsed;
654 // quick replace
655 if (!noreplace && messagesUsed == 1) {
656 switch (messages.ptr[0].phase) {
657 case Message.Phase.FadeIn:
658 messages.ptr[0].phase = Message.Phase.FadeOut;
659 break;
660 case Message.Phase.Stay:
661 messages.ptr[0].phase = Message.Phase.FadeOut;
662 messages.ptr[0].alpha = 255;
663 break;
664 default:
667 auto msg = messages.ptr+messagesUsed;
668 ++messagesUsed;
669 msg.phase = Message.Phase.FadeIn;
670 msg.alpha = 0;
671 msg.pauseMsecs = pauseMsecs;
672 // copy text
673 if (msgtext.length > msg.text.length) {
674 msg.text = msgtext[0..msg.text.length];
675 msg.textlen = msg.text.length;
676 } else {
677 msg.text[0..msgtext.length] = msgtext[];
678 msg.textlen = msgtext.length;
683 void doMessages (MonoTime curtime) {
684 //messageLock.lock();
685 //scope(exit) messageLock.unlock();
687 if (messagesUsed == 0) return;
688 glEnable(GL_BLEND);
689 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
691 Message* msg;
693 again:
694 msg = messages.ptr;
695 final switch (msg.phase) {
696 case Message.Phase.FadeIn:
697 if ((msg.alpha += 10) >= 255) {
698 msg.phase = Message.Phase.Stay;
699 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
700 goto case; // to stay
702 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
703 break;
704 case Message.Phase.Stay:
705 if (msg.removeTime <= curtime) {
706 msg.alpha = 255;
707 msg.phase = Message.Phase.FadeOut;
708 goto case; // to fade
710 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
711 break;
712 case Message.Phase.FadeOut:
713 if ((msg.alpha -= 10) <= 0) {
714 if (--messagesUsed == 0) return;
715 // remove this message
716 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
717 goto again;
719 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
720 break;
723 smDrawText(10, 10, msg.text[0..msg.textlen]);
727 // ////////////////////////////////////////////////////////////////////////// //
728 //mixin(Actor.FieldPropMixin!("0drawlistpos", uint));
730 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
731 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
732 mixin(Actor.FieldGetMixin!("x", int));
733 mixin(Actor.FieldGetMixin!("y", int));
734 mixin(Actor.FieldGetMixin!("s", int));
735 mixin(Actor.FieldGetMixin!("radius", int));
736 mixin(Actor.FieldGetMixin!("height", int));
737 mixin(Actor.FieldGetMixin!("flags", uint));
738 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
739 mixin(Actor.FieldGetMixin!("zAnimidx", int));
740 mixin(Actor.FieldGetMixin!("dir", uint));
741 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
742 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
743 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
745 //mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
746 //mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
747 mixin(Actor.FieldGetPtrMixin!("x", int));
748 mixin(Actor.FieldGetPtrMixin!("y", int));
749 //mixin(Actor.FieldGetPtrMixin!("flags", uint));
750 //mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
751 //mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
752 //mixin(Actor.FieldGetPtrMixin!("dir", uint));
753 //mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
754 //mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
755 //mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
758 // ////////////////////////////////////////////////////////////////////////// //
759 __gshared int vportX0, vportY0, vportX1, vportY1;
762 // ////////////////////////////////////////////////////////////////////////// //
763 void renderLightAmbient() (int lightX, int lightY, int lightW, int lightH, in auto ref SVec4F lcol) {
764 //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));
765 if (lightW < 1 || lightH < 1) return;
766 int lightX1 = lightX+lightW-1;
767 int lightY1 = lightY+lightH-1;
768 // clip light to viewport
769 if (lightX < vportX0) lightX = vportX0;
770 if (lightY < vportY0) lightY = vportY0;
771 if (lightX1 > vportX1) lightX1 = vportX1;
772 if (lightY1 > vportY1) lightY1 = vportY1;
773 // is this light visible?
774 //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));
775 if (lightX1 < lightX || lightY1 < lightY || lightX > vportX1 || lightY > vportY1 || lightX1 < vportX0 || lightY1 < vportY0) return;
776 //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));
778 fboLevelLight.exec({
779 bindTexture(0);
780 glEnable(GL_BLEND);
781 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
782 //glDisable(GL_BLEND);
783 orthoCamera(map.width*TileSize, map.height*TileSize);
784 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
785 shadAmbient.exec((Shader shad) {
786 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
787 //shad["lightPos"] = SVec2F(lightX, lightY);
788 glRectf(lightX, lightY, lightX1, lightY1);
794 // ////////////////////////////////////////////////////////////////////////// //
795 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
796 if (lightRadius < 2) return;
797 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
798 int lightSize = lightRadius*2;
799 // is this light visible?
800 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*TileSize || lightY-lightRadius >= map.height*TileSize) return;
802 // out of viewport -- do nothing
803 if (lightX+lightRadius < vportX0 || lightY+lightRadius < vportY0) return;
804 if (lightX-lightRadius > vportX1 || lightY-lightRadius > vportY1) return;
806 if (lightX >= 0 && lightY >= 0 && lightX < map.width*TileSize && lightY < map.height*TileSize &&
807 map.teximgs[map.LightMask].imageData.colors.ptr[lightY*(map.width*TileSize)+lightX].a > 190) return;
809 // common color for all the following
810 glDisable(GL_BLEND);
811 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
813 // build 1d distance map to fboShadowMapId
814 fboDistMap.ptr[lightRadius].exec({
815 // no need to clear it, shader will take care of that
816 shadToPolar.exec((Shader shad) {
817 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
818 shad["lightPos"] = SVec2F(lightX, lightY);
819 orthoCamera(lightSize, 1);
820 // it doesn't matter what we will draw here, so just draw filled rect
821 glRectf(0, 0, lightSize, 1);
825 // build light texture for blending
826 fboOccluders.exec({
827 // no need to clear it, shader will take care of that
828 // debug
829 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
830 //glClear(GL_COLOR_BUFFER_BIT);
831 shadBlur.exec((Shader shad) {
832 shad["lightTexSize"] = SVec2F(lightSize, MaxLightRadius*2); // x: size of distmap; y: size of this texture
833 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
834 shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
835 orthoCamera(fboOccluders.tex.width, fboOccluders.tex.height);
836 //drawAtXY(fboDistMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
837 bindTexture(fboDistMap.ptr[lightRadius].tex.tid);
838 glBegin(GL_QUADS);
839 glTexCoord2f(0.0f, 0.0f); glVertex2i(0, 0); // top-left
840 glTexCoord2f(1.0f, 0.0f); glVertex2i(lightSize, 0); // top-right
841 glTexCoord2f(1.0f, 1.0f); glVertex2i(lightSize, lightSize); // bottom-right
842 glTexCoord2f(0.0f, 1.0f); glVertex2i(0, lightSize); // bottom-left
843 glEnd();
847 // blend light texture
848 fboLevelLight.exec({
849 glEnable(GL_BLEND);
850 //glDisable(GL_BLEND);
851 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
852 orthoCamera(fboLevelLight.tex.width, fboLevelLight.tex.height);
853 //drawAtXY(fboOccluders.tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
854 float occe = 1.0f*lightSize/(MaxLightRadius*2);
855 float occs = 1.0f-occe;
856 int x0 = lightX-lightRadius+0;
857 int y1 = lightY-lightRadius+0;
858 int x1 = lightX+lightRadius-1+1;
859 int y0 = lightY+lightRadius-1+1;
860 bindTexture(fboOccluders.tex.tid);
861 glBegin(GL_QUADS);
863 glTexCoord2f(0.0f, 0.0f); glVertex2i(x0, y0); // top-left
864 glTexCoord2f(occe, 0.0f); glVertex2i(x1, y0); // top-right
865 glTexCoord2f(occe, occe); glVertex2i(x1, y1); // bottom-right
866 glTexCoord2f(0.0f, occe); glVertex2i(x0, y1); // bottom-left
868 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
869 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
870 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
871 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
872 glEnd();
874 bindTexture(0);
875 glRectf(x0, y0, x1, y1);
877 // and blend it again, with the shader that will touch only occluders
878 shadBlurOcc.exec((Shader shad) {
879 //shad["lightTexSize"] = SVec2F(lightSize, lightSize);
880 shad["lightTexSize"] = SVec2F(lightSize, fboOccluders.tex.height);
881 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
882 shad["lightPos"] = SVec2F(lightX, lightY);
883 //shad["lightPos"] = SVec2F(lightX-lightRadius, lightY-lightRadius);
884 bindTexture(fboOccluders.tex.tid);
885 glBegin(GL_QUADS);
886 glTexCoord2f(0.0f, occs); glVertex2i(x0, y0); // top-left
887 glTexCoord2f(occe, occs); glVertex2i(x1, y0); // top-right
888 glTexCoord2f(occe, 1.0f); glVertex2i(x1, y1); // bottom-right
889 glTexCoord2f(0.0f, 1.0f); glVertex2i(x0, y1); // bottom-left
890 glEnd();
891 //drawAtXY(fboOccluders.tex.tid, lightX-lightRadius, lightY-lightRadius, lightSize, lightSize, mirrorY:true);
897 // ////////////////////////////////////////////////////////////////////////// //
898 __gshared int testLightX = vlWidth/2, testLightY = vlHeight/2;
899 __gshared bool testLightMoved = false;
900 //__gshared int mapOfsX, mapOfsY;
901 //__gshared bool movement = false;
902 __gshared float iLiquidTime = 0.0;
903 //__gshared bool altMove = false;
906 void renderScene (MonoTime curtime) {
907 //enum BackIntens = 0.05f;
908 enum BackIntens = 0.0f;
910 gloStackClear();
911 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
912 if (gamePaused || inEditMode) atob = 1.0f;
913 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
916 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
917 int curfp = cast(int)((curtime-lastthink).total!"msecs");
918 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
922 int mofsx, mofsy; // camera offset, will be set in background layer builder
924 if (mapTilesChanged != 0) rebuildMapMegaTextures();
926 // build background layer
927 fboOrigBack.exec({
928 //glDisable(GL_BLEND);
929 //glClearDepth(1.0f);
930 //glDepthFunc(GL_LESS);
931 //glDepthFunc(GL_NEVER);
932 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
933 glClear(GL_COLOR_BUFFER_BIT/*|GL_DEPTH_BUFFER_BIT*/);
934 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
935 orthoCamera(map.width*TileSize, map.height*TileSize);
937 glEnable(GL_BLEND);
938 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
939 // draw sky
941 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
942 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*TileSize, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
943 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*TileSize, map.MapSize*TileSize, map.MapSize*TileSize);
944 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*TileSize, map.MapSize*TileSize);
946 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*TileSize, map.MapSize*TileSize);
947 // draw background
948 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
949 // draw distorted liquid areas
950 shadLiquidDistort.exec((Shader shad) {
951 shad["iDistortTime"] = iLiquidTime;
952 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
954 // monsters, items; we'll do linear interpolation here
955 glColor3f(1.0f, 1.0f, 1.0f);
956 //glEnable(GL_DEPTH_TEST);
957 attachedLightCount = 0;
959 // who cares about memory?!
960 // draw order: players, items, monsters, other
961 static struct DrawInfo {
962 ActorDef adef;
963 ActorId aid;
964 int actorX, actorY;
965 @disable this (this); // no copies
967 enum { Pixels, Players, Items, Monsters, Other }
968 __gshared DrawInfo[65536][4] drawlists;
969 __gshared uint[4] dlpos;
970 DrawInfo camchickdi;
972 dlpos[] = 0;
974 Actor.forEach((ActorId me) {
975 //me.fprop_0drawlistpos = 0;
976 if (auto adef = findActorDef(me)) {
977 uint dlnum = Other;
978 switch (adef.classtype.get) {
979 case "monster": dlnum = (adef.classname.get != "Player" ? Monsters : Players); break;
980 case "item": dlnum = Items; break;
981 default: dlnum = Other; break;
983 if (me.fget_flags&AF_PIXEL) dlnum = Pixels;
984 int actorX, actorY; // current actor position
986 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
987 if (frameInterpolation && ofs < uint.max-1 && (me.fget_flags&AF_TELEPORT) == 0 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
988 import core.stdc.math : roundf;
989 auto xptr = prevFrameActorsData.ptr+ofs;
990 int ox = xptr.fgetp_x;
991 int nx = me.fget_x;
992 int oy = xptr.fgetp_y;
993 int ny = me.fget_y;
994 actorX = cast(int)(ox+roundf((nx-ox)*atob));
995 actorY = cast(int)(oy+roundf((ny-oy)*atob));
996 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
997 } else {
998 actorX = me.fget_x;
999 actorY = me.fget_y;
1002 if (me.id == cameraChick.id) {
1003 camchickdi.adef = adef;
1004 camchickdi.aid = me;
1005 camchickdi.actorX = actorX;
1006 camchickdi.actorY = actorY;
1008 // draw sprite
1009 if ((me.fget_flags&AF_NODRAW) == 0) {
1010 //auto dl = &drawlists[dlnum][dlpos.ptr[dlnum]];
1011 //me.fprop_0drawlistpos = (dlpos.ptr[dlnum]&0xffff)|((dlnum&0xff)<<16);
1012 auto dl = drawlists.ptr[dlnum].ptr+dlpos.ptr[dlnum];
1013 ++dlpos.ptr[dlnum];
1014 dl.adef = adef;
1015 dl.aid = me;
1016 dl.actorX = actorX;
1017 dl.actorY = actorY;
1019 // process attached lights
1020 if ((me.fget_flags&AF_NOLIGHT) == 0) {
1021 uint alr = me.fget_attLightRGBX;
1022 bool isambient = (me.fget_classtype.get == "light" && me.fget_classname.get == "Ambient");
1023 if ((alr&0xff) >= 4 || (isambient && me.fget_radius >= 1 && me.fget_height >= 1)) {
1024 //if (isambient) conwriteln("isambient: ", isambient, "; x=", me.fget_x, "; y=", me.fget_y, "; w=", me.fget_radius, "; h=", me.fget_height);
1025 // yep, add it
1026 auto li = attachedLights.ptr+attachedLightCount;
1027 ++attachedLightCount;
1028 li.type = (!isambient ? AttachedLightInfo.Type.Point : AttachedLightInfo.Type.Ambient);
1029 li.x = actorX+me.fget_attLightXOfs;
1030 li.y = actorY+me.fget_attLightYOfs;
1031 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
1032 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
1033 li.uncolored = true;
1034 } else {
1035 li.g = ((alr>>16)&0xff)/255.0f;
1036 li.b = ((alr>>8)&0xff)/255.0f;
1037 li.uncolored = false;
1039 li.radius = (alr&0xff);
1040 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
1041 if (isambient) {
1042 li.w = me.fget_radius;
1043 li.h = me.fget_height;
1047 } else {
1048 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
1052 // draw actor lists
1053 foreach_reverse (uint dlnum; 0..drawlists.length) {
1054 if (dlnum == Pixels) continue;
1055 auto dl = drawlists.ptr[dlnum].ptr;
1056 if (dlnum == Players) dl += dlpos.ptr[dlnum]-1;
1057 foreach (uint idx; 0..dlpos.ptr[dlnum]) {
1058 auto me = dl.aid;
1059 if (auto isp = dl.adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
1060 //drawAtXY(isp.tex, dl.actorX-isp.vga.sx, dl.actorY-isp.vga.sy);
1061 isp.drawAtXY(dl.actorX, dl.actorY);
1063 if (dlnum != Players) ++dl; else --dl;
1066 // draw pixels
1067 if (dlpos[Pixels]) {
1068 bindTexture(0);
1069 bool pointsStarted = false;
1070 Color lastColor = Color(0, 0, 0, 0);
1071 auto dl = drawlists.ptr[Pixels].ptr;
1072 foreach (uint idx; 0..dlpos.ptr[Pixels]) {
1073 auto me = dl.aid;
1074 auto s = me.fget_s;
1075 if (s < 0 || s > 255) continue; //FIXME
1076 Color clr = d2dpal.ptr[s&0xff];
1077 if (clr.a == 0) continue;
1078 if (clr != lastColor) {
1079 if (pointsStarted) glEnd();
1080 glColor4f(clr.r/255.0f, clr.g/255.0f, clr.b/255.0f, clr.a/255.0f);
1081 lastColor = clr;
1082 pointsStarted = false;
1084 if (!pointsStarted) {
1085 glBegin(GL_POINTS);
1086 pointsStarted = true;
1088 glVertex2i(dl.actorX, dl.actorY);
1089 ++dl;
1091 if (pointsStarted) {
1092 glEnd();
1093 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1097 // camera movement
1098 if (/*altMove || movement ||*/ scale == 1 || !cameraChick.valid) {
1099 mofsx = 0;
1100 mofsy = 0;
1101 vportX0 = 0;
1102 vportY0 = 0;
1103 vportX1 = map.width*TileSize;
1104 vportY1 = map.height*TileSize;
1105 } else {
1106 int tiltHeight = /*getMapViewHeight()*/(vlHeight/scale)/4;
1107 int vy = cameraChick.looky!int;
1108 if (vy < -tiltHeight) vy = -tiltHeight; else if (vy > tiltHeight) vy = tiltHeight;
1109 int swdt = vlWidth/scale;
1110 int shgt = vlHeight/scale;
1111 int x = camchickdi.actorX-swdt/2;
1112 int y = (camchickdi.actorY+vy)-shgt/2;
1113 if (x < 0) x = 0; else if (x >= map.width*TileSize-swdt) x = map.width*TileSize-swdt-1;
1114 if (y < 0) y = 0; else if (y >= map.height*TileSize-shgt) y = map.height*TileSize-shgt-1;
1115 mofsx = x*2;
1116 mofsy = y*2;
1117 vportX0 = mofsx/scale;
1118 vportY0 = mofsy/scale;
1119 vportX1 = vportX0+vlWidth/scale;
1120 vportY1 = vportY0+vlHeight/scale;
1123 //glDisable(GL_DEPTH_TEST);
1124 // draw dots
1125 dotDraw(atob);
1126 // do liquid coloring
1127 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
1128 // foreground -- hide secrets, draw lifts and such
1129 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
1132 enum r = 255;
1133 enum g = 0;
1134 enum b = 0;
1135 enum a = 255;
1136 bindTexture(0);
1137 glColor4f(r/255.0f, g/255.0f, b/255.0f, a/255.0f);
1138 glColor4f(1.0f, 0.0f, 0.0f, 1.0f);
1139 if (cameraChick.valid) {
1140 glBegin(GL_POINTS);
1141 glVertex2i(camchickdi.actorX, camchickdi.actorY-70);
1142 glEnd();
1143 //glRectf(camchickdi.actorX, camchickdi.actorY-70, camchickdi.actorX+4, camchickdi.actorY-70+4);
1145 //glRectf(0, 0, 300, 300);
1146 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1152 if (doLighting) {
1153 glDisable(GL_BLEND);
1154 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1156 // make smaller occluder texture, so we can trace faster
1157 //assert(fboLMaskSmall.tex.width == map.width);
1158 //assert(fboLMaskSmall.tex.height == map.height);
1159 fboLMaskSmall.exec({
1160 orthoCamera(map.width, map.height);
1161 drawAtXY(map.texgl.ptr[map.LightMask].tid, 0, 0, map.width, map.height, mirrorY:true);
1164 // clear light layer
1165 fboLevelLight.exec({
1166 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1167 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
1168 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
1169 glClear(GL_COLOR_BUFFER_BIT);
1172 // texture 1 is background
1173 glActiveTexture(GL_TEXTURE0+1);
1174 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
1175 // texture 2 is occluders
1176 glActiveTexture(GL_TEXTURE0+2);
1177 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
1178 // texture 3 is small occluder map
1179 glActiveTexture(GL_TEXTURE0+3);
1180 glBindTexture(GL_TEXTURE_2D, fboLMaskSmall.tex.tid);
1181 // done texture assign
1182 glActiveTexture(GL_TEXTURE0+0);
1185 enum LYOfs = 1;
1187 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1188 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
1189 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1190 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1191 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1192 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1193 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1194 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
1195 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1196 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
1198 renderLight(24*TileSize+4, (24+18)*TileSize-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
1200 renderLight(280, 330, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
1203 foreach (; 0..1) {
1204 // attached lights
1205 foreach (ref li; attachedLights[0..attachedLightCount]) {
1206 if (li.type == AttachedLightInfo.Type.Ambient) {
1207 //conwriteln("ambient: x=", li.x, "; y=", li.y, "; w=", li.w, "; h=", li.h);
1208 // ambient light
1209 if (li.uncolored) {
1210 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(0.0f, 0.0f, 0.0f, li.r));
1211 } else {
1212 renderLightAmbient(li.x, li.y, li.w, li.h, SVec4F(li.r, li.g, li.b, 1.0f));
1214 } else if (li.type == AttachedLightInfo.Type.Point) {
1215 // point light
1216 if (li.uncolored) {
1217 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
1218 } else {
1219 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
1226 if (testLightMoved) {
1227 testLightX = testLightX/scale+mofsx/scale;
1228 testLightY = testLightY/scale+mofsy/scale;
1229 testLightMoved = false;
1231 foreach (immutable _; 0..1) {
1232 renderLight(testLightX, testLightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
1236 glActiveTexture(GL_TEXTURE0+1);
1237 glBindTexture(GL_TEXTURE_2D, 0);
1238 glActiveTexture(GL_TEXTURE0+2);
1239 glBindTexture(GL_TEXTURE_2D, 0);
1240 glActiveTexture(GL_TEXTURE0+3);
1241 glBindTexture(GL_TEXTURE_2D, 0);
1242 glActiveTexture(GL_TEXTURE0+0);
1245 // draw scaled level
1247 shadScanlines.exec((Shader shad) {
1248 shad["scanlines"] = scanlines;
1249 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
1250 glClear(GL_COLOR_BUFFER_BIT);
1251 orthoCamera(vlWidth, vlHeight);
1252 //orthoCamera(map.width*TileSize*scale, map.height*TileSize*scale);
1253 //glMatrixMode(GL_MODELVIEW);
1254 //glLoadIdentity();
1255 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
1256 // somehow, FBO objects are mirrored; wtf?!
1257 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1258 //glLoadIdentity();
1263 fboLevelLight.exec({
1264 smDrawText(map.width*TileSize/2, map.height*TileSize/2, "Testing...");
1269 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
1271 glDisable(GL_BLEND);
1274 fboOrigBack.exec({
1275 //auto img = smfont.ptr[0x39];
1276 auto img = fftest;
1277 if (img !is null) {
1278 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
1279 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
1286 { // http://stackoverflow.com/questions/7207422/setting-up-opengl-multiple-render-targets
1287 GLenum[1] buffers = [ GL_BACK_LEFT, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1288 //GLenum[1] buffers = [ GL_NONE, /*GL_COLOR_ATTACHMENT0_EXT*/ ];
1289 glDrawBuffers(1, buffers.ptr);
1294 orthoCamera(vlWidth, vlHeight);
1295 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
1296 drawAtXY(tex, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1298 if (levelLoaded) {
1299 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1300 //orthoCamera(map.width*TileSize, map.height*TileSize);
1301 glEnable(GL_BLEND);
1302 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1303 hudScripts.runDraw();
1306 //drawAtXY(map.texgl.ptr[map.LightMask].tid, -mofsx, -mofsy, map.width*TileSize*scale, map.height*TileSize*scale, mirrorY:true);
1307 //drawAtXY(fboLMaskSmall.tex.tid, 0, 0, map.width*TileSize, map.height*TileSize);
1309 if (inEditMode) {
1310 glEnable(GL_BLEND);
1311 //glBlendFunc(GL_SRC_ALPHA, GL_ONE);
1312 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1313 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1314 editorUpdateImage();
1315 fboEditor.tex.setFromImage(editorImg);
1316 drawAtXY(fboEditor.tex, 0, 0);
1317 glDisable(GL_BLEND);
1320 doMessages(curtime);
1322 if (rConsoleVisible) {
1323 renderConsoleFBO();
1324 orthoCamera(vlWidth, vlHeight);
1325 glEnable(GL_BLEND);
1326 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
1327 glColor4f(1.0f, 1.0f, 1.0f, 0.7f);
1328 drawAtXY(fboConsole.tex, 0, rConsoleHeight-vlHeight, mirrorY:true);
1333 // ////////////////////////////////////////////////////////////////////////// //
1334 // returns time slept
1335 int sleepAtMaxMsecs (int msecs) {
1336 if (msecs > 0) {
1337 import core.sys.posix.signal : timespec;
1338 import core.sys.posix.time : nanosleep;
1339 timespec ts = void, tpassed = void;
1340 ts.tv_sec = 0;
1341 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
1342 nanosleep(&ts, &tpassed);
1343 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
1344 } else {
1345 return 0;
1350 // ////////////////////////////////////////////////////////////////////////// //
1351 mixin(import("editor.d"));
1354 // ////////////////////////////////////////////////////////////////////////// //
1355 // rendering thread
1356 shared int diedie = 0;
1358 enum D2DFrameTime = 55; // milliseconds
1359 enum MinFrameTime = 1000/60; // ~60 FPS
1361 public void renderThread (Tid starterTid) {
1362 enum BoolOptVarMsgMixin(string varname) =
1363 "if (msg.toggle) msg.value = !"~varname~";\n"~
1364 "if ("~varname~" != msg.value) "~varname~" = msg.value; else msg.showMessage = false;\n";
1366 send(starterTid, 42);
1367 try {
1368 MonoTime curtime = MonoTime.currTime;
1370 lastthink = curtime; // for interpolator
1371 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1372 MonoTime nextvframe = curtime;
1374 enum MaxFPSFrames = 16;
1375 float frtimes = 0.0f;
1376 int framenum = 0;
1377 int prevFPS = -1;
1378 int hushFrames = 6; // ignore first `hushFrames` frames overtime
1379 MonoTime prevFrameStartTime = curtime;
1381 bool vframeWasLost = false;
1383 void resetFrameTimers () {
1384 MonoTime curtime = MonoTime.currTime;
1385 lastthink = curtime; // for interpolator
1386 nextthink = curtime+dur!"msecs"(D2DFrameTime);
1387 nextvframe = curtime;
1390 void loadNewLevel (string name) {
1392 if (levelLoaded) {
1393 conwriteln("ERROR: can't load new levels yet");
1394 return;
1397 if (name.length == 0) {
1398 conwriteln("ERROR: can't load empty level!");
1400 conwriteln("loading map '", name, "'");
1401 loadMap(name);
1402 resetFrameTimers();
1405 conRegFunc!({
1406 string mn = genNextMapName(0);
1407 if (mn.length) {
1408 nextmapname = null; // clear "exit" flag
1409 loadNewLevel(mn);
1410 } else {
1411 conwriteln("can't skip level");
1413 })("skiplevel", "skip current level");
1415 conRegFunc!({
1416 inEditMode = !inEditMode;
1417 if (inEditMode) sdwindow.hideCursor(); else sdwindow.showCursor();
1418 })("ed_toggle", "toggle editor");
1420 conRegFunc!({
1421 if (inEditMode) {
1422 inEditMode = false;
1423 sdwindow.showCursor();
1425 })("ed_exit", "exit from editor");
1427 conRegFunc!((string mapname) {
1428 nextmapname = null; // clear "exit" flag
1429 loadNewLevel(mapname);
1430 })("map", "load map");
1432 void receiveMessages () {
1433 for (;;) {
1434 import core.time : Duration;
1435 //conwriteln("rendering thread: waiting for messages...");
1436 auto got = receiveTimeout(
1437 Duration.zero, // don't wait
1438 (TMsgMessage msg) {
1439 addMessage(msg.text[0..msg.textlen], msg.pauseMsecs, msg.noreplace);
1441 (TMsgTestLightMove msg) {
1442 testLightX = msg.x;
1443 testLightY = msg.y;
1444 testLightMoved = true;
1446 (TMsgMouseEvent msg) { editorMouseEvent(msg); },
1447 (TMsgKeyEvent msg) { editorKeyEvent(msg); },
1448 (TMsgChar msg) { concliChar(msg.ch); },
1449 (Variant v) {
1450 conwriteln("WARNING: unknown thread message received and ignored");
1453 if (!got) {
1454 // no more messages
1455 //conwriteln("rendering thread: no more messages");
1456 break;
1459 if (nextmapname.length) {
1460 string mn = nextmapname;
1461 nextmapname = null; // clear "exit" flag
1462 loadNewLevel(mn);
1466 void processConsoleCommands () {
1467 cbufLock();
1468 scope(exit) cbufUnlock();
1469 concmdDoAll();
1472 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1473 bool doThinkFrame () {
1474 if (curtime >= nextthink) {
1475 lastthink = curtime;
1476 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
1477 if (levelLoaded) {
1478 // save snapshot and other data for interpolator
1479 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
1480 if (!gamePaused && !inEditMode) {
1481 // process actors
1482 doActorsThink();
1483 dotThink();
1486 // some timing
1487 auto tm = MonoTime.currTime;
1488 int thinkTime = cast(int)((tm-curtime).total!"msecs");
1489 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
1490 curtime = tm;
1491 return true;
1492 } else {
1493 return false;
1497 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1498 bool doVFrame () {
1499 version(dont_use_vsync) {
1500 // timer
1501 enum doCheckTime = true;
1502 } else {
1503 // vsync
1504 __gshared bool prevLost = false;
1505 bool doCheckTime = vframeWasLost;
1506 if (vframeWasLost) {
1507 if (!prevLost) {
1508 { import core.stdc.stdio; printf("frame was lost!\n"); }
1510 prevLost = true;
1511 } else {
1512 prevLost = false;
1515 if (doCheckTime) {
1516 if (curtime < nextvframe) return false;
1517 version(dont_use_vsync) {
1518 if (curtime > nextvframe) {
1519 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
1520 if (overtime > 2500) {
1521 if (hushFrames) {
1522 --hushFrames;
1523 } else {
1524 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
1530 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
1531 bool ctset = false;
1533 sdwindow.mtLock();
1534 scope(exit) sdwindow.mtUnlock();
1535 ctset = sdwindow.setAsCurrentOpenGlContextNT;
1537 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
1538 if (ctset) {
1539 // render scene
1540 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
1541 receiveMessages(); // here, 'cause we need active OpenGL context for some messages
1542 processConsoleCommands();
1543 if (levelLoaded) {
1544 renderScene(curtime);
1545 } else {
1546 //renderLoading(curtime);
1548 sdwindow.mtLock();
1549 scope(exit) sdwindow.mtUnlock();
1550 sdwindow.swapOpenGlBuffers();
1551 glFinish();
1552 sdwindow.releaseCurrentOpenGlContext();
1553 vframeWasLost = false;
1554 } else {
1555 vframeWasLost = true;
1556 { import core.stdc.stdio; printf("xframe was lost!\n"); }
1558 curtime = MonoTime.currTime;
1559 return true;
1562 for (;;) {
1563 if (sdwindow.closed) break;
1564 if (atomicLoad(diedie) > 0) break;
1566 curtime = MonoTime.currTime;
1567 auto fstime = curtime;
1569 doThinkFrame(); // this will fix curtime if necessary
1570 if (doVFrame()) {
1571 if (!vframeWasLost) {
1572 // fps
1573 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
1574 prevFrameStartTime = curtime;
1575 frtimes += frameTime;
1576 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
1577 import std.string : format;
1578 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
1579 if (newFPS != prevFPS) {
1580 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
1581 prevFPS = newFPS;
1583 framenum = 0;
1584 frtimes = 0.0f;
1589 curtime = MonoTime.currTime;
1591 // now sleep until next "video" or "think" frame
1592 if (nextthink > curtime && nextvframe > curtime) {
1593 // let's decide
1594 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
1595 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
1596 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
1597 sleepAtMaxMsecs(sleepTime);
1598 //curtime = MonoTime.currTime;
1601 } catch (Throwable e) {
1602 // here, we are dead and fucked (the exact order doesn't matter)
1603 import core.stdc.stdlib : abort;
1604 import core.stdc.stdio : fprintf, stderr;
1605 import core.memory : GC;
1606 GC.disable(); // yeah
1607 thread_suspendAll(); // stop right here, you criminal scum!
1608 auto s = e.toString();
1609 fprintf(stderr, "\n=== FATAL ===\n%.*s\n", cast(uint)s.length, s.ptr);
1610 abort(); // die, you bitch!
1612 import core.stdc.stdio;
1613 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
1614 import std.stdio : stderr;
1615 writeln(
1616 for (;;) {
1617 if (sdwindow.closed) break;
1618 if (atomicLoad(diedie) > 0) break;
1619 sleepAtMaxMsecs(100);
1623 atomicStore(diedie, 2);
1627 // ////////////////////////////////////////////////////////////////////////// //
1628 __gshared Tid renderTid;
1629 shared bool renderThreadStarted = false;
1632 public void startRenderThread () {
1633 if (!cas(&renderThreadStarted, false, true)) {
1634 assert(0, "render thread already started!");
1636 renderTid = spawn(&renderThread, thisTid);
1637 setMaxMailboxSize(renderTid, 1024, OnCrowding.throwException); //FIXME
1638 // wait for "i'm ready" signal
1639 receive(
1640 (int ok) {
1641 if (ok != 42) assert(0, "wtf?!");
1644 conwriteln("rendering thread started");
1648 // ////////////////////////////////////////////////////////////////////////// //
1649 public void closeWindow () {
1650 if (atomicLoad(diedie) != 2) {
1651 atomicStore(diedie, 1);
1652 while (atomicLoad(diedie) != 2) {}
1654 if (!sdwindow.closed) {
1655 flushGui();
1656 sdwindow.close();
1661 // ////////////////////////////////////////////////////////////////////////// //
1662 // thread messages
1665 // ////////////////////////////////////////////////////////////////////////// //
1666 struct TMsgMouseEvent {
1667 MouseEventType type;
1668 int x, y;
1669 int dx, dy;
1670 MouseButton button; /// See $(LREF MouseButton)
1671 int modifierState; /// See $(LREF ModifierState)
1674 public void postMouseEvent() (in auto ref MouseEvent evt) {
1675 if (!atomicLoad(renderThreadStarted)) return;
1676 TMsgMouseEvent msg;
1677 msg.type = evt.type;
1678 msg.x = evt.x;
1679 msg.y = evt.y;
1680 msg.dx = evt.dx;
1681 msg.dy = evt.dy;
1682 msg.button = evt.button;
1683 msg.modifierState = evt.modifierState;
1684 send(renderTid, msg);
1688 // ////////////////////////////////////////////////////////////////////////// //
1689 struct TMsgKeyEvent {
1690 Key key;
1691 uint hardwareCode;
1692 bool pressed;
1693 dchar character;
1694 uint modifierState;
1697 public void postKeyEvent() (in auto ref KeyEvent evt) {
1698 if (!atomicLoad(renderThreadStarted)) return;
1699 TMsgKeyEvent msg;
1700 msg.key = evt.key;
1701 msg.pressed = evt.pressed;
1702 msg.character = evt.character;
1703 msg.modifierState = evt.modifierState;
1704 send(renderTid, msg);
1708 // ////////////////////////////////////////////////////////////////////////// //
1709 struct TMsgTestLightMove {
1710 int x, y;
1713 public void postTestLightMove (int x, int y) {
1714 if (!atomicLoad(renderThreadStarted)) return;
1715 auto msg = TMsgTestLightMove(x, y);
1716 send(renderTid, msg);
1720 // ////////////////////////////////////////////////////////////////////////// //
1721 struct TMsgMessage {
1722 char[256] text;
1723 uint textlen;
1724 int pauseMsecs;
1725 bool noreplace;
1728 public void postAddMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
1729 if (!atomicLoad(renderThreadStarted)) return;
1730 if (msgtext.length > TMsgMessage.text.length) msgtext = msgtext[0..TMsgMessage.text.length];
1731 TMsgMessage msg;
1732 msg.textlen = cast(uint)msgtext.length;
1733 if (msg.textlen) msg.text[0..msg.textlen] = msgtext[0..msg.textlen];
1734 msg.pauseMsecs = pauseMsecs;
1735 msg.noreplace = noreplace;
1736 send(renderTid, msg);
1740 // ////////////////////////////////////////////////////////////////////////// //
1741 struct TMsgChar {
1742 char ch;
1745 public void postChar (char ch) {
1746 if (!atomicLoad(renderThreadStarted)) return;
1747 TMsgChar msg;
1748 msg.ch = ch;
1749 send(renderTid, msg);
1753 // ////////////////////////////////////////////////////////////////////////// //
1754 public void concmd (const(char)[] cmd) {
1755 //if (!atomicLoad(renderThreadStarted)) return;
1756 cbufLock();
1757 scope(exit) cbufUnlock();
1758 concmdAdd(cmd);