Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void Triangle::Draw(Surface* mScreen, float*& ZBuffer, const unsigned int LineColour)
- {
- unsigned int yMin = SCRHEIGHT - 1;
- unsigned int yMax = 0;
- const int textureWidth = Texture->GetWidth();
- const int textureHeight = Texture->GetHeight();
- const int screenWidth = mScreen->GetWidth();
- const int screenHeight = mScreen->GetHeight();
- Vertex* v0 = nullptr;
- Vertex* v1 = nullptr;
- for (unsigned int i = 0; i < amountOfVerts; i++)
- {
- v0 = &Vertices[i];
- v1 = &Vertices[(i + 1) % amountOfVerts];
- if (v0->TransformedPos.y > v1->TransformedPos.y)
- {
- std::swap(v0, v1);
- }
- float x1 = v0->TransformedPos.x;
- float y1 = v0->TransformedPos.y;
- float x2 = v1->TransformedPos.x;
- float y2 = v1->TransformedPos.y;
- float z1 = 1 / v0->TransformedPos.w;
- float z2 = 1 / v1->TransformedPos.w;
- float U1 = v0->U* z1;
- float V1 = v0->V* z1;
- float U2 = v1->U* z2;
- float V2 = v1->V* z2;
- const float dxdy = ((x2 - x1) / (y2 - y1));
- const float dzdy = ((z2 - z1) / (y2 - y1));
- const float dudy = ((U2 - U1) / (y2 - y1));
- const float dvdy = ((V2 - V1) / (y2 - y1));
- const unsigned int intY1 = (unsigned int)floor(y1);
- const unsigned int intY2 = (unsigned int)y2;
- for (unsigned int y = intY1; y < intY2; y++)
- {
- if (y < SCRHEIGHT&&y>0)
- {
- if (x1 < xMin[y])
- {
- xMin[y] = x1;
- zMin[y] = z1;
- uMin[y] = U1;
- vMin[y] = V1;
- }
- if (x1 > xMax[y])
- {
- xMax[y] = x1;
- zMax[y] = z1;
- uMax[y] = U1;
- vMax[y] = V1;
- }
- }
- z1 += dzdy;
- U1 += dudy;
- V1 += dvdy;
- x1 += dxdy;
- }
- yMin = min(intY1, yMin);
- yMax = max(intY2, yMax);
- }
- float u;
- float v;
- float z;
- for (unsigned int y = yMin; y <= yMax; y++)
- {
- const float dudx = (uMax[y] - uMin[y]) / (xMax[y] - xMin[y]);
- const float dvdx = (vMax[y] - vMin[y]) / (xMax[y] - xMin[y]);
- const float dzdx = (zMax[y] - zMin[y]) / (xMax[y] - xMin[y]);
- const float subTexelCorrection = (const float)(((int)(xMin[y] + 1)) - xMin[y]);
- u = uMin[y] + dudx*subTexelCorrection;
- v = vMin[y] + dvdx*subTexelCorrection;
- z = zMin[y] + dzdx*subTexelCorrection;
- for (unsigned int x = xMin[y]; x < xMax[y]; x++)
- {
- z += dzdx;
- u += dudx;
- v += dvdx;
- const unsigned int screenBufferIndex = y* SCRWIDTH + (int)x;
- if (ZBuffer[screenBufferIndex] < z)
- {
- const float RealZ = 1.0f / z;
- const float FinalU = u *RealZ;
- const float FinalV = 1.0f - v *RealZ;
- const int textureBufferIndex = max(0, ((const int)(textureWidth*(FinalU)) % textureWidth) + (const int)(textureHeight*FinalV)*textureWidth % (textureWidth*textureHeight));
- mScreen->GetBuffer()[screenBufferIndex] = Texture->GetBuffer()[textureBufferIndex];
- ZBuffer[screenBufferIndex] = z;
- }
- }
- }
- memset(xMax, 0, 640 * sizeof(int));
- std::fill(xMin, xMin + 640, SCRWIDTH - 1);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement