app.d 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974
  1. import std.stdio;
  2. import std.typecons;
  3. import three;
  4. import std.experimental.logger;
  5. public import derelict.opengl3.gl3;
  6. public import derelict.glfw3.glfw3;
  7. public import derelict.anttweakbar.anttweakbar;
  8. public import derelict.freeimage.freeimage;
  9. public import derelict.freetype.ft;
  10. public import derelict.assimp3.assimp;
  11. public import std.experimental.logger;
  12. import three.gl.renderer;
  13. import three.window;
  14. import three.camera;
  15. import three.scene;
  16. void main() {
  17. Window window;
  18. Viewport viewport;
  19. Scene scene;
  20. Camera camera;
  21. GlRenderTarget renderTarget;
  22. // OpenGlTiledDeferredRenderer renderer;
  23. Renderer renderer;
  24. bool keepRunning = true;
  25. //------------------------------------------------
  26. // Load and Construct Rendering Pipeline
  27. //------------------------------------------------
  28. DerelictGL3.load();
  29. DerelictGLFW3.load();
  30. DerelictFI.load();
  31. // DerelictFT.load();
  32. DerelictASSIMP3.load();
  33. DerelictAntTweakBar.load();
  34. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  35. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  36. try {
  37. GLVersion glVersion = DerelictGL3.reload();
  38. import std.conv : to;
  39. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  40. } catch(Exception e) {
  41. writeln("Reloading OpenGl failed: " ~ e.msg);
  42. }
  43. // static FT_Library _s_freeTypeLibrary
  44. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  45. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  46. viewport.construct(); scope(exit) viewport.destruct();
  47. scene.construct(); scope(exit) scene.destruct();
  48. camera.construct(); scope(exit) camera.destruct();
  49. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  50. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  51. //------------------------------------------------
  52. // Create Scene
  53. //------------------------------------------------
  54. scene.loadModel("C:/Coding/models/Collada/duck.dae");
  55. log("vertexCount: ", scene.vertexCount, " (", scene.vertexCount * VertexData.sizeof / 1024," KiB)");
  56. log("indexCount: ", scene.indexCount, " (", scene.indexCount * IndexData.sizeof / 1024," KiB)");
  57. log("meshCount: ", scene.meshCount);
  58. log("modelCount: ", scene.modelCount);
  59. //------------------------------------------------
  60. // Generate TweakBar
  61. //------------------------------------------------
  62. TwWindowSize(window.width, window.height);
  63. auto tweakBar = TwNewBar("TweakBar");
  64. //------------------------------------------------
  65. // Connect Window callbacks
  66. //------------------------------------------------
  67. window.onKey = (ref Window rWindow, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  68. if(window is window && action == KeyAction.Pressed) {
  69. if(key == Key.Escape) {
  70. keepRunning = false;
  71. }
  72. }
  73. };
  74. window.onClose = (ref Window rWindow) {
  75. keepRunning = false;
  76. };
  77. window.onSize = (ref Window rWindow, int width, int height) {
  78. TwWindowSize(width, height);
  79. };
  80. window.onPosition = (ref Window rWindow, int x, int y) {
  81. };
  82. window.onButton = (ref Window rWindow , int button, ButtonAction action) {
  83. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  84. TwMouseButtonID twbutton;
  85. switch(button) {
  86. default:
  87. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  88. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  89. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  90. }
  91. TwMouseButton(twaction, twbutton);
  92. };
  93. window.onCursorPos = (ref Window rWindow, double x, double y) {
  94. TwMouseMotion(cast(int)x, window.height - cast(int)y);
  95. };
  96. //------------------------------------------------
  97. // Main Loop
  98. //------------------------------------------------
  99. ulong frameCount = 0;
  100. glfwSetTime(0);
  101. while(keepRunning) {
  102. window.pollEvents();
  103. window.makeAktiveRenderWindow();
  104. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  105. debug{ renderer.blitGBufferToScreen(); }
  106. // TwDraw();
  107. window.swapBuffers();
  108. ++frameCount;
  109. if(frameCount % 10 == 0) {
  110. auto fps = cast(double)frameCount / glfwGetTime();
  111. log("FPS: ", fps);
  112. frameCount = 0;
  113. glfwSetTime(0);
  114. }
  115. }
  116. }
  117. /+++++++
  118. //======================================================================================================================
  119. //
  120. //======================================================================================================================
  121. struct Slice(T) {
  122. T* data;
  123. size_t length;
  124. }
  125. //======================================================================================================================
  126. //
  127. //======================================================================================================================
  128. struct PersistentlyMappedBuffer(T) {
  129. GLuint bo;
  130. GLenum target;
  131. Slice!T data;
  132. alias Atom = T;
  133. }
  134. void create(T)(out PersistentlyMappedBuffer!T pmb, GLuint count, GLenum target, GLbitfield createFlags, GLbitfield mapFlags) {
  135. pmb.target = target;
  136. glCheck!glGenBuffers(1, &pmb.bo);
  137. glCheck!glBindBuffer(target, pmb.bo);
  138. glCheck!glBufferStorage(target, T.sizeof * count, null, createFlags);
  139. pmb.data.data = cast(T*)glMapBufferRange(target, 0, T.sizeof * count, mapFlags);
  140. pmb.data.length = count;
  141. if (!pmb.data.data) {
  142. throw new Exception("glMapBufferRange failed, probable bug.");
  143. }
  144. }
  145. void destroy(T)(ref PersistentlyMappedBuffer!T pmb) {
  146. glCheck!glBindBuffer(pmb.target, mName);
  147. glCheck!glUnmapBuffer(pmb.target);
  148. glCheck!glDeleteBuffers(1, &mName);
  149. pmb = GlPersistentlyMappedBuffer!T.init;
  150. }
  151. //
  152. ////======================================================================================================================
  153. ////
  154. ////======================================================================================================================
  155. //struct GlCircularBufferView(T) {
  156. // GlPersistentlyMappedBuffer!T _buffer;
  157. // GLsizeiptr _head;
  158. //}
  159. //======================================================================================================================
  160. //
  161. //======================================================================================================================
  162. struct DrawArraysIndirectCommand {
  163. GLuint vertexCount;
  164. GLuint instanceCount;
  165. GLuint firstVertex;
  166. GLuint baseInstance;
  167. }
  168. struct DrawElementsIndirectCommand {
  169. GLuint count;
  170. GLuint instanceCount;
  171. GLuint firstIndex;
  172. GLuint baseVertex;
  173. GLuint baseInstance;
  174. }
  175. struct PerInstanceRenderData {
  176. }
  177. struct MeshDataRef {
  178. }
  179. struct PerInstanceDataRef {
  180. }
  181. struct Mesh {
  182. size_t meshDataRef;
  183. InstanceData[] instanceData;
  184. }
  185. struct MeshInstance {
  186. size_t meshRef;
  187. size_t meshInstanceRef;
  188. }
  189. struct Renderer {
  190. MeshData[] meshData;
  191. Mesh[] meshes;
  192. MeshInstance[] meshInstances;
  193. PersistentlyMappedBuffer!DrawElementsIndirectCommand commandBuffer;
  194. PersistentlyMappedBuffer!TransformationMatrix perInstanceBuffer;
  195. void renderOneFrame(Instances instances) {
  196. auto instanceCount = 0;
  197. // write draw commands
  198. DrawElementsIndirectCommand* cmds = commandBuffer.reserve(instanceCount);
  199. foreach(size_t i = 0; i < instanceCount; ++i) {
  200. DrawElementsIndirectCommand* cmd = &cmds[u];
  201. cmd->count = mIndexCount;
  202. cmd->instanceCount = 1;
  203. cmd->firstIndex = 0;
  204. cmd->baseVertex = 0;
  205. cmd->baseInstance = mUseShaderDrawParameters ? 0 : u;
  206. }
  207. // write per instance
  208. perInstanceBuffer.reserve(instances.length);
  209. foreach() {
  210. }
  211. glCheck!glMultiDrawElementsIndirect(GL_TRIANGLES, GL_UNSIGNED_SHORT, mCommands.GetHeadOffset(), xformCount, 0);
  212. }
  213. }
  214. /++++
  215. struct GlPeristentBuffer {
  216. }
  217. struct GlRingBuffer {
  218. GLuint bo;
  219. }
  220. struct ParamPerInstanceRingBuffer {
  221. GLuint bo;
  222. }
  223. struct Renderer {
  224. CommandRingBuffer commandRb;
  225. ParamPerInstanceRingBuffer paramPerInstanceRb;
  226. }
  227. struct MeshStorageManager(MeshLayout = DefaultVertexLayout) {
  228. struct Slice {
  229. size_t offset;
  230. size_t length;
  231. }
  232. struct MeshStorage {
  233. Slice vertexSlice;
  234. Slice indexSlice;
  235. }
  236. GLuint vao;
  237. GLuint vbo;
  238. GLuint ibo;
  239. MeshStorage[] meshes;
  240. }
  241. struct MeshInstance {
  242. }
  243. struct MappedPersistentBuffer {
  244. GLuint vbo;
  245. void* data;
  246. }
  247. void create(out MappedPersistentBuffer mpb, GLsizeiptr bufferSize) {
  248. glCheck!glGenVertexArrays(1, &mpb.vbo);
  249. GLbitfield mapFlags = GL_MAP_WRITE_BIT | GL_MAP_PERSISTENT_BIT | GL_MAP_COHERENT_BIT;
  250. GLbitfield createFlags = mapFlags | GL_MAP_DYNAMIC_STORAGE_BIT;
  251. glCheck!glBindBuffer(GL_ARRAY_BUFFER, mpb.vbo);
  252. glCheck!glBufferStorage(GL_ARRAY_BUFFER, bufferSize, null, createFlags);
  253. mpb.data = glCheck!glMapBufferRange(GL_ARRAY_BUFFER, 0, bufferSize, mapFlags);
  254. }
  255. ++++/
  256. //======================================================================================================================
  257. //
  258. //======================================================================================================================
  259. struct SOAVector3 {
  260. SoA!float x;
  261. SoA!float y;
  262. SoA!float z;
  263. }
  264. struct SOAQuaternion {
  265. SoA!float x;
  266. SoA!float y;
  267. SoA!float z;
  268. SoA!float w;
  269. }
  270. //======================================================================================================================
  271. //
  272. //======================================================================================================================
  273. void main() {
  274. Window window;
  275. Viewport viewport;
  276. Scene scene;
  277. Camera camera;
  278. RenderTarget renderTarget;
  279. OpenGlTiledDeferredRenderer renderer;
  280. bool keepRunning = true;
  281. //------------------------------------------------
  282. // Load and Construct Rendering Pipeline
  283. //------------------------------------------------
  284. DerelictGL3.load();
  285. DerelictGLFW3.load();
  286. DerelictFI.load();
  287. // DerelictFT.load();
  288. DerelictASSIMP3.load();
  289. DerelictAntTweakBar.load();
  290. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  291. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  292. try {
  293. GLVersion glVersion = DerelictGL3.reload();
  294. import std.conv : to;
  295. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  296. } catch(Exception e) {
  297. writeln("Reloading OpenGl failed: " ~ e.msg);
  298. }
  299. // static FT_Library _s_freeTypeLibrary
  300. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  301. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  302. viewport.construct(); scope(exit) window.destruct();
  303. scene.construct(); scope(exit) window.destruct();
  304. camera.construct(); scope(exit) window.destruct();
  305. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  306. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  307. //############################
  308. //############################
  309. //############################
  310. //############################
  311. GlPersistentlyMappedBuffer!DefaultVertexData vertexBuffer;
  312. vertexBuffer.create(1024, GL_ARRAY_BUFFER, 0, 0);
  313. //############################
  314. //############################
  315. //############################
  316. //############################
  317. //------------------------------------------------
  318. // Create Scene
  319. //------------------------------------------------
  320. scene.mesh.loadModel("C:/Coding/models/Collada/duck.dae");
  321. //------------------------------------------------
  322. // Generate TweakBar
  323. //------------------------------------------------
  324. TwWindowSize(window.width, window.height);
  325. auto tweakBar = TwNewBar("TweakBar");
  326. //------------------------------------------------
  327. // Connect Window callbacks
  328. //------------------------------------------------
  329. window.onKey = (ref Window rWindow, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  330. if(window is window && action == KeyAction.Pressed) {
  331. if(key == Key.Escape) {
  332. keepRunning = false;
  333. }
  334. }
  335. };
  336. window.onClose = (ref Window rWindow) {
  337. keepRunning = false;
  338. };
  339. window.onSize = (ref Window rWindow, int width, int height) {
  340. TwWindowSize(width, height);
  341. };
  342. window.onPosition = (ref Window rWindow, int x, int y) {
  343. };
  344. window.onButton = (ref Window rWindow , int button, ButtonAction action) {
  345. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  346. TwMouseButtonID twbutton;
  347. switch(button) {
  348. default:
  349. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  350. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  351. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  352. }
  353. TwMouseButton(twaction, twbutton);
  354. };
  355. window.onCursorPos = (ref Window rWindow, double x, double y) {
  356. TwMouseMotion(cast(int)x, window.height - cast(int)y);
  357. };
  358. //------------------------------------------------
  359. // Main Loop
  360. //------------------------------------------------
  361. ulong frameCount = 0;
  362. glfwSetTime(0);
  363. while(keepRunning) {
  364. window.pollEvents();
  365. window.makeAktiveRenderWindow();
  366. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  367. glCheck!glClearDepth(1.0f);
  368. glCheck!glClearColor(0, 0.3, 0, 1);
  369. /*
  370. foreach(renderTarget) //framebuffer
  371. foreach(pass)
  372. foreach(material) //shaders
  373. foreach(materialInstance) //textures
  374. foreach(vertexFormat) //vertex buffers
  375. foreach(object) {
  376. write uniform data;
  377. glDrawElementsBaseVertex
  378. }
  379. */
  380. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  381. TwDraw();
  382. debug{ renderer.blitGBufferToScreen(); }
  383. window.swapBuffers();
  384. ++frameCount;
  385. if(frameCount % 1000 == 0) {
  386. auto fps = cast(double)frameCount / glfwGetTime();
  387. log("FPS: ", fps);
  388. frameCount = 0;
  389. glfwSetTime(0);
  390. }
  391. }
  392. }
  393. /+++
  394. struct Vertex {
  395. float x, y, z;
  396. }
  397. struct Normal {
  398. float x, y, z;
  399. }
  400. struct UV {
  401. float u, v;
  402. }
  403. final class Mesh {
  404. public:
  405. Vertex[] vertexData;
  406. Normal[] normalData;
  407. UV[] textureData;
  408. RGBAf[] colorData;
  409. VertexArrayObject vao;
  410. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  411. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  412. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  413. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  414. this(string filePath) {
  415. writeln("loading scene: ", filePath);
  416. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  417. writeln("meshes: ", scene.mNumMeshes);
  418. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  419. const(aiMesh*) mesh = scene.mMeshes[m];
  420. assert(mesh !is null);
  421. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  422. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  423. const(aiFace*) face = &mesh.mFaces[f];
  424. assert(face !is null);
  425. for(uint v = 0; v < 3; ++v) {
  426. aiVector3D p, n, uv;
  427. assert(face.mNumIndices > v);
  428. uint vertex = face.mIndices[v];
  429. assert(mesh.mNumVertices > vertex);
  430. p = mesh.mVertices[vertex];
  431. n = mesh.mNormals[vertex];
  432. // check if the mesh has texture coordinates
  433. if(mesh.mTextureCoords[0] !is null) {
  434. uv = mesh.mTextureCoords[0][vertex];
  435. }
  436. vertexData ~= Vertex(p.x, p.y, p.z);
  437. normalData ~= Normal(n.x, n.y, n.z);
  438. textureData ~= UV(uv.x, uv.y);
  439. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  440. }
  441. }
  442. }
  443. writeln("unloading scene: ", filePath);
  444. aiReleaseImport(scene);
  445. //-----------------------------
  446. // upload
  447. writeln("uploading mesh: ", filePath);
  448. vao = new VertexArrayObject();
  449. vao.bind();
  450. writeln("vertex data");
  451. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  452. vboVertexData.bind();
  453. GLuint attribIndex = 0;
  454. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  455. glEnableVertexAttribArray(attribIndex);
  456. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  457. vboVertexData.unbind();
  458. writeln("normal data");
  459. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  460. vboNormalData.bind();
  461. attribIndex = 1;
  462. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  463. glEnableVertexAttribArray(attribIndex);
  464. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  465. vboNormalData.unbind();
  466. writeln("uv data");
  467. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  468. vboTextureData.bind();
  469. attribIndex = 2;
  470. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  471. glEnableVertexAttribArray(attribIndex);
  472. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  473. vboTextureData.unbind();
  474. writeln("color data");
  475. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  476. vboColorData.bind();
  477. attribIndex = 3;
  478. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  479. glEnableVertexAttribArray(attribIndex);
  480. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  481. vboColorData.unbind();
  482. vao.unbind();
  483. writeln("done");
  484. }
  485. }
  486. void setupTweakbar() {
  487. writeln("creating TweakBar");
  488. double time = 0, dt; // Current time and enlapsed time
  489. double turn = 0; // Model turn counter
  490. double speed = 0.3; // Model rotation speed
  491. int wire = 0; // Draw model in wireframe?
  492. uint frameCount = 0;
  493. double fps = 0;
  494. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  495. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  496. auto quat = Quaternionf(0,0,0,1);
  497. // auto w = this._window.getBounds()[2];
  498. // auto h = this._window.getBounds()[3];
  499. TwWindowSize(1600, 900);
  500. // // Create a tweak bar
  501. // auto bar = TwNewBar("TweakBar");
  502. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  503. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  504. // 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)' ");
  505. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  506. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  507. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  508. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  509. // //
  510. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  511. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  512. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  513. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  514. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  515. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  516. // //
  517. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  518. }
  519. //-----------------
  520. // Create Shaders
  521. enum vertexShaderSource = "
  522. #version 420 core
  523. layout(location = 0) in vec3 in_position;
  524. layout(location = 1) in vec3 in_normal;
  525. layout(location = 2) in vec2 in_texcoord;
  526. layout(location = 3) in vec4 in_color;
  527. out vec4 v_color;
  528. out gl_PerVertex
  529. {
  530. vec4 gl_Position;
  531. };
  532. void main()
  533. {
  534. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  535. v_color = in_color;
  536. }
  537. ";
  538. enum fragmentShaderSource = "
  539. #version 420 core
  540. in vec4 v_color;
  541. out vec4 FragColor;
  542. void main()
  543. {
  544. FragColor = v_color;
  545. }
  546. ";
  547. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  548. assert(vertexShader.isLinked, vertexShader.infoLog());
  549. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  550. writeln("a: ");
  551. auto shaderPipeline = new ShaderPipeline();
  552. shaderPipeline.bind();
  553. shaderPipeline.use(vertexShader);
  554. shaderPipeline.use(fragmentShader);
  555. writeln("b: ");
  556. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  557. shaderPipeline.unbind();
  558. writeln("c: ");
  559. return shaderPipeline;
  560. }
  561. class Tester {
  562. Window _window;
  563. bool _keepRunning = true;
  564. this() {
  565. this._window = initThree();
  566. this._window.onKey.connect!"_onKey"(this);
  567. this._window.onClose.connect!"_onClose"(this);
  568. }
  569. ~this() {
  570. import core.memory;
  571. writeln("GC.collect: ");
  572. GC.collect();
  573. //Collect window _AFTER_ everything else
  574. this._window = null;
  575. GC.collect();
  576. deinitThree();
  577. }
  578. void run() {
  579. RGBAf rgg;
  580. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  581. setupTweakbar();
  582. writeln("creating shaders: ");
  583. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  584. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  585. writeln("creating shader pipeline: ");
  586. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  587. writeln("connectiong window callbacks: ");
  588. this._window.onSize.connect!"onSize"(this);
  589. this._window.onPosition.connect!"onPosition"(this);
  590. this._window.onButton.connect!"onButton"(this);
  591. this._window.onCursorPos.connect!"onCursorPos"(this);
  592. writeln("begin render loop: ");
  593. //-----------------
  594. // Render Loop
  595. glfwSetTime(0);
  596. while(this._keepRunning) {
  597. this._window.clear(0, 0, 0.5, 1);
  598. shaderPipeline.bind();
  599. mesh.vao.bind();
  600. //vboVertexData.bind();
  601. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  602. //vbo.unbind();
  603. mesh.vao.unbind();
  604. shaderPipeline.unbind();
  605. TwDraw();
  606. this._window.swapBuffers();
  607. updateWindows();
  608. // ++frameCount;
  609. // //if(frameCount % 100 == 0) {
  610. // time = glfwGetTime();
  611. // fps = cast(double)frameCount / time;
  612. // //}
  613. }
  614. }
  615. void onSize(Window window, int width, int height) {
  616. TwWindowSize(width, height);
  617. }
  618. void onPosition(Window window, int x, int y) {
  619. }
  620. void onButton(Window window , int button, ButtonAction action) {
  621. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  622. TwMouseButtonID twbutton;
  623. switch(button) {
  624. default:
  625. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  626. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  627. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  628. }
  629. TwMouseButton(twaction, twbutton);
  630. }
  631. void onCursorPos(Window window, double x, double y) {
  632. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  633. }
  634. void stop() {
  635. this._keepRunning = false;
  636. }
  637. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  638. if(window is this._window && action == KeyAction.Pressed) {
  639. if(key == Key.Escape) {
  640. this.stop();
  641. }
  642. }
  643. }
  644. void _onClose(Window window) {
  645. this.stop();
  646. }
  647. }
  648. class InputHandler {
  649. private:
  650. Window _window;
  651. OpenGlRenderer _renderer;
  652. public:
  653. this(Window window, OpenGlRenderer renderer) {
  654. _window = window;
  655. _renderer = renderer;
  656. _window.onKey.connect!"_onKey"(this);
  657. _window.onClose.connect!"_onClose"(this);
  658. _window.onSize.connect!"_onSize"(this);
  659. _window.onPosition.connect!"_onPosition"(this);
  660. _window.onButton.connect!"_onButton"(this);
  661. _window.onCursorPos.connect!"_onCursorPos"(this);
  662. }
  663. private:
  664. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  665. if(window is _window && action == KeyAction.Pressed) {
  666. if(key == Key.Escape) {
  667. _renderer.stop();
  668. }
  669. }
  670. }
  671. void _onClose(Window window) {
  672. _renderer.stop();
  673. }
  674. void _onSize(Window window, int width, int height) {
  675. }
  676. void _onPosition(Window window, int x, int y) {
  677. }
  678. void _onButton(Window window , int button, ButtonAction action) {
  679. }
  680. void _onCursorPos(Window window, double x, double y) {
  681. }
  682. }
  683. void main() {
  684. auto window = initThree();
  685. {
  686. OpenGlRenderer renderer = new OpenGlRenderer(window);
  687. InputHandler inputHandler = new InputHandler(window, renderer);
  688. renderer.run();
  689. }
  690. import core.memory;
  691. GC.collect();
  692. //Collect window _AFTER_ everything else
  693. this._window = null;
  694. GC.collect();
  695. deinitThree();
  696. }
  697. +++/
  698. +++++++/