app.d 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393
  1. import std.stdio;
  2. import std.typecons;
  3. import derelict.opengl3.gl3;
  4. import derelict.glfw3.glfw3;
  5. import derelict.anttweakbar.anttweakbar;
  6. import derelict.freeimage.freeimage;
  7. import derelict.freetype.ft;
  8. import derelict.assimp3.assimp;
  9. import std.string;
  10. import std.experimental.logger;
  11. //======================================================================================================================
  12. //
  13. //======================================================================================================================
  14. import std.traits : ReturnType;
  15. ReturnType!func glCheck(alias func, Args...)(Args args) {
  16. import std.stdio;
  17. import std.stdio : stderr;
  18. import std.array : join;
  19. import std.range : repeat;
  20. import std.string : format;
  21. try{
  22. debug scope(exit) {
  23. GLenum err = glGetError();
  24. if(err != GL_NO_ERROR) {
  25. stderr.writefln(`OpenGL function "%s(%s)" failed: "%s."`, func.stringof, format("%s".repeat(Args.length).join(", "), args), glErrorString(err));
  26. assert(false);
  27. }
  28. }
  29. }
  30. catch(Exception e){
  31. }
  32. debug if(func is null) {
  33. try{
  34. stderr.writefln("%s is null! OpenGL loaded? Required OpenGL version not supported?".format(func.stringof));
  35. }
  36. catch(Exception e){
  37. assert(false);
  38. }
  39. assert(false);
  40. }
  41. return func(args);
  42. }
  43. string glErrorString(GLenum error) pure @safe nothrow @nogc {
  44. final switch(error) {
  45. case GL_NO_ERROR: return "no error";
  46. case GL_INVALID_ENUM: return "invalid enum";
  47. case GL_INVALID_VALUE: return "invalid value";
  48. case GL_INVALID_OPERATION: return "invalid operation";
  49. //case GL_STACK_OVERFLOW: return "stack overflow";
  50. //case GL_STACK_UNDERFLOW: return "stack underflow";
  51. case GL_INVALID_FRAMEBUFFER_OPERATION: return "invalid framebuffer operation";
  52. case GL_OUT_OF_MEMORY: return "out of memory";
  53. }
  54. assert(false, "invalid enum");
  55. }
  56. //======================================================================================================================
  57. //
  58. //======================================================================================================================
  59. alias SoA(T) = T[];
  60. //======================================================================================================================
  61. //
  62. //======================================================================================================================
  63. struct SOAVector3 {
  64. SoA!float x;
  65. SoA!float y;
  66. SoA!float z;
  67. }
  68. struct SOAQuaternion {
  69. SoA!float x;
  70. SoA!float y;
  71. SoA!float z;
  72. SoA!float w;
  73. }
  74. //======================================================================================================================
  75. //
  76. //======================================================================================================================
  77. struct Window {
  78. private:
  79. GLFWwindow* glfwWindow = null;
  80. string _title;
  81. uint _x, _y, _w, _h;
  82. KeyAction[int] _keyStates;
  83. ButtonAction[int] _buttonStates;
  84. }
  85. alias ScanCode = int;
  86. enum IconifyAction {
  87. Iconified,
  88. Restored
  89. }
  90. enum FocusAction {
  91. Focused,
  92. Defocused
  93. }
  94. enum CursorAction {
  95. Entered,
  96. Leaved
  97. }
  98. enum ButtonAction {
  99. Pressed,
  100. Released
  101. }
  102. enum KeyAction {
  103. Pressed,
  104. Released,
  105. Repeated
  106. }
  107. enum KeyMod {
  108. Shift = 0x0001,
  109. Control = 0x0002,
  110. Alt = 0x0004,
  111. Super = 0x0008,
  112. }
  113. enum Key {
  114. Unknown = -1,
  115. Space = 32,
  116. Apostrophe = 39,
  117. Comma = 44,
  118. Minus = 45,
  119. Period = 46,
  120. Slash = 47,
  121. Key0 = 48,
  122. Key1 = 49,
  123. Key2 = 50,
  124. Key3 = 51,
  125. Key4 = 52,
  126. Key5 = 53,
  127. Key6 = 54,
  128. Key7 = 55,
  129. Key8 = 56,
  130. Key9 = 57,
  131. Semicolon = 59,
  132. Equal = 61,
  133. KeyA = 65,
  134. KeyB = 66,
  135. KeyC = 67,
  136. KeyD = 68,
  137. KeyE = 69,
  138. KeyF = 70,
  139. KeyG = 71,
  140. KeyH = 72,
  141. KeyI = 73,
  142. KeyJ = 74,
  143. KeyK = 75,
  144. Keyl = 76,
  145. KeyM = 77,
  146. KeyN = 78,
  147. KeyO = 79,
  148. KeyP = 80,
  149. KeyQ = 81,
  150. KeyR = 82,
  151. KeyS = 83,
  152. KeyT = 84,
  153. KeyU = 85,
  154. KeyV = 86,
  155. KeyW = 87,
  156. KeyX = 88,
  157. KeyY = 89,
  158. KeyZ = 90,
  159. LeftBracket = 91,
  160. Backslash = 92,
  161. RightBracket = 93,
  162. GraveAccent = 96,
  163. World1 = 161,
  164. World2 = 162,
  165. Escape = 256,
  166. Enter = 257,
  167. Tab = 258,
  168. Backspace = 259,
  169. Insert = 260,
  170. Delete = 261,
  171. Right = 262,
  172. Left = 263,
  173. Down = 264,
  174. Up = 265,
  175. PageUp = 266,
  176. PageDown = 267,
  177. Home = 268,
  178. End = 269,
  179. CapsLock = 280,
  180. ScrollLock = 281,
  181. NumLock = 282,
  182. PrintScreen = 283,
  183. Pause = 284,
  184. F1 = 290,
  185. F2 = 291,
  186. F3 = 292,
  187. F4 = 293,
  188. F5 = 294,
  189. F6 = 295,
  190. F7 = 296,
  191. F8 = 297,
  192. F9 = 298,
  193. F10 = 299,
  194. F11 = 300,
  195. F12 = 301,
  196. F13 = 302,
  197. F14 = 303,
  198. F15 = 304,
  199. F16 = 305,
  200. F17 = 306,
  201. F18 = 307,
  202. F19 = 308,
  203. F20 = 309,
  204. F21 = 310,
  205. F22 = 311,
  206. F23 = 312,
  207. F24 = 313,
  208. F25 = 314,
  209. NumBlock0 = 320,
  210. NumBlock1 = 321,
  211. NumBlock2 = 322,
  212. NumBlock3 = 323,
  213. NumBlock4 = 324,
  214. NumBlock5 = 325,
  215. NumBlock6 = 326,
  216. NumBlock7 = 327,
  217. NumBlock8 = 328,
  218. NumBlock9 = 329,
  219. KpDecimal = 330,
  220. KpDivide = 331,
  221. KpMultiply = 332,
  222. KpSubtract = 333,
  223. KpAdd = 334,
  224. KpEnter = 335,
  225. KpEqual = 336,
  226. LeftShift = 340,
  227. LeftControl = 341,
  228. LeftAlt = 342,
  229. LeftSuper = 343,
  230. RightShift = 344,
  231. RightControl = 345,
  232. RightAlt = 346,
  233. RightSuper = 347,
  234. Menu = 348
  235. }
  236. void construct(out Window window, string title, uint width, uint height) nothrow {
  237. glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  238. glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  239. glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
  240. glfwDefaultWindowHints();
  241. glfwWindowHint(GLFW_RED_BITS, 8);
  242. glfwWindowHint(GLFW_GREEN_BITS, 8);
  243. glfwWindowHint(GLFW_BLUE_BITS, 8);
  244. glfwWindowHint(GLFW_ALPHA_BITS, 0);
  245. glfwWindowHint(GLFW_DEPTH_BITS, 24);
  246. glfwWindowHint(GLFW_STENCIL_BITS, 8);
  247. window.glfwWindow = glfwCreateWindow(width, height, title.toStringz(), null, null);
  248. assert(window.glfwWindow !is null);
  249. // glfwSetWindowUserPointer(window.glfwWindow, cast(void*)&window);
  250. // glfwSetWindowPosCallback(window.glfwWindow, cast(GLFWwindowposfun)&_GLFWwindowposfun);
  251. // glfwSetWindowSizeCallback(window.glfwWindow, cast(GLFWwindowsizefun)&_GLFWwindowsizefun);
  252. // glfwSetWindowCloseCallback(window.glfwWindow, cast(GLFWwindowclosefun)&_GLFWwindowclosefun);
  253. // glfwSetWindowRefreshCallback(window.glfwWindow, cast(GLFWwindowrefreshfun)&_GLFWwindowrefreshfun);
  254. // glfwSetWindowIconifyCallback(window.glfwWindow, cast(GLFWwindowiconifyfun)&_GLFWwindowiconifyfun);
  255. // glfwSetMouseButtonCallback(window.glfwWindow, cast(GLFWmousebuttonfun)&_GLFWmousebuttonfun);
  256. // glfwSetCursorPosCallback(window.glfwWindow, cast(GLFWcursorposfun)&_GLFWcursorposfun);
  257. // //glfwSetCursorEnterCallback(window.glfwWindow, cast(GLFWcursorenterfunfun)&_GLFWcursorenterfunfun);
  258. // glfwSetScrollCallback(window.glfwWindow, cast(GLFWscrollfun)&_GLFWscrollfun);
  259. // glfwSetKeyCallback(window.glfwWindow, cast(GLFWkeyfun)&_GLFWkeyfun);
  260. // glfwSetCharCallback(window.glfwWindow, cast(GLFWcharfun)&_GLFWcharfun);
  261. glfwMakeContextCurrent(window.glfwWindow);
  262. }
  263. void destruct(ref Window window) nothrow @nogc {
  264. // glfwSetWindowPosCallback(window.glfwWindow, null);
  265. // glfwSetWindowSizeCallback(window.glfwWindow, null);
  266. // glfwSetWindowCloseCallback(window.glfwWindow, null);
  267. // glfwSetWindowRefreshCallback(window.glfwWindow, null);
  268. // glfwSetWindowIconifyCallback(window.glfwWindow, null);
  269. // glfwSetMouseButtonCallback(window.glfwWindow, null);
  270. // glfwSetCursorPosCallback(window.glfwWindow, null);
  271. // //glfwSetCursorEnterCallback(this._glfwWindow, null);
  272. // glfwSetScrollCallback(window.glfwWindow, null);
  273. // glfwSetKeyCallback(window.glfwWindow, null);
  274. // glfwSetCharCallback(window.glfwWindow, null);
  275. glfwDestroyWindow(window.glfwWindow);
  276. window = Window.init;
  277. }
  278. void makeAktiveRenderWindow(ref Window window) nothrow @nogc {
  279. glfwMakeContextCurrent(window.glfwWindow);
  280. }
  281. void swapBuffers(ref Window window) nothrow @nogc {
  282. glfwSwapBuffers(window.glfwWindow);
  283. }
  284. void pollEvents(ref Window window) nothrow @nogc {
  285. glfwPollEvents();
  286. }
  287. @property void setTitle(ref Window window, string title) nothrow {
  288. glfwSetWindowTitle(window.glfwWindow, title.toStringz());
  289. }
  290. uint x(ref Window window) pure @safe nothrow @nogc {
  291. return window._x;
  292. }
  293. uint y(ref Window window) pure @safe nothrow @nogc {
  294. return window._y;
  295. }
  296. uint width(ref Window window) pure @safe nothrow @nogc {
  297. return window._w;
  298. }
  299. uint height(ref Window window) pure @safe nothrow @nogc {
  300. return window._h;
  301. }
  302. KeyAction keyState(ref Window window, int key) pure @safe nothrow {
  303. try {
  304. return window._keyStates.get(key, KeyAction.Released);
  305. }
  306. catch(Exception) {
  307. return KeyAction.Released;
  308. }
  309. }
  310. ButtonAction buttonState(ref Window window, int button) pure @safe nothrow {
  311. try {
  312. return window._buttonStates.get(button, ButtonAction.Released);
  313. }
  314. catch(Exception) {
  315. return ButtonAction.Released;
  316. }
  317. }
  318. //======================================================================================================================
  319. //
  320. //======================================================================================================================
  321. struct Viewport {
  322. }
  323. void construct(out Viewport viewport) pure @safe nothrow @nogc {
  324. }
  325. void destruct(ref Viewport viewport) pure @safe nothrow @nogc {
  326. viewport = Viewport.init;
  327. }
  328. //======================================================================================================================
  329. //
  330. //======================================================================================================================
  331. struct Scene {
  332. SOAMesh mesh;
  333. }
  334. void construct(out Scene scene) pure @safe nothrow @nogc {
  335. }
  336. void destruct(ref Scene scene) pure @safe nothrow @nogc {
  337. scene = Scene.init;
  338. }
  339. //======================================================================================================================
  340. //
  341. //======================================================================================================================
  342. struct Camera {
  343. }
  344. void construct(out Camera camera) pure @safe nothrow @nogc {
  345. }
  346. void destruct(ref Camera camera) pure @safe nothrow @nogc {
  347. camera = Camera.init;
  348. }
  349. //======================================================================================================================
  350. //
  351. //======================================================================================================================
  352. struct DeferredRenderer {
  353. struct GBuffer {
  354. }
  355. GBuffer gBuffer;
  356. }
  357. void construct(out DeferredRenderer deferredRenderer) pure @safe nothrow @nogc {
  358. }
  359. void destruct(ref DeferredRenderer deferredRenderer) pure @safe nothrow @nogc {
  360. deferredRenderer = DeferredRenderer.init;
  361. }
  362. void renderOneFrame(ref DeferredRenderer deferredRenderer, ref Viewport viewport, ref Scene scene, ref Camera camera) nothrow {
  363. // 1. Render the (opaque) geometry into the G-Buffers.
  364. // 2. Construct a screen space grid, covering the frame buffer, with some fixed tile
  365. // size, t = (x, y), e.g. 32 × 32 pixels.
  366. // 3. For each light: find the screen space extents of the light volume and append the
  367. // light ID to each affected grid cell.
  368. // 4. For each fragment in the frame buffer, with location f = (x, y).
  369. // (a) sample the G-Buffers at f.
  370. // (b) accumulate light contributions from all lights in tile at ⌊f /t⌋
  371. // (c) output total light contributions to frame buffer at f
  372. scope(exit) glCheck!glBindVertexArray(0);
  373. scope(exit) glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // TODO: GL_ELEMENT_ARRAY_BUFFER should be vao state, but bugs might make this necessary
  374. for(size_t meshIdx = 0; meshIdx < scene.mesh.cnt; ++meshIdx) {
  375. glCheck!glBindVertexArray(scene.mesh.vao[meshIdx]);
  376. glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, scene.mesh.vboIndices[meshIdx]); // TODO: GL_ELEMENT_ARRAY_BUFFER should be vao state, but bugs might make this necessary
  377. glDrawElements(GL_TRIANGLES, scene.mesh.cntIndices[meshIdx], GL_UNSIGNED_SHORT, null);
  378. }
  379. }
  380. //======================================================================================================================
  381. //
  382. //======================================================================================================================
  383. struct SOAMesh {
  384. SoA!GLuint vao;
  385. SoA!GLuint vboVertices;
  386. SoA!GLuint vboNormals;
  387. SoA!GLuint vboTexcoords;
  388. SoA!GLuint vboIndices;
  389. SoA!GLuint cntIndices;
  390. size_t cnt;
  391. }
  392. //======================================================================================================================
  393. //
  394. //======================================================================================================================
  395. void main() {
  396. Window window;
  397. Viewport viewport;
  398. Scene scene;
  399. Camera camera;
  400. DeferredRenderer deferredRenderer;
  401. DerelictGL3.load();
  402. DerelictGLFW3.load();
  403. DerelictFI.load();
  404. // DerelictFT.load();
  405. DerelictASSIMP3.load();
  406. DerelictAntTweakBar.load();
  407. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  408. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  409. try {
  410. GLVersion glVersion = DerelictGL3.reload();
  411. import std.conv : to;
  412. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  413. } catch(Exception e) {
  414. writeln("Reloading OpenGl failed: " ~ e.msg);
  415. }
  416. // static FT_Library _s_freeTypeLibrary
  417. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  418. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  419. viewport.construct(); scope(exit) window.destruct();
  420. scene.construct(); scope(exit) window.destruct();
  421. camera.construct(); scope(exit) window.destruct();
  422. deferredRenderer.construct(); scope(exit) deferredRenderer.destruct();
  423. while(true) {
  424. window.pollEvents();
  425. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  426. glCheck!glClearDepth(1.0f);
  427. glCheck!glClearColor(0.5, 0, 0, 1);
  428. deferredRenderer.renderOneFrame(viewport, scene, camera);
  429. window.swapBuffers();
  430. }
  431. }
  432. //struct BoundingBox
  433. //{
  434. // vec4 min;
  435. // vec4 max;
  436. // vec4 material;
  437. //}
  438. //
  439. //struct Mesh {
  440. // vec3[] vertices;
  441. // vec3[] normals;
  442. // vec2[] texcoords;
  443. // ushort[] indices;
  444. // string texname;
  445. // vec3 color;
  446. //}
  447. //
  448. //struct GlMesh {
  449. // GLuint vertex_array;
  450. // GLuint vbo_indices;
  451. // GLuint num_indices;
  452. // GLuint vbo_vertices;
  453. // GLuint vbo_normals;
  454. // GLuint vbo_texcoords;
  455. // vec3 color;
  456. // string texname;
  457. // BoundingBox boundingBox;
  458. //}
  459. //
  460. //GlMesh uploadMesh(Mesh mesh) {
  461. // GlMesh glMesh;
  462. //
  463. // glGenVertexArrays(1, &(glMesh.vertex_array));
  464. // glBindVertexArray(glMesh.vertex_array);
  465. //
  466. // glGenBuffers(1, &(glMesh.vbo_vertices));
  467. // glGenBuffers(1, &(glMesh.vbo_normals));
  468. // glGenBuffers(1, &(glMesh.vbo_indices));
  469. // glGenBuffers(1, &(glMesh.vbo_texcoords));
  470. //}
  471. //
  472. /+++
  473. //======================================================================================================================
  474. // GBuffer
  475. //======================================================================================================================
  476. struct GBuffer {
  477. GLuint hDepth;
  478. GLuint hNormal;
  479. GLuint hColor;
  480. GLuint hFin;
  481. GLuint hStencil;
  482. };
  483. GBuffer createGBuffer() {
  484. GBuffer gBuffer;
  485. check!glGenTextures(1, &gBuffer.hDepth);
  486. check!glBindTexture(GL_TEXTURE_2D, gBuffer.hDepth);
  487. check!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  488. check!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  489. check!glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  490. check!glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  491. check!glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
  492. with(_window) check!glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH_COMPONENT32F, width, height);
  493. with(_window) check!glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_DEPTH_COMPONENT, GL_FLOAT, null);
  494. check!glBindTexture(GL_TEXTURE_2D, 0);
  495. check!glGenTextures(1, &gBuffer.hNormal);
  496. check!glBindTexture(GL_TEXTURE_2D, gBuffer.hNormal);
  497. check!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  498. check!glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  499. check!glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
  500. check!glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
  501. with(_window) check!glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB10_A2, width, height);
  502. with(_window) check!glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_FLOAT, null);
  503. check!glBindTexture(GL_TEXTURE_2D, 0);
  504. check!glGenTextures(1, &gBuffer.hColor);
  505. check!glBindTexture(GL_TEXTURE_2D, gBuffer.hColor);
  506. with(_window) check!glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGBA8, width, height);
  507. with(_window) check!glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_FLOAT, null);
  508. check!glBindTexture(GL_TEXTURE_2D, 0);
  509. check!glGenTextures(1, &gBuffer.hFin);
  510. check!glBindTexture(GL_TEXTURE_2D, gBuffer.hFin);
  511. with(_window) check!glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB32F, width, height);
  512. with(_window) check!glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGB, GL_FLOAT, null);
  513. check!glBindTexture(GL_TEXTURE_2D, 0);
  514. check!glGenTextures(1, &gBuffer.hStencil);
  515. check!glBindTexture(GL_TEXTURE_2D, gBuffer.hStencil);
  516. with(_window) check!glTexStorage2D(GL_TEXTURE_2D, 1, GL_DEPTH24_STENCIL8, width, height);
  517. with(_window) check!glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, null);
  518. check!glBindTexture(GL_TEXTURE_2D, 0);
  519. return gBuffer;
  520. }
  521. void destroyGBuffer(ref GBuffer gBuffer) {
  522. check!glDeleteTextures(1, &gBuffer.hStencil);
  523. check!glDeleteTextures(1, &gBuffer.hFin);
  524. check!glDeleteTextures(1, &gBuffer.hColor);
  525. check!glDeleteTextures(1, &gBuffer.hNormal);
  526. check!glDeleteTextures(1, &gBuffer.hDepth);
  527. }
  528. //======================================================================================================================
  529. // FrameBuffer
  530. //======================================================================================================================
  531. struct FrameBuffer {
  532. GLuint hFrameBuffer;
  533. };
  534. FrameBuffer createFrameBuffer() {
  535. FrameBuffer frameBuffer;
  536. check!glGenFramebuffers(1, &frameBuffer.hFrameBuffer);
  537. check!glBindFramebuffer(GL_DRAW_FRAMEBUFFER, frameBuffer.hFrameBuffer);
  538. check!glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, GL_TEXTURE_2D, gBuffer.hDepth, 0);
  539. check!glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 1, GL_TEXTURE_2D, gBuffer.hNormal, 0);
  540. check!glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 2, GL_TEXTURE_2D, gBuffer.hColor, 0);
  541. check!glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 3, GL_TEXTURE_2D, gBuffer.hFin, 0);
  542. check!glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_TEXTURE_2D, gBuffer.hStencil, 0);
  543. check!glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  544. return frameBuffer;
  545. }
  546. void destroyFrameBuffer(ref FrameBuffer frameBuffer) {
  547. check!glDeleteFramebuffers(1, &frameBuffer.hFrameBuffer);
  548. }
  549. //======================================================================================================================
  550. // ShaderPipeline
  551. //======================================================================================================================
  552. struct ShaderPipeline {
  553. GLuint hShaderPipeline;
  554. };
  555. ShaderPipeline createShaderPipeline() {
  556. ShaderPipeline shaderPipeline;
  557. glGenProgramPipelines(1, &shaderPipeline.hShaderPipeline);
  558. return shaderPipeline;
  559. }
  560. void destroyShaderPipeline(ref ShaderPipeline shaderPipeline) {
  561. glDeleteProgramPipelines(1, &shaderPipeline.hShaderPipeline);
  562. }
  563. //======================================================================================================================
  564. // ShaderProgram
  565. //======================================================================================================================
  566. struct ShaderProgram {
  567. GLuint hShaderProgram;
  568. };
  569. ShaderProgram createShaderProgram(string source) {
  570. ShaderProgram shaderProgram;
  571. auto szSource = [source.toStringz()];
  572. shaderProgram.hShaderProgram = check!glCreateShaderProgramv(GL_VERTEX_SHADER, 1, szSource.ptr);
  573. debug {
  574. int len;
  575. check!glGetProgramiv(this._id, GL_INFO_LOG_LENGTH , &len);
  576. if (len > 1) {
  577. char[] msg = new char[len];
  578. check!glGetProgramInfoLog(this._id, len, null, cast(char*) msg);
  579. error(cast(string)msg);
  580. }
  581. }
  582. return shaderProgram;
  583. }
  584. void destroyShaderProgram(ref ShaderProgram shaderProgram) {
  585. check!glDeleteProgram(shaderProgram.hShaderProgram);
  586. }
  587. //======================================================================================================================
  588. // VertexArrayObject
  589. //======================================================================================================================
  590. struct VertexArrayObject {
  591. GLuint hVertexArrayObject;
  592. }
  593. VertexArrayObject createVertexArrayObject() {
  594. VertexArrayObject vertexArrayObject;
  595. check!glGenVertexArrays(1, &vertexArrayObject.hVertexArrayObject);
  596. return vertexArrayObject;
  597. }
  598. void destroyVertexArrayObject(ref VertexArrayObject vertexArrayObject) {
  599. check!glDeleteVertexArrays(1, &vertexArrayObject.hVertexArrayObject);
  600. }
  601. //======================================================================================================================
  602. // VertexBufferObject
  603. //======================================================================================================================
  604. struct VertexBufferObject {
  605. GLuint hVertexBufferObject;
  606. }
  607. VertexBufferObject createVertexBufferObject() {
  608. VertexBufferObject vertexBufferObject;
  609. check!glGenBuffers(1, &vertexBufferObject.hVertexBufferObject);
  610. return vertexBufferObject;
  611. }
  612. void destroyVertexArrayObject(ref VertexBufferObject vertexBufferObject) {
  613. check!glDeleteVertexArrays(1, &vertexBufferObject.hVertexBufferObject);
  614. }
  615. //======================================================================================================================
  616. //
  617. //======================================================================================================================
  618. final class Camera {
  619. }
  620. final class Viewport {
  621. int x;
  622. int y;
  623. int width;
  624. int height;
  625. }
  626. final class Scene {
  627. VertexBufferObject[] vertexBufferObjects;
  628. VertexArrayObject[] vertexArrayObjects;
  629. }
  630. struct RenderGroup {
  631. Scene scene;
  632. Camera camera;
  633. Viewport viewport;
  634. }
  635. class OpenGlRenderer {
  636. private:
  637. Window _window;
  638. GBuffer _gBuffer;
  639. GBuffer _frameBuffer;
  640. ShaderProgram _geometryPassVertexShader;
  641. ShaderProgram _geometryPassFragmentShader;
  642. ShaderProgram _stencilPassVertexShader;
  643. ShaderProgram _stencilPassFragmentShader;
  644. ShaderProgram _pointLightPassVertexShader;
  645. ShaderProgram _pointLightPassFragmentShader;
  646. ShaderPipeline _shaderPipeline;
  647. Camera[] _cameras;
  648. Viewport[] _viewports;
  649. Scene[] _scenes;
  650. RenderGroup[] _renderGroups;
  651. public:
  652. this(Window window) {
  653. _window = window;
  654. _gBuffer = createGBuffer();
  655. _frameBuffer = createFrameBuffer();
  656. _geometryPassVertexShader = createShaderProgram("TODO: load and pass source code");
  657. _geometryPassFragmentShader = createShaderProgram("TODO: load and pass source code");
  658. _stencilPassVertexShader = createShaderProgram("TODO: load and pass source code");
  659. _stencilPassFragmentShader = createShaderProgram("TODO: load and pass source code");
  660. _pointLightPassVertexShader = createShaderProgram("TODO: load and pass source code");
  661. _pointLightPassFragmentShader = createShaderProgram("TODO: load and pass source code");
  662. _shaderPipeline = createShaderPipeline();
  663. }
  664. ~this() {
  665. destroyShaderPipeline(_shaderPipeline);
  666. destroyShaderProgram(_pointLightPassFragmentShader);
  667. destroyShaderProgram(_pointLightPassVertexShader);
  668. destroyShaderProgram(_stencilPassFragmentShader);
  669. destroyShaderProgram(_stencilPassVertexShader);
  670. destroyShaderProgram(_geometryPassFragmentShader);
  671. destroyShaderProgram(_geometryPassVertexShader);
  672. destroyFrameBuffer(_frameBuffer);
  673. destroyGBuffer(_gBuffer);
  674. }
  675. void run() {
  676. //--------------------------------------------------------------------------------------------------------------
  677. // Render Loop
  678. //--------------------------------------------------------------------------------------------------------------
  679. while(_keepRunning) {
  680. _window.makeAktiveRenderWindow();
  681. glClearColor(0, 0, 0, 1);
  682. glClearDepth(1.0);
  683. for(renderGroup; _renderGroups) {
  684. with(renderGroup.viewport) glViewport(x, y, width, height);
  685. geometryPass();
  686. lightningPass();
  687. finalPass();
  688. }
  689. }
  690. }
  691. void stop() {
  692. this._keepRunning = false;
  693. }
  694. private:
  695. //------------------------------------------------------------------------------------------------------------------
  696. // Geometry Pass
  697. //------------------------------------------------------------------------------------------------------------------
  698. void geometryPass() {
  699. //enable depth mask _before_ glClear ing the depth buffer!
  700. check!glDepthMask(GL_TRUE);
  701. check!glEnable(GL_DEPTH_TEST);
  702. check!glDepthFunc(GL_LEQUAL);
  703. check!glBindFramebuffer(GL_DRAW_FRAMEBUFFER, _frameBuffer.hframeBuffer);
  704. check!glDrawBuffer(GL_COLOR_ATTACHMENT3);
  705. GLenum[] drawBuffers = [GL_COLOR_ATTACHMENT0, GL_COLOR_ATTACHMENT1, GL_COLOR_ATTACHMENT2];
  706. check!glDrawBuffers(drawBuffers.length, drawBuffers.ptr);
  707. check!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
  708. glBindProgramPipeline(shaderPipeline.hShaderPipeline);
  709. foreach(vao; _scenes) {
  710. mesh._vertexData.bind();
  711. glUseProgramStages(_shaderPipeline.hShaderPipeline, GL_VERTEX_SHADER_BIT, _geometryPassVertexShader);
  712. glUseProgramStages(_shaderPipeline.hShaderPipeline, GL_FRAGMENT_SHADER_BIT, _geometryPassFragmentShader);
  713. setCullMode(CullMode.Back);
  714. mesh._vertexShader.sendUniform("u_vpMatrix", camera.viewProjectionMatrix);
  715. mesh._fragmentShader.sendTexture("u_textureImage", this._texture, 0);
  716. foreach(model; this._models) {
  717. mesh._vertexShader.sendUniform("u_modelMatrix", model.modelMatrix);
  718. check!glDrawArrays(GL_TRIANGLES, 0, 36);
  719. }
  720. mesh._vertexData.unbind();
  721. }
  722. glBindProgramPipeline(0);
  723. check!glDepthMask(GL_FALSE);
  724. }
  725. //------------------------------------------------------------------------------------------------------------------
  726. // Lightning Pass
  727. //------------------------------------------------------------------------------------------------------------------
  728. void lightningPass() {
  729. this.framebuffer.bind(FrameBuffer.Target.Write);
  730. check!glDrawBuffer(GL_COLOR_ATTACHMENT3);
  731. check!glEnable(GL_STENCIL_TEST);
  732. foreach(pointLight; scene.pointLights)
  733. {
  734. //------------------------------------------------------------------------------------------------------
  735. // Stencil Pass
  736. //------------------------------------------------------------------------------------------------------
  737. glBindProgramPipeline(shaderPipeline.hShaderPipeline);
  738. this.framebuffer.bind(FrameBuffer.Target.Write);
  739. check!glDrawBuffer(GL_NONE);
  740. check!glClear(GL_STENCIL_BUFFER_BIT);//TODO: reqired?
  741. this._vao.bind();
  742. check!glEnable(GL_DEPTH_TEST);
  743. check!glDisable(GL_CULL_FACE);
  744. check!glStencilFunc(GL_ALWAYS, 0, 0);
  745. check!glStencilOpSeparate(GL_BACK, GL_KEEP, GL_INCR, GL_KEEP);
  746. check!glStencilOpSeparate(GL_FRONT, GL_KEEP, GL_DECR, GL_KEEP);
  747. glUseProgramStages(shaderPipeline.hShaderPipeline, GL_VERTEX_SHADER_BIT, stencilPassVertexShader);
  748. glUseProgramStages(shaderPipeline.hShaderPipeline, GL_FRAGMENT_SHADER_BIT, stencilPassFragmentShader);
  749. this.vertexShader.sendUniform("u_mvpMatrix", camera.viewProjectionMatrix * pointLight.modelMatrix);
  750. check!glDrawArrays(GL_TRIANGLES, 0, 36);
  751. this._vao.unbind();
  752. glBindProgramPipeline(0);
  753. //------------------------------------------------------------------------------------------------------
  754. // PointLight Pass
  755. //------------------------------------------------------------------------------------------------------
  756. glBindProgramPipeline(shaderPipeline.hShaderPipeline);
  757. //~ camera.gbuffer.bind(GBuffer.Pass.Lighting);
  758. this.framebuffer.bind(FrameBuffer.Target.Write);
  759. check!glDrawBuffer(GL_COLOR_ATTACHMENT3);
  760. this._vao.bind();
  761. check!glDisable(GL_DEPTH_TEST);
  762. check!glEnable(GL_BLEND);
  763. check!glBlendFunc(GL_ONE, GL_ONE);
  764. check!glBlendEquation(GL_FUNC_ADD);
  765. check!glStencilFunc(GL_NOTEQUAL, 0, 0xFF);
  766. check!glEnable(GL_CULL_FACE);
  767. check!glCullFace(GL_FRONT);
  768. glUseProgramStages(shaderPipeline.hShaderPipeline, GL_VERTEX_SHADER_BIT, pointLightPassVertexShader);
  769. glUseProgramStages(shaderPipeline.hShaderPipeline, GL_FRAGMENT_SHADER_BIT, pointLightPassFragmentShader);
  770. this.vertexShader.sendUniform("u_mvpMatrix", camera.viewProjectionMatrix * pointLight.modelMatrix);
  771. this.fragmentShader.sendUniform("u_viewport", Vec4f(camera.viewport.x, camera.viewport.y, camera.viewport.width, camera.viewport.height));
  772. this.fragmentShader.sendUniform("u_viewProjMatrix", camera.viewProjectionMatrix);
  773. this.fragmentShader.sendUniform("u_projMatrix", camera.projectionMatrix);
  774. this.fragmentShader.sendUniform("u_viewMatrix", camera.viewMatrix);
  775. this.fragmentShader.sendTexture("u_gbuffer.depth", camera.gbuffer.depth, 0);
  776. this.fragmentShader.sendTexture("u_gbuffer.normal", camera.gbuffer.normal, 1);
  777. this.fragmentShader.sendTexture("u_gbuffer.color", camera.gbuffer.color, 2);
  778. this.fragmentShader.sendTexture("u_gbuffer.depthstencil", camera.gbuffer.depthstencil, 4);
  779. this.fragmentShader.sendUniform("u_light.color", pointLight.color);
  780. this.fragmentShader.sendUniform("u_light.ambientIntensity", pointLight.ambientIntensity);
  781. this.fragmentShader.sendUniform("u_light.diffuseIntensity", pointLight.diffuseIntensity);
  782. this.fragmentShader.sendUniform("u_light.constant", pointLight.constant);
  783. this.fragmentShader.sendUniform("u_light.linear", pointLight.linear);
  784. this.fragmentShader.sendUniform("u_light.exp", pointLight.exp);
  785. this.fragmentShader.sendUniform("u_light.position", pointLight.position);
  786. check!glDrawArrays(GL_TRIANGLES, 0, 36);
  787. this._vao.unbind();
  788. check!glDisable(GL_BLEND);
  789. glBindProgramPipeline(0);
  790. }
  791. check!glDisable(GL_STENCIL_TEST);
  792. }
  793. //------------------------------------------------------------------------------------------------------------------
  794. // Final Pass
  795. //------------------------------------------------------------------------------------------------------------------
  796. void finalPass() {
  797. check!glBindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
  798. check!glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
  799. check!glReadBuffer(GL_COLOR_ATTACHMENT3);
  800. with(camera.viewport) {
  801. check!glBlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_LINEAR);
  802. }
  803. _window.swapBuffers();
  804. }
  805. }
  806. struct Vertex {
  807. float x, y, z;
  808. }
  809. struct Normal {
  810. float x, y, z;
  811. }
  812. struct UV {
  813. float u, v;
  814. }
  815. final class Mesh {
  816. public:
  817. Vertex[] vertexData;
  818. Normal[] normalData;
  819. UV[] textureData;
  820. RGBAf[] colorData;
  821. VertexArrayObject vao;
  822. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  823. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  824. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  825. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  826. this(string filePath) {
  827. writeln("loading scene: ", filePath);
  828. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  829. writeln("meshes: ", scene.mNumMeshes);
  830. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  831. const(aiMesh*) mesh = scene.mMeshes[m];
  832. assert(mesh !is null);
  833. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  834. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  835. const(aiFace*) face = &mesh.mFaces[f];
  836. assert(face !is null);
  837. for(uint v = 0; v < 3; ++v) {
  838. aiVector3D p, n, uv;
  839. assert(face.mNumIndices > v);
  840. uint vertex = face.mIndices[v];
  841. assert(mesh.mNumVertices > vertex);
  842. p = mesh.mVertices[vertex];
  843. n = mesh.mNormals[vertex];
  844. // check if the mesh has texture coordinates
  845. if(mesh.mTextureCoords[0] !is null) {
  846. uv = mesh.mTextureCoords[0][vertex];
  847. }
  848. vertexData ~= Vertex(p.x, p.y, p.z);
  849. normalData ~= Normal(n.x, n.y, n.z);
  850. textureData ~= UV(uv.x, uv.y);
  851. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  852. }
  853. }
  854. }
  855. writeln("unloading scene: ", filePath);
  856. aiReleaseImport(scene);
  857. //-----------------------------
  858. // upload
  859. writeln("uploading mesh: ", filePath);
  860. vao = new VertexArrayObject();
  861. vao.bind();
  862. writeln("vertex data");
  863. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  864. vboVertexData.bind();
  865. GLuint attribIndex = 0;
  866. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  867. glEnableVertexAttribArray(attribIndex);
  868. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  869. vboVertexData.unbind();
  870. writeln("normal data");
  871. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  872. vboNormalData.bind();
  873. attribIndex = 1;
  874. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  875. glEnableVertexAttribArray(attribIndex);
  876. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  877. vboNormalData.unbind();
  878. writeln("uv data");
  879. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  880. vboTextureData.bind();
  881. attribIndex = 2;
  882. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  883. glEnableVertexAttribArray(attribIndex);
  884. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  885. vboTextureData.unbind();
  886. writeln("color data");
  887. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  888. vboColorData.bind();
  889. attribIndex = 3;
  890. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  891. glEnableVertexAttribArray(attribIndex);
  892. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  893. vboColorData.unbind();
  894. vao.unbind();
  895. writeln("done");
  896. }
  897. }
  898. void setupTweakbar() {
  899. writeln("creating TweakBar");
  900. double time = 0, dt; // Current time and enlapsed time
  901. double turn = 0; // Model turn counter
  902. double speed = 0.3; // Model rotation speed
  903. int wire = 0; // Draw model in wireframe?
  904. uint frameCount = 0;
  905. double fps = 0;
  906. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  907. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  908. auto quat = Quaternionf(0,0,0,1);
  909. // auto w = this._window.getBounds()[2];
  910. // auto h = this._window.getBounds()[3];
  911. TwWindowSize(1600, 900);
  912. // // Create a tweak bar
  913. // auto bar = TwNewBar("TweakBar");
  914. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  915. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  916. // TwAddVarRW(bar, "speed", TW_TYPE_DOUBLE, &speed, " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' ");
  917. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  918. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  919. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  920. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  921. // //
  922. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  923. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  924. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  925. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  926. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  927. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  928. // //
  929. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  930. }
  931. //-----------------
  932. // Create Shaders
  933. enum vertexShaderSource = "
  934. #version 420 core
  935. layout(location = 0) in vec3 in_position;
  936. layout(location = 1) in vec3 in_normal;
  937. layout(location = 2) in vec2 in_texcoord;
  938. layout(location = 3) in vec4 in_color;
  939. out vec4 v_color;
  940. out gl_PerVertex
  941. {
  942. vec4 gl_Position;
  943. };
  944. void main()
  945. {
  946. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  947. v_color = in_color;
  948. }
  949. ";
  950. enum fragmentShaderSource = "
  951. #version 420 core
  952. in vec4 v_color;
  953. out vec4 FragColor;
  954. void main()
  955. {
  956. FragColor = v_color;
  957. }
  958. ";
  959. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  960. assert(vertexShader.isLinked, vertexShader.infoLog());
  961. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  962. writeln("a: ");
  963. auto shaderPipeline = new ShaderPipeline();
  964. shaderPipeline.bind();
  965. shaderPipeline.use(vertexShader);
  966. shaderPipeline.use(fragmentShader);
  967. writeln("b: ");
  968. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  969. shaderPipeline.unbind();
  970. writeln("c: ");
  971. return shaderPipeline;
  972. }
  973. class Tester {
  974. Window _window;
  975. bool _keepRunning = true;
  976. this() {
  977. this._window = initThree();
  978. this._window.onKey.connect!"_onKey"(this);
  979. this._window.onClose.connect!"_onClose"(this);
  980. }
  981. ~this() {
  982. import core.memory;
  983. writeln("GC.collect: ");
  984. GC.collect();
  985. //Collect window _AFTER_ everything else
  986. this._window = null;
  987. GC.collect();
  988. deinitThree();
  989. }
  990. void run() {
  991. RGBAf rgg;
  992. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  993. setupTweakbar();
  994. writeln("creating shaders: ");
  995. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  996. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  997. writeln("creating shader pipeline: ");
  998. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  999. writeln("connectiong window callbacks: ");
  1000. this._window.onSize.connect!"onSize"(this);
  1001. this._window.onPosition.connect!"onPosition"(this);
  1002. this._window.onButton.connect!"onButton"(this);
  1003. this._window.onCursorPos.connect!"onCursorPos"(this);
  1004. writeln("begin render loop: ");
  1005. //-----------------
  1006. // Render Loop
  1007. glfwSetTime(0);
  1008. while(this._keepRunning) {
  1009. this._window.clear(0, 0, 0.5, 1);
  1010. shaderPipeline.bind();
  1011. mesh.vao.bind();
  1012. //vboVertexData.bind();
  1013. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  1014. //vbo.unbind();
  1015. mesh.vao.unbind();
  1016. shaderPipeline.unbind();
  1017. TwDraw();
  1018. this._window.swapBuffers();
  1019. updateWindows();
  1020. // ++frameCount;
  1021. // //if(frameCount % 100 == 0) {
  1022. // time = glfwGetTime();
  1023. // fps = cast(double)frameCount / time;
  1024. // //}
  1025. }
  1026. }
  1027. void onSize(Window window, int width, int height) {
  1028. TwWindowSize(width, height);
  1029. }
  1030. void onPosition(Window window, int x, int y) {
  1031. }
  1032. void onButton(Window window , int button, ButtonAction action) {
  1033. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  1034. TwMouseButtonID twbutton;
  1035. switch(button) {
  1036. default:
  1037. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  1038. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  1039. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  1040. }
  1041. TwMouseButton(twaction, twbutton);
  1042. }
  1043. void onCursorPos(Window window, double x, double y) {
  1044. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  1045. }
  1046. void stop() {
  1047. this._keepRunning = false;
  1048. }
  1049. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  1050. if(window is this._window && action == KeyAction.Pressed) {
  1051. if(key == Key.Escape) {
  1052. this.stop();
  1053. }
  1054. }
  1055. }
  1056. void _onClose(Window window) {
  1057. this.stop();
  1058. }
  1059. }
  1060. class InputHandler {
  1061. private:
  1062. Window _window;
  1063. OpenGlRenderer _renderer;
  1064. public:
  1065. this(Window window, OpenGlRenderer renderer) {
  1066. _window = window;
  1067. _renderer = renderer;
  1068. _window.onKey.connect!"_onKey"(this);
  1069. _window.onClose.connect!"_onClose"(this);
  1070. _window.onSize.connect!"_onSize"(this);
  1071. _window.onPosition.connect!"_onPosition"(this);
  1072. _window.onButton.connect!"_onButton"(this);
  1073. _window.onCursorPos.connect!"_onCursorPos"(this);
  1074. }
  1075. private:
  1076. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  1077. if(window is _window && action == KeyAction.Pressed) {
  1078. if(key == Key.Escape) {
  1079. _renderer.stop();
  1080. }
  1081. }
  1082. }
  1083. void _onClose(Window window) {
  1084. _renderer.stop();
  1085. }
  1086. void _onSize(Window window, int width, int height) {
  1087. }
  1088. void _onPosition(Window window, int x, int y) {
  1089. }
  1090. void _onButton(Window window , int button, ButtonAction action) {
  1091. }
  1092. void _onCursorPos(Window window, double x, double y) {
  1093. }
  1094. }
  1095. void main() {
  1096. auto window = initThree();
  1097. {
  1098. OpenGlRenderer renderer = new OpenGlRenderer(window);
  1099. InputHandler inputHandler = new InputHandler(window, renderer);
  1100. renderer.run();
  1101. }
  1102. import core.memory;
  1103. GC.collect();
  1104. //Collect window _AFTER_ everything else
  1105. this._window = null;
  1106. GC.collect();
  1107. deinitThree();
  1108. }
  1109. +++/