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

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