7 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
8 #include "transformationtype.h"
10 #include "stb_truetype.h"
15 //TODO: Make this work for variable sized Reals
17 // Loads an std::vector<T> of size num_elements from a file.
19 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
21 size_t structsread = 0;
22 dest.resize(num_elems);
23 structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
24 if (structsread != num_elems)
25 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
28 // Saves an std::vector<T> to a file. Size must be saves separately.
30 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
33 written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
34 if (written != src.size())
35 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
38 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
41 written = fwrite(&type, sizeof(type), 1, dst_file);
43 Fatal("Could not write Chunk header! (ID)");
44 written = fwrite(&size, sizeof(size), 1, dst_file);
46 Fatal("Could not write Chunk header (size)!");
49 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
51 if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
53 if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
58 void Document::Save(const string & filename)
60 Debug("Saving document to file \"%s\"...", filename.c_str());
61 FILE * file = fopen(filename.c_str(), "w");
63 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
66 Debug("Number of objects (%u)...", ObjectCount());
67 WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
68 written = fwrite(&m_count, sizeof(m_count), 1, file);
70 Fatal("Failed to write number of objects!");
72 Debug("Object types...");
73 WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
74 SaveStructVector<ObjectType>(file, m_objects.types);
76 Debug("Object bounds...");
77 WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
78 SaveStructVector<Rect>(file, m_objects.bounds);
80 Debug("Object data indices...");
81 WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
82 SaveStructVector<unsigned>(file, m_objects.data_indices);
84 Debug("Bezier data...");
85 WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
86 SaveStructVector<Bezier>(file, m_objects.beziers);
88 int err = fclose(file);
90 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
92 Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
95 #ifndef QUADTREE_DISABLED
97 void Document::GenBaseQuadtree()
99 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount(), -1});
100 m_quadtree.root_id = 0;
103 int Document::ClipObjectToQuadChild(int object_id, QuadTreeNodeChildren type)
105 PROFILE_SCOPE("Document::ClipObjectToQuadChild");
106 switch (m_objects.types[object_id])
112 Rect obj_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
113 if (obj_bounds.x < 0)
115 obj_bounds.w += obj_bounds.x;
118 if (obj_bounds.y < 0)
120 obj_bounds.h += obj_bounds.y;
123 if (obj_bounds.x + obj_bounds.w > 1)
125 obj_bounds.w += (1 - (obj_bounds.x + obj_bounds.w));
127 if (obj_bounds.y + obj_bounds.h > 1)
129 obj_bounds.h += (1 - (obj_bounds.y + obj_bounds.h));
131 m_objects.bounds.push_back(obj_bounds);
132 m_objects.types.push_back(m_objects.types[object_id]);
133 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
138 // If we're entirely within the quadtree node, no clipping need occur.
139 if (ContainedInQuadChild(m_objects.bounds[object_id], type))
141 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
142 m_objects.types.push_back(m_objects.types[object_id]);
143 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
146 Rect clip_bezier_bounds = TransformRectCoordinates(m_objects.bounds[object_id], TransformFromQuadChild(Rect{0,0,1,1}, type));
147 std::vector<Bezier> new_curves = m_objects.beziers[m_objects.data_indices[object_id]].ClipToRectangle(clip_bezier_bounds);
148 for (size_t i = 0; i < new_curves.size(); ++i)
150 Rect new_bounds = TransformToQuadChild(m_objects.bounds[object_id], type);
151 Bezier new_curve_data = new_curves[i].ToAbsolute(TransformToQuadChild(m_objects.bounds[object_id],type));
152 new_bounds = new_curve_data.SolveBounds();
153 Debug("New bounds: %s", new_bounds.Str().c_str());
154 new_curve_data = new_curve_data.ToRelative(new_bounds);
155 unsigned index = AddBezierData(new_curve_data);
156 m_objects.bounds.push_back(new_bounds);
157 m_objects.types.push_back(BEZIER);
158 m_objects.data_indices.push_back(index);
160 return new_curves.size();
163 Debug("Adding %s -> %s", m_objects.bounds[object_id].Str().c_str(), TransformToQuadChild(m_objects.bounds[object_id], type).Str().c_str());
164 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[object_id], type));
165 m_objects.types.push_back(m_objects.types[object_id]);
166 m_objects.data_indices.push_back(m_objects.data_indices[object_id]);
171 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
173 PROFILE_SCOPE("Document::GenQuadChild()");
174 QuadTreeIndex new_index = m_quadtree.nodes.size();
175 Debug("-------------- Generating Quadtree Node %d (parent %d, type %d) ----------------------", new_index, parent, type);
176 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0, -1});
178 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
179 for (QuadTreeIndex overlay = parent; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
181 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
183 if (IntersectsQuadChild(m_objects.bounds[i], type))
185 m_count += ClipObjectToQuadChild(i, type);
189 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
190 // No objects are dirty.
191 m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
195 m_quadtree.nodes[parent].top_left = new_index;
198 m_quadtree.nodes[parent].top_right = new_index;
200 case QTC_BOTTOM_LEFT:
201 m_quadtree.nodes[parent].bottom_left = new_index;
203 case QTC_BOTTOM_RIGHT:
204 m_quadtree.nodes[parent].bottom_right = new_index;
207 Fatal("Tried to add a QuadTree child of invalid type!");
209 m_document_dirty = true;
213 void Document::OverlayQuadChildren(QuadTreeIndex orig_parent, QuadTreeIndex parent, QuadTreeNodeChildren type)
215 PROFILE_SCOPE("Document::OverlayQuadChildren()");
216 QuadTreeIndex new_index = m_quadtree.nodes.size();
217 Debug("-------------- Generating Quadtree Node %d (orig %d parent %d, type %d) ----------------------", new_index, orig_parent, parent, type);
218 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, orig_parent, type, 0, 0, -1});
220 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
221 for (unsigned i = m_quadtree.nodes[parent].object_dirty; i < m_quadtree.nodes[parent].object_end; ++i)
223 if (IntersectsQuadChild(m_objects.bounds[i], type))
225 m_count += ClipObjectToQuadChild(i, type);
228 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
229 QuadTreeIndex orig_node = -1;
233 orig_node = m_quadtree.nodes[orig_parent].top_left;
236 orig_node = m_quadtree.nodes[orig_parent].top_right;
238 case QTC_BOTTOM_LEFT:
239 orig_node = m_quadtree.nodes[orig_parent].bottom_left;
241 case QTC_BOTTOM_RIGHT:
242 orig_node = m_quadtree.nodes[orig_parent].bottom_right;
245 Fatal("Tried to overlay a QuadTree child of invalid type!");
248 Fatal("Tried to overlay a QuadTree child that didn't exist!");
250 // Add us to the node's overlay linked list.
251 QuadTreeIndex prev_overlay = orig_node;
252 while (m_quadtree.nodes[prev_overlay].next_overlay != -1) prev_overlay = m_quadtree.nodes[prev_overlay].next_overlay;
253 Debug("- Original node %d, Previous overlay %d, new overlay %d", orig_node, prev_overlay, new_index);
254 m_quadtree.nodes[prev_overlay].next_overlay = new_index;
256 // Recurse into any extant children.
257 if (m_quadtree.nodes[orig_node].top_left != -1)
258 OverlayQuadChildren(orig_node, new_index, QTC_TOP_LEFT);
259 if (m_quadtree.nodes[orig_node].top_right != -1)
260 OverlayQuadChildren(orig_node, new_index, QTC_TOP_RIGHT);
261 if (m_quadtree.nodes[orig_node].bottom_left != -1)
262 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_LEFT);
263 if (m_quadtree.nodes[orig_node].bottom_right != -1)
264 OverlayQuadChildren(orig_node, new_index, QTC_BOTTOM_RIGHT);
266 m_quadtree.nodes[new_index].object_dirty = m_quadtree.nodes[new_index].object_end;
267 m_quadtree.nodes[new_index].next_overlay = -1;
268 m_document_dirty = true;
271 void Document::OverlayQuadParent(QuadTreeIndex orig_child, QuadTreeIndex child, QuadTreeNodeChildren type)
273 PROFILE_SCOPE("Document::OverlayQuadParent()");
274 QuadTreeIndex new_index = m_quadtree.nodes.size();
275 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1});
277 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
278 m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
279 for (QuadTreeIndex overlay = child; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
281 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
283 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
284 m_objects.types.push_back(m_objects.types[i]);
285 m_objects.data_indices.push_back(m_objects.data_indices[i]);
289 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
290 QuadTreeIndex orig_node = m_quadtree.nodes[orig_child].parent;
292 Fatal("Tried to overlay a QuadTree child that didn't exist!");
294 // Add us to the node's overlay linked list.
295 QuadTreeIndex prev_overlay = orig_node;
296 while (m_quadtree.nodes[prev_overlay].next_overlay != -1) prev_overlay = m_quadtree.nodes[prev_overlay].next_overlay;
297 m_quadtree.nodes[prev_overlay].next_overlay = new_index;
299 // Recurse into any extant parent.
300 if (m_quadtree.nodes[orig_node].parent != -1)
301 OverlayQuadParent(orig_node, new_index, m_quadtree.nodes[orig_node].child_type);
303 m_quadtree.nodes[new_index].object_dirty = m_quadtree.nodes[new_index].object_end;
304 m_quadtree.nodes[new_index].next_overlay = -1;
305 m_document_dirty = true;
308 void Document::PropagateQuadChanges(QuadTreeIndex node)
310 for(QuadTreeIndex overlay = node; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
312 // We don't care about clean overlays.
313 if (m_quadtree.nodes[overlay].object_dirty == m_quadtree.nodes[overlay].object_end) continue;
314 // Recurse into our parent, should we have any.
315 if (m_quadtree.nodes[node].parent != -1)
316 OverlayQuadParent(node, overlay, m_quadtree.nodes[overlay].child_type);
317 // Recurse into any extant children.
318 if (m_quadtree.nodes[node].top_left != -1)
319 OverlayQuadChildren(node, overlay, QTC_TOP_LEFT);
320 if (m_quadtree.nodes[node].top_right != -1)
321 OverlayQuadChildren(node, overlay, QTC_TOP_RIGHT);
322 if (m_quadtree.nodes[node].bottom_left != -1)
323 OverlayQuadChildren(node, overlay, QTC_BOTTOM_LEFT);
324 if (m_quadtree.nodes[node].bottom_right != -1)
325 OverlayQuadChildren(node, overlay, QTC_BOTTOM_RIGHT);
327 m_quadtree.nodes[overlay].object_dirty = m_quadtree.nodes[overlay].object_end;
331 // Reparent a quadtree node, making it the "type" child of a new node.
332 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
334 QuadTreeIndex new_index = m_quadtree.nodes.size();
335 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0, -1});
337 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
338 for (QuadTreeIndex overlay = child; overlay != -1; overlay = m_quadtree.nodes[overlay].next_overlay)
340 for (unsigned i = m_quadtree.nodes[overlay].object_begin; i < m_quadtree.nodes[overlay].object_end; ++i)
342 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
343 m_objects.types.push_back(m_objects.types[i]);
344 m_objects.data_indices.push_back(m_objects.data_indices[i]);
348 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
349 m_quadtree.nodes[new_index].object_dirty = m_objects.bounds.size();
353 m_quadtree.nodes[new_index].top_left = child;
356 m_quadtree.nodes[new_index].top_right = child;
358 case QTC_BOTTOM_LEFT:
359 m_quadtree.nodes[new_index].bottom_left = child;
361 case QTC_BOTTOM_RIGHT:
362 m_quadtree.nodes[new_index].bottom_right = child;
365 Fatal("Tried to add a QuadTree child of invalid type!");
368 m_document_dirty = true;
373 void Document::Load(const string & filename)
375 m_objects.bounds.clear();
379 Debug("Loaded empty document.");
382 Debug("Loading document from file \"%s\"", filename.c_str());
383 FILE * file = fopen(filename.c_str(), "r");
385 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
389 DocChunkTypes chunk_type;
391 while (ReadChunkHeader(file, chunk_type, chunk_size))
396 read = fread(&m_count, sizeof(m_count), 1, file);
398 Fatal("Failed to read number of objects!");
399 Debug("Number of objects: %u", ObjectCount());
402 Debug("Object types...");
403 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
406 Debug("Object bounds...");
407 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
410 Debug("Object data indices...");
411 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
414 Debug("Bezier data...");
415 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
419 Debug("Path data...");
420 Warn("Not handled because lazy");
424 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
425 #ifndef QUADTREE_DISABLED
426 if (m_quadtree.root_id == QUADTREE_EMPTY)
433 unsigned Document::AddPath(unsigned start_index, unsigned end_index, const Colour & fill, const Colour & stroke)
435 Path path(m_objects, start_index, end_index, fill, stroke);
436 unsigned data_index = AddPathData(path);
437 Rect bounds = path.SolveBounds(m_objects);
438 unsigned result = Add(PATH, bounds,data_index);
439 m_objects.paths[data_index].m_index = result;
440 //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);
445 * Add a Bezier using Absolute coords
447 unsigned Document::AddBezier(const Bezier & bezier)
449 Rect bounds = bezier.SolveBounds();
450 Bezier data = bezier.ToRelative(bounds); // Relative
451 if (data.ToAbsolute(bounds) != bezier)
453 Warn("%s != %s", data.ToAbsolute(bounds).Str().c_str(),
454 bezier.Str().c_str());
455 Warn("ToAbsolute on ToRelative does not give original Bezier");
457 unsigned index = AddBezierData(data);
458 return Add(BEZIER, bounds, index);
460 // Adds an object to the Document, clipping it to m_clip_rect.
461 // Helper function called by Document::Add()
462 int Document::AddClip(ObjectType type, const Rect& bounds, unsigned data_index, const Rect& clip_rect)
464 PROFILE_SCOPE("Document::AddAndClip");
471 Rect obj_bounds = clip_rect.Clip(bounds);
472 m_objects.bounds.push_back(obj_bounds);
473 m_objects.types.push_back(type);
474 m_objects.data_indices.push_back(data_index);
479 // If we're entirely within the clipping rect, no clipping need occur.
480 if (clip_rect.Contains(bounds))
482 m_objects.bounds.push_back(bounds);
483 m_objects.types.push_back(type);
484 m_objects.data_indices.push_back(data_index);
487 Rect clip_bezier_bounds = TransformRectCoordinates(bounds, clip_rect);
488 std::vector<Bezier> new_curves = m_objects.beziers[data_index].ClipToRectangle(clip_bezier_bounds);
489 for (size_t i = 0; i < new_curves.size(); ++i)
491 Bezier new_curve_data = new_curves[i].ToAbsolute(bounds);
492 Rect new_bounds = new_curve_data.SolveBounds();
493 new_curve_data = new_curve_data.ToRelative(new_bounds);
494 unsigned index = AddBezierData(new_curve_data);
495 m_objects.bounds.push_back(new_bounds);
496 m_objects.types.push_back(BEZIER);
497 m_objects.data_indices.push_back(index);
499 return new_curves.size();
502 m_objects.bounds.push_back(bounds);
503 m_objects.types.push_back(type);
504 m_objects.data_indices.push_back(data_index);
510 unsigned Document::Add(ObjectType type, const Rect & bounds, unsigned data_index, QuadTreeIndex qti)
512 PROFILE_SCOPE("Document::Add");
513 Rect new_bounds = bounds;
515 bool still_to_add = true;
516 #ifndef QUADTREE_DISABLED
517 if (qti == -1) qti = m_current_insert_node;
520 // Move the object to the quadtree node it should be in.
521 m_quadtree.GetCanonicalCoords(qti, new_bounds.x, new_bounds.y, this);
522 Rect cliprect = Rect(0,0,1,1);
523 // If an object spans multiple quadtree nodes...
524 if (!cliprect.Contains(new_bounds))
526 num_added = AddClip(type, new_bounds, data_index, cliprect);
527 still_to_add = false;
533 m_objects.types.push_back(type);
534 m_objects.bounds.push_back(new_bounds);
535 m_objects.data_indices.push_back(data_index);
537 #ifndef QUADTREE_DISABLED
540 QuadTreeIndex new_qti = qti;
541 while (m_quadtree.nodes[new_qti].next_overlay != -1)
543 if (m_count == m_quadtree.nodes[new_qti].object_end+1)
545 m_quadtree.nodes[new_qti].object_end += num_added;
548 new_qti = m_quadtree.nodes[new_qti].next_overlay;
551 QuadTreeIndex overlay = m_quadtree.nodes.size();
552 Debug("Adding new overlay, nqti = %d, overlay = %d", new_qti, overlay);
553 m_quadtree.nodes.push_back(m_quadtree.nodes[qti]);
554 m_quadtree.nodes[overlay].object_begin = m_count;
555 // All objects are dirty.
556 m_quadtree.nodes[overlay].object_dirty = m_count;
557 m_quadtree.nodes[overlay].object_end = m_count+num_added;
558 m_quadtree.nodes[overlay].next_overlay = -1;
559 m_quadtree.nodes[new_qti].next_overlay = overlay;
562 done: // matches is not amused, but sulix is nice and moved it inside the #ifdef for him.
563 m_count += num_added;
565 return m_count-num_added;
566 #else // words fail me (still not amused)
572 unsigned Document::AddBezierData(const Bezier & bezier)
574 m_objects.beziers.push_back(bezier);
575 return m_objects.beziers.size()-1;
578 unsigned Document::AddPathData(const Path & path)
580 m_objects.paths.push_back(path);
581 return m_objects.paths.size()-1;
584 void Document::DebugDumpObjects()
586 Debug("Objects for Document %p are:", this);
587 for (unsigned id = 0; id < ObjectCount(); ++id)
589 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
593 bool Document::operator==(const Document & equ) const
595 return (ObjectCount() == equ.ObjectCount()
596 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
597 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
598 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
603 // Behold my amazing tokenizing abilities
604 static string & GetToken(const string & d, string & token, unsigned & i, const string & delims = "()[],{}<>;:=")
607 while (i < d.size() && iswspace(d[i]))
614 if (iswspace(d[i]) || strchr(delims.c_str(),d[i]) != NULL)
616 if (token.size() == 0 && !iswspace(d[i]))
624 //Debug("Got token \"%s\"", token.c_str());
628 static void GetXYPair(const string & d, Real & x, Real & y, unsigned & i,const string & delims = "()[],{}<>;:=")
631 while (GetToken(d, token, i, delims) == ",");
632 x = RealFromStr(token);
633 if (GetToken(d, token, i, delims) != ",")
635 Fatal("Expected \",\" seperating x,y pair");
637 y = RealFromStr(GetToken(d,token,i,delims));
640 static bool GetKeyValuePair(const string & d, string & key, string & value, unsigned & i, const string & delims = "()[],{}<>;:=")
644 while (GetToken(d, token, i, delims) == ":" || token == ";");
646 if (GetToken(d, token, i, delims) != ":")
648 Error("Expected \":\" seperating key:value pair");
652 GetToken(d, value, i, delims);
656 static void TransformXYPair(Real & x, Real & y, const SVGMatrix & transform)
659 x = transform.a * x + transform.c * y + transform.e;
660 y = transform.b * x0 + transform.d * y + transform.f;
663 void Document::ParseSVGTransform(const string & s, SVGMatrix & transform)
665 //Debug("Parsing transform %s", s.c_str());
672 GetToken(s, command, i);
673 if (command == "," || command == "" || command == ":")
676 GetToken(s, command, i);
680 //Debug("Token is \"%s\"", command.c_str());
682 SVGMatrix delta = {1,0,0,0,1,0};
685 assert(GetToken(s,token, i) == "(");
686 if (command == "translate")
688 GetXYPair(s, delta.e, delta.f, i);
689 assert(GetToken(s,token, i) == ")");
691 else if (command == "matrix")
693 GetXYPair(s, delta.a, delta.b,i);
694 GetXYPair(s, delta.c, delta.d,i);
695 GetXYPair(s, delta.e, delta.f,i);
696 assert(GetToken(s,token, i) == ")");
698 else if (command == "scale")
700 delta.a = RealFromStr(GetToken(s,token,i));
701 GetToken(s, token, i);
704 delta.d = RealFromStr(GetToken(s,token,i));
705 assert(GetToken(s, token, i) == ")");
710 assert(token == ")");
716 Warn("Unrecognised transform \"%s\", using identity", command.c_str());
719 //Debug("Old transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
720 //Debug("Delta transform is {%f,%f,%f,%f,%f,%f}", delta.a, delta.b, delta.c, delta.d,delta.e,delta.f);
722 SVGMatrix old(transform);
723 transform.a = old.a * delta.a + old.c * delta.b;
724 transform.c = old.a * delta.c + old.c * delta.d;
725 transform.e = old.a * delta.e + old.c * delta.f + old.e;
727 transform.b = old.b * delta.a + old.d * delta.b;
728 transform.d = old.b * delta.c + old.d * delta.d;
729 transform.f = old.b * delta.e + old.d * delta.f + old.f;
731 //Debug("New transform is {%f,%f,%f,%f,%f,%f}", transform.a, transform.b, transform.c, transform.d,transform.e,transform.f);
735 inline Colour ParseColourString(const string & colour_str)
738 if (colour_str == "red")
740 else if (colour_str == "blue")
742 else if (colour_str == "green")
744 else if (colour_str == "black")
746 else if (colour_str == "white")
747 c = {255,255,255,255};
748 else if (colour_str.size() == 7 && colour_str[0] == '#')
750 //Debug("Parse colour string: \"%s\"", colour_str.c_str());
751 char comp[3] = {colour_str[1], colour_str[2], '\0'};
752 c.r = strtoul(comp, NULL, 16);
753 comp[0] = colour_str[3]; comp[1] = colour_str[4];
754 c.g = strtoul(comp, NULL, 16);
755 comp[0] = colour_str[5]; comp[1] = colour_str[6];
756 c.b = strtoul(comp, NULL, 16);
758 //Debug("Colour is: %u, %u, %u, %u", c.r, c.g, c.b, c.a);
763 void Document::ParseSVGNode(pugi::xml_node & root, SVGMatrix & parent_transform)
765 //Debug("Parse node <%s>", root.name());
769 if (strcmp(root.name(),"svg") == 0)
771 Real ww = RealFromStr(root.attribute("width").as_string());
772 Real hh = RealFromStr(root.attribute("height").as_string());
773 parent_transform.e -= parent_transform.a * ww/Real(2);
774 parent_transform.f -= parent_transform.d * hh/Real(2);
777 for (pugi::xml_node child = root.first_child(); child; child = child.next_sibling())
779 SVGMatrix transform(parent_transform);
780 pugi::xml_attribute attrib_trans = child.attribute("transform");
781 if (!attrib_trans.empty())
783 ParseSVGTransform(attrib_trans.as_string(), transform);
788 if (strcmp(child.name(), "svg") == 0 || strcmp(child.name(),"g") == 0
789 || strcmp(child.name(), "group") == 0)
792 ParseSVGNode(child, transform);
795 else if (strcmp(child.name(), "path") == 0)
797 string d = child.attribute("d").as_string();
798 //Debug("Path data attribute is \"%s\"", d.c_str());
800 pair<unsigned, unsigned> range = ParseSVGPathData(d, transform, closed);
801 if (true && range.first < m_count && range.second < m_count)//(closed)
804 string colour_str("");
805 map<string, string> style;
806 if (child.attribute("style"))
808 ParseSVGStyleData(child.attribute("style").as_string(), style);
811 // Determine shading colour
812 if (child.attribute("fill"))
814 colour_str = child.attribute("fill").as_string();
816 else if (style.find("fill") != style.end())
818 colour_str = style["fill"];
820 Colour fill = ParseColourString(colour_str);
821 Colour stroke = fill;
823 if (child.attribute("stroke"))
825 colour_str = child.attribute("stroke").as_string();
826 stroke = ParseColourString(colour_str);
828 else if (style.find("stroke") != style.end())
830 colour_str = style["stroke"];
831 stroke = ParseColourString(colour_str);
835 // Determin shading alpha
836 if (child.attribute("fill-opacity"))
838 fill.a = 255*child.attribute("fill-opacity").as_float();
840 else if (style.find("fill-opacity") != style.end())
842 fill.a = 255*strtod(style["fill-opacity"].c_str(), NULL);
844 if (child.attribute("stroke-opacity"))
846 stroke.a = 255*child.attribute("stroke-opacity").as_float();
848 else if (style.find("stroke-opacity") != style.end())
850 stroke.a = 255*strtod(style["stroke-opacity"].c_str(), NULL);
852 AddPath(range.first, range.second, fill, stroke);
856 else if (strcmp(child.name(), "line") == 0)
858 Real x0(child.attribute("x1").as_float());
859 Real y0(child.attribute("y1").as_float());
860 Real x1(child.attribute("x2").as_float());
861 Real y1(child.attribute("y2").as_float());
862 TransformXYPair(x0,y0,transform);
863 TransformXYPair(x1,y1,transform);
864 AddBezier(Bezier(x0,y0,x1,y1,x1,y1,x1,y1));
866 else if (strcmp(child.name(), "rect") == 0)
869 const char * attrib_names[] = {"x", "y", "width", "height"};
870 for (size_t i = 0; i < 4; ++i)
871 coords[i] = child.attribute(attrib_names[i]).as_float();
873 Real x2(coords[0]+coords[2]);
874 Real y2(coords[1]+coords[3]);
875 TransformXYPair(coords[0],coords[1],transform); // x, y, transform
876 TransformXYPair(x2,y2,transform);
877 coords[2] = x2 - coords[0];
878 coords[3] = y2 - coords[1];
880 bool outline = !(child.attribute("fill") && strcmp(child.attribute("fill").as_string(),"none") != 0);
881 Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0], coords[1], coords[2], coords[3]),0);
883 else if (strcmp(child.name(), "circle") == 0)
885 Real cx = child.attribute("cx").as_float();
886 Real cy = child.attribute("cy").as_float();
887 Real r = child.attribute("r").as_float();
891 TransformXYPair(x,y,transform);
892 Real w = Real(2)*r*transform.a; // width scales
893 Real h = Real(2)*r*transform.d; // height scales
897 Add(CIRCLE_FILLED, rect,0);
898 Debug("Added Circle %s", rect.Str().c_str());
900 else if (strcmp(child.name(), "text") == 0)
902 Real x = child.attribute("x").as_float();
903 Real y = child.attribute("y").as_float();
904 TransformXYPair(x,y,transform);
905 Debug("Add text \"%s\"", child.child_value());
906 AddText(child.child_value(), 0.05, x, y);
911 void Document::ParseSVGStyleData(const string & style, map<string, string> & results)
916 while (i < style.size() && GetKeyValuePair(style, key, value, i))
918 results[key] = value;
923 * Parse an SVG string into a rectangle
925 void Document::ParseSVG(const string & input, const Rect & bounds)
927 using namespace pugi;
929 xml_document doc_xml;
930 xml_parse_result result = doc_xml.load(input.c_str());
933 Error("Couldn't parse SVG input - %s", result.description());
935 Debug("Loaded XML - %s", result.description());
936 SVGMatrix transform = {bounds.w, 0,bounds.x, 0,bounds.h,bounds.y};
937 ParseSVGNode(doc_xml, transform);
941 * Load an SVG into a rectangle
943 void Document::LoadSVG(const string & filename, const Rect & bounds)
945 using namespace pugi;
947 xml_document doc_xml;
948 ifstream input(filename.c_str(), ios_base::in);
949 xml_parse_result result = doc_xml.load(input);
952 Error("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
954 Debug("Loaded XML from \"%s\" - %s", filename.c_str(), result.description());
958 SVGMatrix transform = {bounds.w,0 ,bounds.x, 0,bounds.h,bounds.y};
959 ParseSVGNode(doc_xml, transform);
964 // Fear the wrath of the tokenizing svg data
965 // Seriously this isn't really very DOM-like at all is it?
966 pair<unsigned, unsigned> Document::ParseSVGPathData(const string & d, const SVGMatrix & transform, bool & closed)
969 Real x[4] = {0,0,0,0};
970 Real y[4] = {0,0,0,0};
984 static string delims("()[],{}<>;:=LlHhVvmMqQzZcC");
986 pair<unsigned, unsigned> range(m_count, m_count);
988 while (i < d.size() && GetToken(d, token, i, delims).size() > 0)
990 if (isalpha(token[0]))
999 bool relative = islower(command[0]);
1001 if (command == "m" || command == "M")
1003 //Debug("Construct moveto command");
1004 Real dx = RealFromStr(GetToken(d,token,i,delims));
1005 assert(GetToken(d,token,i,delims) == ",");
1006 Real dy = RealFromStr(GetToken(d,token,i,delims));
1008 x[0] = (relative) ? x[0] + dx : dx;
1009 y[0] = (relative) ? y[0] + dy : dy;
1013 //Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
1014 command = (command == "m") ? "l" : "L";
1016 else if (command == "c" || command == "C" || command == "q" || command == "Q")
1018 //Debug("Construct curveto command");
1019 Real dx = RealFromStr(GetToken(d,token,i,delims));
1020 assert(GetToken(d,token,i,delims) == ",");
1021 Real dy = RealFromStr(GetToken(d,token,i,delims));
1023 x[1] = (relative) ? x[0] + dx : dx;
1024 y[1] = (relative) ? y[0] + dy : dy;
1026 dx = RealFromStr(GetToken(d,token,i,delims));
1027 assert(GetToken(d,token,i,delims) == ",");
1028 dy = RealFromStr(GetToken(d,token,i,delims));
1030 x[2] = (relative) ? x[0] + dx : dx;
1031 y[2] = (relative) ? y[0] + dy : dy;
1033 if (command != "q" && command != "Q")
1035 dx = RealFromStr(GetToken(d,token,i,delims));
1036 assert(GetToken(d,token,i,delims) == ",");
1037 dy = RealFromStr(GetToken(d,token,i,delims));
1038 x[3] = (relative) ? x[0] + dx : dx;
1039 y[3] = (relative) ? y[0] + dy : dy;
1045 Real old_x1(x[1]), old_y1(y[1]);
1046 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
1047 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
1048 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
1049 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
1054 for (int j = 0; j < 4; ++j)
1055 TransformXYPair(x[j],y[j], transform);
1057 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
1059 //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]));
1066 else if (command == "l" || command == "L" || command == "h" || command == "H" || command == "v" || command == "V")
1068 //Debug("Construct lineto command, relative %d", relative);
1070 Real dx = RealFromStr(GetToken(d,token,i,delims));
1072 if (command == "l" || command == "L")
1074 assert(GetToken(d,token,i,delims) == ",");
1075 dy = RealFromStr(GetToken(d,token,i,delims));
1077 else if (command == "v" || command == "V")
1082 x[1] = (relative) ? x[0] + dx : dx;
1083 y[1] = (relative) ? y[0] + dy : dy;
1084 if (command == "v" || command == "V")
1088 else if (command == "h" || command == "H")
1096 TransformXYPair(x[0],y[0],transform);
1097 TransformXYPair(x[1],y[1],transform);
1100 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[1],y[1],x[1],y[1]));
1102 //Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
1108 else if (command == "z" || command == "Z")
1110 //Debug("Construct returnto command");
1120 for (int j = 0; j < 4; ++j)
1121 TransformXYPair(x[j],y[j], transform);
1123 range.second = AddBezier(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
1124 //Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
1133 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
1148 void Document::SetFont(const string & font_filename)
1150 if (m_font_data != NULL)
1155 FILE *font_file = fopen(font_filename.c_str(), "rb");
1156 fseek(font_file, 0, SEEK_END);
1157 size_t font_file_size = ftell(font_file);
1158 fseek(font_file, 0, SEEK_SET);
1159 m_font_data = (unsigned char*)malloc(font_file_size);
1160 size_t read = fread(m_font_data, 1, font_file_size, font_file);
1161 if (read != font_file_size)
1163 Fatal("Failed to read font data from \"%s\" - Read %u bytes expected %u - %s", font_filename.c_str(), read, font_file_size, strerror(errno));
1166 stbtt_InitFont(&m_font, m_font_data, 0);
1169 void Document::AddText(const string & text, Real scale, Real x, Real y)
1171 if (m_font_data == NULL)
1173 Warn("No font loaded");
1179 int ascent = 0, descent = 0, line_gap = 0;
1180 stbtt_GetFontVMetrics(&m_font, &ascent, &descent, &line_gap);
1181 Real font_scale = scale;
1182 font_scale /= Real(ascent - descent);
1183 Real y_advance = Real(font_scale) * Real(ascent - descent + line_gap);
1184 for (unsigned i = 0; i < text.size(); ++i)
1186 if (text[i] == '\n')
1191 if (!isprint(text[i]))
1194 int advance_width = 0, left_side_bearing = 0, kerning = 0;
1195 stbtt_GetCodepointHMetrics(&m_font, text[i], &advance_width, &left_side_bearing);
1198 kerning = stbtt_GetCodepointKernAdvance(&m_font, text[i-1], text[i]);
1200 x += font_scale * Real(kerning);
1201 AddFontGlyphAtPoint(&m_font, text[i], font_scale, x, y);
1202 x += font_scale * Real(advance_width);
1206 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
1208 int glyph_index = stbtt_FindGlyphIndex(font, character);
1210 // Check if there is actully a glyph to render.
1211 if (stbtt_IsGlyphEmpty(font, glyph_index))
1216 stbtt_vertex *instructions;
1217 int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
1219 Real current_x(0), current_y(0);
1220 unsigned start_index = m_count;
1221 unsigned end_index = m_count;
1222 for (int i = 0; i < num_instructions; ++i)
1224 // TTF uses 16-bit signed ints for coordinates:
1225 // with the y-axis inverted compared to us.
1226 // Convert and scale any data.
1227 Real inst_x = Real(instructions[i].x)*scale;
1228 Real inst_y = Real(instructions[i].y)*-scale;
1229 Real inst_cx = Real(instructions[i].cx)*scale;
1230 Real inst_cy = Real(instructions[i].cy)*-scale;
1231 Real old_x(current_x), old_y(current_y);
1235 switch(instructions[i].type)
1242 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));
1244 // Quadratic Bezier To:
1246 // Quadratic -> Cubic:
1247 // - Endpoints are the same.
1248 // - cubic1 = quad0+(2/3)*(quad1-quad0)
1249 // - cubic2 = quad2+(2/3)*(quad1-quad2)
1250 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,
1251 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));
1256 if (start_index < m_count && end_index < m_count)
1258 AddPath(start_index, end_index);
1260 //Debug("Added Glyph \"%c\" at %f %f, scale %f", (char)character, Float(x), Float(y), Float(scale));
1262 stbtt_FreeShape(font, instructions);
1265 void Document::TransformObjectBounds(const SVGMatrix & transform, ObjectType type)
1267 #ifdef TRANSFORM_BEZIERS_TO_PATH
1268 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1270 Path & p = m_objects.paths[i];
1271 p.m_bounds.x = transform.a * p.m_bounds.x + transform.e;
1272 p.m_bounds.y = transform.d * p.m_bounds.y + transform.f;
1273 p.m_bounds.w *= transform.a;
1274 p.m_bounds.h *= transform.d;
1279 for (unsigned i = 0; i < m_count; ++i)
1281 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1283 TransformXYPair(m_objects.bounds[i].x, m_objects.bounds[i].y, transform);
1284 m_objects.bounds[i].w *= transform.a;
1285 m_objects.bounds[i].h *= transform.d;
1290 void Document::TranslateObjects(const Real & dx, const Real & dy, ObjectType type)
1292 #ifdef TRANSFORM_BEZIERS_TO_PATH
1293 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1295 Path & p = m_objects.paths[i];
1302 for (unsigned i = 0; i < m_count; ++i)
1304 if (type == NUMBER_OF_OBJECT_TYPES || m_objects.types[i] == type)
1306 m_objects.bounds[i].x += dx;
1307 m_objects.bounds[i].y += dy;
1312 void Document::ScaleObjectsAboutPoint(const Real & x, const Real & y, const Real & scale_amount, ObjectType type)
1314 #ifdef TRANSFORM_BEZIERS_TO_PATH
1315 for (unsigned i = 0; i < m_objects.paths.size(); ++i)
1317 Path & p = m_objects.paths[i];
1318 p.m_bounds.w /= scale_amount;
1319 p.m_bounds.h /= scale_amount;
1321 p.m_bounds.x /= scale_amount;
1324 p.m_bounds.y /= scale_amount;
1330 for (unsigned i = 0; i < m_count; ++i)
1332 if (type != NUMBER_OF_OBJECT_TYPES && m_objects.types[i] != type)
1335 m_objects.bounds[i].w /= scale_amount;
1336 m_objects.bounds[i].h /= scale_amount;
1337 //m_objects.bounds[i].x = x + (m_objects.bounds[i].x-x)/scale_amount;
1338 //m_objects.bounds[i].y = y + (m_objects.bounds[i].y-x)/scale_amount;
1339 m_objects.bounds[i].x -= x;
1340 m_objects.bounds[i].x /= scale_amount;
1341 m_objects.bounds[i].x += x;
1343 m_objects.bounds[i].y -= y;
1344 m_objects.bounds[i].y /= scale_amount;
1345 m_objects.bounds[i].y += y;