6 #include "stb_truetype.h"
11 //TODO: Make this work for variable sized Reals
13 // Loads an std::vector<T> of size num_elements from a file.
15 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
17 size_t structsread = 0;
18 dest.resize(num_elems);
19 structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
20 if (structsread != num_elems)
21 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
24 // Saves an std::vector<T> to a file. Size must be saves separately.
26 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
29 written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
30 if (written != src.size())
31 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
34 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
37 written = fwrite(&type, sizeof(type), 1, dst_file);
39 Fatal("Could not write Chunk header! (ID)");
40 written = fwrite(&size, sizeof(size), 1, dst_file);
42 Fatal("Could not write Chunk header (size)!");
45 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
47 if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
49 if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
54 void Document::Save(const string & filename)
56 Debug("Saving document to file \"%s\"...", filename.c_str());
57 FILE * file = fopen(filename.c_str(), "w");
59 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
62 Debug("Number of objects (%u)...", ObjectCount());
63 WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
64 written = fwrite(&m_count, sizeof(m_count), 1, file);
66 Fatal("Failed to write number of objects!");
68 Debug("Object types...");
69 WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
70 SaveStructVector<ObjectType>(file, m_objects.types);
72 Debug("Object bounds...");
73 WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
74 SaveStructVector<Rect>(file, m_objects.bounds);
76 Debug("Object data indices...");
77 WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
78 SaveStructVector<unsigned>(file, m_objects.data_indices);
80 Debug("Bezier data...");
81 WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
82 SaveStructVector<Bezier>(file, m_objects.beziers);
84 int err = fclose(file);
86 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
88 Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
91 #ifndef QUADTREE_DISABLED
93 void Document::GenBaseQuadtree()
95 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount()});
96 m_quadtree.root_id = 0;
97 GenQuadChild(0, QTC_TOP_LEFT);
100 QuadTreeIndex Document::GenQuadChild(QuadTreeIndex parent, QuadTreeNodeChildren type)
102 QuadTreeIndex new_index = m_quadtree.nodes.size();
103 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0});
105 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
106 for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
108 if (ContainedInQuadChild(m_objects.bounds[i], type))
110 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[i], type));
111 m_objects.types.push_back(m_objects.types[i]);
112 m_objects.data_indices.push_back(m_objects.data_indices[i]);
116 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
120 m_quadtree.nodes[parent].top_left = new_index;
123 m_quadtree.nodes[parent].top_right = new_index;
125 case QTC_BOTTOM_LEFT:
126 m_quadtree.nodes[parent].bottom_left = new_index;
128 case QTC_BOTTOM_RIGHT:
129 m_quadtree.nodes[parent].bottom_right = new_index;
132 Fatal("Tried to add a QuadTree child of invalid type!");
137 // Reparent a quadtree node, making it the "type" child of a new node.
138 QuadTreeIndex Document::GenQuadParent(QuadTreeIndex child, QuadTreeNodeChildren type)
140 QuadTreeIndex new_index = m_quadtree.nodes.size();
141 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, -1, QTC_UNKNOWN, 0, 0});
143 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
144 for (unsigned i = m_quadtree.nodes[child].object_begin; i < m_quadtree.nodes[child].object_end; ++i)
146 m_objects.bounds.push_back(TransformFromQuadChild(m_objects.bounds[i], type));
147 m_objects.types.push_back(m_objects.types[i]);
148 m_objects.data_indices.push_back(m_objects.data_indices[i]);
151 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
155 m_quadtree.nodes[new_index].top_left = child;
158 m_quadtree.nodes[new_index].top_right = child;
160 case QTC_BOTTOM_LEFT:
161 m_quadtree.nodes[new_index].bottom_left = child;
163 case QTC_BOTTOM_RIGHT:
164 m_quadtree.nodes[new_index].bottom_right = child;
167 Fatal("Tried to add a QuadTree child of invalid type!");
174 void Document::Load(const string & filename)
176 m_objects.bounds.clear();
180 Debug("Loaded empty document.");
183 Debug("Loading document from file \"%s\"", filename.c_str());
184 FILE * file = fopen(filename.c_str(), "r");
186 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
190 DocChunkTypes chunk_type;
192 while (ReadChunkHeader(file, chunk_type, chunk_size))
197 read = fread(&m_count, sizeof(m_count), 1, file);
199 Fatal("Failed to read number of objects!");
200 Debug("Number of objects: %u", ObjectCount());
203 Debug("Object types...");
204 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
207 Debug("Object bounds...");
208 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
211 Debug("Object data indices...");
212 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
215 Debug("Bezier data...");
216 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
220 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
221 #ifndef QUADTREE_DISABLED
222 if (m_quadtree.root_id == QUADTREE_EMPTY)
229 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
231 m_objects.types.push_back(type);
232 m_objects.bounds.push_back(bounds);
233 m_objects.data_indices.push_back(data_index);
234 ++m_count; // Why can't we just use the size of types or something?
237 unsigned Document::AddBezierData(const Bezier & bezier)
239 m_objects.beziers.push_back(bezier);
240 return m_objects.beziers.size()-1;
244 void Document::DebugDumpObjects()
246 Debug("Objects for Document %p are:", this);
247 for (unsigned id = 0; id < ObjectCount(); ++id)
249 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
253 bool Document::operator==(const Document & equ) const
255 return (ObjectCount() == equ.ObjectCount()
256 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
257 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
258 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
262 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
263 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
266 * Load an SVG into a rectangle
268 void Document::LoadSVG(const string & filename, const Rect & bounds)
270 using namespace pugi;
272 xml_document doc_xml;
273 ifstream input(filename.c_str(), ios_base::in);
274 xml_parse_result result = doc_xml.load(input);
277 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
279 Debug("Loaded XML - %s", result.description());
283 // Combine all SVG tags into one thing because lazy
284 for (xml_node svg : doc_xml.children("svg"))
286 Real width = Real(svg.attribute("width").as_float()) * bounds.w;
287 Real height = Real(svg.attribute("width").as_float()) * bounds.h;
292 const char * attrib_names[] = {"x", "y", "width", "height"};
293 for (pugi::xml_node rect : svg.children("rect"))
295 for (size_t i = 0; i < 4; ++i)
296 coords[i] = rect.attribute(attrib_names[i]).as_float();
298 bool outline = !(rect.attribute("fill"));
299 Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0]/width + bounds.x, coords[1]/height + bounds.y, coords[2]/width, coords[3]/height),0);
300 Debug("Added rectangle");
304 for (pugi::xml_node circle : svg.children("circle"))
306 Real cx = circle.attribute("cx").as_float();
307 Real cy = circle.attribute("cy").as_float();
308 Real r = circle.attribute("r").as_float();
310 Real x = (cx - r)/width + bounds.x;
311 Real y = (cy - r)/height + bounds.y;
312 Real w = Real(2)*r/width;
313 Real h = Real(2)*r/height;
316 Add(CIRCLE_FILLED, rect,0);
317 Debug("Added Circle %s", rect.Str().c_str());
322 for (pugi::xml_node path : svg.children("path"))
325 string d = path.attribute("d").as_string();
326 Debug("Path data attribute is \"%s\"", d.c_str());
327 AddPathFromString(d, Rect(bounds.x,bounds.y,width,height));
338 // Behold my amazing tokenizing abilities
339 static string & GetToken(const string & d, string & token, unsigned & i)
342 while (i < d.size() && iswspace(d[i]))
349 if (d[i] == ',' || (isalpha(d[i]) && d[i] != 'e') || iswspace(d[i]))
351 if (token.size() == 0 && !iswspace(d[i]))
359 Debug("Got token \"%s\"", token.c_str());
364 // Fear the wrath of the tokenizing svg data
365 // Seriously this isn't really very DOM-like at all is it?
366 void Document::AddPathFromString(const string & d, const Rect & bounds)
368 Real x[4] = {0,0,0,0};
369 Real y[4] = {0,0,0,0};
382 while (i < d.size() && GetToken(d, token, i).size() > 0)
384 if (isalpha(token[0]))
393 bool relative = islower(command[0]);
395 if (command == "m" || command == "M")
397 Debug("Construct moveto command");
398 Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
399 assert(GetToken(d,token,i) == ",");
400 Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
402 x[0] = (relative) ? x[0] + dx : dx;
403 y[0] = (relative) ? y[0] + dy : dy;
407 Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
408 command = (command == "m") ? "l" : "L";
410 else if (command == "c" || command == "C" || command == "q" || command == "Q")
412 Debug("Construct curveto command");
413 Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL))/bounds.w;
414 assert(GetToken(d,token,i) == ",");
415 Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL))/bounds.h;
417 x[1] = (relative) ? x[0] + dx : dx;
418 y[1] = (relative) ? y[0] + dy : dy;
420 dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
421 assert(GetToken(d,token,i) == ",");
422 dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
424 x[2] = (relative) ? x[0] + dx : dx;
425 y[2] = (relative) ? y[0] + dy : dy;
427 if (command != "q" && command != "Q")
429 dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
430 assert(GetToken(d,token,i) == ",");
431 dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
432 x[3] = (relative) ? x[0] + dx : dx;
433 y[3] = (relative) ? y[0] + dy : dy;
439 Real old_x1(x[1]), old_y1(y[1]);
440 x[1] = x[0] + Real(2) * (old_x1 - x[0])/ Real(3);
441 y[1] = y[0] + Real(2) * (old_y1 - y[0])/ Real(3);
442 x[2] = x[3] + Real(2) * (old_x1 - x[3])/ Real(3);
443 y[2] = y[3] + Real(2) * (old_y1 - y[3])/ Real(3);
446 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
447 Add(BEZIER,Rect(0,0,1,1),index);
450 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]));
457 else if (command == "l" || command == "L")
459 Debug("Construct lineto command");
461 Real dx = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.w;
462 assert(GetToken(d,token,i) == ",");
463 Real dy = Real(strtod(GetToken(d,token,i).c_str(),NULL)) / bounds.h;
465 x[1] = (relative) ? x[0] + dx : dx;
466 y[1] = (relative) ? y[0] + dy : dy;
474 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
475 Add(BEZIER,Rect(0,0,1,1),index);
477 Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
483 else if (command == "z" || command == "Z")
485 Debug("Construct returnto command");
493 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2],x[3],y[3]));
494 Add(BEZIER,Rect(0,0,1,1),index);
496 Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
504 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());
518 void Document::AddFontGlyphAtPoint(stbtt_fontinfo *font, int character, Real scale, Real x, Real y)
520 int glyph_index = stbtt_FindGlyphIndex(font, character);
522 // Check if there is actully a glyph to render.
523 if (stbtt_IsGlyphEmpty(font, glyph_index))
528 stbtt_vertex *instructions;
529 int num_instructions = stbtt_GetGlyphShape(font, glyph_index, &instructions);
531 Real current_x(0), current_y(0);
533 for (int i = 0; i < num_instructions; ++i)
535 // TTF uses 16-bit signed ints for coordinates:
536 // with the y-axis inverted compared to us.
537 // Convert and scale any data.
538 Real inst_x = Real(instructions[i].x)*scale;
539 Real inst_y = Real(instructions[i].y)*-scale;
540 Real inst_cx = Real(instructions[i].cx)*scale;
541 Real inst_cy = Real(instructions[i].cy)*-scale;
542 Real old_x(current_x), old_y(current_y);
545 unsigned bezier_index;
546 switch(instructions[i].type)
553 bezier_index = AddBezierData(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));
554 Add(BEZIER,Rect(0,0,1,1),bezier_index);
556 // Quadratic Bezier To:
558 // Quadratic -> Cubic:
559 // - Endpoints are the same.
560 // - cubic1 = quad0+(2/3)*(quad1-quad0)
561 // - cubic2 = quad2+(2/3)*(quad1-quad2)
562 bezier_index = AddBezierData(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,
563 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));
564 Add(BEZIER,Rect(0,0,1,1),bezier_index);
569 stbtt_FreeShape(font, instructions);