1
1

app.d 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544
  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. ulong frameCount = 0;
  101. glfwSetTime(0);
  102. while(keepRunning) {
  103. window.pollEvents();
  104. window.makeAktiveRenderWindow();
  105. glCheck!glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  106. glCheck!glClearDepth(1.0f);
  107. glCheck!glClearColor(0.5, 0, 0, 1);
  108. renderer.renderOneFrame(scene, camera, renderTarget, viewport);
  109. TwDraw();
  110. window.swapBuffers();
  111. ++frameCount;
  112. if(frameCount % 1000 == 0) {
  113. auto fps = cast(double)frameCount / glfwGetTime();
  114. log("FPS: ", fps);
  115. frameCount = 0;
  116. glfwSetTime(0);
  117. }
  118. }
  119. }
  120. /+++
  121. struct Vertex {
  122. float x, y, z;
  123. }
  124. struct Normal {
  125. float x, y, z;
  126. }
  127. struct UV {
  128. float u, v;
  129. }
  130. final class Mesh {
  131. public:
  132. Vertex[] vertexData;
  133. Normal[] normalData;
  134. UV[] textureData;
  135. RGBAf[] colorData;
  136. VertexArrayObject vao;
  137. VertexBufferObject!(VertexBufferObjectTarget.Array) vboVertexData;
  138. VertexBufferObject!(VertexBufferObjectTarget.Array) vboNormalData;
  139. VertexBufferObject!(VertexBufferObjectTarget.Array) vboTextureData;
  140. VertexBufferObject!(VertexBufferObjectTarget.Array) vboColorData;
  141. this(string filePath) {
  142. writeln("loading scene: ", filePath);
  143. auto scene = aiImportFile(filePath.toStringz(), aiProcess_Triangulate);
  144. writeln("meshes: ", scene.mNumMeshes);
  145. for(uint m = 0; m < scene.mNumMeshes; ++m) {
  146. const(aiMesh*) mesh = scene.mMeshes[m];
  147. assert(mesh !is null);
  148. writeln("mesh[", m, "] faces : ", mesh.mNumFaces);
  149. for (uint f = 0; f < mesh.mNumFaces; ++f) {
  150. const(aiFace*) face = &mesh.mFaces[f];
  151. assert(face !is null);
  152. for(uint v = 0; v < 3; ++v) {
  153. aiVector3D p, n, uv;
  154. assert(face.mNumIndices > v);
  155. uint vertex = face.mIndices[v];
  156. assert(mesh.mNumVertices > vertex);
  157. p = mesh.mVertices[vertex];
  158. n = mesh.mNormals[vertex];
  159. // check if the mesh has texture coordinates
  160. if(mesh.mTextureCoords[0] !is null) {
  161. uv = mesh.mTextureCoords[0][vertex];
  162. }
  163. vertexData ~= Vertex(p.x, p.y, p.z);
  164. normalData ~= Normal(n.x, n.y, n.z);
  165. textureData ~= UV(uv.x, uv.y);
  166. colorData ~= RGBAf(n.x, n.y, n.z, 1.0f);
  167. }
  168. }
  169. }
  170. writeln("unloading scene: ", filePath);
  171. aiReleaseImport(scene);
  172. //-----------------------------
  173. // upload
  174. writeln("uploading mesh: ", filePath);
  175. vao = new VertexArrayObject();
  176. vao.bind();
  177. writeln("vertex data");
  178. vboVertexData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  179. vboVertexData.bind();
  180. GLuint attribIndex = 0;
  181. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Vertex.sizeof * vertexData.length) , vertexData.ptr, GL_STATIC_DRAW);
  182. glEnableVertexAttribArray(attribIndex);
  183. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  184. vboVertexData.unbind();
  185. writeln("normal data");
  186. vboNormalData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  187. vboNormalData.bind();
  188. attribIndex = 1;
  189. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(Normal.sizeof * normalData.length) , normalData.ptr, GL_STATIC_DRAW);
  190. glEnableVertexAttribArray(attribIndex);
  191. glVertexAttribPointer(attribIndex, 3, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  192. vboNormalData.unbind();
  193. writeln("uv data");
  194. vboTextureData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  195. vboTextureData.bind();
  196. attribIndex = 2;
  197. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(UV.sizeof * textureData.length) , textureData.ptr, GL_STATIC_DRAW);
  198. glEnableVertexAttribArray(attribIndex);
  199. glVertexAttribPointer(attribIndex, 2, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  200. vboTextureData.unbind();
  201. writeln("color data");
  202. vboColorData = new VertexBufferObject!(VertexBufferObjectTarget.Array);
  203. vboColorData.bind();
  204. attribIndex = 3;
  205. glBufferData(GL_ARRAY_BUFFER, cast(ptrdiff_t)(RGBAf.sizeof * colorData.length) , colorData.ptr, GL_STATIC_DRAW);
  206. glEnableVertexAttribArray(attribIndex);
  207. glVertexAttribPointer(attribIndex, 4, GL_FLOAT, GL_FALSE, 0, cast(void*)0);
  208. vboColorData.unbind();
  209. vao.unbind();
  210. writeln("done");
  211. }
  212. }
  213. void setupTweakbar() {
  214. writeln("creating TweakBar");
  215. double time = 0, dt; // Current time and enlapsed time
  216. double turn = 0; // Model turn counter
  217. double speed = 0.3; // Model rotation speed
  218. int wire = 0; // Draw model in wireframe?
  219. uint frameCount = 0;
  220. double fps = 0;
  221. float bgColor[3] = [0.1f, 0.2f, 0.4f]; // Background color
  222. ubyte cubeColor[4] = [255, 0, 0, 128]; // Model color (32bits RGBA)
  223. auto quat = Quaternionf(0,0,0,1);
  224. // auto w = this._window.getBounds()[2];
  225. // auto h = this._window.getBounds()[3];
  226. TwWindowSize(1600, 900);
  227. // // Create a tweak bar
  228. // auto bar = TwNewBar("TweakBar");
  229. // TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.
  230. // // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
  231. // 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)' ");
  232. // // Add 'wire' to 'bar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
  233. // TwAddVarRW(bar, "wire", TW_TYPE_BOOL32, &wire, " label='Wireframe mode' key=CTRL+w help='Toggle wireframe display mode.' ");
  234. // // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
  235. // TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");
  236. // //
  237. // TwAddVarRO(bar, "frameCount", TW_TYPE_UINT32, &frameCount, " label='FrameCount' precision=1 help='FrameCount (in counts).' ");
  238. // TwAddVarRO(bar, "fps", TW_TYPE_DOUBLE, &fps, " label='fps' precision=1 help='fps (in fps).' ");
  239. // // Add 'bgColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
  240. // TwAddVarRW(bar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");
  241. // // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
  242. // TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, " label='Cube color' alpha help='Color and transparency of the cube.' ");
  243. // //
  244. // TwAddVarRW(bar, "quaternion", TW_TYPE_QUAT4F, &quat, " label='Cubde color' alpha help='Color anwdwd transparency of the cube.' ");
  245. }
  246. //-----------------
  247. // Create Shaders
  248. enum vertexShaderSource = "
  249. #version 420 core
  250. layout(location = 0) in vec3 in_position;
  251. layout(location = 1) in vec3 in_normal;
  252. layout(location = 2) in vec2 in_texcoord;
  253. layout(location = 3) in vec4 in_color;
  254. out vec4 v_color;
  255. out gl_PerVertex
  256. {
  257. vec4 gl_Position;
  258. };
  259. void main()
  260. {
  261. gl_Position = vec4(0.005 * in_position.x, 0.005 * in_position.y, 0.005* in_position.z, 1.0);
  262. v_color = in_color;
  263. }
  264. ";
  265. enum fragmentShaderSource = "
  266. #version 420 core
  267. in vec4 v_color;
  268. out vec4 FragColor;
  269. void main()
  270. {
  271. FragColor = v_color;
  272. }
  273. ";
  274. auto createShaderPipeline(Shader!(ShaderType.Vertex) vertexShader, Shader!(ShaderType.Fragment) fragmentShader) {
  275. assert(vertexShader.isLinked, vertexShader.infoLog());
  276. assert(fragmentShader.isLinked, fragmentShader.infoLog());
  277. writeln("a: ");
  278. auto shaderPipeline = new ShaderPipeline();
  279. shaderPipeline.bind();
  280. shaderPipeline.use(vertexShader);
  281. shaderPipeline.use(fragmentShader);
  282. writeln("b: ");
  283. assert(shaderPipeline.isValidProgramPipeline, shaderPipeline.infoLog());
  284. shaderPipeline.unbind();
  285. writeln("c: ");
  286. return shaderPipeline;
  287. }
  288. class Tester {
  289. Window _window;
  290. bool _keepRunning = true;
  291. this() {
  292. this._window = initThree();
  293. this._window.onKey.connect!"_onKey"(this);
  294. this._window.onClose.connect!"_onClose"(this);
  295. }
  296. ~this() {
  297. import core.memory;
  298. writeln("GC.collect: ");
  299. GC.collect();
  300. //Collect window _AFTER_ everything else
  301. this._window = null;
  302. GC.collect();
  303. deinitThree();
  304. }
  305. void run() {
  306. RGBAf rgg;
  307. auto mesh = new Mesh("C:/Coding/models/Collada/duck.dae");
  308. setupTweakbar();
  309. writeln("creating shaders: ");
  310. auto vertexShader = new Shader!(ShaderType.Vertex)(vertexShaderSource);
  311. auto fragmentShader = new Shader!(ShaderType.Fragment)(fragmentShaderSource);
  312. writeln("creating shader pipeline: ");
  313. auto shaderPipeline = createShaderPipeline(vertexShader, fragmentShader);
  314. writeln("connectiong window callbacks: ");
  315. this._window.onSize.connect!"onSize"(this);
  316. this._window.onPosition.connect!"onPosition"(this);
  317. this._window.onButton.connect!"onButton"(this);
  318. this._window.onCursorPos.connect!"onCursorPos"(this);
  319. writeln("begin render loop: ");
  320. //-----------------
  321. // Render Loop
  322. glfwSetTime(0);
  323. while(this._keepRunning) {
  324. this._window.clear(0, 0, 0.5, 1);
  325. shaderPipeline.bind();
  326. mesh.vao.bind();
  327. //vboVertexData.bind();
  328. glDrawArrays(GL_TRIANGLES, 0, mesh.vertexData.length);
  329. //vbo.unbind();
  330. mesh.vao.unbind();
  331. shaderPipeline.unbind();
  332. TwDraw();
  333. this._window.swapBuffers();
  334. updateWindows();
  335. // ++frameCount;
  336. // //if(frameCount % 100 == 0) {
  337. // time = glfwGetTime();
  338. // fps = cast(double)frameCount / time;
  339. // //}
  340. }
  341. }
  342. void onSize(Window window, int width, int height) {
  343. TwWindowSize(width, height);
  344. }
  345. void onPosition(Window window, int x, int y) {
  346. }
  347. void onButton(Window window , int button, ButtonAction action) {
  348. TwMouseAction twaction = action == ButtonAction.Pressed ? TW_MOUSE_PRESSED : TW_MOUSE_RELEASED;
  349. TwMouseButtonID twbutton;
  350. switch(button) {
  351. default:
  352. case GLFW_MOUSE_BUTTON_LEFT: twbutton = TW_MOUSE_LEFT; break;
  353. case GLFW_MOUSE_BUTTON_RIGHT: twbutton = TW_MOUSE_RIGHT; break;
  354. case GLFW_MOUSE_BUTTON_MIDDLE: twbutton = TW_MOUSE_MIDDLE; break;
  355. }
  356. TwMouseButton(twaction, twbutton);
  357. }
  358. void onCursorPos(Window window, double x, double y) {
  359. TwMouseMotion(cast(int)x, this._window.getBounds()[3] - cast(int)y);
  360. }
  361. void stop() {
  362. this._keepRunning = false;
  363. }
  364. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  365. if(window is this._window && action == KeyAction.Pressed) {
  366. if(key == Key.Escape) {
  367. this.stop();
  368. }
  369. }
  370. }
  371. void _onClose(Window window) {
  372. this.stop();
  373. }
  374. }
  375. class InputHandler {
  376. private:
  377. Window _window;
  378. OpenGlRenderer _renderer;
  379. public:
  380. this(Window window, OpenGlRenderer renderer) {
  381. _window = window;
  382. _renderer = renderer;
  383. _window.onKey.connect!"_onKey"(this);
  384. _window.onClose.connect!"_onClose"(this);
  385. _window.onSize.connect!"_onSize"(this);
  386. _window.onPosition.connect!"_onPosition"(this);
  387. _window.onButton.connect!"_onButton"(this);
  388. _window.onCursorPos.connect!"_onCursorPos"(this);
  389. }
  390. private:
  391. void _onKey(Window window, Key key, ScanCode scanCode, KeyAction action, KeyMod keyMod) {
  392. if(window is _window && action == KeyAction.Pressed) {
  393. if(key == Key.Escape) {
  394. _renderer.stop();
  395. }
  396. }
  397. }
  398. void _onClose(Window window) {
  399. _renderer.stop();
  400. }
  401. void _onSize(Window window, int width, int height) {
  402. }
  403. void _onPosition(Window window, int x, int y) {
  404. }
  405. void _onButton(Window window , int button, ButtonAction action) {
  406. }
  407. void _onCursorPos(Window window, double x, double y) {
  408. }
  409. }
  410. void main() {
  411. auto window = initThree();
  412. {
  413. OpenGlRenderer renderer = new OpenGlRenderer(window);
  414. InputHandler inputHandler = new InputHandler(window, renderer);
  415. renderer.run();
  416. }
  417. import core.memory;
  418. GC.collect();
  419. //Collect window _AFTER_ everything else
  420. this._window = null;
  421. GC.collect();
  422. deinitThree();
  423. }
  424. +++/