Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

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