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

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