X3DImporter.cpp 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2017, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /// \file X3DImporter.cpp
  34. /// \brief X3D-format files importer for Assimp: main algorithm implementation.
  35. /// \date 2015-2016
  36. /// \author [email protected]
  37. #ifndef ASSIMP_BUILD_NO_X3D_IMPORTER
  38. #include "X3DImporter.hpp"
  39. #include "X3DImporter_Macro.hpp"
  40. #include "StringUtils.h"
  41. // Header files, Assimp.
  42. #include <assimp/DefaultIOSystem.h>
  43. #include "fast_atof.h"
  44. #include "FIReader.hpp"
  45. // Header files, stdlib.
  46. #include <memory>
  47. #include <string>
  48. namespace Assimp {
  49. /// \var aiImporterDesc X3DImporter::Description
  50. /// Constant which holds the importer description
  51. const aiImporterDesc X3DImporter::Description = {
  52. "Extensible 3D(X3D) Importer",
  53. "smalcom",
  54. "",
  55. "See documentation in source code. Chapter: Limitations.",
  56. aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_LimitedSupport | aiImporterFlags_Experimental,
  57. 0,
  58. 0,
  59. 0,
  60. 0,
  61. "x3d x3db"
  62. };
  63. const std::regex X3DImporter::pattern_nws(R"([^, \t\r\n]+)");
  64. const std::regex X3DImporter::pattern_true(R"(^\s*(?:true|1)\s*$)", std::regex::icase);
  65. X3DImporter::X3DImporter()
  66. : NodeElement_Cur( nullptr )
  67. , mReader( nullptr ) {
  68. // empty
  69. }
  70. X3DImporter::~X3DImporter() {
  71. // Clear() is accounting if data already is deleted. So, just check again if all data is deleted.
  72. Clear();
  73. }
  74. void X3DImporter::Clear() {
  75. NodeElement_Cur = nullptr;
  76. // Delete all elements
  77. if(NodeElement_List.size()) {
  78. for ( std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++ ) {
  79. delete *it;
  80. }
  81. NodeElement_List.clear();
  82. }
  83. }
  84. /*********************************************************************************************************************************************/
  85. /************************************************************ Functions: find set ************************************************************/
  86. /*********************************************************************************************************************************************/
  87. bool X3DImporter::FindNodeElement_FromRoot(const std::string& pID, const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  88. {
  89. for(std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++)
  90. {
  91. if(((*it)->Type == pType) && ((*it)->ID == pID))
  92. {
  93. if(pElement != nullptr) *pElement = *it;
  94. return true;
  95. }
  96. }// for(std::list<CX3DImporter_NodeElement*>::iterator it = NodeElement_List.begin(); it != NodeElement_List.end(); it++)
  97. return false;
  98. }
  99. bool X3DImporter::FindNodeElement_FromNode(CX3DImporter_NodeElement* pStartNode, const std::string& pID,
  100. const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  101. {
  102. bool found = false;// flag: true - if requested element is found.
  103. // Check if pStartNode - this is the element, we are looking for.
  104. if((pStartNode->Type == pType) && (pStartNode->ID == pID))
  105. {
  106. found = true;
  107. if ( pElement != nullptr )
  108. {
  109. *pElement = pStartNode;
  110. }
  111. goto fne_fn_end;
  112. }// if((pStartNode->Type() == pType) && (pStartNode->ID() == pID))
  113. // Check childs of pStartNode.
  114. for(std::list<CX3DImporter_NodeElement*>::iterator ch_it = pStartNode->Child.begin(); ch_it != pStartNode->Child.end(); ch_it++)
  115. {
  116. found = FindNodeElement_FromNode(*ch_it, pID, pType, pElement);
  117. if ( found )
  118. {
  119. break;
  120. }
  121. }// for(std::list<CX3DImporter_NodeElement*>::iterator ch_it = it->Child.begin(); ch_it != it->Child.end(); ch_it++)
  122. fne_fn_end:
  123. return found;
  124. }
  125. bool X3DImporter::FindNodeElement(const std::string& pID, const CX3DImporter_NodeElement::EType pType, CX3DImporter_NodeElement** pElement)
  126. {
  127. CX3DImporter_NodeElement* tnd = NodeElement_Cur;// temporary pointer to node.
  128. bool static_search = false;// flag: true if searching in static node.
  129. // At first check if we have deal with static node. Go up through parent nodes and check flag.
  130. while(tnd != nullptr)
  131. {
  132. if(tnd->Type == CX3DImporter_NodeElement::ENET_Group)
  133. {
  134. if(((CX3DImporter_NodeElement_Group*)tnd)->Static)
  135. {
  136. static_search = true;// Flag found, stop walking up. Node with static flag will holded in tnd variable.
  137. break;
  138. }
  139. }
  140. tnd = tnd->Parent;// go up in graph.
  141. }// while(tnd != nullptr)
  142. // at now call appropriate search function.
  143. if ( static_search )
  144. {
  145. return FindNodeElement_FromNode( tnd, pID, pType, pElement );
  146. }
  147. else
  148. {
  149. return FindNodeElement_FromRoot( pID, pType, pElement );
  150. }
  151. }
  152. /*********************************************************************************************************************************************/
  153. /************************************************************ Functions: throw set ***********************************************************/
  154. /*********************************************************************************************************************************************/
  155. void X3DImporter::Throw_ArgOutOfRange(const std::string& pArgument)
  156. {
  157. throw DeadlyImportError("Argument value is out of range for: \"" + pArgument + "\".");
  158. }
  159. void X3DImporter::Throw_CloseNotFound(const std::string& pNode)
  160. {
  161. throw DeadlyImportError("Close tag for node <" + pNode + "> not found. Seems file is corrupt.");
  162. }
  163. void X3DImporter::Throw_ConvertFail_Str2ArrF(const std::string& pAttrValue)
  164. {
  165. throw DeadlyImportError("In <" + std::string(mReader->getNodeName()) + "> failed to convert attribute value \"" + pAttrValue +
  166. "\" from string to array of floats.");
  167. }
  168. void X3DImporter::Throw_DEF_And_USE()
  169. {
  170. throw DeadlyImportError("\"DEF\" and \"USE\" can not be defined both in <" + std::string(mReader->getNodeName()) + ">.");
  171. }
  172. void X3DImporter::Throw_IncorrectAttr(const std::string& pAttrName)
  173. {
  174. throw DeadlyImportError("Node <" + std::string(mReader->getNodeName()) + "> has incorrect attribute \"" + pAttrName + "\".");
  175. }
  176. void X3DImporter::Throw_IncorrectAttrValue(const std::string& pAttrName)
  177. {
  178. throw DeadlyImportError("Attribute \"" + pAttrName + "\" in node <" + std::string(mReader->getNodeName()) + "> has incorrect value.");
  179. }
  180. void X3DImporter::Throw_MoreThanOnceDefined(const std::string& pNodeType, const std::string& pDescription)
  181. {
  182. throw DeadlyImportError("\"" + pNodeType + "\" node can be used only once in " + mReader->getNodeName() + ". Description: " + pDescription);
  183. }
  184. void X3DImporter::Throw_TagCountIncorrect(const std::string& pNode)
  185. {
  186. throw DeadlyImportError("Count of open and close tags for node <" + pNode + "> are not equivalent. Seems file is corrupt.");
  187. }
  188. void X3DImporter::Throw_USE_NotFound(const std::string& pAttrValue)
  189. {
  190. throw DeadlyImportError("Not found node with name \"" + pAttrValue + "\" in <" + std::string(mReader->getNodeName()) + ">.");
  191. }
  192. /*********************************************************************************************************************************************/
  193. /************************************************************* Functions: XML set ************************************************************/
  194. /*********************************************************************************************************************************************/
  195. void X3DImporter::XML_CheckNode_MustBeEmpty()
  196. {
  197. if(!mReader->isEmptyElement()) throw DeadlyImportError(std::string("Node <") + mReader->getNodeName() + "> must be empty.");
  198. }
  199. void X3DImporter::XML_CheckNode_SkipUnsupported(const std::string& pParentNodeName)
  200. {
  201. static const size_t Uns_Skip_Len = 192;
  202. const char* Uns_Skip[ Uns_Skip_Len ] = {
  203. // CAD geometry component
  204. "CADAssembly", "CADFace", "CADLayer", "CADPart", "IndexedQuadSet", "QuadSet",
  205. // Core
  206. "ROUTE", "ExternProtoDeclare", "ProtoDeclare", "ProtoInstance", "ProtoInterface", "WorldInfo",
  207. // Distributed interactive simulation (DIS) component
  208. "DISEntityManager", "DISEntityTypeMapping", "EspduTransform", "ReceiverPdu", "SignalPdu", "TransmitterPdu",
  209. // Cube map environmental texturing component
  210. "ComposedCubeMapTexture", "GeneratedCubeMapTexture", "ImageCubeMapTexture",
  211. // Environmental effects component
  212. "Background", "Fog", "FogCoordinate", "LocalFog", "TextureBackground",
  213. // Environmental sensor component
  214. "ProximitySensor", "TransformSensor", "VisibilitySensor",
  215. // Followers component
  216. "ColorChaser", "ColorDamper", "CoordinateChaser", "CoordinateDamper", "OrientationChaser", "OrientationDamper", "PositionChaser", "PositionChaser2D",
  217. "PositionDamper", "PositionDamper2D", "ScalarChaser", "ScalarDamper", "TexCoordChaser2D", "TexCoordDamper2D",
  218. // Geospatial component
  219. "GeoCoordinate", "GeoElevationGrid", "GeoLocation", "GeoLOD", "GeoMetadata", "GeoOrigin", "GeoPositionInterpolator", "GeoProximitySensor",
  220. "GeoTouchSensor", "GeoTransform", "GeoViewpoint",
  221. // Humanoid Animation (H-Anim) component
  222. "HAnimDisplacer", "HAnimHumanoid", "HAnimJoint", "HAnimSegment", "HAnimSite",
  223. // Interpolation component
  224. "ColorInterpolator", "CoordinateInterpolator", "CoordinateInterpolator2D", "EaseInEaseOut", "NormalInterpolator", "OrientationInterpolator",
  225. "PositionInterpolator", "PositionInterpolator2D", "ScalarInterpolator", "SplinePositionInterpolator", "SplinePositionInterpolator2D",
  226. "SplineScalarInterpolator", "SquadOrientationInterpolator",
  227. // Key device sensor component
  228. "KeySensor", "StringSensor",
  229. // Layering component
  230. "Layer", "LayerSet", "Viewport",
  231. // Layout component
  232. "Layout", "LayoutGroup", "LayoutLayer", "ScreenFontStyle", "ScreenGroup",
  233. // Navigation component
  234. "Billboard", "Collision", "LOD", "NavigationInfo", "OrthoViewpoint", "Viewpoint", "ViewpointGroup",
  235. // Networking component
  236. "EXPORT", "IMPORT", "Anchor", "LoadSensor",
  237. // NURBS component
  238. "Contour2D", "ContourPolyline2D", "CoordinateDouble", "NurbsCurve", "NurbsCurve2D", "NurbsOrientationInterpolator", "NurbsPatchSurface",
  239. "NurbsPositionInterpolator", "NurbsSet", "NurbsSurfaceInterpolator", "NurbsSweptSurface", "NurbsSwungSurface", "NurbsTextureCoordinate",
  240. "NurbsTrimmedSurface",
  241. // Particle systems component
  242. "BoundedPhysicsModel", "ConeEmitter", "ExplosionEmitter", "ForcePhysicsModel", "ParticleSystem", "PointEmitter", "PolylineEmitter", "SurfaceEmitter",
  243. "VolumeEmitter", "WindPhysicsModel",
  244. // Picking component
  245. "LinePickSensor", "PickableGroup", "PointPickSensor", "PrimitivePickSensor", "VolumePickSensor",
  246. // Pointing device sensor component
  247. "CylinderSensor", "PlaneSensor", "SphereSensor", "TouchSensor",
  248. // Rendering component
  249. "ClipPlane",
  250. // Rigid body physics
  251. "BallJoint", "CollidableOffset", "CollidableShape", "CollisionCollection", "CollisionSensor", "CollisionSpace", "Contact", "DoubleAxisHingeJoint",
  252. "MotorJoint", "RigidBody", "RigidBodyCollection", "SingleAxisHingeJoint", "SliderJoint", "UniversalJoint",
  253. // Scripting component
  254. "Script",
  255. // Programmable shaders component
  256. "ComposedShader", "FloatVertexAttribute", "Matrix3VertexAttribute", "Matrix4VertexAttribute", "PackagedShader", "ProgramShader", "ShaderPart",
  257. "ShaderProgram",
  258. // Shape component
  259. "FillProperties", "LineProperties", "TwoSidedMaterial",
  260. // Sound component
  261. "AudioClip", "Sound",
  262. // Text component
  263. "FontStyle", "Text",
  264. // Texturing3D Component
  265. "ComposedTexture3D", "ImageTexture3D", "PixelTexture3D", "TextureCoordinate3D", "TextureCoordinate4D", "TextureTransformMatrix3D", "TextureTransform3D",
  266. // Texturing component
  267. "MovieTexture", "MultiTexture", "MultiTextureCoordinate", "MultiTextureTransform", "PixelTexture", "TextureCoordinateGenerator", "TextureProperties",
  268. // Time component
  269. "TimeSensor",
  270. // Event Utilities component
  271. "BooleanFilter", "BooleanSequencer", "BooleanToggle", "BooleanTrigger", "IntegerSequencer", "IntegerTrigger", "TimeTrigger",
  272. // Volume rendering component
  273. "BlendedVolumeStyle", "BoundaryEnhancementVolumeStyle", "CartoonVolumeStyle", "ComposedVolumeStyle", "EdgeEnhancementVolumeStyle", "IsoSurfaceVolumeData",
  274. "OpacityMapVolumeStyle", "ProjectionVolumeStyle", "SegmentedVolumeData", "ShadedVolumeStyle", "SilhouetteEnhancementVolumeStyle", "ToneMappedVolumeStyle",
  275. "VolumeData"
  276. };
  277. const std::string nn( mReader->getNodeName() );
  278. bool found = false;
  279. bool close_found = false;
  280. for(size_t i = 0; i < Uns_Skip_Len; i++)
  281. {
  282. if(nn == Uns_Skip[i])
  283. {
  284. found = true;
  285. if(mReader->isEmptyElement())
  286. {
  287. close_found = true;
  288. goto casu_cres;
  289. }
  290. while(mReader->read())
  291. {
  292. if((mReader->getNodeType() == irr::io::EXN_ELEMENT_END) && (nn == mReader->getNodeName()))
  293. {
  294. close_found = true;
  295. goto casu_cres;
  296. }
  297. }
  298. }
  299. }
  300. casu_cres:
  301. if(!found) throw DeadlyImportError("Unknown node \"" + nn + "\" in " + pParentNodeName + ".");
  302. if(close_found)
  303. LogInfo("Skipping node \"" + nn + "\" in " + pParentNodeName + ".");
  304. else
  305. Throw_CloseNotFound(nn);
  306. }
  307. bool X3DImporter::XML_SearchNode(const std::string& pNodeName)
  308. {
  309. while(mReader->read())
  310. {
  311. if((mReader->getNodeType() == irr::io::EXN_ELEMENT) && XML_CheckNode_NameEqual(pNodeName)) return true;
  312. }
  313. return false;
  314. }
  315. bool X3DImporter::XML_ReadNode_GetAttrVal_AsBool(const int pAttrIdx)
  316. {
  317. auto boolValue = std::dynamic_pointer_cast<const FIBoolValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  318. if (boolValue) {
  319. if (boolValue->value.size() == 1) {
  320. return boolValue->value.front();
  321. }
  322. throw DeadlyImportError("Invalid bool value");
  323. }
  324. else {
  325. std::string val(mReader->getAttributeValue(pAttrIdx));
  326. if(val == "false")
  327. return false;
  328. else if(val == "true")
  329. return true;
  330. else
  331. throw DeadlyImportError("Bool attribute value can contain \"false\" or \"true\" not the \"" + val + "\"");
  332. }
  333. }
  334. float X3DImporter::XML_ReadNode_GetAttrVal_AsFloat(const int pAttrIdx)
  335. {
  336. auto floatValue = std::dynamic_pointer_cast<const FIFloatValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  337. if (floatValue) {
  338. if (floatValue->value.size() == 1) {
  339. return floatValue->value.front();
  340. }
  341. throw DeadlyImportError("Invalid float value");
  342. }
  343. else {
  344. std::string val;
  345. float tvalf;
  346. ParseHelper_FixTruncatedFloatString(mReader->getAttributeValue(pAttrIdx), val);
  347. fast_atoreal_move(val.c_str(), tvalf, false);
  348. return tvalf;
  349. }
  350. }
  351. int32_t X3DImporter::XML_ReadNode_GetAttrVal_AsI32(const int pAttrIdx)
  352. {
  353. auto intValue = std::dynamic_pointer_cast<const FIIntValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  354. if (intValue) {
  355. if (intValue->value.size() == 1) {
  356. return intValue->value.front();
  357. }
  358. throw DeadlyImportError("Invalid int value");
  359. }
  360. else {
  361. return strtol10(mReader->getAttributeValue(pAttrIdx));
  362. }
  363. }
  364. void X3DImporter::XML_ReadNode_GetAttrVal_AsCol3f(const int pAttrIdx, aiColor3D& pValue)
  365. {
  366. std::vector<float> tlist;
  367. std::vector<float>::iterator it;
  368. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  369. if(tlist.size() != 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  370. it = tlist.begin();
  371. pValue.r = *it++;
  372. pValue.g = *it++;
  373. pValue.b = *it;
  374. }
  375. void X3DImporter::XML_ReadNode_GetAttrVal_AsVec2f(const int pAttrIdx, aiVector2D& pValue)
  376. {
  377. std::vector<float> tlist;
  378. std::vector<float>::iterator it;
  379. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  380. if(tlist.size() != 2) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  381. it = tlist.begin();
  382. pValue.x = *it++;
  383. pValue.y = *it;
  384. }
  385. void X3DImporter::XML_ReadNode_GetAttrVal_AsVec3f(const int pAttrIdx, aiVector3D& pValue)
  386. {
  387. std::vector<float> tlist;
  388. std::vector<float>::iterator it;
  389. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);
  390. if(tlist.size() != 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  391. it = tlist.begin();
  392. pValue.x = *it++;
  393. pValue.y = *it++;
  394. pValue.z = *it;
  395. }
  396. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrB(const int pAttrIdx, std::vector<bool>& pValue)
  397. {
  398. auto boolValue = std::dynamic_pointer_cast<const FIBoolValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  399. if (boolValue) {
  400. pValue = boolValue->value;
  401. }
  402. else {
  403. const char *val = mReader->getAttributeValue(pAttrIdx);
  404. std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  405. const std::cregex_iterator wordItEnd;
  406. pValue.clear();
  407. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::regex_match(match.str(), pattern_true); });
  408. }
  409. }
  410. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrI32(const int pAttrIdx, std::vector<int32_t>& pValue)
  411. {
  412. auto intValue = std::dynamic_pointer_cast<const FIIntValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  413. if (intValue) {
  414. pValue = intValue->value;
  415. }
  416. else {
  417. const char *val = mReader->getAttributeValue(pAttrIdx);
  418. std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  419. const std::cregex_iterator wordItEnd;
  420. pValue.clear();
  421. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stoi(match.str()); });
  422. }
  423. }
  424. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrF(const int pAttrIdx, std::vector<float>& pValue)
  425. {
  426. auto floatValue = std::dynamic_pointer_cast<const FIFloatValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  427. if (floatValue) {
  428. pValue = floatValue->value;
  429. }
  430. else {
  431. const char *val = mReader->getAttributeValue(pAttrIdx);
  432. std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  433. const std::cregex_iterator wordItEnd;
  434. pValue.clear();
  435. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stof(match.str()); });
  436. }
  437. }
  438. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrD(const int pAttrIdx, std::vector<double>& pValue)
  439. {
  440. auto doubleValue = std::dynamic_pointer_cast<const FIDoubleValue>(mReader->getAttributeEncodedValue(pAttrIdx));
  441. if (doubleValue) {
  442. pValue = doubleValue->value;
  443. }
  444. else {
  445. const char *val = mReader->getAttributeValue(pAttrIdx);
  446. std::cregex_iterator wordItBegin(val, val + strlen(val), pattern_nws);
  447. const std::cregex_iterator wordItEnd;
  448. pValue.clear();
  449. std::transform(wordItBegin, wordItEnd, std::back_inserter(pValue), [](const std::cmatch &match) { return std::stod(match.str()); });
  450. }
  451. }
  452. void X3DImporter::XML_ReadNode_GetAttrVal_AsListCol3f(const int pAttrIdx, std::list<aiColor3D>& pValue)
  453. {
  454. std::vector<float> tlist;
  455. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  456. if(tlist.size() % 3) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  457. // copy data to array
  458. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  459. {
  460. aiColor3D tcol;
  461. tcol.r = *it++;
  462. tcol.g = *it++;
  463. tcol.b = *it++;
  464. pValue.push_back(tcol);
  465. }
  466. }
  467. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol3f(const int pAttrIdx, std::vector<aiColor3D>& pValue)
  468. {
  469. std::list<aiColor3D> tlist;
  470. XML_ReadNode_GetAttrVal_AsListCol3f(pAttrIdx, tlist);// read as list
  471. // and copy to array
  472. if(tlist.size() > 0)
  473. {
  474. pValue.reserve(tlist.size());
  475. for(std::list<aiColor3D>::iterator it = tlist.begin(); it != tlist.end(); it++) pValue.push_back(*it);
  476. }
  477. }
  478. void X3DImporter::XML_ReadNode_GetAttrVal_AsListCol4f(const int pAttrIdx, std::list<aiColor4D>& pValue)
  479. {
  480. std::vector<float> tlist;
  481. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  482. if(tlist.size() % 4) Throw_ConvertFail_Str2ArrF(mReader->getAttributeValue(pAttrIdx));
  483. // copy data to array
  484. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  485. {
  486. aiColor4D tcol;
  487. tcol.r = *it++;
  488. tcol.g = *it++;
  489. tcol.b = *it++;
  490. tcol.a = *it++;
  491. pValue.push_back(tcol);
  492. }
  493. }
  494. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrCol4f(const int pAttrIdx, std::vector<aiColor4D>& pValue)
  495. {
  496. std::list<aiColor4D> tlist;
  497. XML_ReadNode_GetAttrVal_AsListCol4f(pAttrIdx, tlist);// read as list
  498. // and copy to array
  499. if(tlist.size() > 0)
  500. {
  501. pValue.reserve(tlist.size());
  502. for ( std::list<aiColor4D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  503. {
  504. pValue.push_back( *it );
  505. }
  506. }
  507. }
  508. void X3DImporter::XML_ReadNode_GetAttrVal_AsListVec2f(const int pAttrIdx, std::list<aiVector2D>& pValue)
  509. {
  510. std::vector<float> tlist;
  511. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  512. if ( tlist.size() % 2 )
  513. {
  514. Throw_ConvertFail_Str2ArrF( mReader->getAttributeValue( pAttrIdx ) );
  515. }
  516. // copy data to array
  517. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  518. {
  519. aiVector2D tvec;
  520. tvec.x = *it++;
  521. tvec.y = *it++;
  522. pValue.push_back(tvec);
  523. }
  524. }
  525. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec2f(const int pAttrIdx, std::vector<aiVector2D>& pValue)
  526. {
  527. std::list<aiVector2D> tlist;
  528. XML_ReadNode_GetAttrVal_AsListVec2f(pAttrIdx, tlist);// read as list
  529. // and copy to array
  530. if(tlist.size() > 0)
  531. {
  532. pValue.reserve(tlist.size());
  533. for ( std::list<aiVector2D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  534. {
  535. pValue.push_back( *it );
  536. }
  537. }
  538. }
  539. void X3DImporter::XML_ReadNode_GetAttrVal_AsListVec3f(const int pAttrIdx, std::list<aiVector3D>& pValue)
  540. {
  541. std::vector<float> tlist;
  542. XML_ReadNode_GetAttrVal_AsArrF(pAttrIdx, tlist);// read as list
  543. if ( tlist.size() % 3 )
  544. {
  545. Throw_ConvertFail_Str2ArrF( mReader->getAttributeValue( pAttrIdx ) );
  546. }
  547. // copy data to array
  548. for(std::vector<float>::iterator it = tlist.begin(); it != tlist.end();)
  549. {
  550. aiVector3D tvec;
  551. tvec.x = *it++;
  552. tvec.y = *it++;
  553. tvec.z = *it++;
  554. pValue.push_back(tvec);
  555. }
  556. }
  557. void X3DImporter::XML_ReadNode_GetAttrVal_AsArrVec3f(const int pAttrIdx, std::vector<aiVector3D>& pValue)
  558. {
  559. std::list<aiVector3D> tlist;
  560. XML_ReadNode_GetAttrVal_AsListVec3f(pAttrIdx, tlist);// read as list
  561. // and copy to array
  562. if(tlist.size() > 0)
  563. {
  564. pValue.reserve(tlist.size());
  565. for ( std::list<aiVector3D>::iterator it = tlist.begin(); it != tlist.end(); it++ )
  566. {
  567. pValue.push_back( *it );
  568. }
  569. }
  570. }
  571. void X3DImporter::XML_ReadNode_GetAttrVal_AsListS(const int pAttrIdx, std::list<std::string>& pValue)
  572. {
  573. // make copy of attribute value - strings list.
  574. const size_t tok_str_len = strlen(mReader->getAttributeValue(pAttrIdx));
  575. if ( 0 == tok_str_len )
  576. {
  577. Throw_IncorrectAttrValue( mReader->getAttributeName( pAttrIdx ) );
  578. }
  579. // get pointer to begin of value.
  580. char *tok_str = const_cast<char*>(mReader->getAttributeValue(pAttrIdx));
  581. char *tok_str_end = tok_str + tok_str_len;
  582. // string list has following format: attr_name='"s1" "s2" "sn"'.
  583. do
  584. {
  585. char* tbeg;
  586. char* tend;
  587. size_t tlen;
  588. std::string tstr;
  589. // find begin of string(element of string list): "sn".
  590. tbeg = strstr(tok_str, "\"");
  591. if(tbeg == nullptr) Throw_IncorrectAttrValue(mReader->getAttributeName(pAttrIdx));
  592. tbeg++;// forward pointer from '\"' symbol to next after it.
  593. tok_str = tbeg;
  594. // find end of string(element of string list): "sn".
  595. tend = strstr(tok_str, "\"");
  596. if(tend == nullptr) Throw_IncorrectAttrValue(mReader->getAttributeName(pAttrIdx));
  597. tok_str = tend + 1;
  598. // create storage for new string
  599. tlen = tend - tbeg;
  600. tstr.resize(tlen);// reserve enough space and copy data
  601. memcpy((void*)tstr.data(), tbeg, tlen);// not strcpy because end of copied string from tok_str has no terminator.
  602. // and store string in output list.
  603. pValue.push_back(tstr);
  604. } while(tok_str < tok_str_end);
  605. }
  606. /*********************************************************************************************************************************************/
  607. /****************************************************** Functions: geometry helper set ******************************************************/
  608. /*********************************************************************************************************************************************/
  609. aiVector3D X3DImporter::GeometryHelper_Make_Point2D(const float pAngle, const float pRadius)
  610. {
  611. return aiVector3D(pRadius * std::cos(pAngle), pRadius * std::sin(pAngle), 0);
  612. }
  613. void X3DImporter::GeometryHelper_Make_Arc2D(const float pStartAngle, const float pEndAngle, const float pRadius, size_t pNumSegments,
  614. std::list<aiVector3D>& pVertices)
  615. {
  616. // check argument values ranges.
  617. if ( ( pStartAngle < -AI_MATH_TWO_PI_F ) || ( pStartAngle > AI_MATH_TWO_PI_F ) )
  618. {
  619. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pStartAngle" );
  620. }
  621. if ( ( pEndAngle < -AI_MATH_TWO_PI_F ) || ( pEndAngle > AI_MATH_TWO_PI_F ) )
  622. {
  623. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pEndAngle" );
  624. }
  625. if ( pRadius <= 0 )
  626. {
  627. Throw_ArgOutOfRange( "GeometryHelper_Make_Arc2D.pRadius" );
  628. }
  629. // calculate arc angle and check type of arc
  630. float angle_full = std::fabs(pEndAngle - pStartAngle);
  631. if ( ( angle_full > AI_MATH_TWO_PI_F ) || ( angle_full == 0.0f ) )
  632. {
  633. angle_full = AI_MATH_TWO_PI_F;
  634. }
  635. // calculate angle for one step - angle to next point of line.
  636. float angle_step = angle_full / (float)pNumSegments;
  637. // make points
  638. for(size_t pi = 0; pi <= pNumSegments; pi++)
  639. {
  640. float tangle = pStartAngle + pi * angle_step;
  641. pVertices.push_back(GeometryHelper_Make_Point2D(tangle, pRadius));
  642. }// for(size_t pi = 0; pi <= pNumSegments; pi++)
  643. // if we making full circle then add last vertex equal to first vertex
  644. if(angle_full == AI_MATH_TWO_PI_F) pVertices.push_back(*pVertices.begin());
  645. }
  646. void X3DImporter::GeometryHelper_Extend_PointToLine(const std::list<aiVector3D>& pPoint, std::list<aiVector3D>& pLine)
  647. {
  648. std::list<aiVector3D>::const_iterator pit = pPoint.begin();
  649. std::list<aiVector3D>::const_iterator pit_last = pPoint.end();
  650. pit_last--;
  651. if ( pPoint.size() < 2 )
  652. {
  653. Throw_ArgOutOfRange( "GeometryHelper_Extend_PointToLine.pPoint.size() can not be less than 2." );
  654. }
  655. // add first point of first line.
  656. pLine.push_back(*pit++);
  657. // add internal points
  658. while(pit != pit_last)
  659. {
  660. pLine.push_back(*pit);// second point of previous line
  661. pLine.push_back(*pit);// first point of next line
  662. pit++;
  663. }
  664. // add last point of last line
  665. pLine.push_back(*pit);
  666. }
  667. void X3DImporter::GeometryHelper_Extend_PolylineIdxToLineIdx(const std::list<int32_t>& pPolylineCoordIdx, std::list<int32_t>& pLineCoordIdx)
  668. {
  669. std::list<int32_t>::const_iterator plit = pPolylineCoordIdx.begin();
  670. while(plit != pPolylineCoordIdx.end())
  671. {
  672. // add first point of polyline
  673. pLineCoordIdx.push_back(*plit++);
  674. while((*plit != (-1)) && (plit != pPolylineCoordIdx.end()))
  675. {
  676. std::list<int32_t>::const_iterator plit_next;
  677. plit_next = plit, plit_next++;
  678. pLineCoordIdx.push_back(*plit);// second point of previous line.
  679. pLineCoordIdx.push_back(-1);// delimiter
  680. if((*plit_next == (-1)) || (plit_next == pPolylineCoordIdx.end())) break;// current polyline is finished
  681. pLineCoordIdx.push_back(*plit);// first point of next line.
  682. plit = plit_next;
  683. }// while((*plit != (-1)) && (plit != pPolylineCoordIdx.end()))
  684. }// while(plit != pPolylineCoordIdx.end())
  685. }
  686. #define MESH_RectParallelepiped_CREATE_VERT \
  687. aiVector3D vert_set[8]; \
  688. float x1, x2, y1, y2, z1, z2, hs; \
  689. \
  690. hs = pSize.x / 2, x1 = -hs, x2 = hs; \
  691. hs = pSize.y / 2, y1 = -hs, y2 = hs; \
  692. hs = pSize.z / 2, z1 = -hs, z2 = hs; \
  693. vert_set[0].Set(x2, y1, z2); \
  694. vert_set[1].Set(x2, y2, z2); \
  695. vert_set[2].Set(x2, y2, z1); \
  696. vert_set[3].Set(x2, y1, z1); \
  697. vert_set[4].Set(x1, y1, z2); \
  698. vert_set[5].Set(x1, y2, z2); \
  699. vert_set[6].Set(x1, y2, z1); \
  700. vert_set[7].Set(x1, y1, z1)
  701. void X3DImporter::GeometryHelper_MakeQL_RectParallelepiped(const aiVector3D& pSize, std::list<aiVector3D>& pVertices)
  702. {
  703. MESH_RectParallelepiped_CREATE_VERT;
  704. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 3, 2, 1, 0);// front
  705. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 6, 7, 4, 5);// back
  706. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 7, 3, 0, 4);// left
  707. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 2, 6, 5, 1);// right
  708. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 0, 1, 5, 4);// top
  709. MACRO_FACE_ADD_QUAD_FA(true, pVertices, vert_set, 7, 6, 2, 3);// bottom
  710. }
  711. #undef MESH_RectParallelepiped_CREATE_VERT
  712. void X3DImporter::GeometryHelper_CoordIdxStr2FacesArr(const std::vector<int32_t>& pCoordIdx, std::vector<aiFace>& pFaces, unsigned int& pPrimitiveTypes) const
  713. {
  714. std::vector<int32_t> f_data(pCoordIdx);
  715. std::vector<unsigned int> inds;
  716. unsigned int prim_type = 0;
  717. if ( f_data.back() != ( -1 ) )
  718. {
  719. f_data.push_back( -1 );
  720. }
  721. // reserve average size.
  722. pFaces.reserve(f_data.size() / 3);
  723. inds.reserve(4);
  724. //PrintVectorSet("build. ci", pCoordIdx);
  725. for(std::vector<int32_t>::iterator it = f_data.begin(); it != f_data.end(); it++)
  726. {
  727. // when face is got count how many indices in it.
  728. if(*it == (-1))
  729. {
  730. aiFace tface;
  731. size_t ts;
  732. ts = inds.size();
  733. switch(ts)
  734. {
  735. case 0: goto mg_m_err;
  736. case 1: prim_type |= aiPrimitiveType_POINT; break;
  737. case 2: prim_type |= aiPrimitiveType_LINE; break;
  738. case 3: prim_type |= aiPrimitiveType_TRIANGLE; break;
  739. default: prim_type |= aiPrimitiveType_POLYGON; break;
  740. }
  741. tface.mNumIndices = static_cast<unsigned int>(ts);
  742. tface.mIndices = new unsigned int[ts];
  743. memcpy(tface.mIndices, inds.data(), ts * sizeof(unsigned int));
  744. pFaces.push_back(tface);
  745. inds.clear();
  746. }// if(*it == (-1))
  747. else
  748. {
  749. inds.push_back(*it);
  750. }// if(*it == (-1)) else
  751. }// for(std::list<int32_t>::iterator it = f_data.begin(); it != f_data.end(); it++)
  752. //PrintVectorSet("build. faces", pCoordIdx);
  753. pPrimitiveTypes = prim_type;
  754. return;
  755. mg_m_err:
  756. for(size_t i = 0, i_e = pFaces.size(); i < i_e; i++) delete [] pFaces.at(i).mIndices;
  757. pFaces.clear();
  758. }
  759. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list<aiColor3D>& pColors, const bool pColorPerVertex) const
  760. {
  761. std::list<aiColor4D> tcol;
  762. // create RGBA array from RGB.
  763. for(std::list<aiColor3D>::const_iterator it = pColors.begin(); it != pColors.end(); it++) tcol.push_back(aiColor4D((*it).r, (*it).g, (*it).b, 1));
  764. // call existing function for adding RGBA colors
  765. MeshGeometry_AddColor(pMesh, tcol, pColorPerVertex);
  766. }
  767. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::list<aiColor4D>& pColors, const bool pColorPerVertex) const
  768. {
  769. std::list<aiColor4D>::const_iterator col_it = pColors.begin();
  770. if(pColorPerVertex)
  771. {
  772. if(pColors.size() < pMesh.mNumVertices)
  773. {
  774. throw DeadlyImportError("MeshGeometry_AddColor1. Colors count(" + to_string(pColors.size()) + ") can not be less than Vertices count(" +
  775. to_string(pMesh.mNumVertices) + ").");
  776. }
  777. // copy colors to mesh
  778. pMesh.mColors[0] = new aiColor4D[pMesh.mNumVertices];
  779. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mColors[0][i] = *col_it++;
  780. }// if(pColorPerVertex)
  781. else
  782. {
  783. if(pColors.size() < pMesh.mNumFaces)
  784. {
  785. throw DeadlyImportError("MeshGeometry_AddColor1. Colors count(" + to_string(pColors.size()) + ") can not be less than Faces count(" +
  786. to_string(pMesh.mNumFaces) + ").");
  787. }
  788. // copy colors to mesh
  789. pMesh.mColors[0] = new aiColor4D[pMesh.mNumVertices];
  790. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  791. {
  792. // apply color to all vertices of face
  793. for ( size_t vi = 0, vi_e = pMesh.mFaces[ fi ].mNumIndices; vi < vi_e; vi++ )
  794. {
  795. pMesh.mColors[ 0 ][ pMesh.mFaces[ fi ].mIndices[ vi ] ] = *col_it;
  796. }
  797. col_it++;
  798. }
  799. }// if(pColorPerVertex) else
  800. }
  801. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pColorIdx,
  802. const std::list<aiColor3D>& pColors, const bool pColorPerVertex) const
  803. {
  804. std::list<aiColor4D> tcol;
  805. // create RGBA array from RGB.
  806. for ( std::list<aiColor3D>::const_iterator it = pColors.begin(); it != pColors.end(); it++ )
  807. {
  808. tcol.push_back( aiColor4D( ( *it ).r, ( *it ).g, ( *it ).b, 1 ) );
  809. }
  810. // call existing function for adding RGBA colors
  811. MeshGeometry_AddColor(pMesh, pCoordIdx, pColorIdx, tcol, pColorPerVertex);
  812. }
  813. void X3DImporter::MeshGeometry_AddColor(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pColorIdx,
  814. const std::list<aiColor4D>& pColors, const bool pColorPerVertex) const
  815. {
  816. std::vector<aiColor4D> col_tgt_arr;
  817. std::list<aiColor4D> col_tgt_list;
  818. std::vector<aiColor4D> col_arr_copy;
  819. if ( pCoordIdx.size() == 0 )
  820. {
  821. throw DeadlyImportError( "MeshGeometry_AddColor2. pCoordIdx can not be empty." );
  822. }
  823. // copy list to array because we are need indexed access to colors.
  824. col_arr_copy.reserve(pColors.size());
  825. for ( std::list<aiColor4D>::const_iterator it = pColors.begin(); it != pColors.end(); it++ )
  826. {
  827. col_arr_copy.push_back( *it );
  828. }
  829. if(pColorPerVertex)
  830. {
  831. if(pColorIdx.size() > 0)
  832. {
  833. // check indices array count.
  834. if(pColorIdx.size() < pCoordIdx.size())
  835. {
  836. throw DeadlyImportError("MeshGeometry_AddColor2. Colors indices count(" + to_string(pColorIdx.size()) +
  837. ") can not be less than Coords inidces count(" + to_string(pCoordIdx.size()) + ").");
  838. }
  839. // create list with colors for every vertex.
  840. col_tgt_arr.resize(pMesh.mNumVertices);
  841. for(std::vector<int32_t>::const_iterator colidx_it = pColorIdx.begin(), coordidx_it = pCoordIdx.begin(); colidx_it != pColorIdx.end(); colidx_it++, coordidx_it++)
  842. {
  843. if ( *colidx_it == ( -1 ) )
  844. {
  845. continue;// skip faces delimiter
  846. }
  847. if ( ( unsigned int ) ( *coordidx_it ) > pMesh.mNumVertices )
  848. {
  849. throw DeadlyImportError( "MeshGeometry_AddColor2. Coordinate idx is out of range." );
  850. }
  851. if ( ( unsigned int ) *colidx_it > pMesh.mNumVertices )
  852. {
  853. throw DeadlyImportError( "MeshGeometry_AddColor2. Color idx is out of range." );
  854. }
  855. col_tgt_arr[*coordidx_it] = col_arr_copy[*colidx_it];
  856. }
  857. }// if(pColorIdx.size() > 0)
  858. else
  859. {
  860. // when color indices list is absent use CoordIdx.
  861. // check indices array count.
  862. if(pColors.size() < pMesh.mNumVertices)
  863. {
  864. throw DeadlyImportError("MeshGeometry_AddColor2. Colors count(" + to_string(pColors.size()) + ") can not be less than Vertices count(" +
  865. to_string(pMesh.mNumVertices) + ").");
  866. }
  867. // create list with colors for every vertex.
  868. col_tgt_arr.resize(pMesh.mNumVertices);
  869. for ( size_t i = 0; i < pMesh.mNumVertices; i++ )
  870. {
  871. col_tgt_arr[ i ] = col_arr_copy[ i ];
  872. }
  873. }// if(pColorIdx.size() > 0) else
  874. }// if(pColorPerVertex)
  875. else
  876. {
  877. if(pColorIdx.size() > 0)
  878. {
  879. // check indices array count.
  880. if(pColorIdx.size() < pMesh.mNumFaces)
  881. {
  882. throw DeadlyImportError("MeshGeometry_AddColor2. Colors indices count(" + to_string(pColorIdx.size()) +
  883. ") can not be less than Faces count(" + to_string(pMesh.mNumFaces) + ").");
  884. }
  885. // create list with colors for every vertex using faces indices.
  886. col_tgt_arr.resize(pMesh.mNumFaces);
  887. std::vector<int32_t>::const_iterator colidx_it = pColorIdx.begin();
  888. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  889. {
  890. if((unsigned int)*colidx_it > pMesh.mNumFaces) throw DeadlyImportError("MeshGeometry_AddColor2. Face idx is out of range.");
  891. col_tgt_arr[fi] = col_arr_copy[*colidx_it++];
  892. }
  893. }// if(pColorIdx.size() > 0)
  894. else
  895. {
  896. // when color indices list is absent use CoordIdx.
  897. // check indices array count.
  898. if(pColors.size() < pMesh.mNumFaces)
  899. {
  900. throw DeadlyImportError("MeshGeometry_AddColor2. Colors count(" + to_string(pColors.size()) + ") can not be less than Faces count(" +
  901. to_string(pMesh.mNumFaces) + ").");
  902. }
  903. // create list with colors for every vertex using faces indices.
  904. col_tgt_arr.resize(pMesh.mNumFaces);
  905. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++) col_tgt_arr[fi] = col_arr_copy[fi];
  906. }// if(pColorIdx.size() > 0) else
  907. }// if(pColorPerVertex) else
  908. // copy array to list for calling function that add colors.
  909. for(std::vector<aiColor4D>::const_iterator it = col_tgt_arr.begin(); it != col_tgt_arr.end(); it++) col_tgt_list.push_back(*it);
  910. // add prepared colors list to mesh.
  911. MeshGeometry_AddColor(pMesh, col_tgt_list, pColorPerVertex);
  912. }
  913. void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pNormalIdx,
  914. const std::list<aiVector3D>& pNormals, const bool pNormalPerVertex) const
  915. {
  916. std::vector<size_t> tind;
  917. std::vector<aiVector3D> norm_arr_copy;
  918. // copy list to array because we are need indexed access to normals.
  919. norm_arr_copy.reserve(pNormals.size());
  920. for ( std::list<aiVector3D>::const_iterator it = pNormals.begin(); it != pNormals.end(); it++ )
  921. {
  922. norm_arr_copy.push_back( *it );
  923. }
  924. if(pNormalPerVertex)
  925. {
  926. if(pNormalIdx.size() > 0)
  927. {
  928. // check indices array count.
  929. if(pNormalIdx.size() != pCoordIdx.size()) throw DeadlyImportError("Normals and Coords inidces count must be equal.");
  930. tind.reserve(pNormalIdx.size());
  931. for(std::vector<int32_t>::const_iterator it = pNormalIdx.begin(); it != pNormalIdx.end(); it++)
  932. {
  933. if(*it != (-1)) tind.push_back(*it);
  934. }
  935. // copy normals to mesh
  936. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  937. for(size_t i = 0; (i < pMesh.mNumVertices) && (i < tind.size()); i++)
  938. {
  939. if(tind[i] >= norm_arr_copy.size())
  940. throw DeadlyImportError("MeshGeometry_AddNormal. Normal index(" + to_string(tind[i]) +
  941. ") is out of range. Normals count: " + to_string(norm_arr_copy.size()) + ".");
  942. pMesh.mNormals[i] = norm_arr_copy[tind[i]];
  943. }
  944. }
  945. else
  946. {
  947. if(pNormals.size() != pMesh.mNumVertices) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and vertices count must be equal.");
  948. // copy normals to mesh
  949. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  950. std::list<aiVector3D>::const_iterator norm_it = pNormals.begin();
  951. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mNormals[i] = *norm_it++;
  952. }
  953. }// if(pNormalPerVertex)
  954. else
  955. {
  956. if(pNormalIdx.size() > 0)
  957. {
  958. if(pMesh.mNumFaces != pNormalIdx.size()) throw DeadlyImportError("Normals faces count must be equal to mesh faces count.");
  959. std::vector<int32_t>::const_iterator normidx_it = pNormalIdx.begin();
  960. tind.reserve(pNormalIdx.size());
  961. for(size_t i = 0, i_e = pNormalIdx.size(); i < i_e; i++) tind.push_back(*normidx_it++);
  962. }
  963. else
  964. {
  965. tind.reserve(pMesh.mNumFaces);
  966. for(size_t i = 0; i < pMesh.mNumFaces; i++) tind.push_back(i);
  967. }
  968. // copy normals to mesh
  969. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  970. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  971. {
  972. aiVector3D tnorm;
  973. tnorm = norm_arr_copy[tind[fi]];
  974. for(size_t vi = 0, vi_e = pMesh.mFaces[fi].mNumIndices; vi < vi_e; vi++) pMesh.mNormals[pMesh.mFaces[fi].mIndices[vi]] = tnorm;
  975. }
  976. }// if(pNormalPerVertex) else
  977. }
  978. void X3DImporter::MeshGeometry_AddNormal(aiMesh& pMesh, const std::list<aiVector3D>& pNormals, const bool pNormalPerVertex) const
  979. {
  980. std::list<aiVector3D>::const_iterator norm_it = pNormals.begin();
  981. if(pNormalPerVertex)
  982. {
  983. if(pNormals.size() != pMesh.mNumVertices) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and vertices count must be equal.");
  984. // copy normals to mesh
  985. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  986. for(size_t i = 0; i < pMesh.mNumVertices; i++) pMesh.mNormals[i] = *norm_it++;
  987. }// if(pNormalPerVertex)
  988. else
  989. {
  990. if(pNormals.size() != pMesh.mNumFaces) throw DeadlyImportError("MeshGeometry_AddNormal. Normals and faces count must be equal.");
  991. // copy normals to mesh
  992. pMesh.mNormals = new aiVector3D[pMesh.mNumVertices];
  993. for(size_t fi = 0; fi < pMesh.mNumFaces; fi++)
  994. {
  995. // apply color to all vertices of face
  996. for(size_t vi = 0, vi_e = pMesh.mFaces[fi].mNumIndices; vi < vi_e; vi++) pMesh.mNormals[pMesh.mFaces[fi].mIndices[vi]] = *norm_it;
  997. norm_it++;
  998. }
  999. }// if(pNormalPerVertex) else
  1000. }
  1001. void X3DImporter::MeshGeometry_AddTexCoord(aiMesh& pMesh, const std::vector<int32_t>& pCoordIdx, const std::vector<int32_t>& pTexCoordIdx,
  1002. const std::list<aiVector2D>& pTexCoords) const
  1003. {
  1004. std::vector<aiVector3D> texcoord_arr_copy;
  1005. std::vector<aiFace> faces;
  1006. unsigned int prim_type;
  1007. // copy list to array because we are need indexed access to normals.
  1008. texcoord_arr_copy.reserve(pTexCoords.size());
  1009. for(std::list<aiVector2D>::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++)
  1010. {
  1011. texcoord_arr_copy.push_back(aiVector3D((*it).x, (*it).y, 0));
  1012. }
  1013. if(pTexCoordIdx.size() > 0)
  1014. {
  1015. GeometryHelper_CoordIdxStr2FacesArr(pTexCoordIdx, faces, prim_type);
  1016. if ( faces.empty() )
  1017. {
  1018. throw DeadlyImportError( "Failed to add texture coordinates to mesh, faces list is empty." );
  1019. }
  1020. if ( faces.size() != pMesh.mNumFaces )
  1021. {
  1022. throw DeadlyImportError( "Texture coordinates faces count must be equal to mesh faces count." );
  1023. }
  1024. }
  1025. else
  1026. {
  1027. GeometryHelper_CoordIdxStr2FacesArr(pCoordIdx, faces, prim_type);
  1028. }
  1029. pMesh.mTextureCoords[0] = new aiVector3D[pMesh.mNumVertices];
  1030. pMesh.mNumUVComponents[0] = 2;
  1031. for(size_t fi = 0, fi_e = faces.size(); fi < fi_e; fi++)
  1032. {
  1033. if(pMesh.mFaces[fi].mNumIndices != faces.at(fi).mNumIndices)
  1034. throw DeadlyImportError("Number of indices in texture face and mesh face must be equal. Invalid face index: " + to_string(fi) + ".");
  1035. for(size_t ii = 0; ii < pMesh.mFaces[fi].mNumIndices; ii++)
  1036. {
  1037. size_t vert_idx = pMesh.mFaces[fi].mIndices[ii];
  1038. size_t tc_idx = faces.at(fi).mIndices[ii];
  1039. pMesh.mTextureCoords[0][vert_idx] = texcoord_arr_copy.at(tc_idx);
  1040. }
  1041. }// for(size_t fi = 0, fi_e = faces.size(); fi < fi_e; fi++)
  1042. }
  1043. void X3DImporter::MeshGeometry_AddTexCoord(aiMesh& pMesh, const std::list<aiVector2D>& pTexCoords) const
  1044. {
  1045. std::vector<aiVector3D> tc_arr_copy;
  1046. if ( pTexCoords.size() != pMesh.mNumVertices )
  1047. {
  1048. throw DeadlyImportError( "MeshGeometry_AddTexCoord. Texture coordinates and vertices count must be equal." );
  1049. }
  1050. // copy list to array because we are need convert aiVector2D to aiVector3D and also get indexed access as a bonus.
  1051. tc_arr_copy.reserve(pTexCoords.size());
  1052. for ( std::list<aiVector2D>::const_iterator it = pTexCoords.begin(); it != pTexCoords.end(); it++ )
  1053. {
  1054. tc_arr_copy.push_back( aiVector3D( ( *it ).x, ( *it ).y, 0 ) );
  1055. }
  1056. // copy texture coordinates to mesh
  1057. pMesh.mTextureCoords[0] = new aiVector3D[pMesh.mNumVertices];
  1058. pMesh.mNumUVComponents[0] = 2;
  1059. for ( size_t i = 0; i < pMesh.mNumVertices; i++ )
  1060. {
  1061. pMesh.mTextureCoords[ 0 ][ i ] = tc_arr_copy[ i ];
  1062. }
  1063. }
  1064. aiMesh* X3DImporter::GeometryHelper_MakeMesh(const std::vector<int32_t>& pCoordIdx, const std::list<aiVector3D>& pVertices) const
  1065. {
  1066. std::vector<aiFace> faces;
  1067. unsigned int prim_type = 0;
  1068. // create faces array from input string with vertices indices.
  1069. GeometryHelper_CoordIdxStr2FacesArr(pCoordIdx, faces, prim_type);
  1070. if ( !faces.size() )
  1071. {
  1072. throw DeadlyImportError( "Failed to create mesh, faces list is empty." );
  1073. }
  1074. //
  1075. // Create new mesh and copy geometry data.
  1076. //
  1077. aiMesh *tmesh = new aiMesh;
  1078. size_t ts = faces.size();
  1079. // faces
  1080. tmesh->mFaces = new aiFace[ts];
  1081. tmesh->mNumFaces = static_cast<unsigned int>(ts);
  1082. for(size_t i = 0; i < ts; i++) tmesh->mFaces[i] = faces.at(i);
  1083. // vertices
  1084. std::list<aiVector3D>::const_iterator vit = pVertices.begin();
  1085. ts = pVertices.size();
  1086. tmesh->mVertices = new aiVector3D[ts];
  1087. tmesh->mNumVertices = static_cast<unsigned int>(ts);
  1088. for ( size_t i = 0; i < ts; i++ )
  1089. {
  1090. tmesh->mVertices[ i ] = *vit++;
  1091. }
  1092. // set primitives type and return result.
  1093. tmesh->mPrimitiveTypes = prim_type;
  1094. return tmesh;
  1095. }
  1096. /*********************************************************************************************************************************************/
  1097. /************************************************************ Functions: parse set ***********************************************************/
  1098. /*********************************************************************************************************************************************/
  1099. void X3DImporter::ParseHelper_Group_Begin(const bool pStatic)
  1100. {
  1101. CX3DImporter_NodeElement_Group* new_group = new CX3DImporter_NodeElement_Group(NodeElement_Cur, pStatic);// create new node with current node as parent.
  1102. // if we are adding not the root element then add new element to current element child list.
  1103. if ( NodeElement_Cur != nullptr )
  1104. {
  1105. NodeElement_Cur->Child.push_back( new_group );
  1106. }
  1107. NodeElement_List.push_back(new_group);// it's a new element - add it to list.
  1108. NodeElement_Cur = new_group;// switch current element to new one.
  1109. }
  1110. void X3DImporter::ParseHelper_Node_Enter(CX3DImporter_NodeElement* pNode)
  1111. {
  1112. NodeElement_Cur->Child.push_back(pNode);// add new element to current element child list.
  1113. NodeElement_Cur = pNode;// switch current element to new one.
  1114. }
  1115. void X3DImporter::ParseHelper_Node_Exit()
  1116. {
  1117. // check if we can walk up.
  1118. if ( NodeElement_Cur != nullptr )
  1119. {
  1120. NodeElement_Cur = NodeElement_Cur->Parent;
  1121. }
  1122. }
  1123. void X3DImporter::ParseHelper_FixTruncatedFloatString(const char* pInStr, std::string& pOutString)
  1124. {
  1125. pOutString.clear();
  1126. const size_t instr_len = strlen(pInStr);
  1127. if ( 0 == instr_len )
  1128. {
  1129. return;
  1130. }
  1131. pOutString.reserve(instr_len * 3 / 2);
  1132. // check and correct floats in format ".x". Must be "x.y".
  1133. if ( pInStr[ 0 ] == '.' )
  1134. {
  1135. pOutString.push_back( '0' );
  1136. }
  1137. pOutString.push_back(pInStr[0]);
  1138. for(size_t ci = 1; ci < instr_len; ci++)
  1139. {
  1140. if((pInStr[ci] == '.') && ((pInStr[ci - 1] == ' ') || (pInStr[ci - 1] == '-') || (pInStr[ci - 1] == '+') || (pInStr[ci - 1] == '\t')))
  1141. {
  1142. pOutString.push_back('0');
  1143. pOutString.push_back('.');
  1144. }
  1145. else
  1146. {
  1147. pOutString.push_back(pInStr[ci]);
  1148. }
  1149. }
  1150. }
  1151. extern FIVocabulary X3D_vocabulary_3_2;
  1152. extern FIVocabulary X3D_vocabulary_3_3;
  1153. void X3DImporter::ParseFile(const std::string& pFile, IOSystem* pIOHandler)
  1154. {
  1155. std::unique_ptr<FIReader> OldReader = std::move(mReader);// store current XMLreader.
  1156. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  1157. // Check whether we can read from the file
  1158. if ( file.get() == nullptr )
  1159. {
  1160. throw DeadlyImportError( "Failed to open X3D file " + pFile + "." );
  1161. }
  1162. mReader = FIReader::create(file.get());
  1163. if ( !mReader )
  1164. {
  1165. throw DeadlyImportError( "Failed to create XML reader for file" + pFile + "." );
  1166. }
  1167. mReader->registerVocabulary("urn:web3d:x3d:fi-vocabulary-3.2", &X3D_vocabulary_3_2);
  1168. mReader->registerVocabulary("urn:web3d:x3d:fi-vocabulary-3.3", &X3D_vocabulary_3_3);
  1169. // start reading
  1170. ParseNode_Root();
  1171. // restore old XMLreader
  1172. mReader = std::move(OldReader);
  1173. }
  1174. void X3DImporter::ParseNode_Root()
  1175. {
  1176. // search for root tag <X3D>
  1177. if ( !XML_SearchNode( "X3D" ) )
  1178. {
  1179. throw DeadlyImportError( "Root node \"X3D\" not found." );
  1180. }
  1181. ParseHelper_Group_Begin();// create root node element.
  1182. // parse other contents
  1183. while(mReader->read())
  1184. {
  1185. if ( mReader->getNodeType() != irr::io::EXN_ELEMENT )
  1186. {
  1187. continue;
  1188. }
  1189. if(XML_CheckNode_NameEqual("head"))
  1190. ParseNode_Head();
  1191. else if(XML_CheckNode_NameEqual("Scene"))
  1192. ParseNode_Scene();
  1193. else
  1194. XML_CheckNode_SkipUnsupported("Root");
  1195. }
  1196. // exit from root node element.
  1197. ParseHelper_Node_Exit();
  1198. }
  1199. void X3DImporter::ParseNode_Head()
  1200. {
  1201. bool close_found = false;// flag: true if close tag of node are found.
  1202. while(mReader->read())
  1203. {
  1204. if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1205. {
  1206. if(XML_CheckNode_NameEqual("meta"))
  1207. {
  1208. XML_CheckNode_MustBeEmpty();
  1209. // adding metadata from <head> as MetaString from <Scene>
  1210. bool added( false );
  1211. CX3DImporter_NodeElement_MetaString* ms = new CX3DImporter_NodeElement_MetaString(NodeElement_Cur);
  1212. ms->Name = mReader->getAttributeValueSafe("name");
  1213. // name must not be empty
  1214. if(!ms->Name.empty())
  1215. {
  1216. ms->Value.push_back(mReader->getAttributeValueSafe("content"));
  1217. NodeElement_List.push_back(ms);
  1218. if ( NodeElement_Cur != nullptr )
  1219. {
  1220. NodeElement_Cur->Child.push_back( ms );
  1221. added = true;
  1222. }
  1223. }
  1224. // if an error has occurred, release instance
  1225. if ( !added ) {
  1226. delete ms;
  1227. }
  1228. }// if(XML_CheckNode_NameEqual("meta"))
  1229. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1230. else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1231. {
  1232. if(XML_CheckNode_NameEqual("head"))
  1233. {
  1234. close_found = true;
  1235. break;
  1236. }
  1237. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT) else
  1238. }// while(mReader->read())
  1239. if ( !close_found )
  1240. {
  1241. Throw_CloseNotFound( "head" );
  1242. }
  1243. }
  1244. void X3DImporter::ParseNode_Scene()
  1245. {
  1246. auto GroupCounter_Increase = [](size_t& pCounter, const char* pGroupName) -> void
  1247. {
  1248. pCounter++;
  1249. if(pCounter == 0) throw DeadlyImportError("Group counter overflow. Too much groups with type: " + std::string(pGroupName) + ".");
  1250. };
  1251. auto GroupCounter_Decrease = [&](size_t& pCounter, const char* pGroupName) -> void
  1252. {
  1253. if(pCounter == 0) Throw_TagCountIncorrect(pGroupName);
  1254. pCounter--;
  1255. };
  1256. static const char* GroupName_Group = "Group";
  1257. static const char* GroupName_StaticGroup = "StaticGroup";
  1258. static const char* GroupName_Transform = "Transform";
  1259. static const char* GroupName_Switch = "Switch";
  1260. bool close_found = false;
  1261. size_t counter_group = 0;
  1262. size_t counter_transform = 0;
  1263. size_t counter_switch = 0;
  1264. // while create static node? Because objects name used deeper in "USE" attribute can be equal to some meta in <head> node.
  1265. ParseHelper_Group_Begin(true);
  1266. while(mReader->read())
  1267. {
  1268. if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1269. {
  1270. if(XML_CheckNode_NameEqual("Shape"))
  1271. {
  1272. ParseNode_Shape_Shape();
  1273. }
  1274. else if(XML_CheckNode_NameEqual(GroupName_Group))
  1275. {
  1276. GroupCounter_Increase(counter_group, GroupName_Group);
  1277. ParseNode_Grouping_Group();
  1278. // if node is empty then decrease group counter at this place.
  1279. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_group, GroupName_Group);
  1280. }
  1281. else if(XML_CheckNode_NameEqual(GroupName_StaticGroup))
  1282. {
  1283. GroupCounter_Increase(counter_group, GroupName_StaticGroup);
  1284. ParseNode_Grouping_StaticGroup();
  1285. // if node is empty then decrease group counter at this place.
  1286. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_group, GroupName_StaticGroup);
  1287. }
  1288. else if(XML_CheckNode_NameEqual(GroupName_Transform))
  1289. {
  1290. GroupCounter_Increase(counter_transform, GroupName_Transform);
  1291. ParseNode_Grouping_Transform();
  1292. // if node is empty then decrease group counter at this place.
  1293. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_transform, GroupName_Transform);
  1294. }
  1295. else if(XML_CheckNode_NameEqual(GroupName_Switch))
  1296. {
  1297. GroupCounter_Increase(counter_switch, GroupName_Switch);
  1298. ParseNode_Grouping_Switch();
  1299. // if node is empty then decrease group counter at this place.
  1300. if(mReader->isEmptyElement()) GroupCounter_Decrease(counter_switch, GroupName_Switch);
  1301. }
  1302. else if(XML_CheckNode_NameEqual("DirectionalLight"))
  1303. {
  1304. ParseNode_Lighting_DirectionalLight();
  1305. }
  1306. else if(XML_CheckNode_NameEqual("PointLight"))
  1307. {
  1308. ParseNode_Lighting_PointLight();
  1309. }
  1310. else if(XML_CheckNode_NameEqual("SpotLight"))
  1311. {
  1312. ParseNode_Lighting_SpotLight();
  1313. }
  1314. else if(XML_CheckNode_NameEqual("Inline"))
  1315. {
  1316. ParseNode_Networking_Inline();
  1317. }
  1318. else if(!ParseHelper_CheckRead_X3DMetadataObject())
  1319. {
  1320. XML_CheckNode_SkipUnsupported("Scene");
  1321. }
  1322. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT)
  1323. else if(mReader->getNodeType() == irr::io::EXN_ELEMENT_END)
  1324. {
  1325. if(XML_CheckNode_NameEqual("Scene"))
  1326. {
  1327. close_found = true;
  1328. break;
  1329. }
  1330. else if(XML_CheckNode_NameEqual(GroupName_Group))
  1331. {
  1332. GroupCounter_Decrease(counter_group, GroupName_Group);
  1333. ParseNode_Grouping_GroupEnd();
  1334. }
  1335. else if(XML_CheckNode_NameEqual(GroupName_StaticGroup))
  1336. {
  1337. GroupCounter_Decrease(counter_group, GroupName_StaticGroup);
  1338. ParseNode_Grouping_StaticGroupEnd();
  1339. }
  1340. else if(XML_CheckNode_NameEqual(GroupName_Transform))
  1341. {
  1342. GroupCounter_Decrease(counter_transform, GroupName_Transform);
  1343. ParseNode_Grouping_TransformEnd();
  1344. }
  1345. else if(XML_CheckNode_NameEqual(GroupName_Switch))
  1346. {
  1347. GroupCounter_Decrease(counter_switch, GroupName_Switch);
  1348. ParseNode_Grouping_SwitchEnd();
  1349. }
  1350. }// if(mReader->getNodeType() == irr::io::EXN_ELEMENT) else
  1351. }// while(mReader->read())
  1352. ParseHelper_Node_Exit();
  1353. if(counter_group) Throw_TagCountIncorrect("Group");
  1354. if(counter_transform) Throw_TagCountIncorrect("Transform");
  1355. if(counter_switch) Throw_TagCountIncorrect("Switch");
  1356. if(!close_found) Throw_CloseNotFound("Scene");
  1357. }
  1358. /*********************************************************************************************************************************************/
  1359. /******************************************************** Functions: BaseImporter set ********************************************************/
  1360. /*********************************************************************************************************************************************/
  1361. bool X3DImporter::CanRead(const std::string& pFile, IOSystem* pIOHandler, bool pCheckSig) const
  1362. {
  1363. const std::string extension = GetExtension(pFile);
  1364. if((extension == "x3d") || (extension == "x3db")) return true;
  1365. if(!extension.length() || pCheckSig)
  1366. {
  1367. const char* tokens[] = { "DOCTYPE X3D PUBLIC", "http://www.web3d.org/specifications/x3d" };
  1368. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 2);
  1369. }
  1370. return false;
  1371. }
  1372. void X3DImporter::GetExtensionList(std::set<std::string>& pExtensionList)
  1373. {
  1374. pExtensionList.insert("x3d");
  1375. pExtensionList.insert("x3db");
  1376. }
  1377. const aiImporterDesc* X3DImporter::GetInfo () const
  1378. {
  1379. return &Description;
  1380. }
  1381. void X3DImporter::InternReadFile(const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
  1382. {
  1383. mpIOHandler = pIOHandler;
  1384. Clear();// delete old graph.
  1385. std::string::size_type slashPos = pFile.find_last_of("\\/");
  1386. pIOHandler->PushDirectory(slashPos == std::string::npos ? std::string() : pFile.substr(0, slashPos + 1));
  1387. ParseFile(pFile, pIOHandler);
  1388. pIOHandler->PopDirectory();
  1389. //
  1390. // Assimp use static arrays of objects for fast speed of rendering. That's good, but need some additional operations/
  1391. // We know that geometry objects(meshes) are stored in <Shape>, also in <Shape>-><Appearance> materials(in Assimp logical view)
  1392. // are stored. So at first we need to count how meshes and materials are stored in scene graph.
  1393. //
  1394. // at first creating root node for aiScene.
  1395. pScene->mRootNode = new aiNode;
  1396. pScene->mRootNode->mParent = nullptr;
  1397. pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
  1398. //search for root node element
  1399. NodeElement_Cur = NodeElement_List.front();
  1400. while(NodeElement_Cur->Parent != nullptr) NodeElement_Cur = NodeElement_Cur->Parent;
  1401. {// fill aiScene with objects.
  1402. std::list<aiMesh*> mesh_list;
  1403. std::list<aiMaterial*> mat_list;
  1404. std::list<aiLight*> light_list;
  1405. // create nodes tree
  1406. Postprocess_BuildNode(*NodeElement_Cur, *pScene->mRootNode, mesh_list, mat_list, light_list);
  1407. // copy needed data to scene
  1408. if(mesh_list.size() > 0)
  1409. {
  1410. std::list<aiMesh*>::const_iterator it = mesh_list.begin();
  1411. pScene->mNumMeshes = static_cast<unsigned int>(mesh_list.size());
  1412. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  1413. for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *it++;
  1414. }
  1415. if(mat_list.size() > 0)
  1416. {
  1417. std::list<aiMaterial*>::const_iterator it = mat_list.begin();
  1418. pScene->mNumMaterials = static_cast<unsigned int>(mat_list.size());
  1419. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  1420. for(size_t i = 0; i < pScene->mNumMaterials; i++) pScene->mMaterials[i] = *it++;
  1421. }
  1422. if(light_list.size() > 0)
  1423. {
  1424. std::list<aiLight*>::const_iterator it = light_list.begin();
  1425. pScene->mNumLights = static_cast<unsigned int>(light_list.size());
  1426. pScene->mLights = new aiLight*[pScene->mNumLights];
  1427. for(size_t i = 0; i < pScene->mNumLights; i++) pScene->mLights[i] = *it++;
  1428. }
  1429. }// END: fill aiScene with objects.
  1430. ///TODO: IME optimize tree
  1431. }
  1432. }// namespace Assimp
  1433. #endif // !ASSIMP_BUILD_NO_X3D_IMPORTER