some mapmod code
[dd2d.git] / xmain_d2d.d
blob83dd4c0c7659930d16a105bddfae95ba75d18bc8
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 xmain_d2d is aliced;
20 private:
21 import core.atomic;
22 import core.thread;
23 import core.time;
25 import iv.glbinds;
26 import glutils;
27 import console;
28 import wadarc;
30 import iv.stream;
32 import d2dmap;
33 import d2dadefs;
34 //import d2dactors;
35 import d2dgfx;
36 import d2dfont;
37 import dacs;
39 import d2dunigrid;
41 // `map` is there
42 import dengapi;
45 // ////////////////////////////////////////////////////////////////////////// //
46 import arsd.color;
47 import arsd.png;
50 // ////////////////////////////////////////////////////////////////////////// //
51 public __gshared bool cheatNoDoors = false;
54 // ////////////////////////////////////////////////////////////////////////// //
55 __gshared SimpleWindow sdwindow;
58 public enum vlWidth = 800;
59 public enum vlHeight = 800;
60 public __gshared int scale = 1;
63 // ////////////////////////////////////////////////////////////////////////// //
64 __gshared bool scanlines = false;
65 __gshared bool doLighting = true;
68 // ////////////////////////////////////////////////////////////////////////// //
69 // interpolation
70 __gshared ubyte[] prevFrameActorsData;
71 __gshared uint[65536] prevFrameActorOfs; // uint.max-1: dead; uint.max: last
72 __gshared MonoTime lastthink = MonoTime.zero; // for interpolator
73 __gshared MonoTime nextthink = MonoTime.zero;
74 __gshared bool frameInterpolation = true;
77 __gshared int[2] mapViewPosX, mapViewPosY; // [0]: previous frame -- for interpolator
80 // this should be screen center
81 public void setMapViewPos (int x, int y) {
82 if (map is null) {
83 mapViewPosX[] = 0;
84 mapViewPosY[] = 0;
85 return;
87 int swdt = vlWidth/scale;
88 int shgt = vlHeight/scale;
89 x -= swdt/2;
90 y -= shgt/2;
91 if (x < 0) x = 0; else if (x >= map.width*8-swdt) x = map.width*8-swdt-1;
92 if (y < 0) y = 0; else if (y >= map.height*8-shgt) y = map.height*8-shgt-1;
93 mapViewPosX[1] = x*scale;
94 mapViewPosY[1] = y*scale;
98 // ////////////////////////////////////////////////////////////////////////// //
99 // attached lights
100 struct AttachedLightInfo {
101 int x, y;
102 float r, g, b;
103 bool uncolored;
104 int radius;
107 __gshared AttachedLightInfo[65536] attachedLights;
108 __gshared uint attachedLightCount = 0;
111 // ////////////////////////////////////////////////////////////////////////// //
112 enum MaxLightRadius = 512;
115 // ////////////////////////////////////////////////////////////////////////// //
116 // for light
117 __gshared FBO[MaxLightRadius+1] fboOccluders, fboShadowMap;
118 __gshared Shader shadToPolar, shadBlur, shadBlurOcc;
120 __gshared FBO fboLevel, fboLevelLight, fboOrigBack;
121 __gshared Shader shadScanlines;
122 __gshared Shader shadLiquidDistort;
125 // ////////////////////////////////////////////////////////////////////////// //
126 void initOpenGL () {
127 glEnable(GL_TEXTURE_2D);
128 glDisable(GL_LIGHTING);
129 glDisable(GL_DITHER);
130 glDisable(GL_BLEND);
131 glDisable(GL_DEPTH_TEST);
133 // create shaders
134 shadScanlines = new Shader("scanlines", loadTextFile("data/shaders/srscanlines.frag"));
136 shadLiquidDistort = new Shader("liquid_distort", loadTextFile("data/shaders/srliquid_distort.frag"));
137 shadLiquidDistort.exec((Shader shad) { shad["tex0"] = 0; });
139 // lights
140 shadToPolar = new Shader("light_topolar", loadTextFile("data/shaders/srlight_topolar.frag"));
141 shadBlur = new Shader("light_blur", loadTextFile("data/shaders/srlight_blur.frag"));
142 shadBlur.exec((Shader shad) {
143 shad["tex0"] = 0;
144 shad["tex1"] = 1;
145 shad["tex2"] = 2;
147 shadBlurOcc = new Shader("light_blur_occ", loadTextFile("data/shaders/srlight_blur_occ.frag"));
148 shadBlurOcc.exec((Shader shad) {
149 shad["tex0"] = 0;
150 shad["tex1"] = 1;
151 shad["tex2"] = 2;
153 //TODO: this sux!
154 foreach (int sz; 2..MaxLightRadius+1) {
155 fboOccluders[sz] = new FBO(sz*2, sz*2, Texture.Option.Clamp, Texture.Option.Linear); // create occluders FBO
156 fboShadowMap[sz] = new FBO(sz*2, 1, Texture.Option.Clamp); // create 1d shadowmap FBO
159 // setup matrices
160 glMatrixMode(GL_MODELVIEW);
161 glLoadIdentity();
163 map.oglBuildMega();
164 mapTilesChanged = false;
166 fboLevel = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // final level render will be here
167 fboLevelLight = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level lights will be rendered here
168 //fboForeground = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // level foreground
169 fboOrigBack = new FBO(map.width*8, map.height*8, Texture.Option.Nearest); // background+foreground
171 shadBlur.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
172 shadBlurOcc.exec((Shader shad) { shad["mapPixSize"] = SVec2F(map.width*8, map.height*8); });
174 glActiveTexture(GL_TEXTURE0+0);
175 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
176 orthoCamera(vlWidth, vlHeight);
178 loadSmFont();
180 Actor.resetStorage();
181 loadMapMonsters();
183 // save first snapshot
184 prevFrameActorsData = new ubyte[](Actor.actorSize*65536); // ~15-20 megabytes
185 prevFrameActorOfs[] = uint.max; // just for fun
186 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
187 mapViewPosX[0] = mapViewPosX[1];
188 mapViewPosY[0] = mapViewPosY[1];
190 { import core.memory : GC; GC.collect(); }
194 // ////////////////////////////////////////////////////////////////////////// //
195 //FIXME: optimize!
196 __gshared bool mapTilesChanged = false;
199 public void mapDirty () { mapTilesChanged = true; }
201 void rebuildMapMegaTextures () {
202 //fbo.replaceTexture
203 mapTilesChanged = false;
204 map.clearMegaTextures();
205 map.oglBuildMega();
209 // ////////////////////////////////////////////////////////////////////////// //
210 void renderLight() (int lightX, int lightY, in auto ref SVec4F lcol, int lightRadius) {
211 if (lightRadius < 2) return;
212 if (lightRadius > MaxLightRadius) lightRadius = MaxLightRadius;
213 int lightSize = lightRadius*2;
214 // is this light visible?
215 if (lightX <= -lightRadius || lightY <= -lightRadius || lightX-lightRadius >= map.width*8 || lightY-lightRadius >= map.height*8) return;
217 // draw shadow casters to fboOccludersId, light should be in the center
218 glUseProgram(0);
219 glDisable(GL_BLEND);
220 fboOccluders[lightRadius].exec({
221 //glDisable(GL_BLEND);
222 glColor3f(0.0f, 0.0f, 0.0f);
223 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
224 glClear(GL_COLOR_BUFFER_BIT);
225 orthoCamera(lightSize, lightSize);
226 drawAtXY(map.texgl.ptr[map.LightMask], lightRadius-lightX, lightRadius-lightY);
229 // build 1d shadow map to fboShadowMapId
230 fboShadowMap[lightRadius].exec({
231 shadToPolar.exec((Shader shad) {
232 //glDisable(GL_BLEND);
233 glColor3f(0.0f, 0.0f, 0.0f);
234 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
235 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
236 glClear(GL_COLOR_BUFFER_BIT);
237 orthoCamera(lightSize, 1);
238 drawAtXY(fboOccluders[lightRadius].tex.tid, 0, 0, lightSize, 1);
242 // build light texture for blending
243 fboOccluders[lightRadius].exec({
244 // no need to clear it, shader will take care of that
245 //glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
246 //glClear(GL_COLOR_BUFFER_BIT);
247 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
248 //glDisable(GL_BLEND);
249 shadBlur.exec((Shader shad) {
250 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
251 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
252 shad["lightPos"] = SVec2F(lightX, lightY);
253 orthoCamera(lightSize, lightSize);
254 drawAtXY(fboShadowMap[lightRadius].tex.tid, 0, 0, lightSize, lightSize);
258 // blend light texture
259 fboLevelLight.exec({
260 glEnable(GL_BLEND);
261 glBlendFunc(GL_SRC_ALPHA, GL_ONE);
262 orthoCamera(map.width*8, map.height*8);
263 drawAtXY(fboOccluders[lightRadius].tex, lightX-lightRadius, lightY-lightRadius, mirrorY:true);
264 // and blend it again, somewhat bigger, with the shader that will touch only occluders
265 enum szmore = 0;
266 shadBlurOcc.exec((Shader shad) {
267 shad["lightTexSize"] = SVec2F(lightSize, lightSize);
268 shad["lightColor"] = SVec4F(lcol.x, lcol.y, lcol.z, lcol.w);
269 shad["lightPos"] = SVec2F(lightX, lightY);
270 drawAtXY(fboOccluders[lightRadius].tex.tid, lightX-lightRadius-szmore, lightY-lightRadius-szmore, lightSize+szmore*2, lightSize+szmore*2, mirrorY:true);
276 // ////////////////////////////////////////////////////////////////////////// //
277 // messages
278 struct Message {
279 enum Phase { FadeIn, Stay, FadeOut }
280 Phase phase;
281 int alpha;
282 int pauseMsecs;
283 MonoTime removeTime;
284 char[256] text;
285 usize textlen;
288 private import core.sync.mutex : Mutex;
290 __gshared Message[128] messages;
291 __gshared uint messagesUsed = 0;
292 __gshared Mutex messageLock;
294 shared static this () { messageLock = new Mutex(); }
297 void addMessage (const(char)[] msgtext, int pauseMsecs=3000, bool noreplace=false) {
298 messageLock.lock();
299 scope(exit) messageLock.unlock();
300 if (msgtext.length == 0) return;
301 conwriteln(msgtext);
302 if (pauseMsecs <= 50) return;
303 if (messagesUsed == messages.length) {
304 // remove top message
305 foreach (immutable cidx; 1..messagesUsed) messages.ptr[cidx-1] = messages.ptr[cidx];
306 messages.ptr[0].alpha = 255;
307 --messagesUsed;
309 // quick replace
310 if (!noreplace && messagesUsed == 1) {
311 switch (messages.ptr[0].phase) {
312 case Message.Phase.FadeIn:
313 messages.ptr[0].phase = Message.Phase.FadeOut;
314 break;
315 case Message.Phase.Stay:
316 messages.ptr[0].phase = Message.Phase.FadeOut;
317 messages.ptr[0].alpha = 255;
318 break;
319 default:
322 auto msg = messages.ptr+messagesUsed;
323 ++messagesUsed;
324 msg.phase = Message.Phase.FadeIn;
325 msg.alpha = 0;
326 msg.pauseMsecs = pauseMsecs;
327 // copy text
328 if (msgtext.length > msg.text.length) {
329 msg.text = msgtext[0..msg.text.length];
330 msg.textlen = msg.text.length;
331 } else {
332 msg.text[0..msgtext.length] = msgtext[];
333 msg.textlen = msgtext.length;
338 void doMessages (MonoTime curtime) {
339 messageLock.lock();
340 scope(exit) messageLock.unlock();
342 if (messagesUsed == 0) return;
343 glEnable(GL_BLEND);
344 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
346 Message* msg;
348 again:
349 msg = messages.ptr;
350 final switch (msg.phase) {
351 case Message.Phase.FadeIn:
352 if ((msg.alpha += 10) >= 255) {
353 msg.phase = Message.Phase.Stay;
354 msg.removeTime = curtime+dur!"msecs"(msg.pauseMsecs);
355 goto case; // to stay
357 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
358 break;
359 case Message.Phase.Stay:
360 if (msg.removeTime <= curtime) {
361 msg.alpha = 255;
362 msg.phase = Message.Phase.FadeOut;
363 goto case; // to fade
365 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
366 break;
367 case Message.Phase.FadeOut:
368 if ((msg.alpha -= 10) <= 0) {
369 if (--messagesUsed == 0) return;
370 // remove this message
371 foreach (immutable cidx; 1..messagesUsed+1) messages.ptr[cidx-1] = messages.ptr[cidx];
372 goto again;
374 glColor4f(1.0f, 1.0f, 1.0f, msg.alpha/255.0f);
375 break;
378 smDrawText(10, 10, msg.text[0..msg.textlen]);
382 // ////////////////////////////////////////////////////////////////////////// //
383 mixin(Actor.FieldGetMixin!("classtype", StrId)); // fget_classtype
384 mixin(Actor.FieldGetMixin!("classname", StrId)); // fget_classname
385 mixin(Actor.FieldGetMixin!("x", int));
386 mixin(Actor.FieldGetMixin!("y", int));
387 mixin(Actor.FieldGetMixin!("flags", uint));
388 mixin(Actor.FieldGetMixin!("zAnimstate", StrId));
389 mixin(Actor.FieldGetMixin!("zAnimidx", int));
390 mixin(Actor.FieldGetMixin!("dir", uint));
391 mixin(Actor.FieldGetMixin!("attLightXOfs", int));
392 mixin(Actor.FieldGetMixin!("attLightYOfs", int));
393 mixin(Actor.FieldGetMixin!("attLightRGBX", uint));
395 mixin(Actor.FieldGetPtrMixin!("classtype", StrId)); // fget_classtype
396 mixin(Actor.FieldGetPtrMixin!("classname", StrId)); // fget_classname
397 mixin(Actor.FieldGetPtrMixin!("x", int));
398 mixin(Actor.FieldGetPtrMixin!("y", int));
399 mixin(Actor.FieldGetPtrMixin!("flags", uint));
400 mixin(Actor.FieldGetPtrMixin!("zAnimstate", StrId));
401 mixin(Actor.FieldGetPtrMixin!("zAnimidx", int));
402 mixin(Actor.FieldGetPtrMixin!("dir", uint));
403 mixin(Actor.FieldGetPtrMixin!("attLightXOfs", int));
404 mixin(Actor.FieldGetPtrMixin!("attLightYOfs", int));
405 mixin(Actor.FieldGetPtrMixin!("attLightRGBX", uint));
408 // ////////////////////////////////////////////////////////////////////////// //
409 __gshared int lightX = vlWidth/2, lightY = vlHeight/2;
410 __gshared int mapOfsX, mapOfsY;
411 __gshared bool movement = false;
412 __gshared float iLiquidTime = 0.0;
413 __gshared bool altMove = false;
416 void renderScene (MonoTime curtime) {
417 //enum BackIntens = 0.05f;
418 enum BackIntens = 0.0f;
420 float atob = (curtime > lastthink ? cast(float)((curtime-lastthink).total!"msecs")/cast(float)((nextthink-lastthink).total!"msecs") : 1.0f);
421 //{ import core.stdc.stdio; printf("atob=%f\n", cast(double)atob); }
424 int framelen = cast(int)((nextthink-lastthink).total!"msecs");
425 int curfp = cast(int)((curtime-lastthink).total!"msecs");
426 { import core.stdc.stdio; printf("framelen=%d; curfp=%d\n", framelen, curfp); }
430 glUseProgram(0);
432 if (mapTilesChanged) rebuildMapMegaTextures();
434 // build background layer
435 fboOrigBack.exec({
436 //glDisable(GL_BLEND);
437 glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
438 glClear(GL_COLOR_BUFFER_BIT);
439 glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
440 orthoCamera(map.width*8, map.height*8);
441 glEnable(GL_BLEND);
442 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
443 // draw sky
445 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
446 drawAtXY(map.skytexgl.tid, mapOfsX/2-map.MapSize*8, mapOfsY/2, map.MapSize*8, map.MapSize*8);
447 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2-map.MapSize*8, map.MapSize*8, map.MapSize*8);
448 drawAtXY(map.skytexgl.tid, mapOfsX/2, mapOfsY/2, map.MapSize*8, map.MapSize*8);
450 drawAtXY(map.skytexgl.tid, 0, 0, map.MapSize*8, map.MapSize*8);
451 // draw background
452 drawAtXY(map.texgl.ptr[map.Back], 0, 0);
453 // draw distorted liquid areas
454 shadLiquidDistort.exec((Shader shad) {
455 shad["iDistortTime"] = iLiquidTime;
456 drawAtXY(map.texgl.ptr[map.AllLiquids], 0, 0);
458 // monsters, items; we'll do linear interpolation here
459 // we need this for saved frame anyway, so let's play dirty and speed up the things
460 glColor3f(1.0f, 1.0f, 1.0f);
461 attachedLightCount = 0;
462 Actor.forEach((ActorId me) {
463 if (auto adef = findActorDef(me)) {
464 int actorX, actorY; // current actor position
466 auto ofs = prevFrameActorOfs.ptr[me.id&0xffff];
467 if (frameInterpolation && ofs < uint.max-1 && Actor.isSameSavedActor(me.id, prevFrameActorsData.ptr, ofs)) {
468 import core.stdc.math : roundf;
469 auto xptr = prevFrameActorsData.ptr+ofs;
470 int ox = xptr.fgetp_x;
471 int nx = me.fget_x;
472 int oy = xptr.fgetp_y;
473 int ny = me.fget_y;
474 actorX = cast(int)(ox+roundf((nx-ox)*atob));
475 actorY = cast(int)(oy+roundf((ny-oy)*atob));
476 //conwriteln("actor ", me.id, "; o=(", ox, ",", oy, "); n=(", nx, ",", ny, "); p=(", x, ",", y, ")");
477 } else {
478 actorX = me.fget_x;
479 actorY = me.fget_y;
482 // draw sprite
483 if ((me.fget_flags&AF_NODRAW) == 0) {
484 if (auto isp = adef.animSpr(me.fget_zAnimstate, me.fget_dir, me.fget_zAnimidx)) {
485 drawAtXY(isp.tex, actorX-isp.vga.sx, actorY-isp.vga.sy);
486 } else {
487 //conwriteln("no animation for actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
490 // process attached lights
491 if ((me.fget_flags&AF_NOLIGHT) == 0) {
492 uint alr = me.fget_attLightRGBX;
493 if ((alr&0xff) >= 4) {
494 // yep, add it
495 auto li = attachedLights.ptr+attachedLightCount;
496 ++attachedLightCount;
497 li.x = actorX+me.fget_attLightXOfs;
498 li.y = actorY+me.fget_attLightYOfs;
499 li.r = ((alr>>24)&0xff)/255.0f; // red or intensity
500 if ((alr&0x00_ff_ff_00U) == 0x00_00_01_00U) {
501 li.uncolored = true;
502 } else {
503 li.g = ((alr>>16)&0xff)/255.0f;
504 li.b = ((alr>>8)&0xff)/255.0f;
505 li.uncolored = false;
507 li.radius = (alr&0xff);
508 if (li.radius > MaxLightRadius) li.radius = MaxLightRadius;
511 } else {
512 conwriteln("not found actor ", me.id, " (", me.classtype!string, ":", me.classname!string, ")");
515 // do liquid coloring
516 drawAtXY(map.texgl.ptr[map.LiquidMask], 0, 0);
517 // foreground -- hide secrets, draw lifts and such
518 drawAtXY(map.texgl.ptr[map.Front], 0, 0);
522 if (doLighting) {
523 // clear light layer
524 fboLevelLight.exec({
525 glDisable(GL_BLEND);
526 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
527 //glClearColor(0.15f, 0.15f, 0.15f, 1.0f);
528 ////glColor4f(1.0f, 1.0f, 1.0f, 0.0f);
529 glClear(GL_COLOR_BUFFER_BIT);
532 // texture 1 is background
533 glActiveTexture(GL_TEXTURE0+1);
534 glBindTexture(GL_TEXTURE_2D, fboOrigBack.tex.tid);
535 // texture 2 is occluders
536 glActiveTexture(GL_TEXTURE0+2);
537 glBindTexture(GL_TEXTURE_2D, map.texgl.ptr[map.LightMask].tid);
538 // done texture assign
539 glActiveTexture(GL_TEXTURE0+0);
541 enum LYOfs = 1;
543 renderLight( 27, 391-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
544 renderLight(542, 424-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 100);
545 renderLight(377, 368-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
546 renderLight(147, 288-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
547 renderLight( 71, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
548 renderLight(249, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
549 renderLight(426, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
550 renderLight(624, 200-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 128);
551 renderLight(549, 298-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 64);
552 renderLight( 74, 304-0+LYOfs, SVec4F(0.0f, 0.0f, 0.0f, 1.0f), 32);
554 renderLight(24*8+4, (24+18)*8-2+LYOfs, SVec4F(0.6f, 0.0f, 0.0f, 1.0f), 128);
556 // attached lights
557 foreach (ref li; attachedLights[0..attachedLightCount]) {
558 if (li.uncolored) {
559 renderLight(li.x, li.y, SVec4F(0.0f, 0.0f, 0.0f, li.r), li.radius);
560 } else {
561 renderLight(li.x, li.y, SVec4F(li.r, li.g, li.b, 1.0f), li.radius);
565 foreach (immutable _; 0..1) {
566 renderLight(lightX, lightY, SVec4F(0.3f, 0.3f, 0.0f, 1.0f), 96);
569 glActiveTexture(GL_TEXTURE0+1);
570 glBindTexture(GL_TEXTURE_2D, 0);
571 glActiveTexture(GL_TEXTURE0+2);
572 glBindTexture(GL_TEXTURE_2D, 0);
573 glActiveTexture(GL_TEXTURE0+0);
576 // draw scaled level
578 shadScanlines.exec((Shader shad) {
579 shad["scanlines"] = scanlines;
580 glClearColor(BackIntens, BackIntens, BackIntens, 1.0f);
581 glClear(GL_COLOR_BUFFER_BIT);
582 orthoCamera(vlWidth, vlHeight);
583 //orthoCamera(map.width*8*scale, map.height*8*scale);
584 //glMatrixMode(GL_MODELVIEW);
585 //glLoadIdentity();
586 //glTranslatef(0.375, 0.375, 0); // to be pixel-perfect
587 // somehow, FBO objects are mirrored; wtf?!
588 drawAtXY(fboLevel.tex.tid, -mapOfsX, -mapOfsY, map.width*8*scale, map.height*8*scale, mirrorY:true);
589 //glLoadIdentity();
594 fboLevelLight.exec({
595 smDrawText(map.width*8/2, map.height*8/2, "Testing...");
600 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
601 glDisable(GL_BLEND);
604 fboOrigBack.exec({
605 //auto img = smfont.ptr[0x39];
606 auto img = fftest;
607 if (img !is null) {
608 //conwriteln("img.sx=", img.sx, "; img.sy=", img.sy, "; ", img.width, "x", img.height);
609 drawAtXY(img.tex, 10-img.sx, 10-img.sy);
614 int mofsx, mofsy;
616 if (altMove || movement || scale == 1) {
617 mofsx = mapOfsX;
618 mofsy = mapOfsY;
619 } else {
620 if (frameInterpolation) {
621 import core.stdc.math : roundf;
622 mofsx = cast(int)(mapViewPosX[0]+roundf((mapViewPosX[1]-mapViewPosX[0])*atob));
623 mofsy = cast(int)(mapViewPosY[0]+roundf((mapViewPosY[1]-mapViewPosY[0])*atob));
624 } else {
625 mofsx = mapViewPosX[1];
626 mofsy = mapViewPosY[1];
630 orthoCamera(vlWidth, vlHeight);
631 auto tex = (doLighting ? fboLevelLight.tex.tid : fboOrigBack.tex.tid);
632 drawAtXY(tex, -mofsx, -mofsy, map.width*8*scale, map.height*8*scale, mirrorY:true);
634 doMessages(curtime);
638 // ////////////////////////////////////////////////////////////////////////// //
639 // returns time slept
640 int sleepAtMaxMsecs (int msecs) {
641 if (msecs > 0) {
642 import core.sys.posix.signal : timespec;
643 import core.sys.posix.time : nanosleep;
644 timespec ts = void, tpassed = void;
645 ts.tv_sec = 0;
646 ts.tv_nsec = msecs*1000*1000+(500*1000); // milli to nano
647 nanosleep(&ts, &tpassed);
648 return (ts.tv_nsec-tpassed.tv_nsec)/(1000*1000);
649 } else {
650 return 0;
655 // ////////////////////////////////////////////////////////////////////////// //
656 // rendering thread
657 shared int diedie = 0;
659 enum D2DFrameTime = 55; // milliseconds
660 enum MinFrameTime = 1000/60; // ~60 FPS
662 void renderThread () {
663 try {
664 version(use_vsync) {} else MonoTime ltt = MonoTime.currTime;
666 MonoTime curtime = MonoTime.currTime;
668 lastthink = curtime; // for interpolator
669 nextthink = curtime+dur!"msecs"(D2DFrameTime);
670 MonoTime nextvframe = curtime;
672 enum MaxFPSFrames = 16;
673 float frtimes = 0.0f;
674 int framenum = 0;
675 int prevFPS = -1;
676 int hushFrames = 6; // ignore first `hushFrames` frames overtime
677 MonoTime prevFrameStartTime = curtime;
679 bool vframeWasLost = false;
681 // "D2D frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
682 bool doThinkFrame () {
683 if (curtime >= nextthink) {
684 lastthink = curtime;
685 while (nextthink <= curtime) nextthink += dur!"msecs"(D2DFrameTime);
686 // save snapshot and other datafor interpolator
687 Actor.saveSnapshot(prevFrameActorsData[], prevFrameActorOfs.ptr);
688 mapViewPosX[0] = mapViewPosX[1];
689 mapViewPosY[0] = mapViewPosY[1];
690 // process actors
691 doActorsThink();
692 // some timing
693 auto tm = MonoTime.currTime;
694 int thinkTime = cast(int)((tm-curtime).total!"msecs");
695 if (thinkTime > 9) { import core.stdc.stdio; printf("spent on thinking: %d msecs\n", thinkTime); }
696 curtime = tm;
697 return true;
698 } else {
699 return false;
703 // "video frames"; curtime should be set; return `true` if frame was processed; will fix `curtime`
704 bool doVFrame () {
705 version(use_vsync) {
706 __gshared bool prevLost = false;
707 bool doCheckTime = vframeWasLost;
708 if (vframeWasLost) {
709 if (!prevLost) {
710 { import core.stdc.stdio; printf("frame was lost!\n"); }
712 prevLost = true;
713 } else {
714 prevLost = false;
716 } else {
717 enum doCheckTime = true;
719 if (doCheckTime) {
720 if (curtime < nextvframe) return false;
721 version(use_vsync) {} else {
722 if (curtime > nextvframe) {
723 auto overtime = cast(int)((curtime-nextvframe).total!"msecs");
724 if (overtime > 2500) {
725 if (hushFrames) {
726 --hushFrames;
727 } else {
728 { import core.stdc.stdio; printf(" spent whole %d msecs\n", overtime); }
734 while (nextvframe <= curtime) nextvframe += dur!"msecs"(MinFrameTime);
735 bool ctset = false;
737 sdwindow.mtLock();
738 scope(exit) sdwindow.mtUnlock();
739 ctset = sdwindow.setAsCurrentOpenGlContextNT;
741 // if we can't set context, pretend that videoframe was processed; this should solve problem with vsync and invisible window
742 if (ctset) {
743 // render scene
744 iLiquidTime = cast(float)((curtime-MonoTime.zero).total!"msecs"%10000000)/18.0f*0.04f;
745 renderScene(curtime);
746 sdwindow.mtLock();
747 scope(exit) sdwindow.mtUnlock();
748 sdwindow.swapOpenGlBuffers();
749 glFinish();
750 sdwindow.releaseCurrentOpenGlContext();
751 vframeWasLost = false;
752 } else {
753 vframeWasLost = true;
754 { import core.stdc.stdio; printf("xframe was lost!\n"); }
756 curtime = MonoTime.currTime;
757 return true;
760 for (;;) {
761 if (sdwindow.closed) break;
762 if (atomicLoad(diedie) > 0) break;
764 curtime = MonoTime.currTime;
765 auto fstime = curtime;
767 doThinkFrame(); // this will fix curtime if necessary
768 if (doVFrame()) {
769 if (!vframeWasLost) {
770 // fps
771 auto frameTime = cast(float)(curtime-prevFrameStartTime).total!"msecs"/1000.0f;
772 prevFrameStartTime = curtime;
773 frtimes += frameTime;
774 if (++framenum >= MaxFPSFrames || frtimes >= 3.0f) {
775 import std.string : format;
776 int newFPS = cast(int)(cast(float)MaxFPSFrames/frtimes+0.5);
777 if (newFPS != prevFPS) {
778 sdwindow.title = "%s / FPS:%s".format("D2D", newFPS);
779 prevFPS = newFPS;
781 framenum = 0;
782 frtimes = 0.0f;
787 curtime = MonoTime.currTime;
789 // now sleep until next "video" or "think" frame
790 if (nextthink > curtime && nextvframe > curtime) {
791 // let's decide
792 immutable nextVideoFrameSleep = cast(int)((nextvframe-curtime).total!"msecs");
793 immutable nextThinkFrameSleep = cast(int)((nextthink-curtime).total!"msecs");
794 immutable sleepTime = (nextVideoFrameSleep < nextThinkFrameSleep ? nextVideoFrameSleep : nextThinkFrameSleep);
795 sleepAtMaxMsecs(sleepTime);
796 //curtime = MonoTime.currTime;
799 } catch (Exception e) {
800 import core.stdc.stdio;
801 fprintf(stderr, "FUUUUUUUUUUUUUUUUUUUUUUUUUU\n");
802 for (;;) {
803 if (sdwindow.closed) break;
804 if (atomicLoad(diedie) > 0) break;
805 //{ import core.stdc.stdio; printf(" spent only %d msecs\n", cast(int)((time-ltt).total!"msecs")); }
806 sleepAtMaxMsecs(100);
809 atomicStore(diedie, 2);
813 // ////////////////////////////////////////////////////////////////////////// //
814 void closeWindow () {
815 if (atomicLoad(diedie) != 2) {
816 atomicStore(diedie, 1);
817 while (atomicLoad(diedie) != 2) {}
819 if (!sdwindow.closed) {
820 flushGui();
821 sdwindow.close();
826 // ////////////////////////////////////////////////////////////////////////// //
827 __gshared Thread renderTid;
830 void main (string[] args) {
831 FuncPool.dumpCode = false;
832 FuncPool.dumpCodeSize = false;
833 dacsDumpSemantic = false;
834 dacsOptimize = 9;
835 //version(rdmd) { dacsOptimize = 0; }
836 bool compileOnly = false;
838 for (usize idx = 1; idx < args.length; ++idx) {
839 bool remove = true;
840 if (args[idx] == "--dump-code") FuncPool.dumpCode = true;
841 else if (args[idx] == "--dump-code-size") FuncPool.dumpCodeSize = true;
842 else if (args[idx] == "--dump-semantic") dacsDumpSemantic = true;
843 else if (args[idx] == "--dump-all") { FuncPool.dumpCode = true; FuncPool.dumpCodeSize = true; dacsDumpSemantic = true; }
844 else if (args[idx] == "--compile") compileOnly = true;
845 else if (args[idx] == "--compile-only") compileOnly = true;
846 else if (args[idx] == "--messages") ++dacsMessages;
847 else if (args[idx] == "--no-copro") dacsOptimizeNoCoPro = true;
848 else if (args[idx] == "--no-deadass") dacsOptimizeNoDeadAss = true;
849 else if (args[idx] == "--no-purekill") dacsOptimizeNoPureKill = true;
850 else if (args[idx].length > 2 && args[idx][0..2] == "-O") {
851 import std.conv : to;
852 ubyte olevel = to!ubyte(args[idx][2..$]);
853 dacsOptimize = olevel;
855 else remove = false;
856 if (remove) {
857 foreach (immutable c; idx+1..args.length) args.ptr[c-1] = args.ptr[c];
858 args.length -= 1;
859 --idx; //hack
863 static void setDP () {
864 version(rdmd) {
865 setDataPath("data");
866 } else {
867 import std.file : thisExePath;
868 import std.path : dirName;
869 setDataPath(thisExePath.dirName);
871 addPK3(getDataPath~"base.pk3"); loadWadScripts();
872 //addWad("/home/ketmar/k8prj/doom2d-tl/data/doom2d.wad"); loadWadScripts();
873 //addWad("/home/ketmar/k8prj/doom2d-tl/data/meat.wad"); loadWadScripts();
874 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm.wad"); loadWadScripts();
875 //addWad("/home/ketmar/k8prj/doom2d-tl/data/megadm1.wad"); loadWadScripts();
876 //addWad("/home/ketmar/k8prj/doom2d-tl/data/superdm.wad"); loadWadScripts();
877 //addWad("/home/ketmar/k8prj/doom2d-tl/data/zadoomka.wad"); loadWadScripts();
878 scriptLoadingComplete();
881 setDP();
883 if (compileOnly) return;
885 try {
886 registerAPI();
887 loadPalette();
889 setOpenGLContextVersion(3, 2); // up to GLSL 150
890 //openGLContextCompatible = false;
892 map = new LevelMap("maps/map01.d2m");
893 ugInit(map.width*8, map.height*8);
895 scale = 2;
897 //mapOfsX = 8*26;
898 //mapOfsY = 8*56;
899 map.getThingPos(1/*ThingId.Player1*/, &mapOfsX, &mapOfsY);
900 // fix viewport
902 mapOfsX = (mapOfsX*2)-vlWidth/2;
903 if (mapOfsX+vlWidth > map.width*16) mapOfsX = map.width*16-vlWidth;
904 if (mapOfsX < 0) mapOfsX = 0;
905 mapOfsY = (mapOfsY*2)-vlHeight/2;
906 if (mapOfsY+vlHeight > map.height*16) mapOfsY = map.height*16-vlHeight;
907 if (mapOfsY < 0) mapOfsY = 0;
909 setMapViewPos(mapOfsX, mapOfsY);
910 mapOfsX = mapViewPosX[1];
911 mapOfsY = mapViewPosY[1];
913 sdwindow = new SimpleWindow(vlWidth, vlHeight, "D2D", OpenGlOptions.yes, Resizablity.fixedSize);
915 sdwindow.visibleForTheFirstTime = delegate () {
916 sdwindow.setAsCurrentOpenGlContext(); // make this window active
917 glbindLoadFunctions();
920 import core.stdc.stdio;
921 printf("GL version: %s\n", glGetString(GL_VERSION));
922 GLint l, h;
923 glGetIntegerv(GL_MAJOR_VERSION, &h);
924 glGetIntegerv(GL_MINOR_VERSION, &l);
925 printf("version: %d.%d\n", h, l);
926 printf("shader version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION));
927 GLint svcount;
928 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &svcount);
929 if (svcount > 0) {
930 printf("%d shader versions supported:\n", svcount);
931 foreach (GLuint n; 0..svcount) printf(" %d: %s\n", n, glGetStringi(GL_SHADING_LANGUAGE_VERSION, n));
934 GLint ecount;
935 glGetIntegerv(GL_NUM_EXTENSIONS, &ecount);
936 if (ecount > 0) {
937 printf("%d extensions supported:\n", ecount);
938 foreach (GLuint n; 0..ecount) printf(" %d: %s\n", n, glGetStringi(GL_EXTENSIONS, n));
943 // check if we have sufficient shader version here
945 bool found = false;
946 GLint svcount;
947 glGetIntegerv(GL_NUM_SHADING_LANGUAGE_VERSIONS, &svcount);
948 if (svcount > 0) {
949 foreach (GLuint n; 0..svcount) {
950 import core.stdc.string : strncmp;
951 auto v = glGetStringi(GL_SHADING_LANGUAGE_VERSION, n);
952 if (v is null) continue;
953 if (strncmp(v, "120", 3) != 0) continue;
954 if (v[3] > ' ') continue;
955 found = true;
956 break;
959 if (!found) assert(0, "can't find OpenGL GLSL 120");
961 auto adr = glGetProcAddress("glTexParameterf");
962 if (adr is null) assert(0);
965 version(use_vsync) {
966 sdwindow.vsync = true;
967 } else {
968 sdwindow.vsync = false;
970 //sdwindow.useGLFinish = false;
971 initOpenGL();
972 //sdwindow.redrawOpenGlScene();
973 if (!sdwindow.releaseCurrentOpenGlContext()) { import core.stdc.stdio; printf("can't release OpenGL context(1)\n"); }
974 if (!renderTid) {
975 renderTid = new Thread(&renderThread);
976 renderTid.start();
980 //sdwindow.redrawOpenGlScene = delegate () { renderScene(); };
982 enum MSecsPerFrame = 1000/30; /* 30 is FPS */
984 uint[8] frameTimes = 1000;
985 enum { Left, Right, Up, Down }
986 bool[4] pressed = false;
988 sdwindow.eventLoop(MSecsPerFrame,
989 delegate () {
990 if (sdwindow.closed) return;
991 if (pressed[Left]) mapOfsX -= 8;
992 if (pressed[Right]) mapOfsX += 8;
993 if (pressed[Up]) mapOfsY -= 8;
994 if (pressed[Down]) mapOfsY += 8;
995 import std.math : cos, sin;
996 __gshared float itime = 0.0;
997 itime += 0.02;
998 if (movement) {
999 mapOfsX = cast(int)(800.0/2.0+cos(itime)*220.0);
1000 mapOfsY = cast(int)(800.0/2.0+120.0+sin(itime)*160.0);
1002 if (scale == 1) mapOfsX = mapOfsY = 0;
1003 //sdwindow.redrawOpenGlSceneNow();
1005 delegate (KeyEvent event) {
1006 if (sdwindow.closed) return;
1007 if (event.pressed && event.key == Key.Escape) { closeWindow(); return; }
1008 switch (event.key) {
1009 case Key.X: if (event.pressed) altMove = !altMove; break;
1010 case Key.Left: if (altMove) pressed[Left] = event.pressed; break;
1011 case Key.Right: if (altMove) pressed[Right] = event.pressed; break;
1012 case Key.Up: if (altMove) pressed[Up] = event.pressed; break;
1013 case Key.Down: if (altMove) pressed[Down] = event.pressed; break;
1014 default:
1016 if (!altMove) {
1017 switch (event.key) {
1018 case Key.Left: case Key.Pad4: plrKeyUpDown(0, PLK_LEFT, event.pressed); break;
1019 case Key.Right: case Key.Pad6: plrKeyUpDown(0, PLK_RIGHT, event.pressed); break;
1020 case Key.Up: case Key.Pad8: plrKeyUpDown(0, PLK_UP, event.pressed); break;
1021 case Key.Down: case Key.Pad2: plrKeyUpDown(0, PLK_DOWN, event.pressed); break;
1022 case Key.Alt: plrKeyUpDown(0, PLK_JUMP, event.pressed); break;
1023 case Key.Ctrl: plrKeyUpDown(0, PLK_FIRE, event.pressed); break;
1024 case Key.Shift: plrKeyUpDown(0, PLK_USE, event.pressed); break;
1025 default:
1029 delegate (MouseEvent event) {
1030 lightX = event.x/scale;
1031 lightY = event.y/scale;
1032 lightX += mapOfsX/scale;
1033 lightY += mapOfsY/scale;
1035 delegate (dchar ch) {
1036 if (ch == 'q') { closeWindow(); return; }
1037 if (ch == 's') scanlines = !scanlines;
1038 if (ch == '1') scale = 1;
1039 if (ch == '2') scale = 2;
1040 if (ch == 'D') cheatNoDoors = !cheatNoDoors;
1041 if (ch == 'i') {
1042 frameInterpolation = !frameInterpolation;
1043 if (frameInterpolation) addMessage("Interpolation: ON"); else addMessage("Interpolation: OFF");
1045 if (ch == 'l') {
1046 doLighting = !doLighting;
1047 if (doLighting) addMessage("Lighting: ON"); else addMessage("Lighting: OFF");
1049 if (ch == ' ') movement = !movement;
1052 } catch (Exception e) {
1053 import std.stdio : stderr;
1054 stderr.writeln("FUUUUUUUUUUUU\n", e.toString);
1056 closeWindow();
1057 flushGui();