Graphics 对象空间中的光线跟踪,变换法线

Graphics 对象空间中的光线跟踪,变换法线,graphics,3d,raytracing,Graphics,3d,Raytracing,我有一个工作光线跟踪器(使用gl矩阵在节点中编写) 它可以很好地处理球体,但现在我添加了通用矩阵变换(平移、旋转、缩放),以支持其他对象类型 每个对象有两个变换矩阵,一个是世界到对象的逆矩阵,称为trans,另一个是transFwd,使用fromRotationTranslationScale // Here pos is center of sphere and r is radius mat4.fromRotationTranslationScale(this.transFwd, rotat

我有一个工作光线跟踪器(使用gl矩阵在节点中编写) 它可以很好地处理球体,但现在我添加了通用矩阵变换(平移、旋转、缩放),以支持其他对象类型

每个对象有两个变换矩阵,一个是世界到对象的逆矩阵,称为
trans
,另一个是
transFwd
,使用fromRotationTranslationScale

// Here pos is center of sphere and r is radius
mat4.fromRotationTranslationScale(this.transFwd, rotation, [pos[0], pos[1], pos[2]], [r, r, r]);
mat4.invert(this.trans, this.transFwd);
我正在使用
trans
变换将所有光线变换到对象空间,计算关于原点的光线对象交点(值t),半径为1的球体

挑战是在计算t之后,使用我的交点和法线。当我向变换添加任何类型的旋转时,它们都会扭曲

// ray has already been transformed to object space
// getPoint simply returns ray.pos + t * ray.dir
let intersect: vec4 = ray.getPoint(t);

let normal: vec4 = vec4.sub(vec4.create(), i, [0, 0, 0, 1]);
vec4.normalize(n, n);

// move intersect back to world space
vec4.transformMat4(intersect, intersect, this.transFwd);

为对象使用变换矩阵时,处理法线的正确方法是什么?我试着在之后转换回世界空间,我试着在移回交叉点后计算法线,但没有任何效果

我已经设法解决了这个问题。我走在正确的道路上,只是我没有变换法线和反射光线,所以看起来仍然很奇怪。光线跟踪的难点在于,你能做的唯一测试就是“目视检查”

下面是我在对象空间中工作的球体相交代码的摘要

// Intersection in object space
let intersect: vec4 = ray.getPoint(t);

// Normal is pointing from center of sphere (0,0,0) to intersect (i)
// Divide by sphere radius 
vec4.div(normal, intersect, [radius, radius, radius, 1]);
n[3] = 0;

// Move i back to world space
vec4.transformMat4(intersect, intersect, transFwd);

// Reflected ray about the normal, & move to world
let reflect: vec4 = ray.reflect(normal);
vec4.transformMat4(reflect, r, transFwd);
vec4.normalize(reflect, reflect);   

// Move normal into world & normalize
vec4.transformMat4(normal, normal, transFwd);
vec4.normalize(normal, normal);

变换法线的方式与变换相交的方式相同(至少在变换仅由旋转、平移和均匀缩放组成的情况下)。只需确保w分量为0,然后进行规格化。对于向量,仅使用位置设置为
(0,0,0)
的矩阵。缩放是一个大问题,因为它会改变向量大小,因此在某些情况下需要添加
规格化
。此外,轴之间的不同比例可能会破坏向量之间的关系,因此一些算法/方程可能随后出错。我使用同一坐标系中的所有对象(它们是由三角形和球体构成的),我就是这样做的。谢谢,我现在已经解决了这个问题。谢谢你给我一个线索,我没有完全做错事情!我有点困惑。对光线(原点和方向)使用逆矩阵。使用模型矩阵表示命中点,然后使用逆矩阵表示命中法线。我走的路对吗?