you can type commands in console now
[dd2d.git] / glutils.d
blobbab34bef764c1173fa7893cc9e2c0f2f4c160b4a
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 glutils is aliced;
19 private:
20 import iv.glbinds;
21 import arsd.color;
22 import arsd.png;
24 import wadarc;
27 // ////////////////////////////////////////////////////////////////////////// //
28 __gshared bool glutilsShowShaderWarnings = false; // shut up!
31 __gshared GLuint glLastUsedTexture = 0;
33 public void useTexture (GLuint tid) {
34 pragma(inline, true);
35 if (glLastUsedTexture != tid) {
36 glLastUsedTexture = tid;
37 glBindTexture(GL_TEXTURE_2D, tid);
41 public void useTexture (Texture tex) { pragma(inline, true); useTexture(tex !is null ? tex.tid : 0); }
45 public TrueColorImage loadPngFile (string fname) {
46 auto fl = openFile(fname);
47 auto sz = fl.size;
48 if (sz < 4 || sz > 32*1024*1024) throw new Exception("invalid png file size: '"~fname~"'");
49 if (sz == 0) return null;
50 auto res = new ubyte[](cast(uint)sz);
51 if (fl.rawRead(res[]).length != res.length) throw new Exception("error reading png file '"~fname~"'");
52 return imageFromPng(readPng(res)).getAsTrueColorImage;
56 // ////////////////////////////////////////////////////////////////////////// //
57 class OpenGLObject {
58 abstract @property uint id () const pure nothrow @nogc;
60 final void activate () nothrow @nogc {
61 if (gloSP >= gloStack.length) assert(0, "glo stack overflow");
62 gloStack.ptr[gloSP++] = this;
63 activateObj();
66 final void deactivate () nothrow @nogc {
67 foreach_reverse (usize idx; 0..gloStack.length) {
68 if (gloStack.ptr[idx] is this) {
69 // find previous object of this type
70 foreach_reverse (usize pidx; 0..idx) {
71 if (typeid(gloStack.ptr[pidx]) is typeid(gloStack.ptr[idx])) {
72 gloStack.ptr[pidx].activateObj();
73 removeFromStack(pidx);
74 return;
77 deactivateObj();
78 removeFromStack(idx);
79 return;
82 assert(0, "trying to deactivate inactive object");
85 protected:
86 abstract void activateObj () nothrow @nogc;
87 abstract void deactivateObj () nothrow @nogc;
91 __gshared OpenGLObject[1024] gloStack;
92 __gshared uint gloSP = 0;
95 public void gloStackClear () nothrow @nogc {
96 bindTexture(0);
97 //glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
98 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
99 glUseProgram(0);
103 void removeFromStack (usize idx) nothrow @nogc {
104 if (idx >= gloSP) return;
105 if (idx != gloSP-1) {
106 import core.stdc.string : memmove;
107 memmove(gloStack.ptr+idx, gloStack.ptr+idx+1, (gloSP-idx-1)*gloStack[0].sizeof);
109 --gloSP;
113 // ////////////////////////////////////////////////////////////////////////// //
114 public final class Texture : OpenGLObject {
115 GLuint tid;
116 int width, height;
118 override @property uint id () const pure nothrow @nogc => tid;
120 // default: repeat, linear
121 enum Option : int {
122 Repeat,
123 Clamp,
124 ClampBorder,
125 Linear,
126 Nearest,
127 UByte,
128 Float, // create floating point texture
129 Depth, // FBO: attach depth buffer
132 this (string fname, in Option[] opts...) { loadPng(fname, opts); }
133 this (int w, int h, in Option[] opts...) { createIntr(w, h, null, opts); }
134 this (TrueColorImage aimg, Option[] opts...) { createIntr(aimg.width, aimg.height, aimg, opts); }
135 ~this () { clear(); }
138 void clear () {
139 if (tid) {
140 //useTexture(tid);
141 bindTexture(tid);
142 glDeleteTextures(1, &tid);
143 //useTexture(0);
144 bindTexture(0);
145 tid = 0;
146 width = 0;
147 height = 0;
151 private static void processOpt (GLuint* wrapOpt, GLuint* filterOpt, GLuint* ttype, in Option[] opts...) {
152 foreach (immutable opt; opts) {
153 switch (opt) with (Option) {
154 case Repeat: *wrapOpt = GL_REPEAT; break;
155 case Clamp: *wrapOpt = GL_CLAMP_TO_EDGE; break;
156 case ClampBorder: *wrapOpt = GL_CLAMP_TO_BORDER; break;
157 case Linear: *filterOpt = GL_LINEAR; break;
158 case Nearest: *filterOpt = GL_NEAREST; break;
159 case UByte: *ttype = GL_UNSIGNED_BYTE; break;
160 case Float: *ttype = GL_FLOAT; break;
161 default:
166 void createIntr (int w, int h, TrueColorImage img, in Option[] opts...) {
167 import core.stdc.stdlib : malloc, free;
168 assert(w > 0);
169 assert(h > 0);
170 clear();
172 GLuint wrapOpt = GL_REPEAT;
173 GLuint filterOpt = GL_LINEAR;
174 GLuint ttype = GL_UNSIGNED_BYTE;
175 processOpt(&wrapOpt, &filterOpt, &ttype, opts);
177 glGenTextures(1, &tid);
178 //useTexture(tid);
179 auto oldtid = boundTexture;
180 bindTexture(tid);
181 scope(exit) bindTexture(oldtid);
182 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapOpt);
183 glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapOpt);
184 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, filterOpt);
185 glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filterOpt);
186 //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
187 //glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
188 GLfloat[4] bclr = 0.0;
189 glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, bclr.ptr);
190 if (img !is null && img.width == w && img.height == h) {
191 // create straight from image
192 glTexImage2D(GL_TEXTURE_2D, 0, (ttype == GL_FLOAT ? GL_RGBA16F : GL_RGBA), w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, img.imageData.bytes.ptr);
193 } else {
194 // create empty texture
195 ubyte* ptr = null;
196 scope(exit) if (ptr !is null) free(ptr);
198 import core.stdc.string : memset;
199 ptr = cast(ubyte*)malloc(w*h*4);
200 if (ptr !is null) memset(ptr, 0, w*h*4);
202 glTexImage2D(GL_TEXTURE_2D, 0, (ttype == GL_FLOAT ? GL_RGBA16F : GL_RGBA), w, h, 0, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
203 if (img !is null && img.width > 0 && img.height > 0) {
204 // setup from image
205 //TODO: dunno if it's ok to use images bigger than texture here
206 glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, img.imageData.bytes.ptr);
207 // the following is ok too
208 //bindTexture(0);
209 //glTextureSubImage2D(tid, 0, 0, 0, img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, img.imageData.bytes.ptr);
212 width = w;
213 height = h;
216 void setFromImage (TrueColorImage img, int x=0, int y=0) {
217 if (img is null || !tid || img.height < 1 || img.width < 1) return;
218 if (x >= width || y >= height) return;
219 if (x+img.width <= 0 || y+img.height <= 0) return; //TODO: overflow
220 if (x >= 0 && y >= 0 && x+img.width <= width && y+img.height <= height) {
221 // easy case, just copy it
222 glTextureSubImage2D(tid, 0, x, y, img.width, img.height, GL_RGBA, GL_UNSIGNED_BYTE, img.imageData.bytes.ptr);
223 } else {
224 import core.stdc.stdlib : malloc, free;
225 import core.stdc.string : memset, memcpy;
226 // hard case, have to build the temp region
227 uint* src = cast(uint*)img.imageData.bytes.ptr;
228 // calc x skip and effective width
229 int rwdt = img.width;
230 if (x < 0) {
231 rwdt += x;
232 src -= x; // as `x` is negative here
233 x = 0;
235 if (x+rwdt > width) rwdt = width-x;
236 // calc y skip and effective height
237 int rhgt = img.height;
238 if (y < 0) {
239 rhgt += y;
240 src -= y*img.width; // as `y` is negative here
241 y = 0;
243 if (y+rhgt > height) rhgt = height-y;
244 assert(rwdt > 0 && rhgt > 0);
245 uint* ptr = null;
246 scope(exit) if (ptr !is null) free(ptr);
247 ptr = cast(uint*)malloc(rwdt*rhgt*4);
248 if (ptr is null) assert(0, "out of memory in `Texture.setFromImage()`");
249 // now copy
250 auto d = ptr;
251 foreach (immutable _; 0..rhgt) {
252 memcpy(d, src, rwdt*4);
253 src += img.width;
254 d += rwdt;
256 glTextureSubImage2D(tid, 0, x, y, rwdt, rhgt, GL_RGBA, GL_UNSIGNED_BYTE, ptr);
260 void loadPng (string fname, in Option[] opts...) {
261 scope(failure) clear;
262 auto img = loadPngFile(fname);
263 createIntr(img.width, img.height, img, opts);
266 protected:
267 override void activateObj () nothrow @nogc { /*if (tid)*/ bindTexture(tid); }
268 override void deactivateObj () nothrow @nogc { /*if (tid)*/ bindTexture(0); }
272 // ////////////////////////////////////////////////////////////////////////// //
273 public final class FBO : OpenGLObject {
274 int width;
275 int height;
276 GLuint fbo;
277 Texture tex;
278 Texture texdepth;
279 //Texture.Option[] xopts;
281 override @property uint id () const pure nothrow @nogc => fbo;
283 this (Texture atex) { createWithTexture(atex); }
285 this (int wdt, int hgt, Texture.Option[] opts...) {
286 //xopts = opts.dup;
287 createWithTexture(new Texture(wdt, hgt, opts), opts);
290 ~this () {
291 //FIXME: this may be wrong, as texture may be already destroyed (and it's wrong too); we need refcount for textures
292 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0);
293 glDeleteFramebuffersEXT(1, &fbo);
294 fbo = 0;
297 void clear () {
298 if (fbo) {
299 // detach texture
300 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0);
301 glDeleteFramebuffersEXT(1, &fbo);
302 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, 0, 0);
303 glDeleteFramebuffersEXT(1, &fbo);
304 fbo = 0;
306 if (tex !is null) tex.clear();
307 tex = null;
308 if (texdepth !is null) texdepth.clear();
309 texdepth = null;
312 protected:
313 override void activateObj () nothrow @nogc { /*if (fbo)*/ glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo); }
314 override void deactivateObj () nothrow @nogc { glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0); }
316 // this will deactivate current FBO!
318 void replaceTexture (Texture ntex) {
319 if (tex !is null) {
320 if (ntex !is null && ntex.tid == tex.tid) return;
321 } else {
322 if (ntex is null) return;
324 glGenFramebuffersEXT(1, &fbo);
325 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
326 scope(exit) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
327 // detach texture
328 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, 0, 0);
329 glDeleteFramebuffersEXT(1, &fbo);
330 fbo = 0;
331 tex = ntex;
332 // attach texture
333 if (tex !is null) {
334 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex.tid, 0);
336 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
337 if (status != GL_FRAMEBUFFER_COMPLETE_EXT) assert(0, "framebuffer fucked!");
343 private:
344 void createWithTexture (Texture atex, Texture.Option[] opts...) {
345 assert(atex !is null && atex.tid);
347 tex = atex;
348 glGenFramebuffersEXT(1, &fbo);
349 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);
350 scope(exit) glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
351 // attach 2D texture to this FBO
352 glFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, tex.tid, 0);
353 // GL_COLOR_ATTACHMENT0_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_STENCIL_ATTACHMENT_EXT
355 void createDepth () {
356 uint fboDepthId;
357 glGenRenderbuffersEXT(1, &fboDepthId);
358 glBindRenderbufferEXT(GL_RENDERBUFFER_EXT, fboDepthId);
359 glRenderbufferStorageEXT(GL_RENDERBUFFER_EXT, GL_DEPTH_COMPONENT/*24*/, atex.width, atex.height);
360 // attach depth buffer to FBO
361 glFramebufferRenderbufferEXT(GL_FRAMEBUFFER_EXT, GL_DEPTH_ATTACHMENT_EXT, GL_RENDERBUFFER_EXT, fboDepthId);
362 // kill it (we don't need it anymore)
363 glDeleteRenderbuffersEXT(1, &fboDepthId);
367 foreach (Texture.Option opt; opts) {
368 if (opt == Texture.Option.Depth) {
369 createDepth();
370 break;
374 //createDepth();
377 GLenum status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER_EXT);
378 if (status != GL_FRAMEBUFFER_COMPLETE_EXT) assert(0, "framebuffer fucked!");
380 glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, 0);
382 width = tex.width;
383 height = tex.height;
388 // ////////////////////////////////////////////////////////////////////////// //
389 public struct SVec2I { int x, y; }
390 public struct SVec3I { int x, y, z; alias r = x; alias g = y; alias b = z; }
391 public struct SVec4I { int x, y, z, w; alias r = x; alias g = y; alias b = z; alias a = w; }
393 public struct SVec2F { float x, y; }
394 public struct SVec3F { float x, y, z; alias r = x; alias g = y; alias b = z; }
395 public struct SVec4F { float x, y, z, w; alias r = x; alias g = y; alias b = z; alias a = w; }
398 public final class Shader : OpenGLObject {
399 string shaderName;
400 GLuint prg = 0;
401 GLint[string] vars;
403 override @property uint id () const pure nothrow @nogc => prg;
405 this (string ashaderName, const(char)[] src) {
406 shaderName = ashaderName;
407 if (src.length > int.max) {
408 import core.stdc.stdio : printf;
409 printf("shader '%.*s' code too long!", cast(uint)ashaderName.length, ashaderName.ptr);
410 assert(0);
412 auto shaderId = glCreateShader(GL_FRAGMENT_SHADER);
413 auto sptr = src.ptr;
414 GLint slen = cast(int)src.length;
415 glShaderSource(shaderId, 1, &sptr, &slen);
416 glCompileShader(shaderId);
417 GLint success = 0;
418 glGetShaderiv(shaderId, GL_COMPILE_STATUS, &success);
419 if (!success || glutilsShowShaderWarnings) {
420 import core.stdc.stdio : printf;
421 import core.stdc.stdlib : malloc, free;
422 GLint logSize = 0;
423 glGetShaderiv(shaderId, GL_INFO_LOG_LENGTH, &logSize);
424 if (logSize > 0) {
425 auto logStrZ = cast(GLchar*)malloc(logSize);
426 glGetShaderInfoLog(shaderId, logSize, null, logStrZ);
427 printf("shader '%.*s' compilation messages:\n%s\n", cast(uint)ashaderName.length, ashaderName.ptr, logStrZ);
428 free(logStrZ);
431 if (!success) assert(0);
432 prg = glCreateProgram();
433 glAttachShader(prg, shaderId);
434 glLinkProgram(prg);
437 GLint varId(NT) (NT vname) if (is(NT == char[]) || is(NT == const(char)[]) || is(NT == immutable(char)[])) {
438 GLint id = -1;
439 if (vname.length > 0 && vname.length <= 128) {
440 if (auto vi = vname in vars) {
441 id = *vi;
442 } else {
443 char[129] buf = void;
444 buf[0..vname.length] = vname[];
445 buf[vname.length] = 0;
446 id = glGetUniformLocation(prg, buf.ptr);
447 //{ import core.stdc.stdio; printf("[%.*s.%s]=%i\n", cast(uint)shaderName.length, shaderName.ptr, buf.ptr, id); }
448 static if (is(NT == immutable(char)[])) {
449 vars[vname.idup] = id;
450 } else {
451 vars[vname.idup] = id;
453 if (id < 0) {
454 import core.stdc.stdio : printf;
455 printf("shader '%.*s': unknown variable '%.*s'\n", cast(uint)shaderName.length, shaderName.ptr, cast(uint)vname.length, vname.ptr);
459 return id;
462 // get unified var id
463 GLint opIndex(NT) (NT vname) if (is(NT == char[]) || is(NT == const(char)[]) || is(NT == immutable(char)[])) {
464 auto id = varId(vname);
465 if (id < 0) {
466 import core.stdc.stdio : printf;
467 printf("shader '%.*s': unknown variable '%.*s'\n", cast(uint)shaderName.length, shaderName.ptr, cast(uint)vname.length, vname.ptr);
468 assert(0);
470 return id;
473 private import std.traits;
474 void opIndexAssign(T, NT) (in auto ref T v, NT vname)
475 if (((isIntegral!T && T.sizeof <= 4) || (isFloatingPoint!T && T.sizeof == float.sizeof) || isBoolean!T ||
476 is(T : SVec2I) || is(T : SVec3I) || is(T : SVec4I) ||
477 is(T : SVec2F) || is(T : SVec3F) || is(T : SVec4F)) &&
478 (is(NT == char[]) || is(NT == const(char)[]) || is(NT == immutable(char)[])))
480 auto id = varId(vname);
481 if (id < 0) return;
482 //{ import core.stdc.stdio; printf("setting '%.*s' (%d)\n", cast(uint)vname.length, vname.ptr, id); }
483 static if (isIntegral!T || isBoolean!T) glUniform1i(id, cast(int)v);
484 else static if (isFloatingPoint!T) glUniform1f(id, cast(float)v);
485 else static if (is(SVec2I : T)) glUniform2i(id, cast(int)v.x, cast(int)v.y);
486 else static if (is(SVec3I : T)) glUniform3i(id, cast(int)v.x, cast(int)v.y, cast(int)v.z);
487 else static if (is(SVec4I : T)) glUniform4i(id, cast(int)v.x, cast(int)v.y, cast(int)v.z, cast(int)v.w);
488 else static if (is(SVec2F : T)) glUniform2f(id, cast(float)v.x, cast(float)v.y);
489 else static if (is(SVec3F : T)) glUniform3f(id, cast(float)v.x, cast(float)v.y, cast(float)v.z);
490 else static if (is(SVec4F : T)) glUniform4f(id, cast(float)v.x, cast(float)v.y, cast(float)v.z, cast(float)v.w);
491 else static assert(0, "wtf?!");
494 protected:
495 override void activateObj () nothrow @nogc { /*if (prg)*/ glUseProgram(prg); }
496 override void deactivateObj () nothrow @nogc { glUseProgram(0); }
500 // ////////////////////////////////////////////////////////////////////////// //
501 //private import std.traits;
503 public:
504 void exec(TO) (TO obj, scope void delegate () dg) if (is(typeof(() { obj.activate(); obj.deactivate(); }))) {
505 obj.activate();
506 scope(exit) obj.deactivate();
507 dg();
510 void exec(TO, TG) (TO obj, scope TG dg) if (is(typeof((TO obj) { dg(obj); })) && is(typeof(() { obj.activate(); obj.deactivate(); }))) {
511 obj.activate();
512 scope(exit) obj.deactivate();
513 dg(obj);
517 // ////////////////////////////////////////////////////////////////////////// //
518 void orthoCamera (int wdt, int hgt) {
519 glMatrixMode(GL_PROJECTION); // for ortho camera
520 glLoadIdentity();
521 // left, right, bottom, top, near, far
522 //glOrtho(0, wdt, 0, hgt, -1, 1); // bottom-to-top
523 glOrtho(0, wdt, hgt, 0, -1, 1); // top-to-bottom
524 glViewport(0, 0, wdt, hgt);
526 //glTranslatef(-cx, -cy, 0.0f);
529 // origin is texture left top
530 void drawAtXY (GLuint tid, int x, int y, int w, int h, bool mirrorX=false, bool mirrorY=false) {
531 if (!tid || w < 1 || h < 1) return;
532 w += x;
533 h += y;
534 if (mirrorX) { int tmp = x; x = w; w = tmp; }
535 if (mirrorY) { int tmp = y; y = h; h = tmp; }
536 bindTexture(tid);
537 glBegin(GL_QUADS);
538 glTexCoord2f(0.0f, 0.0f); glVertex2i(x, y); // top-left
539 glTexCoord2f(1.0f, 0.0f); glVertex2i(w, y); // top-right
540 glTexCoord2f(1.0f, 1.0f); glVertex2i(w, h); // bottom-right
541 glTexCoord2f(0.0f, 1.0f); glVertex2i(x, h); // bottom-left
542 glEnd();
546 // origin is texture center
547 void drawAtXYC (Texture tex, int x, int y, bool mirrorX=false, bool mirrorY=false) {
548 if (tex is null || !tex.tid) return;
549 x -= tex.width/2;
550 y -= tex.height/2;
551 drawAtXY(tex.tid, x, y, tex.width, tex.height, mirrorX, mirrorY);
555 // origin is texture left top
556 void drawAtXY (Texture tex, int x, int y, bool mirrorX=false, bool mirrorY=false) {
557 if (tex is null || !tex.tid) return;
558 drawAtXY(tex.tid, x, y, tex.width, tex.height, mirrorX, mirrorY);
562 private __gshared GLuint boundTexture = 0;
564 // make sure that texture unit 0 is active!
565 void bindTexture (GLuint tid) nothrow @trusted @nogc {
566 if (tid != boundTexture) {
567 boundTexture = tid;
568 glBindTexture(GL_TEXTURE_2D, tid);