mesh.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Task, RuntimeContext } from 'mol-task'
  7. import { ValueCell } from 'mol-util'
  8. import { Vec3, Mat4 } from 'mol-math/linear-algebra'
  9. import { Sphere3D } from 'mol-math/geometry'
  10. import { transformPositionArray/* , transformDirectionArray, getNormalMatrix */ } from '../../util';
  11. import { Geometry } from '../geometry';
  12. import { createMarkers } from '../marker-data';
  13. import { TransformData } from '../transform-data';
  14. import { LocationIterator } from '../../util/location-iterator';
  15. import { createColors } from '../color-data';
  16. import { ChunkedArray } from 'mol-data/util';
  17. import { ParamDefinition as PD } from 'mol-util/param-definition';
  18. import { calculateBoundingSphere } from 'mol-gl/renderable/util';
  19. import { Theme } from 'mol-theme/theme';
  20. import { MeshValues } from 'mol-gl/renderable/mesh';
  21. export interface Mesh {
  22. readonly kind: 'mesh',
  23. /** Number of vertices in the mesh */
  24. vertexCount: number,
  25. /** Number of triangles in the mesh */
  26. triangleCount: number,
  27. /** Vertex buffer as array of xyz values wrapped in a value cell */
  28. readonly vertexBuffer: ValueCell<Float32Array>,
  29. /** Index buffer as array of vertex index triplets wrapped in a value cell */
  30. readonly indexBuffer: ValueCell<Uint32Array>,
  31. /** Normal buffer as array of xyz values for each vertex wrapped in a value cell */
  32. readonly normalBuffer: ValueCell<Float32Array>,
  33. /** Group buffer as array of group ids for each vertex wrapped in a value cell */
  34. readonly groupBuffer: ValueCell<Float32Array>,
  35. /** Flag indicating if normals are computed for the current set of vertices */
  36. normalsComputed: boolean,
  37. /** Bounding sphere of the mesh */
  38. boundingSphere?: Sphere3D
  39. }
  40. export namespace Mesh {
  41. export function createEmpty(mesh?: Mesh): Mesh {
  42. const vb = mesh ? mesh.vertexBuffer.ref.value : new Float32Array(0)
  43. const ib = mesh ? mesh.indexBuffer.ref.value : new Uint32Array(0)
  44. const nb = mesh ? mesh.normalBuffer.ref.value : new Float32Array(0)
  45. const gb = mesh ? mesh.groupBuffer.ref.value : new Float32Array(0)
  46. return {
  47. kind: 'mesh',
  48. vertexCount: 0,
  49. triangleCount: 0,
  50. vertexBuffer: mesh ? ValueCell.update(mesh.vertexBuffer, vb) : ValueCell.create(vb),
  51. indexBuffer: mesh ? ValueCell.update(mesh.indexBuffer, ib) : ValueCell.create(ib),
  52. normalBuffer: mesh ? ValueCell.update(mesh.normalBuffer, nb) : ValueCell.create(nb),
  53. groupBuffer: mesh ? ValueCell.update(mesh.groupBuffer, gb) : ValueCell.create(gb),
  54. normalsComputed: true,
  55. }
  56. }
  57. export function computeNormalsImmediate(mesh: Mesh) {
  58. if (mesh.normalsComputed) return;
  59. const normals = mesh.normalBuffer.ref.value.length >= mesh.vertexCount * 3
  60. ? mesh.normalBuffer.ref.value : new Float32Array(mesh.vertexBuffer.ref.value.length);
  61. const v = mesh.vertexBuffer.ref.value, triangles = mesh.indexBuffer.ref.value;
  62. if (normals === mesh.normalBuffer.ref.value) {
  63. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  64. normals[i] = 0; normals[i + 1] = 0; normals[i + 2] = 0;
  65. }
  66. }
  67. const x = Vec3.zero(), y = Vec3.zero(), z = Vec3.zero(), d1 = Vec3.zero(), d2 = Vec3.zero(), n = Vec3.zero();
  68. for (let i = 0, ii = 3 * mesh.triangleCount; i < ii; i += 3) {
  69. const a = 3 * triangles[i], b = 3 * triangles[i + 1], c = 3 * triangles[i + 2];
  70. Vec3.fromArray(x, v, a);
  71. Vec3.fromArray(y, v, b);
  72. Vec3.fromArray(z, v, c);
  73. Vec3.sub(d1, z, y);
  74. Vec3.sub(d2, x, y);
  75. Vec3.cross(n, d1, d2);
  76. normals[a] += n[0]; normals[a + 1] += n[1]; normals[a + 2] += n[2];
  77. normals[b] += n[0]; normals[b + 1] += n[1]; normals[b + 2] += n[2];
  78. normals[c] += n[0]; normals[c + 1] += n[1]; normals[c + 2] += n[2];
  79. }
  80. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  81. const nx = normals[i];
  82. const ny = normals[i + 1];
  83. const nz = normals[i + 2];
  84. const f = 1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz);
  85. normals[i] *= f; normals[i + 1] *= f; normals[i + 2] *= f;
  86. // console.log([normals[i], normals[i + 1], normals[i + 2]], [v[i], v[i + 1], v[i + 2]])
  87. }
  88. ValueCell.update(mesh.normalBuffer, normals);
  89. mesh.normalsComputed = true;
  90. }
  91. export function checkForDuplicateVertices(mesh: Mesh, fractionDigits = 3) {
  92. const v = mesh.vertexBuffer.ref.value
  93. const map = new Map<string, number>()
  94. const hash = (v: Vec3, d: number) => `${v[0].toFixed(d)}|${v[1].toFixed(d)}|${v[2].toFixed(d)}`
  95. let duplicates = 0
  96. const a = Vec3.zero()
  97. for (let i = 0, il = mesh.vertexCount; i < il; ++i) {
  98. Vec3.fromArray(a, v, i * 3)
  99. const k = hash(a, fractionDigits)
  100. const count = map.get(k)
  101. if (count !== undefined) {
  102. duplicates += 1
  103. map.set(k, count + 1)
  104. } else {
  105. map.set(k, 1)
  106. }
  107. }
  108. return duplicates
  109. }
  110. export function computeNormals(surface: Mesh): Task<Mesh> {
  111. return Task.create<Mesh>('Surface (Compute Normals)', async ctx => {
  112. if (surface.normalsComputed) return surface;
  113. await ctx.update('Computing normals...');
  114. computeNormalsImmediate(surface);
  115. return surface;
  116. });
  117. }
  118. export function transformImmediate(mesh: Mesh, t: Mat4) {
  119. transformRangeImmediate(mesh, t, 0, mesh.vertexCount)
  120. }
  121. export function transformRangeImmediate(mesh: Mesh, t: Mat4, offset: number, count: number) {
  122. const v = mesh.vertexBuffer.ref.value
  123. transformPositionArray(t, v, offset, count)
  124. // TODO normals transformation does not work for an unknown reason, ASR
  125. // if (mesh.normalBuffer.ref.value) {
  126. // const n = getNormalMatrix(Mat3.zero(), t)
  127. // transformDirectionArray(n, mesh.normalBuffer.ref.value, offset, count)
  128. // mesh.normalsComputed = true;
  129. // }
  130. ValueCell.update(mesh.vertexBuffer, v);
  131. mesh.normalsComputed = false;
  132. }
  133. export function computeBoundingSphere(mesh: Mesh): Task<Mesh> {
  134. return Task.create<Mesh>('Mesh (Compute Bounding Sphere)', async ctx => {
  135. if (mesh.boundingSphere) {
  136. return mesh;
  137. }
  138. await ctx.update('Computing bounding sphere...');
  139. const vertices = mesh.vertexBuffer.ref.value;
  140. let x = 0, y = 0, z = 0;
  141. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  142. x += vertices[i];
  143. y += vertices[i + 1];
  144. z += vertices[i + 2];
  145. }
  146. x /= mesh.vertexCount;
  147. y /= mesh.vertexCount;
  148. z /= mesh.vertexCount;
  149. let r = 0;
  150. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  151. const dx = x - vertices[i];
  152. const dy = y - vertices[i + 1];
  153. const dz = z - vertices[i + 2];
  154. r = Math.max(r, dx * dx + dy * dy + dz * dz);
  155. }
  156. mesh.boundingSphere = {
  157. center: Vec3.create(x, y, z),
  158. radius: Math.sqrt(r)
  159. }
  160. return mesh;
  161. });
  162. }
  163. /**
  164. * Ensure that each vertices of each triangle have the same group id.
  165. * Note that normals are copied over and can't be re-created from the new mesh.
  166. */
  167. export function uniformTriangleGroup(mesh: Mesh, splitTriangles = true) {
  168. const { indexBuffer, vertexBuffer, groupBuffer, normalBuffer, triangleCount, vertexCount } = mesh
  169. const ib = indexBuffer.ref.value
  170. const vb = vertexBuffer.ref.value
  171. const gb = groupBuffer.ref.value
  172. const nb = normalBuffer.ref.value
  173. // new
  174. const index = ChunkedArray.create(Uint32Array, 3, 1024, triangleCount)
  175. // re-use
  176. const vertex = ChunkedArray.create(Float32Array, 3, 1024, vb)
  177. vertex.currentIndex = vertexCount * 3
  178. vertex.elementCount = vertexCount
  179. const normal = ChunkedArray.create(Float32Array, 3, 1024, nb)
  180. normal.currentIndex = vertexCount * 3
  181. normal.elementCount = vertexCount
  182. const group = ChunkedArray.create(Float32Array, 1, 1024, gb)
  183. group.currentIndex = vertexCount
  184. group.elementCount = vertexCount
  185. const vi = Vec3.zero()
  186. const vj = Vec3.zero()
  187. const vk = Vec3.zero()
  188. const ni = Vec3.zero()
  189. const nj = Vec3.zero()
  190. const nk = Vec3.zero()
  191. function add(i: number) {
  192. Vec3.fromArray(vi, vb, i * 3)
  193. Vec3.fromArray(ni, nb, i * 3)
  194. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  195. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  196. }
  197. function addMid(i: number, j: number) {
  198. Vec3.fromArray(vi, vb, i * 3)
  199. Vec3.fromArray(vj, vb, j * 3)
  200. Vec3.scale(vi, Vec3.add(vi, vi, vj), 0.5)
  201. Vec3.fromArray(ni, nb, i * 3)
  202. Vec3.fromArray(nj, nb, j * 3)
  203. Vec3.scale(ni, Vec3.add(ni, ni, nj), 0.5)
  204. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  205. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  206. }
  207. function addCenter(i: number, j: number, k: number) {
  208. Vec3.fromArray(vi, vb, i * 3)
  209. Vec3.fromArray(vj, vb, j * 3)
  210. Vec3.fromArray(vk, vb, k * 3)
  211. Vec3.scale(vi, Vec3.add(vi, Vec3.add(vi, vi, vj), vk), 1/3)
  212. Vec3.fromArray(ni, nb, i * 3)
  213. Vec3.fromArray(nj, nb, j * 3)
  214. Vec3.fromArray(nk, nb, k * 3)
  215. Vec3.scale(ni, Vec3.add(ni, Vec3.add(ni, ni, nj), nk), 1/3)
  216. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  217. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  218. }
  219. function split2(i0: number, i1: number, i2: number, g0: number, g1: number) {
  220. ++newTriangleCount
  221. add(i0); addMid(i0, i1); addMid(i0, i2);
  222. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2)
  223. for (let j = 0; j < 3; ++j) ChunkedArray.add(group, g0)
  224. newVertexCount += 3
  225. newTriangleCount += 2
  226. add(i1); add(i2); addMid(i0, i1); addMid(i0, i2);
  227. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  228. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  229. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g1)
  230. newVertexCount += 4
  231. }
  232. let newVertexCount = vertexCount
  233. let newTriangleCount = 0
  234. if (splitTriangles) {
  235. for (let i = 0, il = triangleCount; i < il; ++i) {
  236. const i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2]
  237. const g0 = gb[i0], g1 = gb[i1], g2 = gb[i2]
  238. if (g0 === g1 && g0 === g2) {
  239. ++newTriangleCount
  240. ChunkedArray.add3(index, i0, i1, i2)
  241. } else if (g0 === g1) {
  242. split2(i2, i0, i1, g2, g0)
  243. } else if (g0 === g2) {
  244. split2(i1, i2, i0, g1, g2)
  245. } else if (g1 === g2) {
  246. split2(i0, i1, i2, g0, g1)
  247. } else {
  248. newTriangleCount += 2
  249. add(i0); addMid(i0, i1); addMid(i0, i2); addCenter(i0, i1, i2);
  250. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  251. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  252. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g0)
  253. newVertexCount += 4
  254. newTriangleCount += 2
  255. add(i1); addMid(i1, i2); addMid(i1, i0); addCenter(i0, i1, i2);
  256. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  257. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  258. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g1)
  259. newVertexCount += 4
  260. newTriangleCount += 2
  261. add(i2); addMid(i2, i1); addMid(i2, i0); addCenter(i0, i1, i2);
  262. ChunkedArray.add3(index, newVertexCount + 3, newVertexCount + 1, newVertexCount)
  263. ChunkedArray.add3(index, newVertexCount + 2, newVertexCount + 3, newVertexCount)
  264. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g2)
  265. newVertexCount += 4
  266. }
  267. }
  268. } else {
  269. for (let i = 0, il = triangleCount; i < il; ++i) {
  270. const i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2]
  271. const g0 = gb[i0], g1 = gb[i1], g2 = gb[i2]
  272. if (g0 !== g1 || g0 !== g2) {
  273. ++newTriangleCount
  274. add(i0); add(i1); add(i2)
  275. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2)
  276. const g = g1 === g2 ? g1 : g0
  277. for (let j = 0; j < 3; ++j) ChunkedArray.add(group, g)
  278. newVertexCount += 3
  279. } else {
  280. ++newTriangleCount
  281. ChunkedArray.add3(index, i0, i1, i2)
  282. }
  283. }
  284. }
  285. const newIb = ChunkedArray.compact(index)
  286. const newVb = ChunkedArray.compact(vertex)
  287. const newNb = ChunkedArray.compact(normal)
  288. const newGb = ChunkedArray.compact(group)
  289. mesh.vertexCount = newVertexCount
  290. mesh.triangleCount = newTriangleCount
  291. ValueCell.update(vertexBuffer, newVb) as ValueCell<Float32Array>
  292. ValueCell.update(groupBuffer, newGb) as ValueCell<Float32Array>
  293. ValueCell.update(indexBuffer, newIb) as ValueCell<Uint32Array>
  294. ValueCell.update(normalBuffer, newNb) as ValueCell<Float32Array>
  295. return mesh
  296. }
  297. //
  298. export const Params = {
  299. ...Geometry.Params,
  300. doubleSided: PD.Boolean(false),
  301. flipSided: PD.Boolean(false),
  302. flatShaded: PD.Boolean(false),
  303. }
  304. export type Params = typeof Params
  305. export async function createValues(ctx: RuntimeContext, mesh: Mesh, transform: TransformData, locationIt: LocationIterator, theme: Theme, props: PD.Values<Params>): Promise<MeshValues> {
  306. const { instanceCount, groupCount } = locationIt
  307. const color = await createColors(ctx, locationIt, theme.color)
  308. const marker = createMarkers(instanceCount * groupCount)
  309. const counts = { drawCount: mesh.triangleCount * 3, groupCount, instanceCount }
  310. const boundingSphere = calculateBoundingSphere(
  311. mesh.vertexBuffer.ref.value, mesh.vertexCount,
  312. transform.aTransform.ref.value, transform.instanceCount.ref.value
  313. )
  314. return {
  315. aPosition: mesh.vertexBuffer,
  316. aNormal: mesh.normalBuffer,
  317. aGroup: mesh.groupBuffer,
  318. elements: mesh.indexBuffer,
  319. boundingSphere: ValueCell.create(boundingSphere),
  320. ...color,
  321. ...marker,
  322. ...transform,
  323. ...Geometry.createValues(props, counts),
  324. dDoubleSided: ValueCell.create(props.doubleSided),
  325. dFlatShaded: ValueCell.create(props.flatShaded),
  326. dFlipSided: ValueCell.create(props.flipSided),
  327. }
  328. }
  329. export function updateValues(values: MeshValues, props: PD.Values<Params>) {
  330. const boundingSphere = calculateBoundingSphere(
  331. values.aPosition.ref.value, Math.floor(values.aPosition.ref.value.length / 3),
  332. values.aTransform.ref.value, values.instanceCount.ref.value
  333. )
  334. if (!Sphere3D.equals(boundingSphere, values.boundingSphere.ref.value)) {
  335. ValueCell.update(values.boundingSphere, boundingSphere)
  336. }
  337. Geometry.updateValues(values, props)
  338. ValueCell.updateIfChanged(values.dDoubleSided, props.doubleSided)
  339. ValueCell.updateIfChanged(values.dFlatShaded, props.flatShaded)
  340. ValueCell.updateIfChanged(values.dFlipSided, props.flipSided)
  341. }
  342. }
  343. // function addVertex(src: Float32Array, i: number, dst: Float32Array, j: number) {
  344. // dst[3 * j] += src[3 * i];
  345. // dst[3 * j + 1] += src[3 * i + 1];
  346. // dst[3 * j + 2] += src[3 * i + 2];
  347. // }
  348. // function laplacianSmoothIter(surface: Surface, vertexCounts: Int32Array, vs: Float32Array, vertexWeight: number) {
  349. // const triCount = surface.triangleIndices.length,
  350. // src = surface.vertices;
  351. // const triangleIndices = surface.triangleIndices;
  352. // for (let i = 0; i < triCount; i += 3) {
  353. // const a = triangleIndices[i],
  354. // b = triangleIndices[i + 1],
  355. // c = triangleIndices[i + 2];
  356. // addVertex(src, b, vs, a);
  357. // addVertex(src, c, vs, a);
  358. // addVertex(src, a, vs, b);
  359. // addVertex(src, c, vs, b);
  360. // addVertex(src, a, vs, c);
  361. // addVertex(src, b, vs, c);
  362. // }
  363. // const vw = 2 * vertexWeight;
  364. // for (let i = 0, _b = surface.vertexCount; i < _b; i++) {
  365. // const n = vertexCounts[i] + vw;
  366. // vs[3 * i] = (vs[3 * i] + vw * src[3 * i]) / n;
  367. // vs[3 * i + 1] = (vs[3 * i + 1] + vw * src[3 * i + 1]) / n;
  368. // vs[3 * i + 2] = (vs[3 * i + 2] + vw * src[3 * i + 2]) / n;
  369. // }
  370. // }
  371. // async function laplacianSmoothComputation(ctx: Computation.Context, surface: Surface, iterCount: number, vertexWeight: number) {
  372. // await ctx.updateProgress('Smoothing surface...', true);
  373. // const vertexCounts = new Int32Array(surface.vertexCount),
  374. // triCount = surface.triangleIndices.length;
  375. // const tris = surface.triangleIndices;
  376. // for (let i = 0; i < triCount; i++) {
  377. // // in a triangle 2 edges touch each vertex, hence the constant.
  378. // vertexCounts[tris[i]] += 2;
  379. // }
  380. // let vs = new Float32Array(surface.vertices.length);
  381. // let started = Utils.PerformanceMonitor.currentTime();
  382. // await ctx.updateProgress('Smoothing surface...', true);
  383. // for (let i = 0; i < iterCount; i++) {
  384. // if (i > 0) {
  385. // for (let j = 0, _b = vs.length; j < _b; j++) vs[j] = 0;
  386. // }
  387. // surface.normals = void 0;
  388. // laplacianSmoothIter(surface, vertexCounts, vs, vertexWeight);
  389. // const t = surface.vertices;
  390. // surface.vertices = <any>vs;
  391. // vs = <any>t;
  392. // const time = Utils.PerformanceMonitor.currentTime();
  393. // if (time - started > Computation.UpdateProgressDelta) {
  394. // started = time;
  395. // await ctx.updateProgress('Smoothing surface...', true, i + 1, iterCount);
  396. // }
  397. // }
  398. // return surface;
  399. // }
  400. // /*
  401. // * Smooths the vertices by averaging the neighborhood.
  402. // *
  403. // * Resets normals. Might replace vertex array.
  404. // */
  405. // export function laplacianSmooth(surface: Surface, iterCount: number = 1, vertexWeight: number = 1): Computation<Surface> {
  406. // if (iterCount < 1) iterCount = 0;
  407. // if (iterCount === 0) return Computation.resolve(surface);
  408. // return computation(async ctx => await laplacianSmoothComputation(ctx, surface, iterCount, (1.1 * vertexWeight) / 1.1));
  409. // }