Skip to content

Instantly share code, notes, and snippets.

@AndrewRayCode
Last active December 7, 2020 03:13
Show Gist options
  • Save AndrewRayCode/c9c41b549d0b1e97da8890a79e3ab8d0 to your computer and use it in GitHub Desktop.
Save AndrewRayCode/c9c41b549d0b1e97da8890a79e3ab8d0 to your computer and use it in GitHub Desktop.
Face centroids were removed from Three.js some time ago. These function modify faces **in place** to add a `.centroid` property, which a `Vector3` representing the center of that face. I've added an ES6 version as well for convenience if you're using ES6.
function computeFaceCentroids( geometry ) {
var f, fl, face;
for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
face = geometry.faces[ f ];
face.centroid = new THREE.Vector3( 0, 0, 0 );
if ( face instanceof THREE.Face3 ) {
face.centroid.add( geometry.vertices[ face.a ] );
face.centroid.add( geometry.vertices[ face.b ] );
face.centroid.add( geometry.vertices[ face.c ] );
face.centroid.divideScalar( 3 );
} else if ( face instanceof THREE.Face4 ) {
face.centroid.add( geometry.vertices[ face.a ] );
face.centroid.add( geometry.vertices[ face.b ] );
face.centroid.add( geometry.vertices[ face.c ] );
face.centroid.add( geometry.vertices[ face.d ] );
face.centroid.divideScalar( 4 );
}
}
}
import { Vector3, Face3, Face4 } from 'three';
function computeFaceCentroids( geometry ) {
let f;
let fl;
let face;
for ( f = 0, fl = geometry.faces.length; f < fl; f ++ ) {
face = geometry.faces[ f ];
face.centroid = new Vector3( 0, 0, 0 );
if ( face instanceof Face3 ) {
face.centroid.add( geometry.vertices[ face.a ] );
face.centroid.add( geometry.vertices[ face.b ] );
face.centroid.add( geometry.vertices[ face.c ] );
face.centroid.divideScalar( 3 );
} else if ( face instanceof Face4 ) {
face.centroid.add( geometry.vertices[ face.a ] );
face.centroid.add( geometry.vertices[ face.b ] );
face.centroid.add( geometry.vertices[ face.c ] );
face.centroid.add( geometry.vertices[ face.d ] );
face.centroid.divideScalar( 4 );
}
}
}
@SuperstrongBE
Copy link

SuperstrongBE commented Nov 29, 2020

Hi,
Just find your function super usefull, but it's missing the matrix to work perfectly !
I just add it as an helper function inside my project.
`export function getFacesCenterByCardinalDirection(object,cardinalDirection,matrix) {

	object.updateWorldMatrix();
	const center = new Vector3();
	const faces =  getFacesByCardinalDirection(object.geometry.faces,cardinalDirection);
	faces.map((face,index)=>{

		let centroid = new Vector3();
		centroid.copy(object.geometry.vertices[face.a]);
		centroid.add(object.geometry.vertices[face.b]);
		centroid.add(object.geometry.vertices[face.c]);
		centroid.divideScalar(3);
		centroid.applyMatrix4(object.matrixWorld);
		center.add(centroid);

	});

	return center.divideScalar(faces.length);

}`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment