如何在不使用像three.js这样的库的情况下在webgl中进行环境反射?

Hri*_*sto 8 javascript texture-mapping webgl

我正在试图找出如何在对象上进行环境映射.这是设置:

茶壶

我如何让茶壶的表面反映周围的环境?所以我的意思是,不是茶壶是灰色阴影,它的表面应该反映它的环境,所以它应该将棋盘映射到它的表面.

这是我想要完成的一个例子,但它使用Three.js并且我想自己做这个(这是为了一个类).

http://aerotwist.com/tutorials/create-your-own-environment-maps/demo/

这有意义吗?我该如何开始?


跟进

完成我的家庭作业后,我回答了这个问题:https://stackoverflow.com/a/10093646/196921.请参阅答案以获取链接和代码:)

Hri*_*sto 12

我在这里找到了这个茶壶的好例子......

https://cvs.khronos.org/svn/repos/registry/trunk/public/webgl/sdk/demos/google/shiny-teapot/index.html

浏览源代码,我发现了我在寻找的东西:

function loadCubeMap(base, suffix) {
    var texture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
    gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);

    var faces = [["posx.png", gl.TEXTURE_CUBE_MAP_POSITIVE_X],
                 ["negx.png", gl.TEXTURE_CUBE_MAP_NEGATIVE_X],
                 ["posy.png", gl.TEXTURE_CUBE_MAP_POSITIVE_Y],
                 ["negy.png", gl.TEXTURE_CUBE_MAP_NEGATIVE_Y],
                 ["posz.png", gl.TEXTURE_CUBE_MAP_POSITIVE_Z],
                 ["negz.png", gl.TEXTURE_CUBE_MAP_NEGATIVE_Z]];
    for (var i = 0; i < faces.length; i++) {
        var face = faces[i][1];
        var image = new Image();
        image.onload = function(texture, face, image) {
            return function() {
                gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture);
                gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false);
                gl.texImage2D(face, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image);
            }
        } (texture, face, image);
        image.src = faces[i][0];
    }
    return texture;
}
Run Code Online (Sandbox Code Playgroud)

...和示例片段着色器(它具有超过我需要的环境反射映射)...

precision mediump float;
const float bumpHeight = 0.2;

uniform sampler2D normalSampler;
uniform samplerCube envSampler;

varying vec2 texCoord;
varying vec3 worldEyeVec;
varying vec3 worldNormal;
varying vec3 worldTangent;
varying vec3 worldBinorm;

void main() {
    vec2 bump = (texture2D(normalSampler texCoord.xy).xy * 2.0 - 1.0) * bumpHeight;
    vec3 normal = normalize(worldNormal);
    vec3 tangent = normalize(worldTangent);
    vec3 binormal = normalize(worldBinorm);
    vec3 nb = normal + bump.x * tangent + bump.y * binormal;
    nb = normalize(nb);
    vec3 worldEye = normalize(worldEyeVec);
    vec3 lookup = reflect(worldEye nb);
    vec4 color = textureCube(envSampler, lookup);  // <--- this was the aha! line
    gl_FragColor = color;
}
Run Code Online (Sandbox Code Playgroud)

结果出来有点酷......

茶壶与环境映射

请随时访问http://hristo.oskov.com/projects/cs418/mp3/查看.源代码是它的荣耀......代码很糟糕所以请不要评判我:)这是主要的JS文件:http://hristo.oskov.com/projects/cs418/mp3/js/mp3 .js.着色器位于index.html页面中,因此只需查看源代码.