camera.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { Mat4, Vec3, Vec4, EPSILON } from '../mol-math/linear-algebra';
  8. import { Viewport, cameraProject, cameraUnproject } from './camera/util';
  9. import { CameraTransitionManager } from './camera/transition';
  10. import { BehaviorSubject } from 'rxjs';
  11. export { Camera };
  12. class Camera {
  13. readonly view: Mat4 = Mat4.identity();
  14. readonly projection: Mat4 = Mat4.identity();
  15. readonly projectionView: Mat4 = Mat4.identity();
  16. readonly inverseProjectionView: Mat4 = Mat4.identity();
  17. readonly viewport: Viewport;
  18. readonly state: Readonly<Camera.Snapshot> = Camera.createDefaultSnapshot();
  19. readonly viewOffset: Camera.ViewOffset = {
  20. enabled: false,
  21. fullWidth: 1, fullHeight: 1,
  22. offsetX: 0, offsetY: 0,
  23. width: 1, height: 1
  24. }
  25. near = 1
  26. far = 10000
  27. fogNear = 5000
  28. fogFar = 10000
  29. zoom = 1
  30. readonly transition: CameraTransitionManager = new CameraTransitionManager(this);
  31. readonly stateChanged = new BehaviorSubject<Partial<Camera.Snapshot>>(this.state);
  32. get position() { return this.state.position; }
  33. set position(v: Vec3) { Vec3.copy(this.state.position, v); }
  34. get up() { return this.state.up; }
  35. set up(v: Vec3) { Vec3.copy(this.state.up, v); }
  36. get target() { return this.state.target; }
  37. set target(v: Vec3) { Vec3.copy(this.state.target, v); }
  38. private prevProjection = Mat4.identity();
  39. private prevView = Mat4.identity();
  40. private deltaDirection = Vec3();
  41. private newPosition = Vec3();
  42. update() {
  43. const snapshot = this.state as Camera.Snapshot;
  44. const height = 2 * Math.tan(snapshot.fov / 2) * Vec3.distance(snapshot.position, snapshot.target);
  45. this.zoom = this.viewport.height / height;
  46. updateClip(this);
  47. switch (this.state.mode) {
  48. case 'orthographic': updateOrtho(this); break;
  49. case 'perspective': updatePers(this); break;
  50. default: throw new Error('unknown camera mode');
  51. }
  52. const changed = !Mat4.areEqual(this.projection, this.prevProjection, EPSILON) || !Mat4.areEqual(this.view, this.prevView, EPSILON);
  53. if (changed) {
  54. Mat4.mul(this.projectionView, this.projection, this.view);
  55. Mat4.invert(this.inverseProjectionView, this.projectionView);
  56. Mat4.copy(this.prevView, this.view);
  57. Mat4.copy(this.prevProjection, this.projection);
  58. }
  59. return changed;
  60. }
  61. setState(snapshot: Partial<Camera.Snapshot>, durationMs?: number) {
  62. this.transition.apply(snapshot, durationMs);
  63. this.stateChanged.next(snapshot);
  64. }
  65. getSnapshot() {
  66. return Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
  67. }
  68. getTargetDistance(radius: number) {
  69. const r = Math.max(radius, 0.01);
  70. const { fov } = this.state;
  71. const { width, height } = this.viewport;
  72. const aspect = width / height;
  73. const aspectFactor = (height < width ? 1 : aspect);
  74. return Math.abs((r / aspectFactor) / Math.sin(fov / 2));
  75. }
  76. getFocus(target: Vec3, radius: number, up?: Vec3, dir?: Vec3): Partial<Camera.Snapshot> {
  77. const r = Math.max(radius, 0.01);
  78. const targetDistance = this.getTargetDistance(r);
  79. Vec3.sub(this.deltaDirection, this.target, this.position);
  80. if (dir) Vec3.matchDirection(this.deltaDirection, dir, this.deltaDirection);
  81. Vec3.setMagnitude(this.deltaDirection, this.deltaDirection, targetDistance);
  82. Vec3.sub(this.newPosition, target, this.deltaDirection);
  83. const state = Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
  84. state.target = Vec3.clone(target);
  85. state.radius = r;
  86. state.position = Vec3.clone(this.newPosition);
  87. if (up) Vec3.matchDirection(state.up, up, state.up);
  88. return state;
  89. }
  90. focus(target: Vec3, radius: number, durationMs?: number, up?: Vec3, dir?: Vec3) {
  91. if (radius > 0) {
  92. this.setState(this.getFocus(target, radius, up, dir), durationMs);
  93. }
  94. }
  95. project(out: Vec4, point: Vec3) {
  96. return cameraProject(out, point, this.viewport, this.projectionView);
  97. }
  98. unproject(out: Vec3, point: Vec3) {
  99. return cameraUnproject(out, point, this.viewport, this.inverseProjectionView);
  100. }
  101. constructor(state?: Partial<Camera.Snapshot>, viewport = Viewport.create(-1, -1, 1, 1)) {
  102. this.viewport = viewport;
  103. Camera.copySnapshot(this.state, state);
  104. }
  105. }
  106. namespace Camera {
  107. export type Mode = 'perspective' | 'orthographic'
  108. /**
  109. * Sets an offseted view in a larger frustum. This is useful for
  110. * - multi-window or multi-monitor/multi-machine setups
  111. * - jittering the camera position for
  112. */
  113. export interface ViewOffset {
  114. enabled: boolean,
  115. fullWidth: number,
  116. fullHeight: number,
  117. offsetX: number,
  118. offsetY: number,
  119. width: number,
  120. height: number
  121. }
  122. export function setViewOffset(out: ViewOffset, fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number) {
  123. out.fullWidth = fullWidth;
  124. out.fullHeight = fullHeight;
  125. out.offsetX = offsetX;
  126. out.offsetY = offsetY;
  127. out.width = width;
  128. out.height = height;
  129. }
  130. export function createDefaultSnapshot(): Snapshot {
  131. return {
  132. mode: 'perspective',
  133. fov: Math.PI / 4,
  134. position: Vec3.create(0, 0, 100),
  135. up: Vec3.create(0, 1, 0),
  136. target: Vec3.create(0, 0, 0),
  137. radius: 10,
  138. radiusMax: 10,
  139. fog: 50,
  140. clipFar: true
  141. };
  142. }
  143. export interface Snapshot {
  144. mode: Mode
  145. fov: number
  146. position: Vec3
  147. up: Vec3
  148. target: Vec3
  149. radius: number
  150. radiusMax: number
  151. fog: number
  152. clipFar: boolean
  153. }
  154. export function copySnapshot(out: Snapshot, source?: Partial<Snapshot>) {
  155. if (!source) return out;
  156. if (typeof source.mode !== 'undefined') out.mode = source.mode;
  157. if (typeof source.fov !== 'undefined') out.fov = source.fov;
  158. if (typeof source.position !== 'undefined') Vec3.copy(out.position, source.position);
  159. if (typeof source.up !== 'undefined') Vec3.copy(out.up, source.up);
  160. if (typeof source.target !== 'undefined') Vec3.copy(out.target, source.target);
  161. if (typeof source.radius !== 'undefined') out.radius = source.radius;
  162. if (typeof source.radiusMax !== 'undefined') out.radiusMax = source.radiusMax;
  163. if (typeof source.fog !== 'undefined') out.fog = source.fog;
  164. if (typeof source.clipFar !== 'undefined') out.clipFar = source.clipFar;
  165. return out;
  166. }
  167. }
  168. function updateOrtho(camera: Camera) {
  169. const { viewport, zoom, near, far, viewOffset } = camera;
  170. const fullLeft = -(viewport.width - viewport.x) / 2;
  171. const fullRight = (viewport.width - viewport.x) / 2;
  172. const fullTop = (viewport.height - viewport.y) / 2;
  173. const fullBottom = -(viewport.height - viewport.y) / 2;
  174. const dx = (fullRight - fullLeft) / (2 * zoom);
  175. const dy = (fullTop - fullBottom) / (2 * zoom);
  176. const cx = (fullRight + fullLeft) / 2;
  177. const cy = (fullTop + fullBottom) / 2;
  178. let left = cx - dx;
  179. let right = cx + dx;
  180. let top = cy + dy;
  181. let bottom = cy - dy;
  182. if (viewOffset.enabled) {
  183. const zoomW = zoom / (viewOffset.width / viewOffset.fullWidth);
  184. const zoomH = zoom / (viewOffset.height / viewOffset.fullHeight);
  185. const scaleW = (fullRight - fullLeft) / viewOffset.width;
  186. const scaleH = (fullTop - fullBottom) / viewOffset.height;
  187. left += scaleW * (viewOffset.offsetX / zoomW);
  188. right = left + scaleW * (viewOffset.width / zoomW);
  189. top -= scaleH * (viewOffset.offsetY / zoomH);
  190. bottom = top - scaleH * (viewOffset.height / zoomH);
  191. }
  192. // build projection matrix
  193. Mat4.ortho(camera.projection, left, right, top, bottom, near, far);
  194. // build view matrix
  195. Mat4.lookAt(camera.view, camera.position, camera.target, camera.up);
  196. }
  197. function updatePers(camera: Camera) {
  198. const aspect = camera.viewport.width / camera.viewport.height;
  199. const { near, far, viewOffset } = camera;
  200. let top = near * Math.tan(0.5 * camera.state.fov);
  201. let height = 2 * top;
  202. let width = aspect * height;
  203. let left = -0.5 * width;
  204. if (viewOffset.enabled) {
  205. left += viewOffset.offsetX * width / viewOffset.fullWidth;
  206. top -= viewOffset.offsetY * height / viewOffset.fullHeight;
  207. width *= viewOffset.width / viewOffset.fullWidth;
  208. height *= viewOffset.height / viewOffset.fullHeight;
  209. }
  210. // build projection matrix
  211. Mat4.perspective(camera.projection, left, left + width, top, top - height, near, far);
  212. // build view matrix
  213. Mat4.lookAt(camera.view, camera.position, camera.target, camera.up);
  214. }
  215. function updateClip(camera: Camera) {
  216. let { radius, radiusMax, mode, fog, clipFar } = camera.state;
  217. if (radius < 0.01) radius = 0.01;
  218. const normalizedFar = clipFar ? radius : radiusMax;
  219. const cameraDistance = Vec3.distance(camera.position, camera.target);
  220. let near = cameraDistance - radius;
  221. let far = cameraDistance + normalizedFar;
  222. const fogNearFactor = -(50 - fog) / 50;
  223. let fogNear = cameraDistance - (normalizedFar * fogNearFactor);
  224. let fogFar = far;
  225. if (mode === 'perspective') {
  226. // set at least to 5 to avoid slow sphere impostor rendering
  227. near = Math.max(5, near);
  228. far = Math.max(5, far);
  229. } else {
  230. near = Math.max(0, near);
  231. far = Math.max(0, far);
  232. }
  233. if (near === far) {
  234. // make sure near and far are not identical to avoid Infinity in the projection matrix
  235. far = near + 0.01;
  236. }
  237. camera.near = near;
  238. camera.far = far;
  239. camera.fogNear = fogNear;
  240. camera.fogFar = fogFar;
  241. }