Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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