This repository has been archived by the owner on Jun 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
material-modifier.js
74 lines (68 loc) · 1.94 KB
/
material-modifier.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
import { UniformsUtils } from 'three';
const hooks = {
vertex: {
preTransform: 'before:#include <begin_vertex>\n',
postTransform: 'after:#include <project_vertex>\n',
preNormal: 'before:#include <beginnormal_vertex>\n'
},
fragment: {
preFragColor: 'before:gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n',
postFragColor: 'after:gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n',
postNormal: 'after:#include <normal_fragment>\n',
postFragFog: 'after:#include <fog_fragment>\n'
}
};
function replace(shader: string, hooks: Object, config: Object) {
Object.keys(hooks).forEach((hook: string) => {
if (config[hook]) {
const parts = hooks[hook].split(':');
const line = parts[1];
switch (parts[0]) {
case 'after': {
shader = shader.replace(
line,
`${line}
${config[hook]}`
);
break;
}
default: {
// before
shader = shader.replace(
line,
`${config[hook]}
${line}`
);
break;
}
}
}
});
return shader;
}
/**
* The material modifier injects custom shader code and uniforms
* to three's built in materials
*
* @export
* @param {Object} shader
* @param {Object} config
* @returns
*/
export default function materialModifier(shader: Object, config: Object) {
shader.uniforms = UniformsUtils.merge([shader.uniforms, config.uniforms]);
shader.vertexShader = `
${config.vertexShader.uniforms}
${config.vertexShader.functions}
${shader.vertexShader}
`;
shader.fragmentShader = `
${config.fragmentShader.uniforms}
${config.fragmentShader.functions}
${shader.fragmentShader}
`;
// Injection
shader.vertexShader = replace(shader.vertexShader, hooks.vertex, config.vertexShader);
shader.fragmentShader = replace(shader.fragmentShader, hooks.fragment, config.fragmentShader);
return shader;
}