scene.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. /**
  2. * Copyright (c) 2018-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { WebGLContext } from './webgl/context';
  8. import { GraphicsRenderObject, createRenderable } from './render-object';
  9. import { Object3D } from './object3d';
  10. import { Sphere3D } from '../mol-math/geometry';
  11. import { CommitQueue } from './commit-queue';
  12. import { now } from '../mol-util/now';
  13. import { arraySetRemove } from '../mol-util/array';
  14. import { BoundaryHelper } from '../mol-math/geometry/boundary-helper';
  15. import { hash1 } from '../mol-data/util';
  16. import { GraphicsRenderable } from './renderable';
  17. import { GraphicsRenderVariants } from './webgl/render-item';
  18. import { clamp } from '../mol-math/interpolate';
  19. const boundaryHelper = new BoundaryHelper('98');
  20. function calculateBoundingSphere(renderables: GraphicsRenderable[], boundingSphere: Sphere3D, onlyVisible: boolean): Sphere3D {
  21. boundaryHelper.reset();
  22. for (let i = 0, il = renderables.length; i < il; ++i) {
  23. if (onlyVisible && !renderables[i].state.visible) continue;
  24. const boundingSphere = renderables[i].values.boundingSphere.ref.value;
  25. if (!boundingSphere.radius) continue;
  26. boundaryHelper.includeSphere(boundingSphere);
  27. }
  28. boundaryHelper.finishedIncludeStep();
  29. for (let i = 0, il = renderables.length; i < il; ++i) {
  30. if (onlyVisible && !renderables[i].state.visible) continue;
  31. const boundingSphere = renderables[i].values.boundingSphere.ref.value;
  32. if (!boundingSphere.radius) continue;
  33. boundaryHelper.radiusSphere(boundingSphere);
  34. }
  35. return boundaryHelper.getSphere(boundingSphere);
  36. }
  37. function renderableSort(a: GraphicsRenderable, b: GraphicsRenderable) {
  38. const drawProgramIdA = (a.getProgram('colorBlended') || a.getProgram('colorWboit')).id;
  39. const drawProgramIdB = (b.getProgram('colorBlended') || a.getProgram('colorWboit')).id;
  40. const materialIdA = a.materialId;
  41. const materialIdB = b.materialId;
  42. if (drawProgramIdA !== drawProgramIdB) {
  43. // sort by program id to minimize gl state changes
  44. return drawProgramIdA - drawProgramIdB;
  45. } else if (materialIdA !== materialIdB) {
  46. // sort by material id to minimize gl state changes
  47. return materialIdA - materialIdB;
  48. } else {
  49. return a.id - b.id;
  50. }
  51. }
  52. interface Scene extends Object3D {
  53. readonly count: number
  54. readonly renderables: ReadonlyArray<GraphicsRenderable>
  55. readonly boundingSphere: Sphere3D
  56. readonly boundingSphereVisible: Sphere3D
  57. readonly primitives: Scene.Group
  58. readonly volumes: Scene.Group
  59. /** Returns `true` if some visibility has changed, `false` otherwise. */
  60. syncVisibility: () => boolean
  61. update: (objects: ArrayLike<GraphicsRenderObject> | undefined, keepBoundingSphere: boolean) => void
  62. add: (o: GraphicsRenderObject) => void // GraphicsRenderable
  63. remove: (o: GraphicsRenderObject) => void
  64. commit: (maxTimeMs?: number) => boolean
  65. readonly needsCommit: boolean
  66. has: (o: GraphicsRenderObject) => boolean
  67. clear: () => void
  68. forEach: (callbackFn: (value: GraphicsRenderable, key: GraphicsRenderObject) => void) => void
  69. /** Marker average of primitive renderables */
  70. readonly markerAverage: number
  71. /** Opacity average of primitive renderables */
  72. readonly opacityAverage: number
  73. /** Is `true` if any primitive renderable (possibly) has any opaque part */
  74. readonly hasOpaque: boolean
  75. }
  76. namespace Scene {
  77. export interface Group extends Object3D {
  78. readonly renderables: ReadonlyArray<GraphicsRenderable>
  79. }
  80. export function create(ctx: WebGLContext, variants = GraphicsRenderVariants): Scene {
  81. const renderableMap = new Map<GraphicsRenderObject, GraphicsRenderable>();
  82. const renderables: GraphicsRenderable[] = [];
  83. const boundingSphere = Sphere3D();
  84. const boundingSphereVisible = Sphere3D();
  85. const primitives: GraphicsRenderable[] = [];
  86. const volumes: GraphicsRenderable[] = [];
  87. let boundingSphereDirty = true;
  88. let boundingSphereVisibleDirty = true;
  89. let markerAverage = 0;
  90. let opacityAverage = 0;
  91. let hasOpaque = false;
  92. const object3d = Object3D.create();
  93. const { view, position, direction, up } = object3d;
  94. function add(o: GraphicsRenderObject) {
  95. if (!renderableMap.has(o)) {
  96. const renderable = createRenderable(ctx, o, variants);
  97. renderables.push(renderable);
  98. if (o.type === 'direct-volume') {
  99. volumes.push(renderable);
  100. } else {
  101. primitives.push(renderable);
  102. }
  103. renderableMap.set(o, renderable);
  104. boundingSphereDirty = true;
  105. boundingSphereVisibleDirty = true;
  106. return renderable;
  107. } else {
  108. console.warn(`RenderObject with id '${o.id}' already present`);
  109. return renderableMap.get(o)!;
  110. }
  111. }
  112. function remove(o: GraphicsRenderObject) {
  113. const renderable = renderableMap.get(o);
  114. if (renderable) {
  115. renderable.dispose();
  116. arraySetRemove(renderables, renderable);
  117. arraySetRemove(primitives, renderable);
  118. arraySetRemove(volumes, renderable);
  119. renderableMap.delete(o);
  120. boundingSphereDirty = true;
  121. boundingSphereVisibleDirty = true;
  122. }
  123. }
  124. const commitBulkSize = 100;
  125. function commit(maxTimeMs: number) {
  126. const start = now();
  127. let i = 0;
  128. while (true) {
  129. const o = commitQueue.tryGetRemove();
  130. if (!o) break;
  131. remove(o);
  132. if (++i % commitBulkSize === 0 && now() - start > maxTimeMs) return false;
  133. }
  134. while (true) {
  135. const o = commitQueue.tryGetAdd();
  136. if (!o) break;
  137. add(o);
  138. if (++i % commitBulkSize === 0 && now() - start > maxTimeMs) return false;
  139. }
  140. renderables.sort(renderableSort);
  141. markerAverage = calculateMarkerAverage();
  142. opacityAverage = calculateOpacityAverage();
  143. hasOpaque = calculateHasOpaque();
  144. return true;
  145. }
  146. const commitQueue = new CommitQueue();
  147. let visibleHash = -1;
  148. function computeVisibleHash() {
  149. let hash = 23;
  150. for (let i = 0, il = renderables.length; i < il; ++i) {
  151. if (!renderables[i].state.visible) continue;
  152. hash = (31 * hash + renderables[i].id) | 0;
  153. }
  154. hash = hash1(hash);
  155. if (hash === -1) hash = 0;
  156. return hash;
  157. }
  158. function syncVisibility() {
  159. const newVisibleHash = computeVisibleHash();
  160. if (newVisibleHash !== visibleHash) {
  161. boundingSphereVisibleDirty = true;
  162. markerAverage = calculateMarkerAverage();
  163. opacityAverage = calculateOpacityAverage();
  164. hasOpaque = calculateHasOpaque();
  165. visibleHash = newVisibleHash;
  166. return true;
  167. } else {
  168. return false;
  169. }
  170. }
  171. function calculateMarkerAverage() {
  172. if (primitives.length === 0) return 0;
  173. let count = 0;
  174. let markerAverage = 0;
  175. for (let i = 0, il = primitives.length; i < il; ++i) {
  176. if (!primitives[i].state.visible) continue;
  177. markerAverage += primitives[i].values.markerAverage.ref.value;
  178. count += 1;
  179. }
  180. return count > 0 ? markerAverage / count : 0;
  181. }
  182. function calculateOpacityAverage() {
  183. if (primitives.length === 0) return 0;
  184. let count = 0;
  185. let opacityAverage = 0;
  186. for (let i = 0, il = primitives.length; i < il; ++i) {
  187. const p = primitives[i];
  188. if (!p.state.visible) continue;
  189. // TODO: simplify, handle in renderable.state???
  190. // uAlpha is updated in "render" so we need to recompute it here
  191. const alpha = clamp(p.values.alpha.ref.value * p.state.alphaFactor, 0, 1);
  192. const xray = p.values.dXrayShaded?.ref.value ? 0.5 : 1;
  193. const fuzzy = p.values.dPointStyle?.ref.value === 'fuzzy' ? 0.5 : 1;
  194. const text = p.values.dGeometryType.ref.value === 'text' ? 0.5 : 1;
  195. opacityAverage += (1 - p.values.transparencyAverage.ref.value) * alpha * xray * fuzzy * text;
  196. count += 1;
  197. }
  198. return count > 0 ? opacityAverage / count : 0;
  199. }
  200. function calculateHasOpaque() {
  201. if (primitives.length === 0) return false;
  202. for (let i = 0, il = primitives.length; i < il; ++i) {
  203. const p = primitives[i];
  204. if (!p.state.visible) continue;
  205. if (p.state.opaque) return true;
  206. if (p.state.alphaFactor === 1 && p.values.alpha.ref.value === 1 && p.values.transparencyAverage.ref.value !== 1) return true;
  207. if (p.values.dTransparentBackfaces?.ref.value === 'opaque') return true;
  208. }
  209. return false;
  210. }
  211. return {
  212. view, position, direction, up,
  213. renderables,
  214. primitives: { view, position, direction, up, renderables: primitives },
  215. volumes: { view, position, direction, up, renderables: volumes },
  216. syncVisibility,
  217. update(objects, keepBoundingSphere) {
  218. Object3D.update(object3d);
  219. if (objects) {
  220. for (let i = 0, il = objects.length; i < il; ++i) {
  221. renderableMap.get(objects[i])?.update();
  222. }
  223. } else {
  224. for (let i = 0, il = renderables.length; i < il; ++i) {
  225. renderables[i].update();
  226. }
  227. }
  228. if (!keepBoundingSphere) {
  229. boundingSphereDirty = true;
  230. boundingSphereVisibleDirty = true;
  231. } else {
  232. syncVisibility();
  233. }
  234. markerAverage = calculateMarkerAverage();
  235. opacityAverage = calculateOpacityAverage();
  236. hasOpaque = calculateHasOpaque();
  237. },
  238. add: (o: GraphicsRenderObject) => commitQueue.add(o),
  239. remove: (o: GraphicsRenderObject) => commitQueue.remove(o),
  240. commit: (maxTime = Number.MAX_VALUE) => commit(maxTime),
  241. get needsCommit() { return !commitQueue.isEmpty; },
  242. has: (o: GraphicsRenderObject) => {
  243. return renderableMap.has(o);
  244. },
  245. clear: () => {
  246. for (let i = 0, il = renderables.length; i < il; ++i) {
  247. renderables[i].dispose();
  248. }
  249. renderables.length = 0;
  250. primitives.length = 0;
  251. volumes.length = 0;
  252. renderableMap.clear();
  253. boundingSphereDirty = true;
  254. boundingSphereVisibleDirty = true;
  255. },
  256. forEach: (callbackFn: (value: GraphicsRenderable, key: GraphicsRenderObject) => void) => {
  257. renderableMap.forEach(callbackFn);
  258. },
  259. get count() {
  260. return renderables.length;
  261. },
  262. get boundingSphere() {
  263. if (boundingSphereDirty) {
  264. calculateBoundingSphere(renderables, boundingSphere, false);
  265. boundingSphereDirty = false;
  266. }
  267. return boundingSphere;
  268. },
  269. get boundingSphereVisible() {
  270. if (boundingSphereVisibleDirty) {
  271. calculateBoundingSphere(renderables, boundingSphereVisible, true);
  272. boundingSphereVisibleDirty = false;
  273. }
  274. return boundingSphereVisible;
  275. },
  276. get markerAverage() {
  277. return markerAverage;
  278. },
  279. get opacityAverage() {
  280. return opacityAverage;
  281. },
  282. get hasOpaque() {
  283. return hasOpaque;
  284. },
  285. };
  286. }
  287. }
  288. export { Scene };