File: xml_writer.cpp

package info (click to toggle)
embree 3.13.5%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 27,924 kB
  • sloc: cpp: 180,815; xml: 3,877; ansic: 2,957; python: 1,466; sh: 502; makefile: 229; csh: 42
file content (785 lines) | stat: -rw-r--r-- 29,045 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
// Copyright 2009-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0

#include "xml_writer.h"

namespace embree
{
  class XMLWriter
  {
  public:

    XMLWriter(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat);

  public:
    void tab();
    void open(std::string str);
    void open(std::string str, size_t id);
    void close(std::string str);
    
    void store(const char* name, const char* str);
    void store(const char* name, const float& v);
    void store(const char* name, const Vec3fa& v);

    void store_array_elt(const int& v);
    void store_array_elt(const Vec2f& v);
    void store_array_elt(const Vec3f& v);
    void store_array_elt(const Vec3fa& v);
    void store_array_elt(const Vec3ff& v);
    void store_array_elt(const SceneGraph::TriangleMeshNode::Triangle& v);
    void store_array_elt(const SceneGraph::QuadMeshNode::Quad& v);
    
    template<typename T> void store_array_text  (const char* name, const std::vector<T>& vec);
    template<typename T> void store_array_binary(const char* name, const std::vector<T>& vec);
    template<typename T> void store             (const char* name, const std::vector<T>& vec);

    void store_array_text  (const char* name, const avector<Vec3fa>& vec);
    void store_array_binary(const char* name, const avector<Vec3fa>& vec);
    void store             (const char* name, const avector<Vec3fa>& vec);

    void store_array_text  (const char* name, const avector<Vec3ff>& vec);
    void store_array_binary(const char* name, const avector<Vec3ff>& vec);
    void store             (const char* name, const avector<Vec3ff>& vec);
    
    void store_parm(const char* name, const float& v);
    void store_parm(const char* name, const Vec3fa& v);
    void store_parm(const char* name, const std::shared_ptr<Texture> tex);
    void store(const char* name, const AffineSpace3fa& space);

    void store(const SceneGraph::PointLight& light, ssize_t id);
    void store(const SceneGraph::SpotLight& light, ssize_t id);
    void store(const SceneGraph::DirectionalLight& light, ssize_t id);
    void store(const SceneGraph::DistantLight& light, ssize_t id);
    void store(const SceneGraph::AmbientLight& light, ssize_t id);
    void store(const SceneGraph::TriangleLight& light, ssize_t id);
    void store(const SceneGraph::QuadLight& light, ssize_t id);
    void store(Ref<SceneGraph::LightNode> light, ssize_t id);
    void store(Ref<SceneGraph::AnimatedLightNode> light, ssize_t id);
    
    void store(Ref<MatteMaterial> material, ssize_t id);
    void store(Ref<MirrorMaterial> material, ssize_t id);
    void store(Ref<ThinDielectricMaterial> material, ssize_t id);
    void store(Ref<OBJMaterial> material, ssize_t id);
    void store(Ref<MetalMaterial> material, ssize_t id);
    void store(Ref<VelvetMaterial> material, ssize_t id);
    void store(Ref<DielectricMaterial> material, ssize_t id);
    void store(Ref<MetallicPaintMaterial> material, ssize_t id);
    void store(Ref<HairMaterial> material, ssize_t id);
    void store(Ref<SceneGraph::MaterialNode> material);

    void store(Ref<SceneGraph::TriangleMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::QuadMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::SubdivMeshNode> mesh, ssize_t id);
    void store(Ref<SceneGraph::HairSetNode> hair, ssize_t id);

    void store(Ref<SceneGraph::PerspectiveCameraNode> camera, ssize_t id);
    void store(Ref<SceneGraph::AnimatedPerspectiveCameraNode> camera, ssize_t id);
    void store(Ref<SceneGraph::TransformNode> node, ssize_t id);
    void store(std::vector<Ref<SceneGraph::TransformNode>> nodes);
    void store(Ref<SceneGraph::GroupNode> group, ssize_t id);
    void store(Ref<SceneGraph::Node> node);

  private:
    std::fstream xml;         //!< .xml file for writing XML data
    std::fstream bin;         //!< .bin file for writing binary data

  private:
    size_t ident;
    size_t currentNodeID;
    std::map<Ref<SceneGraph::Node>, size_t> nodeMap;   
    std::map<std::shared_ptr<Texture>, size_t> textureMap; // FIXME: use Ref<Texture>
    bool embedTextures;
    bool referenceMaterials;
    bool binaryFormat;
  };

  //////////////////////////////////////////////////////////////////////////////
  //// Storing of objects to XML file
  //////////////////////////////////////////////////////////////////////////////

  void XMLWriter::tab()
  {
    for (size_t i=0; i<ident; i++) 
      xml << " ";
  }

  void XMLWriter::open(std::string str)
  {
    tab(); xml << "<" << str << ">" << std::endl;
    ident+=2;
  }

  void XMLWriter::open(std::string str, size_t id)
  {
    tab(); xml << "<" << str << " id=\"" << id << "\">" << std::endl;
    ident+=2;
  }

  void XMLWriter::close(std::string str)
  {
    assert(ident>=2);
    ident-=2;
    tab(); xml << "</" << str << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const char* str) {
    tab(); xml << "<" << name << ">\"" << str << "\"</" << name << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const float& v) {
    tab(); xml << "<" << name << ">" << v << "</" << name << ">" << std::endl;
  }

  void XMLWriter::store(const char* name, const Vec3fa& v) {
    tab(); xml << "<" << name << ">" << v.x << " " << v.y << " " << v.z << "</" << name << ">" << std::endl;
  }

  void XMLWriter::store_array_elt(const int& v) {
    xml << v << std::endl;
  }
  
  void XMLWriter::store_array_elt(const Vec2f& v) {
    xml << v.x << " " << v.y << std::endl;
  }
  
  void XMLWriter::store_array_elt(const Vec3f& v) {
    xml << v.x << " " << v.y << " " << v.z << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec3fa& v) {
    xml << v.x << " " << v.y << " " << v.z << std::endl;
  }

  void XMLWriter::store_array_elt(const Vec3ff& v) {
    xml << v.x << " " << v.y << " " << v.z << " " << v.w << std::endl;
  }

  void XMLWriter::store_array_elt(const SceneGraph::TriangleMeshNode::Triangle& v) {
    xml << v.v0 << " " << v.v1 << " " << v.v2 << std::endl;
  }

  void XMLWriter::store_array_elt(const SceneGraph::QuadMeshNode::Quad& v) {
    xml << v.v0 << " " << v.v1 << " " << v.v2 << " "  << v.v3 << std::endl;
  }

  template<typename T>
  void XMLWriter::store_array_text(const char* name, const std::vector<T>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }

  template<typename T>
  void XMLWriter::store_array_binary(const char* name, const std::vector<T>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    if (vec.size()) bin.write((char*)vec.data(),vec.size()*sizeof(T));
  }

  template<typename T>
  void XMLWriter::store(const char* name, const std::vector<T>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_array_text(const char* name, const avector<Vec3fa>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }
  
  void XMLWriter::store_array_binary(const char* name, const avector<Vec3fa>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    for (size_t i=0; i<vec.size(); i++) bin.write((char*)&vec[i],sizeof(Vec3f));
  }

  void XMLWriter::store(const char* name, const avector<Vec3fa>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_array_text(const char* name, const avector<Vec3ff>& vec)
  {
    open(name);
    for (size_t i=0; i<vec.size(); i++) {
      tab(); store_array_elt(vec[i]);
    }
    close(name);
  }
  
  void XMLWriter::store_array_binary(const char* name, const avector<Vec3ff>& vec)
  {
    std::streampos offset = bin.tellg();
    tab(); xml << "<" << name << " ofs=\"" << offset << "\" size=\"" << vec.size() << "\"/>" << std::endl;
    for (size_t i=0; i<vec.size(); i++) bin.write((char*)&vec[i],sizeof(Vec3ff));
  }

  void XMLWriter::store(const char* name, const avector<Vec3ff>& vec)
  {
    if (binaryFormat) store_array_binary(name,vec);
    else              store_array_text  (name,vec);
  }

  void XMLWriter::store_parm(const char* name, const float& v) {
    tab(); xml << "<float name=\"" << name << "\">" << v << "</float>" << std::endl;
  }

  void XMLWriter::store_parm(const char* name, const Vec3fa& v) {
    tab(); xml << "<float3 name=\"" << name << "\">" << v.x << " " << v.y << " " << v.z << "</float3>" << std::endl;
  }

  void XMLWriter::store_parm(const char* name, const std::shared_ptr<Texture> tex) 
  {
    if (tex == nullptr) return;

    if (textureMap.find(tex) != textureMap.end()) {
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << textureMap[tex] << "\"/>" << std::endl;
    } else if (embedTextures) {
      std::streampos offset = bin.tellg();
      bin.write((char*)tex->data,tex->width*tex->height*tex->bytesPerTexel);
      const size_t id = textureMap[tex] = currentNodeID++;
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << id << "\" ofs=\"" << offset 
                 << "\" width=\"" << tex->width << "\" height=\"" << tex->height 
                 << "\" format=\"" << Texture::format_to_string(tex->format) << "\"/>" << std::endl;
    }
    else {
      const size_t id = textureMap[tex] = currentNodeID++;
      tab(); xml << "<texture3d name=\"" << name << "\" id=\"" << id << "\" src=\"" << tex->fileName << "\"/>" << std::endl;
    }
  }

  void XMLWriter::store(const char* name, const AffineSpace3fa& space)
  {
    tab(); xml << "<" << name << ">" << std::endl;
    tab(); xml << "  " << space.l.vx.x << " " << space.l.vy.x << " " << space.l.vz.x << " " << space.p.x << std::endl;
    tab(); xml << "  " << space.l.vx.y << " " << space.l.vy.y << " " << space.l.vz.y << " " << space.p.y << std::endl;
    tab(); xml << "  " << space.l.vx.z << " " << space.l.vy.z << " " << space.l.vz.z << " " << space.p.z << std::endl;
    tab(); xml << "</" << name << ">" << std::endl;
  }
                  
  void XMLWriter::store(const SceneGraph::PointLight& light, ssize_t id)
  {
    open("PointLight",id);
    store("AffineSpace",AffineSpace3fa::translate(light.P));
    store("I",light.I);
    close("PointLight");
  }

  void XMLWriter::store(const SceneGraph::SpotLight& light, ssize_t id)
  {
    open("SpotLight",id);
    store("AffineSpace",AffineSpace3fa(frame(light.D),light.P));
    store("I",light.I);
    store("angleMin",light.angleMin);
    store("angleMax",light.angleMax);
    close("SpotLight");
  }

  void XMLWriter::store(const SceneGraph::DirectionalLight& light, ssize_t id)
  {
    open("DirectionalLight",id);
    store("AffineSpace",frame(light.D));
    store("E",light.E);
    close("DirectionalLight");
  }

  void XMLWriter::store(const SceneGraph::DistantLight& light, ssize_t id)
  {
    open("DistantLight",id);
    store("AffineSpace",frame(light.D));
    store("L",light.L);
    store("halfAngle",light.halfAngle);
    close("DistantLight");
  }

  void XMLWriter::store(const SceneGraph::AmbientLight& light, ssize_t id)
  {
    open("AmbientLight");
    store("L",light.L);
    close("AmbientLight");
  }

  void XMLWriter::store(const SceneGraph::TriangleLight& light, ssize_t id)
  {
    open("TriangleLight",id);
    const Vec3fa dx = light.v0-light.v2;
    const Vec3fa dy = light.v1-light.v2;
    const Vec3fa dz = cross(dx,dy);
    const Vec3fa p = light.v2;
    store("AffineSpace",AffineSpace3fa(dx,dy,dz,p));
    store("L",light.L);
    close("TriangleLight");
  }

  void XMLWriter::store(const SceneGraph::QuadLight& light, ssize_t id)
  {
    open("QuadLight",id);
    const Vec3fa dx = light.v3-light.v0;
    const Vec3fa dy = light.v1-light.v0;
    const Vec3fa dz = cross(dx,dy);
    const Vec3fa p = light.v2;
    store("AffineSpace",AffineSpace3fa(dx,dy,dz,p));
    store("L",light.L);
    close("QuadLight");
  }

  void XMLWriter::store(Ref<SceneGraph::LightNode> node, ssize_t id)
  {
    if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::AmbientLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::PointLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::DirectionalLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::SpotLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::DistantLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::TriangleLight>>())
      store(light->light,id);
    else if (auto light = node.dynamicCast<SceneGraph::LightNodeImpl<SceneGraph::QuadLight>>())
      store(light->light,id);
    else
      throw std::runtime_error("unsupported light");
  }

  void XMLWriter::store(Ref<SceneGraph::AnimatedLightNode> node, ssize_t id)
  {
    open(std::string("AnimatedLight ")+
         "time_range=\""+std::to_string(node->time_range.lower)+" "+std::to_string(node->time_range.upper)+"\"");
    
    for (size_t i=0; i<node->lights.size(); i++)
      store(node->lights[i].dynamicCast<SceneGraph::Node>());
    
    close("AnimatedLight");
  }

  void XMLWriter::store(Ref<MatteMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Matte");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MirrorMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Mirror");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<ThinDielectricMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","ThinDielectric");
    open("parameters");
    store_parm("transmission",material->transmission);
    store_parm("eta",material->eta);
    store_parm("thickness",material->thickness);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<OBJMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","OBJ");
    open("parameters");
    store_parm("d",material->d);
    store_parm("Kd",material->Kd);
    store_parm("Ks",material->Ks);
    store_parm("Ns",material->Ns);
    store_parm("map_d",material->_map_d);
    store_parm("map_Kd",material->_map_Kd);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MetalMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Metal");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    store_parm("eta",material->eta);
    store_parm("k",material->k);
    store_parm("roughness",material->roughness);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<VelvetMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Velvet");
    open("parameters");
    store_parm("reflectance",material->reflectance);
    store_parm("backScattering",material->backScattering);
    store_parm("horizonScatteringColor",material->horizonScatteringColor);
    store_parm("horizonScatteringFallOff",material->horizonScatteringFallOff);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<DielectricMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Dielectric");
    open("parameters");
    store_parm("transmissionOutside",material->transmissionOutside);
    store_parm("transmission",material->transmissionInside);
    store_parm("etaOutside",material->etaOutside);
    store_parm("etaInside",material->etaInside);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<MetallicPaintMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","MetallicPaint");
    open("parameters");
    store_parm("shadeColor",material->shadeColor);
    store_parm("glitterColor",material->glitterColor);
    store_parm("glitterSpread",material->glitterSpread);
    store_parm("eta",material->eta);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<HairMaterial> material, ssize_t id)
  {
    open("material",id);
    store("code","Hair");
    open("parameters");
    store_parm("Kr",material->Kr);
    store_parm("Kt",material->Kt);
    store_parm("nx",material->nx);
    store_parm("ny",material->ny);
    close("parameters");
    close("material");
  }

  void XMLWriter::store(Ref<SceneGraph::MaterialNode> mnode)
  {
    /* let materials reference by their name, allows separate bindings of materials */
    if (referenceMaterials) {
      tab(); xml << "<material id=\""+mnode->name+"\"/>" << std::endl;
      return;
    }
    
    Ref<SceneGraph::Node> node = mnode.dynamicCast<SceneGraph::Node>();
    if (nodeMap.find(node) != nodeMap.end()) {
      tab(); xml << "<material id=\"" << nodeMap[node] << "\"/>" << std::endl;
      return;
    }
    const ssize_t id = nodeMap[node] = currentNodeID++;

    if      (Ref<OBJMaterial> m = mnode.dynamicCast<OBJMaterial>()) store(m,id);
    else if (Ref<ThinDielectricMaterial> m = mnode.dynamicCast<ThinDielectricMaterial>()) store(m,id);
    else if (Ref<MetalMaterial> m = mnode.dynamicCast<MetalMaterial>()) store(m,id);
    else if (Ref<VelvetMaterial> m = mnode.dynamicCast<VelvetMaterial>()) store(m,id);
    else if (Ref<DielectricMaterial> m = mnode.dynamicCast<DielectricMaterial>()) store(m,id);
    else if (Ref<MetallicPaintMaterial> m = mnode.dynamicCast<MetallicPaintMaterial>()) store(m,id);
    else if (Ref<MatteMaterial> m = mnode.dynamicCast<MatteMaterial>()) store(m,id);
    else if (Ref<MirrorMaterial> m = mnode.dynamicCast<MirrorMaterial>()) store(m,id);
    else if (Ref<ReflectiveMetalMaterial> m = mnode.dynamicCast<ReflectiveMetalMaterial>()) store(m,id);
    else if (Ref<HairMaterial> m = mnode.dynamicCast<HairMaterial>()) store(m,id);
    else throw std::runtime_error("unsupported material");
  }

  void XMLWriter::store(Ref<SceneGraph::TriangleMeshNode> mesh, ssize_t id) 
  {
    open("TriangleMesh",id);
    store(mesh->material);
    
    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");
    
    store("texcoords",mesh->texcoords);
    store("triangles",mesh->triangles);
    close("TriangleMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::QuadMeshNode> mesh, ssize_t id) 
  {
    open("QuadMesh",id);
    store(mesh->material);
    
    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");
    
    store("texcoords",mesh->texcoords);
    store("indices",mesh->quads);
    close("QuadMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::SubdivMeshNode> mesh, ssize_t id)
  {
    open("SubdivisionMesh",id);
    store(mesh->material);
    
    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");

    if (mesh->numTimeSteps() != 1) open("animated_normals");
    for (const auto& p : mesh->normals) store("normals",p);
    if (mesh->numTimeSteps() != 1) close("animated_normals");

    store("texcoords",mesh->texcoords);
    store("position_indices",mesh->position_indices);
    store("normal_indices",mesh->normal_indices);
    store("texcoord_indices",mesh->texcoord_indices);
    store("faces",mesh->verticesPerFace);
    store("holes",mesh->holes);
    store("edge_creases",mesh->edge_creases);
    store("edge_crease_weights",mesh->edge_crease_weights);
    store("vertex_creases",mesh->vertex_creases);
    store("vertex_crease_weights",mesh->vertex_crease_weights);
    close("SubdivisionMesh");
  }

  void XMLWriter::store(Ref<SceneGraph::HairSetNode> mesh, ssize_t id)
  {
    std::string str_type = "";
    std::string str_subtype = "";

    switch (mesh->type) {
    case RTC_GEOMETRY_TYPE_FLAT_LINEAR_CURVE:
      str_type = "linear";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_ROUND_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "round";
      break;

    case RTC_GEOMETRY_TYPE_FLAT_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BEZIER_CURVE:
      str_type = "bezier";
      str_subtype = "oriented";
      break;

    case RTC_GEOMETRY_TYPE_ROUND_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "round";
      break;

    case RTC_GEOMETRY_TYPE_FLAT_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "flat";
      break;

    case RTC_GEOMETRY_TYPE_NORMAL_ORIENTED_BSPLINE_CURVE:
      str_type = "bspline";
      str_subtype = "oriented";
      break;

    default:
      throw std::runtime_error("invalid curve type");
    }

    std::vector<int> indices(mesh->hairs.size());
    std::vector<int> hairid(mesh->hairs.size());
    for (size_t i=0; i<mesh->hairs.size(); i++) {
      indices[i] = mesh->hairs[i].vertex;
      hairid[i] = mesh->hairs[i].id;
    }
    
    open("Curves type=\""+str_subtype+"\" basis=\""+str_type+"\"",id);
    store(mesh->material);
    if (mesh->numTimeSteps() != 1) open("animated_positions");
    for (const auto& p : mesh->positions) store("positions",p);
    if (mesh->numTimeSteps() != 1) close("animated_positions");
    if (mesh->normals.size()) {
      if (mesh->numTimeSteps() != 1) open("animated_normals");
      for (const auto& p : mesh->normals) store("normals",p);
      if (mesh->numTimeSteps() != 1) close("animated_normals");
    }
    store("indices",indices);
    store("hairid",hairid);
    close("Curves");
  }

  void XMLWriter::store(Ref<SceneGraph::PerspectiveCameraNode> camera, ssize_t id)
  {
    tab(); 
    xml << "<PerspectiveCamera " <<
      "id=\"" << id << "\" " << 
      "name=\"" << camera->name << "\" " <<
      "from=\"" << camera->data.from.x << " " << camera->data.from.y << " " << camera->data.from.z << "\" " <<
      "to=\""   << camera->data.to.x   << " " << camera->data.to.y   << " " << camera->data.to.z << "\" " <<
      "up=\""   << camera->data.up.x   << " " << camera->data.up.y   << " " << camera->data.up.z << "\" " <<
      "fov=\""  << camera->data.fov << "\" " << "/>" << std::endl;
  }

  void XMLWriter::store(Ref<SceneGraph::AnimatedPerspectiveCameraNode> camera, ssize_t id)
  {
    open(std::string("AnimatedPerspectiveCamera ")+
         "name=\"" + camera->name + "\" "
         "time_range=\""+std::to_string(camera->time_range.lower)+" "+std::to_string(camera->time_range.upper)+"\"");
    
    for (size_t i=0; i<camera->size(); i++)
      store(camera->cameras[i].dynamicCast<SceneGraph::Node>());
    
    close("AnimatedPerspectiveCamera");
  }

  void XMLWriter::store(Ref<SceneGraph::TransformNode> node, ssize_t id)
  {
    if (node->spaces.size() == 1)
    {
      open("Transform",id);
      store("AffineSpace",node->spaces[0]);
      store(node->child);
      close("Transform");
    }
    else 
    {
      open("TransformAnimation",id);
      for (size_t i=0; i<node->spaces.size(); i++)
        store("AffineSpace",node->spaces[i]);
      store(node->child);
      close("TransformAnimation");
    }
  }

  void XMLWriter::store(std::vector<Ref<SceneGraph::TransformNode>> nodes)
  {
    if (nodes.size() == 0)
      return;

    if (nodes.size() == 1) {
      store(nodes[0].dynamicCast<SceneGraph::Node>());
      return;
    }
    
    open("MultiTransform");
    std::streampos offset = bin.tellg();
    tab(); xml << "<AffineSpace3f ofs=\"" << offset << "\" size=\"" << nodes.size() << "\"/>" << std::endl;
    for (size_t i=0; i<nodes.size(); i++) {
      assert(nodes[i]->spaces.size() == 1);
      assert(nodes[i]->child == nodes[0]->child);
      bin.write((char*)&nodes[i]->spaces[0].l.vx,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].l.vy,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].l.vz,sizeof(Vec3f));
      bin.write((char*)&nodes[i]->spaces[0].p,sizeof(Vec3f));
    }
    store(nodes[0]->child);
    close("MultiTransform");
  }

  void XMLWriter::store(Ref<SceneGraph::GroupNode> group, ssize_t id)
  {
    open("Group",id);

    std::map<Ref<SceneGraph::Node>,std::vector<Ref<SceneGraph::TransformNode>>> object_to_transform_map;
    for (size_t i=0; i<group->children.size(); i++)
    {
      /* compress transformation of the same object into MultiTransform nodes if possible */
      if (Ref<SceneGraph::TransformNode> xfmNode = group->children[i].dynamicCast<SceneGraph::TransformNode>())
      {
        /* we can only compress non-animated transform nodes and only ones that are referenced once */
        if (xfmNode->spaces.size() == 1 && xfmNode->indegree == 1) 
        {
          Ref<SceneGraph::Node> child = xfmNode->child;
          if (object_to_transform_map.find(child) == object_to_transform_map.end()) {
            object_to_transform_map[child] = std::vector<Ref<SceneGraph::TransformNode>>();
          }
          object_to_transform_map[child].push_back(xfmNode);
          continue;
        }
      }
      store(group->children[i]);
    }
    
    /* store all compressed transform nodes */
    for (auto i : object_to_transform_map)
      store(i.second);

    close("Group");
  }

  void XMLWriter::store(Ref<SceneGraph::Node> node)
  {
    if (nodeMap.find(node) != nodeMap.end()) {
      tab(); xml << "<ref id=\"" << nodeMap[node] << "\"/>" << std::endl; return;
    }
    
    const ssize_t id = nodeMap[node] = currentNodeID++;
    if (node->fileName != "") {
      tab(); xml << "<extern id=\"" << id << "\" src=\"" << node->fileName << "\"/>" << std::endl; return;
    }

    if      (Ref<SceneGraph::AnimatedLightNode> cnode = node.dynamicCast<SceneGraph::AnimatedLightNode>()) store(cnode,id);
    else if (Ref<SceneGraph::LightNode> cnode = node.dynamicCast<SceneGraph::LightNode>()) store(cnode,id);
    //else if (Ref<SceneGraph::MaterialNode> cnode = node.dynamicCast<SceneGraph::MaterialNode>()) store(cnode,id);
    else if (Ref<SceneGraph::TriangleMeshNode> cnode = node.dynamicCast<SceneGraph::TriangleMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::QuadMeshNode> cnode = node.dynamicCast<SceneGraph::QuadMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::SubdivMeshNode> cnode = node.dynamicCast<SceneGraph::SubdivMeshNode>()) store(cnode,id);
    else if (Ref<SceneGraph::HairSetNode> cnode = node.dynamicCast<SceneGraph::HairSetNode>()) store(cnode,id);
    else if (Ref<SceneGraph::AnimatedPerspectiveCameraNode> cnode = node.dynamicCast<SceneGraph::AnimatedPerspectiveCameraNode>()) store(cnode,id);
    else if (Ref<SceneGraph::PerspectiveCameraNode> cnode = node.dynamicCast<SceneGraph::PerspectiveCameraNode>()) store(cnode,id);
    else if (Ref<SceneGraph::TransformNode> cnode = node.dynamicCast<SceneGraph::TransformNode>()) store(cnode,id);
    else if (Ref<SceneGraph::GroupNode> cnode = node.dynamicCast<SceneGraph::GroupNode>()) store(cnode,id);
    else throw std::runtime_error("unknown node type");
  }
 
  XMLWriter::XMLWriter(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat) 
    : ident(0), currentNodeID(0), embedTextures(embedTextures), referenceMaterials(referenceMaterials), binaryFormat(binaryFormat)
  {
    xml.exceptions (std::fstream::failbit | std::fstream::badbit);
    xml.open (fileName, std::fstream::out);

    if (binaryFormat)
    {
      const FileName binFileName = fileName.addExt(".bin");
      bin.exceptions (std::fstream::failbit | std::fstream::badbit);
      bin.open (binFileName, std::fstream::out | std::fstream::binary);
    }

    xml << "<?xml version=\"1.0\"?>" << std::endl;
    root->calculateInDegree();
    open("scene");
    store(root);
    close("scene");
    root->resetInDegree();
  }

  void SceneGraph::storeXML(Ref<SceneGraph::Node> root, const FileName& fileName, bool embedTextures, bool referenceMaterials, bool binaryFormat) {
    XMLWriter(root,fileName,embedTextures,referenceMaterials,binaryFormat);
  }
}