OcclusionBuffer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  1. //
  2. // Copyright (c) 2008-2014 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 "Camera.h"
  24. #include "Log.h"
  25. #include "OcclusionBuffer.h"
  26. #include <cstring>
  27. #include "DebugNew.h"
  28. namespace Urho3D
  29. {
  30. static const unsigned CLIPMASK_X_POS = 0x1;
  31. static const unsigned CLIPMASK_X_NEG = 0x2;
  32. static const unsigned CLIPMASK_Y_POS = 0x4;
  33. static const unsigned CLIPMASK_Y_NEG = 0x8;
  34. static const unsigned CLIPMASK_Z_POS = 0x10;
  35. static const unsigned CLIPMASK_Z_NEG = 0x20;
  36. OcclusionBuffer::OcclusionBuffer(Context* context) :
  37. Object(context),
  38. buffer_(0),
  39. width_(0),
  40. height_(0),
  41. numTriangles_(0),
  42. maxTriangles_(OCCLUSION_DEFAULT_MAX_TRIANGLES),
  43. cullMode_(CULL_CCW),
  44. depthHierarchyDirty_(true),
  45. reverseCulling_(false),
  46. nearClip_(0.0f),
  47. farClip_(0.0f)
  48. {
  49. }
  50. OcclusionBuffer::~OcclusionBuffer()
  51. {
  52. }
  53. bool OcclusionBuffer::SetSize(int width, int height)
  54. {
  55. // Force the height to an even amount of pixels for better mip generation
  56. if (height & 1)
  57. ++height;
  58. if (width == width_ && height == height_)
  59. return true;
  60. if (width <= 0 || height <= 0)
  61. return false;
  62. if (!IsPowerOfTwo(width))
  63. {
  64. LOGERROR("Width is not a power of two");
  65. return false;
  66. }
  67. width_ = width;
  68. height_ = height;
  69. // Reserve extra memory in case 3D clipping is not exact
  70. fullBuffer_ = new int[width * (height + 2) + 2];
  71. buffer_ = fullBuffer_.Get() + width + 1;
  72. mipBuffers_.Clear();
  73. // Build buffers for mip levels
  74. for (;;)
  75. {
  76. width = (width + 1) / 2;
  77. height = (height + 1) / 2;
  78. mipBuffers_.Push(SharedArrayPtr<DepthValue>(new DepthValue[width * height]));
  79. if (width <= OCCLUSION_MIN_SIZE && height <= OCCLUSION_MIN_SIZE)
  80. break;
  81. }
  82. LOGDEBUG("Set occlusion buffer size " + String(width_) + "x" + String(height_) + " with " +
  83. String(mipBuffers_.Size()) + " mip levels");
  84. CalculateViewport();
  85. return true;
  86. }
  87. void OcclusionBuffer::SetView(Camera* camera)
  88. {
  89. if (!camera)
  90. return;
  91. view_ = camera->GetView();
  92. projection_ = camera->GetProjection(false);
  93. viewProj_ = projection_ * view_;
  94. nearClip_ = camera->GetNearClip();
  95. farClip_ = camera->GetFarClip();
  96. reverseCulling_ = camera->GetReverseCulling();
  97. CalculateViewport();
  98. }
  99. void OcclusionBuffer::SetMaxTriangles(unsigned triangles)
  100. {
  101. maxTriangles_ = triangles;
  102. }
  103. void OcclusionBuffer::SetCullMode(CullMode mode)
  104. {
  105. if (reverseCulling_)
  106. {
  107. if (mode == CULL_CW)
  108. mode = CULL_CCW;
  109. else if (mode == CULL_CCW)
  110. mode = CULL_CW;
  111. }
  112. cullMode_ = mode;
  113. }
  114. void OcclusionBuffer::Reset()
  115. {
  116. numTriangles_ = 0;
  117. }
  118. void OcclusionBuffer::Clear()
  119. {
  120. if (!buffer_)
  121. return;
  122. Reset();
  123. int* dest = buffer_;
  124. int count = width_ * height_;
  125. while (count--)
  126. *dest++ = 0x7fffffff;
  127. depthHierarchyDirty_ = true;
  128. }
  129. bool OcclusionBuffer::Draw(const Matrix3x4& model, const void* vertexData, unsigned vertexSize, unsigned vertexStart, unsigned vertexCount)
  130. {
  131. const unsigned char* srcData = ((const unsigned char*)vertexData) + vertexStart * vertexSize;
  132. Matrix4 modelViewProj = viewProj_ * model;
  133. depthHierarchyDirty_ = true;
  134. // Theoretical max. amount of vertices if each of the 6 clipping planes doubles the triangle count
  135. Vector4 vertices[64 * 3];
  136. // 16-bit indices
  137. unsigned index = 0;
  138. while (index + 2 < vertexCount)
  139. {
  140. if (numTriangles_ >= maxTriangles_)
  141. return false;
  142. const Vector3& v0 = *((const Vector3*)(&srcData[index * vertexSize]));
  143. const Vector3& v1 = *((const Vector3*)(&srcData[(index + 1) * vertexSize]));
  144. const Vector3& v2 = *((const Vector3*)(&srcData[(index + 2) * vertexSize]));
  145. vertices[0] = ModelTransform(modelViewProj, v0);
  146. vertices[1] = ModelTransform(modelViewProj, v1);
  147. vertices[2] = ModelTransform(modelViewProj, v2);
  148. DrawTriangle(vertices);
  149. index += 3;
  150. }
  151. return true;
  152. }
  153. bool OcclusionBuffer::Draw(const Matrix3x4& model, const void* vertexData, unsigned vertexSize, const void* indexData,
  154. unsigned indexSize, unsigned indexStart, unsigned indexCount)
  155. {
  156. const unsigned char* srcData = (const unsigned char*)vertexData;
  157. Matrix4 modelViewProj = viewProj_ * model;
  158. depthHierarchyDirty_ = true;
  159. // Theoretical max. amount of vertices if each of the 6 clipping planes doubles the triangle count
  160. Vector4 vertices[64 * 3];
  161. // 16-bit indices
  162. if (indexSize == sizeof(unsigned short))
  163. {
  164. const unsigned short* indices = ((const unsigned short*)indexData) + indexStart;
  165. const unsigned short* indicesEnd = indices + indexCount;
  166. while (indices < indicesEnd)
  167. {
  168. if (numTriangles_ >= maxTriangles_)
  169. return false;
  170. const Vector3& v0 = *((const Vector3*)(&srcData[indices[0] * vertexSize]));
  171. const Vector3& v1 = *((const Vector3*)(&srcData[indices[1] * vertexSize]));
  172. const Vector3& v2 = *((const Vector3*)(&srcData[indices[2] * vertexSize]));
  173. vertices[0] = ModelTransform(modelViewProj, v0);
  174. vertices[1] = ModelTransform(modelViewProj, v1);
  175. vertices[2] = ModelTransform(modelViewProj, v2);
  176. DrawTriangle(vertices);
  177. indices += 3;
  178. }
  179. }
  180. else
  181. {
  182. const unsigned* indices = ((const unsigned*)indexData) + indexStart;
  183. const unsigned* indicesEnd = indices + indexCount;
  184. while (indices < indicesEnd)
  185. {
  186. if (numTriangles_ >= maxTriangles_)
  187. return false;
  188. const Vector3& v0 = *((const Vector3*)(&srcData[indices[0] * vertexSize]));
  189. const Vector3& v1 = *((const Vector3*)(&srcData[indices[1] * vertexSize]));
  190. const Vector3& v2 = *((const Vector3*)(&srcData[indices[2] * vertexSize]));
  191. vertices[0] = ModelTransform(modelViewProj, v0);
  192. vertices[1] = ModelTransform(modelViewProj, v1);
  193. vertices[2] = ModelTransform(modelViewProj, v2);
  194. DrawTriangle(vertices);
  195. indices += 3;
  196. }
  197. }
  198. return true;
  199. }
  200. void OcclusionBuffer::BuildDepthHierarchy()
  201. {
  202. if (!buffer_)
  203. return;
  204. // Build the first mip level from the pixel-level data
  205. int width = (width_ + 1) / 2;
  206. int height = (height_ + 1) / 2;
  207. if (mipBuffers_.Size())
  208. {
  209. for (int y = 0; y < height; ++y)
  210. {
  211. int* src = buffer_ + (y * 2) * width_;
  212. DepthValue* dest = mipBuffers_[0].Get() + y * width;
  213. DepthValue* end = dest + width;
  214. if (y * 2 + 1 < height_)
  215. {
  216. int* src2 = src + width_;
  217. while (dest < end)
  218. {
  219. int minUpper = Min(src[0], src[1]);
  220. int minLower = Min(src2[0], src2[1]);
  221. dest->min_ = Min(minUpper, minLower);
  222. int maxUpper = Max(src[0], src[1]);
  223. int maxLower = Max(src2[0], src2[1]);
  224. dest->max_ = Max(maxUpper, maxLower);
  225. src += 2;
  226. src2 += 2;
  227. ++dest;
  228. }
  229. }
  230. else
  231. {
  232. while (dest < end)
  233. {
  234. dest->min_ = Min(src[0], src[1]);
  235. dest->max_ = Max(src[0], src[1]);
  236. src += 2;
  237. ++dest;
  238. }
  239. }
  240. }
  241. }
  242. // Build the rest of the mip levels
  243. for (unsigned i = 1; i < mipBuffers_.Size(); ++i)
  244. {
  245. int prevWidth = width;
  246. int prevHeight = height;
  247. width = (width + 1) / 2;
  248. height = (height + 1) / 2;
  249. for (int y = 0; y < height; ++y)
  250. {
  251. DepthValue* src = mipBuffers_[i - 1].Get() + (y * 2) * prevWidth;
  252. DepthValue* dest = mipBuffers_[i].Get() + y * width;
  253. DepthValue* end = dest + width;
  254. if (y * 2 + 1 < prevHeight)
  255. {
  256. DepthValue* src2 = src + prevWidth;
  257. while (dest < end)
  258. {
  259. int minUpper = Min(src[0].min_, src[1].min_);
  260. int minLower = Min(src2[0].min_, src2[1].min_);
  261. dest->min_ = Min(minUpper, minLower);
  262. int maxUpper = Max(src[0].max_, src[1].max_);
  263. int maxLower = Max(src2[0].max_, src2[1].max_);
  264. dest->max_ = Max(maxUpper, maxLower);
  265. src += 2;
  266. src2 += 2;
  267. ++dest;
  268. }
  269. }
  270. else
  271. {
  272. while (dest < end)
  273. {
  274. dest->min_ = Min(src[0].min_, src[1].min_);
  275. dest->max_ = Max(src[0].max_, src[1].max_);
  276. src += 2;
  277. ++dest;
  278. }
  279. }
  280. }
  281. }
  282. depthHierarchyDirty_ = false;
  283. }
  284. void OcclusionBuffer::ResetUseTimer()
  285. {
  286. useTimer_.Reset();
  287. }
  288. bool OcclusionBuffer::IsVisible(const BoundingBox& worldSpaceBox) const
  289. {
  290. if (!buffer_)
  291. return true;
  292. // Transform corners to projection space
  293. Vector4 vertices[8];
  294. vertices[0] = ModelTransform(viewProj_, worldSpaceBox.min_);
  295. vertices[1] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.min_.y_, worldSpaceBox.min_.z_));
  296. vertices[2] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.max_.y_, worldSpaceBox.min_.z_));
  297. vertices[3] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.max_.y_, worldSpaceBox.min_.z_));
  298. vertices[4] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.min_.y_, worldSpaceBox.max_.z_));
  299. vertices[5] = ModelTransform(viewProj_, Vector3(worldSpaceBox.max_.x_, worldSpaceBox.min_.y_, worldSpaceBox.max_.z_));
  300. vertices[6] = ModelTransform(viewProj_, Vector3(worldSpaceBox.min_.x_, worldSpaceBox.max_.y_, worldSpaceBox.max_.z_));
  301. vertices[7] = ModelTransform(viewProj_, worldSpaceBox.max_);
  302. // Apply a far clip relative bias
  303. for (unsigned i = 0; i < 8; ++i)
  304. vertices[i].z_ -= OCCLUSION_RELATIVE_BIAS;
  305. // Transform to screen space. If any of the corners cross the near plane, assume visible
  306. float minX, maxX, minY, maxY, minZ;
  307. if (vertices[0].z_ <= 0.0f)
  308. return true;
  309. Vector3 projected = ViewportTransform(vertices[0]);
  310. minX = maxX = projected.x_;
  311. minY = maxY = projected.y_;
  312. minZ = projected.z_;
  313. // Project the rest
  314. for (unsigned i = 1; i < 8; ++i)
  315. {
  316. if (vertices[i].z_ <= 0.0f)
  317. return true;
  318. projected = ViewportTransform(vertices[i]);
  319. if (projected.x_ < minX) minX = projected.x_;
  320. if (projected.x_ > maxX) maxX = projected.x_;
  321. if (projected.y_ < minY) minY = projected.y_;
  322. if (projected.y_ > maxY) maxY = projected.y_;
  323. if (projected.z_ < minZ) minZ = projected.z_;
  324. }
  325. // Expand the bounding box 1 pixel in each direction to be conservative and correct rasterization offset
  326. IntRect rect(
  327. (int)(minX - 1.5f), (int)(minY - 1.5f),
  328. (int)(maxX + 0.5f), (int)(maxY + 0.5f)
  329. );
  330. // If the rect is outside, let frustum culling handle
  331. if (rect.right_ < 0 || rect.bottom_ < 0)
  332. return true;
  333. if (rect.left_ >= width_ || rect.top_ >= height_)
  334. return true;
  335. // Clipping of rect
  336. if (rect.left_ < 0)
  337. rect.left_ = 0;
  338. if (rect.top_ < 0)
  339. rect.top_ = 0;
  340. if (rect.right_ >= width_)
  341. rect.right_ = width_ - 1;
  342. if (rect.bottom_ >= height_)
  343. rect.bottom_ = height_ - 1;
  344. // Convert depth to integer and apply final bias
  345. int z = (int)(minZ + 0.5f) - OCCLUSION_FIXED_BIAS;
  346. if (!depthHierarchyDirty_)
  347. {
  348. // Start from lowest mip level and check if a conclusive result can be found
  349. for (int i = mipBuffers_.Size() - 1; i >= 0; --i)
  350. {
  351. int shift = i + 1;
  352. int width = width_ >> shift;
  353. int left = rect.left_ >> shift;
  354. int right = rect.right_ >> shift;
  355. DepthValue* buffer = mipBuffers_[i].Get();
  356. DepthValue* row = buffer + (rect.top_ >> shift) * width;
  357. DepthValue* endRow = buffer + (rect.bottom_ >> shift) * width;
  358. bool allOccluded = true;
  359. while (row <= endRow)
  360. {
  361. DepthValue* src = row + left;
  362. DepthValue* end = row + right;
  363. while (src <= end)
  364. {
  365. if (z <= src->min_)
  366. return true;
  367. if (z <= src->max_)
  368. allOccluded = false;
  369. ++src;
  370. }
  371. row += width;
  372. }
  373. if (allOccluded)
  374. return false;
  375. }
  376. }
  377. // If no conclusive result, finally check the pixel-level data
  378. int* row = buffer_ + rect.top_ * width_;
  379. int* endRow = buffer_ + rect.bottom_ * width_;
  380. while (row <= endRow)
  381. {
  382. int* src = row + rect.left_;
  383. int* end = row + rect.right_;
  384. while (src <= end)
  385. {
  386. if (z <= *src)
  387. return true;
  388. ++src;
  389. }
  390. row += width_;
  391. }
  392. return false;
  393. }
  394. unsigned OcclusionBuffer::GetUseTimer()
  395. {
  396. return useTimer_.GetMSec(false);
  397. }
  398. inline Vector4 OcclusionBuffer::ModelTransform(const Matrix4& transform, const Vector3& vertex) const
  399. {
  400. return Vector4(
  401. transform.m00_ * vertex.x_ + transform.m01_ * vertex.y_ + transform.m02_ * vertex.z_ + transform.m03_,
  402. transform.m10_ * vertex.x_ + transform.m11_ * vertex.y_ + transform.m12_ * vertex.z_ + transform.m13_,
  403. transform.m20_ * vertex.x_ + transform.m21_ * vertex.y_ + transform.m22_ * vertex.z_ + transform.m23_,
  404. transform.m30_ * vertex.x_ + transform.m31_ * vertex.y_ + transform.m32_ * vertex.z_ + transform.m33_
  405. );
  406. }
  407. inline Vector3 OcclusionBuffer::ViewportTransform(const Vector4& vertex) const
  408. {
  409. float invW = 1.0f / vertex.w_;
  410. return Vector3(
  411. invW * vertex.x_ * scaleX_ + offsetX_,
  412. invW * vertex.y_ * scaleY_ + offsetY_,
  413. invW * vertex.z_ * OCCLUSION_Z_SCALE
  414. );
  415. }
  416. inline Vector4 OcclusionBuffer::ClipEdge(const Vector4& v0, const Vector4& v1, float d0, float d1) const
  417. {
  418. float t = d0 / (d0 - d1);
  419. return v0 + t * (v1 - v0);
  420. }
  421. inline bool OcclusionBuffer::CheckFacing(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  422. {
  423. if (cullMode_ == CULL_NONE)
  424. return true;
  425. float aX = v0.x_ - v1.x_;
  426. float aY = v0.y_ - v1.y_;
  427. float bX = v2.x_ - v1.x_;
  428. float bY = v2.y_ - v1.y_;
  429. float signedArea = aX * bY - aY * bX;
  430. if (cullMode_ == CULL_CCW)
  431. return signedArea < 0.0f;
  432. else
  433. return signedArea > 0.0f;
  434. }
  435. void OcclusionBuffer::CalculateViewport()
  436. {
  437. // Add half pixel offset due to 3D frustum culling
  438. scaleX_ = 0.5f * width_;
  439. scaleY_ = -0.5f * height_;
  440. offsetX_ = 0.5f * width_ + 0.5f;
  441. offsetY_ = 0.5f * height_ + 0.5f;
  442. projOffsetScaleX_ = projection_.m00_ * scaleX_;
  443. projOffsetScaleY_ = projection_.m11_ * scaleY_;
  444. }
  445. void OcclusionBuffer::DrawTriangle(Vector4* vertices)
  446. {
  447. unsigned clipMask = 0;
  448. unsigned andClipMask = 0;
  449. bool drawOk = false;
  450. Vector3 projected[3];
  451. // Build the clip plane mask for the triangle
  452. for (unsigned i = 0; i < 3; ++i)
  453. {
  454. unsigned vertexClipMask = 0;
  455. if (vertices[i].x_ > vertices[i].w_)
  456. vertexClipMask |= CLIPMASK_X_POS;
  457. if (vertices[i].x_ < -vertices[i].w_)
  458. vertexClipMask |= CLIPMASK_X_NEG;
  459. if (vertices[i].y_ > vertices[i].w_)
  460. vertexClipMask |= CLIPMASK_Y_POS;
  461. if (vertices[i].y_ < -vertices[i].w_)
  462. vertexClipMask |= CLIPMASK_Y_NEG;
  463. if (vertices[i].z_ > vertices[i].w_)
  464. vertexClipMask |= CLIPMASK_Z_POS;
  465. if (vertices[i].z_ < 0.0f)
  466. vertexClipMask |= CLIPMASK_Z_NEG;
  467. clipMask |= vertexClipMask;
  468. if (!i)
  469. andClipMask = vertexClipMask;
  470. else
  471. andClipMask &= vertexClipMask;
  472. }
  473. // If triangle is fully behind any clip plane, can reject quickly
  474. if (andClipMask)
  475. return;
  476. // Check if triangle is fully inside
  477. if (!clipMask)
  478. {
  479. projected[0] = ViewportTransform(vertices[0]);
  480. projected[1] = ViewportTransform(vertices[1]);
  481. projected[2] = ViewportTransform(vertices[2]);
  482. if (CheckFacing(projected[0], projected[1], projected[2]))
  483. {
  484. DrawTriangle2D(projected);
  485. drawOk = true;
  486. }
  487. }
  488. else
  489. {
  490. bool triangles[64];
  491. // Initial triangle
  492. triangles[0] = true;
  493. unsigned numTriangles = 1;
  494. if (clipMask & CLIPMASK_X_POS)
  495. ClipVertices(Vector4(-1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  496. if (clipMask & CLIPMASK_X_NEG)
  497. ClipVertices(Vector4(1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  498. if (clipMask & CLIPMASK_Y_POS)
  499. ClipVertices(Vector4(0.0f, -1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  500. if (clipMask & CLIPMASK_Y_NEG)
  501. ClipVertices(Vector4(0.0f, 1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  502. if (clipMask & CLIPMASK_Z_POS)
  503. ClipVertices(Vector4(0.0f, 0.0f, -1.0f, 1.0f), vertices, triangles, numTriangles);
  504. if (clipMask & CLIPMASK_Z_NEG)
  505. ClipVertices(Vector4(0.0f, 0.0f, 1.0f, 0.0f), vertices, triangles, numTriangles);
  506. // Draw each accepted triangle
  507. for (unsigned i = 0; i < numTriangles; ++i)
  508. {
  509. if (triangles[i])
  510. {
  511. unsigned index = i * 3;
  512. projected[0] = ViewportTransform(vertices[index]);
  513. projected[1] = ViewportTransform(vertices[index + 1]);
  514. projected[2] = ViewportTransform(vertices[index + 2]);
  515. if (CheckFacing(projected[0], projected[1], projected[2]))
  516. {
  517. DrawTriangle2D(projected);
  518. drawOk = true;
  519. }
  520. }
  521. }
  522. }
  523. if (drawOk)
  524. ++numTriangles_;
  525. }
  526. void OcclusionBuffer::ClipVertices(const Vector4& plane, Vector4* vertices, bool* triangles, unsigned& numTriangles)
  527. {
  528. unsigned num = numTriangles;
  529. for (unsigned i = 0; i < num; ++i)
  530. {
  531. if (triangles[i])
  532. {
  533. unsigned index = i * 3;
  534. float d0 = plane.DotProduct(vertices[index]);
  535. float d1 = plane.DotProduct(vertices[index + 1]);
  536. float d2 = plane.DotProduct(vertices[index + 2]);
  537. // If all vertices behind the plane, reject triangle
  538. if (d0 < 0.0f && d1 < 0.0f && d2 < 0.0f)
  539. {
  540. triangles[i] = false;
  541. continue;
  542. }
  543. // If 2 vertices behind the plane, create a new triangle in-place
  544. else if (d0 < 0.0f && d1 < 0.0f)
  545. {
  546. vertices[index] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  547. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  548. }
  549. else if (d0 < 0.0f && d2 < 0.0f)
  550. {
  551. vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  552. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  553. }
  554. else if (d1 < 0.0f && d2 < 0.0f)
  555. {
  556. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  557. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  558. }
  559. // 1 vertex behind the plane: create one new triangle, and modify one in-place
  560. else if (d0 < 0.0f)
  561. {
  562. unsigned newIdx = numTriangles * 3;
  563. triangles[numTriangles] = true;
  564. ++numTriangles;
  565. vertices[newIdx] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  566. vertices[newIdx + 1] = vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  567. vertices[newIdx + 2] = vertices[index + 2];
  568. }
  569. else if (d1 < 0.0f)
  570. {
  571. unsigned newIdx = numTriangles * 3;
  572. triangles[numTriangles] = true;
  573. ++numTriangles;
  574. vertices[newIdx + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  575. vertices[newIdx + 2] = vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  576. vertices[newIdx] = vertices[index];
  577. }
  578. else if (d2 < 0.0f)
  579. {
  580. unsigned newIdx = numTriangles * 3;
  581. triangles[numTriangles] = true;
  582. ++numTriangles;
  583. vertices[newIdx + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  584. vertices[newIdx] = vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  585. vertices[newIdx + 1] = vertices[index + 1];
  586. }
  587. }
  588. }
  589. }
  590. // Code based on Chris Hecker's Perspective Texture Mapping series in the Game Developer magazine
  591. // Also available online at http://chrishecker.com/Miscellaneous_Technical_Articles
  592. /// %Gradients of a software rasterized triangle.
  593. struct Gradients
  594. {
  595. /// Construct from vertices.
  596. Gradients(const Vector3* vertices)
  597. {
  598. float invdX = 1.0f / (((vertices[1].x_ - vertices[2].x_) *
  599. (vertices[0].y_ - vertices[2].y_)) -
  600. ((vertices[0].x_ - vertices[2].x_) *
  601. (vertices[1].y_ - vertices[2].y_)));
  602. float invdY = -invdX;
  603. dInvZdX_ = invdX * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].y_ - vertices[2].y_)) -
  604. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].y_ - vertices[2].y_)));
  605. dInvZdY_ = invdY * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].x_ - vertices[2].x_)) -
  606. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].x_ - vertices[2].x_)));
  607. dInvZdXInt_ = (int)dInvZdX_;
  608. }
  609. /// Integer horizontal gradient.
  610. int dInvZdXInt_;
  611. /// Horizontal gradient.
  612. float dInvZdX_;
  613. /// Vertical gradient.
  614. float dInvZdY_;
  615. };
  616. /// %Edge of a software rasterized triangle.
  617. struct Edge
  618. {
  619. /// Construct from gradients and top & bottom vertices.
  620. Edge(const Gradients& gradients, const Vector3& top, const Vector3& bottom, int topY)
  621. {
  622. float slope = (bottom.x_ - top.x_) / (bottom.y_ - top.y_);
  623. float yPreStep = (float)(topY + 1) - top.y_;
  624. float xPreStep = slope * yPreStep;
  625. x_ = (int)((xPreStep + top.x_) * OCCLUSION_X_SCALE + 0.5f);
  626. xStep_ = (int)(slope * OCCLUSION_X_SCALE + 0.5f);
  627. invZ_ = (int)(top.z_ + xPreStep * gradients.dInvZdX_ + yPreStep * gradients.dInvZdY_ + 0.5f);
  628. invZStep_ = (int)(slope * gradients.dInvZdX_ + gradients.dInvZdY_ + 0.5f);
  629. }
  630. /// X coordinate.
  631. int x_;
  632. /// X coordinate step.
  633. int xStep_;
  634. /// Inverse Z.
  635. int invZ_;
  636. /// Inverse Z step.
  637. int invZStep_;
  638. };
  639. void OcclusionBuffer::DrawTriangle2D(const Vector3* vertices)
  640. {
  641. int top, middle, bottom;
  642. bool middleIsRight;
  643. // Sort vertices in Y-direction
  644. if (vertices[0].y_ < vertices[1].y_)
  645. {
  646. if (vertices[2].y_ < vertices[0].y_)
  647. {
  648. top = 2; middle = 0; bottom = 1;
  649. middleIsRight = true;
  650. }
  651. else
  652. {
  653. top = 0;
  654. if (vertices[1].y_ < vertices[2].y_)
  655. {
  656. middle = 1; bottom = 2;
  657. middleIsRight = true;
  658. }
  659. else
  660. {
  661. middle = 2; bottom = 1;
  662. middleIsRight = false;
  663. }
  664. }
  665. }
  666. else
  667. {
  668. if (vertices[2].y_ < vertices[1].y_)
  669. {
  670. top = 2; middle = 1; bottom = 0;
  671. middleIsRight = false;
  672. }
  673. else
  674. {
  675. top = 1;
  676. if (vertices[0].y_ < vertices[2].y_)
  677. {
  678. middle = 0; bottom = 2;
  679. middleIsRight = false;
  680. }
  681. else
  682. {
  683. middle = 2; bottom = 0;
  684. middleIsRight = true;
  685. }
  686. }
  687. }
  688. int topY = (int)vertices[top].y_;
  689. int middleY = (int)vertices[middle].y_;
  690. int bottomY = (int)vertices[bottom].y_;
  691. // Check for degenerate triangle
  692. if (topY == bottomY)
  693. return;
  694. Gradients gradients(vertices);
  695. Edge topToMiddle(gradients, vertices[top], vertices[middle], topY);
  696. Edge topToBottom(gradients, vertices[top], vertices[bottom], topY);
  697. Edge middleToBottom(gradients, vertices[middle], vertices[bottom], middleY);
  698. // The triangle is clockwise, so if bottom > middle then middle is right
  699. if (middleIsRight)
  700. {
  701. // Top half
  702. int* row = buffer_ + topY * width_;
  703. int* endRow = buffer_ + middleY * width_;
  704. while (row < endRow)
  705. {
  706. int invZ = topToBottom.invZ_;
  707. int* dest = row + (topToBottom.x_ >> 16);
  708. int* end = row + (topToMiddle.x_ >> 16);
  709. while (dest < end)
  710. {
  711. if (invZ < *dest)
  712. *dest = invZ;
  713. invZ += gradients.dInvZdXInt_;
  714. ++dest;
  715. }
  716. topToBottom.x_ += topToBottom.xStep_;
  717. topToBottom.invZ_ += topToBottom.invZStep_;
  718. topToMiddle.x_ += topToMiddle.xStep_;
  719. row += width_;
  720. }
  721. // Bottom half
  722. row = buffer_ + middleY * width_;
  723. endRow = buffer_ + bottomY * width_;
  724. while (row < endRow)
  725. {
  726. int invZ = topToBottom.invZ_;
  727. int* dest = row + (topToBottom.x_ >> 16);
  728. int* end = row + (middleToBottom.x_ >> 16);
  729. while (dest < end)
  730. {
  731. if (invZ < *dest)
  732. *dest = invZ;
  733. invZ += gradients.dInvZdXInt_;
  734. ++dest;
  735. }
  736. topToBottom.x_ += topToBottom.xStep_;
  737. topToBottom.invZ_ += topToBottom.invZStep_;
  738. middleToBottom.x_ += middleToBottom.xStep_;
  739. row += width_;
  740. }
  741. }
  742. else
  743. {
  744. // Top half
  745. int* row = buffer_ + topY * width_;
  746. int* endRow = buffer_ + middleY * width_;
  747. while (row < endRow)
  748. {
  749. int invZ = topToMiddle.invZ_;
  750. int* dest = row + (topToMiddle.x_ >> 16);
  751. int* end = row + (topToBottom.x_ >> 16);
  752. while (dest < end)
  753. {
  754. if (invZ < *dest)
  755. *dest = invZ;
  756. invZ += gradients.dInvZdXInt_;
  757. ++dest;
  758. }
  759. topToMiddle.x_ += topToMiddle.xStep_;
  760. topToMiddle.invZ_ += topToMiddle.invZStep_;
  761. topToBottom.x_ += topToBottom.xStep_;
  762. row += width_;
  763. }
  764. // Bottom half
  765. row = buffer_ + middleY * width_;
  766. endRow = buffer_ + bottomY * width_;
  767. while (row < endRow)
  768. {
  769. int invZ = middleToBottom.invZ_;
  770. int* dest = row + (middleToBottom.x_ >> 16);
  771. int* end = row + (topToBottom.x_ >> 16);
  772. while (dest < end)
  773. {
  774. if (invZ < *dest)
  775. *dest = invZ;
  776. invZ += gradients.dInvZdXInt_;
  777. ++dest;
  778. }
  779. middleToBottom.x_ += middleToBottom.xStep_;
  780. middleToBottom.invZ_ += middleToBottom.invZStep_;
  781. topToBottom.x_ += topToBottom.xStep_;
  782. row += width_;
  783. }
  784. }
  785. }
  786. }