【发布时间】:2014-10-12 01:39:53
【问题描述】:
我有一些代码可以将 2D 精灵渲染到屏幕上。一切正常;但纹理坐标在0,0 - 1,1 范围内提供。我想以像素为单位提供坐标,以便在创建精灵时,我可以提供以像素为单位渲染的精灵表部分(否则,如果我的精灵表改变大小,我需要重新 -计算所有位置,这看起来不太正常)。
// IDEAL SPRITE INIT CODE
var player = new Sprite(
position: new Vector2.zero(),
velocity: new Vector2.zero(),
size: new Vector2(128.0, 128.0) // Rendered size in world-units
texture: player2Texture,
textureOffset: new Vector2.zero(), // Offset in spritesheet
textureSize: new Vector2(100, 100), // Size of section of spritesheet to render
);
我可以在这里传入纹理的总大小,然后除以它,得到 0-1 范围内的数字,但我看不到 WebGL 中的纹理是否让我可以访问它(我也不能当然这是正常的事情)。
我正在尝试在着色器中进行尽可能多的计算(我认为这是合乎逻辑的,因为 GPU 往往比 CPU 更快,但就像我说的,我是菜鸟,请指出这是否是傻!),我当前的着色器看起来像这样:
# VERTEXT SHADER
uniform vec2 uResolution;
attribute vec2 aSpriteLocation;
attribute vec2 aSpriteSize;
attribute vec2 aVertexPosition;
attribute vec2 aTextureCoord;
attribute vec2 aTextureSize;
varying vec2 vTextureCoord;
varying vec2 vTextureSize;
void main() {
// Convert from screen coords to clipSpace (-1,-1 to 1,1)
vec2 clipSpace = (((aSpriteLocation + (aVertexPosition * aSpriteSize)) / uResolution) * 2.0) - 1.0;
// Flip upside down, so 0,0 is at the top of the screen!
clipSpace = clipSpace * vec2(1, -1);
gl_Position = vec4(clipSpace, 0.0, 1.0);
vTextureCoord = aTextureCoord;
vTextureSize = aTextureSize;
}
# FRAGMENT SHADER
#ifdef GL_ES
precision highp float;
#endif
uniform sampler2D uSampler;
varying vec2 vTextureCoord;
varying vec2 vTextureSize; # Currently this must be in the range 0,0 - 1,1; but I want to pass in texture pixels
void main() {
gl_FragColor = texture2D(uSampler, vTextureSize * vec2(vTextureCoord.s, vTextureCoord.t));
}
目前,用于我的片段着色器的vTextureSize 在0,0 - 1,1 范围内工作。为我的纹理提供像素坐标并将它们映射到某处的正确方法是什么?
我认为可能有一个用于基本 2D 渲染的通用/标准着色器集,它已经有一堆我可以提供的制服/属性,但我一直找不到。但是,如果存在这样的事情,我很想知道(因为我什至还没有进行旋转、alpha、着色和其他我可能想要在精灵上做的事情;-))
【问题讨论】:
标签: opengl-es dart webgl shader fragment-shader