forked from michaljaz/webmc
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDistanceBasedFog.js
More file actions
60 lines (56 loc) · 2.04 KB
/
DistanceBasedFog.js
File metadata and controls
60 lines (56 loc) · 2.04 KB
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
import { Vector3, Vector2, Vector4 } from "three";
class DistanceBasedFog {
constructor(game) {
this.game = game;
this.view = new Vector3();
this.farnear = new Vector2();
this.color = new Vector4();
}
update() {
this.view
.copy(this.game.camera.position)
.applyMatrix4(this.game.camera.matrixWorldInverse);
}
addShaderToMaterial(material) {
material.onBeforeCompile = (shader) => {
shader.uniforms.u_viewPos = {
value: this.view,
};
shader.uniforms.u_fogColor = {
value: this.color,
};
shader.uniforms.u_farnear = {
value: this.farnear,
};
shader.fragmentShader = [
"uniform vec3 u_viewPos;",
"uniform vec4 u_fogColor;",
"uniform vec2 u_farnear;",
shader.fragmentShader,
].join("\n");
shader.fragmentShader = shader.fragmentShader.replace(
"gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
[
"float dist=length(u_viewPos-vViewPosition);",
"float fogAmount = smoothstep(u_farnear.x, u_farnear.y, dist);",
"gl_FragColor = vec4( outgoingLight, diffuseColor.a );",
"gl_FragColor = mix(gl_FragColor,u_fogColor,max(0.1,fogAmount));",
].join("\n")
);
shader.vertexShader = [
"uniform float time;",
"uniform mat4 u_worldView;",
"attribute vec4 a_position;",
shader.vertexShader,
].join("\n");
shader.vertexShader = shader.vertexShader.replace(
"#include <fog_vertex>",
[
"vec4 vViewPosition4 = modelViewMatrix * vec4(position, 1);",
"vViewPosition = vViewPosition4.xyz;",
].join("\n")
);
};
}
}
export { DistanceBasedFog };