Merge branch 'master' of git.ucc.asn.au:/ipdf/code
[ipdf/code.git] / src / view.cpp
1 #include "view.h"
2 #include "bufferbuilder.h"
3 #include "screen.h"
4 #include "gl_core44.h"
5
6 #ifndef CONTROLPANEL_DISABLED
7         #include "controlpanel.h"
8 #endif //CONTROLPANEL_DISABLED
9
10 using namespace IPDF;
11 using namespace std;
12
13 /**
14  * Constructs a view
15  * Allocates memory for ObjectRenderers
16  * @param document - The document to associate the View with
17  * @param bounds - Initial bounds of the View
18  * @param colour - Colour to use for rendering this view. TODO: Make sure this actually works, or just remove it
19  */
20 View::View(Document & document, Screen & screen, const Rect & bounds, const Colour & colour)
21         : m_use_gpu_transform(USE_GPU_TRANSFORM), m_use_gpu_rendering(USE_GPU_RENDERING), m_bounds_dirty(true), m_buffer_dirty(true), 
22                 m_render_dirty(true), m_document(document), m_screen(screen), m_cached_display(), m_bounds(bounds), m_colour(colour), m_bounds_ubo(), 
23                 m_objbounds_vbo(), m_object_renderers(NUMBER_OF_OBJECT_TYPES), m_cpu_rendering_pixels(NULL)
24 {
25         Debug("View Created - Bounds => {%s}", m_bounds.Str().c_str());
26
27         screen.SetView(this); // oh dear...
28
29         // Create ObjectRenderers - new's match delete's in View::~View
30         //TODO: Don't forget to put new renderers here or things will be segfaultastic
31         m_object_renderers[RECT_FILLED] = new RectFilledRenderer();
32         m_object_renderers[RECT_OUTLINE] = new RectOutlineRenderer();
33         m_object_renderers[CIRCLE_FILLED] = new CircleFilledRenderer();
34         m_object_renderers[BEZIER] = new BezierRenderer();
35         m_object_renderers[GROUP] = new GroupRenderer();
36
37         // To add rendering for a new type of object;
38         // 1. Add enum to ObjectType in ipdf.h
39         // 2. Implement class inheriting from ObjectRenderer using that type in objectrenderer.h and objectrenderer.cpp
40         // 3. Add it here
41         // 4. Profit
42
43
44 #ifndef QUADTREE_DISABLED
45         m_quadtree_max_depth = 1;
46         m_current_quadtree_node = document.GetQuadTree().root_id;
47 #endif
48 }
49
50 /**
51  * Destroy a view
52  * Frees memory used by ObjectRenderers
53  */
54 View::~View()
55 {
56         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
57         {
58                 delete m_object_renderers[i]; // delete's match new's in constructor
59         }
60         m_object_renderers.clear();
61         delete [] m_cpu_rendering_pixels;
62 }
63
64 /**
65  * Translate the view
66  * @param x, y - Amount to translate
67  */
68 void View::Translate(Real x, Real y)
69 {
70         x *= m_bounds.w;
71         y *= m_bounds.h;
72         m_bounds.x += x;
73         m_bounds.y += y;
74         Debug("View Bounds => %s", m_bounds.Str().c_str());
75         if (!m_use_gpu_transform)
76                 m_buffer_dirty = true;
77         m_bounds_dirty = true;
78 }
79
80 /**
81  * Set View bounds
82  * @param bounds - New bounds
83  */
84 void View::SetBounds(const Rect & bounds)
85 {
86         m_bounds.x = bounds.x;
87         m_bounds.y = bounds.y;
88         m_bounds.w = bounds.w;
89         m_bounds.h = bounds.h;
90         if (!m_use_gpu_transform)
91                 m_buffer_dirty = true;
92         m_bounds_dirty = true;
93 }
94
95 /**
96  * Scale the View at a point
97  * @param x, y - Coordinates to scale at (eg: Mouse cursor position)
98  * @param scale_amount - Amount to scale by
99  */
100 void View::ScaleAroundPoint(Real x, Real y, Real scale_amount)
101 {
102         // x and y are coordinates in the window
103         // Convert to local coords.
104         x *= m_bounds.w;
105         y *= m_bounds.h;
106         x += m_bounds.x;
107         y += m_bounds.y;
108         
109         Real top = y - m_bounds.y;
110         Real left = x - m_bounds.x;
111         
112         top *= scale_amount;
113         left *= scale_amount;
114         
115         m_bounds.x = x - left;
116         m_bounds.y = y - top;
117         m_bounds.w *= scale_amount;
118         m_bounds.h *= scale_amount;
119         //Debug("Scale at {%s, %s} by %s View Bounds => %s", x.Str().c_str(), y.Str().c_str(), scale_amount.Str().c_str(), m_bounds.Str().c_str());
120         if (!m_use_gpu_transform)
121                 m_buffer_dirty = true;
122         m_bounds_dirty = true;
123 }
124
125 /**
126  * Transform a point in the document to a point relative to the top left corner of the view
127  * This is the CPU coordinate transform code; used only if the CPU is doing coordinate transforms
128  * @param inp - Input Rect {x,y,w,h} in the document
129  * @returns output Rect {x,y,w,h} in the View
130  */
131 Rect View::TransformToViewCoords(const Rect& inp) const
132 {
133         Rect out;
134         out.x = (inp.x - m_bounds.x) / m_bounds.w;
135         out.y = (inp.y - m_bounds.y) / m_bounds.h;
136         out.w = inp.w / m_bounds.w;
137         out.h = inp.h / m_bounds.h;
138         return out;
139 }
140
141 /**
142  * Render the view
143  * Updates FrameBuffer if the document, object bounds, or view bounds have changed, then Blits it
144  * Otherwise just Blits the cached FrameBuffer
145  * @param width - Width of View to render
146  * @param height - Height of View to render
147  */
148 void View::Render(int width, int height)
149 {
150         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION,42,-1, "Beginning View::Render()");
151         // View dimensions have changed (ie: Window was resized)
152         int prev_width = m_cached_display.GetWidth();
153         int prev_height = m_cached_display.GetHeight();
154         if (width != prev_width || height != prev_height)
155         {
156                 m_cached_display.Create(width, height);
157                 m_bounds_dirty = true;
158         }
159
160         // View bounds have not changed; blit the FrameBuffer as it is
161         if (!m_bounds_dirty)
162         {
163                 m_cached_display.UnBind();
164                 m_cached_display.Blit();
165                 glPopDebugGroup();
166                 return;
167         }
168         m_cached_display.Bind(); //NOTE: This is redundant; Clear already calls Bind
169         m_cached_display.Clear();
170
171 #ifndef QUADTREE_DISABLED
172         if (m_bounds_dirty)
173         {
174                 if (m_bounds.x > 1.0 || m_bounds.x < 0.0 || m_bounds.y > 1.0 || m_bounds.y < 0.0 || m_bounds.w > 1.0 || m_bounds.h > 1.0)
175                 {
176                         //TODO: Generate a new parent node.
177                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].parent != QUADTREE_EMPTY)
178                         {
179                                 m_bounds = TransformFromQuadChild(m_bounds, m_document.GetQuadTree().nodes[m_current_quadtree_node].child_type);
180                                 m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].parent;
181                         }
182                 }
183                 if (ContainedInQuadChild(m_bounds, QTC_TOP_LEFT))
184                 {
185                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left == QUADTREE_EMPTY)
186                         {
187                                 // We want to reparent into a child node, but none exist. Get the document to create one.
188                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_LEFT);
189                                 m_render_dirty = true;
190                         }
191                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_LEFT);
192                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left;
193                 }
194                 if (ContainedInQuadChild(m_bounds, QTC_TOP_RIGHT))
195                 {
196                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right == QUADTREE_EMPTY)
197                         {
198                                 // We want to reparent into a child node, but none exist. Get the document to create one.
199                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_RIGHT);
200                                 m_render_dirty = true;
201                         }
202                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_RIGHT);
203                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right;
204                 }
205                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_LEFT))
206                 {
207                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left == QUADTREE_EMPTY)
208                         {
209                                 // We want to reparent into a child node, but none exist. Get the document to create one.
210                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_LEFT);
211                                 m_render_dirty = true;
212                         }
213                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_LEFT);
214                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left;
215                 }
216                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_RIGHT))
217                 {
218                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right == QUADTREE_EMPTY)
219                         {
220                                 // We want to reparent into a child node, but none exist. Get the document to create one.
221                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_RIGHT);
222                                 m_render_dirty = true;
223                         }
224                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_RIGHT);
225                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right;
226                 }
227         }
228         m_screen.DebugFontPrintF("Current View QuadTree Node: %d (objs: %d -> %d)\n", m_current_quadtree_node, m_document.GetQuadTree().nodes[m_current_quadtree_node].object_begin,
229                                 m_document.GetQuadTree().nodes[m_current_quadtree_node].object_end);
230 #endif
231
232         if (!m_use_gpu_rendering)
233         {
234                 // Dynamically resize CPU rendering target pixels if needed
235                 if (m_cpu_rendering_pixels == NULL || width*height > prev_width*prev_height)
236                 {
237                         delete [] m_cpu_rendering_pixels;
238                         m_cpu_rendering_pixels = new uint8_t[width*height*4];
239                         if (m_cpu_rendering_pixels == NULL)
240                                 Fatal("Could not allocate %d*%d*4 = %d bytes for cpu rendered pixels", width, height, width*height*4);
241                 }
242                 // Clear CPU rendering pixels
243                 for (int i = 0; i < width*height*4; ++i)
244                         m_cpu_rendering_pixels[i] = 255;
245         }
246 #ifdef QUADTREE_DISABLED
247         RenderRange(width, height, 0, m_document.ObjectCount());
248 #else
249         RenderQuadtreeNode(width, height, m_current_quadtree_node, m_quadtree_max_depth);
250 #endif
251         if (!m_use_gpu_rendering)
252         {
253                 m_screen.RenderPixels(0,0,width, height, m_cpu_rendering_pixels); //TODO: Make this work :(
254                 // Debug for great victory (do something similar for GPU and compare?)
255                 ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, width, height}, "cpu_rendering_last_frame.bmp");
256         }
257         m_cached_display.UnBind(); // resets render target to the screen
258         m_cached_display.Blit(); // blit FrameBuffer to screen
259         m_buffer_dirty = false;
260         glPopDebugGroup();
261         
262 #ifndef CONTROLPANEL_DISABLED
263         ControlPanel::Update();
264 #endif //CONTROLPANEL_DISABLED
265         
266 }
267
268 #ifndef QUADTREE_DISABLED
269 void View::RenderQuadtreeNode(int width, int height, QuadTreeIndex node, int remaining_depth)
270 {
271         Rect old_bounds = m_bounds;
272         if (node == QUADTREE_EMPTY) return;
273         if (!remaining_depth) return;
274         //Debug("Rendering QT node %d, (objs: %d -- %d)\n", node, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
275         m_bounds_dirty = true;
276         RenderRange(width, height, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
277
278         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_LEFT);
279         m_bounds_dirty = true;
280         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_left, remaining_depth-1);
281         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_RIGHT);
282         m_bounds_dirty = true;
283         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_right, remaining_depth-1);
284         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_LEFT);
285         m_bounds_dirty = true;
286         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_left, remaining_depth-1);
287         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_RIGHT);
288         m_bounds_dirty = true;
289         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_right, remaining_depth-1);
290         m_bounds = old_bounds;
291         m_bounds_dirty = true;
292 }
293 #endif
294
295 void View::RenderRange(int width, int height, unsigned first_obj, unsigned last_obj)
296 {
297         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 43, -1, "View::RenderRange()");
298         if (m_render_dirty) // document has changed
299                 PrepareRender();
300
301         if (m_buffer_dirty || m_bounds_dirty) // object bounds have changed
302                 UpdateObjBoundsVBO(first_obj, last_obj);
303
304         if (m_use_gpu_transform)
305         {
306                 GLfloat glbounds[] = {static_cast<GLfloat>(Float(m_bounds.x)), static_cast<GLfloat>(Float(m_bounds.y)), static_cast<GLfloat>(Float(m_bounds.w)), static_cast<GLfloat>(Float(m_bounds.h)),
307                                         0.0, 0.0, static_cast<GLfloat>(width), static_cast<GLfloat>(height)};
308                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
309         }
310         else
311         {
312                 GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f,
313                                         0.0f, 0.0f, float(width), float(height)};
314                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
315         }
316         m_bounds_dirty = false;
317
318
319         // Render using GPU
320         if (m_use_gpu_rendering) 
321         {
322                 if (m_colour.a < 1.0f)
323                 {
324                         glEnable(GL_BLEND);
325                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
326                 }
327                 m_objbounds_vbo.Bind();
328                 m_bounds_ubo.Bind();
329                 glEnableVertexAttribArray(0);
330                 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
331         
332                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
333                 {
334                         m_object_renderers[i]->RenderUsingGPU(first_obj, last_obj);
335                 }
336                 
337                 glDisableVertexAttribArray(0);
338                 if (m_colour.a < 1.0f)
339                 {
340                         glDisable(GL_BLEND);
341                 }
342         }
343         else // Rasterise on CPU then blit texture to GPU
344         {
345
346                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
347                 {
348                         m_object_renderers[i]->RenderUsingCPU(m_document.m_objects, *this, {m_cpu_rendering_pixels, width, height}, first_obj, last_obj);
349                 }
350         }
351         glPopDebugGroup();
352 }
353
354 void View::UpdateObjBoundsVBO(unsigned first_obj, unsigned last_obj)
355 {
356         //m_objbounds_vbo.Invalidate();
357         m_objbounds_vbo.SetType(GraphicsBuffer::BufferTypeVertex);
358         m_objbounds_vbo.SetName("Object Bounds VBO");
359         if (m_use_gpu_transform)
360         {
361                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
362         }
363         else
364         {
365                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageDynamicCopy);
366         }
367         m_objbounds_vbo.Resize(m_document.ObjectCount()*sizeof(GPUObjBounds));
368
369         BufferBuilder<GPUObjBounds> obj_bounds_builder(m_objbounds_vbo.MapRange(first_obj*sizeof(GPUObjBounds), (last_obj-first_obj)*sizeof(GPUObjBounds), false, true, true), m_objbounds_vbo.GetSize());
370
371         for (unsigned id = first_obj; id < last_obj; ++id)
372         {
373                 Rect obj_bounds;
374                 if (m_use_gpu_transform)
375                 {
376                         obj_bounds = m_document.m_objects.bounds[id];
377                 }
378                 else
379                 {
380                         obj_bounds = TransformToViewCoords(m_document.m_objects.bounds[id]);
381                 }
382                 GPUObjBounds gpu_bounds = {
383                         (float)Float(obj_bounds.x),
384                         (float)Float(obj_bounds.y),
385                         (float)Float(obj_bounds.x + obj_bounds.w),
386                         (float)Float(obj_bounds.y + obj_bounds.h)
387                 };
388                 obj_bounds_builder.Add(gpu_bounds);
389
390         }
391         m_objbounds_vbo.UnMap();
392 }
393 /**
394  * Prepare the document for rendering
395  * Will be called on View::Render if m_render_dirty is set
396  * (Called at least once, on the first Render)
397  */
398 void View::PrepareRender()
399 {
400         Debug("Recreate buffers with %u objects", m_document.ObjectCount());
401         // Prepare bounds vbo
402         m_bounds_ubo.Invalidate();
403         m_bounds_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
404         m_bounds_ubo.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
405         m_bounds_ubo.SetName("m_bounds_ubo: Screen bounds.");
406         
407         // Instead of having each ObjectRenderer go through the whole document
408         //  we initialise them, go through the document once adding to the appropriate Renderers
409         //  and then finalise them
410         // This will totally be efficient if we have like, a lot of distinct ObjectTypes. Which could totally happen. You never know.
411
412         // Prepare the buffers
413         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
414         {
415                 m_object_renderers[i]->PrepareBuffers(m_document.ObjectCount());
416         }
417
418         // Add objects from Document to buffers
419         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
420         {
421                 ObjectType type = m_document.m_objects.types[id];
422                 m_object_renderers.at(type)->AddObjectToBuffers(id); // Use at() in case the document is corrupt TODO: Better error handling?
423                 // (Also, Wow I just actually used std::vector::at())
424                 // (Also, I just managed to make it throw an exception because I'm a moron)
425                 //Debug("Object of type %d", type);
426         }
427
428         // Finish the buffers
429         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
430         {
431                 m_object_renderers[i]->FinaliseBuffers();
432         }
433         dynamic_cast<BezierRenderer*>(m_object_renderers[BEZIER])->PrepareBezierGPUBuffer(m_document.m_objects);
434         m_render_dirty = false;
435 }

UCC git Repository :: git.ucc.asn.au