Still-broken quadtree shenanigans!
[ipdf/code.git] / src / document.cpp
1 #include "document.h"
2 #include "bezier.h"
3 #include <cstdio>
4 #include <fstream>
5
6 #include "stb_truetype.h"
7
8 using namespace IPDF;
9 using namespace std;
10
11 //TODO: Make this work for variable sized Reals
12
13 // Loads an std::vector<T> of size num_elements from a file.
14 template<typename T>
15 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
16 {
17         size_t structsread = 0;
18         dest.resize(num_elems);
19         structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
20         if (structsread != num_elems)
21                 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
22 }
23
24 // Saves an std::vector<T> to a file. Size must be saves separately.
25 template<typename T>
26 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
27 {
28         size_t written = 0;
29         written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
30         if (written != src.size())
31                 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
32 }
33
34 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
35 {
36         size_t written = 0;
37         written = fwrite(&type, sizeof(type), 1, dst_file);
38         if (written != 1)
39                 Fatal("Could not write Chunk header! (ID)");
40         written = fwrite(&size, sizeof(size), 1, dst_file);
41         if (written != 1)
42                 Fatal("Could not write Chunk header (size)!");
43 }
44
45 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
46 {
47         if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
48                 return false;
49         if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
50                 return false;
51         return true;
52 }
53
54 void Document::Save(const string & filename)
55 {
56         Debug("Saving document to file \"%s\"...", filename.c_str());
57         FILE * file = fopen(filename.c_str(), "w");
58         if (file == NULL)
59                 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
60
61         size_t written;
62         Debug("Number of objects (%u)...", ObjectCount());
63         WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
64         written = fwrite(&m_count, sizeof(m_count), 1, file);
65         if (written != 1)
66                 Fatal("Failed to write number of objects!");
67
68         Debug("Object types...");
69         WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
70         SaveStructVector<ObjectType>(file, m_objects.types);
71
72         Debug("Object bounds...");
73         WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
74         SaveStructVector<Rect>(file, m_objects.bounds);
75
76         Debug("Object data indices...");
77         WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
78         SaveStructVector<unsigned>(file, m_objects.data_indices);
79         
80         Debug("Bezier data...");
81         WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
82         SaveStructVector<Bezier>(file, m_objects.beziers);
83
84         int err = fclose(file);
85         if (err != 0)
86                 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
87
88         Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
89 }
90
91 #ifndef QUADTREE_DISABLED
92
93 void Document::GenBaseQuadtree()
94 {
95         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount()});
96         m_quadtree.root_id = 0;
97         GenQuadChild(0, QTC_TOP_LEFT);
98 }
99
100 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
101 {
102         QuadTreeIndex new_index = m_quadtree.nodes.size();
103         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0});
104
105         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
106         for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
107         {
108                 if (ContainedInQuadChild(m_objects.bounds[i], type))
109                 {
110                         m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[i], type));
111                         m_objects.types.push_back(m_objects.types[i]);
112                         m_objects.data_indices.push_back(m_objects.data_indices[i]);
113                         m_count++;
114                 }
115         }
116         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
117         switch (type)
118         {
119                 case QTC_TOP_LEFT:
120                         m_quadtree.nodes[parent].top_left = new_index;
121                         break;
122                 case QTC_TOP_RIGHT:
123                         m_quadtree.nodes[parent].top_right = new_index;
124                         break;
125                 case QTC_BOTTOM_LEFT:
126                         m_quadtree.nodes[parent].bottom_left = new_index;
127                         break;
128                 case QTC_BOTTOM_RIGHT:
129                         m_quadtree.nodes[parent].bottom_right = new_index;
130                         break;
131                 default:
132                         Fatal("Tried to add a QuadTree child of invalid type!");
133         }
134         return new_index;
135 }
136
137 // Reparent a quadtree node, making it the "type" child of a new node.
138 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
139 {
140         QuadTreeIndex new_index = m_quadtree.nodes.size();
141         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0});
142
143         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
144         for (unsigned i = m_quadtree.nodes[child].object_begin; i < m_quadtree.nodes[child].object_end; ++i)
145         {
146                 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
147                 m_objects.types.push_back(m_objects.types[i]);
148                 m_objects.data_indices.push_back(m_objects.data_indices[i]);
149                 m_count++;
150         }
151         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
152         switch (type)
153         {
154                 case QTC_TOP_LEFT:
155                         m_quadtree.nodes[new_index].top_left = child;
156                         break;
157                 case QTC_TOP_RIGHT:
158                         m_quadtree.nodes[new_index].top_right = child;
159                         break;
160                 case QTC_BOTTOM_LEFT:
161                         m_quadtree.nodes[new_index].bottom_left = child;
162                         break;
163                 case QTC_BOTTOM_RIGHT:
164                         m_quadtree.nodes[new_index].bottom_right = child;
165                         break;
166                 default:
167                         Fatal("Tried to add a QuadTree child of invalid type!");
168         }
169         return new_index;
170 }
171
172 #endif
173
174 void Document::Load(const string & filename)
175 {
176         m_objects.bounds.clear();
177         m_count = 0;
178         if (filename == "")
179         {
180                 Debug("Loaded empty document.");
181                 return;
182         }
183         Debug("Loading document from file \"%s\"", filename.c_str());
184         FILE * file = fopen(filename.c_str(), "r");
185         if (file == NULL)
186                 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
187
188         size_t read;
189
190         DocChunkTypes chunk_type;
191         uint32_t chunk_size;
192         while (ReadChunkHeader(file, chunk_type, chunk_size))
193         {
194                 switch(chunk_type)
195                 {
196                 case CT_NUMOBJS:
197                         read = fread(&m_count, sizeof(m_count), 1, file);
198                         if (read != 1)
199                                 Fatal("Failed to read number of objects!");
200                         Debug("Number of objects: %u", ObjectCount());
201                         break;
202                 case CT_OBJTYPES:
203                         Debug("Object types...");
204                         LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
205                         break;
206                 case CT_OBJBOUNDS:
207                         Debug("Object bounds...");
208                         LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
209                         break;
210                 case CT_OBJINDICES:
211                         Debug("Object data indices...");
212                         LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
213                         break;
214                 case CT_OBJBEZIERS:
215                         Debug("Bezier data...");
216                         LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
217                         break;
218                 }
219         }
220         Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
221 #ifndef QUADTREE_DISABLED
222         if (m_quadtree.root_id == QUADTREE_EMPTY)
223         {
224                 GenBaseQuadtree();
225         }
226 #endif
227 }
228
229 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
230 {
231         m_objects.types.push_back(type);
232         m_objects.bounds.push_back(bounds);
233         m_objects.data_indices.push_back(data_index);
234         ++m_count; // Why can't we just use the size of types or something?
235 }
236
237 unsigned Document::AddBezierData(const Bezier & bezier)
238 {
239         m_objects.beziers.push_back(bezier);
240         return m_objects.beziers.size()-1;
241 }
242
243
244 void Document::DebugDumpObjects()
245 {
246         Debug("Objects for Document %p are:", this);
247         for (unsigned id = 0; id < ObjectCount(); ++id)
248         {
249                 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
250         }
251 }
252
253 bool Document::operator==(const Document & equ) const
254 {
255         return (ObjectCount() == equ.ObjectCount() 
256                 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
257                 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
258                 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
259 }
260
261
262 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
263 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
264
265 /**
266  * Load an SVG into a rectangle
267  */
268 void Document::LoadSVG(const string & filename, const Rect & bounds)
269 {
270         using namespace pugi;
271         
272         xml_document doc_xml;
273         ifstream input(filename.c_str(), ios_base::in);
274         xml_parse_result result = doc_xml.load(input);
275         
276         if (!result)
277                 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
278                 
279         Debug("Loaded XML - %s", result.description());
280         
281         input.close();
282
283         // Combine all SVG tags into one thing because lazy
284         for (xml_node svg : doc_xml.children("svg"))
285         {
286                 Real width = Real(svg.attribute("width").as_float()) * bounds.w;
287                 Real height = Real(svg.attribute("width").as_float()) * bounds.h;
288                 
289                 
290                 // Rectangles
291                 Real coords[4];
292                 const char * attrib_names[] = {"x", "y", "width", "height"};
293                 for (pugi::xml_node rect : svg.children("rect"))
294                 {
295                         for (size_t i = 0; i < 4; ++i)
296                                 coords[i] = rect.attribute(attrib_names[i]).as_float();
297                         
298                         bool outline = !(rect.attribute("fill"));
299                         Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0]/width + bounds.x, coords[1]/height + bounds.y, coords[2]/width, coords[3]/height),0);
300                         Debug("Added rectangle");
301                 }               
302                 
303                 // Circles
304                 for (pugi::xml_node circle : svg.children("circle"))
305                 {
306                         Real cx = circle.attribute("cx").as_float();
307                         Real cy = circle.attribute("cy").as_float();
308                         Real r = circle.attribute("r").as_float();
309                         
310                         Real x = (cx - r)/width + bounds.x; 
311                         Real y = (cy - r)/height + bounds.y; 
312                         Real w = Real(2)*r/width; 
313                         Real h = Real(2)*r/height;
314                         
315                         Rect rect(x,y,w,h);
316                         Add(CIRCLE_FILLED, rect,0);
317                         Debug("Added Circle %s", rect.Str().c_str());
318
319                 }               
320                 
321                 // paths
322                 for (pugi::xml_node path : svg.children("path"))
323                 {
324                         
325                         string d = path.attribute("d").as_string();
326                         Debug("Path data attribute is \"%s\"", d.c_str());
327                         AddPathFromString(d, Rect(bounds.x,bounds.y,width,height));
328                         
329                 }
330         }
331         
332         //Fatal("Done");
333         
334         
335
336 }
337
338 // Behold my amazing tokenizing abilities
339 static string & GetToken(const string & d, string & token, unsigned & i)
340 {
341         token.clear();
342         while (i < d.size() && iswspace(d[i]))
343         {
344                 ++i;
345         }
346         
347         while (i < d.size())
348         {
349                 if (d[i] == ',' || (isalpha(d[i]) && d[i] != 'e') || iswspace(d[i]))
350                 {
351                         if (token.size() == 0 && !iswspace(d[i]))
352                         {
353                                 token += d[i++];
354                         }
355                         break;  
356                 }
357                 token += d[i++];
358         }
359         Debug("Got token \"%s\"", token.c_str());
360         return token;
361 }
362
363
364 // Fear the wrath of the tokenizing svg data
365 // Seriously this isn't really very DOM-like at all is it?
366 void Document::AddPathFromString(const string & d, const Rect & bounds)
367 {
368         Real x[4] = {0,0,0,0};
369         Real y[4] = {0,0,0,0};
370         
371         string token("");
372         string command("m");
373         
374         Real x0(0);
375         Real y0(0);
376         
377         unsigned i = 0;
378         unsigned prev_i = 0;
379         
380         bool start = false;
381         
382         while (i < d.size() && GetToken(d, token, i).size() > 0)
383         {
384                 if (isalpha(token[0]))
385                         command = token;
386                 else
387                 {
388                         i = prev_i; // hax
389                         if(command == "")
390                                 command = "L";
391                 }
392                 
393                 bool relative = islower(command[0]);
394                         
395                 if (command == "m" || command == "M")
396                 {
397                         Debug("Construct moveto command");
398                         Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
399                         assert(GetToken(d,token,i) == ",");
400                         Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
401                         
402                         x[0] = (relative) ? x[0] + dx : dx;
403                         y[0] = (relative) ? y[0] + dy : dy;
404                         
405
406                         
407                         Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
408                         command = (command == "m") ? "l" : "L";
409                 }
410                 else if (command == "c" || command == "C" || command == "q" || command == "Q")
411                 {
412                         Debug("Construct curveto command");
413                         Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL))/bounds.w;
414                         assert(GetToken(d,token,i) == ",");
415                         Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL))/bounds.h;
416                         
417                         x[1] = (relative) ? x[0] + dx : dx;
418                         y[1] = (relative) ? y[0] + dy : dy;
419                         
420                         dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
421                         assert(GetToken(d,token,i) == ",");
422                         dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
423                         
424                         x[2] = (relative) ? x[0] + dx : dx;
425                         y[2] = (relative) ? y[0] + dy : dy;
426                         
427                         if (command != "q" && command != "Q")
428                         {
429                                 dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
430                                 assert(GetToken(d,token,i) == ",");
431                                 dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
432                                 x[3] = (relative) ? x[0] + dx : dx;
433                                 y[3] = (relative) ? y[0] + dy : dy;
434                         }
435                         else
436                         {
437                                 x[3] = x[2];
438                                 y[3] = y[2];
439                                 Real old_x1(x[1]), old_y1(y[1]);
440                                 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
441                                 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
442                                 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
443                                 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
444                         }
445                         
446                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
447                         Add(BEZIER,Rect(0,0,1,1),index);
448                         
449                         
450                         Debug("[%u] curveto %f,%f %f,%f %f,%f", index, Float(x[1]),Float(y[1]),Float(x[2]),Float(y[2]),Float(x[3]),Float(y[3]));
451                         
452                         x[0] = x[3];
453                         y[0] = y[3];
454
455                         
456                 }
457                 else if (command == "l" || command == "L")
458                 {
459                         Debug("Construct lineto command");
460                 
461                         Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
462                         assert(GetToken(d,token,i) == ",");
463                         Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
464                         
465                         x[1] = (relative) ? x[0] + dx : dx;
466                         y[1] = (relative) ? y[0] + dy : dy;
467                         
468                         x[2] = x[1];
469                         y[2] = y[1];
470                         
471                         x[3] = x[1];
472                         y[3] = y[1];
473
474                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
475                         Add(BEZIER,Rect(0,0,1,1),index);
476                         
477                         Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
478                         
479                         x[0] = x[3];
480                         y[0] = y[3];
481
482                 }
483                 else if (command == "z" || command == "Z")
484                 {
485                         Debug("Construct returnto command");
486                         x[1] = x0;
487                         y[1] = y0;
488                         x[2] = x0;
489                         y[2] = y0;
490                         x[3] = x0;
491                         y[3] = y0;
492                         
493                         unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
494                         Add(BEZIER,Rect(0,0,1,1),index);
495                         
496                         Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
497                         
498                         x[0] = x[3];
499                         y[0] = y[3];
500                         command = "m";
501                 }
502                 else
503                 {
504                         Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
505                         command = "m";
506                 }
507                 
508                 if (!start)
509                 {
510                         x0 = x[0];
511                         y0 = y[0];
512                         start = true;
513                 }
514                 prev_i = i;
515         }
516 }
517
518 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
519 {
520         int glyph_index = stbtt_FindGlyphIndex(font, character);
521
522         // Check if there is actully a glyph to render.
523         if (stbtt_IsGlyphEmpty(font, glyph_index))
524         {
525                 return;
526         }
527
528         stbtt_vertex *instructions;
529         int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
530
531         Real current_x(0), current_y(0);
532
533         for (int i = 0; i < num_instructions; ++i)
534         {
535                 // TTF uses 16-bit signed ints for coordinates:
536                 // with the y-axis inverted compared to us.
537                 // Convert and scale any data.
538                 Real inst_x = Real(instructions[i].x)*scale;
539                 Real inst_y = Real(instructions[i].y)*-scale;
540                 Real inst_cx = Real(instructions[i].cx)*scale;
541                 Real inst_cy = Real(instructions[i].cy)*-scale;
542                 Real old_x(current_x), old_y(current_y);
543                 current_x = inst_x;
544                 current_y = inst_y;
545                 unsigned bezier_index;
546                 switch(instructions[i].type)
547                 {
548                 // Move To
549                 case STBTT_vmove:
550                         break;
551                 // Line To
552                 case STBTT_vline:
553                         bezier_index = AddBezierData(Bezier(old_x + x, old_y + y, old_x + x, old_y + y, current_x + x, current_y + y, current_x + x, current_y + y));
554                         Add(BEZIER,Rect(0,0,1,1),bezier_index);
555                         break;
556                 // Quadratic Bezier To:
557                 case STBTT_vcurve:
558                         // Quadratic -> Cubic:
559                         // - Endpoints are the same.
560                         // - cubic1 = quad0+(2/3)*(quad1-quad0)
561                         // - cubic2 = quad2+(2/3)*(quad1-quad2)
562                         bezier_index = AddBezierData(Bezier(old_x + x, old_y + y, old_x + Real(2)*(inst_cx-old_x)/Real(3) + x, old_y + Real(2)*(inst_cy-old_y)/Real(3) + y,
563                                                 current_x + Real(2)*(inst_cx-current_x)/Real(3) + x, current_y + Real(2)*(inst_cy-current_y)/Real(3) + y, current_x + x, current_y + y));
564                         Add(BEZIER,Rect(0,0,1,1),bezier_index);
565                         break;
566                 }
567         }
568
569         stbtt_FreeShape(font, instructions);
570 }

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