X3DImporter.cpp 57 KB

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