Skip to main content

Issues Creating a 3D Renderer in JavaScript

I am trying to make my own 3D renderer in JavaScript using raycasting, but despite checking over the math and the code countless times, it still does not seem to be working. I've tried everything I possibly could to get this thing to work and it won't, so I'm hoping someone else can figure it out.

My code runs an Update method every frame, increasing the yaw (Camera.Rot.Yaw) by 0.1 radians every iteration, but it ends up looking weird and unrealistic, and I can't figure out why. Sorry if it's confusing and long, I can't really think of a way to make a minimal reproducible example of this. This is the Update method:

  Update(Canvas, Ctx, Map, Camera) {
    var id = Ctx.getImageData(0, 0, Canvas.width, Canvas.height);
    var Pixels = id.data;
    //Distance of projection plane from camera
    //It should be behind I think
    var PlaneDist = 64;
    //Divides the second slopes by this so each ray goes a shorter
    //distance each iteration, effectively increasing quality
    var Quality = 160;
    //The midpoint of the projection plane for each coordinate
    var MidX =
      Camera.Pos.X +
      PlaneDist * Math.cos(Camera.Rot.Pitch) * Math.cos(Camera.Rot.Yaw);
    var MidY = Camera.Pos.Y + PlaneDist * Math.sin(Camera.Rot.Pitch);
    var MidZ =
      Camera.Pos.Z +
      PlaneDist * Math.cos(Camera.Rot.Pitch) * Math.sin(Camera.Rot.Yaw);
    //Slopes to get to other points on the projection plane
    var SlopeX =
      Math.sin(Camera.Rot.Yaw) +
      (Canvas.height / Canvas.width) *
        Math.cos(Camera.Rot.Yaw) *
        Math.sin(Camera.Rot.Pitch);
    var SlopeY = -Math.cos(Camera.Rot.Pitch);
    var SlopeZ =
      Math.cos(Camera.Rot.Yaw) +
      (Canvas.height / Canvas.width) *
        Math.sin(Camera.Rot.Yaw) *
        Math.sin(Camera.Rot.Pitch);
    //Loops for every point on the projection plane
    for (let i = 0; i < Canvas.height; i++) {
      for (let j = 0; j < Canvas.width; j++) {
        let NewX = Camera.Pos.X;
        let NewY = Camera.Pos.Y;
        let NewZ = Camera.Pos.Z;
        //Slopes for the actual ray to follow, just the distance between
        //the plane point and the camera divided by quality
        let SlopeX2 = (Camera.Pos.X-(MidX - SlopeX * (j - Canvas.width / 2)))/ Quality;
        let SlopeY2 = (Camera.Pos.Y-(MidY - SlopeY * (i - Canvas.height / 2))) / Quality;
        let SlopeZ2 = (Camera.Pos.Z-(MidZ - SlopeZ * (j - Canvas.width / 2)))/ Quality;
        //Ray's current map position, divides the map into a 16x32x16
        //list of blocks (map initialization shown elsewhere)
        let MapPos =
          Map.MData[0][Math.floor(NewX / 16) + 2][Math.floor(NewY / 16)][
            Math.floor(NewZ / 16)
          ];
        //Iterates until ray either hits a block with max opacity, or
        //hits the boundary of the map
        while (
          MapPos[3] !== 255 &&
          NewX + SlopeX2 < 256 &&
          NewY + SlopeY2 < 512 &&
          NewZ + SlopeZ2 < 256 &&
          NewX + SlopeX2 >= 0 &&
          NewY + SlopeY2 >= 0 &&
          NewZ + SlopeZ2 >= 0
        ) {
          //Advances ray's current position according to slopes
          NewX += SlopeX2;
          NewY += SlopeY2;
          NewZ += SlopeZ2;
          MapPos =
            Map.MData[0][Math.floor(NewX / 16) + 2][Math.floor(NewY / 16)][
              Math.floor(NewZ / 16)
            ];
        }
        //Sets pixel on screen to the color of the block the ray hit
        //or just white (opacity 0) if it hit the boundary
        Pixels[(i * id.width + j) * 4] = MapPos[0];
        Pixels[(i * id.width + j) * 4 + 1] = MapPos[1];
        Pixels[(i * id.width + j) * 4 + 2] = MapPos[2];
        Pixels[(i * id.width + j) * 4 + 3] = MapPos[3];
      }
    }
    //Displays the final image
    Ctx.putImageData(id, 0, 0);
  }

The map initialization (CreateChunk) looks like this:

  constructor() {
    this.MData = [];
  }
  CreateChunk(X, Y) {
    let Chunk = [X, Y];
    for (let x = 0; x < 16; x++) {
      let Plane = [];
      for (let y = 0; y < 32; y++) {
        let Row = [];
        for (let z = 0; z < 16; z++) {
          //Colors are just to help tell which pixels are at what coordinates
          if (y < 8) Row.push([x * 15, y * 7, z * 15, 255]);
          else Row.push([0, 0, 0, 0]);
        }
        Plane.push(Row);
      }
      Chunk.push(Plane);
    }
    this.MData.push(Chunk);
  }

I'm hoping it's just some coding mistake I've made, but despite my countless checks it may be the trigonometry that's wrong.

Via Active questions tagged javascript - Stack Overflow https://ift.tt/14HfyEx

Comments

Popular posts from this blog

ValueError: X has 10 features, but LinearRegression is expecting 1 features as input

So, I am trying to predict the model but its throwing error like it has 10 features but it expacts only 1. So I am confused can anyone help me with it? more importantly its not working for me when my friend runs it. It works perfectly fine dose anyone know the reason about it? cv = KFold(n_splits = 10) all_loss = [] for i in range(9): # 1st for loop over polynomial orders poly_order = i X_train = make_polynomial(x, poly_order) loss_at_order = [] # initiate a set to collect loss for CV for train_index, test_index in cv.split(X_train): print('TRAIN:', train_index, 'TEST:', test_index) X_train_cv, X_test_cv = X_train[train_index], X_test[test_index] t_train_cv, t_test_cv = t[train_index], t[test_index] reg.fit(X_train_cv, t_train_cv) loss_at_order.append(np.mean((t_test_cv - reg.predict(X_test_cv))**2)) # collect loss at fold all_loss.append(np.mean(loss_at_order)) # collect loss at order plt.plot(np.log(al...

Sorting large arrays of big numeric stings

I was solving bigSorting() problem from hackerrank: Consider an array of numeric strings where each string is a positive number with anywhere from to digits. Sort the array's elements in non-decreasing, or ascending order of their integer values and return the sorted array. I know it works as follows: def bigSorting(unsorted): return sorted(unsorted, key=int) But I didnt guess this approach earlier. Initially I tried below: def bigSorting(unsorted): int_unsorted = [int(i) for i in unsorted] int_sorted = sorted(int_unsorted) return [str(i) for i in int_sorted] However, for some of the test cases, it was showing time limit exceeded. Why is it so? PS: I dont know exactly what those test cases were as hacker rank does not reveal all test cases. source https://stackoverflow.com/questions/73007397/sorting-large-arrays-of-big-numeric-stings

How to load Javascript with imported modules?

I am trying to import modules from tensorflowjs, and below is my code. test.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title </head> <body> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script> <script type="module" src="./test.js"></script> </body> </html> test.js import * as tf from "./node_modules/@tensorflow/tfjs"; import {loadGraphModel} from "./node_modules/@tensorflow/tfjs-converter"; const MODEL_URL = './model.json'; const model = await loadGraphModel(MODEL_URL); const cat = document.getElementById('cat'); model.execute(tf.browser.fromPixels(cat)); Besides, I run the server using python -m http.server in my command prompt(Windows 10), and this is the error prompt in the console log of my browser: Failed to loa...