2
0

Camera.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. // zlib open source license
  2. //
  3. // Copyright (c) 2017 to 2022 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. #ifndef DFPSR_RENDER_CAMERA
  24. #define DFPSR_RENDER_CAMERA
  25. #include <cstdint>
  26. #include <cassert>
  27. #include "../../math/FVector.h"
  28. #include "../../math/LVector.h"
  29. #include "../../math/FPlane3D.h"
  30. #include "../../math/Transform3D.h"
  31. #include "../math/scalar.h"
  32. #include "constants.h"
  33. #include "ProjectedPoint.h"
  34. #include <limits>
  35. namespace dsr {
  36. // A special rounding used for vertex projection
  37. static inline int64_t safeRoundInt64(float value) {
  38. int64_t result = (int64_t)value;
  39. if (value <= -1048576.0f || value >= 1048576.0f) { result = 0; }
  40. return result;
  41. }
  42. class ViewFrustum {
  43. private:
  44. FPlane3D planes[6];
  45. int planeCount;
  46. public:
  47. ViewFrustum() : planeCount(0) {}
  48. // Orthogonal view frustum in camera space
  49. ViewFrustum(float halfWidth, float halfHeight)
  50. : planeCount(4) {
  51. // Sides
  52. planes[0] = FPlane3D(FVector3D(1.0f, 0.0f, 0.0f), halfWidth);
  53. planes[1] = FPlane3D(FVector3D(-1.0f, 0.0f, 0.0f), halfWidth);
  54. planes[2] = FPlane3D(FVector3D(0.0f, 1.0f, 0.0f), halfHeight);
  55. planes[3] = FPlane3D(FVector3D(0.0f, -1.0f, 0.0f), halfHeight);
  56. }
  57. // Perspective view frustum in camera space
  58. ViewFrustum(float nearClip, float farClip, float widthSlope, float heightSlope)
  59. : planeCount(farClip == std::numeric_limits<float>::infinity() ? 5 : 6) { // Skip the far clip plane if its distance is infinite.
  60. // Sides
  61. planes[0] = FPlane3D(FVector3D(1.0f, 0.0f, -widthSlope), 0.0f);
  62. planes[1] = FPlane3D(FVector3D(-1.0f, 0.0f, -widthSlope), 0.0f);
  63. planes[2] = FPlane3D(FVector3D(0.0f, 1.0f, -heightSlope), 0.0f);
  64. planes[3] = FPlane3D(FVector3D(0.0f, -1.0f, -heightSlope), 0.0f);
  65. // Near and far clip planes
  66. planes[4] = FPlane3D(FVector3D(0.0f, 0.0f, -1.0f), -nearClip);
  67. planes[5] = FPlane3D(FVector3D(0.0f, 0.0f, 1.0f), farClip);
  68. }
  69. inline int getPlaneCount() const {
  70. return this->planeCount;
  71. }
  72. inline FPlane3D getPlane(int sideIndex) const {
  73. assert(sideIndex >= 0 && sideIndex < this->planeCount);
  74. return planes[sideIndex];
  75. }
  76. // Quick estimation of potential visibility without caring about edges nor details.
  77. // The convex hull points to test are relative to the camera's location.
  78. // Returns 0 if all points are outside of the same plane, so that an object within the convex hull can not be visible.
  79. // Returns 1 if one or more points are outside of the view frustum but they are not all outside of the same plane, so it may or may not be visible.
  80. // Returns 2 if all points are inside of the view frustum, so that it is certainly visible, unless hidden by something else.
  81. int isConvexHullSeen(SafePointer<const FVector3D> cameraSpacePoints, int32_t pointCount) const {
  82. bool anyOutside = false;
  83. for (int s = 0; s < this->getPlaneCount(); s++) {
  84. FPlane3D plane = this->getPlane(s);
  85. // Check if any point is inside of the current plane.
  86. bool anyInside = false;
  87. for (int p = 0; p < pointCount; p++) {
  88. if (plane.inside(cameraSpacePoints[p])) {
  89. anyInside = true;
  90. } else {
  91. anyOutside = true;
  92. }
  93. }
  94. // If none was inside of the plane, then the point clound is not visible.
  95. if (!anyInside) {
  96. // All points were outside of the current side, so the hull is not visible.
  97. return 0;
  98. }
  99. }
  100. // Every side had at least one point inside, so the hull is visible.
  101. return anyOutside ? 1 : 2;
  102. }
  103. };
  104. // How much is the image region magnified for skipping entire triangles.
  105. // A small margin is needed to prevent missing pixels from rounding errors along the borders in high image resolutions.
  106. static const float cullRatio = 1.0001f;
  107. // How much is the image region magnified for clipping triangles.
  108. // The larger you make the clip region, the less triangles you have to apply clipping to.
  109. // The triangle rasterization can handle clipping triangles in integer coordinates,
  110. // but there are limits to how large those integers can become before overflowing.
  111. static const float clipRatio = 2.0f;
  112. // To prevent division by zero, a near clipping distance is slightly above zero to
  113. // clip triangles in 3D camera space before projecting the coordinates to the target image.
  114. static const float defaultNearClip = 0.01f;
  115. static const float defaultFarClip = 1000.0f;
  116. // Just create a new camera on stack memory every time you need to render something.
  117. class Camera {
  118. public: // Do not modify individual settings without assigning whole new cameras.
  119. bool perspective; // When off, widthSlope and heightSlope will be used as halfWidth and halfHeight.
  120. Transform3D location; // Only translation and rotation allowed. Scaling and tilting will obviously not work for cameras.
  121. float widthSlope, heightSlope, invWidthSlope, invHeightSlope, imageWidth, imageHeight, nearClip, farClip;
  122. // The tight view frustum, used for skipping rendering as soon as something is fully out of sight.
  123. ViewFrustum cullFrustum;
  124. // The extra large frustum outside of the visible border, used to clip rendering of partial visibility to prevent integer overflow in perspective projection.
  125. // The clip frustum is much larger than the cull frustum because clipping is expensive and can not be done using exact integers.
  126. ViewFrustum clipFrustum;
  127. Camera() :
  128. perspective(true), location(Transform3D()), widthSlope(0.0f), heightSlope(0.0f),
  129. invWidthSlope(0.0f), invHeightSlope(0.0f), imageWidth(0), imageHeight(0),
  130. nearClip(0.0f), farClip(0.0f), cullFrustum(ViewFrustum()), clipFrustum(ViewFrustum()) {}
  131. Camera(bool perspective, const Transform3D &location, float imageWidth, float imageHeight, float widthSlope, float heightSlope, float nearClip, float farClip, const ViewFrustum &cullFrustum, const ViewFrustum &clipFrustum) :
  132. perspective(perspective), location(location), widthSlope(widthSlope), heightSlope(heightSlope),
  133. invWidthSlope(0.5f / widthSlope), invHeightSlope(0.5f / heightSlope), imageWidth(imageWidth), imageHeight(imageHeight),
  134. nearClip(nearClip), farClip(farClip), cullFrustum(cullFrustum), clipFrustum(clipFrustum) {}
  135. public:
  136. static Camera createPerspective(const Transform3D &location, float imageWidth, float imageHeight, float widthSlope = 1.0f, float nearClip = defaultNearClip, float farClip = defaultFarClip) {
  137. float heightSlope = widthSlope * imageHeight / imageWidth;
  138. return Camera(true, location, imageWidth, imageHeight, widthSlope, heightSlope, nearClip, farClip,
  139. ViewFrustum(nearClip, farClip, widthSlope * cullRatio, heightSlope * cullRatio),
  140. ViewFrustum(nearClip, farClip, widthSlope * clipRatio, heightSlope * clipRatio));
  141. }
  142. // Orthogonal cameras doesn't have any near or far clip planes
  143. static Camera createOrthogonal(const Transform3D &location, float imageWidth, float imageHeight, float halfWidth) {
  144. float halfHeight = halfWidth * imageHeight / imageWidth;
  145. return Camera(false, location, imageWidth, imageHeight, halfWidth, halfHeight, -std::numeric_limits<float>::max(), std::numeric_limits<float>::max(),
  146. ViewFrustum(halfWidth * cullRatio, halfHeight * cullRatio),
  147. ViewFrustum(halfWidth * clipRatio, halfHeight * clipRatio));
  148. }
  149. inline FVector3D worldToCamera(const FVector3D &worldSpace) const {
  150. return this->location.transformPointTransposedInverse(worldSpace);
  151. }
  152. ProjectedPoint cameraToScreen(const FVector3D &cameraSpace) const {
  153. // Camera to image space
  154. if (this->perspective) {
  155. float invDepth;
  156. if (cameraSpace.z > 0.0f) {
  157. invDepth = 1.0f / cameraSpace.z;
  158. } else {
  159. invDepth = 0.0f;
  160. }
  161. float centerShear = cameraSpace.z * 0.5f;
  162. FVector2D preProjection = FVector2D(
  163. ( cameraSpace.x * this->invWidthSlope + centerShear) * this->imageWidth,
  164. (-cameraSpace.y * this->invHeightSlope + centerShear) * this->imageHeight
  165. );
  166. FVector2D projectedFloat = preProjection * invDepth;
  167. FVector2D subPixel = projectedFloat * constants::unitsPerPixel;
  168. LVector2D rounded = LVector2D(safeRoundInt64(subPixel.x), safeRoundInt64(subPixel.y));
  169. return ProjectedPoint(cameraSpace, projectedFloat, rounded);
  170. } else {
  171. FVector2D projectedFloat = FVector2D(
  172. ( cameraSpace.x * this->invWidthSlope + 0.5f) * this->imageWidth,
  173. (-cameraSpace.y * this->invHeightSlope + 0.5f) * this->imageHeight
  174. );
  175. FVector2D subPixel = projectedFloat * constants::unitsPerPixel;
  176. LVector2D rounded = LVector2D(safeRoundInt64(subPixel.x), safeRoundInt64(subPixel.y));
  177. return ProjectedPoint(cameraSpace, projectedFloat, rounded);
  178. }
  179. }
  180. inline ProjectedPoint worldToScreen(const FVector3D &worldSpace) const {
  181. return this->cameraToScreen(this->worldToCamera(worldSpace));
  182. }
  183. inline int getFrustumPlaneCount(bool clipping) const {
  184. return clipping ? this->clipFrustum.getPlaneCount() : this->cullFrustum.getPlaneCount();
  185. }
  186. inline FPlane3D getFrustumPlane(int sideIndex, bool clipping) const {
  187. return clipping ? this->clipFrustum.getPlane(sideIndex) : this->cullFrustum.getPlane(sideIndex);
  188. }
  189. // Returns 0 iff the model inside of the bound can clearly not be visible, 1 if it intersects with the view frustum, or 2 if fully in view.
  190. // by having all corners outside of the same side in the camera's culling frustum.
  191. int isBoxSeen(const FVector3D& minModelSpaceBound, const FVector3D& maxModelSpaceBound, const Transform3D &modelToWorld) const {
  192. // Allocate memory for the corners.
  193. FVector3D cornerBuffer[8];
  194. SafePointer<FVector3D> corners = SafePointer<FVector3D>("corners in Camera::isBoxSeen", cornerBuffer, sizeof(cornerBuffer));
  195. // Convert from model space bounds to camera space point cloud.
  196. corners[0] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(minModelSpaceBound.x, minModelSpaceBound.y, minModelSpaceBound.z)));
  197. corners[1] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(maxModelSpaceBound.x, minModelSpaceBound.y, minModelSpaceBound.z)));
  198. corners[2] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(minModelSpaceBound.x, maxModelSpaceBound.y, minModelSpaceBound.z)));
  199. corners[3] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(maxModelSpaceBound.x, maxModelSpaceBound.y, minModelSpaceBound.z)));
  200. corners[4] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(minModelSpaceBound.x, minModelSpaceBound.y, maxModelSpaceBound.z)));
  201. corners[5] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(maxModelSpaceBound.x, minModelSpaceBound.y, maxModelSpaceBound.z)));
  202. corners[6] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(minModelSpaceBound.x, maxModelSpaceBound.y, maxModelSpaceBound.z)));
  203. corners[7] = this->worldToCamera(modelToWorld.transformPoint(FVector3D(maxModelSpaceBound.x, maxModelSpaceBound.y, maxModelSpaceBound.z)));
  204. // Apply a fast visibility test, which might return true even when the object is not visible.
  205. return this->cullFrustum.isConvexHullSeen(corners, 8);
  206. }
  207. };
  208. }
  209. #endif