4e59cd001fc5d0f71de074b9c29cbb59303e37b5
[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 #include <vector>
9 #include <queue>
10 #include <stack>
11
12 using namespace std;
13
14 namespace IPDF
15 {
16
17 /**
18  * ObjectRenderer constructor
19  * Note we cannot compile the shaders in the ShaderProgram constructor
20  *  because the Screen class needs to initialise GL first and it has a
21  *      ShaderProgram member
22  */
23 ObjectRenderer::ObjectRenderer(const ObjectType & type, 
24                 const char * vert_glsl_file, const char * frag_glsl_file, const char * geom_glsl_file)
25                 : m_type(type), m_shader_program(), m_indexes(), m_buffer_builder(NULL)
26 {
27         m_shader_program.InitialiseShaders(vert_glsl_file, frag_glsl_file, geom_glsl_file);
28         m_shader_program.Use();
29         glUniform4f(m_shader_program.GetUniformLocation("colour"), 0,0,0,1); //TODO: Allow different colours
30 }
31
32 /**
33  * Render using GPU
34  */
35 void ObjectRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
36 {
37         // If we don't have anything to render, return.
38         if (first_obj_id == last_obj_id) return;
39         // If there are no objects of this type, return.
40         if (m_indexes.empty()) return;
41         unsigned first_index = 0;
42         while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
43         unsigned last_index = first_index;
44         while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
45
46         m_shader_program.Use();
47         m_ibo.Bind();
48         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
49 }
50
51
52 /**
53  * Default implementation for rendering using CPU
54  */
55 void ObjectRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
56 {
57         Error("Cannot render objects of type %d on CPU", m_type);
58         //TODO: Render a rect or something instead?
59 }
60
61 /**
62  * Prepare index buffers for both CPU and GPU rendering to receive indexes (but don't add any yet!)
63  */
64 void ObjectRenderer::PrepareBuffers(unsigned max_objects)
65 {
66         if (m_buffer_builder != NULL) // We already have a BufferBuilder
67         {
68                 Fatal("Has been called before, without FinaliseBuffers being called since!");
69         }
70         // Empty and reserve the indexes vector (for CPU rendering)
71         m_indexes.clear();
72         m_indexes.reserve(max_objects); //TODO: Can probably make this smaller? Or leave it out? Do we care?
73
74         // Initialise and resize the ibo (for GPU rendering)
75         m_ibo.Invalidate();
76         m_ibo.SetUsage(GraphicsBuffer::BufferUsageStaticDraw);
77         m_ibo.SetType(GraphicsBuffer::BufferTypeIndex);
78         m_ibo.Resize(max_objects * 2 * sizeof(uint32_t));
79         // BufferBuilder is used to construct the ibo
80         m_buffer_builder = new BufferBuilder<uint32_t>(m_ibo.Map(false, true, true), m_ibo.GetSize()); // new matches delete in ObjectRenderer::FinaliseBuffers
81
82 }
83
84 /**
85  * Add object index to the buffers for CPU and GPU rendering
86  */
87 void ObjectRenderer::AddObjectToBuffers(unsigned index)
88 {
89         if (m_buffer_builder == NULL) // No BufferBuilder!
90         {
91                 Fatal("Called without calling PrepareBuffers");
92         }
93         m_buffer_builder->Add(2*index); // ibo for GPU rendering
94         m_buffer_builder->Add(2*index+1);
95         m_indexes.push_back(index); // std::vector of indices for CPU rendering
96 }
97
98 /**
99  * Finalise the index buffers for CPU and GPU rendering
100  */
101 void ObjectRenderer::FinaliseBuffers()
102 {
103         if (m_buffer_builder == NULL) // No BufferBuilder!
104         {
105                 Fatal("Called without calling PrepareBuffers");
106         }
107         // For GPU rendering, UnMap the ibo
108         m_ibo.UnMap();
109         // ... and delete the BufferBuilder used to create it
110         delete m_buffer_builder; // delete matches new in ObjectRenderer::PrepareBuffers
111         m_buffer_builder = NULL;
112         
113         // Nothing is necessary for CPU rendering
114 }
115
116
117 /**
118  * Rectangle (filled)
119  */
120 void RectFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
121 {
122         for (unsigned i = 0; i < m_indexes.size(); ++i)
123         {
124                 if (m_indexes[i] < first_obj_id) continue;
125                 if (m_indexes[i] >= last_obj_id) continue;
126                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
127                 FloodFillOnCPU(bounds.x+1, bounds.y+1, bounds, target, Colour(0,0,0,1));
128                 /*
129                 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
130                 {
131                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y+bounds.h, target.h-1); ++y)
132                         {
133                                 int index = (x+target.w*y)*4;
134                                 target.pixels[index+0] = 0;
135                                 target.pixels[index+1] = 0;
136                                 target.pixels[index+2] = 0;
137                                 target.pixels[index+3] = 255;
138                         }
139                 }
140                 */
141         }
142 }
143
144 /**
145  * Rectangle (outine)
146  */
147 void RectOutlineRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
148 {
149         //Debug("Render %u outlined rectangles on CPU", m_indexes.size());
150         for (unsigned i = 0; i < m_indexes.size(); ++i)
151         {
152                 if (m_indexes[i] < first_obj_id) continue;
153                 if (m_indexes[i] >= last_obj_id) continue;
154                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
155                 
156                 // Using bresenham's lines now mainly because I want to see if they work
157                 // top
158                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x+bounds.w, bounds.y, target);
159                 // bottom
160                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y+bounds.h, bounds.x+bounds.w, bounds.y+bounds.h, target);
161                 // left
162                 ObjectRenderer::RenderLineOnCPU(bounds.x, bounds.y, bounds.x, bounds.y+bounds.h, target);
163                 // right
164                 ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y, bounds.x+bounds.w, bounds.y+bounds.h, target);
165
166                 // Diagonal for testing (from bottom left to top right)
167                 //ObjectRenderer::RenderLineOnCPU(bounds.x,bounds.y+bounds.h, bounds.x+bounds.w, bounds.y,target, C_BLUE);
168                 //ObjectRenderer::RenderLineOnCPU(bounds.x+bounds.w, bounds.y+bounds.h, bounds.x, bounds.y, target,C_GREEN);
169         }
170 }
171
172 /**
173  * Circle (filled)
174  */
175 void CircleFilledRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
176 {
177         for (unsigned i = 0; i < m_indexes.size(); ++i)
178         {
179                 if (m_indexes[i] < first_obj_id) continue;
180                 if (m_indexes[i] >= last_obj_id) continue;
181                 PixelBounds bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
182                 int64_t centre_x = bounds.x + bounds.w / 2;
183                 int64_t centre_y = bounds.y + bounds.h / 2;
184                 
185                 //Debug("Centre is %d, %d", centre_x, centre_y);
186                 //Debug("Bounds are %d,%d,%d,%d", bounds.x, bounds.y, bounds.w, bounds.h);
187                 //Debug("Windos is %d,%d", target.w, target.h);
188                 for (int64_t x = max((int64_t)0, bounds.x); x <= min(bounds.x+bounds.w, target.w-1); ++x)
189                 {
190                         for (int64_t y = max((int64_t)0, bounds.y); y <= min(bounds.y + bounds.h, target.h-1); ++y)
191                         {
192                                 Real dx(2); dx *= Real(x - centre_x)/Real(bounds.w);
193                                 Real dy(2); dy *= Real(y - centre_y)/Real(bounds.h);
194                                 int64_t index = (x+target.w*y)*4;
195                                 
196                                 if (dx*dx + dy*dy <= Real(1))
197                                 {
198                                         target.pixels[index+0] = 0;
199                                         target.pixels[index+1] = 0;
200                                         target.pixels[index+2] = 0;
201                                         target.pixels[index+3] = 255;
202                                 }
203                         }
204                 }
205         }
206 }
207
208 Rect ObjectRenderer::CPURenderBounds(const Rect & bounds, const View & view, const CPURenderTarget & target)
209 {
210         Rect result = view.TransformToViewCoords(bounds);
211         result.x *= Real(target.w);
212         result.y *= Real(target.h);
213         result.w *= Real(target.w);
214         result.h *= Real(target.h);
215         return result;
216 }
217
218 ObjectRenderer::PixelPoint ObjectRenderer::CPUPointLocation(const Vec2 & point, const View & view, const CPURenderTarget & target)
219 {
220         // hack...
221         Rect result = view.TransformToViewCoords(Rect(point.x, point.y,1,1));
222         int64_t x = result.x*target.w;
223         int64_t y = result.y*target.h;
224         return PixelPoint(x,y);
225 }
226         
227
228 /**
229  * Bezier curve
230  * Not sure how to apply De'Casteljau, will just use a bunch of Bresnham lines for now.
231  */
232 void BezierRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
233 {
234         //Warn("Rendering Beziers on CPU. Things may explode.");
235         for (unsigned i = 0; i < m_indexes.size(); ++i)
236         {
237                 if (m_indexes[i] < first_obj_id) continue;
238                 if (m_indexes[i] >= last_obj_id) continue;
239                 const Rect & bounds = objects.bounds[m_indexes[i]];
240                 PixelBounds pix_bounds(CPURenderBounds(bounds,view,target));
241
242                 Bezier control(objects.beziers[objects.data_indices[m_indexes[i]]].ToAbsolute(bounds),CPURenderBounds(Rect(0,0,1,1), view, target));
243                 //Debug("%s -> %s via %s", objects.beziers[objects.data_indices[m_indexes[i]]].Str().c_str(), control.Str().c_str(), bounds.Str().c_str());
244                 // Draw a rectangle around the bezier for debugging the bounds rectangle calculations
245                 if (view.ShowingObjectBounds())
246                 {
247                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y, target, Colour(1,0,0,1));
248                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y+pix_bounds.h, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target, Colour(0,1,0,1));
249                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x, pix_bounds.y, pix_bounds.x, pix_bounds.y+pix_bounds.h, target, Colour(1,0,0,1));
250                         ObjectRenderer::RenderLineOnCPU(pix_bounds.x+pix_bounds.w, pix_bounds.y, pix_bounds.x+pix_bounds.w, pix_bounds.y+pix_bounds.h, target, Colour(0,1,0,1));
251                 }
252                 // Draw lines between the control points for debugging
253                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x0, (int64_t)control.y0, (int64_t)control.x1, (int64_t)control.y1,target);
254                 //ObjectRenderer::RenderLineOnCPU((int64_t)control.x1, (int64_t)control.y1, (int64_t)control.x2, (int64_t)control.y2,target);
255                                                                                 
256
257                 
258         
259                 unsigned blen = min(max(2U, (unsigned)(target.w/view.GetBounds().w)), min((unsigned)(pix_bounds.w+pix_bounds.h)/4 + 1, 100U));
260                 
261                 // DeCasteljau Divide the Bezier
262                 queue<Bezier> divisions;
263                 divisions.push(control);
264                 while(divisions.size() < blen)
265                 {
266                         Bezier & current = divisions.front();
267                         if (current.GetType() == Bezier::LINE)
268                         {
269                                 --blen;
270                                 continue;
271                         }
272                         divisions.push(current.DeCasteljauSubdivideRight(Real(1)/Real(2)));     
273                         divisions.push(current.DeCasteljauSubdivideLeft(Real(1)/Real(2)));
274                         divisions.pop();
275                         
276                         //Debug("divisions %u", divisions.size());
277                 }
278                 while (divisions.size() > 0)
279                 {
280                         Bezier & current = divisions.front();
281                         RenderLineOnCPU(current.x0, current.y0, current.x3, current.y3, target, Colour(0,0,0,!view.PerformingShading()));
282                         divisions.pop();
283                 }
284                 
285                 /* Draw the Bezier by sampling
286                 Real invblen(1); invblen /= blen;
287                 Real t(invblen);
288                 Vec2 v0;
289                 Vec2 v1;
290                 control.Evaluate(v0.x, v0.y, 0);
291                 for (int64_t j = 1; j <= blen; ++j)
292                 {
293                         control.Evaluate(v1.x, v1.y, t);
294                         
295                         ObjectRenderer::RenderLineOnCPU(v0.x, v0.y, v1.x, v1.y, target, Colour(0,0,0,!view.PerformingShading()));
296                         //ObjectRenderer::SetColour(target, x[0], y[0], Colour(1,0,0,1));
297                         //ObjectRenderer::SetColour(target, x[1], y[1], Colour(0,0,1,1));
298                         t += invblen;
299                         v0 = v1;
300                 }
301                 */
302         }
303 }
304
305 void BezierRenderer::PrepareBezierGPUBuffer(const Objects& objects)
306 {
307         m_bezier_coeffs.SetType(GraphicsBuffer::BufferTypeTexture);
308         m_bezier_coeffs.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
309         m_bezier_coeffs.Resize(objects.beziers.size()*sizeof(GPUBezierCoeffs));
310         BufferBuilder<GPUBezierCoeffs> builder(m_bezier_coeffs.Map(false, true, true), m_bezier_coeffs.GetSize());
311
312
313         for (unsigned i = 0; i < objects.beziers.size(); ++i)
314         {
315                 const Bezier & bez = objects.beziers[i];
316                 
317                 GPUBezierCoeffs coeffs = {
318                         Float(bez.x0), Float(bez.y0),
319                         Float(bez.x1), Float(bez.y1),
320                         Float(bez.x2), Float(bez.y2),
321                         Float(bez.x3), Float(bez.y3)
322                         };
323                 builder.Add(coeffs);
324         }
325         m_bezier_coeffs.UnMap();
326         glGenTextures(1, &m_bezier_buffer_texture);
327         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_buffer_texture);
328         glTexBuffer(GL_TEXTURE_BUFFER, GL_RG32F, m_bezier_coeffs.GetHandle());
329
330         m_bezier_ids.SetType(GraphicsBuffer::BufferTypeTexture);
331         m_bezier_ids.SetUsage(GraphicsBuffer::BufferUsageDynamicDraw);
332         m_bezier_ids.Upload(objects.data_indices.size() * sizeof(uint32_t), &objects.data_indices[0]);
333         
334         glGenTextures(1, &m_bezier_id_buffer_texture);
335         glActiveTexture(GL_TEXTURE1);
336         glBindTexture(GL_TEXTURE_BUFFER, m_bezier_id_buffer_texture);
337         glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, m_bezier_ids.GetHandle());
338         glActiveTexture(GL_TEXTURE0);
339 }
340
341 void BezierRenderer::RenderUsingGPU(unsigned first_obj_id, unsigned last_obj_id)
342 {
343         if (!m_shader_program.Valid())
344                 Warn("Shader is invalid (objects are of type %d)", m_type);
345
346         // If we don't have anything to render, return.
347         if (first_obj_id == last_obj_id) return;
348         // If there are no objects of this type, return.
349         if (m_indexes.empty()) return;
350
351         unsigned first_index = 0;
352         while (m_indexes.size() > first_index && m_indexes[first_index] < first_obj_id) first_index ++;
353         unsigned last_index = first_index;
354         while (m_indexes.size() > last_index && m_indexes[last_index] < last_obj_id) last_index ++;
355
356         m_shader_program.Use();
357         glUniform1i(m_shader_program.GetUniformLocation("bezier_buffer_texture"), 0);
358         glUniform1i(m_shader_program.GetUniformLocation("bezier_id_buffer_texture"), 1);
359         m_ibo.Bind();
360         glDrawElements(GL_LINES, (last_index-first_index)*2, GL_UNSIGNED_INT, (GLvoid*)(2*first_index*sizeof(uint32_t)));
361 }
362
363
364
365 /**
366  * Render Path (shading)
367  */
368 void PathRenderer::RenderUsingCPU(const Objects & objects, const View & view, const CPURenderTarget & target, unsigned first_obj_id, unsigned last_obj_id)
369 {
370         if (!view.ShowingObjectBounds() && !view.PerformingShading())
371                 return;
372                 
373         for (unsigned i = 0; i < m_indexes.size(); ++i)
374         {
375                 if (m_indexes[i] < first_obj_id) continue;
376                 if (m_indexes[i] >= last_obj_id) continue;
377                 
378                 
379                 Rect bounds(CPURenderBounds(objects.bounds[m_indexes[i]], view, target));
380                 PixelBounds pix_bounds(bounds);
381                 const Path & path = objects.paths[objects.data_indices[m_indexes[i]]];
382                 if (path.m_fill.a == 0 || !view.PerformingShading())
383                         continue;
384                 
385                 for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
386                 {
387                         PixelPoint fill_point(CPUPointLocation(path.m_fill_points[f], view, target));
388                         FloodFillOnCPU(fill_point.first, fill_point.second, pix_bounds, target, path.m_fill);
389                 }
390                 
391                 /*if (true)//(view.ShowingObjectBounds())
392                 {
393                         
394                         PixelPoint start(CPUPointLocation((path.m_top+path.m_left+path.m_right+path.m_bottom)/4, view, target));
395                         for (unsigned f = 0; f < path.m_fill_points.size(); ++f)
396                         {
397                                 PixelPoint end(CPUPointLocation(path.m_fill_points[f], view, target));
398                                 RenderLineOnCPU(start.first, start.second, end.first, end.second, target, Colour(0,0,1,1));
399                         }
400                 }
401                 */
402         
403         }       
404 }
405
406 /**
407  * For debug, save pixels to bitmap
408  */
409 void ObjectRenderer::SaveBMP(const CPURenderTarget & target, const char * filename)
410 {
411         SDL_Surface * surf = SDL_CreateRGBSurfaceFrom(target.pixels, target.w, target.h, 8*4, target.w*4,
412         #if SDL_BYTEORDER == SDL_LIL_ENDIAN
413                 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000
414         #else
415                 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff
416         #endif //SDL_BYTEORDER  
417         );      
418         if (surf == NULL)
419                 Fatal("SDL_CreateRGBSurfaceFrom(pixels...) failed - %s", SDL_GetError());
420         if (SDL_SaveBMP(surf, filename) != 0)
421                 Fatal("SDL_SaveBMP failed - %s", SDL_GetError());
422
423         // Cleanup
424         SDL_FreeSurface(surf);
425 }
426
427 /**
428  * Bresenham's lines
429  */
430 void ObjectRenderer::RenderLineOnCPU(int64_t x0, int64_t y0, int64_t x1, int64_t y1, const CPURenderTarget & target, const Colour & colour, bool transpose)
431 {
432         int64_t dx = x1 - x0;
433         int64_t dy = y1 - y0;
434         bool neg_m = (dy*dx < 0);
435         dy = abs(dy);
436         dx = abs(dx);
437
438         // If positive slope > 1, just swap x and y
439         if (dy > dx)
440         {
441                 RenderLineOnCPU(y0,x0,y1,x1,target,colour,!transpose);
442                 return;
443         }
444
445         int64_t two_dy = 2*dy;
446         int64_t p = two_dy - dx;
447         int64_t two_dxdy = 2*(dy-dx);
448         int64_t x; int64_t y; int64_t x_end;
449         int64_t width = (transpose ? target.h : target.w);
450         int64_t height = (transpose ? target.w : target.h);
451
452         uint8_t rgba[4];
453         rgba[0] = 255*colour.r;
454         rgba[1] = 255*colour.g;
455         rgba[2] = 255*colour.b;
456         rgba[3] = 255*colour.a;
457
458         if (x0 > x1)
459         {
460                 x = x1;
461                 y = y1;
462                 x_end = x0;
463         }
464         else
465         {
466                 x = x0;
467                 y = y0;
468                 x_end = x1;
469         }
470
471         if (x < 0)
472         {
473                 if (x_end < 0) return;
474                 y = (neg_m ? y - (dy*-x)/dx : y + (dy*-x)/dx);
475                 x = 0;
476         }
477         
478         if (x_end > width)
479         {
480                 if (x > width) return;
481                 x_end = width-1;
482         }
483
484         // TODO: Avoid extra inner conditionals
485         do
486         {       
487                 if (x >= 0 && x < width && y >= 0 && y < height)
488                 {
489                         int64_t index = (transpose ? (y + x*target.w)*4 : (x + y*target.w)*4);
490                         for (int i = 0; i < 4; ++i)
491                                 target.pixels[index+i] = rgba[i];
492                 }
493                 if (p < 0)
494                         p += two_dy;
495                 else
496                 {
497                         if (neg_m) --y; else ++y;
498                         p += two_dxdy;
499                 }
500         } while (++x <= x_end);
501 }
502
503 void ObjectRenderer::FloodFillOnCPU(int64_t x, int64_t y, const PixelBounds & bounds, const CPURenderTarget & target, const Colour & fill)
504 {
505         if (fill == Colour(1,1,1,1))
506                 return;
507         queue<PixelPoint > traverse;
508         traverse.push(PixelPoint(x,y));
509         // now with 100% less stack overflows!
510         while (traverse.size() > 0)
511         {
512                 PixelPoint cur(traverse.front());
513                 traverse.pop();
514                 if (cur.first < 0 || cur.first < bounds.x || cur.first >= bounds.x+bounds.w || cur.first >= target.w ||
515                         cur.second < 0 || cur.second < bounds.y || cur.second >= bounds.y+bounds.h || cur.second >= target.h)
516                         continue;
517                 if (GetColour(target, cur.first, cur.second) != Colour(1,1,1,1))
518                         continue;
519                 SetColour(target, cur.first, cur.second, fill);
520                 
521
522                 traverse.push(PixelPoint(cur.first+1, cur.second));
523                 traverse.push(PixelPoint(cur.first-1, cur.second));
524                 traverse.push(PixelPoint(cur.first, cur.second-1));
525                 traverse.push(PixelPoint(cur.first, cur.second+1)); 
526         }
527 }
528
529 }

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