Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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