How would you texture a sphere with a linear gradient with multiple colour-stops?

I’ve been trying to texture a sphere with a verticle linear gradient to act as a stylised sky and have been using the below code to achieve this:

var vertexShader = document.getElementById( 'vertexShader' ).textContent;
	var fragmentShader = document.getElementById( 'fragmentShader' ).textContent;
	var uniforms = {
		topColor:      { type: "c", value: new THREE.Color(0x000000) },
		bottomColor: { type: "c", value: new THREE.Color( 0xC1987C ) },
		offset:         { type: "f", value: 10 },
		exponent:     { type: "f", value: 0.25}
	}

	var skyGeo = new THREE.SphereGeometry( 2000, 32, 15 );
	var skyMat = new THREE.ShaderMaterial( { vertexShader: vertexShader, fragmentShader: fragmentShader, uniforms: uniforms, side: THREE.BackSide} );

	var sky2 = new THREE.Mesh( skyGeo, skyMat );
	scene.add( sky2 );

along with:

   <script type="x-shader/x-vertex" id="vertexShader">

      varying vec3 vWorldPosition;

      void main() {

        vec4 worldPosition = modelMatrix * vec4( position, 1.0 );
        vWorldPosition = worldPosition.xyz;

        gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );

      }

    </script>

and:

    <script type="x-shader/x-fragment" id="fragmentShader">

      uniform vec3 topColor;

      uniform vec3 bottomColor;
      uniform float offset;
      uniform float exponent;

      varying vec3 vWorldPosition;

      void main() {

        float h = normalize( vWorldPosition + offset ).y;
        gl_FragColor = vec4( mix( bottomColor, topColor, max( pow( max( h , 0.0), exponent ), 0.0 ) ), 1.0 );

      }

    </script>

This something I’ve found as I’m not anywhere good enough with shaders to be able to figure them out quite yet. My question is how this could be done with multiple colour-stops instead of just the start and the end colours?

I’ve been searching around for quite a while now with little luck so many thanks in advance to anyone who can help me out!

Hi!
Take a look at this SO answer:


The third example there seems what you’re looking for.
2 Likes

Amazing cheers, I’ll check this out!

Thanks so much for this. Learned a lot from it!

1 Like