application.cpp

void prepare() {
texture = Image::createImage("assets/textures/test.jpg");

p1.color = RGBA(255, 0, 0, 255);
p1.uv = math::vec2f(0.0f, 0.0f);

p2.color = RGBA(0, 255, 0, 255);
p2.uv = math::vec2f(1.0f, 1.0f);

p3.color = RGBA(0, 0, 255, 255);
p3.uv = math::vec2f(1.0f, 0.0f);

pos1 = {-1.5f, 0.0f, 0.0f, 1.0f};
pos2 = {1.5f, 0.0f, 0.0f, 1.0f };
pos3 = {0.0f, 2.0f, 0.0f, 1.0f };

perspectiveMatrix = math::perspective(60.0f, (float)WIDTH / (float)HEIGHT, 0.1f, 100.0f);
screenMatrix = math::screenMatrix<float>(WIDTH, HEIGHT);
}

float angle = 0.0f;
float cameraPos = 5.0f;
void Application::transform()
{
angle += 0.01f;
//cameraPos += 0.01f;

//模型变换,旋转变换矩阵(先向上平移再旋转)
modelMatrix = math::translate(math::mat4f(1.0f), math::vec3f{ 0.5f, 0.0f, 0.0f }) * math::rotate(math::mat4f(1.0f), angle, math::vec3f{ 0.0f, 1.0f, 0.0f });

//模拟摄像机往后退
auto cameraModelMatrix = math::translate(math::mat4f(1.0f), math::vec3f{ 0.0f, 0.0f, cameraPos });//一个单位Z轴平移矩阵(将相机从世界坐标系原点位移到指定位置)
viewMatrix = math::inverse(cameraModelMatrix);//视图矩阵是相机模型矩阵的逆矩阵;逆矩阵:将相机坐标系位移到世界坐标系原点

/*
视图矩阵:将世界坐标转为相机坐标系中(视图矩阵的目的就是为了实现投影变换,两者的绑定的)
*/

//mvp矩阵相乘:将世界坐标系转为屏幕坐标系(得到的是四维的齐次坐标)
auto sp1 = perspectiveMatrix * viewMatrix * modelMatrix * pos1;
auto sp2 = perspectiveMatrix * viewMatrix * modelMatrix * pos2;
auto sp3 = perspectiveMatrix * viewMatrix * modelMatrix * pos3;

/*
auto sp1 = viewMatrix * modelMatrix * pos1;
auto sp2 = viewMatrix * modelMatrix * pos2;
auto sp3 = viewMatrix * modelMatrix * pos3;
*/

//透视除法(此处故意设计z!=0)得到NDC坐标(除以w的目的就是为了从齐次坐标转为笛卡尔坐标)->(mvp变换得到的是齐次坐标)
sp1 /= sp1.w;
sp2 /= sp2.w;
sp3 /= sp3.w;

//屏幕空间变换,将NDC转为屏幕坐标
sp1 = screenMatrix * sp1;
sp2 = screenMatrix * sp2;
sp3 = screenMatrix * sp3;

mV0.x = sp1.x;
mV0.y = sp1.y;

mV1.x = sp2.x;
mV1.y = sp2.y;

mV2.x = sp3.x;
mV2.y = sp3.y;
}