c41c848d3f289f213473ba3ec92ffd0eb4de2e4c
[ipdf/code.git] / src / document.cpp
1 #include "document.h"
2 #include "bezier.h"
3 #include <cstdio>
4 #include <fstream>
5
6 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
7 #include "transformationtype.h"
8
9 #include "stb_truetype.h"
10
11 using namespace IPDF;
12 using namespace std;
13
14 //TODO: Make this work for variable sized Reals
15
16 // Loads an std::vector<T> of size num_elements from a file.
17 template<typename T>
18 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
19 {
20         size_t structsread = 0;
21         dest.resize(num_elems);
22         structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
23         if (structsread != num_elems)
24                 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
25 }
26
27 // Saves an std::vector<T> to a file. Size must be saves separately.
28 template<typename T>
29 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
30 {
31         size_t written = 0;
32         written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
33         if (written != src.size())
34                 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
35 }
36
37 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
38 {
39         size_t written = 0;
40         written = fwrite(&type, sizeof(type), 1, dst_file);
41         if (written != 1)
42                 Fatal("Could not write Chunk header! (ID)");
43         written = fwrite(&size, sizeof(size), 1, dst_file);
44         if (written != 1)
45                 Fatal("Could not write Chunk header (size)!");
46 }
47
48 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
49 {
50         if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
51                 return false;
52         if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
53                 return false;
54         return true;
55 }
56
57 void Document::Save(const string & filename)
58 {
59         Debug("Saving document to file \"%s\"...", filename.c_str());
60         FILE * file = fopen(filename.c_str(), "w");
61         if (file == NULL)
62                 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
63
64         size_t written;
65         Debug("Number of objects (%u)...", ObjectCount());
66         WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
67         written = fwrite(&m_count, sizeof(m_count), 1, file);
68         if (written != 1)
69                 Fatal("Failed to write number of objects!");
70
71         Debug("Object types...");
72         WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
73         SaveStructVector<ObjectType>(file, m_objects.types);
74
75         Debug("Object bounds...");
76         WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
77         SaveStructVector<Rect>(file, m_objects.bounds);
78
79         Debug("Object data indices...");
80         WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
81         SaveStructVector<unsigned>(file, m_objects.data_indices);
82         
83         Debug("Bezier data...");
84         WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
85         SaveStructVector<Bezier>(file, m_objects.beziers);
86
87         int err = fclose(file);
88         if (err != 0)
89                 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
90
91         Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
92 }
93
94 #ifndef QUADTREE_DISABLED
95
96 void Document::GenBaseQuadtree()
97 {
98         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount(), -1});
99         m_quadtree.root_id = 0;
100 }
101
102 int Document::ClipObjectToQuadChild(int object_id, QuadTreeNodeChildren type)
103 {
104         switch (m_objects.types[object_id])
105         {
106         case RECT_FILLED:
107         case RECT_OUTLINE:
108         case PATH:
109                 {
110                 Rect obj_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
111                 if (obj_bounds.x < 0)
112                 {
113                         obj_bounds.w += obj_bounds.x;
114                         obj_bounds.x = 0;
115                 }
116                 if (obj_bounds.y < 0)
117                 {
118                         obj_bounds.h += obj_bounds.y;
119                         obj_bounds.y = 0;
120                 }
121                 if (obj_bounds.x + obj_bounds.w > 1)
122                 {
123                         obj_bounds.w += (1 - (obj_bounds.x + obj_bounds.w));
124                 }
125                 if (obj_bounds.y + obj_bounds.h > 1)
126                 {
127                         obj_bounds.h += (1 - (obj_bounds.y + obj_bounds.h));
128                 }
129                 m_objects.bounds.push_back(obj_bounds);
130                 m_objects.types.push_back(m_objects.types[object_id]);
131                 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
132                 return 1;
133                 }
134         case BEZIER:
135                 {
136                 // If we're entirely within the quadtree node, no clipping need occur.
137                 if (ContainedInQuadChild(m_objects.bounds[object_id], type))
138                 {
139                         m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
140                         m_objects.types.push_back(m_objects.types[object_id]);
141                         m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
142                         return 1;
143                 }
144                 Rect clip_bezier_bounds = TransformRectCoordinates(m_objects.bounds[object_id], TransformFromQuadChild(Rect{0,0,1,1}, type)); 
145                 std::vector<Bezier> new_curves = m_objects.beziers[m_objects.data_indices[object_id]].ClipToRectangle(clip_bezier_bounds);
146                 for (size_t i = 0; i < new_curves.size(); ++i)
147                 {
148                         Rect new_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
149                         Bezier new_curve_data = new_curves[i].ToAbsolute(TransformToQuadChild(m_objects.bounds[object_id],type));
150                         new_bounds = new_curve_data.SolveBounds();
151                         Debug("New bounds: %s", new_bounds.Str().c_str());
152                         new_curve_data = new_curve_data.ToRelative(new_bounds);
153                         unsigned index = AddBezierData(new_curve_data);
154                         m_objects.bounds.push_back(new_bounds);
155                         m_objects.types.push_back(BEZIER);
156                         m_objects.data_indices.push_back(index);
157                 }
158                 return new_curves.size();
159                 }
160         default:
161                 Debug("Adding %s -> %s", m_objects.bounds[object_id].Str().c_str(), TransformToQuadChild(m_objects.bounds[object_id], type).Str().c_str());
162                 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
163                 m_objects.types.push_back(m_objects.types[object_id]);
164                 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
165                 return 1;
166         }
167         return 0;
168 }
169 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
170 {
171         QuadTreeIndex new_index = m_quadtree.nodes.size();
172         Debug("-------------- Generating Quadtree Node %d (parent %d, type %d) ----------------------", new_index, parent, type);
173         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0, -1});
174
175         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
176         for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
177         {
178                 if (IntersectsQuadChild(m_objects.bounds[i], type))
179                 {
180                         m_count += ClipObjectToQuadChild(i, type);
181                 }
182         }
183         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
184         switch (type)
185         {
186                 case QTC_TOP_LEFT:
187                         m_quadtree.nodes[parent].top_left = new_index;
188                         break;
189                 case QTC_TOP_RIGHT:
190                         m_quadtree.nodes[parent].top_right = new_index;
191                         break;
192                 case QTC_BOTTOM_LEFT:
193                         m_quadtree.nodes[parent].bottom_left = new_index;
194                         break;
195                 case QTC_BOTTOM_RIGHT:
196                         m_quadtree.nodes[parent].bottom_right = new_index;
197                         break;
198                 default:
199                         Fatal("Tried to add a QuadTree child of invalid type!");
200         }
201         return new_index;
202 }
203
204 // Reparent a quadtree node, making it the "type" child of a new node.
205 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
206 {
207         QuadTreeIndex new_index = m_quadtree.nodes.size();
208         m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1});
209
210         m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
211         for (unsigned i = m_quadtree.nodes[child].object_begin; i < m_quadtree.nodes[child].object_end; ++i)
212         {
213                 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
214                 m_objects.types.push_back(m_objects.types[i]);
215                 m_objects.data_indices.push_back(m_objects.data_indices[i]);
216                 m_count++;
217         }
218         m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
219         switch (type)
220         {
221                 case QTC_TOP_LEFT:
222                         m_quadtree.nodes[new_index].top_left = child;
223                         break;
224                 case QTC_TOP_RIGHT:
225                         m_quadtree.nodes[new_index].top_right = child;
226                         break;
227                 case QTC_BOTTOM_LEFT:
228                         m_quadtree.nodes[new_index].bottom_left = child;
229                         break;
230                 case QTC_BOTTOM_RIGHT:
231                         m_quadtree.nodes[new_index].bottom_right = child;
232                         break;
233                 default:
234                         Fatal("Tried to add a QuadTree child of invalid type!");
235         }
236         return new_index;
237 }
238
239 #endif
240
241 void Document::Load(const string & filename)
242 {
243         m_objects.bounds.clear();
244         m_count = 0;
245         if (filename == "")
246         {
247                 Debug("Loaded empty document.");
248                 return;
249         }
250         Debug("Loading document from file \"%s\"", filename.c_str());
251         FILE * file = fopen(filename.c_str(), "r");
252         if (file == NULL)
253                 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
254
255         size_t read;
256
257         DocChunkTypes chunk_type;
258         uint32_t chunk_size;
259         while (ReadChunkHeader(file, chunk_type, chunk_size))
260         {
261                 switch(chunk_type)
262                 {
263                 case CT_NUMOBJS:
264                         read = fread(&m_count, sizeof(m_count), 1, file);
265                         if (read != 1)
266                                 Fatal("Failed to read number of objects!");
267                         Debug("Number of objects: %u", ObjectCount());
268                         break;
269                 case CT_OBJTYPES:
270                         Debug("Object types...");
271                         LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
272                         break;
273                 case CT_OBJBOUNDS:
274                         Debug("Object bounds...");
275                         LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
276                         break;
277                 case CT_OBJINDICES:
278                         Debug("Object data indices...");
279                         LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
280                         break;
281                 case CT_OBJBEZIERS:
282                         Debug("Bezier data...");
283                         LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
284                         break;
285                         
286                 case CT_OBJPATHS:
287                         Debug("Path data...");
288                         Warn("Not handled because lazy");
289                         break;
290                 }
291         }
292         Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
293 #ifndef QUADTREE_DISABLED
294         if (m_quadtree.root_id == QUADTREE_EMPTY)
295         {
296                 GenBaseQuadtree();
297         }
298 #endif
299 }
300
301 unsigned Document::AddPath(unsigned start_index, unsigned end_index, const Colour & fill, const Colour & stroke)
302 {
303         Path path(m_objects, start_index, end_index, fill, stroke);
304         unsigned data_index = AddPathData(path);
305         Rect bounds = path.SolveBounds(m_objects);
306         unsigned result = Add(PATH, bounds,data_index);
307         m_objects.paths[data_index].m_index = result;
308         //Debug("Added path %u -> %u (%u objects) colour {%u,%u,%u,%u}, stroke {%u,%u,%u,%u}", start_index, end_index, (end_index - start_index), fill.r, fill.g, fill.b, fill.a, stroke.r, stroke.g, stroke.b, stroke.a);
309         return result;
310 }
311
312 /**
313  * Add a Bezier using Absolute coords
314  */
315 unsigned Document::AddBezier(const Bezier & bezier)
316 {
317         Rect bounds = bezier.SolveBounds();
318         Bezier data = bezier.ToRelative(bounds); // Relative
319         if (data.ToAbsolute(bounds) != bezier)
320         {
321                 Warn("%s != %s", data.ToAbsolute(bounds).Str().c_str(),
322                         bezier.Str().c_str());
323                 Warn("ToAbsolute on ToRelative does not give original Bezier");
324         }
325         unsigned index = AddBezierData(data);
326         return Add(BEZIER, bounds, index);
327 }
328
329 unsigned Document::Add(ObjectType type, const Rect & bounds, unsigned data_index, QuadTreeIndex qti)
330 {
331         m_objects.types.push_back(type);
332         m_objects.bounds.push_back(bounds);
333         m_objects.data_indices.push_back(data_index);
334 #ifndef QUADTREE_DISABLED
335         if (qti != -1)
336         {
337                 if (m_count == m_quadtree.nodes[qti].object_end+1)
338                 {
339                         m_quadtree.nodes[qti].object_end++;
340                 }
341                 else
342                 {
343                         QuadTreeIndex overlay = m_quadtree.nodes.size();
344                         m_quadtree.nodes.push_back(m_quadtree.nodes[qti]);
345                         m_quadtree.nodes[overlay].object_begin = m_count;
346                         m_quadtree.nodes[overlay].object_end = m_count+1;
347                         m_quadtree.nodes[qti].next_overlay = overlay;
348                 }
349         }
350 #endif
351         return (m_count++); // Why can't we just use the size of types or something?
352 }
353
354 unsigned Document::AddBezierData(const Bezier & bezier)
355 {
356         m_objects.beziers.push_back(bezier);
357         return m_objects.beziers.size()-1;
358 }
359
360 unsigned Document::AddPathData(const Path & path)
361 {
362         m_objects.paths.push_back(path);
363         return m_objects.paths.size()-1;
364 }
365
366 void Document::DebugDumpObjects()
367 {
368         Debug("Objects for Document %p are:", this);
369         for (unsigned id = 0; id < ObjectCount(); ++id)
370         {
371                 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
372         }
373 }
374
375 bool Document::operator==(const Document & equ) const
376 {
377         return (ObjectCount() == equ.ObjectCount() 
378                 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
379                 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
380                 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
381 }
382
383
384
385 // Behold my amazing tokenizing abilities
386 static string & GetToken(const string & d, string & token, unsigned & i, const string & delims = "()[],{}<>;:=")
387 {
388         token.clear();
389         while (i < d.size() && iswspace(d[i]))
390         {
391                 ++i;
392         }
393         
394         while (i < d.size())
395         {
396                 if (iswspace(d[i]) || strchr(delims.c_str(),d[i]) != NULL)
397                 {
398                         if (token.size() == 0 && !iswspace(d[i]))
399                         {
400                                 token += d[i++];
401                         }
402                         break;  
403                 }
404                 token += d[i++];
405         }
406         //Debug("Got token \"%s\"", token.c_str());
407         return token;
408 }
409
410 static void GetXYPair(const string & d, Real & x, Real & y, unsigned & i,const string & delims = "()[],{}<>;:=")
411 {
412         string token("");
413         while (GetToken(d, token, i, delims) == ",");
414         x = RealFromStr(token);
415         if (GetToken(d, token, i, delims) != ",")
416         {
417                 Fatal("Expected \",\" seperating x,y pair");
418         }
419         y = RealFromStr(GetToken(d,token,i,delims));
420 }
421
422 static bool GetKeyValuePair(const string & d, string & key, string & value, unsigned & i, const string & delims = "()[],{}<>;:=")
423 {
424         key = "";
425         string token;
426         while (GetToken(d, token, i, delims) == ":" || token == ";");
427         key = token;
428         if (GetToken(d, token, i, delims) != ":")
429         {
430                 Error("Expected \":\" seperating key:value pair");
431                 return false;
432         }
433         value = "";
434         GetToken(d, value, i, delims);
435         return true;
436 }
437
438 static void TransformXYPair(Real & x, Real & y, const SVGMatrix & transform)
439 {
440         Real x0(x);
441         x = transform.a * x + transform.c * y + transform.e;
442         y = transform.b * x0 + transform.d * y + transform.f;
443 }
444
445 void Document::ParseSVGTransform(const string & s, SVGMatrix & transform)
446 {
447         //Debug("Parsing transform %s", s.c_str());
448         string token;
449         string command;
450         unsigned i = 0;
451         
452         while (i < s.size())
453         {
454                 GetToken(s, command, i);
455                 if (command == "," || command == "" || command == ":")
456                 {
457                         if (i < s.size())
458                                 GetToken(s, command, i);
459                         else
460                                 return;
461                 }
462                 //Debug("Token is \"%s\"", command.c_str());
463         
464                 SVGMatrix delta = {1,0,0,0,1,0};
465         
466         
467                 assert(GetToken(s,token, i) == "(");
468                 if (command == "translate")
469                 {
470                         GetXYPair(s, delta.e, delta.f, i);
471                         assert(GetToken(s,token, i) == ")");    
472                 }
473                 else if (command == "matrix")
474                 {
475                         GetXYPair(s, delta.a, delta.b,i);
476                         GetXYPair(s, delta.c, delta.d,i);
477                         GetXYPair(s, delta.e, delta.f,i);
478                         assert(GetToken(s,token, i) == ")");    
479                 }
480                 else if (command == "scale")
481                 {
482                         delta.a = RealFromStr(GetToken(s,token,i));
483                         GetToken(s, token, i);
484                         if (token == ",")
485                         {
486                                 delta.d = RealFromStr(GetToken(s,token,i));
487                                 assert(GetToken(s, token, i) == ")");
488                         }
489                         else
490                         {
491                                 delta.d = delta.a;
492                                 assert(token == ")");
493                         }
494                         
495                 }
496                 else
497                 {
498                         Warn("Unrecognised transform \"%s\", using identity", command.c_str());
499                 }
500         
501                 //Debug("Old transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
502                 //Debug("Delta transform is {%f,%f,%f,%f,%f,%f}", delta.a, delta.b, delta.c, delta.d,delta.e,delta.f);
503         
504                 SVGMatrix old(transform);
505                 transform.a = old.a * delta.a + old.c * delta.b;
506                 transform.c = old.a * delta.c + old.c * delta.d;
507                 transform.e = old.a * delta.e + old.c * delta.f + old.e;
508         
509                 transform.b = old.b * delta.a + old.d * delta.b;
510                 transform.d = old.b * delta.c + old.d * delta.d;
511                 transform.f = old.b * delta.e + old.d * delta.f + old.f;
512         
513                 //Debug("New transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
514         }
515 }
516
517 inline Colour ParseColourString(const string & colour_str)
518 {
519         Colour c(0,0,0,0);
520         if (colour_str == "red")
521                 c = {255,0,0,255};
522         else if (colour_str == "blue")
523                 c = {0,0,255,255};
524         else if (colour_str == "green")
525                 c = {0,255,0,255};
526         else if (colour_str == "black")
527                 c = {0,0,0,255};
528         else if (colour_str == "white")
529                 c = {255,255,255,255};
530         else if (colour_str.size() == 7 && colour_str[0] == '#')
531         {
532                 //Debug("Parse colour string: \"%s\"", colour_str.c_str());
533                 char comp[3] = {colour_str[1], colour_str[2], '\0'};
534                 c.r = strtoul(comp, NULL, 16);
535                 comp[0] = colour_str[3]; comp[1] = colour_str[4];
536                 c.g = strtoul(comp, NULL, 16);
537                 comp[0] = colour_str[5]; comp[1] = colour_str[6];
538                 c.b = strtoul(comp, NULL, 16);
539                 c.a = 255;
540                 //Debug("Colour is: %u, %u, %u, %u", c.r, c.g, c.b, c.a);
541         }
542         return c;
543 }
544
545 void Document::ParseSVGNode(pugi::xml_node & root, SVGMatrix & parent_transform)
546 {
547         //Debug("Parse node <%s>", root.name());
548
549         
550         // Centre the SVGs
551         if (strcmp(root.name(),"svg") == 0)
552         {
553                 Real ww = RealFromStr(root.attribute("width").as_string());
554                 Real hh = RealFromStr(root.attribute("height").as_string());
555                 parent_transform.e -= parent_transform.a * ww/Real(2);
556                 parent_transform.f -= parent_transform.d * hh/Real(2);
557         }
558         
559         for (pugi::xml_node child = root.first_child(); child; child = child.next_sibling())
560         {
561                 SVGMatrix transform(parent_transform);  
562                 pugi::xml_attribute attrib_trans = child.attribute("transform");
563                 if (!attrib_trans.empty())
564                 {
565                         ParseSVGTransform(attrib_trans.as_string(), transform);
566                 }
567                 
568                 
569                 
570                 if (strcmp(child.name(), "svg") == 0 || strcmp(child.name(),"g") == 0
571                         || strcmp(child.name(), "group") == 0)
572                 {
573                         
574                         ParseSVGNode(child, transform);
575                         continue;
576                 }
577                 else if (strcmp(child.name(), "path") == 0)
578                 {
579                         string d = child.attribute("d").as_string();
580                         //Debug("Path data attribute is \"%s\"", d.c_str());
581                         bool closed = false;
582                         pair<unsigned, unsigned> range = ParseSVGPathData(d, transform, closed);
583                         if (true && range.first < m_count && range.second < m_count)//(closed)
584                         {
585                                 
586                                 string colour_str("");
587                                 map<string, string> style;
588                                 if (child.attribute("style"))
589                                 {
590                                         ParseSVGStyleData(child.attribute("style").as_string(), style);
591                                 }
592                                 
593                                 // Determine shading colour
594                                 if (child.attribute("fill"))
595                                 {
596                                         colour_str = child.attribute("fill").as_string();
597                                 }
598                                 else if (style.find("fill") != style.end())
599                                 {
600                                         colour_str = style["fill"];
601                                 }
602                                 Colour fill = ParseColourString(colour_str);
603                                 Colour stroke = fill;
604                         
605                                 if (child.attribute("stroke"))
606                                 {
607                                         colour_str = child.attribute("stroke").as_string();
608                                         stroke = ParseColourString(colour_str);
609                                 }
610                                 else if (style.find("stroke") != style.end())
611                                 {
612                                         colour_str = style["stroke"];
613                                         stroke = ParseColourString(colour_str);
614                                 }
615                                 
616                                 
617                                 // Determin shading alpha
618                                 if (child.attribute("fill-opacity"))
619                                 {
620                                         fill.a = 255*child.attribute("fill-opacity").as_float();
621                                 }
622                                 else if (style.find("fill-opacity") != style.end())
623                                 {
624                                         fill.a = 255*strtod(style["fill-opacity"].c_str(), NULL);
625                                 }
626                                 if (child.attribute("stroke-opacity"))
627                                 {
628                                         stroke.a = 255*child.attribute("stroke-opacity").as_float();
629                                 }
630                                 else if (style.find("stroke-opacity") != style.end())
631                                 {
632                                         stroke.a = 255*strtod(style["stroke-opacity"].c_str(), NULL);
633                                 }
634                                 AddPath(range.first, range.second, fill, stroke);
635                         }
636                         
637                 }
638                 else if (strcmp(child.name(), "line") == 0)
639                 {
640                         Real x0(child.attribute("x1").as_float());
641                         Real y0(child.attribute("y1").as_float());
642                         Real x1(child.attribute("x2").as_float());
643                         Real y1(child.attribute("y2").as_float());
644                         TransformXYPair(x0,y0,transform);
645                         TransformXYPair(x1,y1,transform);
646                         AddBezier(Bezier(x0,y0,x1,y1,x1,y1,x1,y1));
647                 }
648                 else if (strcmp(child.name(), "rect") == 0)
649                 {
650                         Real coords[4];
651                         const char * attrib_names[] = {"x", "y", "width", "height"};
652                         for (size_t i = 0; i < 4; ++i)
653                                 coords[i] = child.attribute(attrib_names[i]).as_float();
654                         
655                         Real x2(coords[0]+coords[2]);
656                         Real y2(coords[1]+coords[3]);
657                         TransformXYPair(coords[0],coords[1],transform); // x, y, transform
658                         TransformXYPair(x2,y2,transform);
659                         coords[2] = x2 - coords[0];
660                         coords[3] = y2 - coords[1];
661                         
662                         bool outline = !(child.attribute("fill") && strcmp(child.attribute("fill").as_string(),"none") != 0);
663                         Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0], coords[1], coords[2], coords[3]),0);
664                 }
665                 else if (strcmp(child.name(), "circle") == 0)
666                 {
667                         Real cx = child.attribute("cx").as_float();
668                         Real cy = child.attribute("cy").as_float();
669                         Real r = child.attribute("r").as_float();
670                         
671                         Real x = (cx - r);
672                         Real y = (cy - r);
673                         TransformXYPair(x,y,transform);
674                         Real w = Real(2)*r*transform.a; // width scales
675                         Real h = Real(2)*r*transform.d; // height scales
676                         
677                         
678                         Rect rect(x,y,w,h);
679                         Add(CIRCLE_FILLED, rect,0);
680                         Debug("Added Circle %s", rect.Str().c_str());                   
681                 }
682                 else if (strcmp(child.name(), "text") == 0)
683                 {
684                         Real x = child.attribute("x").as_float();
685                         Real y = child.attribute("y").as_float();
686                         TransformXYPair(x,y,transform);
687                         Debug("Add text \"%s\"", child.child_value());
688                         AddText(child.child_value(), 0.05, x, y);
689                 }
690         }
691 }
692
693 void Document::ParseSVGStyleData(const string & style, map<string, string> & results)
694 {
695         unsigned i = 0;
696         string key;
697         string value;
698         while (i < style.size() && GetKeyValuePair(style, key, value, i))
699         {
700                 results[key] = value;
701         }
702 }
703
704 /**
705  * Parse an SVG string into a rectangle
706  */
707 void Document::ParseSVG(const string & input, const Rect & bounds)
708 {
709         using namespace pugi;
710         
711         xml_document doc_xml;
712         xml_parse_result result = doc_xml.load(input.c_str());
713         
714         if (!result)
715                 Error("Couldn't parse SVG input - %s", result.description());
716                 
717         Debug("Loaded XML - %s", result.description());
718         SVGMatrix transform = {bounds.w, 0,bounds.x, 0,bounds.h,bounds.y};
719         ParseSVGNode(doc_xml, transform);
720 }
721
722 /**
723  * Load an SVG into a rectangle
724  */
725 void Document::LoadSVG(const string & filename, const Rect & bounds)
726 {
727         using namespace pugi;
728         
729         xml_document doc_xml;
730         ifstream input(filename.c_str(), ios_base::in);
731         xml_parse_result result = doc_xml.load(input);
732         
733         if (!result)
734                 Error("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
735                 
736         Debug("Loaded XML from \"%s\" - %s", filename.c_str(), result.description());
737         
738         input.close();
739                                                 // a c e, b d f
740         SVGMatrix transform = {bounds.w,0 ,bounds.x, 0,bounds.h,bounds.y};
741         ParseSVGNode(doc_xml, transform);
742 }
743
744
745
746 // Fear the wrath of the tokenizing svg data
747 // Seriously this isn't really very DOM-like at all is it?
748 pair<unsigned, unsigned> Document::ParseSVGPathData(const string & d, const SVGMatrix & transform, bool & closed)
749 {
750         closed = false;
751         Real x[4] = {0,0,0,0};
752         Real y[4] = {0,0,0,0};
753         
754         string token("");
755         string command("m");
756         
757         Real x0(0);
758         Real y0(0);
759         
760         unsigned i = 0;
761         unsigned prev_i = 0;
762         
763         bool start = false;
764         
765
766         static string delims("()[],{}<>;:=LlHhVvmMqQzZcC");
767
768         pair<unsigned, unsigned> range(m_count, m_count);
769         
770         while (i < d.size() && GetToken(d, token, i, delims).size() > 0)
771         {
772                 if (isalpha(token[0]))
773                         command = token;
774                 else
775                 {
776                         i = prev_i; // hax
777                         if(command == "")
778                                 command = "L";
779                 }
780                 
781                 bool relative = islower(command[0]);
782                         
783                 if (command == "m" || command == "M")
784                 {
785                         //Debug("Construct moveto command");
786                         Real dx = RealFromStr(GetToken(d,token,i,delims));
787                         assert(GetToken(d,token,i,delims) == ",");
788                         Real dy = RealFromStr(GetToken(d,token,i,delims));
789                         
790                         x[0] = (relative) ? x[0] + dx : dx;
791                         y[0] = (relative) ? y[0] + dy : dy;
792                         
793                         x0 = x[0];
794                         y0 = y[0];
795                         //Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
796                         command = (command == "m") ? "l" : "L";
797                 }
798                 else if (command == "c" || command == "C" || command == "q" || command == "Q")
799                 {
800                         //Debug("Construct curveto command");
801                         Real dx = RealFromStr(GetToken(d,token,i,delims));
802                         assert(GetToken(d,token,i,delims) == ",");
803                         Real dy = RealFromStr(GetToken(d,token,i,delims));
804                         
805                         x[1] = (relative) ? x[0] + dx : dx;
806                         y[1] = (relative) ? y[0] + dy : dy;
807                         
808                         dx = RealFromStr(GetToken(d,token,i,delims));
809                         assert(GetToken(d,token,i,delims) == ",");
810                         dy = RealFromStr(GetToken(d,token,i,delims));
811                         
812                         x[2] = (relative) ? x[0] + dx : dx;
813                         y[2] = (relative) ? y[0] + dy : dy;
814                         
815                         if (command != "q" && command != "Q")
816                         {
817                                 dx = RealFromStr(GetToken(d,token,i,delims));
818                                 assert(GetToken(d,token,i,delims) == ",");
819                                 dy = RealFromStr(GetToken(d,token,i,delims));
820                                 x[3] = (relative) ? x[0] + dx : dx;
821                                 y[3] = (relative) ? y[0] + dy : dy;
822                         }
823                         else
824                         {
825                                 x[3] = x[2];
826                                 y[3] = y[2];
827                                 Real old_x1(x[1]), old_y1(y[1]);
828                                 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
829                                 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
830                                 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
831                                 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
832                         }
833                         
834                         Real x3(x[3]);
835                         Real y3(y[3]);
836                         for (int j = 0; j < 4; ++j)
837                                 TransformXYPair(x[j],y[j], transform);
838
839                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
840                         
841                         //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]));
842                         
843                         x[0] = x3;
844                         y[0] = y3;
845
846                         
847                 }
848                 else if (command == "l" || command == "L" || command == "h" || command == "H" || command == "v" || command == "V")
849                 {
850                         //Debug("Construct lineto command, relative %d", relative);
851                 
852                         Real dx = RealFromStr(GetToken(d,token,i,delims));
853                         Real dy = 0;
854                         if (command == "l" || command == "L")
855                         {
856                                 assert(GetToken(d,token,i,delims) == ",");
857                                 dy = RealFromStr(GetToken(d,token,i,delims));
858                         }
859                         else if (command == "v" || command == "V")
860                         {
861                                 swap(dx,dy);
862                         }
863                         
864                         x[1] = (relative) ? x[0] + dx : dx;
865                         y[1] = (relative) ? y[0] + dy : dy;
866                         if (command == "v" || command == "V")
867                         {
868                                 x[1] = x[0];
869                         }
870                         else if (command == "h" || command == "H")
871                         {
872                                 y[1] = y[0];
873                         }
874                         
875                         Real x1(x[1]);
876                         Real y1(y[1]);
877                         
878                         TransformXYPair(x[0],y[0],transform);
879                         TransformXYPair(x[1],y[1],transform);
880
881
882                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[1],y[1],x[1],y[1]));
883                         
884                         //Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
885                         
886                         x[0] = x1;
887                         y[0] = y1;
888
889                 }
890                 else if (command == "z" || command == "Z")
891                 {
892                         //Debug("Construct returnto command");
893                         x[1] = x0;
894                         y[1] = y0;
895                         x[2] = x0;
896                         y[2] = y0;
897                         x[3] = x0;
898                         y[3] = y0;
899                         
900                         Real x3(x[3]);
901                         Real y3(y[3]);
902                         for (int j = 0; j < 4; ++j)
903                                 TransformXYPair(x[j],y[j], transform);
904
905                         range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
906                         //Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
907                         
908                         x[0] = x3;
909                         y[0] = y3;
910                         command = "m";
911                         closed = true;
912                 }
913                 else
914                 {
915                         Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
916                         command = "m";
917                 }
918                 
919                 if (!start)
920                 {
921                         x0 = x[0];
922                         y0 = y[0];
923                         start = true;
924                 }
925                 prev_i = i;
926         }
927         return range;
928 }
929
930 void Document::SetFont(const string & font_filename)
931 {
932         if (m_font_data != NULL)
933         {
934                 free(m_font_data);
935         }
936         
937         FILE *font_file = fopen(font_filename.c_str(), "rb");
938         fseek(font_file, 0, SEEK_END);
939         size_t font_file_size = ftell(font_file);
940         fseek(font_file, 0, SEEK_SET);
941         m_font_data = (unsigned char*)malloc(font_file_size);
942         size_t read = fread(m_font_data, 1, font_file_size, font_file);
943         if (read != font_file_size)
944         {
945                 Fatal("Failed to read font data from \"%s\" - Read %u bytes expected %u - %s", font_filename.c_str(), read, font_file_size, strerror(errno));
946         }
947         fclose(font_file);
948         stbtt_InitFont(&m_font, m_font_data, 0);
949 }
950
951 void Document::AddText(const string & text, Real scale, Real x, Real y)
952 {
953         if (m_font_data == NULL)
954         {
955                 Warn("No font loaded");
956                 return;
957         }
958                 
959         Real x0(x);
960         //Real y0(y);
961         int ascent = 0, descent = 0, line_gap = 0;
962         stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &line_gap);
963         Real font_scale = scale;
964         font_scale /= Real(ascent - descent);
965         Real y_advance = Real(font_scale) * Real(ascent - descent + line_gap);
966         for (unsigned i = 0; i < text.size(); ++i)
967         {
968                 if (text[i] == '\n')
969                 {
970                         y += y_advance;
971                         x = x0;
972                 }
973                 if (!isprint(text[i]))
974                         continue;
975                         
976                 int advance_width = 0, left_side_bearing = 0, kerning = 0;
977                 stbtt_GetCodepointHMetrics(&m_font, text[i], &advance_width, &left_side_bearing);
978                 if (i >= 1)
979                 {
980                         kerning = stbtt_GetCodepointKernAdvance(&m_font, text[i-1], text[i]);
981                 }
982                 x += font_scale * Real(kerning);
983                 AddFontGlyphAtPoint(&m_font, text[i], font_scale, x, y);
984                 x += font_scale * Real(advance_width);
985         }
986 }
987
988 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
989 {
990         int glyph_index = stbtt_FindGlyphIndex(font, character);
991
992         // Check if there is actully a glyph to render.
993         if (stbtt_IsGlyphEmpty(font, glyph_index))
994         {
995                 return;
996         }
997
998         stbtt_vertex *instructions;
999         int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
1000
1001         Real current_x(0), current_y(0);
1002         unsigned start_index = m_count;
1003         unsigned end_index = m_count;
1004         for (int i = 0; i < num_instructions; ++i)
1005         {
1006                 // TTF uses 16-bit signed ints for coordinates:
1007                 // with the y-axis inverted compared to us.
1008                 // Convert and scale any data.
1009                 Real inst_x = Real(instructions[i].x)*scale;
1010                 Real inst_y = Real(instructions[i].y)*-scale;
1011                 Real inst_cx = Real(instructions[i].cx)*scale;
1012                 Real inst_cy = Real(instructions[i].cy)*-scale;
1013                 Real old_x(current_x), old_y(current_y);
1014                 current_x = inst_x;
1015                 current_y = inst_y;
1016                 
1017                 switch(instructions[i].type)
1018                 {
1019                 // Move To
1020                 case STBTT_vmove:
1021                         break;
1022                 // Line To
1023                 case STBTT_vline:
1024                         end_index = AddBezier(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));
1025                         break;
1026                 // Quadratic Bezier To:
1027                 case STBTT_vcurve:
1028                         // Quadratic -> Cubic:
1029                         // - Endpoints are the same.
1030                         // - cubic1 = quad0+(2/3)*(quad1-quad0)
1031                         // - cubic2 = quad2+(2/3)*(quad1-quad2)
1032                         end_index = AddBezier(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,
1033                                                 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));
1034                         break;
1035                 }
1036         }
1037         
1038         if (start_index < m_count && end_index < m_count)
1039         {
1040                 AddPath(start_index, end_index);
1041         }
1042         //Debug("Added Glyph \"%c\" at %f %f, scale %f", (char)character, Float(x), Float(y), Float(scale));
1043
1044         stbtt_FreeShape(font, instructions);
1045 }
1046
1047 void Document::TransformObjectBounds(const SVGMatrix & transform)
1048 {
1049         for (unsigned i = 0; i < m_count; ++i)
1050         {
1051                 TransformXYPair(m_objects.bounds[i].x, m_objects.bounds[i].y, transform);
1052                 m_objects.bounds[i].w *= transform.a;
1053                 m_objects.bounds[i].h *= transform.d;
1054         }
1055 }
1056
1057 void Document::TranslateObjects(const Real & dx, const Real & dy, ObjectType type)
1058 {
1059         #ifdef TRANSFORM_BEZIERS_TO_PATH
1060                 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1061                 {
1062                         Path & p = m_objects.paths[i];
1063                         p.m_bounds.x += dx;
1064                         p.m_bounds.y += dy;
1065                 }
1066                 return;
1067         #endif  
1068         
1069         for (unsigned i = 0; i < m_count; ++i)
1070         {
1071                 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1072                 {
1073                         m_objects.bounds[i].x += dx;
1074                         m_objects.bounds[i].y += dy;
1075                 }
1076         }
1077 }
1078
1079 void Document::ScaleObjectsAboutPoint(const Real & x, const Real & y, const Real & scale_amount, ObjectType type)
1080 {
1081         #ifdef TRANSFORM_BEZIERS_TO_PATH
1082                 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1083                 {
1084                         Path & p = m_objects.paths[i];
1085                         p.m_bounds.w /= scale_amount;
1086                         p.m_bounds.h /= scale_amount;
1087                         p.m_bounds.x -= x;
1088                         p.m_bounds.x /= scale_amount;
1089                         p.m_bounds.x += x;
1090                         p.m_bounds.y -= y;
1091                         p.m_bounds.y /= scale_amount;
1092                         p.m_bounds.y += y;
1093                 }
1094                 return;
1095         #endif
1096         
1097         for (unsigned i = 0; i < m_count; ++i)
1098         {
1099                 if (type != NUMBER_OF_OBJECT_TYPES && m_objects.types[i] != type)
1100                         continue;
1101                 
1102                 m_objects.bounds[i].w /= scale_amount;
1103                 m_objects.bounds[i].h /= scale_amount;
1104                 //m_objects.bounds[i].x = x + (m_objects.bounds[i].x-x)/scale_amount;
1105                 //m_objects.bounds[i].y = y + (m_objects.bounds[i].y-x)/scale_amount;
1106                 m_objects.bounds[i].x -= x;
1107                 m_objects.bounds[i].x /= scale_amount;
1108                 m_objects.bounds[i].x += x;
1109                 
1110                 m_objects.bounds[i].y -= y;
1111                 m_objects.bounds[i].y /= scale_amount;
1112                 m_objects.bounds[i].y += y;
1113         }
1114
1115 }
1116
1117

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