如何正确使用顶点着色器来变形 PShape

How to properly use a vertex shader to morph a PShape

我正在尝试通过顶点着色器使用 perlin 噪声变形 PShape。 到目前为止,我设法通过向 gl_Position 添加一些噪声来做到这一点,但这会影响我场景中的所有元素,而不仅仅是形状。

我已经尝试将着色器调用放在 push/popMatrix 块内或调用 resetMatrix,但到目前为止没有成功。

void init() {
    // Initialize Shader
    shader = loadShader("shaders/noisy-frag.glsl", "shaders/noisy-vert.glsl");
    shader.set("u_noise_amnt", 1.0);
    // Initialize Shape
    sphere = createShape(SPHERE, size);
    sphere.setTexture(loadImage("textures/marble.jpg"));
  }


void display() {

    shader(shader);

    pushMatrix();

    translate(position.x, position.y, position.z);
    rotateX(rotation.x);
    rotateY(rotation.y);
    rotateZ(rotation.z);
    shape(sphere);

    popMatrix();
  }

顶点着色器

uniform mat4 transform;
uniform mat3 normalMatrix;
uniform mat4 texMatrix;

uniform vec4 lightPosition;
uniform float u_time;
uniform float u_noise_amnt;

attribute vec4 position;
attribute vec4 color;
attribute vec3 normal;
attribute vec2 texCoord;

varying vec4 vertColor;
varying vec3 ecNormal;
varying vec3 lightDir;
varying vec4 vertTexCoord;

float cnoise(vec4 position) {
  # perlin noise code
}

void main() {

 float displacement = 25.0 * (cnoise( normal.xyz + u_time ) - 0.5);

 gl_Position = transform * position + 1.0 * displacement;

 vec3 ecPosition = vec3(modelview * position);

 ecNormal = normalize(normalMatrix * normal);
 lightDir = normalize(lightPosition.xyz - ecPosition);
 vertColor = color;

 vertTexCoord = texMatrix * vec4(texCoord, 1.0, 1.0);
}

调用resetShader()恢复默认着色器。

如果要将自定义着色器应用于单个对象,请在绘制形状之前应用着色器 shader() 并在绘制对象后恢复默认着色器:

void display() {

    // [...]

    shader(shader);
    shape(sphere); 
    resetShader();

    // [...]
}