Drawable.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. //
  2. // Copyright (c) 2008-2017 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Context.h"
  24. #include "../Graphics/Camera.h"
  25. #include "../Graphics/DebugRenderer.h"
  26. #include "../IO/File.h"
  27. #include "../Graphics/Geometry.h"
  28. #include "../Graphics/Material.h"
  29. #include "../Graphics/Octree.h"
  30. #include "../Graphics/Renderer.h"
  31. #include "../Graphics/VertexBuffer.h"
  32. #include "../Graphics/Zone.h"
  33. #include "../IO/Log.h"
  34. #include "../Scene/Scene.h"
  35. #include "../DebugNew.h"
  36. #ifdef _MSC_VER
  37. #pragma warning(disable:6293)
  38. #endif
  39. namespace Urho3D
  40. {
  41. const char* GEOMETRY_CATEGORY = "Geometry";
  42. SourceBatch::SourceBatch() :
  43. distance_(0.0f),
  44. geometry_(nullptr),
  45. worldTransform_(&Matrix3x4::IDENTITY),
  46. numWorldTransforms_(1),
  47. instancingData_(nullptr),
  48. geometryType_(GEOM_STATIC)
  49. {
  50. }
  51. SourceBatch::SourceBatch(const SourceBatch& batch)
  52. {
  53. *this = batch;
  54. }
  55. SourceBatch::~SourceBatch()
  56. {
  57. }
  58. SourceBatch& SourceBatch::operator =(const SourceBatch& rhs)
  59. {
  60. distance_ = rhs.distance_;
  61. geometry_ = rhs.geometry_;
  62. material_ = rhs.material_;
  63. worldTransform_ = rhs.worldTransform_;
  64. numWorldTransforms_ = rhs.numWorldTransforms_;
  65. instancingData_ = rhs.instancingData_;
  66. geometryType_ = rhs.geometryType_;
  67. return *this;
  68. }
  69. Drawable::Drawable(Context* context, unsigned char drawableFlags) :
  70. Component(context),
  71. boundingBox_(0.0f, 0.0f),
  72. drawableFlags_(drawableFlags),
  73. worldBoundingBoxDirty_(true),
  74. castShadows_(false),
  75. occluder_(false),
  76. occludee_(true),
  77. updateQueued_(false),
  78. zoneDirty_(false),
  79. octant_(nullptr),
  80. zone_(nullptr),
  81. viewMask_(DEFAULT_VIEWMASK),
  82. lightMask_(DEFAULT_LIGHTMASK),
  83. shadowMask_(DEFAULT_SHADOWMASK),
  84. zoneMask_(DEFAULT_ZONEMASK),
  85. viewFrameNumber_(0),
  86. distance_(0.0f),
  87. lodDistance_(0.0f),
  88. drawDistance_(0.0f),
  89. shadowDistance_(0.0f),
  90. sortValue_(0.0f),
  91. minZ_(0.0f),
  92. maxZ_(0.0f),
  93. lodBias_(1.0f),
  94. basePassFlags_(0),
  95. maxLights_(0),
  96. firstLight_(nullptr)
  97. {
  98. }
  99. Drawable::~Drawable()
  100. {
  101. RemoveFromOctree();
  102. }
  103. void Drawable::RegisterObject(Context* context)
  104. {
  105. URHO3D_ATTRIBUTE("Max Lights", int, maxLights_, 0, AM_DEFAULT);
  106. URHO3D_ATTRIBUTE("View Mask", int, viewMask_, DEFAULT_VIEWMASK, AM_DEFAULT);
  107. URHO3D_ATTRIBUTE("Light Mask", int, lightMask_, DEFAULT_LIGHTMASK, AM_DEFAULT);
  108. URHO3D_ATTRIBUTE("Shadow Mask", int, shadowMask_, DEFAULT_SHADOWMASK, AM_DEFAULT);
  109. URHO3D_ACCESSOR_ATTRIBUTE("Zone Mask", GetZoneMask, SetZoneMask, unsigned, DEFAULT_ZONEMASK, AM_DEFAULT);
  110. }
  111. void Drawable::OnSetEnabled()
  112. {
  113. bool enabled = IsEnabledEffective();
  114. if (enabled && !octant_)
  115. AddToOctree();
  116. else if (!enabled && octant_)
  117. RemoveFromOctree();
  118. }
  119. void Drawable::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
  120. {
  121. float distance = query.ray_.HitDistance(GetWorldBoundingBox());
  122. if (distance < query.maxDistance_)
  123. {
  124. RayQueryResult result;
  125. result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
  126. result.normal_ = -query.ray_.direction_;
  127. result.distance_ = distance;
  128. result.drawable_ = this;
  129. result.node_ = GetNode();
  130. result.subObject_ = M_MAX_UNSIGNED;
  131. results.Push(result);
  132. }
  133. }
  134. void Drawable::UpdateBatches(const FrameInfo& frame)
  135. {
  136. const BoundingBox& worldBoundingBox = GetWorldBoundingBox();
  137. const Matrix3x4& worldTransform = node_->GetWorldTransform();
  138. distance_ = frame.camera_->GetDistance(worldBoundingBox.Center());
  139. for (unsigned i = 0; i < batches_.Size(); ++i)
  140. {
  141. batches_[i].distance_ = distance_;
  142. batches_[i].worldTransform_ = &worldTransform;
  143. }
  144. float scale = worldBoundingBox.Size().DotProduct(DOT_SCALE);
  145. float newLodDistance = frame.camera_->GetLodDistance(distance_, scale, lodBias_);
  146. if (newLodDistance != lodDistance_)
  147. lodDistance_ = newLodDistance;
  148. }
  149. Geometry* Drawable::GetLodGeometry(unsigned batchIndex, unsigned level)
  150. {
  151. // By default return the visible batch geometry
  152. if (batchIndex < batches_.Size())
  153. return batches_[batchIndex].geometry_;
  154. else
  155. return nullptr;
  156. }
  157. bool Drawable::DrawOcclusion(OcclusionBuffer* buffer)
  158. {
  159. return true;
  160. }
  161. void Drawable::DrawDebugGeometry(DebugRenderer* debug, bool depthTest)
  162. {
  163. if (debug && IsEnabledEffective())
  164. debug->AddBoundingBox(GetWorldBoundingBox(), Color::GREEN, depthTest);
  165. }
  166. void Drawable::SetDrawDistance(float distance)
  167. {
  168. drawDistance_ = distance;
  169. MarkNetworkUpdate();
  170. }
  171. void Drawable::SetShadowDistance(float distance)
  172. {
  173. shadowDistance_ = distance;
  174. MarkNetworkUpdate();
  175. }
  176. void Drawable::SetLodBias(float bias)
  177. {
  178. lodBias_ = Max(bias, M_EPSILON);
  179. MarkNetworkUpdate();
  180. }
  181. void Drawable::SetViewMask(unsigned mask)
  182. {
  183. viewMask_ = mask;
  184. MarkNetworkUpdate();
  185. }
  186. void Drawable::SetLightMask(unsigned mask)
  187. {
  188. lightMask_ = mask;
  189. MarkNetworkUpdate();
  190. }
  191. void Drawable::SetShadowMask(unsigned mask)
  192. {
  193. shadowMask_ = mask;
  194. MarkNetworkUpdate();
  195. }
  196. void Drawable::SetZoneMask(unsigned mask)
  197. {
  198. zoneMask_ = mask;
  199. // Mark dirty to reset cached zone
  200. OnMarkedDirty(node_);
  201. MarkNetworkUpdate();
  202. }
  203. void Drawable::SetMaxLights(unsigned num)
  204. {
  205. maxLights_ = num;
  206. MarkNetworkUpdate();
  207. }
  208. void Drawable::SetCastShadows(bool enable)
  209. {
  210. castShadows_ = enable;
  211. MarkNetworkUpdate();
  212. }
  213. void Drawable::SetOccluder(bool enable)
  214. {
  215. occluder_ = enable;
  216. MarkNetworkUpdate();
  217. }
  218. void Drawable::SetOccludee(bool enable)
  219. {
  220. if (enable != occludee_)
  221. {
  222. occludee_ = enable;
  223. // Reinsert to octree to make sure octant occlusion does not erroneously hide this drawable
  224. if (octant_ && !updateQueued_)
  225. octant_->GetRoot()->QueueUpdate(this);
  226. MarkNetworkUpdate();
  227. }
  228. }
  229. void Drawable::MarkForUpdate()
  230. {
  231. if (!updateQueued_ && octant_)
  232. octant_->GetRoot()->QueueUpdate(this);
  233. }
  234. const BoundingBox& Drawable::GetWorldBoundingBox()
  235. {
  236. if (worldBoundingBoxDirty_)
  237. {
  238. OnWorldBoundingBoxUpdate();
  239. worldBoundingBoxDirty_ = false;
  240. }
  241. return worldBoundingBox_;
  242. }
  243. bool Drawable::IsInView() const
  244. {
  245. // Note: in headless mode there is no renderer subsystem and no view frustum tests are performed, so return
  246. // always false in that case
  247. Renderer* renderer = GetSubsystem<Renderer>();
  248. return renderer && viewFrameNumber_ == renderer->GetFrameInfo().frameNumber_ && !viewCameras_.Empty();
  249. }
  250. bool Drawable::IsInView(Camera* camera) const
  251. {
  252. Renderer* renderer = GetSubsystem<Renderer>();
  253. return renderer && viewFrameNumber_ == renderer->GetFrameInfo().frameNumber_ && (!camera || viewCameras_.Contains(camera));
  254. }
  255. bool Drawable::IsInView(const FrameInfo& frame, bool anyCamera) const
  256. {
  257. return viewFrameNumber_ == frame.frameNumber_ && (anyCamera || viewCameras_.Contains(frame.camera_));
  258. }
  259. void Drawable::SetZone(Zone* zone, bool temporary)
  260. {
  261. zone_ = zone;
  262. // If the zone assignment was temporary (inconclusive) set the dirty flag so that it will be re-evaluated on the next frame
  263. zoneDirty_ = temporary;
  264. }
  265. void Drawable::SetSortValue(float value)
  266. {
  267. sortValue_ = value;
  268. }
  269. void Drawable::MarkInView(const FrameInfo& frame)
  270. {
  271. if (frame.frameNumber_ != viewFrameNumber_)
  272. {
  273. viewFrameNumber_ = frame.frameNumber_;
  274. viewCameras_.Resize(1);
  275. viewCameras_[0] = frame.camera_;
  276. }
  277. else
  278. viewCameras_.Push(frame.camera_);
  279. basePassFlags_ = 0;
  280. firstLight_ = nullptr;
  281. lights_.Clear();
  282. vertexLights_.Clear();
  283. }
  284. void Drawable::MarkInView(unsigned frameNumber)
  285. {
  286. if (frameNumber != viewFrameNumber_)
  287. {
  288. viewFrameNumber_ = frameNumber;
  289. viewCameras_.Clear();
  290. }
  291. }
  292. void Drawable::LimitLights()
  293. {
  294. // Maximum lights value 0 means unlimited
  295. if (!maxLights_ || lights_.Size() <= maxLights_)
  296. return;
  297. // If more lights than allowed, move to vertex lights and cut the list
  298. const BoundingBox& box = GetWorldBoundingBox();
  299. for (unsigned i = 0; i < lights_.Size(); ++i)
  300. lights_[i]->SetIntensitySortValue(box);
  301. Sort(lights_.Begin(), lights_.End(), CompareDrawables);
  302. vertexLights_.Insert(vertexLights_.End(), lights_.Begin() + maxLights_, lights_.End());
  303. lights_.Resize(maxLights_);
  304. }
  305. void Drawable::LimitVertexLights(bool removeConvertedLights)
  306. {
  307. if (removeConvertedLights)
  308. {
  309. for (unsigned i = vertexLights_.Size() - 1; i < vertexLights_.Size(); --i)
  310. {
  311. if (!vertexLights_[i]->GetPerVertex())
  312. vertexLights_.Erase(i);
  313. }
  314. }
  315. if (vertexLights_.Size() <= MAX_VERTEX_LIGHTS)
  316. return;
  317. const BoundingBox& box = GetWorldBoundingBox();
  318. for (unsigned i = 0; i < vertexLights_.Size(); ++i)
  319. vertexLights_[i]->SetIntensitySortValue(box);
  320. Sort(vertexLights_.Begin(), vertexLights_.End(), CompareDrawables);
  321. vertexLights_.Resize(MAX_VERTEX_LIGHTS);
  322. }
  323. void Drawable::OnNodeSet(Node* node)
  324. {
  325. if (node)
  326. node->AddListener(this);
  327. }
  328. void Drawable::OnSceneSet(Scene* scene)
  329. {
  330. if (scene)
  331. AddToOctree();
  332. else
  333. RemoveFromOctree();
  334. }
  335. void Drawable::OnMarkedDirty(Node* node)
  336. {
  337. worldBoundingBoxDirty_ = true;
  338. if (!updateQueued_ && octant_)
  339. octant_->GetRoot()->QueueUpdate(this);
  340. // Mark zone assignment dirty when transform changes
  341. if (node == node_)
  342. zoneDirty_ = true;
  343. }
  344. void Drawable::AddToOctree()
  345. {
  346. // Do not add to octree when disabled
  347. if (!IsEnabledEffective())
  348. return;
  349. Scene* scene = GetScene();
  350. if (scene)
  351. {
  352. Octree* octree = scene->GetComponent<Octree>();
  353. if (octree)
  354. octree->InsertDrawable(this);
  355. else
  356. URHO3D_LOGERROR("No Octree component in scene, drawable will not render");
  357. }
  358. else
  359. {
  360. // We have a mechanism for adding detached nodes to an octree manually, so do not log this error
  361. //URHO3D_LOGERROR("Node is detached from scene, drawable will not render");
  362. }
  363. }
  364. void Drawable::RemoveFromOctree()
  365. {
  366. if (octant_)
  367. {
  368. Octree* octree = octant_->GetRoot();
  369. if (updateQueued_)
  370. octree->CancelUpdate(this);
  371. // Perform subclass specific deinitialization if necessary
  372. OnRemoveFromOctree();
  373. octant_->RemoveDrawable(this);
  374. }
  375. }
  376. bool WriteDrawablesToOBJ(PODVector<Drawable*> drawables, File* outputFile, bool asZUp, bool asRightHanded, bool writeLightmapUV)
  377. {
  378. // Must track indices independently to deal with potential mismatching of drawables vertex attributes (ie. one with UV, another without, then another with)
  379. unsigned currentPositionIndex = 1;
  380. unsigned currentUVIndex = 1;
  381. unsigned currentNormalIndex = 1;
  382. bool anythingWritten = false;
  383. // Write the common "I came from X" comment
  384. outputFile->WriteLine("# OBJ file exported from Urho3D");
  385. for (unsigned i = 0; i < drawables.Size(); ++i)
  386. {
  387. Drawable* drawable = drawables[i];
  388. // Only write enabled drawables
  389. if (!drawable->IsEnabledEffective())
  390. continue;
  391. Node* node = drawable->GetNode();
  392. Matrix3x4 transMat = drawable->GetNode()->GetWorldTransform();
  393. Matrix3x4 n = transMat.Inverse();
  394. Matrix3 normalMat = Matrix3(n.m00_, n.m01_, n.m02_, n.m10_, n.m11_, n.m12_, n.m20_, n.m21_, n.m22_);
  395. normalMat = normalMat.Transpose();
  396. const Vector<SourceBatch>& batches = drawable->GetBatches();
  397. for (unsigned geoIndex = 0; geoIndex < batches.Size(); ++geoIndex)
  398. {
  399. Geometry* geo = drawable->GetLodGeometry(geoIndex, 0);
  400. if (geo == nullptr)
  401. continue;
  402. if (geo->GetPrimitiveType() != TRIANGLE_LIST)
  403. {
  404. URHO3D_LOGERRORF("%s (%u) %s (%u) Geometry %u contains an unsupported geometry type %u", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex, (unsigned)geo->GetPrimitiveType());
  405. continue;
  406. }
  407. // If we've reached here than we're going to actually write something to the OBJ file
  408. anythingWritten = true;
  409. const unsigned char* vertexData;
  410. const unsigned char* indexData;
  411. unsigned elementSize, indexSize;
  412. const PODVector<VertexElement>* elements;
  413. geo->GetRawData(vertexData, elementSize, indexData, indexSize, elements);
  414. if (!vertexData || !elements)
  415. continue;
  416. bool hasPosition = VertexBuffer::HasElement(*elements, TYPE_VECTOR3, SEM_POSITION);
  417. if (!hasPosition)
  418. {
  419. URHO3D_LOGERRORF("%s (%u) %s (%u) Geometry %u contains does not have Vector3 type positions in vertex data", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex);
  420. continue;
  421. }
  422. bool hasNormals = VertexBuffer::HasElement(*elements, TYPE_VECTOR3, SEM_NORMAL);
  423. bool hasUV = VertexBuffer::HasElement(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 0);
  424. bool hasLMUV = VertexBuffer::HasElement(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 1);
  425. if (elementSize > 0 && indexSize > 0)
  426. {
  427. unsigned vertexStart = geo->GetVertexStart();
  428. unsigned vertexCount = geo->GetVertexCount();
  429. unsigned indexStart = geo->GetIndexStart();
  430. unsigned indexCount = geo->GetIndexCount();
  431. // Name NodeID DrawableType DrawableID GeometryIndex ("Geo" is included for clarity as StaticModel_32_2 could easily be misinterpreted or even quickly misread as 322)
  432. // Generated object name example: Node_5_StaticModel_32_Geo_0 ... or ... Bob_5_StaticModel_32_Geo_0
  433. outputFile->WriteLine(String("o ").AppendWithFormat("%s_%u_%s_%u_Geo_%u", node->GetName().Length() > 0 ? node->GetName().CString() : "Node", node->GetID(), drawable->GetTypeName().CString(), drawable->GetID(), geoIndex));
  434. // Write vertex position
  435. unsigned positionOffset = VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_POSITION);
  436. for (unsigned j = 0; j < vertexCount; ++j)
  437. {
  438. Vector3 vertexPosition = *((const Vector3*)(&vertexData[(vertexStart + j) * elementSize + positionOffset]));
  439. vertexPosition = transMat * vertexPosition;
  440. // Convert coordinates as requested
  441. if (asRightHanded)
  442. vertexPosition.x_ *= -1;
  443. if (asZUp)
  444. {
  445. float yVal = vertexPosition.y_;
  446. vertexPosition.y_ = vertexPosition.z_;
  447. vertexPosition.z_ = yVal;
  448. }
  449. outputFile->WriteLine("v " + String(vertexPosition));
  450. }
  451. if (hasNormals)
  452. {
  453. unsigned normalOffset = VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR3, SEM_NORMAL);
  454. for (unsigned j = 0; j < vertexCount; ++j)
  455. {
  456. Vector3 vertexNormal = *((const Vector3*)(&vertexData[(vertexStart + j) * elementSize + normalOffset]));
  457. vertexNormal = normalMat * vertexNormal;
  458. vertexNormal.Normalize();
  459. if (asRightHanded)
  460. vertexNormal.x_ *= -1;
  461. if (asZUp)
  462. {
  463. float yVal = vertexNormal.y_;
  464. vertexNormal.y_ = vertexNormal.z_;
  465. vertexNormal.z_ = yVal;
  466. }
  467. outputFile->WriteLine("vn " + String(vertexNormal));
  468. }
  469. }
  470. // Write TEXCOORD1 or TEXCOORD2 if it was chosen
  471. if (hasUV || (hasLMUV && writeLightmapUV))
  472. {
  473. // if writing Lightmap UV is chosen, only use it if TEXCOORD2 exists, otherwise use TEXCOORD1
  474. unsigned texCoordOffset = (writeLightmapUV && hasLMUV) ? VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 1) :
  475. VertexBuffer::GetElementOffset(*elements, TYPE_VECTOR2, SEM_TEXCOORD, 0);
  476. for (unsigned j = 0; j < vertexCount; ++j)
  477. {
  478. Vector2 uvCoords = *((const Vector2*)(&vertexData[(vertexStart + j) * elementSize + texCoordOffset]));
  479. outputFile->WriteLine("vt " + String(uvCoords));
  480. }
  481. }
  482. // If we don't have UV but have normals then must write a double-slash to indicate the absence of UV coords, otherwise use a single slash
  483. const String slashCharacter = hasNormals ? "//" : "/";
  484. // Amount by which to offset indices in the OBJ vs their values in the Urho3D geometry, basically the lowest index value
  485. // Compensates for the above vertex writing which doesn't write ALL vertices, just the used ones
  486. unsigned indexOffset = M_MAX_INT;
  487. for (unsigned indexIdx = indexStart; indexIdx < indexStart + indexCount; indexIdx++)
  488. {
  489. if (indexSize == 2)
  490. indexOffset = Min(indexOffset, (unsigned)*((unsigned short*)(indexData + indexIdx * indexSize)));
  491. else
  492. indexOffset = Min(indexOffset, *((unsigned*)(indexData + indexIdx * indexSize)));
  493. }
  494. for (unsigned indexIdx = indexStart; indexIdx < indexStart + indexCount; indexIdx += 3)
  495. {
  496. // Deal with 16 or 32 bit indices
  497. unsigned longIndices[3];
  498. if (indexSize == 2)
  499. {
  500. //16 bit indices
  501. unsigned short indices[3];
  502. memcpy(indices, indexData + (indexIdx * indexSize), indexSize * 3);
  503. longIndices[0] = indices[0] - indexOffset;
  504. longIndices[1] = indices[1] - indexOffset;
  505. longIndices[2] = indices[2] - indexOffset;
  506. }
  507. else
  508. {
  509. //32 bit indices
  510. unsigned indices[3];
  511. memcpy(indices, indexData + (indexIdx * indexSize), indexSize * 3);
  512. longIndices[0] = indices[0] - indexOffset;
  513. longIndices[1] = indices[1] - indexOffset;
  514. longIndices[2] = indices[2] - indexOffset;
  515. }
  516. String output = "f ";
  517. if (hasNormals)
  518. {
  519. output.AppendWithFormat("%l/%l/%l %l/%l/%l %l/%l/%l",
  520. currentPositionIndex + longIndices[0],
  521. currentUVIndex + longIndices[0],
  522. currentNormalIndex + longIndices[0],
  523. currentPositionIndex + longIndices[1],
  524. currentUVIndex + longIndices[1],
  525. currentNormalIndex + longIndices[1],
  526. currentPositionIndex + longIndices[2],
  527. currentUVIndex + longIndices[2],
  528. currentNormalIndex + longIndices[2]);
  529. }
  530. else if (hasNormals || hasUV)
  531. {
  532. unsigned secondTraitIndex = hasNormals ? currentNormalIndex : currentUVIndex;
  533. output.AppendWithFormat("%l%s%l %l%s%l %l%s%l",
  534. currentPositionIndex + longIndices[0],
  535. slashCharacter.CString(),
  536. secondTraitIndex + longIndices[0],
  537. currentPositionIndex + longIndices[1],
  538. slashCharacter.CString(),
  539. secondTraitIndex + longIndices[1],
  540. currentPositionIndex + longIndices[2],
  541. slashCharacter.CString(),
  542. secondTraitIndex + longIndices[2]);
  543. }
  544. else
  545. {
  546. output.AppendWithFormat("%l %l %l",
  547. currentPositionIndex + longIndices[0],
  548. currentPositionIndex + longIndices[1],
  549. currentPositionIndex + longIndices[2]);
  550. }
  551. outputFile->WriteLine(output);
  552. }
  553. // Increment our positions based on what vertex attributes we have
  554. currentPositionIndex += vertexCount;
  555. currentNormalIndex += hasNormals ? vertexCount : 0;
  556. // is it possible to have TEXCOORD2 but not have TEXCOORD1, assume anything
  557. currentUVIndex += (hasUV || hasLMUV) ? vertexCount : 0;
  558. }
  559. }
  560. }
  561. return anythingWritten;
  562. }
  563. }