app.d 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. import std.stdio;
  2. import std.typecons;
  3. import three;
  4. import std.experimental.logger;
  5. //======================================================================================================================
  6. //
  7. //======================================================================================================================
  8. struct SOAVector3 {
  9. SoA!float x;
  10. SoA!float y;
  11. SoA!float z;
  12. }
  13. struct SOAQuaternion {
  14. SoA!float x;
  15. SoA!float y;
  16. SoA!float z;
  17. SoA!float w;
  18. }
  19. //======================================================================================================================
  20. //
  21. //======================================================================================================================
  22. void main() {
  23. Window window;
  24. Viewport viewport;
  25. Scene scene;
  26. Camera camera;
  27. RenderTarget renderTarget;
  28. OpenGlTiledDeferredRenderer renderer;
  29. bool keepRunning = true;
  30. //------------------------------------------------
  31. // Load and Construct Rendering Pipeline
  32. //------------------------------------------------
  33. DerelictGL3.load();
  34. DerelictGLFW3.load();
  35. DerelictFI.load();
  36. // DerelictFT.load();
  37. DerelictASSIMP3.load();
  38. DerelictAntTweakBar.load();
  39. if(!glfwInit()) throw new Exception("Initialising GLFW failed"); scope(exit) glfwTerminate();
  40. window.construct("Three.d", 1600, 900); scope(exit) window.destruct();
  41. try {
  42. GLVersion glVersion = DerelictGL3.reload();
  43. import std.conv : to;
  44. writeln("Reloaded OpenGL Version: ", to!string(glVersion));
  45. } catch(Exception e) {
  46. writeln("Reloading OpenGl failed: " ~ e.msg);
  47. }
  48. // static FT_Library _s_freeTypeLibrary
  49. // if(!FT_Init_FreeType(&_s_freeTypeLibrary)) throw new Exception("Initialising FreeType failed"); scope(exit) FT_Done_FreeType(_s_freeTypeLibrary);
  50. if(TwInit(TW_OPENGL_CORE, null) == 0) throw new Exception("Initialising AntTweakBar failed"); scope(exit) TwTerminate();
  51. viewport.construct(); scope(exit) window.destruct();
  52. scene.construct(); scope(exit) window.destruct();
  53. camera.construct(); scope(exit) window.destruct();
  54. renderTarget.construct(window.width, window.height); scope(exit) renderTarget.destruct();
  55. renderer.construct(window.width, window.height); scope(exit) renderer.destruct();
  56. //------------------------------------------------
  57. // Create Scene
  58. //------------------------------------------------
  59. scene.mesh.loadModel("C:/Coding/models/Collada/duck.dae");
  60. //------------------------------------------------
  61. // Generate TweakBar
  62. //------------------------------------------------
  63. TwWindowSize(window.width, window.height);
  64. auto tweakBar = TwNewBar("TweakBar");
  65. //------------------------------------------------
  66. // Connect Window callbacks
  67. //------------------------------------------------
  68. window.onKey = (ref Window rWindow, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  69. if(window is window && action == KeyAction.Pressed) {
  70. if(key == Key.Escape) {
  71. keepRunning = false;
  72. }
  73. }
  74. };
  75. window.onClose = (ref Window rWindow) {
  76. keepRunning = false;
  77. };
  78. window.onSize = (ref Window rWindow, int width, int height) {
  79. TwWindowSize(width, height);
  80. };
  81. window.onPosition = (ref Window rWindow, int x, int y) {
  82. };
  83. window.onButton = (ref Window rWindow , int button, ButtonAction action) {
  84. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  85. TwMouseButtonID twbutton;
  86. switch(button) {
  87. default:
  88. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  89. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  90. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  91. }
  92. TwMouseButton(twaction, twbutton);
  93. };
  94. window.onCursorPos = (ref Window rWindow, double x, double y) {
  95. TwMouseMotion(cast(int)x, window.height - cast(int)y);
  96. };
  97. //------------------------------------------------
  98. // Main Loop
  99. //------------------------------------------------
  100. while(keepRunning) {
  101. window.pollEvents();
  102. window.makeAktiveRenderWindow();
  103. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  104. glCheck!glClearDepth(1.0f);
  105. glCheck!glClearColor(0.5, 0, 0, 1);
  106. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  107. TwDraw();
  108. window.swapBuffers();
  109. }
  110. }
  111. /+++
  112. struct Vertex {
  113. float x, y, z;
  114. }
  115. struct Normal {
  116. float x, y, z;
  117. }
  118. struct UV {
  119. float u, v;
  120. }
  121. final class Mesh {
  122. public:
  123. Vertex[] vertexData;
  124. Normal[] normalData;
  125. UV[] textureData;
  126. RGBAf[] colorData;
  127. VertexArrayObject vao;
  128. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  129. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  130. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  131. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  132. this(string filePath) {
  133. writeln("loading scene: ", filePath);
  134. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  135. writeln("meshes: ", scene.mNumMeshes);
  136. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  137. const(aiMesh*) mesh = scene.mMeshes[m];
  138. assert(mesh !is null);
  139. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  140. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  141. const(aiFace*) face = &mesh.mFaces[f];
  142. assert(face !is null);
  143. for(uint v = 0; v < 3; ++v) {
  144. aiVector3D p, n, uv;
  145. assert(face.mNumIndices > v);
  146. uint vertex = face.mIndices[v];
  147. assert(mesh.mNumVertices > vertex);
  148. p = mesh.mVertices[vertex];
  149. n = mesh.mNormals[vertex];
  150. // check if the mesh has texture coordinates
  151. if(mesh.mTextureCoords[0] !is null) {
  152. uv = mesh.mTextureCoords[0][vertex];
  153. }
  154. vertexData ~= Vertex(p.x, p.y, p.z);
  155. normalData ~= Normal(n.x, n.y, n.z);
  156. textureData ~= UV(uv.x, uv.y);
  157. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  158. }
  159. }
  160. }
  161. writeln("unloading scene: ", filePath);
  162. aiReleaseImport(scene);
  163. //-----------------------------
  164. // upload
  165. writeln("uploading mesh: ", filePath);
  166. vao = new VertexArrayObject();
  167. vao.bind();
  168. writeln("vertex data");
  169. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  170. vboVertexData.bind();
  171. GLuint attribIndex = 0;
  172. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  173. glEnableVertexAttribArray(attribIndex);
  174. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  175. vboVertexData.unbind();
  176. writeln("normal data");
  177. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  178. vboNormalData.bind();
  179. attribIndex = 1;
  180. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  181. glEnableVertexAttribArray(attribIndex);
  182. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  183. vboNormalData.unbind();
  184. writeln("uv data");
  185. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  186. vboTextureData.bind();
  187. attribIndex = 2;
  188. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  189. glEnableVertexAttribArray(attribIndex);
  190. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  191. vboTextureData.unbind();
  192. writeln("color data");
  193. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  194. vboColorData.bind();
  195. attribIndex = 3;
  196. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  197. glEnableVertexAttribArray(attribIndex);
  198. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  199. vboColorData.unbind();
  200. vao.unbind();
  201. writeln("done");
  202. }
  203. }
  204. void setupTweakbar() {
  205. writeln("creating TweakBar");
  206. double time = 0, dt; // Current time and enlapsed time
  207. double turn = 0; // Model turn counter
  208. double speed = 0.3; // Model rotation speed
  209. int wire = 0; // Draw model in wireframe?
  210. uint frameCount = 0;
  211. double fps = 0;
  212. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  213. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  214. auto quat = Quaternionf(0,0,0,1);
  215. // auto w = this._window.getBounds()[2];
  216. // auto h = this._window.getBounds()[3];
  217. TwWindowSize(1600, 900);
  218. // // Create a tweak bar
  219. // auto bar = TwNewBar("TweakBar");
  220. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  221. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  222. // 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)' ");
  223. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  224. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  225. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  226. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  227. // //
  228. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  229. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  230. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  231. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  232. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  233. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  234. // //
  235. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  236. }
  237. //-----------------
  238. // Create Shaders
  239. enum vertexShaderSource = "
  240. #version 420 core
  241. layout(location = 0) in vec3 in_position;
  242. layout(location = 1) in vec3 in_normal;
  243. layout(location = 2) in vec2 in_texcoord;
  244. layout(location = 3) in vec4 in_color;
  245. out vec4 v_color;
  246. out gl_PerVertex
  247. {
  248. vec4 gl_Position;
  249. };
  250. void main()
  251. {
  252. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  253. v_color = in_color;
  254. }
  255. ";
  256. enum fragmentShaderSource = "
  257. #version 420 core
  258. in vec4 v_color;
  259. out vec4 FragColor;
  260. void main()
  261. {
  262. FragColor = v_color;
  263. }
  264. ";
  265. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  266. assert(vertexShader.isLinked, vertexShader.infoLog());
  267. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  268. writeln("a: ");
  269. auto shaderPipeline = new ShaderPipeline();
  270. shaderPipeline.bind();
  271. shaderPipeline.use(vertexShader);
  272. shaderPipeline.use(fragmentShader);
  273. writeln("b: ");
  274. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  275. shaderPipeline.unbind();
  276. writeln("c: ");
  277. return shaderPipeline;
  278. }
  279. class Tester {
  280. Window _window;
  281. bool _keepRunning = true;
  282. this() {
  283. this._window = initThree();
  284. this._window.onKey.connect!"_onKey"(this);
  285. this._window.onClose.connect!"_onClose"(this);
  286. }
  287. ~this() {
  288. import core.memory;
  289. writeln("GC.collect: ");
  290. GC.collect();
  291. //Collect window _AFTER_ everything else
  292. this._window = null;
  293. GC.collect();
  294. deinitThree();
  295. }
  296. void run() {
  297. RGBAf rgg;
  298. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  299. setupTweakbar();
  300. writeln("creating shaders: ");
  301. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  302. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  303. writeln("creating shader pipeline: ");
  304. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  305. writeln("connectiong window callbacks: ");
  306. this._window.onSize.connect!"onSize"(this);
  307. this._window.onPosition.connect!"onPosition"(this);
  308. this._window.onButton.connect!"onButton"(this);
  309. this._window.onCursorPos.connect!"onCursorPos"(this);
  310. writeln("begin render loop: ");
  311. //-----------------
  312. // Render Loop
  313. glfwSetTime(0);
  314. while(this._keepRunning) {
  315. this._window.clear(0, 0, 0.5, 1);
  316. shaderPipeline.bind();
  317. mesh.vao.bind();
  318. //vboVertexData.bind();
  319. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  320. //vbo.unbind();
  321. mesh.vao.unbind();
  322. shaderPipeline.unbind();
  323. TwDraw();
  324. this._window.swapBuffers();
  325. updateWindows();
  326. // ++frameCount;
  327. // //if(frameCount % 100 == 0) {
  328. // time = glfwGetTime();
  329. // fps = cast(double)frameCount / time;
  330. // //}
  331. }
  332. }
  333. void onSize(Window window, int width, int height) {
  334. TwWindowSize(width, height);
  335. }
  336. void onPosition(Window window, int x, int y) {
  337. }
  338. void onButton(Window window , 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. void onCursorPos(Window window, double x, double y) {
  350. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  351. }
  352. void stop() {
  353. this._keepRunning = false;
  354. }
  355. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  356. if(window is this._window && action == KeyAction.Pressed) {
  357. if(key == Key.Escape) {
  358. this.stop();
  359. }
  360. }
  361. }
  362. void _onClose(Window window) {
  363. this.stop();
  364. }
  365. }
  366. class InputHandler {
  367. private:
  368. Window _window;
  369. OpenGlRenderer _renderer;
  370. public:
  371. this(Window window, OpenGlRenderer renderer) {
  372. _window = window;
  373. _renderer = renderer;
  374. _window.onKey.connect!"_onKey"(this);
  375. _window.onClose.connect!"_onClose"(this);
  376. _window.onSize.connect!"_onSize"(this);
  377. _window.onPosition.connect!"_onPosition"(this);
  378. _window.onButton.connect!"_onButton"(this);
  379. _window.onCursorPos.connect!"_onCursorPos"(this);
  380. }
  381. private:
  382. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  383. if(window is _window && action == KeyAction.Pressed) {
  384. if(key == Key.Escape) {
  385. _renderer.stop();
  386. }
  387. }
  388. }
  389. void _onClose(Window window) {
  390. _renderer.stop();
  391. }
  392. void _onSize(Window window, int width, int height) {
  393. }
  394. void _onPosition(Window window, int x, int y) {
  395. }
  396. void _onButton(Window window , int button, ButtonAction action) {
  397. }
  398. void _onCursorPos(Window window, double x, double y) {
  399. }
  400. }
  401. void main() {
  402. auto window = initThree();
  403. {
  404. OpenGlRenderer renderer = new OpenGlRenderer(window);
  405. InputHandler inputHandler = new InputHandler(window, renderer);
  406. renderer.run();
  407. }
  408. import core.memory;
  409. GC.collect();
  410. //Collect window _AFTER_ everything else
  411. this._window = null;
  412. GC.collect();
  413. deinitThree();
  414. }
  415. +++/