summaryrefslogtreecommitdiff
path: root/Build/source/utils/asymptote/prc/oPRCFile.cc
blob: bef8191d70335349fb4786fe74a52fafb576c5c6 (plain)
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
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
/************
*
*   This file is part of a tool for producing 3D content in the PRC format.
*   Copyright (C) 2008  Orest Shardt <shardtor (at) gmail dot com>
*   with enhancements contributed by Michail Vidiassov.
*
*   This program is free software: you can redistribute it and/or modify
*   it under the terms of the GNU Lesser General Public License as published by
*   the Free Software Foundation, either version 3 of the License, or
*   (at your option) any later version.
*
*   This program is distributed in the hope that it will be useful,
*   but WITHOUT ANY WARRANTY; without even the implied warranty of
*   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*   GNU Lesser General Public License for more details.
*
*   You should have received a copy of the GNU Lesser General Public License
*   along with this program.  If not, see <http://www.gnu.org/licenses/>.
*
*************/

#include "oPRCFile.h"
#include <time.h>
#include <sstream>
#include <iostream>
#include <fstream>
#include <string>
#include <zlib.h>
#include <string.h>

#define WriteUnsignedInteger( value ) out << (uint32_t)(value);
#define WriteInteger( value ) out << (int32_t)(value);
#define SerializeContentPRCBase write(out);
#define SerializeRgbColor( value ) (value).serializeRgbColor(out);
#define SerializePicture( value ) (value).serializePicture(out);
#define SerializeTextureDefinition( value ) (value)->serializeTextureDefinition(out);
#define SerializeMarkup( value ) (value)->serializeMarkup(out);
#define SerializeAnnotationEntity( value ) (value)->serializeAnnotationEntity(out);
#define SerializeFontKeysSameFont( value ) (value).serializeFontKeysSameFont(out);
#define SerializeMaterial( value ) (value)->serializeMaterial(out);

#define SerializeCategory1LineStyle( value ) (value)->serializeCategory1LineStyle(out);
#define SerializeCoordinateSystem( value ) (value)->serializeCoordinateSystem(out);
#define SerializeRepresentationItem( value ) (value)->serializeRepresentationItem(out);
#define SerializePartDefinition( value ) (value)->serializePartDefinition(out);
#define SerializeProductOccurrence( value ) (value)->serializeProductOccurrence(out);
#define SerializeContextAndBodies( value ) (fileStructure->value)->serializeContextAndBodies(out);
#define SerializeGeometrySummary( value ) (fileStructure->value)->serializeGeometrySummary(out);
#define SerializeContextGraphics( value ) (fileStructure->value)->serializeContextGraphics(out);

using std::string;
using namespace std;

void PRCCompressedSection::write(ostream &out)
{
  if(prepared)
    out.write((char*)data,getSize());
}

void PRCCompressedSection::prepare()
{
  writeData();
  compress();
  prepared = true;
}

uint32_t PRCCompressedSection::getSize()
{
  if(!prepared)
    return m1;
  else
    return out.getSize();
}

void PRCGlobalsSection::writeData()
{
  // even though this is technically not part of this section,
  // it is handled here for convenience
  out << (uint32_t)(0); // number of schemas
  uint32_t i=0; // universal index for PRC standard compatibility
  out << (uint32_t)PRC_TYPE_ASM_FileStructureGlobals;

  PRCSingleAttribute sa((int32_t)PRCVersion);
  PRCAttribute a("__PRC_RESERVED_ATTRIBUTE_PRCInternalVersion");
  a.addKey(sa);
  ContentPRCBase cb;
  cb.addAttribute(a);
  cb.serializeContentPRCBase(out);
  out << numberOfReferencedFileStructures; // no referencing of file structures
  out << tessellationChordHeightRatio;
  out << tessellationAngleDegrees;
  out << defaultFontFamilyName; // markup serialization helper

  const uint32_t number_of_fonts = font_keys_of_font.size();
  WriteUnsignedInteger (number_of_fonts)
  for (i=0;i<number_of_fonts;i++)
  {
    SerializeFontKeysSameFont (font_keys_of_font[i])
  }

  
  const uint32_t number_of_colors = colors.size();
  WriteUnsignedInteger (number_of_colors)
  for (i=0;i<number_of_colors;i++)
      SerializeRgbColor (colors[i])

  const uint32_t number_of_pictures = pictures.size();
  WriteUnsignedInteger (number_of_pictures)
  for (i=0;i<number_of_pictures;i++)
     SerializePicture (pictures[i])

  const uint32_t number_of_texture_definitions = texture_definitions.size();
  WriteUnsignedInteger (number_of_texture_definitions)
  for (i=0;i<number_of_texture_definitions;i++)
     SerializeTextureDefinition (texture_definitions[i])

  const uint32_t number_of_materials = materials.size();
  WriteUnsignedInteger (number_of_materials)
  for (i=0;i<number_of_materials;i++)
     SerializeMaterial (materials[i])

  out << (uint32_t)1 // number of line patterns hard coded for now
      << (uint32_t)PRC_TYPE_GRAPH_LinePattern;
  ContentPRCBase("",true,makeCADID(),0,makePRCID()).serializeContentPRCBase(out);
  out << (uint32_t)0 // number of lengths
      << 0.0 // phase
      << false; // is real length

  const uint32_t number_of_styles = styles.size();
  WriteUnsignedInteger (number_of_styles)
  for (i=0;i<number_of_styles;i++)
     SerializeCategory1LineStyle (styles[i])

  out << numberOfFillPatterns; 

  const uint32_t number_of_reference_coordinate_systems = reference_coordinate_systems.size();
  WriteUnsignedInteger (number_of_reference_coordinate_systems)
  for (i=0;i<number_of_reference_coordinate_systems;i++)
     SerializeCoordinateSystem (reference_coordinate_systems[i])

  userData.write(out);
}

void PRCTreeSection::writeData()
{
  out << (uint32_t)(PRC_TYPE_ASM_FileStructureTree);

  EMPTY_CONTENTPRCBASE.serializeContentPRCBase(out);

  uint32_t number_of_part_definitions = part_definitions.size();
  WriteUnsignedInteger (number_of_part_definitions) 
  for (uint32_t i=0;i<number_of_part_definitions;i++)
    SerializePartDefinition (part_definitions[i]) 
	
  uint32_t number_of_product_occurrences = product_occurrences.size();
  WriteUnsignedInteger (number_of_product_occurrences) 
  for (uint32_t i=0;i<number_of_product_occurrences;i++)
  {
    product_occurrences[i]->unit_information.unit_from_CAD_file = true;
    product_occurrences[i]->unit_information.unit = unit;
    SerializeProductOccurrence (product_occurrences[i]) 
  }

  // File Structure Internal Data
  out << (uint32_t)(PRC_TYPE_ASM_FileStructure);
  EMPTY_CONTENTPRCBASE.serializeContentPRCBase(out);
  out << makePRCID(); // next available index
  out << (uint32_t)1; // product occurrence index

  UserData(0,0).write(out);
}

void PRCTessellationSection::writeData()
{
  out << (uint32_t)(PRC_TYPE_ASM_FileStructureTessellation);

  EMPTY_CONTENTPRCBASE.serializeContentPRCBase(out);
  const uint32_t number_of_tessellations = tessellations.size();
  WriteUnsignedInteger (number_of_tessellations) 
  for (uint32_t i=0;i<number_of_tessellations;i++)
    tessellations[i]->serializeBaseTessData(out);
  UserData(0,0).write(out); // no user data
}

void PRCGeometrySection::writeData()
{
   WriteUnsignedInteger (PRC_TYPE_ASM_FileStructureGeometry)

  EMPTY_CONTENTPRCBASE.serializeContentPRCBase(out);
   const uint32_t number_of_contexts = fileStructure->contexts.size();
   WriteUnsignedInteger (number_of_contexts)
   for (uint32_t i=0;i<number_of_contexts;i++)
      SerializeContextAndBodies (contexts[i])

  UserData(0,0).write(out);
}

void PRCExtraGeometrySection::writeData()
{
   WriteUnsignedInteger (PRC_TYPE_ASM_FileStructureExtraGeometry)

  EMPTY_CONTENTPRCBASE.serializeContentPRCBase(out);
   const uint32_t number_of_contexts = fileStructure->contexts.size();
   WriteUnsignedInteger (number_of_contexts)
   for (uint32_t i=0;i<number_of_contexts;i++) 
   {
      SerializeGeometrySummary (contexts[i]) 
      SerializeContextGraphics (contexts[i]) 
   }

  UserData(0,0).write(out);
}

void PRCModelFile::writeData()
{
  // even though this is technically not part of this section,
  // it is handled here for convenience
  out << (uint32_t)(0); // number of schemas
  out << (uint32_t)(PRC_TYPE_ASM_ModelFile);

  PRCSingleAttribute sa((int32_t)PRCVersion);
  PRCAttribute a("__PRC_RESERVED_ATTRIBUTE_PRCInternalVersion");
  a.addKey(sa);
  ContentPRCBase cb("PRC file");
  cb.addAttribute(a);
  cb.serializeContentPRCBase(out);

  writeUnit(out,true,unit); // unit is specified, and happens to come from a CAD file

  out << (uint32_t)1; // 1 product occurrence
  //UUID
  out << parent->fileStructures[0]->header.fileStructureUUID[0]
      << parent->fileStructures[0]->header.fileStructureUUID[1]
      << parent->fileStructures[0]->header.fileStructureUUID[2]
      << parent->fileStructures[0]->header.fileStructureUUID[3];
  // index+1
  out << (uint32_t)parent->fileStructures[0]->tree.product_occurrences.size();
  // active
  out << true;
  out << (uint32_t)0; // index in model file

  UserData(0,0).write(out);
}

void makeFileUUID(uint32_t *UUID)
{
  // make a UUID
  static uint32_t count = 0;
  ++count;
  // the minimum requirement on UUIDs is that all must be unique in the file
  UUID[0] = 0x33595341; // some constant
  UUID[1] = time(NULL); // the time
  UUID[2] = count;
  UUID[3] = 0xa5a55a5a; // Something random, not seeded by the time, would be nice. But for now, a constant
  // maybe add something else to make it more unique
  // so multiple files can be combined
  // a hash of some data perhaps?
}

void makeAppUUID(uint32_t *UUID)
{
  UUID[0] = UUID[1] = UUID[2] = UUID[3] = 0;
}

void writeUINT32_T(ostream &out, uint32_t data)
{
#ifdef WORDS_BIGENDIAN
  out.write(((char*)&data)+3,1);
  out.write(((char*)&data)+2,1);
  out.write(((char*)&data)+1,1);
  out.write(((char*)&data)+0,1);
#else
  out.write(((char*)&data)+0,1);
  out.write(((char*)&data)+1,1);
  out.write(((char*)&data)+2,1);
  out.write(((char*)&data)+3,1);
#endif
}

void PRCUncompressedFile::write(ostream &out)
{
  if(data!=NULL)
  {
    writeUINT32_T(out,file_size);
    out.write((char*)data,file_size);
  }
}

uint32_t PRCUncompressedFile::getSize()
{
  return sizeof(file_size)+file_size;
}


void PRCStartHeader::write(ostream &out)
{
  out.write("PRC",3);
  writeUINT32_T(out,minimal_version_for_read);
  writeUINT32_T(out,authoring_version);
  writeUINT32_T(out,fileStructureUUID[0]);
  writeUINT32_T(out,fileStructureUUID[1]);
  writeUINT32_T(out,fileStructureUUID[2]);
  writeUINT32_T(out,fileStructureUUID[3]);

  writeUINT32_T(out,applicationUUID[0]);
  writeUINT32_T(out,applicationUUID[1]);
  writeUINT32_T(out,applicationUUID[2]);
  writeUINT32_T(out,applicationUUID[3]);
}

uint32_t PRCStartHeader::getSize()
{
  return 3+(2+2*4)*sizeof(uint32_t);
}


void PRCFileStructure::write(ostream &out)
{
  header.write(out);
  uint32_t number_of_uncompressed_files = uncompressedFiles.size();
  writeUINT32_T(out,number_of_uncompressed_files);
  for(list<PRCUncompressedFile>::iterator i = uncompressedFiles.begin(); i != uncompressedFiles.end(); i++)
    i->write(out);
  globals.write(out);
  tree.write(out);
  tessellations.write(out);
  geometry.write(out);
  extraGeometry.write(out);
}

void PRCFileStructure::prepare()
{
  globals.prepare();
  resetGraphicsAndName();

  tree.prepare();
  resetGraphicsAndName();

  tessellations.prepare();
  resetGraphicsAndName();

  geometry.prepare();
  resetGraphicsAndName();

  extraGeometry.prepare();
  resetGraphicsAndName();
}

uint32_t PRCFileStructure::getSize()
{
  uint32_t size = 0;
  size += header.getSize();
  size += sizeof(uint32_t);
  for(list<PRCUncompressedFile>::iterator i = uncompressedFiles.begin(); i != uncompressedFiles.end(); i++)
    size += i->getSize();
  size += globals.getSize();
  size += tree.getSize();
  size += tessellations.getSize();
  size += geometry.getSize();
  size += extraGeometry.getSize();
  return size;
}


void PRCFileStructureInformation::write(ostream &out)
{
  writeUINT32_T(out,UUID[0]);
  writeUINT32_T(out,UUID[1]);
  writeUINT32_T(out,UUID[2]);
  writeUINT32_T(out,UUID[3]);

  writeUINT32_T(out,reserved);
  writeUINT32_T(out,number_of_offsets);
  for(uint32_t i = 0; i < number_of_offsets; ++i)
  {
    writeUINT32_T(out,offsets[i]);
  }
}

uint32_t PRCFileStructureInformation::getSize()
{
  return (4+2+number_of_offsets)*sizeof(uint32_t);
}

void PRCHeader::write(ostream &out)
{
  startHeader.write(out);
  writeUINT32_T(out,number_of_file_structures);
  for(uint32_t i = 0; i < number_of_file_structures; ++i)
  {
    fileStructureInformation[i].write(out);
  }
  writeUINT32_T(out,model_file_offset);
  writeUINT32_T(out,file_size);
  uint32_t number_of_uncompressed_files = uncompressedFiles.size();
  writeUINT32_T(out,number_of_uncompressed_files);
  for(list<PRCUncompressedFile>::iterator i = uncompressedFiles.begin(); i != uncompressedFiles.end(); i++)
    i->write(out);
}

uint32_t PRCHeader::getSize()
{
  uint32_t size = startHeader.getSize() + sizeof(uint32_t);
  for(uint32_t i = 0; i < number_of_file_structures; ++i)
    size += fileStructureInformation[i].getSize();
  size += 3*sizeof(uint32_t);
  for(list<PRCUncompressedFile>::iterator i = uncompressedFiles.begin(); i != uncompressedFiles.end(); i++)
    size += i->getSize();
  return size;
}

void oPRCFile::doGroup(PRCgroup& group, PRCPartDefinition *parent_part_definition, PRCProductOccurrence *parent_product_occurrence)
{
    const string& name = group.name;

    PRCPartDefinition *part_definition = new PRCPartDefinition;

    if(group.options.tess)
    {
      if(!group.lines.empty())
      {
        bool same_color = true;
        const PRCRgbColor &color = group.lines.front().color;
        for(PRCtesslineList::const_iterator lit=group.lines.begin(); lit!=group.lines.end(); lit++)
          if(color!=lit->color)
          {
            same_color = false;
            break;
          }
        map<PRCVector3d,uint32_t> points;
        PRC3DWireTess *tess = new PRC3DWireTess();
        if(!same_color)
        {
          tess->is_segment_color = true;
          tess->is_rgba = false;
        }
        for(PRCtesslineList::const_iterator lit=group.lines.begin(); lit!=group.lines.end(); lit++)
        {
          tess->wire_indexes.push_back(lit->point.size());
          for(uint32_t i=0; i<lit->point.size(); i++)
          {
            map<PRCVector3d,uint32_t>::iterator pPoint = points.find(lit->point[i]);
            if(pPoint!=points.end())
              tess->wire_indexes.push_back(pPoint->second);
            else
            {
              uint32_t point_index = m1;
              points.insert(make_pair(lit->point[i],(point_index = tess->coordinates.size())));
              tess->wire_indexes.push_back(point_index);
              tess->coordinates.push_back(lit->point[i].x);
              tess->coordinates.push_back(lit->point[i].y);
              tess->coordinates.push_back(lit->point[i].z);
            }
            if(!same_color && i>0)
            {
              tess->rgba_vertices.push_back((uint8_t)(255*lit->color.red));
              tess->rgba_vertices.push_back((uint8_t)(255*lit->color.green));
              tess->rgba_vertices.push_back((uint8_t)(255*lit->color.blue));
            }
          }
        }
        const uint32_t tess_index = add3DWireTess(tess);
        PRCPolyWire *polyWire = new PRCPolyWire();
        polyWire->index_tessellation = tess_index;
        if(same_color)
          polyWire->index_of_line_style = addColour(RGBAColour(color.red,color.green,color.blue));
        part_definition->addPolyWire(polyWire);
      }
//    make rectangles pairs of triangles in a tesselation
      if(!group.rectangles.empty())
      {
        bool same_color = true;
        const uint32_t &style = group.rectangles.front().style;
        for(PRCtessrectangleList::const_iterator rit=group.rectangles.begin(); rit!=group.rectangles.end(); rit++)
          if(style!=rit->style)
          {
            same_color = false;
            break;
          }
        map<PRCVector3d,uint32_t> points;
        PRC3DTess *tess = new PRC3DTess();
        PRCTessFace *tessFace = new PRCTessFace();
        tessFace->used_entities_flag=PRC_FACETESSDATA_Triangle;
        uint32_t triangles = 0;
        for(PRCtessrectangleList::const_iterator rit=group.rectangles.begin(); rit!=group.rectangles.end(); rit++)
        {
          const bool degenerate = (rit->vertices[0]==rit->vertices[1]);
          uint32_t vertex_indices[4];
          for(size_t i = (degenerate?1:0); i < 4; ++i)
          {
            map<PRCVector3d,uint32_t>::iterator pPoint = points.find(rit->vertices[i]);
            if(pPoint!=points.end())
              vertex_indices[i] =  pPoint->second;
            else
            {
              points.insert(make_pair(rit->vertices[i],(vertex_indices[i] = tess->coordinates.size())));
              tess->coordinates.push_back(rit->vertices[i].x);
              tess->coordinates.push_back(rit->vertices[i].y);
              tess->coordinates.push_back(rit->vertices[i].z);
            }
          }
          if(degenerate)
          {
            tess->triangulated_index.push_back(vertex_indices[1]);
            tess->triangulated_index.push_back(vertex_indices[2]);
            tess->triangulated_index.push_back(vertex_indices[3]);
            triangles++;
            if(!same_color)
              tessFace->line_attributes.push_back(rit->style);
          }
          else
          {
            tess->triangulated_index.push_back(vertex_indices[0]);
            tess->triangulated_index.push_back(vertex_indices[2]);
            tess->triangulated_index.push_back(vertex_indices[3]);
            triangles++;
            if(!same_color)
              tessFace->line_attributes.push_back(rit->style);
            tess->triangulated_index.push_back(vertex_indices[3]);
            tess->triangulated_index.push_back(vertex_indices[1]);
            tess->triangulated_index.push_back(vertex_indices[0]);
            triangles++;
            if(!same_color)
              tessFace->line_attributes.push_back(rit->style);
          }
        }
        tessFace->sizes_triangulated.push_back(triangles);
        tess->addTessFace(tessFace);
        const uint32_t tess_index = add3DTess(tess);
        PRCPolyBrepModel *polyBrepModel = new PRCPolyBrepModel();
        polyBrepModel->index_tessellation = tess_index;
        polyBrepModel->is_closed = group.options.closed;
        if(same_color)
          polyBrepModel->index_of_line_style = style;
        part_definition->addPolyBrepModel(polyBrepModel);
      }
    }
   
    if(!group.points.empty())
    {
      for(PRCpointsetMap::const_iterator pit=group.points.begin(); pit!=group.points.end(); pit++)
      {
        PRCPointSet *pointset = new PRCPointSet();
        pointset->index_of_line_style = pit->first;
        pointset->point = pit->second;
        part_definition->addPointSet(pointset);
      }
    }

    if(!group.wires.empty())
    {
      PRCTopoContext *wireContext = NULL;
      uint32_t context_index = getTopoContext(wireContext);
      for(PRCwireList::iterator wit=group.wires.begin(); wit!=group.wires.end(); wit++)
      {
        PRCWireEdge *wireEdge = new PRCWireEdge;
        wireEdge->curve_3d = wit->curve;
        PRCSingleWireBody *wireBody = new PRCSingleWireBody;
        wireBody->setWireEdge(wireEdge);
        const uint32_t wire_body_index = wireContext->addSingleWireBody(wireBody);
        PRCWire *wire = new PRCWire();
        wire->index_of_line_style = wit->style;
        wire->context_id = context_index;
        wire->body_id = wire_body_index;
        if(wit->transform)
            wire->index_local_coordinate_system = addTransform(wit->transform);
        part_definition->addWire(wire);
      }
    }

    PRCfaceList &faces = group.faces;
    if(!faces.empty())
    {
      bool same_color = true;
      uint32_t style = faces.front().style;
      for(PRCfaceList::const_iterator fit=faces.begin(); fit!=faces.end(); fit++)
        if(style!=fit->style)
        {
          same_color = false;
          break;
        }
      PRCTopoContext *context = NULL;
      const uint32_t context_index = getTopoContext(context);
      context->granularity = group.options.granularity;
   // Acrobat 9 also does the following:
   // context->tolerance = group.options.granularity;
   // context->have_smallest_face_thickness = true;
   // context->smallest_thickness = group.options.granularity;
      PRCShell *shell = new PRCShell;

      for(PRCfaceList::iterator fit=faces.begin(); fit!=faces.end(); fit++)
      {
        if(fit->transform || group.options.do_break || 
           (fit->transparent && !group.options.no_break))
        {
          PRCShell *shell = new PRCShell;
          shell->addFace(fit->face);
          PRCConnex *connex = new PRCConnex;
          connex->addShell(shell);
          PRCBrepData *body = new PRCBrepData;
          body->addConnex(connex);
          const uint32_t body_index = context->addBrepData(body);
      
          PRCBrepModel *brepmodel = new PRCBrepModel();
          brepmodel->index_of_line_style = fit->style;
          brepmodel->context_id = context_index;
          brepmodel->body_id = body_index;
          brepmodel->is_closed = group.options.closed;

          brepmodel->index_local_coordinate_system = addTransform(fit->transform);

          part_definition->addBrepModel(brepmodel);
        }
        else
        {
          if(!same_color)
            fit->face->index_of_line_style = fit->style;
          shell->addFace(fit->face);
        }
      }
      if(shell->face.empty())
      {
        delete shell;
      }
      else
      {
        PRCConnex *connex = new PRCConnex;
        connex->addShell(shell);
        PRCBrepData *body = new PRCBrepData;
        body->addConnex(connex);
        const uint32_t body_index = context->addBrepData(body);
        PRCBrepModel *brepmodel = new PRCBrepModel();
        if(same_color)
          brepmodel->index_of_line_style = style;
        brepmodel->context_id = context_index;
        brepmodel->body_id = body_index;
        brepmodel->is_closed = group.options.closed;
        part_definition->addBrepModel(brepmodel);
      }
    }

    PRCcompfaceList &compfaces = group.compfaces;
    if(!compfaces.empty())
    {
      bool same_color = true;
      uint32_t style = compfaces.front().style;
      for(PRCcompfaceList::const_iterator fit=compfaces.begin(); fit!=compfaces.end(); fit++)
        if(style!=fit->style)
        {
          same_color = false;
          break;
        }
      PRCTopoContext *context = NULL;
      const uint32_t context_index = getTopoContext(context);
      PRCCompressedBrepData *body = new PRCCompressedBrepData;
      
      body->serial_tolerance=group.options.compression;
      body->brep_data_compressed_tolerance=0.1*group.options.compression;

      for(PRCcompfaceList::const_iterator fit=compfaces.begin(); fit!=compfaces.end(); fit++)
      {
        if(group.options.do_break || 
           (fit->transparent && !group.options.no_break))
        {
          PRCCompressedBrepData *body = new PRCCompressedBrepData;
          body->face.push_back(fit->face);

          body->serial_tolerance=group.options.compression;
          body->brep_data_compressed_tolerance=2.8346456*
            group.options.compression;
          const uint32_t body_index = context->addCompressedBrepData(body);

          PRCBrepModel *brepmodel = new PRCBrepModel();
          brepmodel->index_of_line_style = fit->style;
          brepmodel->context_id = context_index;
          brepmodel->body_id = body_index;
          brepmodel->is_closed = group.options.closed;

          part_definition->addBrepModel(brepmodel);
        }
        else
        {
          if(!same_color)
            fit->face->index_of_line_style = fit->style;
          body->face.push_back(fit->face);
        }
      }
      if(body->face.empty())
      {
        delete body;
      }
      else
      {
        const uint32_t body_index = context->addCompressedBrepData(body);
        PRCBrepModel *brepmodel = new PRCBrepModel();
        if(same_color)
          brepmodel->index_of_line_style = style;
        brepmodel->context_id = context_index;
        brepmodel->body_id = body_index;
        brepmodel->is_closed = group.options.closed;
        part_definition->addBrepModel(brepmodel);
      }
    }

    PRCProductOccurrence *product_occurrence = new PRCProductOccurrence(name);

    for(PRCgroupList::iterator it=group.groupList.begin(); it!=group.groupList.end(); it++)
    {
       doGroup(*it, part_definition, product_occurrence);
    }

    // Simplify and reduce to as simple entities as possible
    // First option - reduce to one element in parent
    if (parent_part_definition && product_occurrence->index_son_occurrence.empty() &&
        part_definition->representation_item.size() == 1 &&
        ( name.empty() || part_definition->representation_item.front()->name.empty() ) &&
        ( !group.transform  || part_definition->representation_item.front()->index_local_coordinate_system==m1) )
    {
      if(part_definition->representation_item.front()->name.empty() )
        part_definition->representation_item.front()->name = name;
      if(part_definition->representation_item.front()->index_local_coordinate_system==m1)
        part_definition->representation_item.front()->index_local_coordinate_system = addTransform(group.transform);
      parent_part_definition->addRepresentationItem(part_definition->representation_item.front());
      part_definition->representation_item.clear();
      delete product_occurrence;
      delete part_definition;
    }
    // Second option - reduce to a set
    else if (parent_part_definition && product_occurrence->index_son_occurrence.empty() &&
      !part_definition->representation_item.empty() &&
      !group.options.do_break )
    {
      PRCSet *set = new PRCSet(name);
      set->index_local_coordinate_system = addTransform(group.transform);
      for(PRCRepresentationItemList::iterator it=part_definition->representation_item.begin(); it!=part_definition->representation_item.end(); it++)
        set->addRepresentationItem(*it);
      part_definition->representation_item.clear();
      parent_part_definition->addSet(set);
      delete product_occurrence;
      delete part_definition;      
    }
    // Third option - create product
    else if ( !product_occurrence->index_son_occurrence.empty() || !part_definition->representation_item.empty())
    {
      if (part_definition->representation_item.empty())
        delete part_definition;
      else
        product_occurrence->index_part = addPartDefinition(part_definition);
      if (group.transform) {
        product_occurrence->location = group.transform;
        group.transform = NULL;
      }
      if (parent_product_occurrence) {
        parent_product_occurrence->index_son_occurrence.push_back(addProductOccurrence(product_occurrence));
      }
      else {
        addProductOccurrence(product_occurrence);
      }
    }
    // Last case - absolutely nothing to do
    else
    {
      delete product_occurrence;
      delete part_definition;
    }
    
}

bool oPRCFile::finish()
{
  rootGroup.name = "root";
  doGroup(rootGroup, NULL, NULL);

  // write each section's bit data
  fileStructures[0]->prepare();
  modelFile.prepare();

  // create the header

  // fill out enough info so that sizes can be computed correctly
  header.number_of_file_structures = number_of_file_structures;
  header.fileStructureInformation = new PRCFileStructureInformation[number_of_file_structures];
  for(uint32_t i = 0; i < number_of_file_structures; ++i)
  {
    header.fileStructureInformation[i].UUID[0] = fileStructures[i]->header.fileStructureUUID[0];
    header.fileStructureInformation[i].UUID[1] = fileStructures[i]->header.fileStructureUUID[1];
    header.fileStructureInformation[i].UUID[2] = fileStructures[i]->header.fileStructureUUID[2];
    header.fileStructureInformation[i].UUID[3] = fileStructures[i]->header.fileStructureUUID[3];
    header.fileStructureInformation[i].reserved = 0;
    header.fileStructureInformation[i].number_of_offsets = 6;
    header.fileStructureInformation[i].offsets = new uint32_t[6];
  }

  header.startHeader.minimal_version_for_read = PRCVersion;
  header.startHeader.authoring_version = PRCVersion;
  makeFileUUID(header.startHeader.fileStructureUUID);
  makeAppUUID(header.startHeader.applicationUUID);

  header.file_size = getSize();
  header.model_file_offset = header.file_size - modelFile.getSize();

  uint32_t currentOffset = header.getSize();

  for(uint32_t i = 0; i < number_of_file_structures; ++i)
  {
    header.fileStructureInformation[i].offsets[0] = currentOffset; // header offset
    currentOffset += fileStructures[i]->header.getSize() + sizeof(uint32_t);
    for(list<PRCUncompressedFile>::iterator j = fileStructures[i]->uncompressedFiles.begin(); j != fileStructures[i]->uncompressedFiles.end(); j++)
      currentOffset += j->getSize();
    header.fileStructureInformation[i].offsets[1] = currentOffset; // globals offset
    currentOffset += fileStructures[i]->globals.getSize();
    header.fileStructureInformation[i].offsets[2] = currentOffset; // tree offset
    currentOffset += fileStructures[i]->tree.getSize();
    header.fileStructureInformation[i].offsets[3] = currentOffset; // tessellations offset
    currentOffset += fileStructures[i]->tessellations.getSize();
    header.fileStructureInformation[i].offsets[4] = currentOffset; // geometry offset
    currentOffset += fileStructures[i]->geometry.getSize();
    header.fileStructureInformation[i].offsets[5] = currentOffset; // extra geometry offset
    currentOffset += fileStructures[i]->extraGeometry.getSize();
  }

  // write the data
  header.write(output);

  for(uint32_t i = 0; i < number_of_file_structures; ++i)
  {
    fileStructures[i]->write(output);
  }

  modelFile.write(output);
  output.flush();

  for(uint32_t i = 0; i < number_of_file_structures; ++i)
    delete[] header.fileStructureInformation[i].offsets;
  delete[] header.fileStructureInformation;

  return true;
}

uint32_t oPRCFile::getSize()
{
  uint32_t size = header.getSize();

  for(uint32_t i = 0; i < number_of_file_structures; ++i)
  {
    size += fileStructures[i]->getSize();
  }

  size += modelFile.getSize();
  return size;
}

#define REPORT_ERROR( value ) { cerr << value << endl; return m1; }

uint32_t PRCFileStructure::addPicture(EPRCPictureDataFormat format, uint32_t size, const uint8_t *p, uint32_t width, uint32_t height, string name)
{
  if(size==0 || p==NULL)
    REPORT_ERROR( "image not set" )
  PRCPicture picture(name);
  PRCUncompressedFile uncompressedFile;
  uint32_t components=0;
  uint8_t *data = NULL;
  switch(format)
  {
    case KEPRCPicture_BITMAP_RGB_BYTE:
      components = 3;
    case KEPRCPicture_BITMAP_RGBA_BYTE:
      components = 4;
    case KEPRCPicture_BITMAP_GREY_BYTE:
      components = 1;
    case KEPRCPicture_BITMAP_GREYA_BYTE:
      components = 2;
      if(width==0 || height==0)
        REPORT_ERROR( "width or height parameter not set" )
      if (size < width*height*components)
        REPORT_ERROR( "image too small" )
   
      {
        uint32_t compressedDataSize = 0;
        const int CHUNK= 1024; // is this reasonable?
       
        z_stream strm;
        strm.zalloc = Z_NULL;
        strm.zfree = Z_NULL;
        strm.opaque = Z_NULL;
        if(deflateInit(&strm,Z_DEFAULT_COMPRESSION) != Z_OK)
          REPORT_ERROR ( "Compression initialization failed" )
        unsigned int sizeAvailable = deflateBound(&strm,size);
        uint8_t *compressedData = (uint8_t*) malloc(sizeAvailable);
        strm.avail_in = size;
        strm.next_in = (unsigned char*)p;
        strm.next_out = (unsigned char*)compressedData;
        strm.avail_out = sizeAvailable;
       
        int code;
        unsigned int chunks = 0;
        while((code = deflate(&strm,Z_FINISH)) == Z_OK)
        {
          ++chunks;
          // strm.avail_out should be 0 if we got Z_OK
          compressedDataSize = sizeAvailable - strm.avail_out;
          compressedData = (uint8_t*) realloc(compressedData,CHUNK*chunks);
          strm.next_out = (Bytef*)(compressedData + compressedDataSize);
          strm.avail_out += CHUNK;
          sizeAvailable += CHUNK;
        }
        compressedDataSize = sizeAvailable-strm.avail_out;
       
        if(code != Z_STREAM_END)
        {
          deflateEnd(&strm);
          free(compressedData);
          REPORT_ERROR ( "Compression error" )
        }
       
        deflateEnd(&strm);
        size = compressedDataSize;
        data = new uint8_t[compressedDataSize];
        memcpy(data, compressedData, compressedDataSize);
        free(compressedData);
      }
      uncompressedFiles.push_back(uncompressedFile);
      uncompressedFiles.back().file_size = size;
      uncompressedFiles.back().data = data;
      picture.format = format;
      picture.uncompressed_file_index = uncompressedFiles.size()-1;
      picture.pixel_width = width;
      picture.pixel_height = height;
      globals.pictures.push_back(picture);
      return globals.pictures.size()-1;
      break;

    case KEPRCPicture_PNG:
    case KEPRCPicture_JPG:
      data = new uint8_t[size];
      memcpy(data, p, size);
      uncompressedFiles.push_back(uncompressedFile);
      uncompressedFiles.back().file_size = size;
      uncompressedFiles.back().data = data;
      picture.format = format;
      picture.uncompressed_file_index = uncompressedFiles.size()-1;
      picture.pixel_width = 0; // width and height are ignored for JPG and PNG pictures - but let us keep things clean
      picture.pixel_height = 0;
      globals.pictures.push_back(picture);
      return globals.pictures.size()-1;
      break;

    default:
      REPORT_ERROR( "unknown picture format" )
  }
  return m1;
}
#undef REPORT_ERROR

uint32_t PRCFileStructure::addTextureDefinition(PRCTextureDefinition *pTextureDefinition)
{
  globals.texture_definitions.push_back(pTextureDefinition);
  return globals.texture_definitions.size()-1;
}

uint32_t PRCFileStructure::addRgbColor(const PRCRgbColor &color)
{
  globals.colors.push_back(color);
  return 3*(globals.colors.size()-1);
}

uint32_t PRCFileStructure::addRgbColorUnique(const PRCRgbColor &color)
{
  for(uint32_t i = 0; i < globals.colors.size(); ++i)
  {
    if(globals.colors[i] == color)
      return 3*i;
  }
  globals.colors.push_back(color);
  return 3*(globals.colors.size()-1);
}

uint32_t oPRCFile::addColor(const PRCRgbColor &color)
{
  PRCcolorMap::iterator pColor = colorMap.find(color);
  uint32_t color_index = m1;
  if(pColor!=colorMap.end())
    return pColor->second;
//  color_index = addRgbColorUnique(color);
  color_index = fileStructures[0]->addRgbColor(color);
  colorMap.insert(make_pair(color,color_index));
  return color_index;
}

uint32_t oPRCFile::addColour(const RGBAColour &colour)
{
  PRCcolourMap::iterator pColour = colourMap.find(colour);
  if(pColour!=colourMap.end())
    return pColour->second;
  const uint32_t color_index = addColor(PRCRgbColor(colour.R, colour.G, colour.B));
  PRCStyle *style = new PRCStyle();  
  style->line_width = 1.0;
  style->is_vpicture = false;
  style->line_pattern_vpicture_index = 0;
  style->is_material = false;
  style->color_material_index = color_index;
  style->is_transparency_defined = (colour.A < 1.0);
  style->transparency = (uint8_t)(colour.A * 256);
  style->additional = 0;
  const uint32_t style_index = fileStructures[0]->addStyle(style);
  colourMap.insert(make_pair(colour,style_index));
  return style_index;
}

uint32_t oPRCFile::addTransform(PRCGeneralTransformation3d*& transform)
{
  if(!transform)
    return m1;
  PRCtransformMap::iterator pTransform = transformMap.find(*transform);
  if(pTransform!=transformMap.end())
    return pTransform->second;
  PRCCoordinateSystem *coordinateSystem = new PRCCoordinateSystem();
  coordinateSystem->axis_set = transform;
  const uint32_t coordinate_system_index = fileStructures[0]->addCoordinateSystem(coordinateSystem);
  transformMap.insert(make_pair(*transform,coordinate_system_index));
  transform = NULL;
  return coordinate_system_index;
}

uint32_t oPRCFile::addMaterial(const PRCmaterial &material)
{
  PRCmaterialMap::iterator pMaterial = materialMap.find(material);
  if(pMaterial!=materialMap.end())
    return pMaterial->second;
  PRCMaterialGeneric *materialGeneric = new PRCMaterialGeneric(); 
  const PRCRgbColor ambient(material.ambient.R, material.ambient.G, material.ambient.B);
  materialGeneric->ambient = addColor(ambient);
  const PRCRgbColor diffuse(material.diffuse.R, material.diffuse.G, material.diffuse.B);
  materialGeneric->diffuse = addColor(diffuse);
  const PRCRgbColor emissive(material.emissive.R, material.emissive.G, material.emissive.B);
  materialGeneric->emissive = addColor(emissive);
  const PRCRgbColor specular(material.specular.R, material.specular.G, material.specular.B);
  materialGeneric->specular = addColor(specular);
  materialGeneric->shininess = material.shininess;
  materialGeneric->ambient_alpha = material.ambient.A;
  materialGeneric->diffuse_alpha = material.diffuse.A;
  materialGeneric->emissive_alpha = material.emissive.A;
  materialGeneric->specular_alpha = material.specular.A;
  const uint32_t material_index = fileStructures[0]->addMaterialGeneric(materialGeneric);
  PRCStyle *style = new PRCStyle();  
  style->line_width = 0.0;
  style->is_vpicture = false;
  style->line_pattern_vpicture_index = 0;
  style->is_material = true;
  style->color_material_index = material_index;
  style->is_transparency_defined = (material.alpha < 1.0);
  style->transparency = (uint8_t)(material.alpha * 256);
  style->additional = 0;
  const uint32_t style_index = fileStructures[0]->addStyle(style);
  materialMap.insert(make_pair(material,style_index)).first;
  return style_index;
}

bool isid(const double t[][4])
{
  return t == NULL ||
    (t[0][0]==1 && t[0][1]==0 && t[0][2]==0 && t[0][3]==0 &&
     t[1][0]==0 && t[1][1]==1 && t[1][2]==0 && t[1][3]==0 &&
     t[2][0]==0 && t[2][1]==0 && t[2][2]==1 && t[2][3]==0 &&
     t[3][0]==0 && t[3][1]==0 && t[3][2]==0 && t[3][3]==1);
}
bool isid(const double t[])
{
  return(isid((double (*)[4])t));
}


void oPRCFile::begingroup(const char *name, PRCoptions *options,
                          const double t[][4])
{
  if(currentGroups.empty())
    currentGroups.push(rootGroup.groupList.insert(rootGroup.groupList.end(),PRCgroup()));
  else
    currentGroups.push(currentGroups.top()->groupList.insert(currentGroups.top()->groupList.end(),PRCgroup()));
  PRCgroup &group = *(currentGroups.top());
  group.name=name;
  if(options) group.options=*options;
  if(t&&!isid(t))
    group.transform = new PRCGeneralTransformation3d(t);
}

void oPRCFile::endgroup()
{
  if(!currentGroups.empty())
    currentGroups.pop();
}

PRCgroup& oPRCFile::findGroup()
{
  if(!currentGroups.empty())
    return *(currentGroups.top());
  else
    return rootGroup;
}

#define ADDWIRE(curvtype)                                 \
  PRCgroup &group = findGroup();                          \
  group.wires.push_back(PRCwire());                       \
  PRCwire &wire = group.wires.back();                     \
  curvtype *curve = new curvtype;                         \
  wire.curve = curve;                                     \
  wire.style = addColour(c);

#define ADDFACE(surftype)                                 \
  PRCgroup &group = findGroup();                          \
  group.faces.push_back(PRCface());                       \
  PRCface& face = group.faces.back();                     \
  surftype *surface = new surftype;                       \
  face.face = new PRCFace;                                \
  face.face->base_surface = surface;                      \
  face.transparent = m.alpha < 1.0;                       \
  face.style = addMaterial(m);

#define ADDCOMPFACE                                       \
  PRCgroup &group = findGroup();                          \
  group.compfaces.push_back(PRCcompface());               \
  PRCcompface& face = group.compfaces.back();             \
  PRCCompressedFace *compface = new PRCCompressedFace;    \
  face.face = compface;                                   \
  face.transparent = m.alpha < 1.0;                       \
  face.style = addMaterial(m);

void oPRCFile::addPoint(const double P[3], const RGBAColour &c)
{
  PRCgroup &group = findGroup();
  group.points[addColour(c)].push_back(PRCVector3d(P[0],P[1],P[2]));
}

void oPRCFile::addLine(uint32_t n, const double P[][3], const RGBAColour &c)
{
  PRCgroup &group = findGroup();
  if(group.options.tess)
  {
    group.lines.push_back(PRCtessline());
    group.lines.back().color.red   = c.R;
    group.lines.back().color.green = c.G;
    group.lines.back().color.blue  = c.B;
    for(uint32_t i=0; i<n; i++)
     group.lines.back().point.push_back(PRCVector3d(P[i][0],P[i][1],P[i][2]));
  }
  else
  {
    ADDWIRE(PRCPolyLine)
    curve->point.resize(n);
    for(uint32_t i=0; i<n; i++)
     curve->point[i].Set(P[i][0],P[i][1],P[i][2]);
    curve->interval.min = 0;
    curve->interval.max = curve->point.size()-1;
  }
}

void oPRCFile::addBezierCurve(uint32_t n, const double cP[][3],
                              const RGBAColour &c)
{
  ADDWIRE(PRCNURBSCurve)
  curve->is_rational = false;
  curve->degree = 3;
  const size_t NUMBER_OF_POINTS = n;
  curve->control_point.resize(NUMBER_OF_POINTS);
  for(size_t i = 0; i < NUMBER_OF_POINTS; ++i)
    curve->control_point[i].Set(cP[i][0],cP[i][1],cP[i][2]);
  curve->knot.resize(3+NUMBER_OF_POINTS+1);
  curve->knot[0] = 1;
  for(size_t i = 1; i < 3+NUMBER_OF_POINTS; ++i)
    curve->knot[i] = (i+2)/3; // integer division is intentional
  curve->knot[3+NUMBER_OF_POINTS] = (3+NUMBER_OF_POINTS+1)/3;
}

void oPRCFile::addCurve(uint32_t d, uint32_t n, const double cP[][3], const double *k, const RGBAColour &c, const double w[])
{
  ADDWIRE(PRCNURBSCurve)
  curve->is_rational = w;
  curve->degree = d;
  curve->control_point.resize(n);
  for(uint32_t i = 0; i < n; i++)
    if(w)
      curve->control_point[i].Set(cP[i][0]*w[i],cP[i][1]*w[i],cP[i][2]*w[i],w[i]);
    else
      curve->control_point[i].Set(cP[i][0],cP[i][1],cP[i][2]);
  curve->knot.resize(d+n+1);
  for(uint32_t i = 0; i < d+n+1; i++)
    curve->knot[i] = k[i];
}

void oPRCFile::addRectangle(const double P[][3], const PRCmaterial &m)
{
  PRCgroup &group = findGroup();
  if(group.options.tess)
  {
    PRCgroup &group = findGroup();
    group.rectangles.push_back(PRCtessrectangle());
    PRCtessrectangle &rectangle = group.rectangles.back();
    rectangle.style = addMaterial(m);
    for(size_t i = 0; i < 4; i++)
    {
       rectangle.vertices[i].x = P[i][0];
       rectangle.vertices[i].y = P[i][1];
       rectangle.vertices[i].z = P[i][2];
    }
  }
  else if(group.options.compression == 0.0)
  {
    ADDFACE(PRCNURBSSurface)

    surface->is_rational = false;
    surface->degree_in_u = 1;
    surface->degree_in_v = 1;
    surface->control_point.resize(4);
    for(size_t i = 0; i < 4; ++i)
    {
        surface->control_point[i].x = P[i][0];
        surface->control_point[i].y = P[i][1];
        surface->control_point[i].z = P[i][2];
    }
    surface->knot_u.resize(4);
    surface->knot_v.resize(4);
    surface->knot_v[0] = surface->knot_u[0] = 1;
    surface->knot_v[1] = surface->knot_u[1] = 3;
    surface->knot_v[2] = surface->knot_u[2] = 4;
    surface->knot_v[3] = surface->knot_u[3] = 4;
  }
  else
  {
    ADDCOMPFACE

    compface->degree = 1;
    compface->control_point.resize(4);
    for(size_t i = 0; i < 4; ++i)
    {
        compface->control_point[i].x = P[i][0];
        compface->control_point[i].y = P[i][1];
        compface->control_point[i].z = P[i][2];
    }
  }
}

void oPRCFile::addPatch(const double cP[][3], const PRCmaterial &m)
{
  PRCgroup &group = findGroup();
  if(group.options.compression == 0.0)
  {
    ADDFACE(PRCNURBSSurface)
   
    surface->is_rational = false;
    surface->degree_in_u = 3;
    surface->degree_in_v = 3;
    surface->control_point.resize(16);
    for(size_t i = 0; i < 16; ++i)
    {
        surface->control_point[i].x = cP[i][0];
        surface->control_point[i].y = cP[i][1];
        surface->control_point[i].z = cP[i][2];
    }
    surface->knot_u.resize(8);
    surface->knot_v.resize(8);
    surface->knot_v[0] = surface->knot_u[0] = 1;
    surface->knot_v[1] = surface->knot_u[1] = 1;
    surface->knot_v[2] = surface->knot_u[2] = 1;
    surface->knot_v[3] = surface->knot_u[3] = 1;
    surface->knot_v[4] = surface->knot_u[4] = 2;
    surface->knot_v[5] = surface->knot_u[5] = 2;
    surface->knot_v[6] = surface->knot_u[6] = 2;
    surface->knot_v[7] = surface->knot_u[7] = 2;
  }
  else
  {
    ADDCOMPFACE

    compface->degree = 3;
    compface->control_point.resize(16);
    for(size_t i = 0; i < 16; ++i)
    {
        compface->control_point[i].x = cP[i][0];
        compface->control_point[i].y = cP[i][1];
        compface->control_point[i].z = cP[i][2];
    }
  }
}

void oPRCFile::addSurface(uint32_t dU, uint32_t dV, uint32_t nU, uint32_t nV,
                          const double cP[][3], const double *kU,
                          const double *kV, const PRCmaterial &m,
                          const double w[])
{
  ADDFACE(PRCNURBSSurface)

  surface->is_rational = w;
  surface->degree_in_u = dU;
  surface->degree_in_v = dV;
  surface->control_point.resize(nU*nV);
  for(size_t i = 0; i < nU*nV; i++)
    if(w)
      surface->control_point[i]=PRCControlPoint(cP[i][0]*w[i],cP[i][1]*w[i],cP[i][2]*w[i],w[i]);
    else
      surface->control_point[i]=PRCControlPoint(cP[i][0],cP[i][1],cP[i][2]);
  surface->knot_u.insert(surface->knot_u.end(), kU, kU+(dU+nU+1));
  surface->knot_v.insert(surface->knot_v.end(), kV, kV+(dV+nV+1));
}

#define SETTRANSF \
  if(t&&!isid(t))                                                             \
    face.transform = new PRCGeneralTransformation3d(t);                       \
  if(origin) surface->origin.Set(origin[0],origin[1],origin[2]);              \
  if(x_axis) surface->x_axis.Set(x_axis[0],x_axis[1],x_axis[2]);              \
  if(y_axis) surface->y_axis.Set(y_axis[0],y_axis[1],y_axis[2]);              \
  surface->scale = scale;                                                     \
  surface->geometry_is_2D = false;                                            \
  if(surface->origin!=PRCVector3d(0,0,0))                                     \
    surface->behaviour = surface->behaviour | PRC_TRANSFORMATION_Translate;   \
  if(surface->x_axis!=PRCVector3d(1,0,0)||surface->y_axis!=PRCVector3d(0,1,0)) \
    surface->behaviour = surface->behaviour | PRC_TRANSFORMATION_Rotate;      \
  if(surface->scale!=1)                                                       \
    surface->behaviour = surface->behaviour | PRC_TRANSFORMATION_Scale;       \
  surface->has_transformation = (surface->behaviour != PRC_TRANSFORMATION_Identity);

#define PRCFACETRANSFORM const double origin[3], const double x_axis[3], const double y_axis[3], double scale, const double t[][4]

void oPRCFile::addTube(uint32_t n, const double cP[][3], const double oP[][3], bool straight, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCBlend01)
  SETTRANSF
  if(straight)
  {
    PRCPolyLine *center_curve = new PRCPolyLine;
    center_curve->point.resize(n);
    for(uint32_t i=0; i<n; i++)
      center_curve->point[i].Set(cP[i][0],cP[i][1],cP[i][2]);
    center_curve->interval.min = 0;
    center_curve->interval.max = center_curve->point.size()-1;
    surface->center_curve = center_curve;

    PRCPolyLine *origin_curve = new PRCPolyLine;
    origin_curve->point.resize(n);
    for(uint32_t i=0; i<n; i++)
      origin_curve->point[i].Set(oP[i][0],oP[i][1],oP[i][2]);
    origin_curve->interval.min = 0;
    origin_curve->interval.max = origin_curve->point.size()-1;
    surface->origin_curve = origin_curve;

    surface->uv_domain.min.x = 0;
    surface->uv_domain.max.x = 2*pi;
    surface->uv_domain.min.y = 0;
    surface->uv_domain.max.y = n-1;
  }
  else
  {
    PRCNURBSCurve *center_curve = new PRCNURBSCurve;
    center_curve->is_rational = false;
    center_curve->degree = 3;
    const uint32_t CENTER_NUMBER_OF_POINTS = n;
    center_curve->control_point.resize(CENTER_NUMBER_OF_POINTS);
    for(uint32_t i = 0; i < CENTER_NUMBER_OF_POINTS; ++i)
      center_curve->control_point[i].Set(cP[i][0],cP[i][1],cP[i][2]);
    center_curve->knot.resize(3+CENTER_NUMBER_OF_POINTS+1);
    center_curve->knot[0] = 1;
    for(uint32_t i = 1; i < 3+CENTER_NUMBER_OF_POINTS; ++i)
      center_curve->knot[i] = (i+2)/3; // integer division is intentional
    center_curve->knot[3+CENTER_NUMBER_OF_POINTS] = (3+CENTER_NUMBER_OF_POINTS+1)/3;
    surface->center_curve = center_curve;

    PRCNURBSCurve *origin_curve = new PRCNURBSCurve;
    origin_curve->is_rational = false;
    origin_curve->degree = 3;
    const uint32_t ORIGIN_NUMBER_OF_POINTS = n;
    origin_curve->control_point.resize(ORIGIN_NUMBER_OF_POINTS);
    for(uint32_t i = 0; i < ORIGIN_NUMBER_OF_POINTS; ++i)
      origin_curve->control_point[i].Set(oP[i][0],oP[i][1],oP[i][2]);
    origin_curve->knot.resize(3+ORIGIN_NUMBER_OF_POINTS+1);
    origin_curve->knot[0] = 1;
    for(size_t i = 1; i < 3+ORIGIN_NUMBER_OF_POINTS; ++i)
      origin_curve->knot[i] = (i+2)/3; // integer division is intentional
    origin_curve->knot[3+ORIGIN_NUMBER_OF_POINTS] = (3+ORIGIN_NUMBER_OF_POINTS+1)/3;
    surface->origin_curve = origin_curve;

    surface->uv_domain.min.x = 0;
    surface->uv_domain.max.x = 2*pi;
    surface->uv_domain.min.y = 1; // first knot
    surface->uv_domain.max.y = (3+CENTER_NUMBER_OF_POINTS+1)/3; // last knot
  }
}

void oPRCFile::addHemisphere(double radius, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCSphere)
  SETTRANSF
  surface->uv_domain.min.x = 0;
  surface->uv_domain.max.x = 2*pi;
  surface->uv_domain.min.y = 0;
  surface->uv_domain.max.y = 0.5*pi;
  surface->radius = radius;
}

void oPRCFile::addSphere(double radius, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCSphere)
  SETTRANSF
  surface->uv_domain.min.x = 0;
  surface->uv_domain.max.x = 2*pi;
  surface->uv_domain.min.y =-0.5*pi;
  surface->uv_domain.max.y = 0.5*pi;
  surface->radius = radius;
}

void oPRCFile::addDisk(double radius, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCRuled)
  SETTRANSF
  PRCCircle *first_curve = new PRCCircle;
  first_curve->radius = radius;
  surface->first_curve = first_curve;
  PRCCircle *second_curve = new PRCCircle;
  second_curve->radius = 0;
  surface->second_curve = second_curve;

  surface->uv_domain.min.x = 0;
  surface->uv_domain.max.x = 1;
  surface->uv_domain.min.y = 0;
  surface->uv_domain.max.y = 2*pi;
  surface->parameterization_on_v_coeff_a = -1;
  surface->parameterization_on_v_coeff_b = 2*pi;
}

void oPRCFile::addCylinder(double radius, double height, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCCylinder)
  SETTRANSF
  surface->uv_domain.min.x = 0;
  surface->uv_domain.max.x = 2*pi;
  surface->uv_domain.min.y = (height>0)?0:height;
  surface->uv_domain.max.y = (height>0)?height:0;
  surface->radius = radius;
}

void oPRCFile::addTorus(double major_radius, double minor_radius, double angle1, double angle2, const PRCmaterial &m, PRCFACETRANSFORM)
{
  ADDFACE(PRCTorus)
  SETTRANSF
  surface->uv_domain.min.x = (angle1/180)*pi;
  surface->uv_domain.max.x = (angle2/180)*pi;
  surface->uv_domain.min.y = 0;
  surface->uv_domain.max.y = 2*pi;
  surface->major_radius = major_radius;
  surface->minor_radius = minor_radius;
}

#undef PRCFACETRANSFORM
#undef ADDFACE
#undef ADDWIRE
#undef SETTRANSF

uint32_t PRCFileStructure::addMaterialGeneric(PRCMaterialGeneric*& pMaterialGeneric)
{
  globals.materials.push_back(pMaterialGeneric);
  pMaterialGeneric = NULL;
  return globals.materials.size()-1;
}

uint32_t PRCFileStructure::addTextureApplication(PRCTextureApplication*& pTextureApplication)
{
  globals.materials.push_back(pTextureApplication);
  pTextureApplication = NULL;
  return globals.materials.size()-1;
}

uint32_t PRCFileStructure::addStyle(PRCStyle*& pStyle)
{
  globals.styles.push_back(pStyle);
  pStyle = NULL;
  return globals.styles.size()-1;
}

uint32_t PRCFileStructure::addPartDefinition(PRCPartDefinition*& pPartDefinition)
{
  tree.part_definitions.push_back(pPartDefinition);
  pPartDefinition = NULL;  
  return tree.part_definitions.size()-1;
}

uint32_t PRCFileStructure::addProductOccurrence(PRCProductOccurrence*& pProductOccurrence)
{
  tree.product_occurrences.push_back(pProductOccurrence);
  pProductOccurrence = NULL;
  return tree.product_occurrences.size()-1;
}

uint32_t PRCFileStructure::addTopoContext(PRCTopoContext*& pTopoContext)
{
  contexts.push_back(pTopoContext);
  pTopoContext = NULL;
  return contexts.size()-1;
}

uint32_t PRCFileStructure::getTopoContext(PRCTopoContext*& pTopoContext)
{
  pTopoContext = new PRCTopoContext;
  contexts.push_back(pTopoContext);
  return contexts.size()-1;
}

uint32_t PRCFileStructure::add3DTess(PRC3DTess*& p3DTess)
{
  tessellations.tessellations.push_back(p3DTess);
  p3DTess = NULL;
  return tessellations.tessellations.size()-1;
}

uint32_t PRCFileStructure::add3DWireTess(PRC3DWireTess*& p3DWireTess)
{
  tessellations.tessellations.push_back(p3DWireTess);
  p3DWireTess = NULL;
  return tessellations.tessellations.size()-1;
}
/*
uint32_t PRCFileStructure::addMarkupTess(PRCMarkupTess*& pMarkupTess)
{
  tessellations.tessellations.push_back(pMarkupTess);
  pMarkupTess = NULL;
  return tessellations.tessellations.size()-1;
}

uint32_t PRCFileStructure::addMarkup(PRCMarkup*& pMarkup)
{
  tree.markups.push_back(pMarkup);
  pMarkup = NULL;
  return tree.markups.size()-1;
}

uint32_t PRCFileStructure::addAnnotationItem(PRCAnnotationItem*& pAnnotationItem)
{
  tree.annotation_entities.push_back(pAnnotationItem);
  pAnnotationItem = NULL;
  return tree.annotation_entities.size()-1;
}
*/
uint32_t PRCFileStructure::addCoordinateSystem(PRCCoordinateSystem*& pCoordinateSystem)
{
  globals.reference_coordinate_systems.push_back(pCoordinateSystem);
  pCoordinateSystem = NULL;
  return globals.reference_coordinate_systems.size()-1;
}

uint32_t PRCFileStructure::addCoordinateSystemUnique(PRCCoordinateSystem*& pCoordinateSystem)
{
  for(uint32_t i = 0; i < globals.reference_coordinate_systems.size(); ++i)
  {
    if(*(globals.reference_coordinate_systems[i])==*pCoordinateSystem) {
      pCoordinateSystem = NULL;
      return i;
    }
  }
  globals.reference_coordinate_systems.push_back(pCoordinateSystem);
  pCoordinateSystem = NULL;
  return globals.reference_coordinate_systems.size()-1;
}