Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A World Rendered Beautifully: The Making of the BFCM 3D Data Visualization - CustomMeshStandardMaterial.ts
import {
MeshStandardMaterial,
MeshStandardMaterialParameters,
Shader,
IUniform,
WebGLRenderer,
} from 'three';
interface CustomUniforms {
[uniform: string]: IUniform;
}
export interface CustomShader {
uniforms?: CustomUniforms;
vertexShader?: string;
fragmentShader?: string;
}
class CustomMeshStandardMaterial extends MeshStandardMaterial {
private customUniforms: CustomUniforms;
private customVertexShader: string;
private customFragmentShader: string;
constructor(
params: MeshStandardMaterialParameters,
customShader: CustomShader,
) {
super(params);
this.customVertexShader = customShader.vertexShader;
this.customFragmentShader = customShader.fragmentShader;
this.customUniforms = customShader.uniforms;
}
onBeforeCompile(shader: Shader, _renderer: WebGLRenderer): void {
for (const [key, value] of Object.entries(this.customUniforms)) {
shader.uniforms[key] = value;
}
shader.vertexShader = this.customVertexShader || shader.vertexShader;
shader.fragmentShader = this.customFragmentShader || shader.fragmentShader;
}
protected setCustomUniform(key: string, value: any) {
this.initializeCustomUniforms();
this.customUniforms[key].value = value;
}
protected getCustomUniform(key: string): any {
this.initializeCustomUniforms();
return this.customUniforms[key] && this.customUniforms[key].value;
}
protected initializeCustomUniforms() {
if (!this.customUniforms) {
this.customUniforms = {};
}
}
}
export {CustomMeshStandardMaterial};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.