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

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