isosurface.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 { ParamDefinition as PD } from '../../mol-util/param-definition';
  8. import { Grid, Volume } from '../../mol-model/volume';
  9. import { VisualContext } from '../visual';
  10. import { Theme, ThemeRegistryContext } from '../../mol-theme/theme';
  11. import { Mesh } from '../../mol-geo/geometry/mesh/mesh';
  12. import { computeMarchingCubesMesh, computeMarchingCubesLines } from '../../mol-geo/util/marching-cubes/algorithm';
  13. import { VolumeVisual, VolumeRepresentation, VolumeRepresentationProvider } from './representation';
  14. import { LocationIterator } from '../../mol-geo/util/location-iterator';
  15. import { NullLocation } from '../../mol-model/location';
  16. import { VisualUpdateState } from '../util';
  17. import { Lines } from '../../mol-geo/geometry/lines/lines';
  18. import { RepresentationContext, RepresentationParamsGetter, Representation } from '../representation';
  19. import { PickingId } from '../../mol-geo/geometry/picking';
  20. import { EmptyLoci, Loci } from '../../mol-model/loci';
  21. import { Interval } from '../../mol-data/int';
  22. import { Tensor, Vec2, Vec3 } from '../../mol-math/linear-algebra';
  23. import { fillSerial } from '../../mol-util/array';
  24. import { createVolumeTexture2d, eachVolumeLoci, getVolumeTexture2dLayout } from './util';
  25. import { TextureMesh } from '../../mol-geo/geometry/texture-mesh/texture-mesh';
  26. import { extractIsosurface } from '../../mol-gl/compute/marching-cubes/isosurface';
  27. import { WebGLContext } from '../../mol-gl/webgl/context';
  28. import { CustomPropertyDescriptor } from '../../mol-model/custom-property';
  29. import { Texture } from '../../mol-gl/webgl/texture';
  30. export const VolumeIsosurfaceParams = {
  31. isoValue: Volume.IsoValueParam
  32. };
  33. export type VolumeIsosurfaceParams = typeof VolumeIsosurfaceParams
  34. export type VolumeIsosurfaceProps = PD.Values<VolumeIsosurfaceParams>
  35. function gpuSupport(webgl: WebGLContext) {
  36. return webgl.extensions.colorBufferFloat && webgl.extensions.textureFloat && webgl.extensions.drawBuffers;
  37. }
  38. const Padding = 1;
  39. function suitableForGpu(volume: Volume, webgl: WebGLContext) {
  40. const gridDim = volume.grid.cells.space.dimensions as Vec3;
  41. const { powerOfTwoSize } = getVolumeTexture2dLayout(gridDim, Padding);
  42. return powerOfTwoSize <= webgl.maxTextureSize / 2;
  43. }
  44. export function IsosurfaceVisual(materialId: number, volume: Volume, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) {
  45. if (props.tryUseGpu && webgl && gpuSupport(webgl) && suitableForGpu(volume, webgl)) {
  46. return IsosurfaceTextureMeshVisual(materialId);
  47. }
  48. return IsosurfaceMeshVisual(materialId);
  49. }
  50. function getLoci(volume: Volume, props: VolumeIsosurfaceProps) {
  51. return Volume.Isosurface.Loci(volume, props.isoValue);
  52. }
  53. function getIsosurfaceLoci(pickingId: PickingId, volume: Volume, props: VolumeIsosurfaceProps, id: number) {
  54. const { objectId, groupId } = pickingId;
  55. if (id === objectId) {
  56. return Volume.Cell.Loci(volume, Interval.ofSingleton(groupId as Volume.CellIndex));
  57. }
  58. return EmptyLoci;
  59. }
  60. export function eachIsosurface(loci: Loci, volume: Volume, props: VolumeIsosurfaceProps, apply: (interval: Interval) => boolean) {
  61. return eachVolumeLoci(loci, volume, props.isoValue, apply);
  62. }
  63. //
  64. export async function createVolumeIsosurfaceMesh(ctx: VisualContext, volume: Volume, theme: Theme, props: VolumeIsosurfaceProps, mesh?: Mesh) {
  65. ctx.runtime.update({ message: 'Marching cubes...' });
  66. const ids = fillSerial(new Int32Array(volume.grid.cells.data.length));
  67. const surface = await computeMarchingCubesMesh({
  68. isoLevel: Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
  69. scalarField: volume.grid.cells,
  70. idField: Tensor.create(volume.grid.cells.space, Tensor.Data1(ids))
  71. }, mesh).runAsChild(ctx.runtime);
  72. const transform = Grid.getGridToCartesianTransform(volume.grid);
  73. Mesh.transform(surface, transform);
  74. if (ctx.webgl && !ctx.webgl.isWebGL2) {
  75. // 2nd arg means not to split triangles based on group id. Splitting triangles
  76. // is too expensive if each cell has its own group id as is the case here.
  77. Mesh.uniformTriangleGroup(surface, false);
  78. }
  79. surface.setBoundingSphere(Volume.getBoundingSphere(volume));
  80. return surface;
  81. }
  82. export const IsosurfaceMeshParams = {
  83. ...Mesh.Params,
  84. ...TextureMesh.Params,
  85. ...VolumeIsosurfaceParams,
  86. quality: { ...Mesh.Params.quality, isEssential: false },
  87. tryUseGpu: PD.Boolean(true),
  88. };
  89. export type IsosurfaceMeshParams = typeof IsosurfaceMeshParams
  90. export function IsosurfaceMeshVisual(materialId: number): VolumeVisual<IsosurfaceMeshParams> {
  91. return VolumeVisual<Mesh, IsosurfaceMeshParams>({
  92. defaultProps: PD.getDefaultValues(IsosurfaceMeshParams),
  93. createGeometry: createVolumeIsosurfaceMesh,
  94. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  95. getLoci: getIsosurfaceLoci,
  96. eachLocation: eachIsosurface,
  97. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceMeshParams>, currentProps: PD.Values<IsosurfaceMeshParams>) => {
  98. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  99. },
  100. geometryUtils: Mesh.Utils,
  101. mustRecreate: (volume: Volume, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) => {
  102. return props.tryUseGpu && !!webgl && suitableForGpu(volume, webgl);
  103. }
  104. }, materialId);
  105. }
  106. //
  107. namespace VolumeIsosurfaceTexture {
  108. const name = 'volume-isosurface-texture';
  109. export const descriptor = CustomPropertyDescriptor({ name });
  110. export function get(volume: Volume, webgl: WebGLContext) {
  111. const { resources } = webgl;
  112. const transform = Grid.getGridToCartesianTransform(volume.grid);
  113. const gridDimension = Vec3.clone(volume.grid.cells.space.dimensions as Vec3);
  114. const { width, height, powerOfTwoSize: texDim } = getVolumeTexture2dLayout(gridDimension, Padding);
  115. const gridTexDim = Vec3.create(width, height, 0);
  116. const gridTexScale = Vec2.create(width / texDim, height / texDim);
  117. // console.log({ texDim, width, height, gridDimension });
  118. if (texDim > webgl.maxTextureSize / 2) {
  119. throw new Error('volume too large for gpu isosurface extraction');
  120. }
  121. if (!volume._propertyData[name]) {
  122. volume._propertyData[name] = resources.texture('image-uint8', 'alpha', 'ubyte', 'linear');
  123. const texture = volume._propertyData[name] as Texture;
  124. texture.define(texDim, texDim);
  125. // load volume into sub-section of texture
  126. texture.load(createVolumeTexture2d(volume, 'data', Padding), true);
  127. volume.customProperties.add(descriptor);
  128. volume.customProperties.assets(descriptor, [{ dispose: () => texture.destroy() }]);
  129. }
  130. gridDimension[0] += Padding;
  131. gridDimension[1] += Padding;
  132. return {
  133. texture: volume._propertyData[name] as Texture,
  134. transform,
  135. gridDimension,
  136. gridTexDim,
  137. gridTexScale
  138. };
  139. }
  140. }
  141. async function createVolumeIsosurfaceTextureMesh(ctx: VisualContext, volume: Volume, theme: Theme, props: VolumeIsosurfaceProps, textureMesh?: TextureMesh) {
  142. if (!ctx.webgl) throw new Error('webgl context required to create volume isosurface texture-mesh');
  143. const { max, min } = volume.grid.stats;
  144. const diff = max - min;
  145. const value = Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue;
  146. const isoLevel = ((value - min) / diff);
  147. const { texture, gridDimension, gridTexDim, gridTexScale, transform } = VolumeIsosurfaceTexture.get(volume, ctx.webgl);
  148. const gv = extractIsosurface(ctx.webgl, texture, gridDimension, gridTexDim, gridTexScale, transform, isoLevel, false, textureMesh?.vertexTexture.ref.value, textureMesh?.groupTexture.ref.value, textureMesh?.normalTexture.ref.value);
  149. const surface = TextureMesh.create(gv.vertexCount, 1, gv.vertexTexture, gv.groupTexture, gv.normalTexture, Volume.getBoundingSphere(volume), textureMesh);
  150. return surface;
  151. }
  152. export function IsosurfaceTextureMeshVisual(materialId: number): VolumeVisual<IsosurfaceMeshParams> {
  153. return VolumeVisual<TextureMesh, IsosurfaceMeshParams>({
  154. defaultProps: PD.getDefaultValues(IsosurfaceMeshParams),
  155. createGeometry: createVolumeIsosurfaceTextureMesh,
  156. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  157. getLoci: getIsosurfaceLoci,
  158. eachLocation: eachIsosurface,
  159. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceMeshParams>, currentProps: PD.Values<IsosurfaceMeshParams>) => {
  160. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  161. },
  162. geometryUtils: TextureMesh.Utils,
  163. mustRecreate: (volume: Volume, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) => {
  164. return !props.tryUseGpu || !webgl || !suitableForGpu(volume, webgl);
  165. },
  166. dispose: (geometry: TextureMesh) => {
  167. geometry.vertexTexture.ref.value.destroy();
  168. geometry.groupTexture.ref.value.destroy();
  169. geometry.normalTexture.ref.value.destroy();
  170. }
  171. }, materialId);
  172. }
  173. //
  174. export async function createVolumeIsosurfaceWireframe(ctx: VisualContext, volume: Volume, theme: Theme, props: VolumeIsosurfaceProps, lines?: Lines) {
  175. ctx.runtime.update({ message: 'Marching cubes...' });
  176. const ids = fillSerial(new Int32Array(volume.grid.cells.data.length));
  177. const wireframe = await computeMarchingCubesLines({
  178. isoLevel: Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
  179. scalarField: volume.grid.cells,
  180. idField: Tensor.create(volume.grid.cells.space, Tensor.Data1(ids))
  181. }, lines).runAsChild(ctx.runtime);
  182. const transform = Grid.getGridToCartesianTransform(volume.grid);
  183. Lines.transform(wireframe, transform);
  184. wireframe.setBoundingSphere(Volume.getBoundingSphere(volume));
  185. return wireframe;
  186. }
  187. export const IsosurfaceWireframeParams = {
  188. ...Lines.Params,
  189. ...VolumeIsosurfaceParams,
  190. quality: { ...Lines.Params.quality, isEssential: false },
  191. sizeFactor: PD.Numeric(3, { min: 0, max: 10, step: 0.1 }),
  192. };
  193. export type IsosurfaceWireframeParams = typeof IsosurfaceWireframeParams
  194. export function IsosurfaceWireframeVisual(materialId: number): VolumeVisual<IsosurfaceWireframeParams> {
  195. return VolumeVisual<Lines, IsosurfaceWireframeParams>({
  196. defaultProps: PD.getDefaultValues(IsosurfaceWireframeParams),
  197. createGeometry: createVolumeIsosurfaceWireframe,
  198. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  199. getLoci: getIsosurfaceLoci,
  200. eachLocation: eachIsosurface,
  201. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceWireframeParams>, currentProps: PD.Values<IsosurfaceWireframeParams>) => {
  202. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  203. },
  204. geometryUtils: Lines.Utils
  205. }, materialId);
  206. }
  207. //
  208. const IsosurfaceVisuals = {
  209. 'solid': (ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceMeshParams>) => VolumeRepresentation('Isosurface mesh', ctx, getParams, IsosurfaceVisual, getLoci),
  210. 'wireframe': (ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceWireframeParams>) => VolumeRepresentation('Isosurface wireframe', ctx, getParams, IsosurfaceWireframeVisual, getLoci),
  211. };
  212. export const IsosurfaceParams = {
  213. ...IsosurfaceMeshParams,
  214. ...IsosurfaceWireframeParams,
  215. visuals: PD.MultiSelect(['solid'], PD.objectToOptions(IsosurfaceVisuals)),
  216. };
  217. export type IsosurfaceParams = typeof IsosurfaceParams
  218. export function getIsosurfaceParams(ctx: ThemeRegistryContext, volume: Volume) {
  219. const p = PD.clone(IsosurfaceParams);
  220. p.isoValue = Volume.createIsoValueParam(Volume.IsoValue.relative(2), volume.grid.stats);
  221. return p;
  222. }
  223. export type IsosurfaceRepresentation = VolumeRepresentation<IsosurfaceParams>
  224. export function IsosurfaceRepresentation(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceParams>): IsosurfaceRepresentation {
  225. return Representation.createMulti('Isosurface', ctx, getParams, Representation.StateBuilder, IsosurfaceVisuals as unknown as Representation.Def<Volume, IsosurfaceParams>);
  226. }
  227. export const IsosurfaceRepresentationProvider = VolumeRepresentationProvider({
  228. name: 'isosurface',
  229. label: 'Isosurface',
  230. description: 'Displays a triangulated isosurface of volumetric data.',
  231. factory: IsosurfaceRepresentation,
  232. getParams: getIsosurfaceParams,
  233. defaultValues: PD.getDefaultValues(IsosurfaceParams),
  234. defaultColorTheme: { name: 'uniform' },
  235. defaultSizeTheme: { name: 'uniform' },
  236. isApplicable: (volume: Volume) => !Volume.isEmpty(volume)
  237. });