-
Notifications
You must be signed in to change notification settings - Fork 5
/
index.js
95 lines (84 loc) · 2.55 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { BackSide, Color, Face3, Mesh, ShaderMaterial } from 'three';
const fragmentShader = `
uniform vec3 color;
uniform float coefficient;
uniform float power;
varying vec3 vVertexNormal;
varying vec3 vVertexWorldPosition;
void main() {
vec3 worldCameraToVertex = vVertexWorldPosition - cameraPosition;
vec3 viewCameraToVertex = (viewMatrix * vec4(worldCameraToVertex, 0.0)).xyz;
viewCameraToVertex = normalize(viewCameraToVertex);
float intensity = pow(
coefficient + dot(vVertexNormal, viewCameraToVertex),
power
);
gl_FragColor = vec4(color, intensity);
}`;
const vertexShader = `
varying vec3 vVertexWorldPosition;
varying vec3 vVertexNormal;
void main() {
vVertexNormal = normalize(normalMatrix * normal);
vVertexWorldPosition = (modelMatrix * vec4(position, 1.0)).xyz;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
export const defaultOptions = {
backside: true,
coefficient: 0.5,
color: 'gold',
size: 2,
power: 1,
};
// Based off: http://stemkoski.blogspot.fr/2013/07/shaders-in-threejs-glow-and-halo.html
export function createGlowMaterial(coefficient, color, power) {
return new ShaderMaterial({
depthWrite: false,
fragmentShader,
transparent: true,
uniforms: {
coefficient: {
value: coefficient,
},
color: {
value: new Color(color),
},
power: {
value: power,
},
},
vertexShader,
});
}
export function createGlowGeometry(geometry, size) {
// Gather vertexNormals from geometry.faces
const glowGeometry = geometry.clone();
const vertexNormals = new Array(glowGeometry.vertices.length);
glowGeometry.faces.forEach((face) => {
if (face instanceof Face3) {
vertexNormals[face.a] = face.vertexNormals[0];
vertexNormals[face.b] = face.vertexNormals[1];
vertexNormals[face.c] = face.vertexNormals[2];
} else {
console.error('Face needs to be an instance of THREE.Face3.');
}
});
// Modify the vertices according to vertexNormal
glowGeometry.vertices.forEach((vertex, i) => {
const { x, y, z } = vertexNormals[i];
vertex.x += x * size;
vertex.y += y * size;
vertex.z += z * size;
});
return glowGeometry;
}
export function createGlowMesh(geometry, options = defaultOptions) {
const { backside, coefficient, color, size, power } = options;
const glowGeometry = createGlowGeometry(geometry, size);
const glowMaterial = createGlowMaterial(coefficient, color, power);
if (backside) {
glowMaterial.side = BackSide;
}
return new Mesh(glowGeometry, glowMaterial);
}