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;
27 import std
.concurrency
;
50 // ////////////////////////////////////////////////////////////////////////// //
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
][];
111 while (pos
< res
.length
&& res
.ptr
[pos
]) ++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
;
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
);
136 foreach (immutable c
; idx
+1..concmdhistory
.length
) concmdhistory
.ptr
[c
-1][] = concmdhistory
.ptr
[c
][];
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
) {
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
;
157 void concmdDoAll () {
158 if (concmdbufpos
== 0) return;
159 scope(exit
) concmdbufpos
= 0;
160 auto ebuf
= concmdbufpos
;
161 const(char)[] s
= concmdbuf
[0..concmdbufpos
];
164 auto cmd
= conGetCommand(s
);
165 if (cmd
is null) break;
168 } catch (Exception e
) {
169 conwriteln("***ERROR: ", e
.msg
);
172 if (concmdbufpos
<= ebuf
) break;
173 s
= concmdbuf
[ebuf
..concmdbufpos
];
179 void concliChar (char ch
) {
180 __gshared
int prevWasEmptyAndTab
= 0;
183 scope(exit
) cbufUnlock();
188 if (conclilen
== 0) {
189 if (++prevWasEmptyAndTab
< 2) return;
191 prevWasEmptyAndTab
= 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;
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
) {
212 bool doRet
= (minPfx
.length
> conclilen
);
214 concli
[0..minPfx
.length
] = minPfx
[];
215 conclilen
= cast(uint)minPfx
.length
;
216 if (conclilen
< concli
.length
&& conHasCommand(minPfx
)) {
217 concli
.ptr
[conclilen
++] = ' ';
223 // nope, print all available commands
224 bool needDelimiter
= true;
225 foreach (auto name
; conByCommand
) {
227 if (name
.length
< conclilen
) continue;
228 if (name
[0..conclilen
] != concli
[0..conclilen
]) continue;
230 if (needDelimiter
) { conwriteln("----------------"); needDelimiter
= false; }
235 // process other keys
236 prevWasEmptyAndTab
= 0;
239 if (conclilen
> 0) { conLastChange
= 0; --conclilen
; }
244 if (conskiplines
) { conskiplines
= 0; conLastChange
= 0; }
248 conhisAdd(concli
[0..conclilen
]);
249 concmdAdd(concli
[0..conclilen
]);
256 if (conclilen
> 0) { conLastChange
= 0; conclilen
= 0; }
262 auto cmd
= conhisAt(conhisidx
);
263 if (cmd
.length
== 0) {
266 concli
[0..cmd
.length
] = cmd
[];
267 conclilen
= cast(uint)cmd
.length
;
275 auto cmd
= conhisAt(conhisidx
);
276 if (cmd
.length
== 0 && conhisidx
< -1) {
279 concli
[0..cmd
.length
] = cmd
[];
280 conclilen
= cast(uint)cmd
.length
;
287 int lnx
= (rConsoleHeight
-4)/conCharHeight
-2;
288 if (lnx
< 1) lnx
= 1;
295 if (conskiplines
> 0) {
296 int lnx
= (rConsoleHeight
-4)/conCharHeight
-2;
297 if (lnx
< 1) lnx
= 1;
298 if ((conskiplines
-= lnx
) < 0) conskiplines
= 0;
304 if (ch
< ' ' || ch
> 127) return;
305 if (conclilen
>= concli
.length
) return;
306 concli
.ptr
[conclilen
++] = ch
;
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");
322 cheatNoDoors
= !cheatNoDoors
;
323 if (cheatNoDoors
) conwriteln("player ignores doors"); else conwriteln("player respects doors");
324 })("nodoorclip", "ignore doors");
326 cheatNoWallClip
= !cheatNoWallClip
;
327 if (cheatNoWallClip
) conwriteln("player ignores walls"); else conwriteln("player respects walls");
328 })("nowallclip", "ignore walls");
331 atomicStore(vquitRequested
, true);
332 })("quit", "quit game");
333 conRegFunc
!((const(char)[] msg
, int pauseMsecs
=3000, bool noreplace
=false) {
335 auto s
= buf
.conFormatStr(msg
);
336 if (s
.length
) postAddMessage(s
, pauseMsecs
, noreplace
);
337 })("hudmsg", "show hud message; hudmsg msg [pausemsecs [noreplace]]");
341 // ////////////////////////////////////////////////////////////////////////// //
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 // ////////////////////////////////////////////////////////////////////////// //
352 struct AttachedLightInfo
{
359 int w
, h
; // for ambient lights
365 __gshared AttachedLightInfo
[65536] attachedLights
;
366 __gshared
uint attachedLightCount
= 0;
369 // ////////////////////////////////////////////////////////////////////////// //
370 enum MaxLightRadius
= 255;
373 // ////////////////////////////////////////////////////////////////////////// //
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 // ////////////////////////////////////////////////////////////////////////// //
390 public void initOpenGL () {
393 glEnable(GL_TEXTURE_2D
);
394 glDisable(GL_LIGHTING
);
395 glDisable(GL_DITHER
);
397 glDisable(GL_DEPTH_TEST
);
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;
408 shadToPolar
= new Shader("light_trace", loadTextFile("shaders/srlight_trace.frag"));
409 shadToPolar
.exec((Shader shad
) {
411 shad
["texOccFull"] = 2;
412 shad
["texOccSmall"] = 3;
415 shadBlur
= new Shader("light_blur", loadTextFile("shaders/srlight_blur.frag"));
416 shadBlur
.exec((Shader shad
) {
420 shad
["texOccSmall"] = 3;
423 shadBlurOcc
= new Shader("light_blur_occ", loadTextFile("shaders/srlight_blur_occ.frag"));
424 shadBlurOcc
.exec((Shader shad
) {
428 shad
["texOccSmall"] = 3;
431 shadAmbient
= new Shader("light_ambient", loadTextFile("shaders/srlight_ambient.frag"));
432 shadAmbient
.exec((Shader shad
) {
435 shad
["texOccSmall"] = 3;
438 fboOccluders
= new FBO(MaxLightRadius
*2, MaxLightRadius
*2, Texture
.Option
.Clamp
, Texture
.Option
.Linear
);
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
);
453 glMatrixMode(GL_MODELVIEW
);
458 loadAllMonsterGraphics();
462 // ////////////////////////////////////////////////////////////////////////// //
463 __gshared
ulong conLastChange
= 0;
465 void renderConsoleFBO () {
467 if (conLastChange
== cbufLastChange
) return;
469 scope(exit
) cbufUnlock();
471 conLastChange
= cbufLastChange
;
472 //foreach (auto s; conbufLinesRev) stdout.writeln(s, "|");
473 int skipLines
= conskiplines
;
474 fboConsole
.exec((FBO me
) {
476 orthoCamera(me
.width
, me
.height
);
478 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
479 glClear(GL_COLOR_BUFFER_BIT
);
482 glColor4f(0.0f, 0.0f, 0.0f, 1.0f);
483 glRectf(0, 0, me.width-1, me.height-1);
487 glBlendFunc(GL_SRC_ALPHA
, GL_ONE
);
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);
492 int y
= me
.height
-conCharHeight
-2;
495 scope(exit
) glPopMatrix();
496 glTranslatef(XOfs
, y
, 0);
497 int w
= conCharWidth('>');
498 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
500 uint spos
= conclilen
;
502 char ch
= concli
.ptr
[spos
-1];
503 if (w
+conCharWidth(ch
) > me
.width
-XOfs
*2-12) break;
504 w
+= conCharWidth(ch
);
507 glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
508 foreach (char ch
; concli
[spos
..conclilen
]) conDrawChar(ch
);
511 glColor4f(1.0f, 0.5f, 0.0f, 1.0f);
512 glRectf(0, 0, 12, 16);
516 glColor4f(0.0f, 1.0f, 0.0f, 1.0f);
518 scope(exit
) glPopMatrix();
519 glTranslatef(XOfs
, y
, 0);
520 foreach (auto line
; conbufLinesRev
) {
521 if (line
.length
== 0) {
522 if (skipLines
-- <= 0) {
526 glTranslatef(XOfs
, y
, 0);
529 usize pos
= line
.length
;
534 char ch
= line
[sp
-1];
535 if (w
+conCharWidth(ch
) > me
.width
-XOfs
*2) break;
536 w
+= conCharWidth(ch
);
539 if (skipLines
-- <= 0) {
540 foreach (immutable p
; sp
..pos
) conDrawChar(line
[p
]);
544 glTranslatef(XOfs
, y
, 0);
546 if (sp
== 0 || y
< 0) break;
556 // ////////////////////////////////////////////////////////////////////////// //
557 // should be called when OpenGL is initialized
558 void loadMap (string mapname
) {
559 mapscripts
.runUnloading(); // "map unloading" script
562 if (map
!is null) map
.clear();
563 map
= new LevelMap(mapname
);
564 curmapname
= mapname
;
566 ugInit(map
.width
*TileSize
, map
.height
*TileSize
);
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();
593 mapscripts
.runInit();
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
);
605 { import core
.memory
: GC
; GC
.collect(); }
609 // ////////////////////////////////////////////////////////////////////////// //
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 () {
620 //mapTilesChanged = false;
621 //map.clearMegaTextures();
622 map
.oglBuildMega(mapTilesChanged
);
624 dotsAwake(); // let dormant dots fall
628 // ////////////////////////////////////////////////////////////////////////// //
631 enum Phase
{ FadeIn
, Stay
, FadeOut
}
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;
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;
662 if (!noreplace
&& messagesUsed
== 1) {
663 switch (messages
.ptr
[0].phase
) {
664 case Message
.Phase
.FadeIn
:
665 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
667 case Message
.Phase
.Stay
:
668 messages
.ptr
[0].phase
= Message
.Phase
.FadeOut
;
669 messages
.ptr
[0].alpha
= 255;
674 auto msg
= messages
.ptr
+messagesUsed
;
676 msg
.phase
= Message
.Phase
.FadeIn
;
678 msg
.pauseMsecs
= pauseMsecs
;
680 if (msgtext
.length
> msg
.text
.length
) {
681 msg
.text
= msgtext
[0..msg
.text
.length
];
682 msg
.textlen
= msg
.text
.length
;
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;
696 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
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);
711 case Message
.Phase
.Stay
:
712 if (msg
.removeTime
<= curtime
) {
714 msg
.phase
= Message
.Phase
.FadeOut
;
715 goto case; // to fade
717 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
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
];
726 glColor4f(1.0f, 1.0f, 1.0f, msg
.alpha
/255.0f);
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));
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
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
834 // no need to clear it, shader will take care of that
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
);
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
854 // blend light texture
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
);
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
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
);
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
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;
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
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
);
945 glBlendFunc(GL_SRC_ALPHA
, GL_ONE_MINUS_SRC_ALPHA
);
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
);
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
{
972 @disable this (this); // no copies
974 enum { Pixels
, Players
, Items
, Monsters
, Other
}
975 __gshared DrawInfo
[65536][4] drawlists
;
976 __gshared
uint[4] dlpos
;
981 Actor
.forEach((ActorId me
) {
982 //me.fprop_0drawlistpos = 0;
983 if (auto adef
= findActorDef(me
)) {
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
;
999 int oy
= xptr
.fgetp_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, ")");
1009 if (me
.id
== cameraChick
.id
) {
1010 camchickdi
.adef
= adef
;
1011 camchickdi
.aid
= me
;
1012 camchickdi
.actorX
= actorX
;
1013 camchickdi
.actorY
= actorY
;
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
];
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);
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;
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
;
1049 li
.w
= me
.fget_radius
;
1050 li
.h
= me
.fget_height
;
1055 conwriteln("not found actor ", me
.id
, " (", me
.classtype
!string
, ":", me
.classname
!string
, ")");
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
]) {
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;
1074 if (dlpos
[Pixels
]) {
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
]) {
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);
1089 pointsStarted
= false;
1091 if (!pointsStarted
) {
1093 pointsStarted
= true;
1095 glVertex2i(dl.actorX
, dl.actorY
);
1098 if (pointsStarted
) {
1100 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1105 if (/*altMove || movement ||*/ scale
== 1 ||
!cameraChick
.valid
) {
1110 vportX1
= map
.width
*TileSize
;
1111 vportY1
= map
.height
*TileSize
;
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;
1124 vportX0
= mofsx
/scale
;
1125 vportY0
= mofsy
/scale
;
1126 vportX1
= vportX0
+vlWidth
/scale
;
1127 vportY1
= vportY0
+vlHeight
/scale
;
1130 //glDisable(GL_DEPTH_TEST);
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);
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) {
1148 glVertex2i(camchickdi.actorX, camchickdi.actorY-70);
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);
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);
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);
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);
1217 renderLightAmbient(li
.x
, li
.y
, li
.w
, li
.h
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
));
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
) {
1224 renderLight(li
.x
, li
.y
, SVec4F(0.0f, 0.0f, 0.0f, li
.r
), li
.radius
);
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);
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);
1270 fboLevelLight.exec({
1271 smDrawText(map.width*TileSize/2, map.height*TileSize/2, "Testing...");
1276 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT
, 0);
1278 glDisable(GL_BLEND
);
1282 //auto img = smfont.ptr[0x39];
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);
1306 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
1307 //orthoCamera(map.width*TileSize, map.height*TileSize);
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);
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
) {
1331 orthoCamera(vlWidth
, vlHeight
);
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
) {
1344 import core
.sys
.posix
.signal
: timespec
;
1345 import core
.sys
.posix
.time
: nanosleep
;
1346 timespec ts
= void, tpassed
= void;
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);
1357 // ////////////////////////////////////////////////////////////////////////// //
1358 mixin(import("editor.d"));
1361 // ////////////////////////////////////////////////////////////////////////// //
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);
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;
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
) {
1400 conwriteln("ERROR: can't load new levels yet");
1404 if (name
.length
== 0) {
1405 conwriteln("ERROR: can't load empty level!");
1407 conwriteln("loading map '", name
, "'");
1413 string mn
= genNextMapName(0);
1415 nextmapname
= null; // clear "exit" flag
1418 conwriteln("can't skip level");
1420 })("skiplevel", "skip current level");
1423 inEditMode
= !inEditMode
;
1424 if (inEditMode
) sdwindow
.hideCursor(); else sdwindow
.showCursor();
1425 })("ed_toggle", "toggle editor");
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 () {
1441 import core
.time
: Duration
;
1442 //conwriteln("rendering thread: waiting for messages...");
1443 auto got
= receiveTimeout(
1444 Duration
.zero
, // don't wait
1446 addMessage(msg
.text
[0..msg
.textlen
], msg
.pauseMsecs
, msg
.noreplace
);
1448 (TMsgTestLightMove msg
) {
1451 testLightMoved
= true;
1453 (TMsgMouseEvent msg
) { editorMouseEvent(msg
); },
1454 (TMsgKeyEvent msg
) { editorKeyEvent(msg
); },
1455 (TMsgChar msg
) { concliChar(msg
.ch
); },
1457 conwriteln("WARNING: unknown thread message received and ignored");
1462 //conwriteln("rendering thread: no more messages");
1466 if (nextmapname
.length
) {
1467 string mn
= nextmapname
;
1468 nextmapname
= null; // clear "exit" flag
1473 void processConsoleCommands () {
1475 scope(exit
) cbufUnlock();
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
);
1485 // save snapshot and other data for interpolator
1486 Actor
.saveSnapshot(prevFrameActorsData
[], prevFrameActorOfs
.ptr
);
1487 if (!gamePaused
&& !inEditMode
) {
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
); }
1504 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
1506 version(dont_use_vsync
) {
1508 enum doCheckTime
= true;
1511 __gshared
bool prevLost
= false;
1512 bool doCheckTime
= vframeWasLost
;
1513 if (vframeWasLost
) {
1515 { import core
.stdc
.stdio
; printf("frame was lost!\n"); }
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) {
1531 { import core
.stdc
.stdio
; printf(" spent whole %d msecs\n", overtime
); }
1537 while (nextvframe
<= curtime
) nextvframe
+= dur
!"msecs"(MinFrameTime
);
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
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();
1551 renderScene(curtime
);
1553 //renderLoading(curtime);
1556 scope(exit
) sdwindow
.mtUnlock();
1557 sdwindow
.swapOpenGlBuffers();
1559 sdwindow
.releaseCurrentOpenGlContext();
1560 vframeWasLost
= false;
1562 vframeWasLost
= true;
1563 { import core
.stdc
.stdio
; printf("xframe was lost!\n"); }
1565 curtime
= MonoTime
.currTime
;
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
1578 if (!vframeWasLost
) {
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
);
1596 curtime
= MonoTime
.currTime
;
1598 // now sleep until next "video" or "think" frame
1599 if (nextthink
> curtime
&& nextvframe
> curtime
) {
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;
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
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
) {
1668 // ////////////////////////////////////////////////////////////////////////// //
1672 // ////////////////////////////////////////////////////////////////////////// //
1673 struct TMsgMouseEvent
{
1674 MouseEventType type
;
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;
1684 msg
.type
= evt
.type
;
1689 msg
.button
= evt
.button
;
1690 msg
.modifierState
= evt
.modifierState
;
1691 send(renderTid
, msg
);
1695 // ////////////////////////////////////////////////////////////////////////// //
1696 struct TMsgKeyEvent
{
1704 public void postKeyEvent() (in auto ref KeyEvent evt
) {
1705 if (!atomicLoad(renderThreadStarted
)) return;
1708 msg
.pressed
= evt
.pressed
;
1709 msg
.character
= evt
.character
;
1710 msg
.modifierState
= evt
.modifierState
;
1711 send(renderTid
, msg
);
1715 // ////////////////////////////////////////////////////////////////////////// //
1716 struct TMsgTestLightMove
{
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
{
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
];
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 // ////////////////////////////////////////////////////////////////////////// //
1752 public void postChar (char ch
) {
1753 if (!atomicLoad(renderThreadStarted
)) return;
1756 send(renderTid
, msg
);
1760 // ////////////////////////////////////////////////////////////////////////// //
1761 public void concmd (const(char)[] cmd
) {
1762 //if (!atomicLoad(renderThreadStarted)) return;
1764 scope(exit
) cbufUnlock();