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

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