简体   繁体   中英

Tricolor Fragment Shader

I'm developing an animation using Three.js which simply involves an Icosahedron Buffer Geometry and a Shader Material applied together into a mesh. The goal is to get the object to resemble this:

Vision for final product:

图像

I'm new to GLSL so getting to this point hasn't been easy. I borrowed some code from the shaders used in this codepen. The issue with this shader is that the colors rendered are merely distinct outputs of Red, Green, and Blue, whereas I want three specific colors each with their own unique hex value.

Here is a snippet of the fragment shader code that I have tried:

uniform int u_color1;
uniform int u_color2;
uniform int u_color3;

void main() {
  float r1 = float(u_color1 / 256 / 256);
  float g1 = float(u_color1 / 256 - int(r1 * 256.0));
  float b1 = float(u_color1 - int(r1 * 256.0 * 256.0) - int(g1 * 256.0));

  float r2 = float(u_color2 / 256 / 256);
  float g2 = float(u_color2 / 256 - int(r1 * 256.0));
  float b2 = float(u_color2 - int(r2 * 256.0 * 256.0) - int(g2 * 256.0));

  float r3 = float(u_color3 / 256 / 256);
  float g3 = float(u_color3 / 256 - int(r3 * 256.0));
  float b3 = float(u_color3 - int(r3 * 256.0 * 256.0) - int(g3 * 256.0));

  vec3 color1 = vec3((r1/255.0) , (g1/255.0) , (b1/255.0) );
  vec3 color2 = vec3((r2/255.0) , (g2/255.0) , (b2/255.0) );
  vec3 color3 = vec3((r3/255.0) , (g3/255.0) , (b3/255.0) );

  vec4 outColor = vec4(r1 /256.0, g1/256.0, b1/256.0, 1.0);
  gl_FragColor = outColor;
}

Any input is appreciated. Thanks!

Skip the integral color unforms

uniform int u_color1;
uniform int u_color2;
uniform int u_color3;

Use the data type vec3 for the color:

uniform vec3 u_color1;
uniform vec3 u_color2;
uniform vec3 u_color3;

void main()
{
    gl_FragColor = vec4(u_color1.rgb, 1.0);
}

The components of each color can be accessed by Swizzling . The read green and blue component can be get as floating value in range [0.0, 1.0] by u_color1.r , u_color1.g , u_color1.b .

A uniform of type vec3 c an be directly set by a THREE.Color object. See Uniform . eg:

uniforms: {
    u_color1: { value: new THREE.Color( 0xff0000 ) },
    u_color2: { value: new THREE.Color( 0x00ff00 ) },
    u_color3: { value: new THREE.Color( 0x0000ff ) }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM