25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

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