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.
 
 
 

599 line
20 KiB

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