Drawable.cpp 23 KB

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