The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1256 lines
46KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE examples.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. The code included in this file is provided under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license. Permission
  7. To use, copy, modify, and/or distribute this software for any purpose with or
  8. without fee is hereby granted provided that the above copyright notice and
  9. this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES,
  11. WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR
  12. PURPOSE, ARE DISCLAIMED.
  13. ==============================================================================
  14. */
  15. /*******************************************************************************
  16. The block below describes the properties of this PIP. A PIP is a short snippet
  17. of code that can be read by the Projucer and used to generate a JUCE project.
  18. BEGIN_JUCE_PIP_METADATA
  19. name: OpenGLDemo
  20. version: 1.0.0
  21. vendor: JUCE
  22. website: http://juce.com
  23. description: Simple 3D OpenGL application.
  24. dependencies: juce_core, juce_data_structures, juce_events, juce_graphics,
  25. juce_gui_basics, juce_gui_extra, juce_opengl
  26. exporters: xcode_mac, vs2019, linux_make, androidstudio, xcode_iphone
  27. moduleFlags: JUCE_STRICT_REFCOUNTEDPOINTER=1
  28. type: Component
  29. mainClass: OpenGLDemo
  30. useLocalCopy: 1
  31. END_JUCE_PIP_METADATA
  32. *******************************************************************************/
  33. #pragma once
  34. #include "../Assets/DemoUtilities.h"
  35. #include "../Assets/WavefrontObjParser.h"
  36. struct OpenGLUtils
  37. {
  38. //==============================================================================
  39. /** Vertex data to be passed to the shaders.
  40. For the purposes of this demo, each vertex will have a 3D position, a colour and a
  41. 2D texture co-ordinate. Of course you can ignore these or manipulate them in the
  42. shader programs but are some useful defaults to work from.
  43. */
  44. struct Vertex
  45. {
  46. float position[3];
  47. float normal[3];
  48. float colour[4];
  49. float texCoord[2];
  50. };
  51. //==============================================================================
  52. // This class just manages the attributes that the demo shaders use.
  53. struct Attributes
  54. {
  55. Attributes (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
  56. {
  57. position .reset (createAttribute (openGLContext, shader, "position"));
  58. normal .reset (createAttribute (openGLContext, shader, "normal"));
  59. sourceColour .reset (createAttribute (openGLContext, shader, "sourceColour"));
  60. textureCoordIn.reset (createAttribute (openGLContext, shader, "textureCoordIn"));
  61. }
  62. void enable (OpenGLContext& openGLContext)
  63. {
  64. if (position.get() != nullptr)
  65. {
  66. openGLContext.extensions.glVertexAttribPointer (position->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), nullptr);
  67. openGLContext.extensions.glEnableVertexAttribArray (position->attributeID);
  68. }
  69. if (normal.get() != nullptr)
  70. {
  71. openGLContext.extensions.glVertexAttribPointer (normal->attributeID, 3, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 3));
  72. openGLContext.extensions.glEnableVertexAttribArray (normal->attributeID);
  73. }
  74. if (sourceColour.get() != nullptr)
  75. {
  76. openGLContext.extensions.glVertexAttribPointer (sourceColour->attributeID, 4, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 6));
  77. openGLContext.extensions.glEnableVertexAttribArray (sourceColour->attributeID);
  78. }
  79. if (textureCoordIn.get() != nullptr)
  80. {
  81. openGLContext.extensions.glVertexAttribPointer (textureCoordIn->attributeID, 2, GL_FLOAT, GL_FALSE, sizeof (Vertex), (GLvoid*) (sizeof (float) * 10));
  82. openGLContext.extensions.glEnableVertexAttribArray (textureCoordIn->attributeID);
  83. }
  84. }
  85. void disable (OpenGLContext& openGLContext)
  86. {
  87. if (position.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (position->attributeID);
  88. if (normal.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (normal->attributeID);
  89. if (sourceColour.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (sourceColour->attributeID);
  90. if (textureCoordIn.get() != nullptr) openGLContext.extensions.glDisableVertexAttribArray (textureCoordIn->attributeID);
  91. }
  92. std::unique_ptr<OpenGLShaderProgram::Attribute> position, normal, sourceColour, textureCoordIn;
  93. private:
  94. static OpenGLShaderProgram::Attribute* createAttribute (OpenGLContext& openGLContext,
  95. OpenGLShaderProgram& shader,
  96. const char* attributeName)
  97. {
  98. if (openGLContext.extensions.glGetAttribLocation (shader.getProgramID(), attributeName) < 0)
  99. return nullptr;
  100. return new OpenGLShaderProgram::Attribute (shader, attributeName);
  101. }
  102. };
  103. //==============================================================================
  104. // This class just manages the uniform values that the demo shaders use.
  105. struct Uniforms
  106. {
  107. Uniforms (OpenGLContext& openGLContext, OpenGLShaderProgram& shader)
  108. {
  109. projectionMatrix.reset (createUniform (openGLContext, shader, "projectionMatrix"));
  110. viewMatrix .reset (createUniform (openGLContext, shader, "viewMatrix"));
  111. texture .reset (createUniform (openGLContext, shader, "demoTexture"));
  112. lightPosition .reset (createUniform (openGLContext, shader, "lightPosition"));
  113. bouncingNumber .reset (createUniform (openGLContext, shader, "bouncingNumber"));
  114. }
  115. std::unique_ptr<OpenGLShaderProgram::Uniform> projectionMatrix, viewMatrix, texture, lightPosition, bouncingNumber;
  116. private:
  117. static OpenGLShaderProgram::Uniform* createUniform (OpenGLContext& openGLContext,
  118. OpenGLShaderProgram& shader,
  119. const char* uniformName)
  120. {
  121. if (openGLContext.extensions.glGetUniformLocation (shader.getProgramID(), uniformName) < 0)
  122. return nullptr;
  123. return new OpenGLShaderProgram::Uniform (shader, uniformName);
  124. }
  125. };
  126. //==============================================================================
  127. /** This loads a 3D model from an OBJ file and converts it into some vertex buffers
  128. that we can draw.
  129. */
  130. struct Shape
  131. {
  132. Shape (OpenGLContext& openGLContext)
  133. {
  134. if (shapeFile.load (loadEntireAssetIntoString ("teapot.obj")).wasOk())
  135. for (auto* s : shapeFile.shapes)
  136. vertexBuffers.add (new VertexBuffer (openGLContext, *s));
  137. }
  138. void draw (OpenGLContext& openGLContext, Attributes& attributes)
  139. {
  140. for (auto* vertexBuffer : vertexBuffers)
  141. {
  142. vertexBuffer->bind();
  143. attributes.enable (openGLContext);
  144. glDrawElements (GL_TRIANGLES, vertexBuffer->numIndices, GL_UNSIGNED_INT, nullptr);
  145. attributes.disable (openGLContext);
  146. }
  147. }
  148. private:
  149. struct VertexBuffer
  150. {
  151. VertexBuffer (OpenGLContext& context, WavefrontObjFile::Shape& shape) : openGLContext (context)
  152. {
  153. numIndices = shape.mesh.indices.size();
  154. openGLContext.extensions.glGenBuffers (1, &vertexBuffer);
  155. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  156. Array<Vertex> vertices;
  157. createVertexListFromMesh (shape.mesh, vertices, Colours::green);
  158. openGLContext.extensions.glBufferData (GL_ARRAY_BUFFER, vertices.size() * (int) sizeof (Vertex),
  159. vertices.getRawDataPointer(), GL_STATIC_DRAW);
  160. openGLContext.extensions.glGenBuffers (1, &indexBuffer);
  161. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
  162. openGLContext.extensions.glBufferData (GL_ELEMENT_ARRAY_BUFFER, numIndices * (int) sizeof (juce::uint32),
  163. shape.mesh.indices.getRawDataPointer(), GL_STATIC_DRAW);
  164. }
  165. ~VertexBuffer()
  166. {
  167. openGLContext.extensions.glDeleteBuffers (1, &vertexBuffer);
  168. openGLContext.extensions.glDeleteBuffers (1, &indexBuffer);
  169. }
  170. void bind()
  171. {
  172. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, vertexBuffer);
  173. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, indexBuffer);
  174. }
  175. GLuint vertexBuffer, indexBuffer;
  176. int numIndices;
  177. OpenGLContext& openGLContext;
  178. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VertexBuffer)
  179. };
  180. WavefrontObjFile shapeFile;
  181. OwnedArray<VertexBuffer> vertexBuffers;
  182. static void createVertexListFromMesh (const WavefrontObjFile::Mesh& mesh, Array<Vertex>& list, Colour colour)
  183. {
  184. auto scale = 0.2f;
  185. WavefrontObjFile::TextureCoord defaultTexCoord = { 0.5f, 0.5f };
  186. WavefrontObjFile::Vertex defaultNormal = { 0.5f, 0.5f, 0.5f };
  187. for (int i = 0; i < mesh.vertices.size(); ++i)
  188. {
  189. auto& v = mesh.vertices.getReference (i);
  190. auto& n = (i < mesh.normals.size() ? mesh.normals.getReference (i)
  191. : defaultNormal);
  192. auto& tc = (i < mesh.textureCoords.size() ? mesh.textureCoords.getReference (i)
  193. : defaultTexCoord);
  194. list.add ({ { scale * v.x, scale * v.y, scale * v.z, },
  195. { scale * n.x, scale * n.y, scale * n.z, },
  196. { colour.getFloatRed(), colour.getFloatGreen(), colour.getFloatBlue(), colour.getFloatAlpha() },
  197. { tc.x, tc.y } });
  198. }
  199. }
  200. };
  201. //==============================================================================
  202. struct ShaderPreset
  203. {
  204. const char* name;
  205. const char* vertexShader;
  206. const char* fragmentShader;
  207. };
  208. static Array<ShaderPreset> getPresets()
  209. {
  210. #define SHADER_DEMO_HEADER \
  211. "/* This is a live OpenGL Shader demo.\n" \
  212. " Edit the shader program below and it will be \n" \
  213. " compiled and applied to the model above!\n" \
  214. "*/\n\n"
  215. ShaderPreset presets[] =
  216. {
  217. {
  218. "Texture + Lighting",
  219. SHADER_DEMO_HEADER
  220. "attribute vec4 position;\n"
  221. "attribute vec4 normal;\n"
  222. "attribute vec4 sourceColour;\n"
  223. "attribute vec2 textureCoordIn;\n"
  224. "\n"
  225. "uniform mat4 projectionMatrix;\n"
  226. "uniform mat4 viewMatrix;\n"
  227. "uniform vec4 lightPosition;\n"
  228. "\n"
  229. "varying vec4 destinationColour;\n"
  230. "varying vec2 textureCoordOut;\n"
  231. "varying float lightIntensity;\n"
  232. "\n"
  233. "void main()\n"
  234. "{\n"
  235. " destinationColour = sourceColour;\n"
  236. " textureCoordOut = textureCoordIn;\n"
  237. "\n"
  238. " vec4 light = viewMatrix * lightPosition;\n"
  239. " lightIntensity = dot (light, normal);\n"
  240. "\n"
  241. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  242. "}\n",
  243. SHADER_DEMO_HEADER
  244. #if JUCE_OPENGL_ES
  245. "varying lowp vec4 destinationColour;\n"
  246. "varying lowp vec2 textureCoordOut;\n"
  247. "varying highp float lightIntensity;\n"
  248. #else
  249. "varying vec4 destinationColour;\n"
  250. "varying vec2 textureCoordOut;\n"
  251. "varying float lightIntensity;\n"
  252. #endif
  253. "\n"
  254. "uniform sampler2D demoTexture;\n"
  255. "\n"
  256. "void main()\n"
  257. "{\n"
  258. #if JUCE_OPENGL_ES
  259. " highp float l = max (0.3, lightIntensity * 0.3);\n"
  260. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  261. #else
  262. " float l = max (0.3, lightIntensity * 0.3);\n"
  263. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  264. #endif
  265. " gl_FragColor = colour * texture2D (demoTexture, textureCoordOut);\n"
  266. "}\n"
  267. },
  268. {
  269. "Textured",
  270. SHADER_DEMO_HEADER
  271. "attribute vec4 position;\n"
  272. "attribute vec4 sourceColour;\n"
  273. "attribute vec2 textureCoordIn;\n"
  274. "\n"
  275. "uniform mat4 projectionMatrix;\n"
  276. "uniform mat4 viewMatrix;\n"
  277. "\n"
  278. "varying vec4 destinationColour;\n"
  279. "varying vec2 textureCoordOut;\n"
  280. "\n"
  281. "void main()\n"
  282. "{\n"
  283. " destinationColour = sourceColour;\n"
  284. " textureCoordOut = textureCoordIn;\n"
  285. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  286. "}\n",
  287. SHADER_DEMO_HEADER
  288. #if JUCE_OPENGL_ES
  289. "varying lowp vec4 destinationColour;\n"
  290. "varying lowp vec2 textureCoordOut;\n"
  291. #else
  292. "varying vec4 destinationColour;\n"
  293. "varying vec2 textureCoordOut;\n"
  294. #endif
  295. "\n"
  296. "uniform sampler2D demoTexture;\n"
  297. "\n"
  298. "void main()\n"
  299. "{\n"
  300. " gl_FragColor = texture2D (demoTexture, textureCoordOut);\n"
  301. "}\n"
  302. },
  303. {
  304. "Flat Colour",
  305. SHADER_DEMO_HEADER
  306. "attribute vec4 position;\n"
  307. "attribute vec4 sourceColour;\n"
  308. "attribute vec2 textureCoordIn;\n"
  309. "\n"
  310. "uniform mat4 projectionMatrix;\n"
  311. "uniform mat4 viewMatrix;\n"
  312. "\n"
  313. "varying vec4 destinationColour;\n"
  314. "varying vec2 textureCoordOut;\n"
  315. "\n"
  316. "void main()\n"
  317. "{\n"
  318. " destinationColour = sourceColour;\n"
  319. " textureCoordOut = textureCoordIn;\n"
  320. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  321. "}\n",
  322. SHADER_DEMO_HEADER
  323. #if JUCE_OPENGL_ES
  324. "varying lowp vec4 destinationColour;\n"
  325. "varying lowp vec2 textureCoordOut;\n"
  326. #else
  327. "varying vec4 destinationColour;\n"
  328. "varying vec2 textureCoordOut;\n"
  329. #endif
  330. "\n"
  331. "void main()\n"
  332. "{\n"
  333. " gl_FragColor = destinationColour;\n"
  334. "}\n"
  335. },
  336. {
  337. "Rainbow",
  338. SHADER_DEMO_HEADER
  339. "attribute vec4 position;\n"
  340. "attribute vec4 sourceColour;\n"
  341. "attribute vec2 textureCoordIn;\n"
  342. "\n"
  343. "uniform mat4 projectionMatrix;\n"
  344. "uniform mat4 viewMatrix;\n"
  345. "\n"
  346. "varying vec4 destinationColour;\n"
  347. "varying vec2 textureCoordOut;\n"
  348. "\n"
  349. "varying float xPos;\n"
  350. "varying float yPos;\n"
  351. "varying float zPos;\n"
  352. "\n"
  353. "void main()\n"
  354. "{\n"
  355. " vec4 v = vec4 (position);\n"
  356. " xPos = clamp (v.x, 0.0, 1.0);\n"
  357. " yPos = clamp (v.y, 0.0, 1.0);\n"
  358. " zPos = clamp (v.z, 0.0, 1.0);\n"
  359. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  360. "}",
  361. SHADER_DEMO_HEADER
  362. #if JUCE_OPENGL_ES
  363. "varying lowp vec4 destinationColour;\n"
  364. "varying lowp vec2 textureCoordOut;\n"
  365. "varying lowp float xPos;\n"
  366. "varying lowp float yPos;\n"
  367. "varying lowp float zPos;\n"
  368. #else
  369. "varying vec4 destinationColour;\n"
  370. "varying vec2 textureCoordOut;\n"
  371. "varying float xPos;\n"
  372. "varying float yPos;\n"
  373. "varying float zPos;\n"
  374. #endif
  375. "\n"
  376. "void main()\n"
  377. "{\n"
  378. " gl_FragColor = vec4 (xPos, yPos, zPos, 1.0);\n"
  379. "}"
  380. },
  381. {
  382. "Changing Colour",
  383. SHADER_DEMO_HEADER
  384. "attribute vec4 position;\n"
  385. "attribute vec2 textureCoordIn;\n"
  386. "\n"
  387. "uniform mat4 projectionMatrix;\n"
  388. "uniform mat4 viewMatrix;\n"
  389. "\n"
  390. "varying vec2 textureCoordOut;\n"
  391. "\n"
  392. "void main()\n"
  393. "{\n"
  394. " textureCoordOut = textureCoordIn;\n"
  395. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  396. "}\n",
  397. SHADER_DEMO_HEADER
  398. "#define PI 3.1415926535897932384626433832795\n"
  399. "\n"
  400. #if JUCE_OPENGL_ES
  401. "precision mediump float;\n"
  402. "varying lowp vec2 textureCoordOut;\n"
  403. #else
  404. "varying vec2 textureCoordOut;\n"
  405. #endif
  406. "uniform float bouncingNumber;\n"
  407. "\n"
  408. "void main()\n"
  409. "{\n"
  410. " float b = bouncingNumber;\n"
  411. " float n = b * PI * 2.0;\n"
  412. " float sn = (sin (n * textureCoordOut.x) * 0.5) + 0.5;\n"
  413. " float cn = (sin (n * textureCoordOut.y) * 0.5) + 0.5;\n"
  414. "\n"
  415. " vec4 col = vec4 (b, sn, cn, 1.0);\n"
  416. " gl_FragColor = col;\n"
  417. "}\n"
  418. },
  419. {
  420. "Simple Light",
  421. SHADER_DEMO_HEADER
  422. "attribute vec4 position;\n"
  423. "attribute vec4 normal;\n"
  424. "\n"
  425. "uniform mat4 projectionMatrix;\n"
  426. "uniform mat4 viewMatrix;\n"
  427. "uniform vec4 lightPosition;\n"
  428. "\n"
  429. "varying float lightIntensity;\n"
  430. "\n"
  431. "void main()\n"
  432. "{\n"
  433. " vec4 light = viewMatrix * lightPosition;\n"
  434. " lightIntensity = dot (light, normal);\n"
  435. "\n"
  436. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  437. "}\n",
  438. SHADER_DEMO_HEADER
  439. #if JUCE_OPENGL_ES
  440. "varying highp float lightIntensity;\n"
  441. #else
  442. "varying float lightIntensity;\n"
  443. #endif
  444. "\n"
  445. "void main()\n"
  446. "{\n"
  447. #if JUCE_OPENGL_ES
  448. " highp float l = lightIntensity * 0.25;\n"
  449. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  450. #else
  451. " float l = lightIntensity * 0.25;\n"
  452. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  453. #endif
  454. "\n"
  455. " gl_FragColor = colour;\n"
  456. "}\n"
  457. },
  458. {
  459. "Flattened",
  460. SHADER_DEMO_HEADER
  461. "attribute vec4 position;\n"
  462. "attribute vec4 normal;\n"
  463. "\n"
  464. "uniform mat4 projectionMatrix;\n"
  465. "uniform mat4 viewMatrix;\n"
  466. "uniform vec4 lightPosition;\n"
  467. "\n"
  468. "varying float lightIntensity;\n"
  469. "\n"
  470. "void main()\n"
  471. "{\n"
  472. " vec4 light = viewMatrix * lightPosition;\n"
  473. " lightIntensity = dot (light, normal);\n"
  474. "\n"
  475. " vec4 v = vec4 (position);\n"
  476. " v.z = v.z * 0.1;\n"
  477. "\n"
  478. " gl_Position = projectionMatrix * viewMatrix * v;\n"
  479. "}\n",
  480. SHADER_DEMO_HEADER
  481. #if JUCE_OPENGL_ES
  482. "varying highp float lightIntensity;\n"
  483. #else
  484. "varying float lightIntensity;\n"
  485. #endif
  486. "\n"
  487. "void main()\n"
  488. "{\n"
  489. #if JUCE_OPENGL_ES
  490. " highp float l = lightIntensity * 0.25;\n"
  491. " highp vec4 colour = vec4 (l, l, l, 1.0);\n"
  492. #else
  493. " float l = lightIntensity * 0.25;\n"
  494. " vec4 colour = vec4 (l, l, l, 1.0);\n"
  495. #endif
  496. "\n"
  497. " gl_FragColor = colour;\n"
  498. "}\n"
  499. },
  500. {
  501. "Toon Shader",
  502. SHADER_DEMO_HEADER
  503. "attribute vec4 position;\n"
  504. "attribute vec4 normal;\n"
  505. "\n"
  506. "uniform mat4 projectionMatrix;\n"
  507. "uniform mat4 viewMatrix;\n"
  508. "uniform vec4 lightPosition;\n"
  509. "\n"
  510. "varying float lightIntensity;\n"
  511. "\n"
  512. "void main()\n"
  513. "{\n"
  514. " vec4 light = viewMatrix * lightPosition;\n"
  515. " lightIntensity = dot (light, normal);\n"
  516. "\n"
  517. " gl_Position = projectionMatrix * viewMatrix * position;\n"
  518. "}\n",
  519. SHADER_DEMO_HEADER
  520. #if JUCE_OPENGL_ES
  521. "varying highp float lightIntensity;\n"
  522. #else
  523. "varying float lightIntensity;\n"
  524. #endif
  525. "\n"
  526. "void main()\n"
  527. "{\n"
  528. #if JUCE_OPENGL_ES
  529. " highp float intensity = lightIntensity * 0.5;\n"
  530. " highp vec4 colour;\n"
  531. #else
  532. " float intensity = lightIntensity * 0.5;\n"
  533. " vec4 colour;\n"
  534. #endif
  535. "\n"
  536. " if (intensity > 0.95)\n"
  537. " colour = vec4 (1.0, 0.5, 0.5, 1.0);\n"
  538. " else if (intensity > 0.5)\n"
  539. " colour = vec4 (0.6, 0.3, 0.3, 1.0);\n"
  540. " else if (intensity > 0.25)\n"
  541. " colour = vec4 (0.4, 0.2, 0.2, 1.0);\n"
  542. " else\n"
  543. " colour = vec4 (0.2, 0.1, 0.1, 1.0);\n"
  544. "\n"
  545. " gl_FragColor = colour;\n"
  546. "}\n"
  547. }
  548. };
  549. return Array<ShaderPreset> (presets, numElementsInArray (presets));
  550. }
  551. //==============================================================================
  552. // These classes are used to load textures from the various sources that the demo uses..
  553. struct DemoTexture
  554. {
  555. virtual ~DemoTexture() {}
  556. virtual bool applyTo (OpenGLTexture&) = 0;
  557. String name;
  558. };
  559. struct DynamicTexture : public DemoTexture
  560. {
  561. DynamicTexture() { name = "Dynamically-generated texture"; }
  562. Image image;
  563. BouncingNumber x, y;
  564. bool applyTo (OpenGLTexture& texture) override
  565. {
  566. int size = 128;
  567. if (! image.isValid())
  568. image = Image (Image::ARGB, size, size, true);
  569. {
  570. Graphics g (image);
  571. g.fillAll (Colours::lightcyan);
  572. g.setColour (Colours::darkred);
  573. g.drawRect (0, 0, size, size, 2);
  574. g.setColour (Colours::green);
  575. g.fillEllipse (x.getValue() * size * 0.9f, y.getValue() * size * 0.9f, size * 0.1f, size * 0.1f);
  576. g.setColour (Colours::black);
  577. g.setFont (40);
  578. const MessageManagerLock mml (ThreadPoolJob::getCurrentThreadPoolJob());
  579. if (! mml.lockWasGained())
  580. return false;
  581. g.drawFittedText (String (Time::getCurrentTime().getMilliseconds()), image.getBounds(), Justification::centred, 1);
  582. }
  583. texture.loadImage (image);
  584. return true;
  585. }
  586. };
  587. static Image resizeImageToPowerOfTwo (Image image)
  588. {
  589. if (! (isPowerOfTwo (image.getWidth()) && isPowerOfTwo (image.getHeight())))
  590. return image.rescaled (jmin (1024, nextPowerOfTwo (image.getWidth())),
  591. jmin (1024, nextPowerOfTwo (image.getHeight())));
  592. return image;
  593. }
  594. struct BuiltInTexture : public DemoTexture
  595. {
  596. BuiltInTexture (const char* nm, const void* imageData, size_t imageSize)
  597. : image (resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (imageData, imageSize)))
  598. {
  599. name = nm;
  600. }
  601. Image image;
  602. bool applyTo (OpenGLTexture& texture) override
  603. {
  604. texture.loadImage (image);
  605. return false;
  606. }
  607. };
  608. struct TextureFromFile : public DemoTexture
  609. {
  610. TextureFromFile (const File& file)
  611. {
  612. name = file.getFileName();
  613. image = resizeImageToPowerOfTwo (ImageFileFormat::loadFrom (file));
  614. }
  615. Image image;
  616. bool applyTo (OpenGLTexture& texture) override
  617. {
  618. texture.loadImage (image);
  619. return false;
  620. }
  621. };
  622. struct TextureFromAsset : public DemoTexture
  623. {
  624. TextureFromAsset (const char* assetName)
  625. {
  626. name = assetName;
  627. image = resizeImageToPowerOfTwo (getImageFromAssets (assetName));
  628. }
  629. Image image;
  630. bool applyTo (OpenGLTexture& texture) override
  631. {
  632. texture.loadImage (image);
  633. return false;
  634. }
  635. };
  636. };
  637. //==============================================================================
  638. /** This is the main demo component - the GL context gets attached to it, and
  639. it implements the OpenGLRenderer callback so that it can do real GL work.
  640. */
  641. class OpenGLDemo : public Component,
  642. private OpenGLRenderer,
  643. private AsyncUpdater
  644. {
  645. public:
  646. OpenGLDemo()
  647. {
  648. if (auto* peer = getPeer())
  649. peer->setCurrentRenderingEngine (0);
  650. setOpaque (true);
  651. controlsOverlay.reset (new DemoControlsOverlay (*this));
  652. addAndMakeVisible (controlsOverlay.get());
  653. openGLContext.setRenderer (this);
  654. openGLContext.attachTo (*this);
  655. openGLContext.setContinuousRepainting (true);
  656. controlsOverlay->initialise();
  657. setSize (500, 500);
  658. }
  659. ~OpenGLDemo() override
  660. {
  661. openGLContext.detach();
  662. }
  663. void newOpenGLContextCreated() override
  664. {
  665. // nothing to do in this case - we'll initialise our shaders + textures
  666. // on demand, during the render callback.
  667. freeAllContextObjects();
  668. if (controlsOverlay.get() != nullptr)
  669. controlsOverlay->updateShader();
  670. }
  671. void openGLContextClosing() override
  672. {
  673. // When the context is about to close, you must use this callback to delete
  674. // any GPU resources while the context is still current.
  675. freeAllContextObjects();
  676. if (lastTexture != nullptr)
  677. setTexture (lastTexture);
  678. }
  679. void freeAllContextObjects()
  680. {
  681. shape .reset();
  682. shader .reset();
  683. attributes.reset();
  684. uniforms .reset();
  685. texture .release();
  686. }
  687. // This is a virtual method in OpenGLRenderer, and is called when it's time
  688. // to do your GL rendering.
  689. void renderOpenGL() override
  690. {
  691. jassert (OpenGLHelpers::isContextActive());
  692. auto desktopScale = (float) openGLContext.getRenderingScale();
  693. OpenGLHelpers::clear (getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground,
  694. Colours::lightblue));
  695. if (textureToUse != nullptr)
  696. if (! textureToUse->applyTo (texture))
  697. textureToUse = nullptr;
  698. // First draw our background graphics to demonstrate the OpenGLGraphicsContext class
  699. if (doBackgroundDrawing)
  700. drawBackground2DStuff (desktopScale);
  701. updateShader(); // Check whether we need to compile a new shader
  702. if (shader.get() == nullptr)
  703. return;
  704. // Having used the juce 2D renderer, it will have messed-up a whole load of GL state, so
  705. // we need to initialise some important settings before doing our normal GL 3D drawing..
  706. glEnable (GL_DEPTH_TEST);
  707. glDepthFunc (GL_LESS);
  708. glEnable (GL_BLEND);
  709. glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
  710. openGLContext.extensions.glActiveTexture (GL_TEXTURE0);
  711. glEnable (GL_TEXTURE_2D);
  712. glViewport (0, 0, roundToInt (desktopScale * getWidth()), roundToInt (desktopScale * getHeight()));
  713. texture.bind();
  714. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  715. glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
  716. shader->use();
  717. if (uniforms->projectionMatrix.get() != nullptr)
  718. uniforms->projectionMatrix->setMatrix4 (getProjectionMatrix().mat, 1, false);
  719. if (uniforms->viewMatrix.get() != nullptr)
  720. uniforms->viewMatrix->setMatrix4 (getViewMatrix().mat, 1, false);
  721. if (uniforms->texture.get() != nullptr)
  722. uniforms->texture->set ((GLint) 0);
  723. if (uniforms->lightPosition.get() != nullptr)
  724. uniforms->lightPosition->set (-15.0f, 10.0f, 15.0f, 0.0f);
  725. if (uniforms->bouncingNumber.get() != nullptr)
  726. uniforms->bouncingNumber->set (bouncingNumber.getValue());
  727. shape->draw (openGLContext, *attributes);
  728. // Reset the element buffers so child Components draw correctly
  729. openGLContext.extensions.glBindBuffer (GL_ARRAY_BUFFER, 0);
  730. openGLContext.extensions.glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, 0);
  731. if (! controlsOverlay->isMouseButtonDown())
  732. rotation += (float) rotationSpeed;
  733. }
  734. Matrix3D<float> getProjectionMatrix() const
  735. {
  736. auto w = 1.0f / (scale + 0.1f);
  737. auto h = w * getLocalBounds().toFloat().getAspectRatio (false);
  738. return Matrix3D<float>::fromFrustum (-w, w, -h, h, 4.0f, 30.0f);
  739. }
  740. Matrix3D<float> getViewMatrix() const
  741. {
  742. auto viewMatrix = draggableOrientation.getRotationMatrix()
  743. * Vector3D<float> (0.0f, 1.0f, -10.0f);
  744. auto rotationMatrix = Matrix3D<float>::rotation ({ rotation, rotation, -0.3f });
  745. return rotationMatrix * viewMatrix;
  746. }
  747. void setTexture (OpenGLUtils::DemoTexture* t)
  748. {
  749. lastTexture = textureToUse = t;
  750. }
  751. void setShaderProgram (const String& vertexShader, const String& fragmentShader)
  752. {
  753. newVertexShader = vertexShader;
  754. newFragmentShader = fragmentShader;
  755. }
  756. void paint (Graphics&) override {}
  757. void resized() override
  758. {
  759. controlsOverlay->setBounds (getLocalBounds());
  760. draggableOrientation.setViewport (getLocalBounds());
  761. }
  762. Draggable3DOrientation draggableOrientation;
  763. bool doBackgroundDrawing = false;
  764. float scale = 0.5f, rotationSpeed = 0.0f;
  765. BouncingNumber bouncingNumber;
  766. private:
  767. void handleAsyncUpdate() override
  768. {
  769. controlsOverlay->statusLabel.setText (statusText, dontSendNotification);
  770. }
  771. void drawBackground2DStuff (float desktopScale)
  772. {
  773. // Create an OpenGLGraphicsContext that will draw into this GL window..
  774. std::unique_ptr<LowLevelGraphicsContext> glRenderer (createOpenGLGraphicsContext (openGLContext,
  775. roundToInt (desktopScale * getWidth()),
  776. roundToInt (desktopScale * getHeight())));
  777. if (glRenderer.get() != nullptr)
  778. {
  779. Graphics g (*glRenderer);
  780. g.addTransform (AffineTransform::scale (desktopScale));
  781. for (auto s : stars)
  782. {
  783. auto size = 0.25f;
  784. // This stuff just creates a spinning star shape and fills it..
  785. Path p;
  786. p.addStar ({ getWidth() * s.x.getValue(),
  787. getHeight() * s.y.getValue() },
  788. 7,
  789. getHeight() * size * 0.5f,
  790. getHeight() * size,
  791. s.angle.getValue());
  792. auto hue = s.hue.getValue();
  793. g.setGradientFill (ColourGradient (Colours::green.withRotatedHue (hue).withAlpha (0.8f),
  794. 0, 0,
  795. Colours::red.withRotatedHue (hue).withAlpha (0.5f),
  796. 0, (float) getHeight(), false));
  797. g.fillPath (p);
  798. }
  799. }
  800. }
  801. OpenGLContext openGLContext;
  802. //==============================================================================
  803. /**
  804. This component sits on top of the main GL demo, and contains all the sliders
  805. and widgets that control things.
  806. */
  807. class DemoControlsOverlay : public Component,
  808. private CodeDocument::Listener,
  809. private Slider::Listener,
  810. private Timer
  811. {
  812. public:
  813. DemoControlsOverlay (OpenGLDemo& d)
  814. : demo (d)
  815. {
  816. addAndMakeVisible (statusLabel);
  817. statusLabel.setJustificationType (Justification::topLeft);
  818. statusLabel.setFont (Font (14.0f));
  819. addAndMakeVisible (sizeSlider);
  820. sizeSlider.setRange (0.0, 1.0, 0.001);
  821. sizeSlider.addListener (this);
  822. addAndMakeVisible (zoomLabel);
  823. zoomLabel.attachToComponent (&sizeSlider, true);
  824. addAndMakeVisible (speedSlider);
  825. speedSlider.setRange (0.0, 0.5, 0.001);
  826. speedSlider.addListener (this);
  827. speedSlider.setSkewFactor (0.5f);
  828. addAndMakeVisible (speedLabel);
  829. speedLabel.attachToComponent (&speedSlider, true);
  830. addAndMakeVisible (showBackgroundToggle);
  831. showBackgroundToggle.onClick = [this] { demo.doBackgroundDrawing = showBackgroundToggle.getToggleState(); };
  832. addAndMakeVisible (tabbedComp);
  833. tabbedComp.setTabBarDepth (25);
  834. tabbedComp.setColour (TabbedButtonBar::tabTextColourId, Colours::grey);
  835. tabbedComp.addTab ("Vertex", Colours::transparentBlack, &vertexEditorComp, false);
  836. tabbedComp.addTab ("Fragment", Colours::transparentBlack, &fragmentEditorComp, false);
  837. vertexDocument.addListener (this);
  838. fragmentDocument.addListener (this);
  839. textures.add (new OpenGLUtils::TextureFromAsset ("portmeirion.jpg"));
  840. textures.add (new OpenGLUtils::TextureFromAsset ("tile_background.png"));
  841. textures.add (new OpenGLUtils::TextureFromAsset ("juce_icon.png"));
  842. textures.add (new OpenGLUtils::DynamicTexture());
  843. addAndMakeVisible (textureBox);
  844. textureBox.onChange = [this] { selectTexture (textureBox.getSelectedId()); };
  845. updateTexturesList();
  846. addAndMakeVisible (presetBox);
  847. presetBox.onChange = [this] { selectPreset (presetBox.getSelectedItemIndex()); };
  848. auto presets = OpenGLUtils::getPresets();
  849. for (int i = 0; i < presets.size(); ++i)
  850. presetBox.addItem (presets[i].name, i + 1);
  851. addAndMakeVisible (presetLabel);
  852. presetLabel.attachToComponent (&presetBox, true);
  853. addAndMakeVisible (textureLabel);
  854. textureLabel.attachToComponent (&textureBox, true);
  855. lookAndFeelChanged();
  856. }
  857. void initialise()
  858. {
  859. showBackgroundToggle.setToggleState (false, sendNotification);
  860. textureBox.setSelectedItemIndex (0);
  861. presetBox .setSelectedItemIndex (0);
  862. speedSlider.setValue (0.01);
  863. sizeSlider .setValue (0.5);
  864. }
  865. void resized() override
  866. {
  867. auto area = getLocalBounds().reduced (4);
  868. auto top = area.removeFromTop (75);
  869. auto sliders = top.removeFromRight (area.getWidth() / 2);
  870. showBackgroundToggle.setBounds (sliders.removeFromBottom (25));
  871. speedSlider .setBounds (sliders.removeFromBottom (25));
  872. sizeSlider .setBounds (sliders.removeFromBottom (25));
  873. top.removeFromRight (70);
  874. statusLabel.setBounds (top);
  875. auto shaderArea = area.removeFromBottom (area.getHeight() / 2);
  876. auto presets = shaderArea.removeFromTop (25);
  877. presets.removeFromLeft (100);
  878. presetBox.setBounds (presets.removeFromLeft (150));
  879. presets.removeFromLeft (100);
  880. textureBox.setBounds (presets);
  881. shaderArea.removeFromTop (4);
  882. tabbedComp.setBounds (shaderArea);
  883. }
  884. void mouseDown (const MouseEvent& e) override
  885. {
  886. demo.draggableOrientation.mouseDown (e.getPosition());
  887. }
  888. void mouseDrag (const MouseEvent& e) override
  889. {
  890. demo.draggableOrientation.mouseDrag (e.getPosition());
  891. }
  892. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& d) override
  893. {
  894. sizeSlider.setValue (sizeSlider.getValue() + d.deltaY);
  895. }
  896. void mouseMagnify (const MouseEvent&, float magnifyAmmount) override
  897. {
  898. sizeSlider.setValue (sizeSlider.getValue() + magnifyAmmount - 1.0f);
  899. }
  900. void selectPreset (int preset)
  901. {
  902. const auto& p = OpenGLUtils::getPresets()[preset];
  903. vertexDocument .replaceAllContent (p.vertexShader);
  904. fragmentDocument.replaceAllContent (p.fragmentShader);
  905. startTimer (1);
  906. }
  907. void selectTexture (int itemID)
  908. {
  909. #if JUCE_MODAL_LOOPS_PERMITTED
  910. if (itemID == 1000)
  911. {
  912. auto lastLocation = File::getSpecialLocation (File::userPicturesDirectory);
  913. FileChooser fc ("Choose an image to open...", lastLocation, "*.jpg;*.jpeg;*.png;*.gif");
  914. if (fc.browseForFileToOpen())
  915. {
  916. lastLocation = fc.getResult();
  917. textures.add (new OpenGLUtils::TextureFromFile (fc.getResult()));
  918. updateTexturesList();
  919. textureBox.setSelectedId (textures.size());
  920. }
  921. }
  922. else
  923. #endif
  924. {
  925. if (auto* t = textures[itemID - 1])
  926. demo.setTexture (t);
  927. }
  928. }
  929. void updateTexturesList()
  930. {
  931. textureBox.clear();
  932. for (int i = 0; i < textures.size(); ++i)
  933. textureBox.addItem (textures.getUnchecked (i)->name, i + 1);
  934. #if JUCE_MODAL_LOOPS_PERMITTED
  935. textureBox.addSeparator();
  936. textureBox.addItem ("Load from a file...", 1000);
  937. #endif
  938. }
  939. void updateShader()
  940. {
  941. startTimer (10);
  942. }
  943. Label statusLabel;
  944. private:
  945. void sliderValueChanged (Slider*) override
  946. {
  947. demo.scale = (float) sizeSlider .getValue();
  948. demo.rotationSpeed = (float) speedSlider.getValue();
  949. }
  950. enum { shaderLinkDelay = 500 };
  951. void codeDocumentTextInserted (const String& /*newText*/, int /*insertIndex*/) override
  952. {
  953. startTimer (shaderLinkDelay);
  954. }
  955. void codeDocumentTextDeleted (int /*startIndex*/, int /*endIndex*/) override
  956. {
  957. startTimer (shaderLinkDelay);
  958. }
  959. void timerCallback() override
  960. {
  961. stopTimer();
  962. demo.setShaderProgram (vertexDocument .getAllContent(),
  963. fragmentDocument.getAllContent());
  964. }
  965. void lookAndFeelChanged() override
  966. {
  967. auto editorBackground = getUIColourIfAvailable (LookAndFeel_V4::ColourScheme::UIColour::windowBackground,
  968. Colours::white);
  969. for (int i = tabbedComp.getNumTabs(); i >= 0; --i)
  970. tabbedComp.setTabBackgroundColour (i, editorBackground);
  971. vertexEditorComp .setColour (CodeEditorComponent::backgroundColourId, editorBackground);
  972. fragmentEditorComp.setColour (CodeEditorComponent::backgroundColourId, editorBackground);
  973. }
  974. OpenGLDemo& demo;
  975. Label speedLabel { {}, "Speed:" },
  976. zoomLabel { {}, "Zoom:" };
  977. CodeDocument vertexDocument, fragmentDocument;
  978. CodeEditorComponent vertexEditorComp { vertexDocument, nullptr },
  979. fragmentEditorComp { fragmentDocument, nullptr };
  980. TabbedComponent tabbedComp { TabbedButtonBar::TabsAtLeft };
  981. ComboBox presetBox, textureBox;
  982. Label presetLabel { {}, "Shader Preset:" },
  983. textureLabel { {}, "Texture:" };
  984. Slider speedSlider, sizeSlider;
  985. ToggleButton showBackgroundToggle { "Draw 2D graphics in background" };
  986. OwnedArray<OpenGLUtils::DemoTexture> textures;
  987. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DemoControlsOverlay)
  988. };
  989. std::unique_ptr<DemoControlsOverlay> controlsOverlay;
  990. float rotation = 0.0f;
  991. std::unique_ptr<OpenGLShaderProgram> shader;
  992. std::unique_ptr<OpenGLUtils::Shape> shape;
  993. std::unique_ptr<OpenGLUtils::Attributes> attributes;
  994. std::unique_ptr<OpenGLUtils::Uniforms> uniforms;
  995. OpenGLTexture texture;
  996. OpenGLUtils::DemoTexture* textureToUse = nullptr;
  997. OpenGLUtils::DemoTexture* lastTexture = nullptr;
  998. String newVertexShader, newFragmentShader, statusText;
  999. struct BackgroundStar
  1000. {
  1001. SlowerBouncingNumber x, y, hue, angle;
  1002. };
  1003. BackgroundStar stars[3];
  1004. //==============================================================================
  1005. void updateShader()
  1006. {
  1007. if (newVertexShader.isNotEmpty() || newFragmentShader.isNotEmpty())
  1008. {
  1009. std::unique_ptr<OpenGLShaderProgram> newShader (new OpenGLShaderProgram (openGLContext));
  1010. if (newShader->addVertexShader (OpenGLHelpers::translateVertexShaderToV3 (newVertexShader))
  1011. && newShader->addFragmentShader (OpenGLHelpers::translateFragmentShaderToV3 (newFragmentShader))
  1012. && newShader->link())
  1013. {
  1014. shape .reset();
  1015. attributes.reset();
  1016. uniforms .reset();
  1017. shader.reset (newShader.release());
  1018. shader->use();
  1019. shape .reset (new OpenGLUtils::Shape (openGLContext));
  1020. attributes.reset (new OpenGLUtils::Attributes (openGLContext, *shader));
  1021. uniforms .reset (new OpenGLUtils::Uniforms (openGLContext, *shader));
  1022. statusText = "GLSL: v" + String (OpenGLShaderProgram::getLanguageVersion(), 2);
  1023. }
  1024. else
  1025. {
  1026. statusText = newShader->getLastError();
  1027. }
  1028. triggerAsyncUpdate();
  1029. newVertexShader = {};
  1030. newFragmentShader = {};
  1031. }
  1032. }
  1033. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OpenGLDemo)
  1034. };