renderCore.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2019 David Forsgren Piuva
  4. //
  5. // This software is provided 'as-is', without any express or implied
  6. // warranty. In no event will the authors be held liable for any damages
  7. // arising from the use of this software.
  8. //
  9. // Permission is granted to anyone to use this software for any purpose,
  10. // including commercial applications, and to alter it and redistribute it
  11. // freely, subject to the following restrictions:
  12. //
  13. // 1. The origin of this software must not be misrepresented; you must not
  14. // claim that you wrote the original software. If you use this software
  15. // in a product, an acknowledgment in the product documentation would be
  16. // appreciated but is not required.
  17. //
  18. // 2. Altered source versions must be plainly marked as such, and must not be
  19. // misrepresented as being the original software.
  20. //
  21. // 3. This notice may not be removed or altered from any source
  22. // distribution.
  23. #include <cassert>
  24. #include "renderCore.h"
  25. #include "../image/internal/imageInternal.h"
  26. #include "shader/Shader.h"
  27. #include "shader/RgbaMultiply.h"
  28. #include "constants.h"
  29. using namespace dsr;
  30. //#define DISABLE_VERTEX_COLOR
  31. //#define DISABLE_DIFFUSE_MAP
  32. //#define DISABLE_LIGHT_MAP
  33. class SubVertex {
  34. public:
  35. FVector3D cs; // Camera space position based on the weights
  36. float subB, subC; // Weights for second and third vertices in the parent triangle
  37. int state = 0; // Used by algorithms
  38. float value = 0.0f; // Used by algorithms
  39. SubVertex() : cs(FVector3D()), subB(0.0f), subC(0.0f) {}
  40. SubVertex(FVector3D cs, float subB, float subC) : cs(cs), subB(subB), subC(subC) {}
  41. SubVertex(SubVertex vertexA, SubVertex vertexB, float ratio) {
  42. float invRatio = 1.0f - ratio;
  43. this->cs = vertexA.cs * invRatio + vertexB.cs * ratio;
  44. this->subB = vertexA.subB * invRatio + vertexB.subB * ratio;
  45. this->subC = vertexA.subC * invRatio + vertexB.subC * ratio;
  46. }
  47. };
  48. class ClippedTriangle {
  49. private:
  50. static const int maxPoints = 9; // If a triangle starts with 3 points and each of 6 planes in the view frustum can add one point each then the maximum is 9 points
  51. int vertexCount = 0;
  52. public:
  53. int getVertexCount() {
  54. return this->vertexCount;
  55. }
  56. SubVertex vertices[maxPoints] = {};
  57. ClippedTriangle(const ITriangle2D &triangle) {
  58. this->vertices[0] = SubVertex(triangle.position[0].cs, 0.0f, 0.0f);
  59. this->vertices[1] = SubVertex(triangle.position[1].cs, 1.0f, 0.0f);
  60. this->vertices[2] = SubVertex(triangle.position[2].cs, 0.0f, 1.0f);
  61. this->vertexCount = 3;
  62. }
  63. void deleteVertex(int removeIndex) {
  64. assert(removeIndex >= 0);
  65. assert(removeIndex < this->vertexCount);
  66. if (this->vertexCount > 0 && this->vertexCount <= maxPoints) {
  67. for (int v = removeIndex; v < this->vertexCount - 1; v++) {
  68. assert(v >= 0 && v + 1 < maxPoints);
  69. this->vertices[v] = this->vertices[v + 1];
  70. }
  71. this->vertexCount--;
  72. }
  73. }
  74. void insertVertex(int newIndex, const SubVertex &newVertex) {
  75. // Check against buffer overflow in case of bugs from rounding errors
  76. assert(newIndex >= 0);
  77. assert(newIndex <= this->vertexCount);
  78. if (this->vertexCount < maxPoints) {
  79. for (int v = this->vertexCount - 1; v >= newIndex; v--) {
  80. assert(v >= 0 && v + 1 < maxPoints);
  81. this->vertices[v + 1] = this->vertices[v];
  82. }
  83. this->vertices[newIndex] = newVertex;
  84. this->vertexCount++;
  85. }
  86. }
  87. void deleteAll() {
  88. this->vertexCount = 0;
  89. }
  90. // Returns 0 when value = a
  91. // Returns 0.5 when value = (a + b) / 2
  92. // Returns 1 when value = b
  93. static float inverseLerp(float a, float b, float value) {
  94. float c = b - a;
  95. if (c == 0.0f) {
  96. return 0.5f;
  97. } else {
  98. return (value - a) / c;
  99. }
  100. }
  101. // Cut away parts of the triangle that are on the positive side of the plane
  102. void clip(const FPlane3D &plane) {
  103. static const int state_use = 0;
  104. static const int state_delete = 1;
  105. static const int state_modified = 2;
  106. if (this->vertexCount >= 3 && this->vertexCount < maxPoints) {
  107. int outsideCount = 0;
  108. int lastOutside = 0;
  109. for (int v = 0; v < this->vertexCount; v++) {
  110. assert(v >= 0 && v < maxPoints);
  111. float distance = plane.signedDistance(this->vertices[v].cs);
  112. this->vertices[v].value = distance;
  113. if (distance > 0.0f) {
  114. outsideCount++;
  115. lastOutside = v;
  116. this->vertices[v].state = state_delete;
  117. } else {
  118. this->vertices[v].state = state_use;
  119. }
  120. }
  121. if (outsideCount > 0) {
  122. if (outsideCount >= this->vertexCount) {
  123. this->deleteAll();
  124. } else if (outsideCount == 1) {
  125. // Split a single vertex into two corners by interpolating with the previous and next corners
  126. int currentVertex = lastOutside;
  127. int previousVertex = (lastOutside - 1 + this->vertexCount) % this->vertexCount;
  128. int nextVertex = (lastOutside + 1) % this->vertexCount;
  129. float previousToCurrentRatio = inverseLerp(this->vertices[previousVertex].value, this->vertices[currentVertex].value, 0.0f);
  130. float currentToNextRatio = inverseLerp(this->vertices[currentVertex].value, this->vertices[nextVertex].value, 0.0f);
  131. SubVertex cutStart(this->vertices[previousVertex], this->vertices[currentVertex], previousToCurrentRatio);
  132. SubVertex cutEnd(this->vertices[currentVertex], this->vertices[nextVertex], currentToNextRatio);
  133. this->vertices[lastOutside] = cutStart;
  134. insertVertex(nextVertex, cutEnd);
  135. } else {
  136. // Start and end of the cut
  137. for (int currentVertex = 0; currentVertex < this->vertexCount; currentVertex++) {
  138. int previousVertex = (currentVertex - 1 + this->vertexCount) % this->vertexCount;
  139. int nextVertex = (currentVertex + 1) % this->vertexCount;
  140. if (this->vertices[currentVertex].state == state_delete) {
  141. if (this->vertices[previousVertex].state == state_use) {
  142. // Begin the cut
  143. float previousToCurrentRatio = inverseLerp(this->vertices[previousVertex].value, this->vertices[currentVertex].value, 0.0f);
  144. this->vertices[currentVertex] = SubVertex(this->vertices[previousVertex], this->vertices[currentVertex], previousToCurrentRatio);
  145. this->vertices[currentVertex].state = state_modified;
  146. } else if (this->vertices[nextVertex].state == state_use) {
  147. // End the cut
  148. float currentToNextRatio = inverseLerp(this->vertices[currentVertex].value, this->vertices[nextVertex].value, 0.0f);
  149. this->vertices[currentVertex] = SubVertex(this->vertices[currentVertex], this->vertices[nextVertex], currentToNextRatio);
  150. this->vertices[currentVertex].state = state_modified;
  151. }
  152. }
  153. }
  154. // Delete every vertex that is marked for removal
  155. // Looping backwards will avoid using altered indices while deleting
  156. if (outsideCount > 2) {
  157. for (int v = this->vertexCount - 1; v >= 0; v--) {
  158. assert(v >= 0 && v < maxPoints);
  159. if (this->vertices[v].state == state_delete) {
  160. this->deleteVertex(v);
  161. }
  162. }
  163. }
  164. }
  165. }
  166. }
  167. }
  168. };
  169. Visibility dsr::getTriangleVisibility(const ITriangle2D &triangle, const Camera &camera, bool clipFrustum) {
  170. static const int cornerCount = 3;
  171. int planeCount = camera.getFrustumPlaneCount(clipFrustum);
  172. bool outside[cornerCount * planeCount];
  173. // Check which corners are outside of the different planes
  174. int offset = 0;
  175. for (int c = 0; c < cornerCount; c++) {
  176. FVector3D triangleCorner = triangle.position[c].cs;
  177. for (int s = 0; s < planeCount; s++) {
  178. outside[offset + s] = !(camera.getFrustumPlane(s, clipFrustum).inside(triangleCorner));
  179. }
  180. offset += planeCount;
  181. }
  182. // Do not render if all corners are outside of the same side
  183. for (int s = 0; s < planeCount; s++) {
  184. if (outside[s] && outside[s + planeCount] && outside[s + 2 * planeCount]) {
  185. return Visibility::Hidden; // All corners outside of the same plane
  186. }
  187. }
  188. // Partial visibility if any corner is outside of a side
  189. for (int i = 0; i < planeCount * cornerCount; i++) {
  190. if (outside[i]) {
  191. return Visibility::Partial; // Any corner outside of a plane
  192. }
  193. }
  194. return Visibility::Full;
  195. }
  196. static bool almostZero(float value) {
  197. return value > -0.001f && value < 0.001f;
  198. }
  199. static bool almostZero(const FVector3D &channel) {
  200. return almostZero(channel.x) && almostZero(channel.y) && almostZero(channel.z);
  201. }
  202. static bool almostOne(float value) {
  203. return value > 0.999f && value < 1.001f;
  204. }
  205. static bool almostOne(const FVector3D &channel) {
  206. return almostOne(channel.x) && almostOne(channel.y) && almostOne(channel.z);
  207. }
  208. static bool almostSame(const FVector3D &channel) {
  209. return almostZero(channel.x - channel.y) && almostZero(channel.x - channel.z) && almostZero(channel.y - channel.z);
  210. }
  211. static const int alignX = 2;
  212. static const int alignY = 2;
  213. void dsr::executeTriangleDrawing(const TriangleDrawCommand &command, const IRect &clipBound) {
  214. IRect finalClipBound = IRect::cut(command.clipBound, clipBound);
  215. int32_t rowCount = command.triangle.getBufferSize(finalClipBound, alignX, alignY);
  216. if (rowCount > 0) {
  217. int startRow;
  218. RowInterval rows[rowCount];
  219. command.triangle.getShape(startRow, rows, finalClipBound, alignX, alignY);
  220. Projection projection = command.triangle.getProjection(command.subB, command.subC, command.perspective);
  221. command.processTriangle(command.triangleInput, command.targetImage, command.depthBuffer, command.triangle, projection, RowShape(startRow, rowCount, rows), command.filter);
  222. #ifdef SHOW_POST_CLIPPING_WIREFRAME
  223. drawWireframe(command.targetImage, command.triangle);
  224. #endif
  225. }
  226. }
  227. // Draw a linearly interpolated sub-triangle for clipping
  228. static void drawSubTriangle(CommandQueue *commandQueue, const TriangleDrawData &triangleDrawData, const Camera &camera, const IRect &clipBound, const SubVertex &vertexA, const SubVertex &vertexB, const SubVertex &vertexC) {
  229. //Get the weight of the first corner from the other weights
  230. FVector3D subB(vertexA.subB, vertexB.subB, vertexC.subB);
  231. FVector3D subC(vertexA.subC, vertexB.subC, vertexC.subC);
  232. //FVector3D subA = FVector3D(1.0f, 1.0f, 1.0f) - (subB + subC);
  233. ProjectedPoint posA = camera.cameraToScreen(vertexA.cs);
  234. ProjectedPoint posB = camera.cameraToScreen(vertexB.cs);
  235. ProjectedPoint posC = camera.cameraToScreen(vertexC.cs);
  236. // Create the sub-triangle
  237. ITriangle2D triangle(posA, posB, posC);
  238. // Rounding sub-triangles to integer locations may reverse the direction of zero area triangles
  239. if (triangle.isFrontfacing()) {
  240. TriangleDrawCommand command(triangleDrawData, triangle, subB, subC, clipBound);
  241. if (commandQueue) {
  242. commandQueue->add(command);
  243. } else {
  244. executeTriangleDrawing(command, clipBound);
  245. }
  246. }
  247. }
  248. // Clip triangles against the clip bounds outside of the image
  249. // Precondition: The triangle needs to be clipped
  250. // TODO: Take drawSubTriangle as a lambda to drawClippedTriangle using vertex weights as arguments and vertex data as captured variables
  251. static void drawClippedTriangle(CommandQueue *commandQueue, const TriangleDrawData &triangleDrawData, const Camera &camera, const ITriangle2D &triangle, const IRect &clipBound) {
  252. ClippedTriangle clipped(triangle);
  253. int planeCount = camera.getFrustumPlaneCount(true);
  254. for (int s = 0; s < planeCount; s++) {
  255. clipped.clip(camera.getFrustumPlane(s, true));
  256. }
  257. // Draw a convex triangle fan from the clipped triangle
  258. for (int triangleIndex = 0; triangleIndex < clipped.getVertexCount() - 2; triangleIndex++) {
  259. int indexA = 0;
  260. int indexB = 1 + triangleIndex;
  261. int indexC = 2 + triangleIndex;
  262. drawSubTriangle(commandQueue, triangleDrawData, camera, clipBound, clipped.vertices[indexA], clipped.vertices[indexB], clipped.vertices[indexC]);
  263. }
  264. }
  265. // Clipping is applied automatically if needed
  266. void dsr::renderTriangleWithShader(CommandQueue *commandQueue, const TriangleDrawData &triangleDrawData, const Camera &camera, const ITriangle2D &triangle, const IRect &clipBound) {
  267. // Allow small triangles to be a bit outside of the view frustum without being clipped by increasing the width and height slopes in a second test
  268. // This reduces redundant clipping to improve both speed and quality
  269. Visibility paddedVisibility = getTriangleVisibility(triangle, camera, true);
  270. // Draw the triangle
  271. if (paddedVisibility == Visibility::Full) {
  272. // Only check if the triangle is front facing once we know that the projection is in positive depth
  273. if (triangle.isFrontfacing()) {
  274. // Draw the full triangle
  275. TriangleDrawCommand command(triangleDrawData, triangle, FVector3D(0.0f, 1.0f, 0.0f), FVector3D(0.0f, 0.0f, 1.0f), clipBound);
  276. if (commandQueue) {
  277. commandQueue->add(command);
  278. } else {
  279. executeTriangleDrawing(command, clipBound);
  280. }
  281. }
  282. } else {
  283. // Draw a clipped triangle
  284. drawClippedTriangle(commandQueue, triangleDrawData, camera, triangle, clipBound);
  285. }
  286. }
  287. // TODO: Move shader selection to Shader_RgbaMultiply and let models default to its shader factory function pointer as shader selection
  288. void dsr::renderTriangleFromData(
  289. CommandQueue *commandQueue, ImageRgbaU8Impl *targetImage, ImageF32Impl *depthBuffer,
  290. const Camera &camera, const ProjectedPoint &posA, const ProjectedPoint &posB, const ProjectedPoint &posC,
  291. Filter filter, const ImageRgbaU8Impl *diffuse, const ImageRgbaU8Impl *light,
  292. TriangleTexCoords texCoords, TriangleColors colors) {
  293. // Get dimensions from both buffers
  294. int colorWidth = imageInternal::getWidth(targetImage);
  295. int colorHeight = imageInternal::getHeight(targetImage);
  296. int depthWidth = imageInternal::getWidth(depthBuffer);
  297. int depthHeight = imageInternal::getHeight(depthBuffer);
  298. // Combine dimensions
  299. int targetWidth, targetHeight;
  300. if (targetImage != nullptr) {
  301. targetWidth = colorWidth;
  302. targetHeight = colorHeight;
  303. if (depthBuffer != nullptr) {
  304. assert(targetWidth == depthWidth);
  305. assert(targetHeight == depthHeight);
  306. }
  307. } else {
  308. if (depthBuffer != nullptr) {
  309. targetWidth = depthWidth;
  310. targetHeight = depthHeight;
  311. } else {
  312. return; // No target buffer to draw on
  313. }
  314. }
  315. // Select a bound
  316. IRect clipBound = IRect::FromSize(targetWidth, targetHeight);
  317. // Create a triangle
  318. ITriangle2D triangle(posA, posB, posC);
  319. // Only draw visible triangles
  320. Visibility visibility = getTriangleVisibility(triangle, camera, false);
  321. if (visibility != Visibility::Hidden) {
  322. // Disable features when debugging
  323. #ifdef DISABLE_VERTEX_COLOR
  324. colors = TriangleColors(1.0f);
  325. #endif
  326. #ifdef DISABLE_DIFFUSE_MAP
  327. diffuse = nullptr;
  328. #endif
  329. #ifdef DISABLE_LIGHT_MAP
  330. light = nullptr;
  331. #endif
  332. // Select an instance of the default shader
  333. if (!(filter == Filter::Alpha && almostZero(colors.alpha))) {
  334. bool hasVertexFade = !(almostSame(colors.red) && almostSame(colors.green) && almostSame(colors.blue) && almostSame(colors.alpha));
  335. bool colorless = almostOne(colors.red) && almostOne(colors.green) && almostOne(colors.blue) && almostOne(colors.alpha);
  336. // Get the function pointer to the correct shader
  337. DRAW_CALLBACK_TYPE drawTask = &drawCallbackTemplate;
  338. if (diffuse) {
  339. bool hasDiffusePyramid = diffuse->texture.hasMipBuffer();
  340. if (light) {
  341. if (hasVertexFade) { // DiffuseLightVertex
  342. if (hasDiffusePyramid) { // With mipmap
  343. drawTask = &(Shader_RgbaMultiply<true, true, true, false, false>::processTriangle);
  344. } else { // Without mipmap
  345. drawTask = &(Shader_RgbaMultiply<true, true, true, false, true>::processTriangle);
  346. }
  347. } else { // DiffuseLight
  348. if (hasDiffusePyramid) { // With mipmap
  349. drawTask = &(Shader_RgbaMultiply<true, true, false, false, false>::processTriangle);
  350. } else { // Without mipmap
  351. drawTask = &(Shader_RgbaMultiply<true, true, false, false, true>::processTriangle);
  352. }
  353. }
  354. } else {
  355. if (hasVertexFade) { // DiffuseVertex
  356. if (hasDiffusePyramid) { // With mipmap
  357. drawTask = &(Shader_RgbaMultiply<true, false, true, false, false>::processTriangle);
  358. } else { // Without mipmap
  359. drawTask = &(Shader_RgbaMultiply<true, false, true, false, true>::processTriangle);
  360. }
  361. } else {
  362. if (colorless) { // Diffuse without normalization
  363. if (hasDiffusePyramid) { // With mipmap
  364. drawTask = &(Shader_RgbaMultiply<true, false, false, true, false>::processTriangle);
  365. } else { // Without mipmap
  366. drawTask = &(Shader_RgbaMultiply<true, false, false, true, true>::processTriangle);
  367. }
  368. } else { // Diffuse
  369. if (hasDiffusePyramid) { // With mipmap
  370. drawTask = &(Shader_RgbaMultiply<true, false, false, false, false>::processTriangle);
  371. } else { // Without mipmap
  372. drawTask = &(Shader_RgbaMultiply<true, false, false, false, true>::processTriangle);
  373. }
  374. }
  375. }
  376. }
  377. } else {
  378. if (light) {
  379. if (hasVertexFade) { // LightVertex
  380. drawTask = &(Shader_RgbaMultiply<false, true, true, false, false>::processTriangle);
  381. } else {
  382. if (colorless) { // Light without normalization
  383. drawTask = &(Shader_RgbaMultiply<false, true, false, true, false>::processTriangle);
  384. } else { // Light
  385. drawTask = &(Shader_RgbaMultiply<false, true, false, false, false>::processTriangle);
  386. }
  387. }
  388. } else {
  389. if (hasVertexFade) { // Vertex
  390. drawTask = &(Shader_RgbaMultiply<false, false, true, false, false>::processTriangle);
  391. } else { // Single color
  392. drawTask = &(Shader_RgbaMultiply<false, false, false, false, false>::processTriangle);
  393. }
  394. }
  395. }
  396. renderTriangleWithShader(commandQueue, TriangleDrawData(targetImage, depthBuffer, camera.perspective, filter, TriangleInput(diffuse, light, texCoords, colors), drawTask), camera, triangle, clipBound);
  397. }
  398. }
  399. }
  400. template<bool AFFINE>
  401. static void executeTriangleDrawingDepth(ImageF32Impl *depthBuffer, const ITriangle2D& triangle, const IRect &clipBound) {
  402. int32_t rowCount = triangle.getBufferSize(clipBound, 1, 1);
  403. if (rowCount > 0) {
  404. int startRow;
  405. RowInterval rows[rowCount];
  406. triangle.getShape(startRow, rows, clipBound, 1, 1);
  407. Projection projection = triangle.getProjection(FVector3D(), FVector3D(), !AFFINE); // TODO: Create a weight using only depth to save time
  408. RowShape shape = RowShape(startRow, rowCount, rows);
  409. // Draw the triangle
  410. const int depthBufferStride = imageInternal::getStride(depthBuffer);
  411. SafePointer<float> depthDataRow = imageInternal::getSafeData<float>(depthBuffer, shape.startRow);
  412. for (int32_t y = shape.startRow; y < shape.startRow + shape.rowCount; y++) {
  413. RowInterval row = shape.rows[y - shape.startRow];
  414. SafePointer<float> depthData = depthDataRow + row.left;
  415. // Initialize depth iteration
  416. float depthValue;
  417. if (AFFINE) {
  418. depthValue = projection.getWeight_affine(IVector2D(row.left, y)).x;
  419. } else {
  420. depthValue = projection.getDepthDividedWeight_perspective(IVector2D(row.left, y)).x;
  421. }
  422. float depthDx = projection.pWeightDx.x;
  423. // Loop over a row of depth pixels
  424. for (int32_t x = row.left; x < row.right; x++) {
  425. float oldValue = *depthData;
  426. if (AFFINE) {
  427. // Write lower depthValue for orthogonal cameras
  428. if (depthValue < oldValue) {
  429. *depthData = depthValue;
  430. }
  431. } else {
  432. // Write higher depthValue for perspective cameras
  433. if (depthValue > oldValue) {
  434. *depthData = depthValue;
  435. }
  436. }
  437. depthValue += depthDx;
  438. depthData += 1;
  439. }
  440. // Iterate to the next row
  441. depthDataRow.increaseBytes(depthBufferStride);
  442. }
  443. }
  444. }
  445. static void drawTriangleDepth(ImageF32Impl *depthBuffer, const Camera &camera, const IRect &clipBound, const ITriangle2D& triangle) {
  446. // Rounding sub-triangles to integer locations may reverse the direction of zero area triangles
  447. if (triangle.isFrontfacing()) {
  448. if (camera.perspective) {
  449. executeTriangleDrawingDepth<false>(depthBuffer, triangle, clipBound);
  450. } else {
  451. executeTriangleDrawingDepth<true>(depthBuffer, triangle, clipBound);
  452. }
  453. }
  454. }
  455. static void drawSubTriangleDepth(ImageF32Impl *depthBuffer, const Camera &camera, const IRect &clipBound, const SubVertex &vertexA, const SubVertex &vertexB, const SubVertex &vertexC) {
  456. ProjectedPoint posA = camera.cameraToScreen(vertexA.cs);
  457. ProjectedPoint posB = camera.cameraToScreen(vertexB.cs);
  458. ProjectedPoint posC = camera.cameraToScreen(vertexC.cs);
  459. drawTriangleDepth(depthBuffer, camera, clipBound, ITriangle2D(posA, posB, posC));
  460. }
  461. void dsr::renderTriangleFromDataDepth(ImageF32Impl *depthBuffer, const Camera &camera, const ProjectedPoint &posA, const ProjectedPoint &posB, const ProjectedPoint &posC) {
  462. // Skip rendering if there's no target buffer
  463. if (depthBuffer == nullptr) { return; }
  464. // Select a bound
  465. IRect clipBound = IRect::FromSize(imageInternal::getWidth(depthBuffer), imageInternal::getHeight(depthBuffer));
  466. // Create a triangle
  467. ITriangle2D triangle(posA, posB, posC);
  468. // Only draw visible triangles
  469. Visibility visibility = getTriangleVisibility(triangle, camera, false);
  470. if (visibility != Visibility::Hidden) {
  471. // Allow small triangles to be a bit outside of the view frustum without being clipped by increasing the width and height slopes in a second test
  472. // This reduces redundant clipping to improve both speed and quality
  473. Visibility paddedVisibility = getTriangleVisibility(triangle, camera, true);
  474. // Draw the triangle
  475. if (paddedVisibility == Visibility::Full) {
  476. // Only check if the triangle is front facing once we know that the projection is in positive depth
  477. if (triangle.isFrontfacing()) {
  478. // Draw the full triangle
  479. drawTriangleDepth(depthBuffer, camera, clipBound, triangle);
  480. }
  481. } else {
  482. // Draw a clipped triangle
  483. ClippedTriangle clipped(triangle); // TODO: Simpler vertex clipping using only positions
  484. int planeCount = camera.getFrustumPlaneCount(true);
  485. for (int s = 0; s < planeCount; s++) {
  486. clipped.clip(camera.getFrustumPlane(s, true));
  487. }
  488. // Draw a convex triangle fan from the clipped triangle
  489. for (int triangleIndex = 0; triangleIndex < clipped.getVertexCount() - 2; triangleIndex++) {
  490. int indexA = 0;
  491. int indexB = 1 + triangleIndex;
  492. int indexC = 2 + triangleIndex;
  493. drawSubTriangleDepth(depthBuffer, camera, clipBound, clipped.vertices[indexA], clipped.vertices[indexB], clipped.vertices[indexC]);
  494. }
  495. }
  496. }
  497. }
  498. void CommandQueue::add(const TriangleDrawCommand &command) {
  499. this->buffer.push(command);
  500. }
  501. void CommandQueue::execute(const IRect &clipBound, int jobCount) const {
  502. if (jobCount <= 1) {
  503. // TODO: Make a setting for sorting triangles using indices within each job
  504. for (int i = 0; i < this->buffer.length(); i++) {
  505. if (!this->buffer[i].occluded) {
  506. executeTriangleDrawing(this->buffer[i], clipBound);
  507. }
  508. }
  509. } else {
  510. std::function<void()> jobs[jobCount];
  511. int y1 = clipBound.top();
  512. for (int j = 0; j < jobCount; j++) {
  513. int y2 = clipBound.top() + ((clipBound.bottom() * (j + 1)) / jobCount);
  514. // Align to multiples of two lines if it's not at the bottom
  515. if (j < jobCount - 1) {
  516. y2 = (y2 / 2) * 2;
  517. }
  518. int height = y2 - y1;
  519. IRect subBound = IRect(clipBound.left(), y1, clipBound.width(), height);
  520. jobs[j] = [this, subBound]() {
  521. //this->execute(subBound, 1);
  522. for (int i = 0; i < this->buffer.length(); i++) {
  523. if (!this->buffer[i].occluded) {
  524. executeTriangleDrawing(this->buffer[i], subBound);
  525. }
  526. }
  527. };
  528. y1 = y2;
  529. }
  530. threadedWorkFromArray(jobs, jobCount);
  531. }
  532. }
  533. void CommandQueue::clear() {
  534. this->buffer.clear();
  535. }