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

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