Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

11_fractal.cpp 19 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582
  1. //
  2. // Lol Engine - Fractal tutorial
  3. //
  4. // Copyright: (c) 2011-2013 Sam Hocevar <sam@hocevar.net>
  5. // This program is free software; you can redistribute it and/or
  6. // modify it under the terms of the Do What The Fuck You Want To
  7. // Public License, Version 2, as published by Sam Hocevar. See
  8. // http://www.wtfpl.net/ for more details.
  9. //
  10. #if defined HAVE_CONFIG_H
  11. # include "config.h"
  12. #endif
  13. #include <cstring>
  14. #include <cstdio>
  15. #include "core.h"
  16. #include "loldebug.h"
  17. using namespace lol;
  18. LOLFX_RESOURCE_DECLARE(11_fractal);
  19. class Fractal : public WorldEntity
  20. {
  21. public:
  22. Fractal(ivec2 const &size)
  23. {
  24. /* Ensure texture size is a multiple of 16 for better aligned
  25. * data access. Store the dimensions of a texel for our shader,
  26. * as well as the half-size of the screen. */
  27. m_size = size;
  28. m_size.x = (m_size.x + 15) & ~15;
  29. m_size.y = (m_size.y + 15) & ~15;
  30. m_texel_settings = vec4(1.0, 1.0, 2.0, 2.0) / m_size.xyxy;
  31. m_screen_settings = vec4(1.0, 1.0, 0.5, 0.5) * m_size.xyxy;
  32. /* Window size decides the world aspect ratio. For instance, 640×480
  33. * will be mapped to (-0.66,-0.5) - (0.66,0.5). */
  34. #if !defined __native_client__
  35. m_window_size = Video::GetSize();
  36. #else
  37. /* FIXME: it's illegal to call this on the game thread! */
  38. m_window_size = ivec2(640, 480);
  39. #endif
  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. #if defined __CELLOS_LV2__ || defined _XBOX
  56. //m_center = rcmplx(-.22815528839841, -1.11514249704382);
  57. //m_center = rcmplx(0.001643721971153, 0.822467633298876);
  58. m_center = rcmplx("-0.65823419062254", "0.50221777363480");
  59. m_zoom_speed = -0.025;
  60. #else
  61. m_center = rcmplx(-0.75, 0.0);
  62. m_zoom_speed = 0.0;
  63. #endif
  64. m_translate = rcmplx(0.0, 0.0);
  65. m_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. double r = 0.5 * lol::sin(f * 0.27 + 2.0) + 0.5;
  72. double g = 0.5 * lol::sin(f * 0.17 - 1.8) + 0.5;
  73. double b = 0.5 * lol::sin(f * 0.21 - 2.6) + 0.5;
  74. if (f < 7.0)
  75. {
  76. f = f < 1.0 ? 0.0 : (f - 1.0) / 6.0;
  77. r *= f;
  78. g *= f;
  79. b *= f;
  80. }
  81. uint8_t red = r * 255.99f;
  82. uint8_t green = g * 255.99f;
  83. uint8_t blue = b * 255.99f;
  84. #if defined __CELLOS_LV2__ || defined _XBOX
  85. m_palette.Push(u8vec4(255, red, green, blue));
  86. #elif defined __native_client__
  87. m_palette.Push(u8vec4(red, green, blue, 255));
  88. #else
  89. m_palette.Push(u8vec4(blue, green, red, 255));
  90. #endif
  91. }
  92. #if !defined __native_client__
  93. m_centertext = new Text(NULL, "data/font/ascii.png");
  94. m_centertext->SetPos(ivec3(5, m_window_size.y - 15, 1));
  95. Ticker::Ref(m_centertext);
  96. m_mousetext = new Text(NULL, "data/font/ascii.png");
  97. m_mousetext->SetPos(ivec3(5, m_window_size.y - 29, 1));
  98. Ticker::Ref(m_mousetext);
  99. m_zoomtext = new Text(NULL, "data/font/ascii.png");
  100. m_zoomtext->SetPos(ivec3(5, m_window_size.y - 43, 1));
  101. Ticker::Ref(m_zoomtext);
  102. #endif
  103. m_position = ivec3(0, 0, 0);
  104. m_bbox[0] = m_position;
  105. m_bbox[1] = ivec3(m_window_size, 0);
  106. //Input::TrackMouse(this);
  107. #if LOL_FEATURE_THREADS
  108. /* Spawn worker threads and wait for their readiness. */
  109. for (int i = 0; i < MAX_THREADS; i++)
  110. m_threads[i] = new Thread(DoWorkHelper, this);
  111. for (int i = 0; i < MAX_THREADS; i++)
  112. m_spawnqueue.Pop();
  113. #endif
  114. }
  115. ~Fractal()
  116. {
  117. #if LOL_FEATURE_THREADS
  118. /* Signal worker threads for completion and wait for
  119. * them to quit. */
  120. for (int i = 0; i < MAX_THREADS; i++)
  121. m_jobqueue.Push(-1);
  122. for (int i = 0; i < MAX_THREADS; i++)
  123. m_donequeue.Pop();
  124. #endif
  125. //Input::UntrackMouse(this);
  126. #if !defined __native_client__
  127. Ticker::Unref(m_centertext);
  128. Ticker::Unref(m_mousetext);
  129. Ticker::Unref(m_zoomtext);
  130. #endif
  131. }
  132. inline dcmplx TexelToWorldOffset(vec2 texel)
  133. {
  134. double dx = (0.5 + texel.x - m_size.x / 2) * m_texel2world.x;
  135. double dy = (0.5 + m_size.y / 2 - texel.y) * m_texel2world.y;
  136. return m_radius * dcmplx(dx, dy);
  137. }
  138. inline dcmplx ScreenToWorldOffset(vec2 pixel)
  139. {
  140. /* No 0.5 offset here, because we want to be able to position the
  141. * mouse at (0,0) exactly. */
  142. double dx = pixel.x - m_window_size.x / 2;
  143. double dy = m_window_size.y / 2 - pixel.y;
  144. return m_radius * m_window2world * dcmplx(dx, dy);
  145. }
  146. virtual void TickGame(float seconds)
  147. {
  148. WorldEntity::TickGame(seconds);
  149. ivec2 mousepos = ivec2::zero; /* FIXME: input */
  150. int prev_frame = (m_frame + 4) % 4;
  151. m_frame = (m_frame + 1) % 4;
  152. rcmplx worldmouse = m_center + rcmplx(ScreenToWorldOffset(mousepos));
  153. uint32_t buttons = 0;
  154. //uint32_t buttons = Input::GetMouseButtons();
  155. #if !defined __CELLOS_LV2__ && !defined _XBOX
  156. if (buttons & 0x2)
  157. {
  158. if (!m_drag)
  159. {
  160. m_oldmouse = mousepos;
  161. m_drag = true;
  162. }
  163. m_translate = ScreenToWorldOffset(m_oldmouse)
  164. - ScreenToWorldOffset(mousepos);
  165. /* XXX: the purpose of this hack is to avoid translating by
  166. * an exact number of pixels. If this were to happen, the step()
  167. * optimisation for i915 cards in our shader would behave
  168. * incorrectly because a quarter of the pixels in the image
  169. * would have tie rankings in the distance calculation. */
  170. m_translate *= real(1023.0 / 1024.0);
  171. m_oldmouse = mousepos;
  172. }
  173. else
  174. {
  175. m_drag = false;
  176. if (m_translate != rcmplx(0.0, 0.0))
  177. {
  178. m_translate *= real(std::pow(2.0, -seconds * 5.0));
  179. if ((double)m_translate.norm() < m_radius * 1e-4)
  180. m_translate = rcmplx(0.0, 0.0);
  181. }
  182. }
  183. if (buttons & 0x5 && mousepos.x != -1)
  184. {
  185. double zoom = (buttons & 0x1) ? -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. #endif
  197. if (m_zoom_speed || m_translate != rcmplx(0.0, 0.0))
  198. {
  199. rcmplx oldcenter = m_center;
  200. double oldradius = m_radius;
  201. double zoom = std::pow(2.0, seconds * 1e3f * m_zoom_speed);
  202. if (m_radius * zoom > 8.0)
  203. {
  204. m_zoom_speed *= -1.0;
  205. zoom = 8.0 / m_radius;
  206. }
  207. else if (m_radius * zoom < 1e-14)
  208. {
  209. m_zoom_speed *= -1.0;
  210. zoom = 1e-14 / m_radius;
  211. }
  212. m_radius *= zoom;
  213. #if !defined __CELLOS_LV2__ && !defined _XBOX
  214. m_center += m_translate;
  215. m_center = (m_center - worldmouse) * real(zoom) + worldmouse;
  216. worldmouse = m_center + rcmplx(ScreenToWorldOffset(mousepos));
  217. #endif
  218. /* Store the transformation properties to go from m_frame - 1
  219. * to m_frame. */
  220. m_deltashift[prev_frame] = (m_center - oldcenter) / real(oldradius);
  221. m_deltashift[prev_frame].x /= m_size.x * m_texel2world.x;
  222. m_deltashift[prev_frame].y /= m_size.y * m_texel2world.y;
  223. m_deltascale[prev_frame] = m_radius / oldradius;
  224. m_dirty[0] = m_dirty[1] = m_dirty[2] = m_dirty[3] = 2;
  225. }
  226. else
  227. {
  228. /* If settings didn't change, set transformation from previous
  229. * frame to identity. */
  230. m_deltashift[prev_frame] = real::R_0();
  231. m_deltascale[prev_frame] = real::R_1();
  232. }
  233. /* Transformation from current frame to current frame is always
  234. * identity. */
  235. m_zoom_settings[m_frame][0] = 0.0f;
  236. m_zoom_settings[m_frame][1] = 0.0f;
  237. m_zoom_settings[m_frame][2] = 1.0f;
  238. /* Compute transformation from other frames to current frame */
  239. for (int i = 0; i < 3; i++)
  240. {
  241. int prev_index = (m_frame + 4 - i) % 4;
  242. int cur_index = (m_frame + 3 - i) % 4;
  243. m_zoom_settings[cur_index][0] = (real)m_zoom_settings[prev_index][0] * m_deltascale[cur_index] + m_deltashift[cur_index].x;
  244. m_zoom_settings[cur_index][1] = (real)m_zoom_settings[prev_index][1] * m_deltascale[cur_index] + m_deltashift[cur_index].y;
  245. m_zoom_settings[cur_index][2] = (real)m_zoom_settings[prev_index][2] * m_deltascale[cur_index];
  246. }
  247. /* Precompute texture offset change instead of doing it in GLSL */
  248. for (int i = 0; i < 4; i++)
  249. {
  250. m_zoom_settings[i][0] += 0.5 * (1.0 - m_zoom_settings[i][2]);
  251. m_zoom_settings[i][1] -= 0.5 * (1.0 - m_zoom_settings[i][2]);
  252. }
  253. #if !defined __native_client__
  254. char buf[256];
  255. std::sprintf(buf, "center: ");
  256. m_center.x.sprintf(buf + strlen(buf), 30);
  257. std::sprintf(buf + strlen(buf), " ");
  258. m_center.y.sprintf(buf + strlen(buf), 30);
  259. m_centertext->SetText(buf);
  260. std::sprintf(buf, " mouse: ");
  261. worldmouse.x.sprintf(buf + strlen(buf), 30);
  262. std::sprintf(buf + strlen(buf), " ");
  263. worldmouse.y.sprintf(buf + strlen(buf), 30);
  264. m_mousetext->SetText(buf);
  265. std::sprintf(buf, " zoom: %g", 1.0 / m_radius);
  266. m_zoomtext->SetText(buf);
  267. #endif
  268. if (m_dirty[m_frame])
  269. {
  270. m_dirty[m_frame]--;
  271. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  272. {
  273. #if LOL_FEATURE_THREADS
  274. m_jobqueue.Push(i);
  275. #else
  276. DoWork(i);
  277. #endif
  278. }
  279. }
  280. }
  281. #if LOL_FEATURE_THREADS
  282. static void *DoWorkHelper(void *data)
  283. {
  284. Fractal *that = (Fractal *)data;
  285. that->m_spawnqueue.Push(0);
  286. for ( ; ; )
  287. {
  288. int line = that->m_jobqueue.Pop();
  289. if (line == -1)
  290. break;
  291. that->DoWork(line);
  292. that->m_donequeue.Push(0);
  293. }
  294. that->m_donequeue.Push(0);
  295. return NULL;
  296. };
  297. #endif
  298. void DoWork(int line)
  299. {
  300. double const maxsqlen = 1024;
  301. double const k1 = 1.0 / (1 << 10) / (std::log(maxsqlen) / std::log(2.0));
  302. int jmin = ((m_frame + 1) % 4) / 2 + line;
  303. int jmax = jmin + MAX_LINES * 2;
  304. if (jmax > m_size.y)
  305. jmax = m_size.y;
  306. u8vec4 *m_pixelstart = &m_pixels[0]
  307. + m_size.x * (m_size.y / 4 * m_frame + line / 4);
  308. dcmplx c = (dcmplx)m_center;
  309. for (int j = jmin; j < jmax; j += 2)
  310. for (int i = m_frame % 2; i < m_size.x; i += 2)
  311. {
  312. double xr, yr, x0, y0, x1, y1, x2, y2, x3, y3;
  313. dcmplx z0 = c + TexelToWorldOffset(ivec2(i, j));
  314. //dcmplx r0(0.28693186889504513, 0.014286693904085048);
  315. //dcmplx r0(0.001643721971153, 0.822467633298876);
  316. //dcmplx r0(-1.207205434596, 0.315432814901);
  317. //dcmplx r0(-0.79192956889854, -0.14632423080102);
  318. //dcmplx r0(0.3245046418497685, 0.04855101129280834);
  319. dcmplx r0 = z0;
  320. x0 = z0.x; y0 = z0.y;
  321. xr = r0.x; yr = r0.y;
  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. */
  327. x1 = x0 * x0 - y0 * y0 + xr;
  328. y1 = x0 * y0 + x0 * y0 + yr;
  329. x2 = x1 * x1 - y1 * y1 + xr;
  330. y2 = x1 * y1 + x1 * y1 + yr;
  331. x3 = x2 * x2 - y2 * y2 + xr;
  332. y3 = x2 * y2 + x2 * y2 + yr;
  333. x0 = x3 * x3 - y3 * y3 + xr;
  334. y0 = x3 * y3 + x3 * y3 + yr;
  335. if (x0 * x0 + y0 * y0 >= maxsqlen)
  336. break;
  337. iter -= 4;
  338. if (iter < 4)
  339. break;
  340. }
  341. if (iter)
  342. {
  343. double n = x0 * x0 + y0 * y0;
  344. if (x1 * x1 + y1 * y1 >= maxsqlen)
  345. {
  346. iter += 3; n = x1 * x1 + y1 * y1;
  347. }
  348. else if (x2 * x2 + y2 * y2 >= maxsqlen)
  349. {
  350. iter += 2; n = x2 * x2 + y2 * y2;
  351. }
  352. else if (x3 * x3 + y3 * y3 >= maxsqlen)
  353. {
  354. iter += 1; n = x3 * x3 + y3 * y3;
  355. }
  356. if (n > maxsqlen * maxsqlen)
  357. n = maxsqlen * maxsqlen;
  358. /* Approximate log(sqrt(n))/log(sqrt(maxsqlen)) */
  359. double f = iter;
  360. union { double n; uint64_t x; } u = { n };
  361. double k = (u.x >> 42) - (((1 << 10) - 1) << 10);
  362. k *= k1;
  363. /* Approximate log2(k) in [1,2]. */
  364. f += (- 0.344847817623168308695977510213252644185 * k
  365. + 2.024664188044341212602376988171727038739) * k
  366. - 1.674876738008591047163498125918330313237;
  367. *m_pixelstart++ = m_palette[(int)(f * PALETTE_STEP)];
  368. }
  369. else
  370. {
  371. #if defined __CELLOS_LV2__ || defined _XBOX
  372. *m_pixelstart++ = u8vec4(255, 0, 0, 0);
  373. #else
  374. *m_pixelstart++ = u8vec4(0, 0, 0, 255);
  375. #endif
  376. }
  377. }
  378. }
  379. virtual void TickDraw(float seconds)
  380. {
  381. WorldEntity::TickDraw(seconds);
  382. static float const vertices[] =
  383. {
  384. 1.0f, 1.0f,
  385. -1.0f, 1.0f,
  386. -1.0f, -1.0f,
  387. -1.0f, -1.0f,
  388. 1.0f, -1.0f,
  389. 1.0f, 1.0f,
  390. };
  391. static float const texcoords[] =
  392. {
  393. 1.0f, 1.0f,
  394. 0.0f, 1.0f,
  395. 0.0f, 0.0f,
  396. 0.0f, 0.0f,
  397. 1.0f, 0.0f,
  398. 1.0f, 1.0f,
  399. };
  400. if (!m_ready)
  401. {
  402. /* Create a texture of half the width and twice the height
  403. * so that we can upload four different subimages each frame. */
  404. m_texture = new Texture(ivec2(m_size.x / 2, m_size.y * 2),
  405. PixelFormat::ABGR_8);
  406. /* Ensure the texture data is complete at least once, otherwise
  407. * uploading subimages will not work. */
  408. m_texture->SetData(&m_pixels[0]);
  409. m_shader = Shader::Create(LOLFX_RESOURCE_NAME(11_fractal));
  410. m_vertexattrib = m_shader->GetAttribLocation(VertexUsage::Position, 0);
  411. m_texattrib = m_shader->GetAttribLocation(VertexUsage::TexCoord, 0);
  412. m_texeluni = m_shader->GetUniformLocation("u_TexelSize");
  413. m_screenuni = m_shader->GetUniformLocation("u_ScreenSize");
  414. m_zoomuni = m_shader->GetUniformLocation("u_ZoomSettings");
  415. m_vdecl =
  416. new VertexDeclaration(VertexStream<vec2>(VertexUsage::Position),
  417. VertexStream<vec2>(VertexUsage::TexCoord));
  418. m_vbo = new VertexBuffer(sizeof(vertices));
  419. m_tbo = new VertexBuffer(sizeof(texcoords));
  420. void *tmp = m_vbo->Lock(0, 0);
  421. memcpy(tmp, vertices, sizeof(vertices));
  422. m_vbo->Unlock();
  423. tmp = m_tbo->Lock(0, 0);
  424. memcpy(tmp, texcoords, sizeof(texcoords));
  425. m_tbo->Unlock();
  426. /* FIXME: this object never cleans up */
  427. m_ready = true;
  428. }
  429. m_texture->Bind();
  430. if (m_dirty[m_frame])
  431. {
  432. #if LOL_FEATURE_THREADS
  433. for (int i = 0; i < m_size.y; i += MAX_LINES * 2)
  434. m_donequeue.Pop();
  435. #endif
  436. m_dirty[m_frame]--;
  437. #if defined __CELLOS_LV2__
  438. /* glTexSubImage2D is extremely slow on the PS3, to the point
  439. * that uploading the whole texture is 40 times faster. */
  440. m_texture->SetData(&m_pixels[0]);
  441. #else
  442. m_texture->SetSubData(ivec2(0, m_frame * m_size.y / 2),
  443. m_size / 2,
  444. &m_pixels[m_size.x * m_size.y / 4 * m_frame]);
  445. #endif
  446. }
  447. m_shader->Bind();
  448. m_shader->SetUniform(m_texeluni, m_texel_settings);
  449. m_shader->SetUniform(m_screenuni, m_screen_settings);
  450. m_shader->SetUniform(m_zoomuni, m_zoom_settings);
  451. m_vdecl->Bind();
  452. m_vdecl->SetStream(m_vbo, m_vertexattrib);
  453. m_vdecl->SetStream(m_tbo, m_texattrib);
  454. m_texture->Bind();
  455. m_vdecl->DrawElements(MeshPrimitive::Triangles, 0, 6);
  456. m_vdecl->Unbind();
  457. }
  458. private:
  459. static int const MAX_ITERATIONS = 340;
  460. static int const PALETTE_STEP = 32;
  461. static int const MAX_THREADS = 8;
  462. static int const MAX_LINES = 8;
  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. Shader *m_shader;
  468. ShaderAttrib m_vertexattrib, m_texattrib;
  469. ShaderUniform m_texeluni, m_screenuni, m_zoomuni;
  470. VertexDeclaration *m_vdecl;
  471. VertexBuffer *m_vbo, *m_tbo;
  472. Texture *m_texture;
  473. int m_frame, m_slices, m_dirty[4];
  474. bool m_ready, m_drag;
  475. rcmplx m_deltashift[4], m_center, m_translate;
  476. real m_deltascale[4];
  477. double m_zoom_speed, m_radius;
  478. vec4 m_texel_settings, m_screen_settings;
  479. mat4 m_zoom_settings;
  480. #if LOL_FEATURE_THREADS
  481. /* Worker threads */
  482. Thread *m_threads[MAX_THREADS];
  483. Queue<int> m_spawnqueue, m_jobqueue, m_donequeue;
  484. #endif
  485. #if !defined __native_client__
  486. /* Debug information */
  487. Text *m_centertext, *m_mousetext, *m_zoomtext;
  488. #endif
  489. };
  490. int main(int argc, char **argv)
  491. {
  492. ivec2 window_size(640, 480);
  493. System::Init(argc, argv);
  494. Application app("Tutorial 3: 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. }