Custom Java 3D renderer is breaking when implementing a perspective projection

I’m not very experienced with Java or computer graphics, but I thought I’d try and program a rough 3D engine in Java as I’ve been finding APCS pretty fun. I’ve gotten as far as implementing vertices, triangles, face culling, and rotation/translation matrices, but I can’t for the life of me figure out how to do a projection matrix.

I have a 4×4 matrix class:

public class Matrix4 {
   
   double[][] m = new double[4][4];
   
   public Matrix4 (double[][] nm) {
      for (int r = 0; r < nm.length; r++) {
         for (int c = 0; c < nm[r].length; c++) {
            m[r][c] = nm[r][c];
         }
      }
   }

   public Vertex multiplyMatrix(Vertex v) {
   
      Vertex o = new Vertex(0, 0, 0);
      
      o.x = v.x * m[0][0] + v.y * m[1][0] + v.z * m[2][0] + m[3][0];
      o.y = v.x * m[0][1] + v.y * m[1][1] + v.z * m[2][1] + m[3][1];
      o.z = v.x * m[0][2] + v.y * m[1][2] + v.z * m[2][2] + m[3][2];
      double w = v.x * m[0][3] + v.y * m[1][3] + v.z * m[2][3] + m[3][3];
      
      if (w != 0) {
         o.x /= w;
         o.y /= w;
         o.z /= w;
      }
      
      System.out.println(o);
      
      return o;
   }
}  

and using this I have created a projection matrix copied from videos/images I’ve seen online:

private double fNear = 0.1;
private double fFar = 1000;
private double fFOV = 50;
private double fAspectRatio = (double)width/height; 
private double fFOVRad = 1 / Math.tan(Math.toRadians(fFOV / 2));

matProj = new Matrix4(new double[][]{
      {fAspectRatio * fFOVRad,0,                      0,                                   0},
      {0,                     fFOVRad,                0,                                   0},
      {0,                     0,                      (fFar + fNear) / (fFar - fNear),     1},
      {0,                     0,                      (-2 * fFar * fNear) / (fFar - fNear),0}});

To render the triangles, I’m going through the list of triangles and one-by-one multiplying their vertices by this projection matrix, and then printing them to the screen:

public void paintComponent(Graphics g) {
      super.paintComponent(g);
      
      for (int i = 0; i < triangleList.size(); i++) {
         
         Triangle triangle = new Triangle(triangleList.get(i).v1, triangleList.get(i).v2, triangleList.get(i).v3);
            
         if (!triangle.cullTriangle(cameraVector)) {
            g.setColor(colorList.get(i));
            
             triangle.v1 = matProj.multiplyMatrix(triangle.v1);
             triangle.v2 = matProj.multiplyMatrix(triangle.v2);
             triangle.v3 = matProj.multiplyMatrix(triangle.v3);
        
            int[] vX = {width / 2 + (int)(triangle.v1.x), 
                        width / 2 + (int)(triangle.v2.x), 
                        width / 2 + (int)(triangle.v3.x)};
                        
            int[] vY = {height / 2 - (int)(triangle.v1.z), 
                        height / 2 - (int)(triangle.v2.z),
                        height / 2 - (int)(triangle.v3.z)};
         
            g.fillPolygon(vX, vY, 3);
         }
      }
   }

However, this isn’t working at all, and it’s just fragmenting the shape into thin strips and glitches. If I just comment out the three matProj.multiplyMatrix lines, everything works as it should but without perspective. I’m sure this is a really stupid issue, but I’m new to this type of stuff and I’m really stumped right now, so any help would be great!

Here is my full main class if needed:

import java.io.*;
import java.lang.Math;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.ArrayList;
import java.awt.PointerInfo;

public class main extends JPanel implements ActionListener, MouseListener {

   private Timer timer;
   public int time;
   public JFrame frame;
   public int width = 500, height = 500;
   private double[] mouseDown;
   private double[] mouseMoved;
   private boolean isRotating = false;
   private double[] viewVertex = {0, 0, 0};
   private double[] worldPos = {0, 0, 0};
   private Point pointer; 
   private boolean inTranslateMode = false; //movement modes
   
   private double fNear = 0.1;
   private double fFar = 1000;
   private double fFOV = 50;
   private double fAspectRatio = (double)width/height; 
   private double fFOVRad = 1 / Math.tan(Math.toRadians(fFOV / 2));
 
   ArrayList<Triangle> triangleList; //List of triangles
   ArrayList<Color> colorList; //List of polygon colors
   
   private Vertex cameraVector; //Vector of the player/camera
   private double fov = Math.toRadians(60); // Field of view in radians
   private double near = 1; // Near clipping plane distance
   private double far = 1000;
   
   private Matrix4 matProj;

   public main () {
   
      mouseDown = new double[2];
      mouseMoved = new double[2];
      triangleList = new ArrayList<>();
      colorList = new ArrayList<>();
      
      //Player vector
      cameraVector = new Vertex(0, 1, 0);
      
      Cube cube1 = new Cube(50, 1, 1, 1);
      cube1.add(triangleList, colorList);

      for (Triangle t : triangleList) {
         t.translate(worldPos[0], worldPos[1], worldPos[2]);
      }

      //set up JFrame
      frame = new JFrame("3D Engine");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLayout(new FlowLayout());
      setPreferredSize(new Dimension(width, height));
      setBackground(Color.WHITE);
      
      frame.add(this);
      addMouseListener(this);
      
      frame.pack();
      frame.setVisible(true);
      setFocusable(true);
      
      timer = new Timer(10, this);
      timer.start();
      time = 0;
      
      
      matProj = new Matrix4(new double[][]{
      {fAspectRatio * fFOVRad,0,                      0,                                   0},
      {0,                     fFOVRad,                0,                                   0},
      {0,                     0,                      (fFar + fNear) / (fFar - fNear),     1},
      {0,                     0,                      (-2 * fFar * fNear) / (fFar - fNear),0}});
      
      
      addKeyListener(new KeyAdapter() {
          public void keyPressed(KeyEvent e) {
              if (e.getKeyCode() == KeyEvent.VK_RIGHT) {
                 if (inTranslateMode) {
                    for (Triangle t : triangleList) {
                       t.translate(5, 0, 0);
                    }
                 } else {
                    for (Triangle t : triangleList) {
                       t.rotateZ(10);
                    }
                 }
              } else if (e.getKeyCode() == KeyEvent.VK_LEFT) {
                 if (inTranslateMode) {
                    for (Triangle t : triangleList) {
                       t.translate(-5, 0, 0);
                    }
                 } else {
                    for (Triangle t : triangleList) {
                       t.rotateZ(-10);
                    }
                 }
              } else if (e.getKeyCode() == KeyEvent.VK_UP) {
                 if (inTranslateMode) {
                    for (Triangle t : triangleList) {
                       t.translate(0, 5, 0);
                    }
                 } else {
                    for (Triangle t : triangleList) {
                       t.rotateX(10);
                    }
                 }
              } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
                 if (inTranslateMode) {
                    for (Triangle t : triangleList) {
                       t.translate(0, -5, 0);
                    }
                 } else {
                    for (Triangle t : triangleList) {
                       t.rotateX(-10);
                    }
                 }
              } else if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                 inTranslateMode = !inTranslateMode;
              }
          }
      });
   }

   public void actionPerformed(ActionEvent e) {
      repaint();
      
      time++;
      
      pointer = MouseInfo.getPointerInfo().getLocation();
      
      if (isRotating) {
      
         mouseMoved[0] = pointer.x - mouseDown[0];
         mouseMoved[1] = pointer.y - mouseDown[1];
      
         for (Triangle t : triangleList) {
            t.rotateX(mouseMoved[0] / 5);
         }
         
         mouseDown[0] = pointer.x;
         mouseDown[1] = pointer.y;
      }
   }

   public void paintComponent(Graphics g) {
      super.paintComponent(g);
      
      for (int i = 0; i < triangleList.size(); i++) {
         
         Triangle triangle = new Triangle(triangleList.get(i).v1, triangleList.get(i).v2, triangleList.get(i).v3);
            
         if (!triangle.cullTriangle(cameraVector)) {
            g.setColor(colorList.get(i));
            
             triangle.v1 = matProj.multiplyMatrix(triangle.v1);
             triangle.v2 = matProj.multiplyMatrix(triangle.v2);
             triangle.v3 = matProj.multiplyMatrix(triangle.v3);
        
            int[] vX = {width / 2 + (int)(triangle.v1.x), 
                        width / 2 + (int)(triangle.v2.x), 
                        width / 2 + (int)(triangle.v3.x)};
                        
            int[] vY = {height / 2 - (int)(triangle.v1.z), 
                        height / 2 - (int)(triangle.v2.z),
                        height / 2 - (int)(triangle.v3.z)};
         
            g.fillPolygon(vX, vY, 3);
         }
      }
   }
   
   public void mouseClicked(MouseEvent e) {}
   public void mousePressed(MouseEvent e) {
      isRotating = true;
      mouseDown[0] = pointer.x;
      mouseDown[1] = pointer.y;
   }
   public void mouseReleased(MouseEvent e) {
      isRotating = false;
   }
   
   public void mouseEntered(MouseEvent e) {}
   public void mouseExited(MouseEvent e) {}

   public static void main (String[] args) {
      new main();
   }
}

I logged the vertex values within the matrix multiply method, and they are incorrect, so I assume it’s an issue with the multiplication if that helps. I also don’t know if I’m drawing them onto the screen correctly since Java uses a weird coordinate system (at least to me).

What I’m expecting is for shapes to be smaller when further away, and to be warped correctly into the screen to show depth. What happened instead is a bunch of this:

3d rendered cube fragments

and without the projection matrix multiplication, it looks like this:

Very minimal but cube-like cube

New contributor

Ryan Jo is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật