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.
 
 
 

585 rivejä
19 KiB

  1. //
  2. // Lol Engine — Fractal tutorial
  3. //
  4. // Copyright © 2011—2020 Sam Hocevar <sam@hocevar.net>
  5. //
  6. // Lol Engine is free software. It comes without any warranty, to
  7. // the extent permitted by applicable law. You can redistribute it
  8. // and/or modify it under the terms of the Do What the Fuck You Want
  9. // to Public License, Version 2, as published by the WTFPL Task Force.
  10. // See http://www.wtfpl.net/ for more details.
  11. //
  12. #if HAVE_CONFIG_H
  13. # include "config.h"
  14. #endif
  15. #include <memory>
  16. #include <sstream>
  17. #include <lol/engine.h>
  18. #include <lol/types/real.h>
  19. #include <lol/math/vector.h>
  20. #include <lol/math/transform.h>
  21. #include "loldebug.h"
  22. #define USE_REAL 0
  23. using namespace lol;
  24. LOLFX_RESOURCE_DECLARE(11_fractal);
  25. class Fractal : public WorldEntity
  26. {
  27. public:
  28. Fractal(ivec2 const &size)
  29. {
  30. /* Ensure texture size is a multiple of 16 for better aligned
  31. * data access. Store the dimensions of a texel for our shader,
  32. * as well as the half-size of the screen. */
  33. m_size = size;
  34. m_size.x = (m_size.x + 15) & ~15;
  35. m_size.y = (m_size.y + 15) & ~15;
  36. m_texel_settings = vec4(1.0, 1.0, 2.0, 2.0) / (vec4)m_size.xyxy;
  37. m_screen_settings = vec4(1.0, 1.0, 0.5, 0.5) * (vec4)m_size.xyxy;
  38. /* Window size decides the world aspect ratio. For instance, 640×480
  39. * will be mapped to (-0.66,-0.5) - (0.66,0.5). */
  40. m_window_size = Video::GetSize();
  41. if (m_window_size.y < m_window_size.x)
  42. m_window2world = 0.5 / m_window_size.y;
  43. else
  44. m_window2world = 0.5 / m_window_size.x;
  45. m_texel2world = (dvec2)m_window_size / (dvec2)m_size * m_window2world;
  46. m_oldmouse = ivec2(0, 0);
  47. m_pixels.resize(m_size.x * m_size.y);
  48. for (int i = 0; i < 4; i++)
  49. {
  50. m_deltashift[i] = real("0");
  51. m_deltascale[i] = real("1");
  52. m_dirty[i] = 2;
  53. }
  54. m_view.center = rcmplx(-0.75, 0.0);
  55. m_zoom_speed = 0.0;
  56. m_view.translate = rcmplx(0.0, 0.0);
  57. m_view.radius = 5.0;
  58. for (int i = 0; i < (MAX_ITERATIONS + 1) * PALETTE_STEP; i++)
  59. {
  60. double f = (double)i / PALETTE_STEP;
  61. vec3 hsv(lol::fmod(i * 0.001f, 1.f),
  62. 0.3 * lol::sin(f * 0.27 + 2.0) + 0.3,
  63. 0.3 * lol::sin(f * 0.21 - 2.6) + 0.6);
  64. vec3 rgb = color::hsv_to_rgb(hsv);
  65. if (f < 7.0)
  66. {
  67. rgb *= f < 1.0 ? 0.0 : (f - 1.0) / 6.0;
  68. }
  69. uint8_t red = (uint8_t)(rgb.r * 256);
  70. uint8_t green = (uint8_t)(rgb.g * 256);
  71. uint8_t blue = (uint8_t)(rgb.b * 256);
  72. m_palette.push(u8vec4(blue, green, red, 255));
  73. }
  74. m_zoomtext = new Text("", "data/font/ascii.png");
  75. m_zoomtext->SetPos(vec3(5, (float)m_window_size.y - 15, 1));
  76. Ticker::Ref(m_zoomtext);
  77. m_centertext = new Text("", "data/font/ascii.png");
  78. m_centertext->SetPos(vec3(5, (float)m_window_size.y - 29, 1));
  79. Ticker::Ref(m_centertext);
  80. m_mousetext = new Text("", "data/font/ascii.png");
  81. m_mousetext->SetPos(vec3(5, (float)m_window_size.y - 43, 1));
  82. Ticker::Ref(m_mousetext);
  83. m_position = vec3::zero;
  84. m_aabb.aa = m_position;
  85. m_aabb.bb = vec3((vec2)m_window_size, 0);
  86. if (thread::has_threads())
  87. {
  88. // Spawn worker threads and wait for their readiness
  89. for (int i = 0; i < MAX_THREADS; i++)
  90. m_threads[i] = new thread(std::bind(&Fractal::DoWorkHelper, this, std::placeholders::_1));
  91. for (int i = 0; i < MAX_THREADS; i++)
  92. m_spawnqueue.pop();
  93. }
  94. }
  95. ~Fractal()
  96. {
  97. if (thread::has_threads())
  98. {
  99. // Signal worker threads for completion and wait for them to quit
  100. for (int i = 0; i < MAX_THREADS; i++)
  101. m_jobqueue.push(-1);
  102. for (int i = 0; i < MAX_THREADS; i++)
  103. m_donequeue.pop();
  104. }
  105. Ticker::Unref(m_centertext);
  106. Ticker::Unref(m_mousetext);
  107. Ticker::Unref(m_zoomtext);
  108. }
  109. inline f128cmplx TexelToWorldOffset(vec2 texel)
  110. {
  111. double dx = (0.5 + texel.x - m_size.x / 2) * m_texel2world.x;
  112. double dy = (0.5 + m_size.y / 2 - texel.y) * m_texel2world.y;
  113. return m_view.radius * f128cmplx(dx, dy);
  114. }
  115. inline f128cmplx ScreenToWorldOffset(vec2 pixel)
  116. {
  117. /* No 0.5 offset here, because we want to be able to position the
  118. * mouse at (0,0) exactly. */
  119. double dx = pixel.x - m_window_size.x / 2;
  120. double dy = m_window_size.y / 2 - pixel.y;
  121. return m_view.radius * m_window2world * f128cmplx(dx, dy);
  122. }
  123. virtual void tick_game(float seconds)
  124. {
  125. WorldEntity::tick_game(seconds);
  126. auto mouse = input::mouse();
  127. auto keyboard = input::keyboard();
  128. vec2 mousepos(mouse->axis(input::axis::ScreenX),
  129. mouse->axis(input::axis::ScreenY));
  130. int prev_frame = (m_frame + 4) % 4;
  131. m_frame = (m_frame + 1) % 4;
  132. if (keyboard->key_pressed(input::key::SC_Space))
  133. {
  134. m_julia = !m_julia;
  135. if (m_julia)
  136. {
  137. m_saved_view = m_view;
  138. m_view.r0 = m_view.center + rcmplx(ScreenToWorldOffset(mousepos));
  139. }
  140. else
  141. {
  142. m_view = m_saved_view;
  143. }
  144. for (auto & flag : m_dirty)
  145. flag = 2;
  146. }
  147. rcmplx worldmouse = m_view.center + rcmplx(ScreenToWorldOffset(mousepos));
  148. if (mouse->button(input::button::BTN_Middle))
  149. {
  150. if (!m_drag)
  151. {
  152. m_oldmouse = (ivec2)mousepos;
  153. m_drag = true;
  154. }
  155. m_view.translate = rcmplx(ScreenToWorldOffset((vec2)m_oldmouse)
  156. - ScreenToWorldOffset(mousepos));
  157. /* XXX: the purpose of this hack is to avoid translating by
  158. * an exact number of pixels. If this were to happen, the step()
  159. * optimisation for i915 cards in our shader would behave
  160. * incorrectly because a quarter of the pixels in the image
  161. * would have tied rankings in the distance calculation. */
  162. m_view.translate *= real(1023.0 / 1024.0);
  163. m_oldmouse = (ivec2)mousepos;
  164. }
  165. else
  166. {
  167. m_drag = false;
  168. if (m_view.translate != rcmplx(0.0, 0.0))
  169. {
  170. m_view.translate *= real(std::pow(2.0, -seconds * 5.0));
  171. if ((double)norm(m_view.translate) < m_view.radius * 1e-4)
  172. m_view.translate = rcmplx(0.0, 0.0);
  173. }
  174. }
  175. bool hold_right = mouse->button(input::button::BTN_Right);
  176. bool hold_left = mouse->button(input::button::BTN_Left);
  177. if ((hold_right || hold_left) && mousepos.x != -1)
  178. {
  179. double zoom = hold_right ? -0.5 : 0.5;
  180. m_zoom_speed += zoom * seconds;
  181. if (m_zoom_speed / zoom > 5e-3f)
  182. m_zoom_speed = zoom * 5e-3f;
  183. }
  184. else if (m_zoom_speed)
  185. {
  186. m_zoom_speed *= std::pow(2.0, -seconds * 5.0);
  187. if (lol::abs(m_zoom_speed) < 1e-5 || m_drag)
  188. m_zoom_speed = 0.0;
  189. }
  190. if (m_zoom_speed || m_view.translate != rcmplx(0.0, 0.0))
  191. {
  192. rcmplx oldcenter = m_view.center;
  193. double oldradius = m_view.radius;
  194. double zoom = std::pow(2.0, seconds * 1e3f * m_zoom_speed);
  195. if (m_view.radius * zoom > 8.0)
  196. {
  197. m_zoom_speed *= -1.0;
  198. zoom = 8.0 / m_view.radius;
  199. }
  200. else if (m_view.radius * zoom < MAX_ZOOM)
  201. {
  202. m_zoom_speed *= -1.0;
  203. zoom = MAX_ZOOM / m_view.radius;
  204. }
  205. m_view.radius *= zoom;
  206. m_view.center += m_view.translate;
  207. m_view.center = (m_view.center - worldmouse) * real(zoom) + worldmouse;
  208. worldmouse = m_view.center
  209. + rcmplx(ScreenToWorldOffset(mousepos));
  210. /* Store the transformation properties to go from m_frame - 1
  211. * to m_frame. */
  212. m_deltashift[prev_frame] = (m_view.center - oldcenter) / real(oldradius);
  213. m_deltashift[prev_frame].x /= m_size.x * m_texel2world.x;
  214. m_deltashift[prev_frame].y /= m_size.y * m_texel2world.y;
  215. m_deltascale[prev_frame] = m_view.radius / oldradius;
  216. for (auto & flag : m_dirty)
  217. flag = 2;
  218. }
  219. else
  220. {
  221. /* If settings didn't change, set transformation from previous
  222. * frame to identity. */
  223. m_deltashift[prev_frame] = real::R_0();
  224. m_deltascale[prev_frame] = real::R_1();
  225. }
  226. /* Transformation from current frame to current frame is always
  227. * identity. */
  228. m_zoom_settings[m_frame][0] = 0.0f;
  229. m_zoom_settings[m_frame][1] = 0.0f;
  230. m_zoom_settings[m_frame][2] = 1.0f;
  231. /* Compute transformation from other frames to current frame */
  232. for (int i = 0; i < 3; i++)
  233. {
  234. int prev_index = (m_frame + 4 - i) % 4;
  235. int cur_index = (m_frame + 3 - i) % 4;
  236. auto t0 = (real)m_zoom_settings[prev_index][0] * m_deltascale[cur_index] + m_deltashift[cur_index].x;
  237. auto t1 = (real)m_zoom_settings[prev_index][1] * m_deltascale[cur_index] + m_deltashift[cur_index].y;
  238. auto t2 = (real)m_zoom_settings[prev_index][2] * m_deltascale[cur_index];
  239. m_zoom_settings[cur_index][0] = float(t0);
  240. m_zoom_settings[cur_index][1] = float(t1);
  241. m_zoom_settings[cur_index][2] = float(t2);
  242. }
  243. /* Precompute texture offset change instead of doing it in GLSL */
  244. for (int i = 0; i < 4; i++)
  245. {
  246. m_zoom_settings[i][0] += 0.5f * (1.0f - m_zoom_settings[i][2]);
  247. m_zoom_settings[i][1] -= 0.5f * (1.0f - m_zoom_settings[i][2]);
  248. }
  249. m_centertext->SetText("center: " + m_view.center.x.str(30) + " " + m_view.center.y.str(30));
  250. m_mousetext->SetText(" mouse: " + worldmouse.x.str(30) + " " + worldmouse.y.str(30));
  251. std::stringstream ss;
  252. ss << '[' << (m_julia ? "Julia" : "Mandelbrot") << "] zoom: " << 1.0 / m_view.radius;
  253. m_zoomtext->SetText(ss.str());
  254. if (m_dirty[m_frame])
  255. {
  256. m_dirty[m_frame]--;
  257. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  258. {
  259. if (thread::has_threads())
  260. m_jobqueue.push(i);
  261. else
  262. DoWork(i);
  263. }
  264. }
  265. }
  266. void DoWorkHelper(thread *)
  267. {
  268. m_spawnqueue.push(0);
  269. for ( ; ; )
  270. {
  271. int line = m_jobqueue.pop();
  272. if (line == -1)
  273. break;
  274. DoWork(line);
  275. m_donequeue.push(0);
  276. }
  277. m_donequeue.push(0);
  278. };
  279. void DoWork(int line)
  280. {
  281. double const maxsqlen = 1024;
  282. double const k1 = 1.0 / (1 << 10) / (std::log(maxsqlen) / std::log(2.0));
  283. int jmin = ((m_frame + 1) % 4) / 2 + line;
  284. int jmax = jmin + MAX_LINES * 2;
  285. if (jmax > m_size.y)
  286. jmax = m_size.y;
  287. u8vec4 *pixelstart = m_pixels.data()
  288. + m_size.x * (m_size.y / 4 * m_frame + line / 4);
  289. #if USE_REAL
  290. rcmplx c = (rcmplx)m_view.center;
  291. rcmplx jr0 = (rcmplx)m_view.r0;
  292. #else
  293. f128cmplx c = (f128cmplx)m_view.center;
  294. f128cmplx jr0 = (f128cmplx)m_view.r0;
  295. #endif
  296. for (int j = jmin; j < jmax; j += 2)
  297. for (int i = m_frame % 2; i < m_size.x; i += 2)
  298. {
  299. #if USE_REAL
  300. real xr, yr, x0, y0, x1, y1, x2, y2, x3, y3;
  301. real sqx0, sqy0, sqx1, sqy1, sqx2, sqy2, sqx3, sqy3;
  302. rcmplx z0 = c + rcmplx(TexelToWorldOffset(vec2(ivec2(i, j))));
  303. rcmplx r0 = m_julia ? jr0 : z0;
  304. #else
  305. ldouble xr, yr, x0, y0, x1, y1, x2, y2, x3, y3;
  306. ldouble sqx0, sqy0, sqx1, sqy1, sqx2, sqy2, sqx3, sqy3;
  307. f128cmplx z0 = c + TexelToWorldOffset(vec2(ivec2(i, j)));
  308. f128cmplx r0 = m_julia ? jr0 : z0;
  309. #endif
  310. x0 = z0.x; y0 = z0.y;
  311. xr = r0.x; yr = r0.y;
  312. sqx0 = x0 * x0; sqy0 = y0 * y0;
  313. int iter = MAX_ITERATIONS - 4;
  314. for (;;)
  315. {
  316. /* Unroll the loop: tests are more expensive to do at each
  317. * iteration than the few extra multiplications, at least
  318. * with floats/doubles. */
  319. x1 = sqx0 - sqy0 + xr; y1 = x0 * y0 + x0 * y0 + yr;
  320. sqx1 = x1 * x1; sqy1 = y1 * y1;
  321. x2 = sqx1 - sqy1 + xr; y2 = x1 * y1 + x1 * y1 + yr;
  322. sqx2 = x2 * x2; sqy2 = y2 * y2;
  323. x3 = sqx2 - sqy2 + xr; y3 = x2 * y2 + x2 * y2 + yr;
  324. sqx3 = x3 * x3; sqy3 = y3 * y3;
  325. x0 = sqx3 - sqy3 + xr; y0 = x3 * y3 + x3 * y3 + yr;
  326. sqx0 = x0 * x0; sqy0 = y0 * y0;
  327. if ((double)sqx0 + (double)sqy0 >= maxsqlen)
  328. break;
  329. iter -= 4;
  330. if (iter < 4)
  331. break;
  332. }
  333. if (iter)
  334. {
  335. double n = (double)sqx0 + (double)sqy0;
  336. if ((double)sqx1 + (double)sqy1 >= maxsqlen)
  337. {
  338. iter += 3; n = (double)sqx1 + (double)sqy1;
  339. }
  340. else if ((double)sqx2 + (double)sqy2 >= maxsqlen)
  341. {
  342. iter += 2; n = (double)sqx2 + (double)sqy2;
  343. }
  344. else if ((double)sqx3 + (double)sqy3 >= maxsqlen)
  345. {
  346. iter += 1; n = (double)sqx3 + (double)sqy3;
  347. }
  348. if (n > maxsqlen * maxsqlen)
  349. n = maxsqlen * maxsqlen;
  350. /* Approximate log(sqrt(n))/log(sqrt(maxsqlen)) */
  351. double f = iter;
  352. union { double n; uint64_t x; } u = { (double)n };
  353. double k = (double)(u.x >> 42) - (((1 << 10) - 1) << 10);
  354. k *= k1;
  355. /* Approximate log2(k) in [1,2]. */
  356. f += (- 0.344847817623168308695977510213252644185 * k
  357. + 2.024664188044341212602376988171727038739) * k
  358. - 1.674876738008591047163498125918330313237;
  359. *pixelstart++ = m_palette[(int)(f * PALETTE_STEP)];
  360. }
  361. else
  362. {
  363. *pixelstart++ = u8vec4(0, 0, 0, 255);
  364. }
  365. }
  366. }
  367. virtual bool init_draw() override
  368. {
  369. float const vertices[] =
  370. {
  371. 1.0f, 1.0f,
  372. -1.0f, 1.0f,
  373. -1.0f, -1.0f,
  374. -1.0f, -1.0f,
  375. 1.0f, -1.0f,
  376. 1.0f, 1.0f,
  377. };
  378. float const texcoords[] =
  379. {
  380. 1.0f, 1.0f,
  381. 0.0f, 1.0f,
  382. 0.0f, 0.0f,
  383. 0.0f, 0.0f,
  384. 1.0f, 0.0f,
  385. 1.0f, 1.0f,
  386. };
  387. /* Create a texture of half the width and twice the height
  388. * so that we can upload four different subimages each frame. */
  389. m_texture = std::make_shared<Texture>(ivec2(m_size.x / 2, m_size.y * 2),
  390. PixelFormat::RGBA_8);
  391. /* Ensure the texture data is complete at least once, otherwise
  392. * uploading subimages will not work. */
  393. m_texture->SetData(m_pixels.data());
  394. m_shader = Shader::Create(LOLFX_RESOURCE_NAME(11_fractal));
  395. m_vertexattrib = m_shader->GetAttribLocation(VertexUsage::Position, 0);
  396. m_texattrib = m_shader->GetAttribLocation(VertexUsage::TexCoord, 0);
  397. m_texuni = m_shader->GetUniformLocation("u_texture");
  398. m_texeluni = m_shader->GetUniformLocation("u_texel_size");
  399. m_screenuni = m_shader->GetUniformLocation("u_screen_size");
  400. m_zoomuni = m_shader->GetUniformLocation("u_zoom_settings");
  401. m_vdecl = std::make_shared<VertexDeclaration>(
  402. VertexStream<vec2>(VertexUsage::Position),
  403. VertexStream<vec2>(VertexUsage::TexCoord));
  404. m_vbo = std::make_shared<VertexBuffer>(sizeof(vertices));
  405. m_vbo->set_data(vertices, sizeof(vertices));
  406. m_tbo = std::make_shared<VertexBuffer>(sizeof(texcoords));
  407. m_tbo->set_data(texcoords, sizeof(texcoords));
  408. return true;
  409. }
  410. virtual void tick_draw(float seconds, Scene &scene) override
  411. {
  412. WorldEntity::tick_draw(seconds, scene);
  413. m_texture->Bind();
  414. if (m_dirty[m_frame])
  415. {
  416. if (thread::has_threads())
  417. {
  418. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  419. m_donequeue.pop();
  420. }
  421. m_dirty[m_frame]--;
  422. m_texture->SetSubData(ivec2(0, m_frame * m_size.y / 2),
  423. m_size / 2,
  424. &m_pixels[m_size.x * m_size.y / 4 * m_frame]);
  425. }
  426. m_shader->Bind();
  427. m_shader->SetUniform(m_texuni, m_texture->GetTextureUniform(), 0);
  428. m_shader->SetUniform(m_texeluni, m_texel_settings);
  429. m_shader->SetUniform(m_screenuni, m_screen_settings);
  430. m_shader->SetUniform(m_zoomuni, m_zoom_settings);
  431. m_vdecl->Bind();
  432. m_vdecl->SetStream(m_vbo, m_vertexattrib);
  433. m_vdecl->SetStream(m_tbo, m_texattrib);
  434. m_texture->Bind();
  435. m_vdecl->DrawElements(MeshPrimitive::Triangles, 0, 6);
  436. m_vdecl->Unbind();
  437. }
  438. virtual bool release_draw() override
  439. {
  440. m_shader.reset();
  441. m_vdecl.reset();
  442. m_vbo.reset();
  443. m_tbo.reset();
  444. m_texture.reset();
  445. return true;
  446. }
  447. private:
  448. static int const MAX_ITERATIONS = 400;
  449. static int const PALETTE_STEP = 32;
  450. static int const MAX_THREADS = 8;
  451. static int const MAX_LINES = 8;
  452. // 1e-14 for doubles, 1e-17 for long doubles
  453. static double constexpr MAX_ZOOM = 1e-17;
  454. ivec2 m_size, m_window_size, m_oldmouse;
  455. double m_window2world;
  456. dvec2 m_texel2world;
  457. array<u8vec4> m_pixels, m_palette;
  458. std::shared_ptr<Shader> m_shader;
  459. ShaderAttrib m_vertexattrib, m_texattrib;
  460. ShaderUniform m_texuni, m_texeluni, m_screenuni, m_zoomuni;
  461. std::shared_ptr<VertexDeclaration> m_vdecl;
  462. std::shared_ptr<VertexBuffer> m_vbo, m_tbo;
  463. std::shared_ptr<Texture> m_texture;
  464. int m_frame = -1, m_slices = 4, m_dirty[4];
  465. bool m_drag = false;
  466. struct view_settings
  467. {
  468. rcmplx center, translate, r0;
  469. double radius;
  470. };
  471. view_settings m_view, m_saved_view;
  472. rcmplx m_deltashift[4];
  473. real m_deltascale[4];
  474. double m_zoom_speed;
  475. bool m_julia = false;
  476. vec4 m_texel_settings, m_screen_settings;
  477. mat4 m_zoom_settings;
  478. // Worker threads
  479. thread *m_threads[MAX_THREADS];
  480. queue<int> m_spawnqueue, m_jobqueue, m_donequeue;
  481. // Debug information
  482. Text *m_centertext, *m_mousetext, *m_zoomtext;
  483. };
  484. int main(int argc, char **argv)
  485. {
  486. ivec2 window_size(640, 480);
  487. sys::init(argc, argv);
  488. Application app("Tutorial 11: Fractal", window_size, 60.0f);
  489. new DebugFps(5, 5);
  490. new Fractal(window_size);
  491. //new DebugRecord("fractalol.ogm", 60.0f);
  492. app.Run();
  493. return EXIT_SUCCESS;
  494. }