JSFiddle - React, Tailwind, and code Playground
by realhunts
HTML
<script src="https://rawgit.com/mrdoob/three.js/master/build/three.js"></script>
<script type="x-shader/x-vertex" id="vertexShader">
attribute vec3 center;
varying vec3 vCenter;
void main() {
vCenter = center;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
</script>
<script type="x-shader/x-fragment" id="fragmentShader">
#extension GL_OES_standard_derivatives: enable
varying vec3 vCenter;
float edgeFactorTri() {
vec3 d = fwidth(vCenter.xyz);
vec3 a3 = smoothstep(vec3(0.0), d * 1.5, vCenter.xyz);
return min(min(a3.x, a3.y), a3.z);
}
void main() {
gl_FragColor.rgb = mix(vec3(1.0), vec3(0.2), edgeFactorTri());
gl_FragColor.a = 1.0;
}
</script>
JavaScript
function setUpBarycentricCoordinates(geometry) {
var positions = geometry.attributes.position.array;
var normals = geometry.attributes.normal.array;
// Build new attribute storing barycentric coordinates
// for each vertex
var centers = new THREE.BufferAttribute(new Float32Array(positions.length), 3);
// start with all edges disabled
for (var f = 0; f < positions.length; f++) { centers.array[f] = 1; }
geometry.addAttribute( 'center', centers );
// Hash all the edges and remember which face they're associated with
// (Adapted from THREE.EdgesHelper)
function sortFunction ( a, b ) {
if (a[0] - b[0] != 0) {
return (a[0] - b[0]);
} else if (a[1] - b[1] != 0) {
return (a[1] - b[1]);
} else {
return (a[2] - b[2]);
}
}
var edge = [ 0, 0 ];
var hash = {};
var face;
var numEdges = 0;
for (var i = 0; i < positions.length/9; i++) {
var a = i * 9
face = [ [ positions[a+0], positions[a+1], positions[a+2] ] ,
[ positions[a+3], positions[a+4], positions[a+5] ] ,
[ positions[a+6], positions[a+7], positions[a+8] ] ];
for (var j = 0; j < 3; j++) {
var k = (j + 1) % 3;
var b = j * 3;
var c = k * 3;
edge[ 0 ] = face[ j ];
edge[ 1 ] = face[ k ];
edge.sort( sortFunction );
key = edge[0] + ' | ' + edge[1];
if ( hash[ key ] == undefined ) {
hash[ key ] = {
face1: a,
face1vert1: a + b,
face1vert2: a + c,
face2: undefined,
face2vert1: undefined,
face2vert2: undefined
};
numEdges++;
} else {
hash[ key ].face2 = a;
hash[ key ].face2vert1 = a + b;
hash[ key ].face2vert2 = a + c;
...