Access varying vertex position in customised shader

I’m using onBeforeCompile and replace to customise MeshStandardMaterial. I assume that model vertex position is passed to the fragment shader as a varying, but I can’t find the name used. I tried define USE_ALPHAMAP to access vPosition but I get an error about a mismatch. Any advice appreciated.

It’s passed as a varying only in specific cases - so it wouldn’t be a bad idea to just pass it yourself as just varying vec3 vWorldPosition = worldPosition.xyz etc.

Two cases in which it’s passed by three is vViewPosition (for all non-Basic materials), and vWorldPosition (only for MeshPhysicalMaterial, and only if you enable transmission, making the shader a billion times more expensive to compute):

2 Likes

I was looking for the model position not the world position. But your solution worked. I did

this.onBeforeCompile = shader => {
   for (const [key, value] of Object.entries(this.userData.uniforms)) {
	shader.uniforms[key] = value;
   }
   shader.vertexShader = shader.vertexShader.replace( 
      '#include <common>', `
	varying vec3 vModelPosition;
	#include <common>
	`);
   shader.vertexShader = shader.vertexShader.replace( 
       '#include <begin_vertex>', `
	vModelPosition = vec3(position);
	#include <begin_vertex>
	`);
   shader.fragmentShader = shader.fragmentShader.replace( 
	'#include <common>', 
	this.userData.colorVars ) ;		
   shader.fragmentShader = shader.fragmentShader.replace( 
	'#include <color_fragment>', 
	this.userData.colorFrag ) ;	
}

Many thanks for your advice.

1 Like

Mark @mjurczyk’s answer as solved! It helps keep the new queue clean… :smiley:

Thanks for the reminder :+1: