camera.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /**
  2. * Copyright (c) 2018-2021 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. import { Scene } from '../mol-gl/scene';
  12. export { ICamera, Camera };
  13. interface ICamera {
  14. readonly viewport: Viewport,
  15. readonly view: Mat4,
  16. readonly projection: Mat4,
  17. readonly projectionView: Mat4,
  18. readonly inverseProjectionView: Mat4,
  19. readonly state: Readonly<Camera.Snapshot>,
  20. readonly viewOffset: Camera.ViewOffset,
  21. readonly far: number,
  22. readonly near: number,
  23. readonly fogFar: number,
  24. readonly fogNear: number,
  25. }
  26. const tmpPos1 = Vec3();
  27. const tmpPos2 = Vec3();
  28. const tmpClip = Vec4();
  29. class Camera implements ICamera {
  30. readonly view: Mat4 = Mat4.identity();
  31. readonly projection: Mat4 = Mat4.identity();
  32. readonly projectionView: Mat4 = Mat4.identity();
  33. readonly inverseProjectionView: Mat4 = Mat4.identity();
  34. private pixelScale: number
  35. get pixelRatio() {
  36. const dpr = (typeof window !== 'undefined') ? window.devicePixelRatio : 1;
  37. return dpr * this.pixelScale;
  38. }
  39. readonly viewport: Viewport;
  40. readonly state: Readonly<Camera.Snapshot> = Camera.createDefaultSnapshot();
  41. readonly viewOffset = Camera.ViewOffset();
  42. near = 1
  43. far = 10000
  44. fogNear = 5000
  45. fogFar = 10000
  46. zoom = 1
  47. readonly transition: CameraTransitionManager = new CameraTransitionManager(this);
  48. readonly stateChanged = new BehaviorSubject<Partial<Camera.Snapshot>>(this.state);
  49. get position() { return this.state.position; }
  50. set position(v: Vec3) { Vec3.copy(this.state.position, v); }
  51. get up() { return this.state.up; }
  52. set up(v: Vec3) { Vec3.copy(this.state.up, v); }
  53. get target() { return this.state.target; }
  54. set target(v: Vec3) { Vec3.copy(this.state.target, v); }
  55. private prevProjection = Mat4.identity();
  56. private prevView = Mat4.identity();
  57. private deltaDirection = Vec3();
  58. private newPosition = Vec3();
  59. update() {
  60. const snapshot = this.state as Camera.Snapshot;
  61. if (snapshot.radiusMax === 0) {
  62. return false;
  63. }
  64. const height = 2 * Math.tan(snapshot.fov / 2) * Vec3.distance(snapshot.position, snapshot.target);
  65. this.zoom = this.viewport.height / height;
  66. updateClip(this);
  67. switch (this.state.mode) {
  68. case 'orthographic': updateOrtho(this); break;
  69. case 'perspective': updatePers(this); break;
  70. default: throw new Error('unknown camera mode');
  71. }
  72. const changed = !Mat4.areEqual(this.projection, this.prevProjection, EPSILON) || !Mat4.areEqual(this.view, this.prevView, EPSILON);
  73. if (changed) {
  74. Mat4.mul(this.projectionView, this.projection, this.view);
  75. if (!Mat4.tryInvert(this.inverseProjectionView, this.projectionView)) {
  76. Mat4.copy(this.view, this.prevView);
  77. Mat4.copy(this.projection, this.prevProjection);
  78. Mat4.mul(this.projectionView, this.projection, this.view);
  79. return false;
  80. }
  81. Mat4.copy(this.prevView, this.view);
  82. Mat4.copy(this.prevProjection, this.projection);
  83. }
  84. return changed;
  85. }
  86. setState(snapshot: Partial<Camera.Snapshot>, durationMs?: number) {
  87. this.transition.apply(snapshot, durationMs);
  88. this.stateChanged.next(snapshot);
  89. }
  90. getSnapshot() {
  91. return Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
  92. }
  93. getTargetDistance(radius: number) {
  94. return Camera.targetDistance(radius, this.state.fov, this.viewport.width, this.viewport.height);
  95. }
  96. getFocus(target: Vec3, radius: number, up?: Vec3, dir?: Vec3): Partial<Camera.Snapshot> {
  97. const r = Math.max(radius, 0.01);
  98. const targetDistance = this.getTargetDistance(r);
  99. Vec3.sub(this.deltaDirection, this.target, this.position);
  100. if (dir) Vec3.matchDirection(this.deltaDirection, dir, this.deltaDirection);
  101. Vec3.setMagnitude(this.deltaDirection, this.deltaDirection, targetDistance);
  102. Vec3.sub(this.newPosition, target, this.deltaDirection);
  103. const state = Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
  104. state.target = Vec3.clone(target);
  105. state.radius = r;
  106. state.position = Vec3.clone(this.newPosition);
  107. if (up) Vec3.matchDirection(state.up, up, state.up);
  108. return state;
  109. }
  110. getInvariantFocus(target: Vec3, radius: number, up: Vec3, dir: Vec3): Partial<Camera.Snapshot> {
  111. const r = Math.max(radius, 0.01);
  112. const targetDistance = this.getTargetDistance(r);
  113. Vec3.copy(this.deltaDirection, dir);
  114. Vec3.setMagnitude(this.deltaDirection, this.deltaDirection, targetDistance);
  115. Vec3.sub(this.newPosition, target, this.deltaDirection);
  116. const state = Camera.copySnapshot(Camera.createDefaultSnapshot(), this.state);
  117. state.target = Vec3.clone(target);
  118. state.radius = r;
  119. state.position = Vec3.clone(this.newPosition);
  120. Vec3.copy(state.up, up);
  121. return state;
  122. }
  123. focus(target: Vec3, radius: number, durationMs?: number, up?: Vec3, dir?: Vec3) {
  124. if (radius > 0) {
  125. this.setState(this.getFocus(target, radius, up, dir), durationMs);
  126. }
  127. }
  128. /** Transform point into 2D window coordinates. */
  129. project(out: Vec4, point: Vec3) {
  130. return cameraProject(out, point, this.viewport, this.projectionView);
  131. }
  132. /**
  133. * Transform point from screen space to 3D coordinates.
  134. * The point must have `x` and `y` set to 2D window coordinates
  135. * and `z` between 0 (near) and 1 (far); the optional `w` is not used.
  136. */
  137. unproject(out: Vec3, point: Vec3 | Vec4) {
  138. return cameraUnproject(out, point, this.viewport, this.inverseProjectionView);
  139. }
  140. /** World space pixel size at given `point` */
  141. getPixelSize(point: Vec3) {
  142. // project -> unproject of `point` does not exactly return the same
  143. // to get a sufficiently accurate measure we unproject the original
  144. // clip position in addition to the one shifted bey one pixel
  145. this.project(tmpClip, point);
  146. this.unproject(tmpPos1, tmpClip);
  147. tmpClip[0] += 1;
  148. this.unproject(tmpPos2, tmpClip);
  149. return Vec3.distance(tmpPos1, tmpPos2);
  150. }
  151. constructor(state?: Partial<Camera.Snapshot>, viewport = Viewport.create(0, 0, 128, 128), props: Partial<{ pixelScale: number }> = {}) {
  152. this.viewport = viewport;
  153. this.pixelScale = props.pixelScale || 1;
  154. Camera.copySnapshot(this.state, state);
  155. }
  156. }
  157. namespace Camera {
  158. export type Mode = 'perspective' | 'orthographic'
  159. export type SnapshotProvider = Partial<Snapshot> | ((scene: Scene, camera: Camera) => Partial<Snapshot>)
  160. /**
  161. * Sets an offseted view in a larger frustum. This is useful for
  162. * - multi-window or multi-monitor/multi-machine setups
  163. * - jittering the camera position for sampling
  164. */
  165. export interface ViewOffset {
  166. enabled: boolean,
  167. fullWidth: number,
  168. fullHeight: number,
  169. offsetX: number,
  170. offsetY: number,
  171. width: number,
  172. height: number
  173. }
  174. export function ViewOffset(): ViewOffset {
  175. return {
  176. enabled: false,
  177. fullWidth: 1, fullHeight: 1,
  178. offsetX: 0, offsetY: 0,
  179. width: 1, height: 1
  180. };
  181. }
  182. export function setViewOffset(out: ViewOffset, fullWidth: number, fullHeight: number, offsetX: number, offsetY: number, width: number, height: number) {
  183. out.fullWidth = fullWidth;
  184. out.fullHeight = fullHeight;
  185. out.offsetX = offsetX;
  186. out.offsetY = offsetY;
  187. out.width = width;
  188. out.height = height;
  189. }
  190. export function copyViewOffset(out: ViewOffset, view: ViewOffset) {
  191. out.enabled = view.enabled;
  192. out.fullWidth = view.fullWidth;
  193. out.fullHeight = view.fullHeight;
  194. out.offsetX = view.offsetX;
  195. out.offsetY = view.offsetY;
  196. out.width = view.width;
  197. out.height = view.height;
  198. }
  199. export function targetDistance(radius: number, fov: number, width: number, height: number) {
  200. const r = Math.max(radius, 0.01);
  201. const aspect = width / height;
  202. const aspectFactor = (height < width ? 1 : aspect);
  203. return Math.abs((r / aspectFactor) / Math.sin(fov / 2));
  204. }
  205. export function createDefaultSnapshot(): Snapshot {
  206. return {
  207. mode: 'perspective',
  208. fov: Math.PI / 4,
  209. position: Vec3.create(0, 0, 100),
  210. up: Vec3.create(0, 1, 0),
  211. target: Vec3.create(0, 0, 0),
  212. radius: 0,
  213. radiusMax: 10,
  214. fog: 50,
  215. clipFar: true
  216. };
  217. }
  218. export interface Snapshot {
  219. mode: Mode
  220. fov: number
  221. position: Vec3
  222. up: Vec3
  223. target: Vec3
  224. radius: number
  225. radiusMax: number
  226. fog: number
  227. clipFar: boolean
  228. }
  229. export function copySnapshot(out: Snapshot, source?: Partial<Snapshot>) {
  230. if (!source) return out;
  231. if (typeof source.mode !== 'undefined') out.mode = source.mode;
  232. if (typeof source.fov !== 'undefined') out.fov = source.fov;
  233. if (typeof source.position !== 'undefined') Vec3.copy(out.position, source.position);
  234. if (typeof source.up !== 'undefined') Vec3.copy(out.up, source.up);
  235. if (typeof source.target !== 'undefined') Vec3.copy(out.target, source.target);
  236. if (typeof source.radius !== 'undefined') out.radius = source.radius;
  237. if (typeof source.radiusMax !== 'undefined') out.radiusMax = source.radiusMax;
  238. if (typeof source.fog !== 'undefined') out.fog = source.fog;
  239. if (typeof source.clipFar !== 'undefined') out.clipFar = source.clipFar;
  240. return out;
  241. }
  242. export function areSnapshotsEqual(a: Snapshot, b: Snapshot) {
  243. return a.mode === b.mode
  244. && a.fov === b.fov
  245. && a.radius === b.radius
  246. && a.radiusMax === b.radiusMax
  247. && a.fog === b.fog
  248. && a.clipFar === b.clipFar
  249. && Vec3.exactEquals(a.position, b.position)
  250. && Vec3.exactEquals(a.up, b.up)
  251. && Vec3.exactEquals(a.target, b.target);
  252. }
  253. }
  254. function updateOrtho(camera: Camera) {
  255. const { viewport, zoom, near, far, viewOffset } = camera;
  256. const fullLeft = -viewport.width / 2;
  257. const fullRight = viewport.width / 2;
  258. const fullTop = viewport.height / 2;
  259. const fullBottom = -viewport.height / 2;
  260. const dx = (fullRight - fullLeft) / (2 * zoom);
  261. const dy = (fullTop - fullBottom) / (2 * zoom);
  262. const cx = (fullRight + fullLeft) / 2;
  263. const cy = (fullTop + fullBottom) / 2;
  264. let left = cx - dx;
  265. let right = cx + dx;
  266. let top = cy + dy;
  267. let bottom = cy - dy;
  268. if (viewOffset.enabled) {
  269. const zoomW = zoom / (viewOffset.width / viewOffset.fullWidth);
  270. const zoomH = zoom / (viewOffset.height / viewOffset.fullHeight);
  271. const scaleW = (fullRight - fullLeft) / viewOffset.width;
  272. const scaleH = (fullTop - fullBottom) / viewOffset.height;
  273. left += scaleW * (viewOffset.offsetX / zoomW);
  274. right = left + scaleW * (viewOffset.width / zoomW);
  275. top -= scaleH * (viewOffset.offsetY / zoomH);
  276. bottom = top - scaleH * (viewOffset.height / zoomH);
  277. }
  278. // build projection matrix
  279. Mat4.ortho(camera.projection, left, right, top, bottom, near, far);
  280. // build view matrix
  281. Mat4.lookAt(camera.view, camera.position, camera.target, camera.up);
  282. }
  283. function updatePers(camera: Camera) {
  284. const aspect = camera.viewport.width / camera.viewport.height;
  285. const { near, far, viewOffset } = camera;
  286. let top = near * Math.tan(0.5 * camera.state.fov);
  287. let height = 2 * top;
  288. let width = aspect * height;
  289. let left = -0.5 * width;
  290. if (viewOffset.enabled) {
  291. left += viewOffset.offsetX * width / viewOffset.fullWidth;
  292. top -= viewOffset.offsetY * height / viewOffset.fullHeight;
  293. width *= viewOffset.width / viewOffset.fullWidth;
  294. height *= viewOffset.height / viewOffset.fullHeight;
  295. }
  296. // build projection matrix
  297. Mat4.perspective(camera.projection, left, left + width, top, top - height, near, far);
  298. // build view matrix
  299. Mat4.lookAt(camera.view, camera.position, camera.target, camera.up);
  300. }
  301. function updateClip(camera: Camera) {
  302. let { radius, radiusMax, mode, fog, clipFar } = camera.state;
  303. if (radius < 0.01) radius = 0.01;
  304. const normalizedFar = clipFar ? radius : radiusMax;
  305. const cameraDistance = Vec3.distance(camera.position, camera.target);
  306. let near = cameraDistance - radius;
  307. let far = cameraDistance + normalizedFar;
  308. const fogNearFactor = -(50 - fog) / 50;
  309. const fogNear = cameraDistance - (normalizedFar * fogNearFactor);
  310. const fogFar = far;
  311. if (mode === 'perspective') {
  312. // set at least to 5 to avoid slow sphere impostor rendering
  313. near = Math.max(Math.min(radiusMax, 5), near);
  314. far = Math.max(5, far);
  315. } else {
  316. // not too close to 0 as it causes issues with outline rendering
  317. near = Math.max(Math.min(radiusMax, 5), near);
  318. far = Math.max(5, far);
  319. }
  320. if (near === far) {
  321. // make sure near and far are not identical to avoid Infinity in the projection matrix
  322. far = near + 0.01;
  323. }
  324. camera.near = near;
  325. camera.far = 2 * far; // avoid precision issues distingushing far objects from background
  326. camera.fogNear = fogNear;
  327. camera.fogFar = fogFar;
  328. }