9 //TODO: Make this work for variable sized Reals
11 // Loads an std::vector<T> of size num_elements from a file.
13 static void LoadStructVector(FILE *src_file, size_t num_elems, std::vector<T>& dest)
15 size_t structsread = 0;
16 dest.resize(num_elems);
17 structsread = fread(dest.data(), sizeof(T), num_elems, src_file);
18 if (structsread != num_elems)
19 Fatal("Only read %u structs (expected %u)!", structsread, num_elems);
22 // Saves an std::vector<T> to a file. Size must be saves separately.
24 static void SaveStructVector(FILE *dst_file, std::vector<T>& src)
27 written = fwrite(src.data(), sizeof(T), src.size(), dst_file);
28 if (written != src.size())
29 Fatal("Only wrote %u structs (expected %u)!", written, src.size());
32 static void WriteChunkHeader(FILE *dst_file, DocChunkTypes type, uint32_t size)
35 written = fwrite(&type, sizeof(type), 1, dst_file);
37 Fatal("Could not write Chunk header! (ID)");
38 written = fwrite(&size, sizeof(size), 1, dst_file);
40 Fatal("Could not write Chunk header (size)!");
43 static bool ReadChunkHeader(FILE *src_file, DocChunkTypes& type, uint32_t& size)
45 if (fread(&type, sizeof(DocChunkTypes), 1, src_file) != 1)
47 if (fread(&size, sizeof(uint32_t), 1, src_file) != 1)
52 void Document::Save(const string & filename)
54 Debug("Saving document to file \"%s\"...", filename.c_str());
55 FILE * file = fopen(filename.c_str(), "w");
57 Fatal("Couldn't open file \"%s\" - %s", filename.c_str(), strerror(errno));
60 Debug("Number of objects (%u)...", ObjectCount());
61 WriteChunkHeader(file, CT_NUMOBJS, sizeof(m_count));
62 written = fwrite(&m_count, sizeof(m_count), 1, file);
64 Fatal("Failed to write number of objects!");
66 Debug("Object types...");
67 WriteChunkHeader(file, CT_OBJTYPES, m_objects.types.size() * sizeof(ObjectType));
68 SaveStructVector<ObjectType>(file, m_objects.types);
70 Debug("Object bounds...");
71 WriteChunkHeader(file, CT_OBJBOUNDS, m_objects.bounds.size() * sizeof(Rect));
72 SaveStructVector<Rect>(file, m_objects.bounds);
74 Debug("Object data indices...");
75 WriteChunkHeader(file, CT_OBJINDICES, m_objects.data_indices.size() * sizeof(unsigned));
76 SaveStructVector<unsigned>(file, m_objects.data_indices);
78 Debug("Bezier data...");
79 WriteChunkHeader(file, CT_OBJBEZIERS, m_objects.beziers.size() * sizeof(uint8_t));
80 SaveStructVector<Bezier>(file, m_objects.beziers);
82 int err = fclose(file);
84 Fatal("Failed to close file \"%s\" - %s", filename.c_str(), strerror(err));
86 Debug("Successfully saved %u objects to \"%s\"", ObjectCount(), filename.c_str());
89 #ifndef QUADTREE_DISABLED
91 void Document::GenBaseQuadtree()
93 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QTC_UNKNOWN, 0, ObjectCount()});
94 m_quadtree.root_id = 0;
95 GenQuadNode(0, QTC_TOP_LEFT);
98 QuadTreeIndex Document::GenQuadNode(QuadTreeIndex parent, QuadTreeNodeChildren type)
100 QuadTreeIndex new_index = m_quadtree.nodes.size();
101 m_quadtree.nodes.push_back(QuadTreeNode{QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, QUADTREE_EMPTY, parent, type, 0, 0});
103 m_quadtree.nodes[new_index].object_begin = m_objects.bounds.size();
104 for (unsigned i = m_quadtree.nodes[parent].object_begin; i < m_quadtree.nodes[parent].object_end; ++i)
106 if (ContainedInQuadChild(m_objects.bounds[i], type))
108 m_objects.bounds.push_back(TransformToQuadChild(m_objects.bounds[i], type));
109 m_objects.types.push_back(m_objects.types[i]);
110 m_objects.data_indices.push_back(m_objects.data_indices[i]);
114 m_quadtree.nodes[new_index].object_end = m_objects.bounds.size();
118 m_quadtree.nodes[parent].top_left = new_index;
121 m_quadtree.nodes[parent].top_right = new_index;
123 case QTC_BOTTOM_LEFT:
124 m_quadtree.nodes[parent].bottom_left = new_index;
126 case QTC_BOTTOM_RIGHT:
127 m_quadtree.nodes[parent].bottom_right = new_index;
130 Fatal("Tried to add a QuadTree child of invalid type!");
137 void Document::Load(const string & filename)
139 m_objects.bounds.clear();
143 Debug("Loaded empty document.");
146 Debug("Loading document from file \"%s\"", filename.c_str());
147 FILE * file = fopen(filename.c_str(), "r");
149 Fatal("Couldn't open file \"%s\"", filename.c_str(), strerror(errno));
153 DocChunkTypes chunk_type;
155 while (ReadChunkHeader(file, chunk_type, chunk_size))
160 read = fread(&m_count, sizeof(m_count), 1, file);
162 Fatal("Failed to read number of objects!");
163 Debug("Number of objects: %u", ObjectCount());
166 Debug("Object types...");
167 LoadStructVector<ObjectType>(file, chunk_size/sizeof(ObjectType), m_objects.types);
170 Debug("Object bounds...");
171 LoadStructVector<Rect>(file, chunk_size/sizeof(Rect), m_objects.bounds);
174 Debug("Object data indices...");
175 LoadStructVector<unsigned>(file, chunk_size/sizeof(unsigned), m_objects.data_indices);
178 Debug("Bezier data...");
179 LoadStructVector<Bezier>(file, chunk_size/sizeof(Bezier), m_objects.beziers);
183 Debug("Successfully loaded %u objects from \"%s\"", ObjectCount(), filename.c_str());
184 #ifndef QUADTREE_DISABLED
185 if (m_quadtree.root_id == QUADTREE_EMPTY)
192 void Document::Add(ObjectType type, const Rect & bounds, unsigned data_index)
194 m_objects.types.push_back(type);
195 m_objects.bounds.push_back(bounds);
196 m_objects.data_indices.push_back(data_index);
197 ++m_count; // Why can't we just use the size of types or something?
200 unsigned Document::AddBezierData(const Bezier & bezier)
202 m_objects.beziers.push_back(bezier);
203 return m_objects.beziers.size()-1;
207 void Document::DebugDumpObjects()
209 Debug("Objects for Document %p are:", this);
210 for (unsigned id = 0; id < ObjectCount(); ++id)
212 Debug("%u. \tType: %u\tBounds: %s", id, m_objects.types[id], m_objects.bounds[id].Str().c_str());
216 bool Document::operator==(const Document & equ) const
218 return (ObjectCount() == equ.ObjectCount()
219 && memcmp(m_objects.bounds.data(), equ.m_objects.bounds.data(), ObjectCount() * sizeof(Rect)) == 0
220 && memcmp(m_objects.data_indices.data(), equ.m_objects.data_indices.data(), ObjectCount() * sizeof(unsigned)) == 0
221 && memcmp(m_objects.beziers.data(), equ.m_objects.beziers.data(), m_objects.beziers.size() * sizeof(Bezier)) == 0);
225 #include "../contrib/pugixml-1.4/src/pugixml.hpp"
226 #include "../contrib/pugixml-1.4/src/pugixml.cpp"
228 void Document::LoadSVG(const string & filename, const Rect & bounds)
230 using namespace pugi;
232 xml_document doc_xml;
233 ifstream input(filename.c_str(), ios_base::in);
234 xml_parse_result result = doc_xml.load(input);
237 Fatal("Couldn't load \"%s\" - %s", filename.c_str(), result.description());
239 Debug("Loaded XML - %s", result.description());
243 // Combine all SVG tags into one thing because lazy
244 for (xml_node svg : doc_xml.children("svg"))
246 Real width = svg.attribute("width").as_float() * bounds.w;
247 Real height = svg.attribute("width").as_float() * bounds.h;
252 const char * attrib_names[] = {"x", "y", "width", "height"};
253 for (pugi::xml_node rect : svg.children("rect"))
255 for (size_t i = 0; i < 4; ++i)
256 coords[i] = rect.attribute(attrib_names[i]).as_float();
258 bool outline = !(rect.attribute("fill"));
259 Add(outline?RECT_OUTLINE:RECT_FILLED, Rect(coords[0]/width + bounds.x, coords[1]/height + bounds.y, coords[2]/width, coords[3]/height),0);
260 Debug("Added rectangle");
264 for (pugi::xml_node circle : svg.children("circle"))
266 Real cx = circle.attribute("cx").as_float();
267 Real cy = circle.attribute("cy").as_float();
268 Real r = circle.attribute("r").as_float();
270 Real x = (cx - r)/width + bounds.x;
271 Real y = (cy - r)/height + bounds.y;
276 Add(CIRCLE_FILLED, rect,0);
277 Debug("Added Circle %s", rect.Str().c_str());
282 for (pugi::xml_node path : svg.children("path"))
285 string d = path.attribute("d").as_string();
286 Debug("Path data attribute is \"%s\"", d.c_str());
287 AddPathFromString(d, Rect(bounds.x,bounds.y,width,height));
298 // Behold my amazing tokenizing abilities
299 static string & GetToken(const string & d, string & token, unsigned & i)
302 while (i < d.size() && iswspace(d[i]))
309 if (d[i] == ',' || isalpha(d[i]) || iswspace(d[i]))
311 if (token.size() == 0 && !iswspace(d[i]))
319 Debug("Got token \"%s\"", token.c_str());
324 // Fear the wrath of the tokenizing svg data
325 // Seriously this isn't really very DOM-like at all is it?
326 void Document::AddPathFromString(const string & d, const Rect & bounds)
338 bool started = false;
339 while (i < d.size() && GetToken(d, token, i).size() > 0)
341 if (isalpha(token[0]))
352 Debug("Construct moveto command");
353 x[0] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
354 assert(GetToken(d,token,i) == ",");
355 y[0] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
362 Debug("mmoveto %f,%f", Float(x[0]),Float(y[0]));
365 else if (command == "c")
367 Debug("Construct curveto command");
368 x[0] = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.w;
369 assert(GetToken(d,token,i) == ",");
370 y[0] = strtod(GetToken(d,token,i).c_str(),NULL)/bounds.h;
372 x[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
373 assert(GetToken(d,token,i) == ",");
374 y[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
376 x[2] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
377 assert(GetToken(d,token,i) == ",");
378 y[2] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
380 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
381 Add(BEZIER,bounds,index);
384 Debug("[%u] curveto %f,%f %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]),Float(x[2]),Float(y[2]));
391 else if (command == "l")
393 Debug("Construct lineto command");
395 x[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.w;
396 assert(GetToken(d,token,i) == ",");
397 y[1] = strtod(GetToken(d,token,i).c_str(),NULL) / bounds.h;
402 Rect segment_bounds(x[0], y[0], x[2] - x[0], y[2] - y[0]);
404 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
405 Add(BEZIER,bounds,index);
407 Debug("[%u] lineto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
413 else if (command == "z")
415 Debug("Construct returnto command");
421 unsigned index = AddBezierData(Bezier(x[0],y[0],x[1],y[1],x[2],y[2]));
422 Add(BEZIER,bounds,index);
424 Debug("[%u] returnto %f,%f %f,%f", index, Float(x[0]),Float(y[0]),Float(x[1]),Float(y[1]));
432 Warn("Unrecognised command \"%s\", set to \"m\"", command.c_str());