OcclusionBuffer.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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 float OcclusionBuffer::SignedArea(const Vector3& v0, const Vector3& v1, const Vector3& v2) const
  422. {
  423. float aX = v0.x_ - v1.x_;
  424. float aY = v0.y_ - v1.y_;
  425. float bX = v2.x_ - v1.x_;
  426. float bY = v2.y_ - v1.y_;
  427. return aX * bY - aY * bX;
  428. }
  429. void OcclusionBuffer::CalculateViewport()
  430. {
  431. // Add half pixel offset due to 3D frustum culling
  432. scaleX_ = 0.5f * width_;
  433. scaleY_ = -0.5f * height_;
  434. offsetX_ = 0.5f * width_ + 0.5f;
  435. offsetY_ = 0.5f * height_ + 0.5f;
  436. projOffsetScaleX_ = projection_.m00_ * scaleX_;
  437. projOffsetScaleY_ = projection_.m11_ * scaleY_;
  438. }
  439. void OcclusionBuffer::DrawTriangle(Vector4* vertices)
  440. {
  441. unsigned clipMask = 0;
  442. unsigned andClipMask = 0;
  443. bool drawOk = false;
  444. Vector3 projected[3];
  445. // Build the clip plane mask for the triangle
  446. for (unsigned i = 0; i < 3; ++i)
  447. {
  448. unsigned vertexClipMask = 0;
  449. if (vertices[i].x_ > vertices[i].w_)
  450. vertexClipMask |= CLIPMASK_X_POS;
  451. if (vertices[i].x_ < -vertices[i].w_)
  452. vertexClipMask |= CLIPMASK_X_NEG;
  453. if (vertices[i].y_ > vertices[i].w_)
  454. vertexClipMask |= CLIPMASK_Y_POS;
  455. if (vertices[i].y_ < -vertices[i].w_)
  456. vertexClipMask |= CLIPMASK_Y_NEG;
  457. if (vertices[i].z_ > vertices[i].w_)
  458. vertexClipMask |= CLIPMASK_Z_POS;
  459. if (vertices[i].z_ < 0.0f)
  460. vertexClipMask |= CLIPMASK_Z_NEG;
  461. clipMask |= vertexClipMask;
  462. if (!i)
  463. andClipMask = vertexClipMask;
  464. else
  465. andClipMask &= vertexClipMask;
  466. }
  467. // If triangle is fully behind any clip plane, can reject quickly
  468. if (andClipMask)
  469. return;
  470. // Check if triangle is fully inside
  471. if (!clipMask)
  472. {
  473. projected[0] = ViewportTransform(vertices[0]);
  474. projected[1] = ViewportTransform(vertices[1]);
  475. projected[2] = ViewportTransform(vertices[2]);
  476. bool clockwise = SignedArea(projected[0], projected[1], projected[2]) < 0.0f;
  477. if (cullMode_ == CULL_NONE || (cullMode_ == CULL_CCW && clockwise) || (cullMode_ == CULL_CW && !clockwise))
  478. {
  479. DrawTriangle2D(projected, clockwise);
  480. drawOk = true;
  481. }
  482. }
  483. else
  484. {
  485. bool triangles[64];
  486. // Initial triangle
  487. triangles[0] = true;
  488. unsigned numTriangles = 1;
  489. if (clipMask & CLIPMASK_X_POS)
  490. ClipVertices(Vector4(-1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  491. if (clipMask & CLIPMASK_X_NEG)
  492. ClipVertices(Vector4(1.0f, 0.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  493. if (clipMask & CLIPMASK_Y_POS)
  494. ClipVertices(Vector4(0.0f, -1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  495. if (clipMask & CLIPMASK_Y_NEG)
  496. ClipVertices(Vector4(0.0f, 1.0f, 0.0f, 1.0f), vertices, triangles, numTriangles);
  497. if (clipMask & CLIPMASK_Z_POS)
  498. ClipVertices(Vector4(0.0f, 0.0f, -1.0f, 1.0f), vertices, triangles, numTriangles);
  499. if (clipMask & CLIPMASK_Z_NEG)
  500. ClipVertices(Vector4(0.0f, 0.0f, 1.0f, 0.0f), vertices, triangles, numTriangles);
  501. // Draw each accepted triangle
  502. for (unsigned i = 0; i < numTriangles; ++i)
  503. {
  504. if (triangles[i])
  505. {
  506. unsigned index = i * 3;
  507. projected[0] = ViewportTransform(vertices[index]);
  508. projected[1] = ViewportTransform(vertices[index + 1]);
  509. projected[2] = ViewportTransform(vertices[index + 2]);
  510. bool clockwise = SignedArea(projected[0], projected[1], projected[2]) < 0.0f;
  511. if (cullMode_ == CULL_NONE || (cullMode_ == CULL_CCW && clockwise) || (cullMode_ == CULL_CW && !clockwise))
  512. {
  513. DrawTriangle2D(projected, clockwise);
  514. drawOk = true;
  515. }
  516. }
  517. }
  518. }
  519. if (drawOk)
  520. ++numTriangles_;
  521. }
  522. void OcclusionBuffer::ClipVertices(const Vector4& plane, Vector4* vertices, bool* triangles, unsigned& numTriangles)
  523. {
  524. unsigned num = numTriangles;
  525. for (unsigned i = 0; i < num; ++i)
  526. {
  527. if (triangles[i])
  528. {
  529. unsigned index = i * 3;
  530. float d0 = plane.DotProduct(vertices[index]);
  531. float d1 = plane.DotProduct(vertices[index + 1]);
  532. float d2 = plane.DotProduct(vertices[index + 2]);
  533. // If all vertices behind the plane, reject triangle
  534. if (d0 < 0.0f && d1 < 0.0f && d2 < 0.0f)
  535. {
  536. triangles[i] = false;
  537. continue;
  538. }
  539. // If 2 vertices behind the plane, create a new triangle in-place
  540. else if (d0 < 0.0f && d1 < 0.0f)
  541. {
  542. vertices[index] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  543. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  544. }
  545. else if (d0 < 0.0f && d2 < 0.0f)
  546. {
  547. vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  548. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  549. }
  550. else if (d1 < 0.0f && d2 < 0.0f)
  551. {
  552. vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  553. vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  554. }
  555. // 1 vertex behind the plane: create one new triangle, and modify one in-place
  556. else if (d0 < 0.0f)
  557. {
  558. unsigned newIdx = numTriangles * 3;
  559. triangles[numTriangles] = true;
  560. ++numTriangles;
  561. vertices[newIdx] = ClipEdge(vertices[index], vertices[index + 2], d0, d2);
  562. vertices[newIdx + 1] = vertices[index] = ClipEdge(vertices[index], vertices[index + 1], d0, d1);
  563. vertices[newIdx + 2] = vertices[index + 2];
  564. }
  565. else if (d1 < 0.0f)
  566. {
  567. unsigned newIdx = numTriangles * 3;
  568. triangles[numTriangles] = true;
  569. ++numTriangles;
  570. vertices[newIdx + 1] = ClipEdge(vertices[index + 1], vertices[index], d1, d0);
  571. vertices[newIdx + 2] = vertices[index + 1] = ClipEdge(vertices[index + 1], vertices[index + 2], d1, d2);
  572. vertices[newIdx] = vertices[index];
  573. }
  574. else if (d2 < 0.0f)
  575. {
  576. unsigned newIdx = numTriangles * 3;
  577. triangles[numTriangles] = true;
  578. ++numTriangles;
  579. vertices[newIdx + 2] = ClipEdge(vertices[index + 2], vertices[index + 1], d2, d1);
  580. vertices[newIdx] = vertices[index + 2] = ClipEdge(vertices[index + 2], vertices[index], d2, d0);
  581. vertices[newIdx + 1] = vertices[index + 1];
  582. }
  583. }
  584. }
  585. }
  586. // Code based on Chris Hecker's Perspective Texture Mapping series in the Game Developer magazine
  587. // Also available online at http://chrishecker.com/Miscellaneous_Technical_Articles
  588. /// %Gradients of a software rasterized triangle.
  589. struct Gradients
  590. {
  591. /// Construct from vertices.
  592. Gradients(const Vector3* vertices)
  593. {
  594. float invdX = 1.0f / (((vertices[1].x_ - vertices[2].x_) *
  595. (vertices[0].y_ - vertices[2].y_)) -
  596. ((vertices[0].x_ - vertices[2].x_) *
  597. (vertices[1].y_ - vertices[2].y_)));
  598. float invdY = -invdX;
  599. dInvZdX_ = invdX * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].y_ - vertices[2].y_)) -
  600. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].y_ - vertices[2].y_)));
  601. dInvZdY_ = invdY * (((vertices[1].z_ - vertices[2].z_) * (vertices[0].x_ - vertices[2].x_)) -
  602. ((vertices[0].z_ - vertices[2].z_) * (vertices[1].x_ - vertices[2].x_)));
  603. dInvZdXInt_ = (int)dInvZdX_;
  604. }
  605. /// Integer horizontal gradient.
  606. int dInvZdXInt_;
  607. /// Horizontal gradient.
  608. float dInvZdX_;
  609. /// Vertical gradient.
  610. float dInvZdY_;
  611. };
  612. /// %Edge of a software rasterized triangle.
  613. struct Edge
  614. {
  615. /// Construct from gradients and top & bottom vertices.
  616. Edge(const Gradients& gradients, const Vector3& top, const Vector3& bottom, int topY)
  617. {
  618. float height = (bottom.y_ - top.y_);
  619. float slope = (height != 0.0f) ? (bottom.x_ - top.x_) / height : 0.0f;
  620. float yPreStep = (float)(topY + 1) - top.y_;
  621. float xPreStep = slope * yPreStep;
  622. x_ = (int)((xPreStep + top.x_) * OCCLUSION_X_SCALE + 0.5f);
  623. xStep_ = (int)(slope * OCCLUSION_X_SCALE + 0.5f);
  624. invZ_ = (int)(top.z_ + xPreStep * gradients.dInvZdX_ + yPreStep * gradients.dInvZdY_ + 0.5f);
  625. invZStep_ = (int)(slope * gradients.dInvZdX_ + gradients.dInvZdY_ + 0.5f);
  626. }
  627. /// X coordinate.
  628. int x_;
  629. /// X coordinate step.
  630. int xStep_;
  631. /// Inverse Z.
  632. int invZ_;
  633. /// Inverse Z step.
  634. int invZStep_;
  635. };
  636. void OcclusionBuffer::DrawTriangle2D(const Vector3* vertices, bool clockwise)
  637. {
  638. int top, middle, bottom;
  639. bool middleIsRight;
  640. // Sort vertices in Y-direction
  641. if (vertices[0].y_ < vertices[1].y_)
  642. {
  643. if (vertices[2].y_ < vertices[0].y_)
  644. {
  645. top = 2; middle = 0; bottom = 1;
  646. middleIsRight = true;
  647. }
  648. else
  649. {
  650. top = 0;
  651. if (vertices[1].y_ < vertices[2].y_)
  652. {
  653. middle = 1; bottom = 2;
  654. middleIsRight = true;
  655. }
  656. else
  657. {
  658. middle = 2; bottom = 1;
  659. middleIsRight = false;
  660. }
  661. }
  662. }
  663. else
  664. {
  665. if (vertices[2].y_ < vertices[1].y_)
  666. {
  667. top = 2; middle = 1; bottom = 0;
  668. middleIsRight = false;
  669. }
  670. else
  671. {
  672. top = 1;
  673. if (vertices[0].y_ < vertices[2].y_)
  674. {
  675. middle = 0; bottom = 2;
  676. middleIsRight = false;
  677. }
  678. else
  679. {
  680. middle = 2; bottom = 0;
  681. middleIsRight = true;
  682. }
  683. }
  684. }
  685. int topY = (int)vertices[top].y_;
  686. int middleY = (int)vertices[middle].y_;
  687. int bottomY = (int)vertices[bottom].y_;
  688. // Check for degenerate triangle
  689. if (topY == bottomY)
  690. return;
  691. // Reverse middleIsRight test if triangle is counterclockwise
  692. if (!clockwise)
  693. middleIsRight = !middleIsRight;
  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. if (middleIsRight)
  699. {
  700. // Top half
  701. int* row = buffer_ + topY * width_;
  702. int* endRow = buffer_ + middleY * width_;
  703. while (row < endRow)
  704. {
  705. int invZ = topToBottom.invZ_;
  706. int* dest = row + (topToBottom.x_ >> 16);
  707. int* end = row + (topToMiddle.x_ >> 16);
  708. while (dest < end)
  709. {
  710. if (invZ < *dest)
  711. *dest = invZ;
  712. invZ += gradients.dInvZdXInt_;
  713. ++dest;
  714. }
  715. topToBottom.x_ += topToBottom.xStep_;
  716. topToBottom.invZ_ += topToBottom.invZStep_;
  717. topToMiddle.x_ += topToMiddle.xStep_;
  718. row += width_;
  719. }
  720. // Bottom half
  721. row = buffer_ + middleY * width_;
  722. endRow = buffer_ + bottomY * width_;
  723. while (row < endRow)
  724. {
  725. int invZ = topToBottom.invZ_;
  726. int* dest = row + (topToBottom.x_ >> 16);
  727. int* end = row + (middleToBottom.x_ >> 16);
  728. while (dest < end)
  729. {
  730. if (invZ < *dest)
  731. *dest = invZ;
  732. invZ += gradients.dInvZdXInt_;
  733. ++dest;
  734. }
  735. topToBottom.x_ += topToBottom.xStep_;
  736. topToBottom.invZ_ += topToBottom.invZStep_;
  737. middleToBottom.x_ += middleToBottom.xStep_;
  738. row += width_;
  739. }
  740. }
  741. else
  742. {
  743. // Top half
  744. int* row = buffer_ + topY * width_;
  745. int* endRow = buffer_ + middleY * width_;
  746. while (row < endRow)
  747. {
  748. int invZ = topToMiddle.invZ_;
  749. int* dest = row + (topToMiddle.x_ >> 16);
  750. int* end = row + (topToBottom.x_ >> 16);
  751. while (dest < end)
  752. {
  753. if (invZ < *dest)
  754. *dest = invZ;
  755. invZ += gradients.dInvZdXInt_;
  756. ++dest;
  757. }
  758. topToMiddle.x_ += topToMiddle.xStep_;
  759. topToMiddle.invZ_ += topToMiddle.invZStep_;
  760. topToBottom.x_ += topToBottom.xStep_;
  761. row += width_;
  762. }
  763. // Bottom half
  764. row = buffer_ + middleY * width_;
  765. endRow = buffer_ + bottomY * width_;
  766. while (row < endRow)
  767. {
  768. int invZ = middleToBottom.invZ_;
  769. int* dest = row + (middleToBottom.x_ >> 16);
  770. int* end = row + (topToBottom.x_ >> 16);
  771. while (dest < end)
  772. {
  773. if (invZ < *dest)
  774. *dest = invZ;
  775. invZ += gradients.dInvZdXInt_;
  776. ++dest;
  777. }
  778. middleToBottom.x_ += middleToBottom.xStep_;
  779. middleToBottom.invZ_ += middleToBottom.invZStep_;
  780. topToBottom.x_ += topToBottom.xStep_;
  781. row += width_;
  782. }
  783. }
  784. }
  785. }