app.d 24 KB

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