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

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