X3DImporter.cpp 58 KB

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