three-ts-types
three-ts-types copied to clipboard
feat: Add ShaderMaterial uniforms typing and autocompletion (+ ShaderPass)
Why
To increase quality and speed of development. With autocompletion you won't misspell uniform names and mistype their values.
What
Added uniforms typings for ShaderMaterial, RawShaderMaterial and ShaderPass and also overall type improvements.
The uniform types are automatically inferred when creating an instance from parameters.

Or they can be supplied in generic (useful when just declaring variables) in multiple ways:
let shaderObject = {
vertexShader: "",
fragmentShader: "",
uniforms: {
u_one: { value: 1 },
u_two: { value: null },
},
};
let s0: ShaderMaterial<typeof shaderObject>;
let r1: RawShaderMaterial<{ u_time: number; u_amp: number }>;
let r2: RawShaderMaterial<{ u_one: { value: number }; u_two: { value: Vector2 } }>;
The uniform types will be asserted while creating an instance.
In ShaderMaterial.d.ts you can also find a more strict variant for uniforms (which is commented out) for the case when you don't supply types during declaration, meaning uniforms themselves can be undefined (as there's no assertion during instance creation) or when you cast Material to ShaderMaterial which produces a correct type error but due to the fact this practice is used everywhere in legacy code I decided not to keep it and leave it more loosely making it fully backwards compatible.
Also as null a separate type it's recommended to type uniforms the following way:
new ShaderMaterial({
uniforms: {
uTexture: { value: null as Texture | null },
},
vertexShader: "",
fragmentShader: "",
});
Because if it's simply a null it will be replaced by any to allow value modification.
Checklist
- [x] Added myself to contributors table
- [x] Ready to be merged
This PR has become a bit convoluted, I think if you want to fix some types these should be different PRs
Oh, I'm sorry it just took so long I started to forget about this PR so it became indeed convoluted, sorry again. Tell me, please, if the part about shader materials is ok, so I'll isolate it. While I'll create a separate PR for postprocessing changes on a different branch
I just have reached to the same TUniforms idea, while I rather want to change the definition of Shader which id defined in types/three/src/renderers/shaders/ShaderLib.d.ts .