Lerp, InvLerp, Remap 함수 코드 및 three.js에서의 적용

언어는 C#인가 C인가.. Java인가.. 다 해당되는거 같기도 한데.. 여튼 워낙 기초 코드로 작성된 함수이니 저장해 두고 three.js의 쉐이더 작성 코드에서 적용한 예를 살펴봅니다.

float Lerp(float a, float b, float t) {
    return (1.0f - t) * a + b + t;
}

float InvLerp(float a, float b, float v) {
    return (v-a) / (b-a);
}

float Remap(float iMin, float iMax, float oMin, float oMax, float v) {
    flat t = InvLerp(iMin, iMax, v);
    return Lerp(oMin, oMax, t);
}

위의 코드는 Shader 중 glsl 언어로도 사용되는데요. 저 같은 경우 three.js에서 사용한 경우를 소개해 봅니다. 참고로 three.js은 WebGL 기술을 랩핑한 js 라이브러리입니다.

Shader는 Vertex와 Fragment에 대한 처리가 있고.. 재질(Material)에 지정되는데요. 다시 재질은 적용될 지오메트리(Geometry)가 필요합니다. 다음은 지오메트리와 재질에 대한 코드입니다.

const geometry = new THREE.BoxGeometry(1, 1, 1, 10, 10, 10);

fetch("shader4.glsl").then(response => {
    return response.text();
}).then(text => {
    const fragmentShaerCode = text;
    const material = new THREE.ShaderMaterial({
        side: THREE.DoubleSide,
        transparent: true,

        uniforms: {
            iTime: { value: 0 },
            iResolution:  { value: new THREE.Vector3() },
        },

        vertexShader: `
            uniform float iTime;    
        
            varying vec2 vUv;

            void main() {
                vUv = uv;
                gl_Position = projectionMatrix * modelViewMatrix  * vec4(position,1.0);
                //gl_Position = projectionMatrix*(modelViewMatrix*vec4(0.,0.,0.,1.)+vec4(position.x,position.y,0.,0.)); // <- billboard
            }
        `,
        
        fragmentShader: fragmentShaerCode
    });

    const cube = new THREE.Mesh(geometry, material);
    this._scene.add(cube);

    this._material = material;

    ....
}).catch(function (error) {
    console.warn(error);
});

fragmentShaerCode는 shader4.glsl 파일로부터 불러와지는데, 해당 코드는 다음과 같습니다.

uniform vec3 iResolution;
uniform float iTime;

varying vec2 vUv;

float rect(vec2 uv, vec2 p0, vec2 p1, float blur) {
    float maskX = smoothstep(p0.x-blur, p0.x+blur, uv.x);
    maskX -= smoothstep(p1.x-blur, p1.x+blur, uv.x);

    float maskY = smoothstep(p0.y-blur, p0.y+blur, uv.y);
    maskY -= smoothstep(p1.y-blur, p1.y+blur, uv.y);

    float mask = maskX * maskY;
    return mask;
}

// t = a -> return 0., t = b -> return 1.
float invLerp(float a, float b, float t) {
    return (a - t) / (a - b);
}

float remap(float a, float b, float c, float d, float t) {
    return invLerp(a, b, t) * (d - c) + c;
}

void main() {
    vec2 cUv = vUv;

    cUv -= .5;
    float x = cUv.x;

    float m = sin(iTime+x*8.) * .1;
    float y = cUv.y - m;

    float blur = remap(-.5, .5, .01, .25, x);
    blur = pow(blur*3., 3.);
    float mask = rect(vec2(x, y), vec2(-.5,-.1), vec2(.5,.1), blur);

    vec3 col = vec3(1., 1., 0.) * mask;
    gl_FragColor = vec4(col, 1. ); 
}

추후 이 내용을 제 스스로도 참조하기 위해 재질에 대한 uniforms 데이터를 지정하고 있는데요. 관련 코드는 다음과 같습니다.

update(time) {
    time *= 0.001; // second unit
    this._material.uniforms.iTime.value = time;
}

resize() {
    const width = this._divContainer.clientWidth;
    const height = this._divContainer.clientHeight;

    ...

    this._material.uniforms.iResolution.value.set(width, height, 1);
}

위의 코드에 대한 실행 결과는 다음과 같습니다.

위의 예제는 YouTube의 The Art Of Code의 영상을 참조하여 three.js에 맞게 적용한 것입니다.

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다