X3DImporter.cpp 57 KB

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