Capítulo 574 de 859

Chapter 574: MeshSurfaceSampler

Core Idea

Utility class for sampling weighted random points on the surface of a mesh.

Building the sampler is a one-time O(n) operation. Once built, any number of random samples may be selected in O(logn) time. Memory usage is O(n).

References:

Code Examples

const sampler = new MeshSurfaceSampler( surfaceMesh )
	.setWeightAttribute( 'color' )
	.build();
const mesh = new THREE.InstancedMesh( sampleGeometry, sampleMaterial, 100 );
const position = new THREE.Vector3();
const matrix = new THREE.Matrix4();
// Sample randomly from the surface, creating an instance of the sample geometry at each sample point.
for ( let i = 0; i < 100; i ++ ) {
	sampler.sample( position );
	matrix.makeTranslation( position.x, position.y, position.z );
	mesh.setMatrixAt( i, matrix );
}
scene.add( mesh );
  • What it demonstrates: Typical usage of MeshSurfaceSampler.

Reference Tables

Constructor

Signature
new MeshSurfaceSampler( mesh : Mesh )

Methods

MethodDescription
.build() : MeshSurfaceSamplerProcesses the input geometry and prepares to return samples. Any configuration of the geometry or sampler must occur before this method is called. Time complexity is O(n) for a surface with n faces.
.sample( targetPosition : Vector3, targetNormal : Vector3, targetColor : Color, targetUV : Vector2 ) : MeshSurfaceSamplerSelects a random point on the surface of the input geometry, returning the position and optionally the normal vector, color and UV Coordinate at that point. Time complexity is O(log n) for a surface …
.setRandomGenerator( randomFunction : function ) : MeshSurfaceSamplerAllows to set a custom random number generator. Default is Math.random().
.setWeightAttribute( name : string ) : MeshSurfaceSamplerSpecifies a vertex attribute to be used as a weight when sampling from the surface. Faces with higher weights are more likely to be sampled, and those with weights of zero will not be sampled at all.…

Key Takeaways

  1. Key methods: build, sample, setRandomGenerator, setWeightAttribute.

Connects To