Camera.h 12 KB

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