MeshSurfaceSampler.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import {
  2. Triangle,
  3. Vector2,
  4. Vector3
  5. } from 'three';
  6. const _face = new Triangle();
  7. const _color = new Vector3();
  8. const _uva = new Vector2(), _uvb = new Vector2(), _uvc = new Vector2();
  9. /**
  10. * Utility class for sampling weighted random points on the surface of a mesh.
  11. *
  12. * Building the sampler is a one-time O(n) operation. Once built, any number of
  13. * random samples may be selected in O(logn) time. Memory usage is O(n).
  14. *
  15. * References:
  16. * - {@link http://www.joesfer.com/?p=84}
  17. * - {@link https://stackoverflow.com/a/4322940/1314762}
  18. *
  19. * ```js
  20. * const sampler = new MeshSurfaceSampler( surfaceMesh )
  21. * .setWeightAttribute( 'color' )
  22. * .build();
  23. *
  24. * const mesh = new THREE.InstancedMesh( sampleGeometry, sampleMaterial, 100 );
  25. *
  26. * const position = new THREE.Vector3();
  27. * const matrix = new THREE.Matrix4();
  28. *
  29. * // Sample randomly from the surface, creating an instance of the sample geometry at each sample point.
  30. *
  31. * for ( let i = 0; i < 100; i ++ ) {
  32. *
  33. * sampler.sample( position );
  34. * matrix.makeTranslation( position.x, position.y, position.z );
  35. * mesh.setMatrixAt( i, matrix );
  36. *
  37. * }
  38. *
  39. * scene.add( mesh );
  40. * ```
  41. */
  42. class MeshSurfaceSampler {
  43. /**
  44. * Constructs a mesh surface sampler.
  45. *
  46. * @param {Mesh} mesh - Surface mesh from which to sample.
  47. */
  48. constructor( mesh ) {
  49. this.geometry = mesh.geometry;
  50. this.randomFunction = Math.random;
  51. this.indexAttribute = this.geometry.index;
  52. this.positionAttribute = this.geometry.getAttribute( 'position' );
  53. this.normalAttribute = this.geometry.getAttribute( 'normal' );
  54. this.colorAttribute = this.geometry.getAttribute( 'color' );
  55. this.uvAttribute = this.geometry.getAttribute( 'uv' );
  56. this.weightAttribute = null;
  57. this.distribution = null;
  58. }
  59. /**
  60. * Specifies a vertex attribute to be used as a weight when sampling from the surface.
  61. * Faces with higher weights are more likely to be sampled, and those with weights of
  62. * zero will not be sampled at all. For vector attributes, only .x is used in sampling.
  63. *
  64. * If no weight attribute is selected, sampling is randomly distributed by area.
  65. *
  66. * @param {string} name - The attribute name.
  67. * @return {MeshSurfaceSampler} A reference to this sampler.
  68. */
  69. setWeightAttribute( name ) {
  70. this.weightAttribute = name ? this.geometry.getAttribute( name ) : null;
  71. return this;
  72. }
  73. /**
  74. * Processes the input geometry and prepares to return samples. Any configuration of the
  75. * geometry or sampler must occur before this method is called. Time complexity is O(n)
  76. * for a surface with n faces.
  77. *
  78. * @return {MeshSurfaceSampler} A reference to this sampler.
  79. */
  80. build() {
  81. const indexAttribute = this.indexAttribute;
  82. const positionAttribute = this.positionAttribute;
  83. const weightAttribute = this.weightAttribute;
  84. const totalFaces = indexAttribute ? ( indexAttribute.count / 3 ) : ( positionAttribute.count / 3 );
  85. const faceWeights = new Float32Array( totalFaces );
  86. // Accumulate weights for each mesh face.
  87. for ( let i = 0; i < totalFaces; i ++ ) {
  88. let faceWeight = 1;
  89. let i0 = 3 * i;
  90. let i1 = 3 * i + 1;
  91. let i2 = 3 * i + 2;
  92. if ( indexAttribute ) {
  93. i0 = indexAttribute.getX( i0 );
  94. i1 = indexAttribute.getX( i1 );
  95. i2 = indexAttribute.getX( i2 );
  96. }
  97. if ( weightAttribute ) {
  98. faceWeight = weightAttribute.getX( i0 )
  99. + weightAttribute.getX( i1 )
  100. + weightAttribute.getX( i2 );
  101. }
  102. _face.a.fromBufferAttribute( positionAttribute, i0 );
  103. _face.b.fromBufferAttribute( positionAttribute, i1 );
  104. _face.c.fromBufferAttribute( positionAttribute, i2 );
  105. faceWeight *= _face.getArea();
  106. faceWeights[ i ] = faceWeight;
  107. }
  108. // Store cumulative total face weights in an array, where weight index
  109. // corresponds to face index.
  110. const distribution = new Float32Array( totalFaces );
  111. let cumulativeTotal = 0;
  112. for ( let i = 0; i < totalFaces; i ++ ) {
  113. cumulativeTotal += faceWeights[ i ];
  114. distribution[ i ] = cumulativeTotal;
  115. }
  116. this.distribution = distribution;
  117. return this;
  118. }
  119. /**
  120. * Allows to set a custom random number generator. Default is `Math.random()`.
  121. *
  122. * @param {Function} randomFunction - A random number generator.
  123. * @return {MeshSurfaceSampler} A reference to this sampler.
  124. */
  125. setRandomGenerator( randomFunction ) {
  126. this.randomFunction = randomFunction;
  127. return this;
  128. }
  129. /**
  130. * Selects a random point on the surface of the input geometry, returning the
  131. * position and optionally the normal vector, color and UV Coordinate at that point.
  132. * Time complexity is O(log n) for a surface with n faces.
  133. *
  134. * @param {Vector3} targetPosition - The target object holding the sampled position.
  135. * @param {Vector3} targetNormal - The target object holding the sampled normal.
  136. * @param {Color} targetColor - The target object holding the sampled color.
  137. * @param {Vector2} targetUV - The target object holding the sampled uv coordinates.
  138. * @return {MeshSurfaceSampler} A reference to this sampler.
  139. */
  140. sample( targetPosition, targetNormal, targetColor, targetUV ) {
  141. const faceIndex = this._sampleFaceIndex();
  142. return this._sampleFace( faceIndex, targetPosition, targetNormal, targetColor, targetUV );
  143. }
  144. // private
  145. _sampleFaceIndex() {
  146. const cumulativeTotal = this.distribution[ this.distribution.length - 1 ];
  147. return this._binarySearch( this.randomFunction() * cumulativeTotal );
  148. }
  149. _binarySearch( x ) {
  150. const dist = this.distribution;
  151. let start = 0;
  152. let end = dist.length - 1;
  153. let index = - 1;
  154. while ( start <= end ) {
  155. const mid = Math.ceil( ( start + end ) / 2 );
  156. if ( mid === 0 || dist[ mid - 1 ] <= x && dist[ mid ] > x ) {
  157. index = mid;
  158. break;
  159. } else if ( x < dist[ mid ] ) {
  160. end = mid - 1;
  161. } else {
  162. start = mid + 1;
  163. }
  164. }
  165. return index;
  166. }
  167. _sampleFace( faceIndex, targetPosition, targetNormal, targetColor, targetUV ) {
  168. let u = this.randomFunction();
  169. let v = this.randomFunction();
  170. if ( u + v > 1 ) {
  171. u = 1 - u;
  172. v = 1 - v;
  173. }
  174. // get the vertex attribute indices
  175. const indexAttribute = this.indexAttribute;
  176. let i0 = faceIndex * 3;
  177. let i1 = faceIndex * 3 + 1;
  178. let i2 = faceIndex * 3 + 2;
  179. if ( indexAttribute ) {
  180. i0 = indexAttribute.getX( i0 );
  181. i1 = indexAttribute.getX( i1 );
  182. i2 = indexAttribute.getX( i2 );
  183. }
  184. _face.a.fromBufferAttribute( this.positionAttribute, i0 );
  185. _face.b.fromBufferAttribute( this.positionAttribute, i1 );
  186. _face.c.fromBufferAttribute( this.positionAttribute, i2 );
  187. targetPosition
  188. .set( 0, 0, 0 )
  189. .addScaledVector( _face.a, u )
  190. .addScaledVector( _face.b, v )
  191. .addScaledVector( _face.c, 1 - ( u + v ) );
  192. if ( targetNormal !== undefined ) {
  193. if ( this.normalAttribute !== undefined ) {
  194. _face.a.fromBufferAttribute( this.normalAttribute, i0 );
  195. _face.b.fromBufferAttribute( this.normalAttribute, i1 );
  196. _face.c.fromBufferAttribute( this.normalAttribute, i2 );
  197. targetNormal.set( 0, 0, 0 ).addScaledVector( _face.a, u ).addScaledVector( _face.b, v ).addScaledVector( _face.c, 1 - ( u + v ) ).normalize();
  198. } else {
  199. _face.getNormal( targetNormal );
  200. }
  201. }
  202. if ( targetColor !== undefined && this.colorAttribute !== undefined ) {
  203. _face.a.fromBufferAttribute( this.colorAttribute, i0 );
  204. _face.b.fromBufferAttribute( this.colorAttribute, i1 );
  205. _face.c.fromBufferAttribute( this.colorAttribute, i2 );
  206. _color
  207. .set( 0, 0, 0 )
  208. .addScaledVector( _face.a, u )
  209. .addScaledVector( _face.b, v )
  210. .addScaledVector( _face.c, 1 - ( u + v ) );
  211. targetColor.r = _color.x;
  212. targetColor.g = _color.y;
  213. targetColor.b = _color.z;
  214. }
  215. if ( targetUV !== undefined && this.uvAttribute !== undefined ) {
  216. _uva.fromBufferAttribute( this.uvAttribute, i0 );
  217. _uvb.fromBufferAttribute( this.uvAttribute, i1 );
  218. _uvc.fromBufferAttribute( this.uvAttribute, i2 );
  219. targetUV.set( 0, 0 ).addScaledVector( _uva, u ).addScaledVector( _uvb, v ).addScaledVector( _uvc, 1 - ( u + v ) );
  220. }
  221. return this;
  222. }
  223. }
  224. export { MeshSurfaceSampler };
粤ICP备19079148号