app.d 25 KB

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