925fa47c54db2933963922a33747fefb0054f10c
[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 = 1;
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 (false && (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         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,
231                                 m_document.GetQuadTree().nodes[m_current_quadtree_node].object_end);
232 #endif
233
234         if (!m_use_gpu_rendering)
235         {
236                 // Dynamically resize CPU rendering target pixels if needed
237                 if (m_cpu_rendering_pixels == NULL || width*height > prev_width*prev_height)
238                 {
239                         delete [] m_cpu_rendering_pixels;
240                         m_cpu_rendering_pixels = new uint8_t[width*height*4];
241                         if (m_cpu_rendering_pixels == NULL)
242                                 Fatal("Could not allocate %d*%d*4 = %d bytes for cpu rendered pixels", width, height, width*height*4);
243                 }
244                 // Clear CPU rendering pixels
245                 for (int i = 0; i < width*height*4; ++i)
246                         m_cpu_rendering_pixels[i] = 255;
247         }
248 #ifdef QUADTREE_DISABLED
249         RenderRange(width, height, 0, m_document.ObjectCount());
250 #else
251         RenderQuadtreeNode(width, height, m_current_quadtree_node, m_quadtree_max_depth);
252 #endif
253         if (!m_use_gpu_rendering)
254         {
255                 m_screen.RenderPixels(0,0,width, height, m_cpu_rendering_pixels); //TODO: Make this work :(
256                 // Debug for great victory (do something similar for GPU and compare?)
257                 //ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, width, height}, "cpu_rendering_last_frame.bmp");
258         }
259         m_cached_display.UnBind(); // resets render target to the screen
260         m_cached_display.Blit(); // blit FrameBuffer to screen
261         m_buffer_dirty = false;
262         glPopDebugGroup();
263         
264 #ifndef CONTROLPANEL_DISABLED
265         ControlPanel::Update();
266 #endif //CONTROLPANEL_DISABLED
267         
268 }
269
270 #ifndef QUADTREE_DISABLED
271 void View::RenderQuadtreeNode(int width, int height, QuadTreeIndex node, int remaining_depth)
272 {
273         Rect old_bounds = m_bounds;
274         if (node == QUADTREE_EMPTY) return;
275         if (!remaining_depth) return;
276         //Debug("Rendering QT node %d, (objs: %d -- %d)\n", node, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
277         m_bounds_dirty = true;
278         RenderRange(width, height, m_document.GetQuadTree().nodes[node].object_begin, m_document.GetQuadTree().nodes[node].object_end);
279
280         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_LEFT);
281         m_bounds_dirty = true;
282         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_left, remaining_depth-1);
283         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_RIGHT);
284         m_bounds_dirty = true;
285         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_right, remaining_depth-1);
286         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_LEFT);
287         m_bounds_dirty = true;
288         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_left, remaining_depth-1);
289         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_RIGHT);
290         m_bounds_dirty = true;
291         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_right, remaining_depth-1);
292         m_bounds = old_bounds;
293         m_bounds_dirty = true;
294 }
295 #endif
296
297 void View::RenderRange(int width, int height, unsigned first_obj, unsigned last_obj)
298 {
299         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 43, -1, "View::RenderRange()");
300         if (m_render_dirty) // document has changed
301                 PrepareRender();
302
303         if (m_buffer_dirty || m_bounds_dirty) // object bounds have changed
304                 UpdateObjBoundsVBO(first_obj, last_obj);
305
306         if (m_use_gpu_transform)
307         {
308                 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)),
309                                         0.0, 0.0, static_cast<GLfloat>(width), static_cast<GLfloat>(height)};
310                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
311         }
312         else
313         {
314                 GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f,
315                                         0.0f, 0.0f, float(width), float(height)};
316                 m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
317         }
318         m_bounds_dirty = false;
319
320
321         // Render using GPU
322         if (m_use_gpu_rendering) 
323         {
324                 if (m_colour.a < 1.0f)
325                 {
326                         glEnable(GL_BLEND);
327                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
328                 }
329                 m_objbounds_vbo.Bind();
330                 m_bounds_ubo.Bind();
331                 glEnableVertexAttribArray(0);
332                 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
333         
334                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
335                 {
336                         m_object_renderers[i]->RenderUsingGPU(first_obj, last_obj);
337                 }
338                 
339                 glDisableVertexAttribArray(0);
340                 if (m_colour.a < 1.0f)
341                 {
342                         glDisable(GL_BLEND);
343                 }
344         }
345         else // Rasterise on CPU then blit texture to GPU
346         {
347
348                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
349                 {
350                         m_object_renderers[i]->RenderUsingCPU(m_document.m_objects, *this, {m_cpu_rendering_pixels, width, height}, first_obj, last_obj);
351                 }
352         }
353         glPopDebugGroup();
354 }
355
356 void View::UpdateObjBoundsVBO(unsigned first_obj, unsigned last_obj)
357 {
358         //m_objbounds_vbo.Invalidate();
359         m_objbounds_vbo.SetType(GraphicsBuffer::BufferTypeVertex);
360         m_objbounds_vbo.SetName("Object Bounds VBO");
361         if (m_use_gpu_transform)
362         {
363                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
364         }
365         else
366         {
367                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageDynamicCopy);
368         }
369         m_objbounds_vbo.Resize(m_document.ObjectCount()*sizeof(GPUObjBounds));
370
371         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());
372
373         for (unsigned id = first_obj; id < last_obj; ++id)
374         {
375                 Rect obj_bounds;
376                 if (m_use_gpu_transform)
377                 {
378                         obj_bounds = m_document.m_objects.bounds[id];
379                 }
380                 else
381                 {
382                         obj_bounds = TransformToViewCoords(m_document.m_objects.bounds[id]);
383                 }
384                 GPUObjBounds gpu_bounds = {
385                         (float)Float(obj_bounds.x),
386                         (float)Float(obj_bounds.y),
387                         (float)Float(obj_bounds.x + obj_bounds.w),
388                         (float)Float(obj_bounds.y + obj_bounds.h)
389                 };
390                 obj_bounds_builder.Add(gpu_bounds);
391
392         }
393         m_objbounds_vbo.UnMap();
394 }
395 /**
396  * Prepare the document for rendering
397  * Will be called on View::Render if m_render_dirty is set
398  * (Called at least once, on the first Render)
399  */
400 void View::PrepareRender()
401 {
402         Debug("Recreate buffers with %u objects", m_document.ObjectCount());
403         // Prepare bounds vbo
404         m_bounds_ubo.Invalidate();
405         m_bounds_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
406         m_bounds_ubo.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
407         m_bounds_ubo.SetName("m_bounds_ubo: Screen bounds.");
408         
409         // Instead of having each ObjectRenderer go through the whole document
410         //  we initialise them, go through the document once adding to the appropriate Renderers
411         //  and then finalise them
412         // This will totally be efficient if we have like, a lot of distinct ObjectTypes. Which could totally happen. You never know.
413
414         // Prepare the buffers
415         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
416         {
417                 m_object_renderers[i]->PrepareBuffers(m_document.ObjectCount());
418         }
419
420         // Add objects from Document to buffers
421         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
422         {
423                 ObjectType type = m_document.m_objects.types[id];
424                 m_object_renderers.at(type)->AddObjectToBuffers(id); // Use at() in case the document is corrupt TODO: Better error handling?
425                 // (Also, Wow I just actually used std::vector::at())
426                 // (Also, I just managed to make it throw an exception because I'm a moron)
427                 //Debug("Object of type %d", type);
428         }
429
430         // Finish the buffers
431         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
432         {
433                 m_object_renderers[i]->FinaliseBuffers();
434         }
435         dynamic_cast<BezierRenderer*>(m_object_renderers[BEZIER])->PrepareBezierGPUBuffer(m_document.m_objects);
436         m_render_dirty = false;
437 }

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