Browse Source

Lesson 19.5 & 19.6

Godzil 3 years ago
parent
commit
30e402e330
1 changed files with 54 additions and 2 deletions
  1. 54 2
      source/triangle.c

+ 54 - 2
source/triangle.c

@@ -112,7 +112,7 @@ void drawFilledTriangle(int32_t x0, int32_t y0, int32_t x1, int32_t y1, int32_t
 
 void drawTextureTriangle(struct triangle_t *t)
 {
-    double My, Mx, Mu, Mv;
+    int32_t x, y;
 
     if (t->points[0].y > t->points[1].y)
     {
@@ -132,7 +132,59 @@ void drawTextureTriangle(struct triangle_t *t)
         doubleSwap(&t->textureCoordinates[0].u, &t->textureCoordinates[1].u);
         doubleSwap(&t->textureCoordinates[0].v, &t->textureCoordinates[1].v);
     }
-    
+
+    /* Render the top part */
+    double inverseSlope1 = 0;
+    double inverseSlope2 = 0;
+    int32_t x0 = t->points[0].x, y0 = t->points[0].y;
+    int32_t x1 = t->points[1].x, y1 = t->points[1].y;
+    int32_t x2 = t->points[2].x, y2 = t->points[2].y;
+
+    if ((y1 - y0) != 0) { inverseSlope1 = (double)(x1 - x0) / abs(y1 - y0); }
+    if ((y2 - y0) != 0) { inverseSlope2 = (double)(x2 - x0) / abs(y2 - y0); }
+
+    if ((y1 - y0) != 0)
+    {
+        for (y = y0 ; y <= y1 ; y++)
+        {
+            int32_t xStart = x1 + (y - y1) * inverseSlope1;
+            int32_t xEnd = x0 + (y - y0) * inverseSlope2;
+
+            if (xEnd < xStart)
+            {
+                intSwap(&xStart, &xEnd);
+            }
+
+            for (x = xStart ; x <= xEnd ; x++)
+            {
+                drawPixel(x, y, (x%2 == 0)?0xFFFF00FF:0xFF000000);
+            }
+        }
+    }
+
+    /* Render the bottom part */
+    inverseSlope1 = 0;
+    if ((y2 - y1) != 0) { inverseSlope1 = (double)(x2 - x1) / abs(y2 - y1); }
+
+    if ((y2 - y1) != 0)
+    {
+        for (y = y1 ; y <= y2 ; y++)
+        {
+            int32_t xStart = x2 + (y - y2) * inverseSlope1;
+            int32_t xEnd = x0 + (y - y0) * inverseSlope2;
+
+            if (xEnd < xStart)
+            {
+                intSwap(&xStart, &xEnd);
+            }
+
+            for (x = xStart ; x <= xEnd ; x++)
+            {
+                drawPixel(x, y, (x%2 == 0)?0xFFFF00FF:0xFF000000);
+            }
+        }
+    }
+
 }
 
 /* ---- Utility ---- */