1
1

app.d 25 KB

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