6 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
7 #include "transformationtype.h"
9 #include "stb_truetype.h"
14 //TODO: Make this work for variable sized Reals
16 // Loads an std::vector<T> of size num_elements from a file.
18 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
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);
27 // Saves an std::vector<T> to a file. Size must be saves separately.
29 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
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());
37 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
40 written = fwrite(&type, sizeof(type), 1, dst_file);
42 Fatal("Could not write Chunk header! (ID)");
43 written = fwrite(&size, sizeof(size), 1, dst_file);
45 Fatal("Could not write Chunk header (size)!");
48 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
50 if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
52 if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
57 void Document::Save(const string & filename)
59 Debug("Saving document to file \"%s\"...", filename.c_str());
60 FILE * file = fopen(filename.c_str(), "w");
62 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
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);
69 Fatal("Failed to write number of objects!");
71 Debug("Object types...");
72 WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
73 SaveStructVector<ObjectType>(file, m_objects.types);
75 Debug("Object bounds...");
76 WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
77 SaveStructVector<Rect>(file, m_objects.bounds);
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);
83 Debug("Bezier data...");
84 WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
85 SaveStructVector<Bezier>(file, m_objects.beziers);
87 int err = fclose(file);
89 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
91 Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
94 #ifndef QUADTREE_DISABLED
96 void Document::GenBaseQuadtree()
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;
102 int Document::ClipObjectToQuadChild(int object_id, QuadTreeNodeChildren type)
104 switch (m_objects.types[object_id])
110 Rect obj_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
111 if (obj_bounds.x < 0)
113 obj_bounds.w += obj_bounds.x;
116 if (obj_bounds.y < 0)
118 obj_bounds.h += obj_bounds.y;
121 if (obj_bounds.x + obj_bounds.w > 1)
123 obj_bounds.w += (1 - (obj_bounds.x + obj_bounds.w));
125 if (obj_bounds.y + obj_bounds.h > 1)
127 obj_bounds.h += (1 - (obj_bounds.y + obj_bounds.h));
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]);
136 // If we're entirely within the quadtree node, no clipping need occur.
137 if (ContainedInQuadChild(m_objects.bounds[object_id], type))
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]);
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)
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);
158 return new_curves.size();
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]);
169 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
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});
175 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
176 for (QuadTreeIndex overlay = parent; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
178 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
180 if (IntersectsQuadChild(m_objects.bounds[i], type))
182 m_count += ClipObjectToQuadChild(i, type);
186 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
187 // No objects are dirty.
188 m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
192 m_quadtree.nodes[parent].top_left = new_index;
195 m_quadtree.nodes[parent].top_right = new_index;
197 case QTC_BOTTOM_LEFT:
198 m_quadtree.nodes[parent].bottom_left = new_index;
200 case QTC_BOTTOM_RIGHT:
201 m_quadtree.nodes[parent].bottom_right = new_index;
204 Fatal("Tried to add a QuadTree child of invalid type!");
209 void Document::OverlayQuadChildren(QuadTreeIndex orig_parent, QuadTreeIndex parent, QuadTreeNodeChildren type)
211 QuadTreeIndex new_index = m_quadtree.nodes.size();
212 Debug("-------------- Generating Quadtree Node %d (orig %d parent %d, type %d) ----------------------", new_index, orig_parent, parent, type);
213 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, orig_parent, type, 0, 0, -1});
215 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
216 for (unsigned i = m_quadtree.nodes[parent].object_dirty; i < m_quadtree.nodes[parent].object_end; ++i)
218 if (IntersectsQuadChild(m_objects.bounds[i], type))
220 m_count += ClipObjectToQuadChild(i, type);
223 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
224 QuadTreeIndex orig_node = -1;
228 orig_node = m_quadtree.nodes[orig_parent].top_left;
231 orig_node = m_quadtree.nodes[orig_parent].top_right;
233 case QTC_BOTTOM_LEFT:
234 orig_node = m_quadtree.nodes[orig_parent].bottom_left;
236 case QTC_BOTTOM_RIGHT:
237 orig_node = m_quadtree.nodes[orig_parent].bottom_right;
240 Fatal("Tried to overlay a QuadTree child of invalid type!");
243 Fatal("Tried to overlay a QuadTree child that didn't exist!");
245 // Add us to the node's overlay linked list.
246 QuadTreeIndex prev_overlay = orig_node;
247 while (m_quadtree.nodes[prev_overlay].next_overlay != -1) prev_overlay = m_quadtree.nodes[prev_overlay].next_overlay;
248 Debug("- Original node %d, Previous overlay %d, new overlay %d", orig_node, prev_overlay, new_index);
249 m_quadtree.nodes[prev_overlay].next_overlay = new_index;
251 // Recurse into any extant children.
252 if (m_quadtree.nodes[orig_node].top_left != -1)
253 OverlayQuadChildren(orig_node, new_index, QTC_TOP_LEFT);
254 if (m_quadtree.nodes[orig_node].top_right != -1)
255 OverlayQuadChildren(orig_node, new_index, QTC_TOP_RIGHT);
256 if (m_quadtree.nodes[orig_node].bottom_left != -1)
257 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_LEFT);
258 if (m_quadtree.nodes[orig_node].bottom_right != -1)
259 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_RIGHT);
261 m_quadtree.nodes[new_index].object_dirty = m_quadtree.nodes[new_index].object_end;
262 m_quadtree.nodes[new_index].next_overlay = -1;
265 void Document::PropagateQuadChanges(QuadTreeIndex node)
267 for(QuadTreeIndex overlay = node; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
269 // We don't care about clean overlays.
270 if (m_quadtree.nodes[overlay].object_dirty == m_quadtree.nodes[overlay].object_end) continue;
271 // Recurse into any extant children.
272 if (m_quadtree.nodes[node].top_left != -1)
273 OverlayQuadChildren(node, overlay, QTC_TOP_LEFT);
274 if (m_quadtree.nodes[node].top_right != -1)
275 OverlayQuadChildren(node, overlay, QTC_TOP_RIGHT);
276 if (m_quadtree.nodes[node].bottom_left != -1)
277 OverlayQuadChildren(node, overlay, QTC_BOTTOM_LEFT);
278 if (m_quadtree.nodes[node].bottom_right != -1)
279 OverlayQuadChildren(node, overlay, QTC_BOTTOM_RIGHT);
281 m_quadtree.nodes[overlay].object_dirty = m_quadtree.nodes[overlay].object_end;
285 // Reparent a quadtree node, making it the "type" child of a new node.
286 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
288 QuadTreeIndex new_index = m_quadtree.nodes.size();
289 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1});
291 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
292 for (QuadTreeIndex overlay = child; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
294 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
296 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
297 m_objects.types.push_back(m_objects.types[i]);
298 m_objects.data_indices.push_back(m_objects.data_indices[i]);
302 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
303 m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
307 m_quadtree.nodes[new_index].top_left = child;
310 m_quadtree.nodes[new_index].top_right = child;
312 case QTC_BOTTOM_LEFT:
313 m_quadtree.nodes[new_index].bottom_left = child;
315 case QTC_BOTTOM_RIGHT:
316 m_quadtree.nodes[new_index].bottom_right = child;
319 Fatal("Tried to add a QuadTree child of invalid type!");
326 void Document::Load(const string & filename)
328 m_objects.bounds.clear();
332 Debug("Loaded empty document.");
335 Debug("Loading document from file \"%s\"", filename.c_str());
336 FILE * file = fopen(filename.c_str(), "r");
338 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
342 DocChunkTypes chunk_type;
344 while (ReadChunkHeader(file, chunk_type, chunk_size))
349 read = fread(&m_count, sizeof(m_count), 1, file);
351 Fatal("Failed to read number of objects!");
352 Debug("Number of objects: %u", ObjectCount());
355 Debug("Object types...");
356 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
359 Debug("Object bounds...");
360 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
363 Debug("Object data indices...");
364 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
367 Debug("Bezier data...");
368 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
372 Debug("Path data...");
373 Warn("Not handled because lazy");
377 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
378 #ifndef QUADTREE_DISABLED
379 if (m_quadtree.root_id == QUADTREE_EMPTY)
386 unsigned Document::AddPath(unsigned start_index, unsigned end_index, const Colour & fill, const Colour & stroke)
388 Path path(m_objects, start_index, end_index, fill, stroke);
389 unsigned data_index = AddPathData(path);
390 Rect bounds = path.SolveBounds(m_objects);
391 unsigned result = Add(PATH, bounds,data_index);
392 m_objects.paths[data_index].m_index = result;
393 //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);
398 * Add a Bezier using Absolute coords
400 unsigned Document::AddBezier(const Bezier & bezier)
402 Rect bounds = bezier.SolveBounds();
403 Bezier data = bezier.ToRelative(bounds); // Relative
404 if (data.ToAbsolute(bounds) != bezier)
406 Warn("%s != %s", data.ToAbsolute(bounds).Str().c_str(),
407 bezier.Str().c_str());
408 Warn("ToAbsolute on ToRelative does not give original Bezier");
410 unsigned index = AddBezierData(data);
411 return Add(BEZIER, bounds, index);
414 unsigned Document::Add(ObjectType type, const Rect & bounds, unsigned data_index, QuadTreeIndex qti)
416 m_objects.types.push_back(type);
417 m_objects.bounds.push_back(bounds);
418 m_objects.data_indices.push_back(data_index);
419 #ifndef QUADTREE_DISABLED
422 QuadTreeIndex new_qti = qti;
423 while (m_quadtree.nodes[new_qti].next_overlay != -1)
425 if (m_count == m_quadtree.nodes[new_qti].object_end+1)
427 m_quadtree.nodes[new_qti].object_end++;
430 new_qti = m_quadtree.nodes[new_qti].next_overlay;
433 QuadTreeIndex overlay = m_quadtree.nodes.size();
434 Debug("Adding new overlay, nqti = %d, overlay = %d", new_qti, overlay);
435 m_quadtree.nodes.push_back(m_quadtree.nodes[qti]);
436 m_quadtree.nodes[overlay].object_begin = m_count;
437 // All objects are dirty.
438 m_quadtree.nodes[overlay].object_dirty = m_count;
439 m_quadtree.nodes[overlay].object_end = m_count+1;
440 m_quadtree.nodes[overlay].next_overlay = -1;
441 m_quadtree.nodes[new_qti].next_overlay = overlay;
444 done: // matches is not amused, but sulix is nice and moved it inside the #ifdef for him.
446 PropagateQuadChanges(qti);
449 #else // words fail me (still not amused)
455 unsigned Document::AddBezierData(const Bezier & bezier)
457 m_objects.beziers.push_back(bezier);
458 return m_objects.beziers.size()-1;
461 unsigned Document::AddPathData(const Path & path)
463 m_objects.paths.push_back(path);
464 return m_objects.paths.size()-1;
467 void Document::DebugDumpObjects()
469 Debug("Objects for Document %p are:", this);
470 for (unsigned id = 0; id < ObjectCount(); ++id)
472 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
476 bool Document::operator==(const Document & equ) const
478 return (ObjectCount() == equ.ObjectCount()
479 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
480 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
481 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
486 // Behold my amazing tokenizing abilities
487 static string & GetToken(const string & d, string & token, unsigned & i, const string & delims = "()[],{}<>;:=")
490 while (i < d.size() && iswspace(d[i]))
497 if (iswspace(d[i]) || strchr(delims.c_str(),d[i]) != NULL)
499 if (token.size() == 0 && !iswspace(d[i]))
507 //Debug("Got token \"%s\"", token.c_str());
511 static void GetXYPair(const string & d, Real & x, Real & y, unsigned & i,const string & delims = "()[],{}<>;:=")
514 while (GetToken(d, token, i, delims) == ",");
515 x = RealFromStr(token);
516 if (GetToken(d, token, i, delims) != ",")
518 Fatal("Expected \",\" seperating x,y pair");
520 y = RealFromStr(GetToken(d,token,i,delims));
523 static bool GetKeyValuePair(const string & d, string & key, string & value, unsigned & i, const string & delims = "()[],{}<>;:=")
527 while (GetToken(d, token, i, delims) == ":" || token == ";");
529 if (GetToken(d, token, i, delims) != ":")
531 Error("Expected \":\" seperating key:value pair");
535 GetToken(d, value, i, delims);
539 static void TransformXYPair(Real & x, Real & y, const SVGMatrix & transform)
542 x = transform.a * x + transform.c * y + transform.e;
543 y = transform.b * x0 + transform.d * y + transform.f;
546 void Document::ParseSVGTransform(const string & s, SVGMatrix & transform)
548 //Debug("Parsing transform %s", s.c_str());
555 GetToken(s, command, i);
556 if (command == "," || command == "" || command == ":")
559 GetToken(s, command, i);
563 //Debug("Token is \"%s\"", command.c_str());
565 SVGMatrix delta = {1,0,0,0,1,0};
568 assert(GetToken(s,token, i) == "(");
569 if (command == "translate")
571 GetXYPair(s, delta.e, delta.f, i);
572 assert(GetToken(s,token, i) == ")");
574 else if (command == "matrix")
576 GetXYPair(s, delta.a, delta.b,i);
577 GetXYPair(s, delta.c, delta.d,i);
578 GetXYPair(s, delta.e, delta.f,i);
579 assert(GetToken(s,token, i) == ")");
581 else if (command == "scale")
583 delta.a = RealFromStr(GetToken(s,token,i));
584 GetToken(s, token, i);
587 delta.d = RealFromStr(GetToken(s,token,i));
588 assert(GetToken(s, token, i) == ")");
593 assert(token == ")");
599 Warn("Unrecognised transform \"%s\", using identity", command.c_str());
602 //Debug("Old transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
603 //Debug("Delta transform is {%f,%f,%f,%f,%f,%f}", delta.a, delta.b, delta.c, delta.d,delta.e,delta.f);
605 SVGMatrix old(transform);
606 transform.a = old.a * delta.a + old.c * delta.b;
607 transform.c = old.a * delta.c + old.c * delta.d;
608 transform.e = old.a * delta.e + old.c * delta.f + old.e;
610 transform.b = old.b * delta.a + old.d * delta.b;
611 transform.d = old.b * delta.c + old.d * delta.d;
612 transform.f = old.b * delta.e + old.d * delta.f + old.f;
614 //Debug("New transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
618 inline Colour ParseColourString(const string & colour_str)
621 if (colour_str == "red")
623 else if (colour_str == "blue")
625 else if (colour_str == "green")
627 else if (colour_str == "black")
629 else if (colour_str == "white")
630 c = {255,255,255,255};
631 else if (colour_str.size() == 7 && colour_str[0] == '#')
633 //Debug("Parse colour string: \"%s\"", colour_str.c_str());
634 char comp[3] = {colour_str[1], colour_str[2], '\0'};
635 c.r = strtoul(comp, NULL, 16);
636 comp[0] = colour_str[3]; comp[1] = colour_str[4];
637 c.g = strtoul(comp, NULL, 16);
638 comp[0] = colour_str[5]; comp[1] = colour_str[6];
639 c.b = strtoul(comp, NULL, 16);
641 //Debug("Colour is: %u, %u, %u, %u", c.r, c.g, c.b, c.a);
646 void Document::ParseSVGNode(pugi::xml_node & root, SVGMatrix & parent_transform)
648 //Debug("Parse node <%s>", root.name());
652 if (strcmp(root.name(),"svg") == 0)
654 Real ww = RealFromStr(root.attribute("width").as_string());
655 Real hh = RealFromStr(root.attribute("height").as_string());
656 parent_transform.e -= parent_transform.a * ww/Real(2);
657 parent_transform.f -= parent_transform.d * hh/Real(2);
660 for (pugi::xml_node child = root.first_child(); child; child = child.next_sibling())
662 SVGMatrix transform(parent_transform);
663 pugi::xml_attribute attrib_trans = child.attribute("transform");
664 if (!attrib_trans.empty())
666 ParseSVGTransform(attrib_trans.as_string(), transform);
671 if (strcmp(child.name(), "svg") == 0 || strcmp(child.name(),"g") == 0
672 || strcmp(child.name(), "group") == 0)
675 ParseSVGNode(child, transform);
678 else if (strcmp(child.name(), "path") == 0)
680 string d = child.attribute("d").as_string();
681 //Debug("Path data attribute is \"%s\"", d.c_str());
683 pair<unsigned, unsigned> range = ParseSVGPathData(d, transform, closed);
684 if (true && range.first < m_count && range.second < m_count)//(closed)
687 string colour_str("");
688 map<string, string> style;
689 if (child.attribute("style"))
691 ParseSVGStyleData(child.attribute("style").as_string(), style);
694 // Determine shading colour
695 if (child.attribute("fill"))
697 colour_str = child.attribute("fill").as_string();
699 else if (style.find("fill") != style.end())
701 colour_str = style["fill"];
703 Colour fill = ParseColourString(colour_str);
704 Colour stroke = fill;
706 if (child.attribute("stroke"))
708 colour_str = child.attribute("stroke").as_string();
709 stroke = ParseColourString(colour_str);
711 else if (style.find("stroke") != style.end())
713 colour_str = style["stroke"];
714 stroke = ParseColourString(colour_str);
718 // Determin shading alpha
719 if (child.attribute("fill-opacity"))
721 fill.a = 255*child.attribute("fill-opacity").as_float();
723 else if (style.find("fill-opacity") != style.end())
725 fill.a = 255*strtod(style["fill-opacity"].c_str(), NULL);
727 if (child.attribute("stroke-opacity"))
729 stroke.a = 255*child.attribute("stroke-opacity").as_float();
731 else if (style.find("stroke-opacity") != style.end())
733 stroke.a = 255*strtod(style["stroke-opacity"].c_str(), NULL);
735 AddPath(range.first, range.second, fill, stroke);
739 else if (strcmp(child.name(), "line") == 0)
741 Real x0(child.attribute("x1").as_float());
742 Real y0(child.attribute("y1").as_float());
743 Real x1(child.attribute("x2").as_float());
744 Real y1(child.attribute("y2").as_float());
745 TransformXYPair(x0,y0,transform);
746 TransformXYPair(x1,y1,transform);
747 AddBezier(Bezier(x0,y0,x1,y1,x1,y1,x1,y1));
749 else if (strcmp(child.name(), "rect") == 0)
752 const char * attrib_names[] = {"x", "y", "width", "height"};
753 for (size_t i = 0; i < 4; ++i)
754 coords[i] = child.attribute(attrib_names[i]).as_float();
756 Real x2(coords[0]+coords[2]);
757 Real y2(coords[1]+coords[3]);
758 TransformXYPair(coords[0],coords[1],transform); // x, y, transform
759 TransformXYPair(x2,y2,transform);
760 coords[2] = x2 - coords[0];
761 coords[3] = y2 - coords[1];
763 bool outline = !(child.attribute("fill") && strcmp(child.attribute("fill").as_string(),"none") != 0);
764 Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0], coords[1], coords[2], coords[3]),0);
766 else if (strcmp(child.name(), "circle") == 0)
768 Real cx = child.attribute("cx").as_float();
769 Real cy = child.attribute("cy").as_float();
770 Real r = child.attribute("r").as_float();
774 TransformXYPair(x,y,transform);
775 Real w = Real(2)*r*transform.a; // width scales
776 Real h = Real(2)*r*transform.d; // height scales
780 Add(CIRCLE_FILLED, rect,0);
781 Debug("Added Circle %s", rect.Str().c_str());
783 else if (strcmp(child.name(), "text") == 0)
785 Real x = child.attribute("x").as_float();
786 Real y = child.attribute("y").as_float();
787 TransformXYPair(x,y,transform);
788 Debug("Add text \"%s\"", child.child_value());
789 AddText(child.child_value(), 0.05, x, y);
794 void Document::ParseSVGStyleData(const string & style, map<string, string> & results)
799 while (i < style.size() && GetKeyValuePair(style, key, value, i))
801 results[key] = value;
806 * Parse an SVG string into a rectangle
808 void Document::ParseSVG(const string & input, const Rect & bounds)
810 using namespace pugi;
812 xml_document doc_xml;
813 xml_parse_result result = doc_xml.load(input.c_str());
816 Error("Couldn't parse SVG input - %s", result.description());
818 Debug("Loaded XML - %s", result.description());
819 SVGMatrix transform = {bounds.w, 0,bounds.x, 0,bounds.h,bounds.y};
820 ParseSVGNode(doc_xml, transform);
824 * Load an SVG into a rectangle
826 void Document::LoadSVG(const string & filename, const Rect & bounds)
828 using namespace pugi;
830 xml_document doc_xml;
831 ifstream input(filename.c_str(), ios_base::in);
832 xml_parse_result result = doc_xml.load(input);
835 Error("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
837 Debug("Loaded XML from \"%s\" - %s", filename.c_str(), result.description());
841 SVGMatrix transform = {bounds.w,0 ,bounds.x, 0,bounds.h,bounds.y};
842 ParseSVGNode(doc_xml, transform);
847 // Fear the wrath of the tokenizing svg data
848 // Seriously this isn't really very DOM-like at all is it?
849 pair<unsigned, unsigned> Document::ParseSVGPathData(const string & d, const SVGMatrix & transform, bool & closed)
852 Real x[4] = {0,0,0,0};
853 Real y[4] = {0,0,0,0};
867 static string delims("()[],{}<>;:=LlHhVvmMqQzZcC");
869 pair<unsigned, unsigned> range(m_count, m_count);
871 while (i < d.size() && GetToken(d, token, i, delims).size() > 0)
873 if (isalpha(token[0]))
882 bool relative = islower(command[0]);
884 if (command == "m" || command == "M")
886 //Debug("Construct moveto command");
887 Real dx = RealFromStr(GetToken(d,token,i,delims));
888 assert(GetToken(d,token,i,delims) == ",");
889 Real dy = RealFromStr(GetToken(d,token,i,delims));
891 x[0] = (relative) ? x[0] + dx : dx;
892 y[0] = (relative) ? y[0] + dy : dy;
896 //Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
897 command = (command == "m") ? "l" : "L";
899 else if (command == "c" || command == "C" || command == "q" || command == "Q")
901 //Debug("Construct curveto command");
902 Real dx = RealFromStr(GetToken(d,token,i,delims));
903 assert(GetToken(d,token,i,delims) == ",");
904 Real dy = RealFromStr(GetToken(d,token,i,delims));
906 x[1] = (relative) ? x[0] + dx : dx;
907 y[1] = (relative) ? y[0] + dy : dy;
909 dx = RealFromStr(GetToken(d,token,i,delims));
910 assert(GetToken(d,token,i,delims) == ",");
911 dy = RealFromStr(GetToken(d,token,i,delims));
913 x[2] = (relative) ? x[0] + dx : dx;
914 y[2] = (relative) ? y[0] + dy : dy;
916 if (command != "q" && command != "Q")
918 dx = RealFromStr(GetToken(d,token,i,delims));
919 assert(GetToken(d,token,i,delims) == ",");
920 dy = RealFromStr(GetToken(d,token,i,delims));
921 x[3] = (relative) ? x[0] + dx : dx;
922 y[3] = (relative) ? y[0] + dy : dy;
928 Real old_x1(x[1]), old_y1(y[1]);
929 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
930 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
931 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
932 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
937 for (int j = 0; j < 4; ++j)
938 TransformXYPair(x[j],y[j], transform);
940 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
942 //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]));
949 else if (command == "l" || command == "L" || command == "h" || command == "H" || command == "v" || command == "V")
951 //Debug("Construct lineto command, relative %d", relative);
953 Real dx = RealFromStr(GetToken(d,token,i,delims));
955 if (command == "l" || command == "L")
957 assert(GetToken(d,token,i,delims) == ",");
958 dy = RealFromStr(GetToken(d,token,i,delims));
960 else if (command == "v" || command == "V")
965 x[1] = (relative) ? x[0] + dx : dx;
966 y[1] = (relative) ? y[0] + dy : dy;
967 if (command == "v" || command == "V")
971 else if (command == "h" || command == "H")
979 TransformXYPair(x[0],y[0],transform);
980 TransformXYPair(x[1],y[1],transform);
983 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[1],y[1],x[1],y[1]));
985 //Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
991 else if (command == "z" || command == "Z")
993 //Debug("Construct returnto command");
1003 for (int j = 0; j < 4; ++j)
1004 TransformXYPair(x[j],y[j], transform);
1006 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
1007 //Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
1016 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
1031 void Document::SetFont(const string & font_filename)
1033 if (m_font_data != NULL)
1038 FILE *font_file = fopen(font_filename.c_str(), "rb");
1039 fseek(font_file, 0, SEEK_END);
1040 size_t font_file_size = ftell(font_file);
1041 fseek(font_file, 0, SEEK_SET);
1042 m_font_data = (unsigned char*)malloc(font_file_size);
1043 size_t read = fread(m_font_data, 1, font_file_size, font_file);
1044 if (read != font_file_size)
1046 Fatal("Failed to read font data from \"%s\" - Read %u bytes expected %u - %s", font_filename.c_str(), read, font_file_size, strerror(errno));
1049 stbtt_InitFont(&m_font, m_font_data, 0);
1052 void Document::AddText(const string & text, Real scale, Real x, Real y)
1054 if (m_font_data == NULL)
1056 Warn("No font loaded");
1062 int ascent = 0, descent = 0, line_gap = 0;
1063 stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &line_gap);
1064 Real font_scale = scale;
1065 font_scale /= Real(ascent - descent);
1066 Real y_advance = Real(font_scale) * Real(ascent - descent + line_gap);
1067 for (unsigned i = 0; i < text.size(); ++i)
1069 if (text[i] == '\n')
1074 if (!isprint(text[i]))
1077 int advance_width = 0, left_side_bearing = 0, kerning = 0;
1078 stbtt_GetCodepointHMetrics(&m_font, text[i], &advance_width, &left_side_bearing);
1081 kerning = stbtt_GetCodepointKernAdvance(&m_font, text[i-1], text[i]);
1083 x += font_scale * Real(kerning);
1084 AddFontGlyphAtPoint(&m_font, text[i], font_scale, x, y);
1085 x += font_scale * Real(advance_width);
1089 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
1091 int glyph_index = stbtt_FindGlyphIndex(font, character);
1093 // Check if there is actully a glyph to render.
1094 if (stbtt_IsGlyphEmpty(font, glyph_index))
1099 stbtt_vertex *instructions;
1100 int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
1102 Real current_x(0), current_y(0);
1103 unsigned start_index = m_count;
1104 unsigned end_index = m_count;
1105 for (int i = 0; i < num_instructions; ++i)
1107 // TTF uses 16-bit signed ints for coordinates:
1108 // with the y-axis inverted compared to us.
1109 // Convert and scale any data.
1110 Real inst_x = Real(instructions[i].x)*scale;
1111 Real inst_y = Real(instructions[i].y)*-scale;
1112 Real inst_cx = Real(instructions[i].cx)*scale;
1113 Real inst_cy = Real(instructions[i].cy)*-scale;
1114 Real old_x(current_x), old_y(current_y);
1118 switch(instructions[i].type)
1125 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));
1127 // Quadratic Bezier To:
1129 // Quadratic -> Cubic:
1130 // - Endpoints are the same.
1131 // - cubic1 = quad0+(2/3)*(quad1-quad0)
1132 // - cubic2 = quad2+(2/3)*(quad1-quad2)
1133 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,
1134 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));
1139 if (start_index < m_count && end_index < m_count)
1141 AddPath(start_index, end_index);
1143 //Debug("Added Glyph \"%c\" at %f %f, scale %f", (char)character, Float(x), Float(y), Float(scale));
1145 stbtt_FreeShape(font, instructions);
1148 void Document::TransformObjectBounds(const SVGMatrix & transform, ObjectType type)
1150 #ifdef TRANSFORM_BEZIERS_TO_PATH
1151 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1153 Path & p = m_objects.paths[i];
1154 p.m_bounds.x = transform.a * p.m_bounds.x + transform.e;
1155 p.m_bounds.y = transform.d * p.m_bounds.y + transform.f;
1156 p.m_bounds.w *= transform.a;
1157 p.m_bounds.h *= transform.d;
1162 for (unsigned i = 0; i < m_count; ++i)
1164 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1166 TransformXYPair(m_objects.bounds[i].x, m_objects.bounds[i].y, transform);
1167 m_objects.bounds[i].w *= transform.a;
1168 m_objects.bounds[i].h *= transform.d;
1173 void Document::TranslateObjects(const Real & dx, const Real & dy, ObjectType type)
1175 #ifdef TRANSFORM_BEZIERS_TO_PATH
1176 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1178 Path & p = m_objects.paths[i];
1185 for (unsigned i = 0; i < m_count; ++i)
1187 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1189 m_objects.bounds[i].x += dx;
1190 m_objects.bounds[i].y += dy;
1195 void Document::ScaleObjectsAboutPoint(const Real & x, const Real & y, const Real & scale_amount, ObjectType type)
1197 #ifdef TRANSFORM_BEZIERS_TO_PATH
1198 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1200 Path & p = m_objects.paths[i];
1201 p.m_bounds.w /= scale_amount;
1202 p.m_bounds.h /= scale_amount;
1204 p.m_bounds.x /= scale_amount;
1207 p.m_bounds.y /= scale_amount;
1213 for (unsigned i = 0; i < m_count; ++i)
1215 if (type != NUMBER_OF_OBJECT_TYPES && m_objects.types[i] != type)
1218 m_objects.bounds[i].w /= scale_amount;
1219 m_objects.bounds[i].h /= scale_amount;
1220 //m_objects.bounds[i].x = x + (m_objects.bounds[i].x-x)/scale_amount;
1221 //m_objects.bounds[i].y = y + (m_objects.bounds[i].y-x)/scale_amount;
1222 m_objects.bounds[i].x -= x;
1223 m_objects.bounds[i].x /= scale_amount;
1224 m_objects.bounds[i].x += x;
1226 m_objects.bounds[i].y -= y;
1227 m_objects.bounds[i].y /= scale_amount;
1228 m_objects.bounds[i].y += y;