Skip to content

Commit

Permalink
feat(model): apply fog to models
Browse files Browse the repository at this point in the history
  • Loading branch information
fallenoak committed Jan 3, 2024
1 parent 427c80b commit 7bba5b1
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 0 deletions.
2 changes: 2 additions & 0 deletions src/lib/model/ModelMaterial.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ class ModelMaterial extends THREE.RawShaderMaterial {
this.uniforms = {
textures: { value: textures },
alphaRef: { value: alphaRef },
fogColor: { value: new THREE.Color(0.25, 0.5, 0.8) },
fogParams: { value: new THREE.Vector3(0.0, 1066.0, 1.0) },
};

this.glslVersion = THREE.GLSL3;
Expand Down
24 changes: 24 additions & 0 deletions src/lib/model/shader/fragment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const FRAGMENT_SHADER_PREAMBLE = `
precision highp float;
uniform sampler2D textures[2];
uniform vec3 fogColor;
uniform vec3 fogParams;
uniform float alphaRef;
in float vLight;
Expand Down Expand Up @@ -68,6 +70,19 @@ void combine_opaque_mod2x(inout vec4 color, in vec4 tex0, in vec4 tex1) {
}
`;

const FRAGMENT_SHADER_FOG = `
void applyFog(inout vec4 color, float distance) {
float fogStart = fogParams.x;
float fogEnd = fogParams.y;
float fogModifier = fogParams.z;
float fogFactor = (fogEnd - distance) / (fogEnd - fogStart);
fogFactor = clamp(fogFactor * fogModifier, 0.0, 1.0);
color = vec4(mix(color.rgb, fogColor.rgb, 1.0 - fogFactor), color.a);
}
`;

const FRAGMENT_SHADER_MAIN_ALPHATEST = `
// Alpha test
if (color.a < alphaRef) {
Expand All @@ -82,6 +97,11 @@ vec3 lightAmbient = normalize(vec3(0.5, 0.5, 0.5));
color.rgb *= lightDiffuse * vLight + lightAmbient;
`;

const FRAGMENT_SHADER_MAIN_FOG = `
// Apply fog
applyFog(color, vCameraDistance);
`;

const createFragmentShader = (textureCount: number, combineFunction: string) => {
const shaderChunks = [];

Expand All @@ -96,6 +116,8 @@ const createFragmentShader = (textureCount: number, combineFunction: string) =>

shaderChunks.push(FRAGMENT_SHADER_COMBINERS);

shaderChunks.push(FRAGMENT_SHADER_FOG);

const mainChunks = [];

mainChunks.push(`color.rgba = vec4(1.0, 1.0, 1.0, 1.0);`);
Expand All @@ -113,6 +135,8 @@ const createFragmentShader = (textureCount: number, combineFunction: string) =>

mainChunks.push(FRAGMENT_SHADER_MAIN_LIGHTING);

mainChunks.push(FRAGMENT_SHADER_MAIN_FOG);

const main = [`void main() {`, mainChunks.map((chunk) => ` ${chunk}`).join('\n'), '}'].join(
'\n',
);
Expand Down

0 comments on commit 7bba5b1

Please sign in to comment.