source: trunk/demos/tutorial/11_fractal.cpp @ 2812

Last change on this file since 2812 was 2812, checked in by lolbot, 6 years ago

fixed 10 files out of 2754:

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