在Javascript中模拟texture2D

Emulate texture2D in Javascript

本文关键字:texture2D 模拟 Javascript      更新时间:2023-09-26

我编写了一个着色器,该着色器通过高度贴图纹理变换顶点位置。因为几何体是在顶点着色器上转换的,如果不对着色器进行反向工程以将顶点转换到其转换位置,我就无法在javascript中使用传统的拾取算法。我对GLSL中texture2D函数的理解似乎有问题。如果您忽略了纹理包装,您将如何在JS中模拟相同的函数?这就是我目前的做法:

    /**
    * Gets the normalized value of an image's  pixel from the x and y coordinates. The x and y coordinates expected here must be between 0 and 1
    */
    sample( data, x, y, wrappingS, wrappingT )
    {
        var tempVec = new Vec2();
        // Checks the texture wrapping and modifies the x and y accordingly
        this.clampCoords( x, y, wrappingS, wrappingT, tempVec );
        // Convert the normalized units into pixel coords
        x = Math.floor( tempVec.x * data.width );
        y = Math.floor( tempVec.y * data.height );
        if ( x >= data.width )
            x = data.width - 1;
        if ( y >= data.height )
            y = data.height - 1;
        var val= data.data[ ((data.width * y) + x) * 4 ];
        return val / 255.0;
    }

这个函数似乎产生了正确的结果。我有一个409像素宽,434像素高的纹理。我将图像涂成黑色,除了最后一个像素我将其涂成红色(408434)。所以当我在JS中调用采样器函数时:

this.sample(imgData, 0.9999, 0.9999. wrapS, wrapT)

结果是1。对我来说,这是正确的,因为它指的是红色像素。

然而,这似乎不是GLSL给我的。在GLSL中,我使用这个(作为测试):

float coarseHeight = texture2D( heightfield, vec2( 0.9999, 0.9999 ) ).r;

我希望粗略高度也应该是1,但它是0。我不明白。。。有人能告诉我哪里出了问题吗?

您可能已经注意到,任何渲染的纹理都是y镜像的。

OpenGLWebGL的纹理原点在左下角,其中,当使用画布2d方法加载时,缓冲区数据的原点在左上角。

因此,您要么需要重写缓冲区,要么反转v坐标。