2 * Sixth 3D engine. Author: Svjatoslav Agejenko.
3 * This project is released under Creative Commons Zero (CC0) license.
5 package eu.svjatoslav.sixth.e3d.renderer.raster.shapes.basic.texturedpolygon;
7 import eu.svjatoslav.sixth.e3d.geometry.Point2D;
8 import eu.svjatoslav.sixth.e3d.gui.RenderingContext;
9 import eu.svjatoslav.sixth.e3d.math.Vertex;
10 import eu.svjatoslav.sixth.e3d.renderer.raster.shapes.AbstractCoordinateShape;
11 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.Texture;
12 import eu.svjatoslav.sixth.e3d.renderer.raster.texture.TextureBitmap;
14 import java.awt.Color;
16 import static eu.svjatoslav.sixth.e3d.geometry.Polygon.pointWithinPolygon;
19 * A textured triangle renderer with perspective-correct texture mapping.
21 * <p>This class renders triangles with UV-mapped textures. For large triangles,
22 * the rendering may be sliced into smaller pieces for better perspective correction.</p>
24 * <p><b>Perspective-correct texture rendering:</b></p>
26 * <li>Small polygons are rendered without perspective correction</li>
27 * <li>Larger polygons are sliced into smaller pieces for accurate perspective</li>
31 * @see Vertex#textureCoordinate
33 public class TexturedPolygon extends AbstractCoordinateShape {
35 private static final ThreadLocal<PolygonBorderInterpolator[]> INTERPOLATORS =
36 ThreadLocal.withInitial(() -> new PolygonBorderInterpolator[]{
37 new PolygonBorderInterpolator(), new PolygonBorderInterpolator(), new PolygonBorderInterpolator()
41 * The texture to apply to this polygon.
43 public final Texture texture;
45 private boolean backfaceCulling = false;
47 private double totalTextureDistance = -1;
50 * Creates a textured triangle with the specified vertices and texture.
52 * @param p1 the first vertex (must have textureCoordinate set)
53 * @param p2 the second vertex (must have textureCoordinate set)
54 * @param p3 the third vertex (must have textureCoordinate set)
55 * @param texture the texture to apply
57 public TexturedPolygon(Vertex p1, Vertex p2, Vertex p3, final Texture texture) {
60 this.texture = texture;
64 * Computes the total UV distance between all texture coordinate pairs.
65 * Used to determine appropriate mipmap level.
67 private void computeTotalTextureDistance() {
68 // compute total texture distance
69 totalTextureDistance = coordinates[0].textureCoordinate.getDistanceTo(coordinates[1].textureCoordinate);
70 totalTextureDistance += coordinates[0].textureCoordinate.getDistanceTo(coordinates[2].textureCoordinate);
71 totalTextureDistance += coordinates[1].textureCoordinate.getDistanceTo(coordinates[2].textureCoordinate);
75 * Draws a horizontal scanline between two edge interpolators with texture sampling.
77 * @param line1 the left edge interpolator
78 * @param line2 the right edge interpolator
79 * @param y the Y coordinate of the scanline
80 * @param renderBuffer the rendering context to draw into
81 * @param textureBitmap the texture bitmap to sample from
83 private void drawHorizontalLine(final PolygonBorderInterpolator line1,
84 final PolygonBorderInterpolator line2, final int y,
85 final RenderingContext renderBuffer,
86 final TextureBitmap textureBitmap) {
91 int x1 = line1.getX();
92 int x2 = line2.getX();
94 final double tx2, ty2;
95 final double tx1, ty1;
99 tx1 = line1.getTX() * textureBitmap.multiplicationFactor;
100 ty1 = line1.getTY() * textureBitmap.multiplicationFactor;
102 tx2 = line2.getTX() * textureBitmap.multiplicationFactor;
103 ty2 = line2.getTY() * textureBitmap.multiplicationFactor;
110 tx1 = line2.getTX() * textureBitmap.multiplicationFactor;
111 ty1 = line2.getTY() * textureBitmap.multiplicationFactor;
113 tx2 = line1.getTX() * textureBitmap.multiplicationFactor;
114 ty2 = line1.getTY() * textureBitmap.multiplicationFactor;
117 final double realWidth = x2 - x1;
118 final double realX1 = x1;
123 if (x2 >= renderBuffer.width)
124 x2 = renderBuffer.width - 1;
126 int renderBufferOffset = (y * renderBuffer.width) + x1;
127 final int[] renderBufferPixels = renderBuffer.pixels;
129 final double twidth = tx2 - tx1;
130 final double theight = ty2 - ty1;
132 for (int x = x1; x < x2; x++) {
134 final double distance = x - realX1;
136 final double tx = tx1 + ((twidth * distance) / realWidth);
137 final double ty = ty1 + ((theight * distance) / realWidth);
139 final int textureOffset = textureBitmap.getAddress((int) tx,
142 textureBitmap.drawPixel(textureOffset, renderBufferPixels,
145 renderBufferOffset++;
151 * Renders this textured triangle to the screen.
153 * <p>This method performs:</p>
155 * <li>Backface culling check (if enabled)</li>
156 * <li>Mouse interaction detection</li>
157 * <li>Mipmap level selection based on screen coverage</li>
158 * <li>Scanline rasterization with texture sampling</li>
161 * @param renderBuffer the rendering context containing the pixel buffer
164 public void paint(final RenderingContext renderBuffer) {
166 final Point2D projectedPoint1 = coordinates[0].onScreenCoordinate;
167 final Point2D projectedPoint2 = coordinates[1].onScreenCoordinate;
168 final Point2D projectedPoint3 = coordinates[2].onScreenCoordinate;
170 if (backfaceCulling) {
171 final double signedArea = (projectedPoint2.x - projectedPoint1.x)
172 * (projectedPoint3.y - projectedPoint1.y)
173 - (projectedPoint3.x - projectedPoint1.x)
174 * (projectedPoint2.y - projectedPoint1.y);
179 projectedPoint1.roundToInteger();
180 projectedPoint2.roundToInteger();
181 projectedPoint3.roundToInteger();
183 if (mouseInteractionController != null)
184 if (renderBuffer.getMouseEvent() != null)
185 if (pointWithinPolygon(
186 renderBuffer.getMouseEvent().coordinate, projectedPoint1,
187 projectedPoint2, projectedPoint3))
188 renderBuffer.setCurrentObjectUnderMouseCursor(mouseInteractionController);
190 // Show polygon boundaries (for debugging)
191 if (renderBuffer.developerTools != null && renderBuffer.developerTools.showPolygonBorders)
192 showBorders(renderBuffer);
194 // find top-most point
195 int yTop = (int) projectedPoint1.y;
197 if (projectedPoint2.y < yTop)
198 yTop = (int) projectedPoint2.y;
200 if (projectedPoint3.y < yTop)
201 yTop = (int) projectedPoint3.y;
206 // find bottom-most point
207 int yBottom = (int) projectedPoint1.y;
209 if (projectedPoint2.y > yBottom)
210 yBottom = (int) projectedPoint2.y;
212 if (projectedPoint3.y > yBottom)
213 yBottom = (int) projectedPoint3.y;
215 if (yBottom >= renderBuffer.height)
216 yBottom = renderBuffer.height - 1;
218 // clamp to render Y bounds
219 yTop = Math.max(yTop, renderBuffer.renderMinY);
220 yBottom = Math.min(yBottom, renderBuffer.renderMaxY);
225 double totalVisibleDistance = projectedPoint1.getDistanceTo(projectedPoint2);
226 totalVisibleDistance += projectedPoint1.getDistanceTo(projectedPoint3);
227 totalVisibleDistance += projectedPoint2.getDistanceTo(projectedPoint3);
229 if (totalTextureDistance == -1)
230 computeTotalTextureDistance();
231 final double scaleFactor = (totalVisibleDistance / totalTextureDistance) * 1.2d;
233 final TextureBitmap zoomedBitmap = texture.getZoomedBitmap(scaleFactor);
235 final PolygonBorderInterpolator[] interp = INTERPOLATORS.get();
236 final PolygonBorderInterpolator polygonBorder1 = interp[0];
237 final PolygonBorderInterpolator polygonBorder2 = interp[1];
238 final PolygonBorderInterpolator polygonBorder3 = interp[2];
240 polygonBorder1.setPoints(projectedPoint1, projectedPoint2,
241 coordinates[0].textureCoordinate,
242 coordinates[1].textureCoordinate);
243 polygonBorder2.setPoints(projectedPoint1, projectedPoint3,
244 coordinates[0].textureCoordinate,
245 coordinates[2].textureCoordinate);
246 polygonBorder3.setPoints(projectedPoint2, projectedPoint3,
247 coordinates[1].textureCoordinate,
248 coordinates[2].textureCoordinate);
250 // Inline sort for 3 elements to avoid array allocation
251 PolygonBorderInterpolator a = polygonBorder1;
252 PolygonBorderInterpolator b = polygonBorder2;
253 PolygonBorderInterpolator c = polygonBorder3;
254 PolygonBorderInterpolator t;
255 if (a.compareTo(b) > 0) { t = a; a = b; b = t; }
256 if (b.compareTo(c) > 0) { t = b; b = c; c = t; }
257 if (a.compareTo(b) > 0) { t = a; a = b; b = t; }
259 for (int y = yTop; y < yBottom; y++)
260 if (a.containsY(y)) {
262 drawHorizontalLine(a, b, y, renderBuffer, zoomedBitmap);
263 else if (c.containsY(y))
264 drawHorizontalLine(a, c, y, renderBuffer, zoomedBitmap);
265 } else if (b.containsY(y))
267 drawHorizontalLine(b, c, y, renderBuffer, zoomedBitmap);
272 * Checks if backface culling is enabled for this polygon.
274 * @return {@code true} if backface culling is enabled
276 public boolean isBackfaceCullingEnabled() {
277 return backfaceCulling;
281 * Enables or disables backface culling for this polygon.
283 * @param backfaceCulling {@code true} to enable backface culling
285 public void setBackfaceCulling(final boolean backfaceCulling) {
286 this.backfaceCulling = backfaceCulling;
290 * Draws the polygon border edges in yellow (for debugging).
292 * @param renderBuffer the rendering context
294 private void showBorders(final RenderingContext renderBuffer) {
296 final Point2D projectedPoint1 = coordinates[0].onScreenCoordinate;
297 final Point2D projectedPoint2 = coordinates[1].onScreenCoordinate;
298 final Point2D projectedPoint3 = coordinates[2].onScreenCoordinate;
300 final int x1 = (int) projectedPoint1.x;
301 final int y1 = (int) projectedPoint1.y;
302 final int x2 = (int) projectedPoint2.x;
303 final int y2 = (int) projectedPoint2.y;
304 final int x3 = (int) projectedPoint3.x;
305 final int y3 = (int) projectedPoint3.y;
307 renderBuffer.executeWithGraphics(g -> {
308 g.setColor(Color.YELLOW);
309 g.drawLine(x1, y1, x2, y2);
310 g.drawLine(x3, y3, x2, y2);
311 g.drawLine(x1, y1, x3, y3);