David's final changes: more profiler features, fixes.
[ipdf/code.git] / src / view.cpp
1 #include "view.h"
2 #include "bufferbuilder.h"
3 #include "screen.h"
4 #include "profiler.h"
5 #include "gl_core44.h"
6
7 #ifndef CONTROLPANEL_DISABLED
8         #include "controlpanel.h"
9 #endif //CONTROLPANEL_DISABLED
10
11
12 #ifdef TRANSFORM_BEZIERS_TO_PATH 
13         #ifndef TRANSFORM_OBJECTS_NOT_VIEW
14         //#error Cannot TRANSFORM_BEZIERS_TO_PATH _without_ TRANSFORM_OBJECTS_NOT_VIEW
15         #endif
16 #endif
17
18 using namespace IPDF;
19 using namespace std;
20
21 /**
22  * Constructs a view
23  * Allocates memory for ObjectRenderers
24  * @param document - The document to associate the View with
25  * @param bounds - Initial bounds of the View
26  * @param colour - Colour to use for rendering this view. TODO: Make sure this actually works, or just remove it
27  */
28 View::View(Document & document, Screen & screen, const VRect & bounds, const Colour & colour)
29         : m_use_gpu_transform(false), m_use_gpu_rendering(USE_GPU_RENDERING), m_bounds_dirty(true), m_buffer_dirty(true), 
30                 m_render_dirty(true), m_document(document), m_screen(screen), m_cached_display(), m_bounds(bounds), m_colour(colour), m_bounds_ubo(), 
31                 m_objbounds_vbo(), m_object_renderers(NUMBER_OF_OBJECT_TYPES), m_cpu_rendering_pixels(NULL),
32                 m_perform_shading(USE_SHADING), m_show_bezier_bounds(false), m_show_bezier_type(false),
33                 m_show_fill_points(false), m_show_fill_bounds(false), m_lazy_rendering(true),
34                 m_query_gpu_bounds_on_next_frame(NULL)
35 {
36         Debug("View Created - Bounds => {%s}", m_bounds.Str().c_str());
37
38         screen.SetView(this); // oh dear...
39
40         
41
42         // Create ObjectRenderers - new's match delete's in View::~View
43         //TODO: Don't forget to put new renderers here or things will be segfaultastic
44         if (screen.Valid())
45         {
46                 m_object_renderers[RECT_FILLED] = new RectFilledRenderer();
47                 m_object_renderers[RECT_OUTLINE] = new RectOutlineRenderer();
48                 m_object_renderers[CIRCLE_FILLED] = new CircleFilledRenderer();
49                 m_object_renderers[BEZIER] = new BezierRenderer();
50                 m_object_renderers[PATH] = new PathRenderer();
51         }
52         else
53         {
54                 for (int i = RECT_FILLED; i <= PATH; ++i)
55                         m_object_renderers[i] = new FakeRenderer();
56         }
57
58         // To add rendering for a new type of object;
59         // 1. Add enum to ObjectType in ipdf.h
60         // 2. Implement class inheriting from ObjectRenderer using that type in objectrenderer.h and objectrenderer.cpp
61         // 3. Add it here
62         // 4. Profit
63
64
65 #ifndef QUADTREE_DISABLED
66         m_quadtree_max_depth = 2;
67         m_current_quadtree_node = document.GetQuadTree().root_id;
68 #endif
69 }
70
71 /**
72  * Destroy a view
73  * Frees memory used by ObjectRenderers
74  */
75 View::~View()
76 {
77         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
78         {
79                 delete m_object_renderers[i]; // delete's match new's in constructor
80         }
81         m_object_renderers.clear();
82         delete [] m_cpu_rendering_pixels;
83 }
84
85 /**
86  * Translate the view
87  * @param x, y - Amount to translate
88  */
89 void View::Translate(Real x, Real y)
90 {
91         PROFILE_SCOPE("View::Translate");       
92         if (!m_use_gpu_transform)
93                 m_buffer_dirty = true;
94         m_bounds_dirty = true;
95         #ifdef TRANSFORM_OBJECTS_NOT_VIEW
96         ObjectType type = NUMBER_OF_OBJECT_TYPES;
97                 #ifdef TRANSFORM_BEZIERS_TO_PATH
98                         type = PATH;
99                 #endif
100         m_document.TranslateObjects(-x, -y, type);
101         #endif
102         m_bounds.x += m_bounds.w*VReal(x);
103         m_bounds.y += m_bounds.h*VReal(y);
104         //Debug("View Bounds => %s", m_bounds.Str().c_str());
105
106         
107 }
108
109 /**
110  * Set View bounds
111  * @param bounds - New bounds
112  */
113 void View::SetBounds(const Rect & bounds)
114 {
115         #ifdef TRANSFORM_OBJECTS_NOT_VIEW
116         ObjectType type = NUMBER_OF_OBJECT_TYPES;
117         #ifdef TRANSFORM_BEZIERS_TO_PATH
118                 type = PATH;
119         #endif
120         SVGMatrix transform = {Real(m_bounds.w)/bounds.w, 0, Real(m_bounds.x) - bounds.x, 0,Real(m_bounds.h)/bounds.h, Real(m_bounds.y) - bounds.y};
121         m_document.TransformObjectBounds(transform, type);
122         #endif
123         m_bounds.x = bounds.x;
124         m_bounds.y = bounds.y;
125         m_bounds.w = bounds.w;
126         m_bounds.h = bounds.h;
127         if (!m_use_gpu_transform)
128                 m_buffer_dirty = true;
129         m_bounds_dirty = true;
130 }
131
132 /**
133  * Scale the View at a point
134  * @param x, y - Coordinates to scale at (eg: Mouse cursor position)
135  * @param scale_amount - Amount to scale by
136  */
137 void View::ScaleAroundPoint(Real x, Real y, Real scale_amount)
138 {
139         PROFILE_SCOPE("View::ScaleAroundPoint");        
140         // (x0, y0, w, h) -> (x*w - (x*w - x0)*s, y*h - (y*h - y0)*s, w*s, h*s)
141         // x and y are coordinates in the window
142         // Convert to local coords.
143         if (!m_use_gpu_transform)
144                 m_buffer_dirty = true;
145         m_bounds_dirty = true;
146         
147         
148         #ifdef TRANSFORM_OBJECTS_NOT_VIEW
149         ObjectType type = NUMBER_OF_OBJECT_TYPES;
150         #ifdef TRANSFORM_BEZIERS_TO_PATH
151                 type = PATH;
152         #endif
153         m_document.ScaleObjectsAboutPoint(x, y, scale_amount, type);
154         #endif
155         VReal vx = m_bounds.w * VReal(x);
156         VReal vy = m_bounds.h * VReal(y);
157         vx += m_bounds.x;
158         vy += m_bounds.y;
159         
160         VReal top = vy - m_bounds.y;
161         VReal left = vx - m_bounds.x;
162         
163         top *= scale_amount;
164         left *= scale_amount;
165         
166         m_bounds.x = vx - left;
167         m_bounds.y = vy - top;
168         m_bounds.w *= scale_amount;
169         m_bounds.h *= scale_amount;
170         if (m_bounds.w == VReal(0))
171         {
172                 Debug("Scaled to zero!!!");
173         }
174         //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());
175         
176         
177 }
178
179 /**
180  * Transform a point in the document to a point relative to the top left corner of the view
181  * This is the CPU coordinate transform code; used only if the CPU is doing coordinate transforms
182  * @param inp - Input Rect {x,y,w,h} in the document
183  * @returns output Rect {x,y,w,h} in the View
184  */
185 Rect View::TransformToViewCoords(const Rect& inp) const
186 {
187         #ifdef TRANSFORM_OBJECTS_NOT_VIEW
188                 return inp;
189         #endif
190         return TransformRectCoordinates(m_bounds.Convert<Real>(), inp);
191 }
192
193 /**
194  * Render the view
195  * Updates FrameBuffer if the document, object bounds, or view bounds have changed, then Blits it
196  * Otherwise just Blits the cached FrameBuffer
197  * @param width - Width of View to render
198  * @param height - Height of View to render
199  */
200 void View::Render(int width, int height)
201 {
202         PROFILE_SCOPE("View::Render()");
203         if (!m_screen.Valid()) return;
204         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION,42,-1, "Beginning View::Render()");
205         // View dimensions have changed (ie: Window was resized)
206         int prev_width = m_cached_display.GetWidth();
207         int prev_height = m_cached_display.GetHeight();
208         if (width != prev_width || height != prev_height)
209         {
210                 m_cached_display.Create(width, height);
211                 m_bounds_dirty = true;
212         }
213
214         // View bounds have not changed; blit the FrameBuffer as it is
215         if (!m_bounds_dirty && m_lazy_rendering)
216         {
217                 m_cached_display.UnBind();
218                 m_cached_display.Blit();
219                 glPopDebugGroup();
220                 return;
221         }
222         m_cached_display.Bind(); //NOTE: This is redundant; Clear already calls Bind
223         m_cached_display.Clear();
224
225 #ifndef QUADTREE_DISABLED
226         // I'm going to write this out in comments, so hopefully then I'll understand it. :/
227         //
228         // This code looks at the current bounds and tries to work out how they need to change
229         // to keep the view looking at the correct quadtree node.
230         //
231         // The idea is that the width/height of the view bounds are always 0.5<=wh<=1.0. We then always
232         // try to keep the bottom-right corner of the node on-screen, changing nodes to suit. Why bottom-right,
233         // you may ask. It's an excellent question, with a dubious, hand-wavey answer: because we're manipulating
234         // the bounds, it was easier to do it that way. (The top-left corner of the bounds are within the main
235         // quadtree node).
236         if (m_bounds_dirty || !m_lazy_rendering)
237         {
238                 g_profiler.BeginZone("View::Render -- Quadtree view bounds management");
239                 // If we're too far zoomed out, become the parent of the current node.
240                 while ( m_bounds.w > 1.0 || m_bounds.h > 1.0)
241                 {
242                         // If a parent node exists, we'll become it.
243                         //TODO: Generate a new parent node if none exists, and work out when to change child_type
244                         // away from QTC_UNKNOWN
245                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].parent != QUADTREE_EMPTY)
246                         {
247                                 m_bounds = TransformFromQuadChild(m_bounds, m_document.GetQuadTree().nodes[m_current_quadtree_node].child_type);
248                                 m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].parent;
249                         }
250                         else break;
251                 }
252
253                 // If we have a parent... (This prevents some crashes, but should disappear.)
254                 if (m_document.GetQuadTree().nodes[m_current_quadtree_node].parent != QUADTREE_EMPTY)
255                 {
256                         // If the current node is off the left-hand side of the screen...
257                         while (m_bounds.x > 1)
258                         {
259                                 //... the current node becomes the node to its right.
260                                 m_bounds = Rect(m_bounds.x - 1, m_bounds.y, m_bounds.w, m_bounds.h);
261                                 m_current_quadtree_node = m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 1, 0, &m_document);
262                         }
263                         while (m_bounds.y > 1)
264                         {
265                                 m_bounds = Rect(m_bounds.x, m_bounds.y - 1, m_bounds.w, m_bounds.h);
266                                 m_current_quadtree_node = m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 0, 1, &m_document);
267                         }
268                         while (m_bounds.x < 0)
269                         {
270                                 m_bounds = Rect(m_bounds.x + 1, m_bounds.y, m_bounds.w, m_bounds.h);
271                                 m_current_quadtree_node = m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, -1, 0, &m_document);
272                         }
273                         while (m_bounds.y < 0)
274                         {
275                                 m_bounds = Rect(m_bounds.x, m_bounds.y + 1, m_bounds.w, m_bounds.h);
276                                 m_current_quadtree_node = m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 0, -1, &m_document);
277                         }
278                 }
279
280                 // Recurse into a node if we are completely within it. (If we're okay with having an invalid frame or two, we can remove this.)
281                 if (ContainedInQuadChild(m_bounds, QTC_TOP_LEFT))
282                 {
283                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left == QUADTREE_EMPTY)
284                         {
285                                 // We want to reparent into a child node, but none exist. Get the document to create one.
286                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_LEFT);
287                                 m_render_dirty = true;
288                         }
289                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_LEFT);
290                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_left;
291                 }
292                 if (ContainedInQuadChild(m_bounds, QTC_TOP_RIGHT))
293                 {
294                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right == QUADTREE_EMPTY)
295                         {
296                                 // We want to reparent into a child node, but none exist. Get the document to create one.
297                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_TOP_RIGHT);
298                                 m_render_dirty = true;
299                         }
300                         m_bounds = TransformToQuadChild(m_bounds, QTC_TOP_RIGHT);
301                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].top_right;
302                 }
303                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_LEFT))
304                 {
305                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left == QUADTREE_EMPTY)
306                         {
307                                 // We want to reparent into a child node, but none exist. Get the document to create one.
308                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_LEFT);
309                                 m_render_dirty = true;
310                         }
311                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_LEFT);
312                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_left;
313                 }
314                 if (ContainedInQuadChild(m_bounds, QTC_BOTTOM_RIGHT))
315                 {
316                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right == QUADTREE_EMPTY)
317                         {
318                                 // We want to reparent into a child node, but none exist. Get the document to create one.
319                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_RIGHT);
320                                 m_render_dirty = true;
321                         }
322                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_RIGHT);
323                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right;
324                 }
325
326                 // Otherwise, we'll arbitrarily select the bottom-right.
327                 // TODO: Perhaps select based on greatest area?
328                 while (m_bounds.w < 0.5 || m_bounds.h < 0.5)
329                 {
330                         if (m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right == QUADTREE_EMPTY)
331                         {
332                                 // We want to reparent into a child node, but none exist. Get the document to create one.
333                                 m_document.GenQuadChild(m_current_quadtree_node, QTC_BOTTOM_RIGHT);
334                                 m_render_dirty = true;
335                         }
336                         m_bounds = TransformToQuadChild(m_bounds, QTC_BOTTOM_RIGHT);
337                         m_current_quadtree_node = m_document.GetQuadTree().nodes[m_current_quadtree_node].bottom_right;
338                 }
339                 g_profiler.EndZone();
340         }
341
342         m_screen.DebugFontPrintF("Current View QuadTree");
343         QuadTreeIndex overlay = m_current_quadtree_node;
344         while (overlay != -1)
345         {
346                 m_screen.DebugFontPrintF(" Node: %d (objs: %d -> %d)", overlay, m_document.GetQuadTree().nodes[overlay].object_begin,
347                                         m_document.GetQuadTree().nodes[overlay].object_end);
348                 overlay = m_document.GetQuadTree().nodes[overlay].next_overlay;
349         }
350         m_screen.DebugFontPrintF("\n");
351         m_screen.DebugFontPrintF("Left: %d, Right: %d, Up: %d, Down: %d\n",
352                         m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, -1, 0, 0),
353                         m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 1, 0, 0),
354                         m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 0, -1, 0),
355                         m_document.GetQuadTree().GetNeighbour(m_current_quadtree_node, 0, 1, 0));
356
357
358         Rect view_top_bounds = m_bounds;
359         QuadTreeIndex tmp = m_current_quadtree_node;
360         while (tmp != -1)
361         {
362                 view_top_bounds = TransformFromQuadChild(view_top_bounds, m_document.GetQuadTree().nodes[tmp].child_type);
363                 tmp = m_document.GetQuadTree().nodes[tmp].parent;
364         }
365         m_screen.DebugFontPrintF("Equivalent View Bounds: %s\n", view_top_bounds.Str().c_str());
366 #endif
367
368         if (!m_use_gpu_rendering)
369         {
370                 // Dynamically resize CPU rendering target pixels if needed
371                 if (m_cpu_rendering_pixels == NULL || width*height > prev_width*prev_height)
372                 {
373                         delete [] m_cpu_rendering_pixels;
374                         m_cpu_rendering_pixels = new uint8_t[width*height*4];
375                         if (m_cpu_rendering_pixels == NULL)
376                                 Fatal("Could not allocate %d*%d*4 = %d bytes for cpu rendered pixels", width, height, width*height*4);
377                 }
378                 // Clear CPU rendering pixels
379                 for (int i = 0; i < width*height*4; ++i)
380                         m_cpu_rendering_pixels[i] = 255;
381         }
382 #ifdef QUADTREE_DISABLED
383         RenderRange(width, height, 0, m_document.ObjectCount());
384 #else
385         // Make sure we update the gpu buffers properly.
386         if (m_document.m_document_dirty)
387         {
388                 m_render_dirty = m_buffer_dirty = true;
389                 m_document.m_document_dirty = false;
390         }
391         RenderQuadtreeNode(width, height, m_current_quadtree_node, m_quadtree_max_depth);
392 #endif
393         if (!m_use_gpu_rendering)
394         {
395                 m_screen.RenderPixels(0,0,width, height, m_cpu_rendering_pixels); //TODO: Make this work :(
396                 // Debug for great victory (do something similar for GPU and compare?)
397                 //ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, width, height}, "cpu_rendering_last_frame.bmp");
398         }
399         m_cached_display.UnBind(); // resets render target to the screen
400         m_cached_display.Blit(); // blit FrameBuffer to screen
401         m_buffer_dirty = false;
402         glPopDebugGroup();
403         
404 #ifndef CONTROLPANEL_DISABLED
405         // The powers that be suggest that this may be causing of the segfaults.
406         //ControlPanel::Update();
407 #endif //CONTROLPANEL_DISABLED
408         //Debug("Completed Render");
409         
410 }
411
412 #ifndef QUADTREE_DISABLED
413 void View::RenderQuadtreeNode(int width, int height, QuadTreeIndex node, int remaining_depth)
414 {
415         Rect old_bounds = m_bounds;
416         if (node == QUADTREE_EMPTY) return;
417         if (!remaining_depth) return;
418         m_bounds_dirty = true;
419         QuadTreeIndex overlay = node;
420         while(overlay != -1)
421         {
422                 //Debug("Rendering QT node %d, (overlay %d, objs: %d -- %d)\n", node, overlay, m_document.GetQuadTree().nodes[overlay].object_begin, m_document.GetQuadTree().nodes[overlay].object_end);
423                 if (m_document.GetQuadTree().nodes[overlay].render_dirty)
424                         m_buffer_dirty = m_render_dirty = true;
425                 RenderRange(width, height, m_document.GetQuadTree().nodes[overlay].object_begin, m_document.GetQuadTree().nodes[overlay].object_end);
426                 const_cast<bool&>(m_document.GetQuadTree().nodes[overlay].render_dirty) = false;
427                 overlay = m_document.GetQuadTree().nodes[overlay].next_overlay;
428         }
429
430         if (m_bounds.Intersects(Rect(1,1,1,1)))
431         {
432                 m_bounds = Rect(m_bounds.x - 1, m_bounds.y - 1, m_bounds.w, m_bounds.h);
433                 m_bounds_dirty = true;
434                 RenderQuadtreeNode(width, height, m_document.GetQuadTree().GetNeighbour(node, 1, 1, &m_document), remaining_depth - 1);
435         }
436         m_bounds = old_bounds;
437         if (m_bounds.Intersects(Rect(1,0,1,1)))
438         {
439                 m_bounds = Rect(m_bounds.x - 1, m_bounds.y, m_bounds.w, m_bounds.h);
440                 m_bounds_dirty = true;
441                 RenderQuadtreeNode(width, height, m_document.GetQuadTree().GetNeighbour(node, 1, 0, &m_document), remaining_depth - 1);
442         }
443         m_bounds = old_bounds;
444         if (m_bounds.Intersects(Rect(0,1,1,1)))
445         {
446                 m_bounds = Rect(m_bounds.x, m_bounds.y - 1, m_bounds.w, m_bounds.h);
447                 m_bounds_dirty = true;
448                 RenderQuadtreeNode(width, height, m_document.GetQuadTree().GetNeighbour(node, 0, 1, &m_document), remaining_depth - 1);
449         }
450         m_bounds = old_bounds;
451         m_bounds_dirty = true;
452
453 #if 0
454         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_LEFT);
455         m_bounds_dirty = true;
456         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_left, remaining_depth-1);
457         m_bounds = TransformToQuadChild(old_bounds, QTC_TOP_RIGHT);
458         m_bounds_dirty = true;
459         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].top_right, remaining_depth-1);
460         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_LEFT);
461         m_bounds_dirty = true;
462         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_left, remaining_depth-1);
463         m_bounds = TransformToQuadChild(old_bounds, QTC_BOTTOM_RIGHT);
464         m_bounds_dirty = true;
465         RenderQuadtreeNode(width, height, m_document.GetQuadTree().nodes[node].bottom_right, remaining_depth-1);
466         m_bounds = old_bounds;
467         m_bounds_dirty = true;
468 #endif
469 }
470 #endif
471
472 void View::RenderRange(int width, int height, unsigned first_obj, unsigned last_obj)
473 {
474         // We don't want to render an empty range,
475         // so don't waste time setting up everything.
476         if (first_obj == last_obj) return;
477         PROFILE_SCOPE("View::RenderRange");
478         glPushDebugGroup(GL_DEBUG_SOURCE_APPLICATION, 43, -1, "View::RenderRange()");
479
480         g_profiler.AddCounter("Objects Rendered", last_obj-first_obj);
481
482         if (m_render_dirty) // document has changed
483                 PrepareRender();
484
485
486         if (m_buffer_dirty || m_bounds_dirty || !m_lazy_rendering) // object bounds have changed
487         {
488                 if (m_use_gpu_rendering)
489                         UpdateObjBoundsVBO(first_obj, last_obj);
490         }
491
492
493         // Render using GPU
494         if (m_use_gpu_rendering) 
495         {
496
497                 if (m_use_gpu_transform)
498                 {
499                         #ifdef TRANSFORM_OBJECTS_NOT_VIEW
500                                 //Debug("Transform objects, not view");
501                                         GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f,
502                                                 0.0f, 0.0f, float(width), float(height)};
503                         #else
504                         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)),
505                                                 0.0, 0.0, static_cast<GLfloat>(width), static_cast<GLfloat>(height)};
506                         #endif
507                         m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
508                 }
509                 else
510                 {
511                         GLfloat glbounds[] = {0.0f, 0.0f, 1.0f, 1.0f,
512                                                 0.0f, 0.0f, float(width), float(height)};
513                         m_bounds_ubo.Upload(sizeof(float)*8, glbounds);
514                 }
515                 m_bounds_dirty = false;
516
517                 if (m_colour.a < 1.0f)
518                 {
519                         glEnable(GL_BLEND);
520                         glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
521                 }
522                 m_objbounds_vbo.Bind();
523                 m_bounds_ubo.Bind();
524                 glEnableVertexAttribArray(0);
525                 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
526         
527                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
528                 {
529                         m_object_renderers[i]->RenderUsingGPU(first_obj, last_obj);
530                 }
531                 
532                 glDisableVertexAttribArray(0);
533                 if (m_colour.a < 1.0f)
534                 {
535                         glDisable(GL_BLEND);
536                 }
537         }
538         else // Rasterise on CPU then blit texture to GPU
539         {
540
541                 for (unsigned i = 0; i < m_object_renderers.size(); ++i)
542                 {
543                         m_object_renderers[i]->RenderUsingCPU(m_document.m_objects, *this, {m_cpu_rendering_pixels, width, height}, first_obj, last_obj);
544                 }
545         }
546         glPopDebugGroup();
547 }
548
549 void View::UpdateObjBoundsVBO(unsigned first_obj, unsigned last_obj)
550 {
551         PROFILE_SCOPE("View::UpdateObjBoundsVBO");
552         if (m_query_gpu_bounds_on_next_frame != NULL)
553         {
554                 fprintf(m_query_gpu_bounds_on_next_frame,"# View: %s\t%s\t%s\t%s\n", Str(m_bounds.x).c_str(), Str(m_bounds.y).c_str(), Str(m_bounds.w).c_str(), Str(m_bounds.h).c_str());
555         }       
556         
557         //m_objbounds_vbo.Invalidate();
558         m_objbounds_vbo.SetType(GraphicsBuffer::BufferTypeVertex);
559         m_objbounds_vbo.SetName("Object Bounds VBO");
560         
561         #ifndef TRANSFORM_OBJECTS_NOT_VIEW
562         if (m_use_gpu_transform)
563         {
564                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
565         }
566         else
567         #endif //TRANSFORM_OBJECTS_NOT_VIEW
568         {
569                 m_objbounds_vbo.SetUsage(GraphicsBuffer::BufferUsageDynamicCopy);
570         }
571         m_objbounds_vbo.Resize(m_document.ObjectCount()*sizeof(GPUObjBounds));
572
573         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());
574
575         #ifndef TRANSFORM_BEZIERS_TO_PATH
576         for (unsigned id = first_obj; id < last_obj; ++id)
577         {
578                 Rect obj_bounds;
579                 if (m_use_gpu_transform)
580                 {
581                         obj_bounds = m_document.m_objects.bounds[id];
582                 }
583                 else
584                 {
585                         obj_bounds = TransformToViewCoords(m_document.m_objects.bounds[id]);
586                 }
587                 GPUObjBounds gpu_bounds = {
588                         Float(obj_bounds.x),
589                         Float(obj_bounds.y),
590                         Float(obj_bounds.x + obj_bounds.w),
591                         Float(obj_bounds.y + obj_bounds.h)
592                 };
593
594                 if (m_query_gpu_bounds_on_next_frame != NULL)
595                 {       
596                         fprintf(m_query_gpu_bounds_on_next_frame,"%d\t%f\t%f\t%f\t%f\n", id, Float(obj_bounds.x), Float(obj_bounds.y), Float(obj_bounds.w), Float(obj_bounds.h));
597                 }
598                 
599                 obj_bounds_builder.Add(gpu_bounds);
600         }
601         #else
602         for (unsigned i = 0; i < m_document.m_objects.paths.size(); ++i)
603         {
604                 Path & path = m_document.m_objects.paths[i];
605                 Rect & pbounds = path.GetBounds(m_document.m_objects); // Not very efficient...
606                 //TODO: Add clipping here
607                 //if (!pbounds.Intersects(Rect(0,0,1,1)) || pbounds.w < Real(1)/Real(800))
608                 //      continue;
609
610                 for (unsigned id = path.m_start; id <= path.m_end; ++id)
611                 {
612                         if (id < first_obj || id >= last_obj)
613                                 continue;
614                                 
615                         Rect obj_bounds = m_document.m_objects.bounds[id];
616                         obj_bounds.x *= pbounds.w;
617                         obj_bounds.x += pbounds.x;
618                         obj_bounds.y *= pbounds.h;
619                         obj_bounds.y += pbounds.y;
620                         obj_bounds.w *= pbounds.w;
621                         obj_bounds.h *= pbounds.h;
622                         
623                         if (!m_use_gpu_transform)
624                                 obj_bounds = TransformToViewCoords(obj_bounds);
625                         GPUObjBounds gpu_bounds = {
626                                 ClampFloat(obj_bounds.x),
627                                 ClampFloat(obj_bounds.y),
628                                 ClampFloat(obj_bounds.x + obj_bounds.w),
629                                 ClampFloat(obj_bounds.y + obj_bounds.h)
630                         };
631                         obj_bounds_builder.Add(gpu_bounds);
632                         //Debug("Path %d %s -> %s via %s", id, m_document.m_objects.bounds[id].Str().c_str(), obj_bounds.Str().c_str(), pbounds.Str().c_str()); 
633                         
634                         if (m_query_gpu_bounds_on_next_frame != NULL)
635                         {
636                                 fprintf(m_query_gpu_bounds_on_next_frame,"%d\t%f\t%f\t%f\t%f\n", id, ClampFloat(obj_bounds.x), ClampFloat(obj_bounds.y), ClampFloat(obj_bounds.w), ClampFloat(obj_bounds.h));
637                         }
638                 }
639                 GPUObjBounds p_gpu_bounds = {
640                                 ClampFloat(pbounds.x),
641                                 ClampFloat(pbounds.y),
642                                 ClampFloat(pbounds.x + pbounds.w),
643                                 ClampFloat(pbounds.y + pbounds.h)
644                 };              
645                 obj_bounds_builder.Add(p_gpu_bounds);
646         }
647         #endif
648         if (m_query_gpu_bounds_on_next_frame != NULL)
649         {
650                 if (m_query_gpu_bounds_on_next_frame != stdout && m_query_gpu_bounds_on_next_frame != stderr)
651                         fclose(m_query_gpu_bounds_on_next_frame);
652                 m_query_gpu_bounds_on_next_frame = NULL;
653         }
654         m_objbounds_vbo.UnMap();
655 }
656 /**
657  * Prepare the document for rendering
658  * Will be called on View::Render if m_render_dirty is set
659  * (Called at least once, on the first Render)
660  */
661 void View::PrepareRender()
662 {
663         PROFILE_SCOPE("View::PrepareRender()");
664         Debug("Recreate buffers with %u objects", m_document.ObjectCount());
665         // Prepare bounds vbo
666         if (UsingGPURendering())
667         {
668                 m_bounds_ubo.Invalidate();
669                 m_bounds_ubo.SetType(GraphicsBuffer::BufferTypeUniform);
670                 m_bounds_ubo.SetUsage(GraphicsBuffer::BufferUsageStreamDraw);
671                 m_bounds_ubo.SetName("m_bounds_ubo: Screen bounds.");
672         }
673         
674         // Instead of having each ObjectRenderer go through the whole document
675         //  we initialise them, go through the document once adding to the appropriate Renderers
676         //  and then finalise them
677         // This will totally be efficient if we have like, a lot of distinct ObjectTypes. Which could totally happen. You never know.
678
679         // Prepare the buffers
680         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
681         {
682                 m_object_renderers[i]->PrepareBuffers(m_document.ObjectCount());
683         }
684
685         // Add objects from Document to buffers
686         for (unsigned id = 0; id < m_document.ObjectCount(); ++id)
687         {
688                 ObjectType type = m_document.m_objects.types[id];
689                 m_object_renderers.at(type)->AddObjectToBuffers(id); // Use at() in case the document is corrupt TODO: Better error handling?
690                 // (Also, Wow I just actually used std::vector::at())
691                 // (Also, I just managed to make it throw an exception because I'm a moron)
692                 //Debug("Object of type %d", type);
693         }
694
695
696         // Finish the buffers
697         for (unsigned i = 0; i < m_object_renderers.size(); ++i)
698         {
699                 m_object_renderers[i]->FinaliseBuffers();
700         }
701         if (UsingGPURendering())
702         {
703                 dynamic_cast<BezierRenderer*>(m_object_renderers[BEZIER])->PrepareBezierGPUBuffer(m_document.m_objects);
704         }
705         m_render_dirty = false;
706 }
707
708 void View::SaveCPUBMP(const char * filename)
709 {
710         bool prev = UsingGPURendering();
711         SetGPURendering(false);
712         Render(800, 600);
713         ObjectRenderer::SaveBMP({m_cpu_rendering_pixels, 800, 600}, filename);
714         SetGPURendering(prev);
715 }
716
717 void View::SaveGPUBMP(const char * filename)
718 {
719         bool prev = UsingGPURendering();
720         SetGPURendering(true);
721         Render(800,600);
722         m_screen.ScreenShot(filename);
723         SetGPURendering(prev);  
724 }
725
726 void View::QueryGPUBounds(const char * filename, const char * mode)
727 {
728         m_query_gpu_bounds_on_next_frame = fopen(filename, mode); 
729         Debug("File: %s", filename);
730         if (m_query_gpu_bounds_on_next_frame == NULL)
731                 Error("Couldn't open file \"%s\" : %s", filename, strerror(errno));
732         ForceBoundsDirty(); 
733         ForceBufferDirty(); 
734         ForceRenderDirty();
735 }

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