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
59 lines (53 loc) · 1.54 KB
/
DistanceBasedFog.js
File metadata and controls
59 lines (53 loc) · 1.54 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
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()
this.visible = true
}
updateDistance (val) {
this.farnear.x = (val - 2) * 16
this.farnear.y = (val - 1) * 16
}
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 fogFactor = smoothstep(u_farnear.x, u_farnear.y, dist);',
'gl_FragColor = vec4(outgoingLight, diffuseColor.a );',
'gl_FragColor = mix(gl_FragColor, u_fogColor, fogFactor);'
].join('\n')
)
}
}
addShaderToMaterials (materials) {
for (let i = 0; i < materials.length; i++) {
this.addShaderToMaterial(materials[i])
}
}
}
export { DistanceBasedFog }