-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathac3d.cpp
More file actions
1452 lines (1313 loc) · 49.6 KB
/
ac3d.cpp
File metadata and controls
1452 lines (1313 loc) · 49.6 KB
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
// 30 Oct 2002
// AC3D loader for models generated by the AC3D modeller (www.ac3d.org)
// part of this source code were supplied by the AC3D project (Andy Colebourne)
// eg the basic parsing of an AC3D file.
// Conversion from AC3D scenegraph to OSG by GW Michel.
#include <vector>
#include <iostream>
#include <limits>
#include <stdlib.h>
#include <osg/GL>
#include <osg/GLU>
#include <osg/Math>
#include <osg/BlendFunc>
#include <osg/CullFace>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Geometry>
#include <osg/Light>
#include <osg/LightSource>
#include <osg/Material>
#include <osg/Math>
#include <osg/Texture2D>
#include <osg/TexEnv>
#include <osg/StateSet>
#include <osg/ShadeModel>
#include <osg/Math>
#include <osg/Notify>
#include <osgUtil/Tessellator>
#include <osgDB/FileNameUtils>
#include <osgDB/Registry>
#include <osgDB/ReadFile>
#include <osgDB/FileUtils>
#include <osgDB/fstream>
#include "Exception.h"
#include "Geode.h"
namespace ac3d {
osg::Node*
readFile(std::istream& stream, const osgDB::ReaderWriter::Options* options);
}
class geodeVisitor : public osg::NodeVisitor { // collects geodes from scene sub-graph attached to 'this'
public:
geodeVisitor():
osg::NodeVisitor(osg::NodeVisitor::TRAVERSE_ALL_CHILDREN) {}
~geodeVisitor() { _geodelist.clear();}
// one apply for each type of Node that might be a user transform
virtual void apply(osg::Geode& geode) {
_geodelist.push_back(&geode);
}
virtual void apply(osg::Group& gp){
traverse(gp); // must continue subgraph traversal.
}
std::vector<const osg::Geode *> getGeodes() {return _geodelist;}
protected:
typedef std::vector<const osg::Geode *> Geodelist;
Geodelist _geodelist;
};
class ReaderWriterAC : public osgDB::ReaderWriter
{
public:
ReaderWriterAC()
{
supportsExtension("ac","AC3D Database format");
}
virtual const char* className() const { return "AC3D Database Reader"; }
virtual ReadResult readObject(const std::string& fileName, const osgDB::ReaderWriter::Options* options) const
{
return readNode(fileName, options);
}
virtual ReadResult readNode(const std::string& file,const Options* options) const
{
std::string ext = osgDB::getFileExtension(file);
if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;
// GWM added Dec 2003 - get full path name (change in osgDB handling of files).
std::string fileName = osgDB::findDataFile( file, options );
OSG_INFO << "osgDB ac3d reader: starting reading \"" << fileName << "\"" << std::endl;
// Anders Backmann - correct return if path not found
if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;
// allocate per file data and start reading
osgDB::ifstream fin;
fin.open(fileName.c_str(), std::ios::in);
if (!fin.is_open()) return ReadResult::FILE_NOT_FOUND;
// code for setting up the database path so that internally referenced file are
// searched for on relative paths.
osg::ref_ptr<Options> local_opt;
if (options)
local_opt = static_cast<Options*>(options->clone(osg::CopyOp::DEEP_COPY_ALL));
else
local_opt = new Options;
local_opt->getDatabasePathList().push_back(osgDB::getFilePath(fileName));
ReadResult result = readNode(fin, local_opt.get());
if (result.validNode())
result.getNode()->setName(fileName);
return result;
}
virtual ReadResult readObject(std::istream& fin, const Options* options) const
{
return readNode(fin, options);
}
virtual ReadResult readNode(std::istream& fin, const Options* options) const
{
std::string header;
fin >> header;
if (header.substr(0, 4) != "AC3D")
return osgDB::ReaderWriter::ReadResult::FILE_NOT_HANDLED;
return ac3d::readFile(fin, options);
}
virtual WriteResult writeNode(const osg::Node& node,const std::string& fileName, const Options* /*options*/) const
{
std::string ext = osgDB::getFileExtension(fileName);
if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
geodeVisitor vs; // this collects geodes.
std::vector<unsigned int>iNumMaterials;
const_cast<osg::Node&>(node).accept(vs); // this parses the tree to streamd Geodes
std::vector<const osg::Geode *> glist=vs.getGeodes();
osgDB::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);
// Write out the file header
std::vector<const osg::Geode *>::iterator itr;
fout << "AC3Db" << std::endl;
// output the Materials
int iNumGeodesWithGeometry = 0;
for (itr=glist.begin();itr!= glist.end();itr++)
{
iNumMaterials.push_back(const_cast<ac3d::Geode*>(static_cast<const ac3d::Geode*>(*itr))->ProcessMaterial(fout,itr-glist.begin()));
unsigned int iNumDrawables = (*itr)->getNumDrawables();
int iNumGeometries = 0;
for (unsigned int i = 0; i < iNumDrawables; i++)
{
const osg::Drawable* pDrawable = (*itr)->getDrawable(i);
if (NULL != pDrawable)
{
const osg::Geometry *pGeometry = pDrawable->asGeometry();
if (NULL != pGeometry)
iNumGeometries++;
}
}
if (iNumGeometries > 0)
iNumGeodesWithGeometry++;
}
// output the Geometry
unsigned int nfirstmat=0;
fout << "OBJECT world" << std::endl;
fout << "kids " << iNumGeodesWithGeometry << std::endl;
for (itr=glist.begin();itr!= glist.end();itr++) {
const_cast<ac3d::Geode*>(static_cast<const ac3d::Geode*>(*itr))->ProcessGeometry(fout,nfirstmat);
nfirstmat+=iNumMaterials[itr-glist.begin()];
}
fout.close();
return WriteResult::FILE_SAVED;
}
virtual WriteResult writeNode(const osg::Node& node,std::ostream& fout, const Options* opts) const
{
// write ac file.
const osg::Group *gp=node.asGroup();
if(gp)
{
const unsigned int nch=gp->getNumChildren();
for (unsigned int i=0; i<nch; i++)
{
writeNode(*(gp->getChild(i)), fout, opts);
}
}
else
OSG_WARN<<"File must start with a geode "<<std::endl;
fout.flush();
return WriteResult::FILE_SAVED;
}
private:
};
// now register with osg::Registry to instantiate the above
// reader/writer.
REGISTER_OSGPLUGIN(ac, ReaderWriterAC)
namespace ac3d {
enum {
ObjectTypeNormal = 0,
ObjectTypeGroup = 1,
ObjectTypeLight = 2,
SurfaceTypePolygon = 0,
SurfaceTypeLineLoop = 1,
SurfaceTypeLineStrip = 2,
SurfaceShaded = 1<<4,
SurfaceTwoSided = 1<<5
};
/// Returns a possibly quoted string given in the end of the current line in the stream
static
std::string
readString(std::istream& stream)
{
std::string s;
stream >> std::ws;
if (stream.peek() != '\"')
{
// Not quoted, just read the string
stream >> s;
}
else
{
// look for quoted strings
// throw away the quote
stream.get();
// extract characters until either an error happens or a quote is found
while (stream.good())
{
std::istream::char_type c;
stream.get(c);
if (c == '\"')
break;
s += c;
}
}
return s;
}
static void
setTranslucent(osg::StateSet* stateSet)
{
osg::BlendFunc* blendFunc = new osg::BlendFunc;
blendFunc->setDataVariance(osg::Object::STATIC);
blendFunc->setSource(osg::BlendFunc::SRC_ALPHA);
blendFunc->setDestination(osg::BlendFunc::ONE_MINUS_SRC_ALPHA);
stateSet->setAttribute(blendFunc);
stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
}
// Just a container to store an ac3d material
class MaterialData
{
public:
MaterialData() :
mMaterial(new osg::Material),
mColorArray(new osg::Vec4Array(1)),
mTranslucent(false)
{
mMaterial->setDataVariance(osg::Object::STATIC);
mColorArray->setDataVariance(osg::Object::STATIC);
}
void readMaterial(std::istream& stream)
{
// note that this might be quoted
std::string name = readString(stream);
mMaterial->setName(name);
std::string tmp;
stream >> tmp;
osg::Vec4 diffuse;
stream >> diffuse[0] >> diffuse[1] >> diffuse[2];
mMaterial->setDiffuse(osg::Material::FRONT_AND_BACK, diffuse);
stream >> tmp;
osg::Vec4 ambient;
stream >> ambient[0] >> ambient[1] >> ambient[2];
mMaterial->setAmbient(osg::Material::FRONT_AND_BACK, ambient);
stream >> tmp;
osg::Vec4 emmissive;
stream >> emmissive[0] >> emmissive[1] >> emmissive[2];
mMaterial->setEmission(osg::Material::FRONT_AND_BACK, emmissive);
stream >> tmp;
osg::Vec4 specular;
stream >> specular[0] >> specular[1] >> specular[2];
mMaterial->setSpecular(osg::Material::FRONT_AND_BACK, specular);
stream >> tmp;
float shininess;
stream >> shininess;
mMaterial->setShininess(osg::Material::FRONT_AND_BACK, shininess);
stream >> tmp;
float transparency;
stream >> transparency;
mMaterial->setTransparency(osg::Material::FRONT_AND_BACK, transparency);
mTranslucent = 0 < transparency;
// must correspond to the material we use for the color array below
mMaterial->setColorMode(osg::Material::DIFFUSE);
// this must be done past the transparency setting ...
(*mColorArray)[0] = mMaterial->getDiffuse(osg::Material::FRONT_AND_BACK);
}
void toStateSet(osg::StateSet* stateSet) const
{
stateSet->setAttribute(mMaterial.get());
if (mTranslucent)
setTranslucent(stateSet);
}
osg::Vec4Array* getColorArray() const
{
return mColorArray.get();
}
private:
osg::ref_ptr<osg::Material> mMaterial;
osg::ref_ptr<osg::Vec4Array> mColorArray;
bool mTranslucent;
};
class TextureData
{
public:
TextureData() :
mTranslucent(false),
mRepeat(true)
{
}
bool setTexture(const std::string& name, const osgDB::ReaderWriter::Options* options, osg::TexEnv* modulateTexEnv)
{
mTexture2DRepeat = new osg::Texture2D;
mTexture2DRepeat->setDataVariance(osg::Object::STATIC);
mTexture2DRepeat->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::REPEAT);
mTexture2DRepeat->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::REPEAT);
mTexture2DClamp = new osg::Texture2D;
mTexture2DClamp->setDataVariance(osg::Object::STATIC);
mTexture2DClamp->setWrap(osg::Texture2D::WRAP_S, osg::Texture2D::CLAMP_TO_EDGE);
mTexture2DClamp->setWrap(osg::Texture2D::WRAP_T, osg::Texture2D::CLAMP_TO_EDGE);
std::string absFileName = osgDB::findDataFile(name, options);
if (absFileName.empty())
{
OSG_FATAL << "osgDB ac3d reader: could not find texture \"" << name << "\"" << std::endl;
return false;
}
mImage = osgDB::readRefImageFile(absFileName, options);
if (!mImage.valid())
{
OSG_FATAL << "osgDB ac3d reader: could not read texture \"" << name << "\"" << std::endl;
return false;
}
mTexture2DRepeat->setImage(mImage.get());
mTexture2DClamp->setImage(mImage.get());
mTranslucent = mImage->isImageTranslucent();
// Use a shared modulate TexEnv
mModulateTexEnv = modulateTexEnv;
return true;
}
void setRepeat(bool repeat)
{
mRepeat = repeat;
}
bool valid() const
{
return mImage.valid();
}
std::string getFileName() const
{
if (!mImage.valid())
return std::string();
return mImage->getFileName();
}
void toTextureStateSet(osg::StateSet* stateSet) const
{
if (!valid())
return;
stateSet->setTextureAttribute(0, mModulateTexEnv.get());
if (mRepeat)
stateSet->setTextureAttribute(0, mTexture2DRepeat.get());
else
stateSet->setTextureAttribute(0, mTexture2DClamp.get());
stateSet->setTextureMode(0, GL_TEXTURE_2D, osg::StateAttribute::ON);
if (mTranslucent)
setTranslucent(stateSet);
}
private:
osg::ref_ptr<osg::TexEnv> mModulateTexEnv;
osg::ref_ptr<osg::Texture2D> mTexture2DClamp;
osg::ref_ptr<osg::Texture2D> mTexture2DRepeat;
osg::ref_ptr<osg::Image> mImage;
bool mTranslucent;
bool mRepeat;
};
class FileData
{
public:
FileData(const osgDB::ReaderWriter::Options* options) :
mOptions(options),
mLightIndex(1)
{
mModulateTexEnv = new osg::TexEnv;
mModulateTexEnv->setDataVariance(osg::Object::STATIC);
mModulateTexEnv->setMode(osg::TexEnv::MODULATE);
}
TextureData toTextureData(const std::string& texName)
{
// If it is already there, use this
TextureDataMap::iterator i = mTextureStates.find(texName);
if (i != mTextureStates.end())
return i->second;
// Try to load that texture.
TextureData textureData;
textureData.setTexture(texName, mOptions.get(), mModulateTexEnv.get());
if (textureData.valid()) {
mTextureStates[texName] = textureData;
return textureData;
}
// still no joy?, try with the stripped filename if this is different
// Try the pure file name if it is different
std::string simpleTexName = osgDB::getSimpleFileName(texName);
if (simpleTexName != texName)
return toTextureData(simpleTexName);
// Nothing that worked, return invalid data
return TextureData();
}
osg::Light* getNextLight()
{
osg::Light* light = new osg::Light;
light->setDataVariance(osg::Object::STATIC);
light->setLightNum(mLightIndex++);
return light;
}
void addMaterial(const MaterialData& material)
{
mMaterials.push_back(material);
}
unsigned getNumMaterials() const
{
return mMaterials.size();
}
const MaterialData& getMaterial(unsigned idx) const
{
return mMaterials[idx];
}
private:
/// Stores the ac3d file reader options, only used for reading texture files
osg::ref_ptr<osgDB::ReaderWriter::Options const> mOptions;
/// The list of ac3d MATERIALS
std::vector<MaterialData> mMaterials;
/// Local per model texture attribute cache.
/// ... images are usually cached in the registries object cache
typedef std::map<std::string, TextureData> TextureDataMap;
TextureDataMap mTextureStates;
/// A common shared TexEnv set to modulate
osg::ref_ptr<osg::TexEnv> mModulateTexEnv;
/// Hack to include light nodes from ac3d into the scenegraph
unsigned mLightIndex;
};
struct RefData {
RefData(const osg::Vec3& _weightedNormal, const osg::Vec2& _texCoord, bool _smooth) :
weightedFlatNormal(_weightedNormal),
weightedFlatNormalLength(_weightedNormal.length()),
texCoord(_texCoord),
smooth(_smooth)
{ }
// weighted flat surface normal
osg::Vec3 weightedFlatNormal;
float weightedFlatNormalLength;
osg::Vec2 texCoord;
// resulting vertex normal
osg::Vec3 finalNormal;
// if zero no need to smooth
unsigned smooth;
};
struct VertexData {
VertexData(const osg::Vec3& vertex) : _vertex(vertex) {}
unsigned addRefData(const RefData& refData)
{
unsigned index = _refs.size();
_refs.push_back(refData);
return index;
}
void collect(float cosCreaseAngle, const RefData& ref)
{
unsigned size = _refs.size();
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth == ~0u)
{
float dot = _refs[i].weightedFlatNormal*ref.weightedFlatNormal;
float lengths = _refs[i].weightedFlatNormalLength*ref.weightedFlatNormalLength;
if (cosCreaseAngle*lengths <= dot)
{
// Ok put that into the current set
_refs[i].smooth = ref.smooth;
collect(cosCreaseAngle, _refs[i]);
}
}
}
}
void smoothNormals(float cosCreaseAngle)
{
// compute sets of vertices smoothed to the same normal
// if smooth is zero we do not need to smooth
// in a first pass mark all refs not yet in a set to ~0u
unsigned size = _refs.size();
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth)
{
_refs[i].smooth = ~0u;
}
}
// Now collect the sets
unsigned currentSet = 1;
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth == ~0u)
{
_refs[i].smooth = currentSet++;
collect(cosCreaseAngle, _refs[i]);
}
}
// smooth and normalize the sets
for (--currentSet; 0 < currentSet; --currentSet)
{
osg::Vec3 normal(0, 0, 0);
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth == currentSet)
{
normal += _refs[i].weightedFlatNormal;
}
}
normal.normalize();
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth == currentSet)
{
_refs[i].finalNormal = normal;
}
}
}
// normalize the ones which do not need smoothing
for (unsigned i = 0; i < size; ++i)
{
if (_refs[i].smooth == 0)
{
_refs[i].finalNormal = _refs[i].weightedFlatNormal;
_refs[i].finalNormal.normalize();
}
}
}
osg::Vec3 _vertex;
std::vector<RefData> _refs;
};
struct VertexIndex {
VertexIndex(unsigned _vertexIndex = 0, unsigned _refIndex = 0) :
vertexIndex(_vertexIndex), refIndex(_refIndex)
{ }
unsigned vertexIndex;
unsigned refIndex;
};
class VertexSet : public osg::Referenced {
public:
VertexSet() :
_cosCreaseAngle(1.0f),
_dirty(true)
{ }
void reserve(unsigned n)
{
_vertices.reserve(n);
}
unsigned size() const
{
return _vertices.size();
}
void setCreaseAngle(float crease)
{
_dirty = true;
if (crease <= 0)
_cosCreaseAngle = 1.0f;
else if (180 <= crease)
_cosCreaseAngle = -1.0f;
else
_cosCreaseAngle = cosf(osg::DegreesToRadians(crease));
}
void addVertex(const osg::Vec3& vertex)
{
_dirty = true;
_vertices.push_back(vertex);
}
const osg::Vec3& getVertex(unsigned index)
{
return _vertices[index]._vertex;
}
const osg::Vec3& getVertex(const VertexIndex& vertexIndex)
{
return _vertices[vertexIndex.vertexIndex]._vertex;
}
const osg::Vec3& getNormal(const VertexIndex& vertexIndex)
{
if (_dirty)
smoothNormals();
return _vertices[vertexIndex.vertexIndex]._refs[vertexIndex.refIndex].finalNormal;
}
const osg::Vec2& getTexCoord(const VertexIndex& vertexIndex)
{
return _vertices[vertexIndex.vertexIndex]._refs[vertexIndex.refIndex].texCoord;
}
VertexIndex addRefData(unsigned i, const RefData& refData)
{
if (_vertices.size() <= i)
{
OSG_FATAL << "osgDB ac3d reader: internal error, got invalid vertex index!" << std::endl;
return VertexIndex(0, 0);
}
_dirty = true;
return VertexIndex(i, _vertices[i].addRefData(refData));
}
private:
void smoothNormals()
{
std::vector<VertexData>::iterator i;
for (i = _vertices.begin(); i != _vertices.end(); ++i)
{
i->smoothNormals(_cosCreaseAngle);
}
_dirty = false;
}
std::vector<VertexData> _vertices;
float _cosCreaseAngle;
bool _dirty;
};
class PrimitiveBin : public osg::Referenced
{
public:
PrimitiveBin(unsigned flags, VertexSet* vertexSet) :
_geode(new osg::Geode),
_vertexSet(vertexSet),
_flags(flags)
{
_geode->setDataVariance(osg::Object::STATIC);
}
virtual bool beginPrimitive(unsigned nRefs) = 0;
virtual bool vertex(unsigned vertexIndex, const osg::Vec2& texCoord) = 0;
virtual bool endPrimitive() = 0;
virtual osg::Geode* finalize(const MaterialData& material, const TextureData& textureData) = 0;
protected:
bool isLineLoop() const
{
return (_flags & SurfaceTypeLineLoop)!=0;
}
bool isLineStrip() const
{
return (_flags & SurfaceTypeLineStrip)!=0;
}
bool isTwoSided() const
{
return (_flags & SurfaceTwoSided)!=0;
}
bool isSmooth() const
{
return (_flags & SurfaceShaded)!=0;
}
osg::ref_ptr<osg::Geode> _geode;
osg::ref_ptr<VertexSet> _vertexSet;
private:
unsigned _flags;
};
class LineBin : public PrimitiveBin
{
private:
osg::ref_ptr<osg::Geometry> _geometry;
osg::ref_ptr<osg::Vec3Array> _vertices;
osg::ref_ptr<osg::Vec2Array> _texCoords;
struct Ref {
osg::Vec2 texCoord;
unsigned index;
};
std::vector<Ref> _refs;
public:
LineBin(unsigned flags, VertexSet* vertexSet) :
PrimitiveBin(flags, vertexSet),
_geometry(new osg::Geometry),
_vertices(new osg::Vec3Array),
_texCoords(new osg::Vec2Array)
{
_geometry->setDataVariance(osg::Object::STATIC);
_vertices->setDataVariance(osg::Object::STATIC);
_texCoords->setDataVariance(osg::Object::STATIC);
_geometry->setVertexArray(_vertices.get());
_geometry->setTexCoordArray(0, _texCoords.get());
osg::StateSet* stateSet = _geode->getOrCreateStateSet();
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
}
virtual bool beginPrimitive(unsigned nRefs)
{
// Check if we have enough for a line or something broken ...
if (nRefs < 2) {
OSG_WARN << "osgDB ac3d reader: detected line with less than 2 vertices!" << std::endl;
return false;
}
_refs.reserve(nRefs);
_refs.resize(0);
return true;
}
virtual bool vertex(unsigned vertexIndex, const osg::Vec2& texCoord)
{
Ref ref;
ref.index = vertexIndex;
ref.texCoord = texCoord;
_refs.push_back(ref);
return true;
}
virtual bool endPrimitive()
{
GLint type;
if (isLineLoop())
type = osg::PrimitiveSet::LINE_LOOP;
else if (isLineStrip())
type = osg::PrimitiveSet::LINE_STRIP;
else {
OSG_FATAL << "osgDB ac3d reader: non surface flags in surface bin!" << std::endl;
return false;
}
unsigned nRefs = _refs.size();
unsigned start = _vertices->size();
for (unsigned i = 0; i < nRefs; ++i) {
osg::Vec3 vertex = _vertexSet->getVertex(_refs[i].index);
_vertices->push_back(vertex);
_texCoords->push_back(_refs[i].texCoord);
}
_geometry->addPrimitiveSet(new osg::DrawArrays(type, start, nRefs));
return true;
}
virtual osg::Geode* finalize(const MaterialData& material, const TextureData& /*textureData*/)
{
_geode->addDrawable(_geometry.get());
material.toStateSet(_geode->getOrCreateStateSet());
_geometry->setColorArray(material.getColorArray(), osg::Array::BIND_OVERALL);
_geometry->setNormalArray(0);
return _geode.get();
}
};
class SurfaceBin : public PrimitiveBin {
private:
struct Ref {
osg::Vec2 texCoord;
unsigned index;
};
std::vector<Ref> _refs;
struct TriangleData {
VertexIndex index[3];
};
std::vector<TriangleData> _triangles;
struct QuadData {
VertexIndex index[4];
};
std::vector<QuadData> _quads;
struct PolygonData {
std::vector<VertexIndex> index;
};
std::vector<PolygonData> _polygons;
std::vector<PolygonData> _toTessellatePolygons;
typedef std::pair<osg::Vec3, osg::Vec3> VertexNormalPair;
typedef std::pair<VertexNormalPair, osg::Vec2> VertexNormalTexTuple;
typedef std::map<VertexNormalTexTuple, unsigned> VertexIndexMap;
VertexIndexMap _vertexIndexMap;
public:
SurfaceBin(unsigned flags, VertexSet *vertexSet) :
PrimitiveBin(flags, vertexSet)
{ }
virtual bool beginPrimitive(unsigned nRefs)
{
_refs.reserve(nRefs);
_refs.clear();
// Check if we have enough for a line or something broken ...
if (nRefs < 3) {
OSG_WARN << "osgDB ac3d reader: detected surface with less than 3 vertices!" << std::endl;
return false;
}
return true;
}
virtual bool vertex(unsigned vertexIndex, const osg::Vec2& texCoord)
{
Ref ref;
ref.index = vertexIndex;
ref.texCoord = texCoord;
_refs.push_back(ref);
return true;
}
virtual bool endPrimitive()
{
unsigned nRefs = _refs.size();
// Compute the normal times the enclosed area.
// During that check if the surface is convex. If so, put in the surface as such.
bool needTessellation = false;
osg::Vec3 prevEdgeNormal;
osg::Vec3 weightedNormal(0, 0, 0);
osg::Vec3 v0 = _vertexSet->getVertex(_refs[0].index);
for (unsigned i = 2; i < nRefs; ++i) {
osg::Vec3 side1 = _vertexSet->getVertex(_refs[i-1].index) - v0;
osg::Vec3 side2 = _vertexSet->getVertex(_refs[i].index) - v0;
osg::Vec3 newNormal = side1^side2;
if (!needTessellation)
{
if (3 < nRefs && newNormal*weightedNormal < 0)
{
needTessellation = true;
}
if (i < 3)
{
prevEdgeNormal = newNormal;
}
else // if (3 <= i) // due to the for loop
{
osg::Vec3 sideim1 = _vertexSet->getVertex(_refs[i-1].index) - _vertexSet->getVertex(_refs[i-2].index);
osg::Vec3 sidei = _vertexSet->getVertex(_refs[i].index) - _vertexSet->getVertex(_refs[i-2].index);
osg::Vec3 edgeNormal = sideim1^sidei;
if (edgeNormal*prevEdgeNormal < 0)
{
needTessellation = true;
}
prevEdgeNormal = edgeNormal;
}
}
weightedNormal += newNormal;
}
if (needTessellation)
{
unsigned polygonIndex = _toTessellatePolygons.size();
_toTessellatePolygons.resize(polygonIndex + 1);
for (unsigned i = 0; i < nRefs; ++i) {
RefData refData(weightedNormal, _refs[i].texCoord, isSmooth());
VertexIndex vertexIndex = _vertexSet->addRefData(_refs[i].index, refData);
_toTessellatePolygons[polygonIndex].index.push_back(vertexIndex);
}
}
else if (nRefs == 3)
{
unsigned triangleIndex = _triangles.size();
_triangles.resize(triangleIndex + 1);
for (unsigned i = 0; i < 3; ++i) {
RefData refData(weightedNormal, _refs[i].texCoord, isSmooth());
VertexIndex vertexIndex = _vertexSet->addRefData(_refs[i].index, refData);
_triangles[triangleIndex].index[i] = vertexIndex;
}
}
else if (nRefs == 4)
{
unsigned quadIndex = _quads.size();
_quads.resize(quadIndex + 1);
for (unsigned i = 0; i < 4; ++i) {
RefData refData(weightedNormal, _refs[i].texCoord, isSmooth());
VertexIndex vertexIndex = _vertexSet->addRefData(_refs[i].index, refData);
_quads[quadIndex].index[i] = vertexIndex;
}
}
else
{
unsigned polygonIndex = _polygons.size();
_polygons.resize(polygonIndex + 1);
for (unsigned i = 0; i < nRefs; ++i) {
RefData refData(weightedNormal, _refs[i].texCoord, isSmooth());
VertexIndex vertexIndex = _vertexSet->addRefData(_refs[i].index, refData);
_polygons[polygonIndex].index.push_back(vertexIndex);
}
}
return true;
}
unsigned pushVertex(const VertexIndex& vertexIndex, osg::Vec3Array* vertexArray,
osg::Vec3Array* normalArray, osg::Vec2Array* texcoordArray)
{
VertexNormalTexTuple vertexNormalTexTuple;
vertexNormalTexTuple.first.first = _vertexSet->getVertex(vertexIndex);
vertexNormalTexTuple.first.second = _vertexSet->getNormal(vertexIndex);
if (texcoordArray)
vertexNormalTexTuple.second = _vertexSet->getTexCoord(vertexIndex);
else
vertexNormalTexTuple.second = osg::Vec2(0, 0);
VertexIndexMap::iterator i = _vertexIndexMap.find(vertexNormalTexTuple);
if (i != _vertexIndexMap.end())
return i->second;
unsigned index = vertexArray->size();
vertexArray->push_back(vertexNormalTexTuple.first.first);
normalArray->push_back(vertexNormalTexTuple.first.second);
if (texcoordArray)
texcoordArray->push_back(vertexNormalTexTuple.second);
_vertexIndexMap.insert(VertexIndexMap::value_type(vertexNormalTexTuple, index));
return index;
}
osg::DrawElements* createOptimalDrawElements(osg::DrawElementsUInt* drawElements)
{
unsigned num = drawElements->getNumIndices();
unsigned maxIndex = 0;
for (unsigned i = 0; i < num; ++i)
{
maxIndex = osg::maximum(maxIndex, drawElements->getElement(i));
}
if (maxIndex <= std::numeric_limits<unsigned char>::max())
{
osg::DrawElementsUByte* drawElementsUByte = new osg::DrawElementsUByte(drawElements->getMode());
drawElementsUByte->reserveElements(num);
for (unsigned i = 0; i < num; ++i)
{
drawElementsUByte->addElement(drawElements->getElement(i));
}
return drawElementsUByte;
}
else if (maxIndex <= std::numeric_limits<unsigned short>::max())
{
osg::DrawElementsUShort* drawElementsUShort = new osg::DrawElementsUShort(drawElements->getMode());
drawElementsUShort->reserveElements(num);
for (unsigned i = 0; i < num; ++i)
{
drawElementsUShort->addElement(drawElements->getElement(i));
}
return drawElementsUShort;
}
else
{
return drawElements;
}
}
virtual osg::Geode* finalize(const MaterialData& material, const TextureData& textureData)
{
osg::StateSet* stateSet = _geode->getOrCreateStateSet();
material.toStateSet(stateSet);
textureData.toTextureStateSet(stateSet);
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::ON);
// Single- or doublesided culling
if (isTwoSided()) {