Newer
Older
EPQ-3D-renderer / src / main / java / uk / org / floop / epq3d / Triangle.java
@cory cory on 8 Feb 2023 11 KB Fix #21
package uk.org.floop.epq3d;

import java.awt.*;

public class Triangle{
    public PointComp point1;
    public PointComp point2;
    public PointComp point3;

    public Matrix[] perspectiveMappingMatrix;

    public boolean[] edgeList; //edge 1-2 , 2-3, 3-1

    private Line2d LineLong;
    private Line2d LineA;
    private Line2d LineB;

    public Texture texture;

    // initialisation variables
    private boolean is_initialised = false;
    private Point2D min;
    private Point2D max;
    private Point2D startPoint;
    private double xGradient;
    private double yGradient;

    private final Point2D result2 = new Point2D(0,0);
    public void invalidate() {
        is_initialised = false;
    }
    public Triangle(PointComp _pA, PointComp _pB, PointComp _pC, boolean[] _edgeList, Texture _texture, Matrix[] mapMatrix){
        point1 = _pA;
        point2 = _pB;
        point3 = _pC;
        edgeList = _edgeList;
        texture = _texture;
        perspectiveMappingMatrix = mapMatrix;
    }
    //  returns int for debug
    public int draw(drawData drawData, double ang){
        //
        long lastMillis;
        if (!is_initialised){
            if(initialise(drawData)){
                int[] point1;
                int[] point2;
                char currentLine = 'A';

                lastMillis = System.currentTimeMillis();

                point1 = LineLong.nextPix();
                point2 = LineA.nextPix();
                for(int x = min.x+1; x <= max.x; x += 1) {
                    while(x-1 == point1[0]) {
                        if((LineLong.isDrawn || drawData.drawLines) && // draw line pixels if needed, and on screen
                                point1[0] > 0 && point1[1] > 0 && point1[0] < drawData.scrX && point1[1] < drawData.scrY){
                            drawData.drawImg[point1[0]][point1[1]] = Color.HSBtoRGB(0, 1, 1);
                        }
                        try {
                            point1 = LineLong.nextPix();
                        }
                        catch (Exception e){
                            throw new RuntimeException("accessed too many line pixels");
                        }
                    }
                    while(x-1 == point2[0]) {
                        if (currentLine == 'A') {
                            try{
                                if((LineA.isDrawn || drawData.drawLines) &&                // draw line pixels if needed, and on screen
                                        point2[0] > 0 && point2[1] > 0 && point2[0] < drawData.scrX && point2[1] < drawData.scrY){
                                    drawData.drawImg[point2[0]][point2[1]] = Color.HSBtoRGB(0, 1, 1);
                                }
                                point2 = LineA.nextPix();
                            }
                            catch (RuntimeException e){
                                currentLine = 'B';
                            }
                        }
                        else {
                            if((LineB.isDrawn || drawData.drawLines) &&                // draw line pixels if needed, and on screen
                                    point2[0] > 0 && point2[1] > 0 && point2[0] < drawData.scrX && point2[1] < drawData.scrY){
                                drawData.drawImg[point2[0]][point2[1]] = Color.HSBtoRGB(0, 1, 1);
                            }
                            point2 = LineB.nextPix();
                        }
                    }
                    // cancel drawing if the x value of the triangle is out of bounds
                    if (x >= drawData.scrX) {break;}
                    if (x > 0) {
                        if (point1[1] < point2[1]) {
                            double z1 = LineLong.getZVal(x); double z2;
                            if(currentLine=='A'){
                                z2=LineA.getZVal(x);
                            } else{
                                z2=LineB.getZVal(x);
                            }
                            double gradient = -(z2 - z1) / (point2[1]-point1[1]);
                            for (int y = Math.max(point1[1], 0); y <= Math.min(point2[1], drawData.scrY - 1); y += 1) {
                                // function only exists so I don't have to copy paste code everywhere.
                                drawPix(drawData, x, y, ang);
                            }
                        } else {
                            double z2 = LineLong.getZVal(x); double z1;
                            if(currentLine=='A'){
                                z1=LineA.getZVal(x);
                            } else{
                                z1=LineB.getZVal(x);
                            }
                            double gradient = -(z2 - z1) / (point1[1]-point2[1]);
                            for (int y = Math.max(point2[1], 0); y <= Math.min(point1[1], drawData.scrY - 1); y += 1) {
                                drawPix(drawData, x, y, ang);
                            }
                        }
                    }
                }
                lastMillis = (System.currentTimeMillis() - lastMillis);
                return (int)lastMillis;
            }
        }
        return 0;
    }
    public boolean initialise(drawData drawData){

        if (point1 == null || point2 == null || point3 == null){
            throw new NullPointerException();
        }
        min = new Point2D(
                Math.min(point1.getProjectedPoint().x,
                        Math.min(point2.getProjectedPoint().x, point3.getProjectedPoint().x)),
                Math.min(point1.getProjectedPoint().y,
                        Math.min(point2.getProjectedPoint().y, point3.getProjectedPoint().y)));
        max = new Point2D(
                Math.max(point1.getProjectedPoint().x,
                        Math.max(point2.getProjectedPoint().x, point3.getProjectedPoint().x)),
                Math.max(point1.getProjectedPoint().y,
                        Math.max(point2.getProjectedPoint().y, point3.getProjectedPoint().y)));
        if(max.x < 0 || min.x > drawData.scrX || max.y < 0 || min.y > drawData.scrY){
            return false;
        }
        // woo horrible IFs mess.
        // we need to figure out which points touch the edges in order to find which line is the 'full length' edge,
        // and then assign line A and line B in order
        if (point1.getProjectedPoint().x == min.x) {
            if (point2.getProjectedPoint().x == max.x){
                LineLong = new Line2d(point1, point2, edgeList[0]);
                LineA = new Line2d(point1, point3, edgeList[2]);
                LineB = new Line2d(point3, point2, edgeList[1]);
            } else {
                LineLong = new Line2d(point1, point3, edgeList[2]);
                LineA = new Line2d(point1, point2, edgeList[0]);
                LineB = new Line2d(point2, point3, edgeList[1]);
            }
        }
        else if (point2.getProjectedPoint().x == min.x) {
            if (point1.getProjectedPoint().x == max.x) {
                LineLong = new Line2d(point2, point1, edgeList[0]);
                LineA = new Line2d(point2, point3, edgeList[1]);
                LineB = new Line2d(point3, point1, edgeList[2]);
            } else {
                LineLong = new Line2d(point2, point3, edgeList[1]);
                LineA = new Line2d(point2, point1, edgeList[0]);
                LineB = new Line2d(point1, point3, edgeList[2]);
            }
        }
        else if (point3.getProjectedPoint().x == min.x){
            if (point1.getProjectedPoint().x == max.x) {
                LineLong = new Line2d(point3, point1, edgeList[2]);
                LineA = new Line2d(point3, point2, edgeList[1]);
                LineB = new Line2d(point2, point1, edgeList[0]);
            } else {
                LineLong = new Line2d(point3, point2, edgeList[2]);
                LineA = new Line2d(point3, point1, edgeList[1]);
                LineB = new Line2d(point1, point2, edgeList[0]);
            }
        }
        // find z calculation constants
        // they are always relative to lineLong point1. This is an arbitrary decision but it must be consistent
        startPoint = LineLong.point1.getProjectedPoint();

        // find two vectors in screen coordinates from the point
        Vector3D vec1 = new Vector3D(
                LineLong.point2.getProjectedPoint().x - startPoint.x,
                LineLong.point2.getProjectedPoint().y - startPoint.y,
                1/LineLong.point2.getRotatedPoint().z - 1/startPoint.z
                );
        // in theory, projected point and rotated point Z values are the same. However, at some point i'd like to remove z values from 2d points
        Vector3D vec2 = new Vector3D(
                LineA.point2.getProjectedPoint().x - startPoint.x,
                LineA.point2.getProjectedPoint().y - startPoint.y,
                1/LineA.point2.getRotatedPoint().z - 1/startPoint.z
        );
        // calculate the cross product of these two vectors in order to obtain a normal vector
        Vector3D cross = vec1.cross(vec2);
        // find xGradient and yGradient for the triangle, in terms of z. We take the negative reciprocal of these gradients, because of the normal vector.
        xGradient = -cross.x / cross.z;
        yGradient = -cross.y / cross.z;
        if(!Double.isFinite(xGradient)){
            xGradient = 0;
        }
        if(!Double.isFinite(yGradient)){
            yGradient = 0;
        }

//        double testZ2 = LineLong.point2.getProjectedPoint().z;
//        double testZ = refPoint.getProjectedPoint().z +
//                xGradient * (LineLong.point2.getProjectedPoint().x-refPoint.getProjectedPoint().x) +
//                yGradient * (LineLong.point2.getProjectedPoint().y-refPoint.getProjectedPoint().y);

        double testZ2 = LineA.point2.getProjectedPoint().z;

        double testZ = 1/(1/startPoint.z +
                xGradient * (LineA.point2.getProjectedPoint().x-startPoint.x) +
                yGradient * (LineA.point2.getProjectedPoint().y-startPoint.y));
        //System.out.println(testZ - testZ2);
        // assign points to lines
        is_initialised = true;
        return true;
    }
    private void drawPix(drawData drawData, int x, int y, double ang){
        // a value of 0 represents a value which is on the camera, at z=0.
        // not the best mapping but it's probably good enough
        double zVal = 1/((1/startPoint.z +
                (x - startPoint.x)*xGradient +
                (y - startPoint.y)*yGradient));
        int newZ = (int)(2147483647d/(zVal + 1));
//        if (newZ == 2147483647){
//            System.out.println((1/startPoint.z +
//                    (x - startPoint.x)*xGradient +
//                    (y - startPoint.y)*yGradient));
//        }
        // if the new Z value is greater than the existing Z value on the buffer, the new pixel is calculated and drawn
        if(drawData.zBuf[x][y] == 0 ||
        newZ > drawData.zBuf[x][y]){ //newZ > zBuf.getRGB(x, y) ||
            drawData.zBuf[x][y] = newZ;
            // project result
            Color pixColor;
            if(texture.isSolid()){
                pixColor = texture.getColor(ang);
            } else {
                throw new RuntimeException("Textures are not supported");
            }
            if(drawData.drawZBuffer){
                drawData.drawImg[x][y] = Color.getHSBColor((float)newZ/2147483648f + 0.5f, 1, 1).getRGB();
            } else{
                drawData.drawImg[x][y] = pixColor.getRGB();
            }
        }
    }
}