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

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