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 (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
178 if (IntersectsQuadChild(m_objects.bounds[i], type))
180 m_count += ClipObjectToQuadChild(i, type);
183 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
187 m_quadtree.nodes[parent].top_left = new_index;
190 m_quadtree.nodes[parent].top_right = new_index;
192 case QTC_BOTTOM_LEFT:
193 m_quadtree.nodes[parent].bottom_left = new_index;
195 case QTC_BOTTOM_RIGHT:
196 m_quadtree.nodes[parent].bottom_right = new_index;
199 Fatal("Tried to add a QuadTree child of invalid type!");
204 // Reparent a quadtree node, making it the "type" child of a new node.
205 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
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});
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)
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]);
218 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
222 m_quadtree.nodes[new_index].top_left = child;
225 m_quadtree.nodes[new_index].top_right = child;
227 case QTC_BOTTOM_LEFT:
228 m_quadtree.nodes[new_index].bottom_left = child;
230 case QTC_BOTTOM_RIGHT:
231 m_quadtree.nodes[new_index].bottom_right = child;
234 Fatal("Tried to add a QuadTree child of invalid type!");
241 void Document::Load(const string & filename)
243 m_objects.bounds.clear();
247 Debug("Loaded empty document.");
250 Debug("Loading document from file \"%s\"", filename.c_str());
251 FILE * file = fopen(filename.c_str(), "r");
253 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
257 DocChunkTypes chunk_type;
259 while (ReadChunkHeader(file, chunk_type, chunk_size))
264 read = fread(&m_count, sizeof(m_count), 1, file);
266 Fatal("Failed to read number of objects!");
267 Debug("Number of objects: %u", ObjectCount());
270 Debug("Object types...");
271 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
274 Debug("Object bounds...");
275 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
278 Debug("Object data indices...");
279 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
282 Debug("Bezier data...");
283 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
287 Debug("Path data...");
288 Warn("Not handled because lazy");
292 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
293 #ifndef QUADTREE_DISABLED
294 if (m_quadtree.root_id == QUADTREE_EMPTY)
301 unsigned Document::AddPath(unsigned start_index, unsigned end_index, const Colour & fill, const Colour & stroke)
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);
313 * Add a Bezier using Absolute coords
315 unsigned Document::AddBezier(const Bezier & bezier)
317 Rect bounds = bezier.SolveBounds();
318 Bezier data = bezier.ToRelative(bounds); // Relative
319 if (data.ToAbsolute(bounds) != bezier)
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");
325 unsigned index = AddBezierData(data);
326 return Add(BEZIER, bounds, index);
329 unsigned Document::Add(ObjectType type, const Rect & bounds, unsigned data_index, QuadTreeIndex qti)
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
337 if (m_count == m_quadtree.nodes[qti].object_end+1)
339 m_quadtree.nodes[qti].object_end++;
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;
351 return (m_count++); // Why can't we just use the size of types or something?
354 unsigned Document::AddBezierData(const Bezier & bezier)
356 m_objects.beziers.push_back(bezier);
357 return m_objects.beziers.size()-1;
360 unsigned Document::AddPathData(const Path & path)
362 m_objects.paths.push_back(path);
363 return m_objects.paths.size()-1;
366 void Document::DebugDumpObjects()
368 Debug("Objects for Document %p are:", this);
369 for (unsigned id = 0; id < ObjectCount(); ++id)
371 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
375 bool Document::operator==(const Document & equ) const
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);
385 // Behold my amazing tokenizing abilities
386 static string & GetToken(const string & d, string & token, unsigned & i, const string & delims = "()[],{}<>;:=")
389 while (i < d.size() && iswspace(d[i]))
396 if (iswspace(d[i]) || strchr(delims.c_str(),d[i]) != NULL)
398 if (token.size() == 0 && !iswspace(d[i]))
406 //Debug("Got token \"%s\"", token.c_str());
410 static void GetXYPair(const string & d, Real & x, Real & y, unsigned & i,const string & delims = "()[],{}<>;:=")
413 while (GetToken(d, token, i, delims) == ",");
414 x = RealFromStr(token);
415 if (GetToken(d, token, i, delims) != ",")
417 Fatal("Expected \",\" seperating x,y pair");
419 y = RealFromStr(GetToken(d,token,i,delims));
422 static bool GetKeyValuePair(const string & d, string & key, string & value, unsigned & i, const string & delims = "()[],{}<>;:=")
426 while (GetToken(d, token, i, delims) == ":" || token == ";");
428 if (GetToken(d, token, i, delims) != ":")
430 Error("Expected \":\" seperating key:value pair");
434 GetToken(d, value, i, delims);
438 static void TransformXYPair(Real & x, Real & y, const SVGMatrix & transform)
441 x = transform.a * x + transform.c * y + transform.e;
442 y = transform.b * x0 + transform.d * y + transform.f;
445 void Document::ParseSVGTransform(const string & s, SVGMatrix & transform)
447 //Debug("Parsing transform %s", s.c_str());
454 GetToken(s, command, i);
455 if (command == "," || command == "" || command == ":")
458 GetToken(s, command, i);
462 //Debug("Token is \"%s\"", command.c_str());
464 SVGMatrix delta = {1,0,0,0,1,0};
467 assert(GetToken(s,token, i) == "(");
468 if (command == "translate")
470 GetXYPair(s, delta.e, delta.f, i);
471 assert(GetToken(s,token, i) == ")");
473 else if (command == "matrix")
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) == ")");
480 else if (command == "scale")
482 delta.a = RealFromStr(GetToken(s,token,i));
483 GetToken(s, token, i);
486 delta.d = RealFromStr(GetToken(s,token,i));
487 assert(GetToken(s, token, i) == ")");
492 assert(token == ")");
498 Warn("Unrecognised transform \"%s\", using identity", command.c_str());
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);
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;
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;
513 //Debug("New transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
517 inline Colour ParseColourString(const string & colour_str)
520 if (colour_str == "red")
522 else if (colour_str == "blue")
524 else if (colour_str == "green")
526 else if (colour_str == "black")
528 else if (colour_str == "white")
529 c = {255,255,255,255};
530 else if (colour_str.size() == 7 && colour_str[0] == '#')
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);
540 //Debug("Colour is: %u, %u, %u, %u", c.r, c.g, c.b, c.a);
545 void Document::ParseSVGNode(pugi::xml_node & root, SVGMatrix & parent_transform)
547 //Debug("Parse node <%s>", root.name());
551 if (strcmp(root.name(),"svg") == 0)
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);
559 for (pugi::xml_node child = root.first_child(); child; child = child.next_sibling())
561 SVGMatrix transform(parent_transform);
562 pugi::xml_attribute attrib_trans = child.attribute("transform");
563 if (!attrib_trans.empty())
565 ParseSVGTransform(attrib_trans.as_string(), transform);
570 if (strcmp(child.name(), "svg") == 0 || strcmp(child.name(),"g") == 0
571 || strcmp(child.name(), "group") == 0)
574 ParseSVGNode(child, transform);
577 else if (strcmp(child.name(), "path") == 0)
579 string d = child.attribute("d").as_string();
580 //Debug("Path data attribute is \"%s\"", d.c_str());
582 pair<unsigned, unsigned> range = ParseSVGPathData(d, transform, closed);
583 if (true && range.first < m_count && range.second < m_count)//(closed)
586 string colour_str("");
587 map<string, string> style;
588 if (child.attribute("style"))
590 ParseSVGStyleData(child.attribute("style").as_string(), style);
593 // Determine shading colour
594 if (child.attribute("fill"))
596 colour_str = child.attribute("fill").as_string();
598 else if (style.find("fill") != style.end())
600 colour_str = style["fill"];
602 Colour fill = ParseColourString(colour_str);
603 Colour stroke = fill;
605 if (child.attribute("stroke"))
607 colour_str = child.attribute("stroke").as_string();
608 stroke = ParseColourString(colour_str);
610 else if (style.find("stroke") != style.end())
612 colour_str = style["stroke"];
613 stroke = ParseColourString(colour_str);
617 // Determin shading alpha
618 if (child.attribute("fill-opacity"))
620 fill.a = 255*child.attribute("fill-opacity").as_float();
622 else if (style.find("fill-opacity") != style.end())
624 fill.a = 255*strtod(style["fill-opacity"].c_str(), NULL);
626 if (child.attribute("stroke-opacity"))
628 stroke.a = 255*child.attribute("stroke-opacity").as_float();
630 else if (style.find("stroke-opacity") != style.end())
632 stroke.a = 255*strtod(style["stroke-opacity"].c_str(), NULL);
634 AddPath(range.first, range.second, fill, stroke);
638 else if (strcmp(child.name(), "line") == 0)
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));
648 else if (strcmp(child.name(), "rect") == 0)
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();
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];
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);
665 else if (strcmp(child.name(), "circle") == 0)
667 Real cx = child.attribute("cx").as_float();
668 Real cy = child.attribute("cy").as_float();
669 Real r = child.attribute("r").as_float();
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
679 Add(CIRCLE_FILLED, rect,0);
680 Debug("Added Circle %s", rect.Str().c_str());
682 else if (strcmp(child.name(), "text") == 0)
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);
693 void Document::ParseSVGStyleData(const string & style, map<string, string> & results)
698 while (i < style.size() && GetKeyValuePair(style, key, value, i))
700 results[key] = value;
705 * Parse an SVG string into a rectangle
707 void Document::ParseSVG(const string & input, const Rect & bounds)
709 using namespace pugi;
711 xml_document doc_xml;
712 xml_parse_result result = doc_xml.load(input.c_str());
715 Error("Couldn't parse SVG input - %s", result.description());
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);
723 * Load an SVG into a rectangle
725 void Document::LoadSVG(const string & filename, const Rect & bounds)
727 using namespace pugi;
729 xml_document doc_xml;
730 ifstream input(filename.c_str(), ios_base::in);
731 xml_parse_result result = doc_xml.load(input);
734 Error("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
736 Debug("Loaded XML from \"%s\" - %s", filename.c_str(), result.description());
740 SVGMatrix transform = {bounds.w,0 ,bounds.x, 0,bounds.h,bounds.y};
741 ParseSVGNode(doc_xml, transform);
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)
751 Real x[4] = {0,0,0,0};
752 Real y[4] = {0,0,0,0};
766 static string delims("()[],{}<>;:=LlHhVvmMqQzZcC");
768 pair<unsigned, unsigned> range(m_count, m_count);
770 while (i < d.size() && GetToken(d, token, i, delims).size() > 0)
772 if (isalpha(token[0]))
781 bool relative = islower(command[0]);
783 if (command == "m" || command == "M")
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));
790 x[0] = (relative) ? x[0] + dx : dx;
791 y[0] = (relative) ? y[0] + dy : dy;
795 //Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
796 command = (command == "m") ? "l" : "L";
798 else if (command == "c" || command == "C" || command == "q" || command == "Q")
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));
805 x[1] = (relative) ? x[0] + dx : dx;
806 y[1] = (relative) ? y[0] + dy : dy;
808 dx = RealFromStr(GetToken(d,token,i,delims));
809 assert(GetToken(d,token,i,delims) == ",");
810 dy = RealFromStr(GetToken(d,token,i,delims));
812 x[2] = (relative) ? x[0] + dx : dx;
813 y[2] = (relative) ? y[0] + dy : dy;
815 if (command != "q" && command != "Q")
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;
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);
836 for (int j = 0; j < 4; ++j)
837 TransformXYPair(x[j],y[j], transform);
839 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
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]));
848 else if (command == "l" || command == "L" || command == "h" || command == "H" || command == "v" || command == "V")
850 //Debug("Construct lineto command, relative %d", relative);
852 Real dx = RealFromStr(GetToken(d,token,i,delims));
854 if (command == "l" || command == "L")
856 assert(GetToken(d,token,i,delims) == ",");
857 dy = RealFromStr(GetToken(d,token,i,delims));
859 else if (command == "v" || command == "V")
864 x[1] = (relative) ? x[0] + dx : dx;
865 y[1] = (relative) ? y[0] + dy : dy;
866 if (command == "v" || command == "V")
870 else if (command == "h" || command == "H")
878 TransformXYPair(x[0],y[0],transform);
879 TransformXYPair(x[1],y[1],transform);
882 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[1],y[1],x[1],y[1]));
884 //Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
890 else if (command == "z" || command == "Z")
892 //Debug("Construct returnto command");
902 for (int j = 0; j < 4; ++j)
903 TransformXYPair(x[j],y[j], transform);
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]));
915 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
930 void Document::SetFont(const string & font_filename)
932 if (m_font_data != NULL)
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)
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));
948 stbtt_InitFont(&m_font, m_font_data, 0);
951 void Document::AddText(const string & text, Real scale, Real x, Real y)
953 if (m_font_data == NULL)
955 Warn("No font loaded");
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)
973 if (!isprint(text[i]))
976 int advance_width = 0, left_side_bearing = 0, kerning = 0;
977 stbtt_GetCodepointHMetrics(&m_font, text[i], &advance_width, &left_side_bearing);
980 kerning = stbtt_GetCodepointKernAdvance(&m_font, text[i-1], text[i]);
982 x += font_scale * Real(kerning);
983 AddFontGlyphAtPoint(&m_font, text[i], font_scale, x, y);
984 x += font_scale * Real(advance_width);
988 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
990 int glyph_index = stbtt_FindGlyphIndex(font, character);
992 // Check if there is actully a glyph to render.
993 if (stbtt_IsGlyphEmpty(font, glyph_index))
998 stbtt_vertex *instructions;
999 int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
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)
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);
1017 switch(instructions[i].type)
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));
1026 // Quadratic Bezier To:
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));
1038 if (start_index < m_count && end_index < m_count)
1040 AddPath(start_index, end_index);
1042 //Debug("Added Glyph \"%c\" at %f %f, scale %f", (char)character, Float(x), Float(y), Float(scale));
1044 stbtt_FreeShape(font, instructions);
1047 void Document::TransformObjectBounds(const SVGMatrix & transform)
1049 for (unsigned i = 0; i < m_count; ++i)
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;
1057 void Document::TranslateObjects(const Real & dx, const Real & dy, ObjectType type)
1059 #ifdef TRANSFORM_BEZIERS_TO_PATH
1060 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1062 Path & p = m_objects.paths[i];
1069 for (unsigned i = 0; i < m_count; ++i)
1071 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1073 m_objects.bounds[i].x += dx;
1074 m_objects.bounds[i].y += dy;
1079 void Document::ScaleObjectsAboutPoint(const Real & x, const Real & y, const Real & scale_amount, ObjectType type)
1081 #ifdef TRANSFORM_BEZIERS_TO_PATH
1082 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1084 Path & p = m_objects.paths[i];
1085 p.m_bounds.w /= scale_amount;
1086 p.m_bounds.h /= scale_amount;
1088 p.m_bounds.x /= scale_amount;
1091 p.m_bounds.y /= scale_amount;
1097 for (unsigned i = 0; i < m_count; ++i)
1099 if (type != NUMBER_OF_OBJECT_TYPES && m_objects.types[i] != type)
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;
1110 m_objects.bounds[i].y -= y;
1111 m_objects.bounds[i].y /= scale_amount;
1112 m_objects.bounds[i].y += y;