Render part of a document (incorrectly) on the GPU
[ipdf/code.git] / src / objectrenderer.cpp
1 /**
2  * @file objectrenderer.cpp
3  * @brief Implements ObjectRenderer and derived classes
4  */
5
6 #include "objectrenderer.h"
7 #include "view.h"
8
9 using namespace std;
10
11 namespace IPDF
12 {
13
14 /**
15  * ObjectRenderer constructor
16  * Note we cannot compile the shaders in the ShaderProgram constructor
17  *  because the Screen class needs to initialise GL first and it has a
18  *      ShaderProgram member
19  */
20 ObjectRenderer::ObjectRenderer(const ObjectType & type, 
21                 const char * vert_glsl_file, const char * frag_glsl_file, const char * geom_glsl_file)
22                 : m_type(type), m_shader_program(), m_indexes(), m_buffer_builder(NULL)
23 {
24         m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
25         m_shader_program.Use();
26         glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
27 }
28
29 /**
30  * Render using GPU
31  */
32 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
33 {
34         unsigned first_index = 0;
35         while (m_indexes[first_index] < first_obj_id*2) first_index += 2;
36         unsigned last_index = first_index;
37         while (m_indexes[last_index] < last_obj_id*2) last_index += 2;
38
39         m_shader_program.Use();
40         m_ibo.Bind();
41         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(first_index*sizeof(uint32_t)));
42 }
43
44
45 /**
46  * Default implementation for rendering using CPU
47  */
48 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
49 {
50         Error("Cannot render objects of type %d on CPU", m_type);
51         //TODO: Render a rect or something instead?
52 }
53
54 /**
55  * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
56  */
57 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
58 {
59         if (m_buffer_builder != NULL) // We already have a BufferBuilder
60         {
61                 Fatal("Has been called before, without FinaliseBuffers being called since!");
62         }
63         // Empty and reserve the indexes vector (for CPU rendering)
64         m_indexes.clear();
65         m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
66
67         // Initialise and resize the ibo (for GPU rendering)
68         m_ibo.Invalidate();
69         m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
70         m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
71         m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
72         // BufferBuilder is used to construct the ibo
73         m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
74
75 }
76
77 /**
78  * Add object index to the buffers for CPU and GPU rendering
79  */
80 void ObjectRenderer::AddObjectToBuffers(unsigned index)
81 {
82         if (m_buffer_builder == NULL) // No BufferBuilder!
83         {
84                 Fatal("Called without calling PrepareBuffers");
85         }
86         m_buffer_builder->Add(2*index); // ibo for GPU rendering
87         m_buffer_builder->Add(2*index+1);
88         m_indexes.push_back(index); // std::vector of indices for CPU rendering
89 }
90
91 /**
92  * Finalise the index buffers for CPU and GPU rendering
93  */
94 void ObjectRenderer::FinaliseBuffers()
95 {
96         if (m_buffer_builder == NULL) // No BufferBuilder!
97         {
98                 Fatal("Called without calling PrepareBuffers");
99         }
100         // For GPU rendering, UnMap the ibo
101         m_ibo.UnMap();
102         // ... and delete the BufferBuilder used to create it
103         delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
104         m_buffer_builder = NULL;
105         
106         // Nothing is necessary for CPU rendering
107 }
108
109
110 /**
111  * Rectangle (filled)
112  */
113 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
114 {
115         for (unsigned i = 0; i < m_indexes.size(); ++i)
116         {
117                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
118                 for (int64_t x = max(0L, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
119                 {
120                         for (int64_t y = max(0L, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
121                         {
122                                 int index = (x+target.w*y)*4;
123                                 target.pixels[index+0] = 0;
124                                 target.pixels[index+1] = 0;
125                                 target.pixels[index+2] = 0;
126                                 target.pixels[index+3] = 255;
127                         }
128                 }
129         }
130 }
131
132 /**
133  * Rectangle (outine)
134  */
135 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
136 {
137         //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
138         for (unsigned i = 0; i < m_indexes.size(); ++i)
139         {
140                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
141                 
142                 // Using bresenham's lines now mainly because I want to see if they work
143                 // top
144                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
145                 // bottom
146                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
147                 // left
148                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
149                 // right
150                 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
151
152                 // Diagonal for testing (from bottom left to top right)
153                 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
154                 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
155         }
156 }
157
158 /**
159  * Circle (filled)
160  */
161 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
162 {
163         for (unsigned i = 0; i < m_indexes.size(); ++i)
164         {
165                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
166                 int64_t centre_x = bounds.x + bounds.w / 2;
167                 int64_t centre_y = bounds.y + bounds.h / 2;
168                 
169                 //Debug("Centre is %d, %d", centre_x, centre_y);
170                 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
171                 //Debug("Windos is %d,%d", target.w, target.h);
172                 for (int64_t x = max(0L, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
173                 {
174                         for (int64_t y = max(0L, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
175                         {
176                                 double dx = 2.0*(double)(x - centre_x)/(double)(bounds.w);
177                                 double dy = 2.0*(double)(y - centre_y)/(double)(bounds.h);
178                                 int64_t index = (x+target.w*y)*4;
179                                 
180                                 if (dx*dx + dy*dy <= 1.0)
181                                 {
182                                         target.pixels[index+0] = 0;
183                                         target.pixels[index+1] = 0;
184                                         target.pixels[index+2] = 0;
185                                         target.pixels[index+3] = 255;
186
187                                 }
188                         }
189                 }
190         }
191 }
192
193 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
194 {
195         Rect result = view.TransformToViewCoords(bounds);
196         result.x *= Real(target.w);
197         result.y *= Real(target.h);
198         result.w *= Real(target.w);
199         result.h *= Real(target.h);
200         return result;
201 }
202         
203
204 /**
205  * Bezier curve
206  * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
207  */
208 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target)
209 {
210         //Warn("Rendering Beziers on CPU. Things may explode.");
211         for (unsigned i = 0; i < m_indexes.size(); ++i)
212         {
213                 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
214                 PixelBounds pix_bounds(bounds);
215
216
217                 Bezier control(objects.beziers[objects.data_indices[m_indexes[i]]], bounds);
218                 //Debug("%s -> %s via %s", objects.beziers[objects.data_indices[m_indexes[i]]].Str().c_str(), control.Str().c_str(), bounds.Str().c_str());
219                 // Draw a rectangle around the bezier for debugging the coord transforms
220                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target);
221                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y+pix_bounds.h, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target);
222                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target);
223                 //ObjectRenderer::RenderLineOnCPU(pix_bounds.x+pix_bounds.w, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target);
224         
225                 // Draw lines between the control points for debugging
226                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x0, (int64_t)control.y0, (int64_t)control.x1, (int64_t)control.y1,target);
227                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x1, (int64_t)control.y1, (int64_t)control.x2, (int64_t)control.y2,target);
228                                                                                 
229
230                 
231                 Real x[2]; Real y[2];
232                 control.Evaluate(x[0], y[0], Real(0));
233                 int64_t blen = max(2L, min(100L, pix_bounds.w));
234                 Real invblen(1); invblen /= blen;
235                 Debug("Using %li lines, inverse %f", blen, Double(invblen));
236                 for (int64_t j = 1; j <= blen; ++j)
237                 {
238                         control.Evaluate(x[j % 2],y[j % 2], invblen*j);
239                         ObjectRenderer::RenderLineOnCPU((int64_t)Double(x[0]),(int64_t)Double(y[0]), (int64_t)Double(x[1]),(int64_t)Double(y[1]), target);
240                 }
241                 
242                 /*
243                 Real u(0);
244                 while (u < Real(1))
245                 {
246                         u += Real(1e-6);
247                         Real x; Real y; control.Evaluate(x,y,u);
248                         int64_t index = ((int64_t)x + (int64_t)y*target.w)*4;
249                         if (index >= 0 && index < 4*(target.w*target.h))
250                         {
251                                 target.pixels[index+0] = 0;
252                                 target.pixels[index+1] = 0;
253                                 target.pixels[index+2] = 0;
254                                 target.pixels[index+3] = 255;
255                         }       
256                 }
257                 */
258                 
259         }
260 }
261
262 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
263 {
264         m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
265         m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
266         m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
267         BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
268
269         for (auto bez : objects.beziers)
270         {
271                 GPUBezierCoeffs coeffs = {
272                         Float(bez.x0), Float(bez.y0),
273                         Float(bez.x1 - bez.x0), Float(bez.y1 - bez.y0),
274                         Float(bez.x2 - bez.x0), Float(bez.y2 - bez.y0)
275                         };
276                 builder.Add(coeffs);
277         }
278         m_bezier_coeffs.UnMap();
279         glGenTextures(1, &m_bezier_buffer_texture);
280         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
281         glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
282
283         m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
284         m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
285         m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
286         
287         glGenTextures(1, &m_bezier_id_buffer_texture);
288         glActiveTexture(GL_TEXTURE1);
289         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
290         glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
291         glActiveTexture(GL_TEXTURE0);
292 }
293
294 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
295 {
296         if (!m_shader_program.Valid())
297                 Warn("Shader is invalid (objects are of type %d)", m_type);
298
299         unsigned first_index = 0;
300         while (m_indexes[first_index] < first_obj_id*2) first_index += 2;
301         unsigned last_index = first_index;
302         while (m_indexes[last_index] < last_obj_id*2) last_index += 2;
303
304         m_shader_program.Use();
305         glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
306         glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
307         m_ibo.Bind();
308         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(first_index*sizeof(uint32_t)));
309 }
310
311 /**
312  * For debug, save pixels to bitmap
313  */
314 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
315 {
316         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
317         #if SDL_BYTEORDER == SDL_LIL_ENDIAN
318                 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
319         #else
320                 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
321         #endif //SDL_BYTEORDER  
322         );      
323         if (surf == NULL)
324                 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
325         if (SDL_SaveBMP(surf, filename) != 0)
326                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
327
328         // Cleanup
329         SDL_FreeSurface(surf);
330 }
331
332 /**
333  * Bresenham's lines
334  */
335 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
336 {
337         int64_t dx = x1 - x0;
338         int64_t dy = y1 - y0;
339         bool neg_m = (dy*dx < 0);
340         dy = abs(dy);
341         dx = abs(dx);
342
343         // If positive slope > 1, just swap x and y
344         if (dy > dx)
345         {
346                 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
347                 return;
348         }
349
350         int64_t two_dy = 2*dy;
351         int64_t p = two_dy - dx;
352         int64_t two_dxdy = 2*(dy-dx);
353         int64_t x; int64_t y; int64_t x_end;
354         int64_t width = (transpose ? target.h : target.w);
355         int64_t height = (transpose ? target.w : target.h);
356
357         uint8_t rgba[4];
358         rgba[0] = 255*colour.r;
359         rgba[1] = 255*colour.g;
360         rgba[2] = 255*colour.b;
361         rgba[3] = 255*colour.a;
362
363         if (x0 > x1)
364         {
365                 x = x1;
366                 y = y1;
367                 x_end = x0;
368         }
369         else
370         {
371                 x = x0;
372                 y = y0;
373                 x_end = x1;
374         }
375
376         if (x < 0)
377         {
378                 if (x_end < 0) return;
379                 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
380                 x = 0;
381         }
382         
383         if (x_end > width)
384         {
385                 if (x > width) return;
386                 x_end = width-1;
387         }
388
389         // TODO: Avoid extra inner conditionals
390         do
391         {
392                 if (x >= 0 && x < width && y >= 0 && y < height)
393                 {
394                         int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
395                         for (int i = 0; i < 4; ++i)
396                                 target.pixels[index+i] = rgba[i];
397                 }
398                 
399                 if (p < 0)
400                         p += two_dy;
401                 else
402                 {
403                         if (neg_m) --y; else ++y;
404                         p += two_dxdy;
405                 }
406         } while (++x < x_end);
407 }
408
409 }

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