<p>I'm trying to figure out how to setup a 3D camera in WebGL. This is my first swing at 3D so a lot of the matrix stuff is new to me.</p>
<h2>Code</h2>
<p>The code can be reviewed in this CodePen: <a href="https://codepen.io/Candleout/pen/poxMLPB" rel="nofollow noreferrer">https://codepen.io/Candleout/pen/poxMLPB</a></p>
<p>For some reason, the scene is sometimes empty (white) when you load the CodePen. If this happens, you can fix it by simply running the code again. Just make any type of update to the code and it will work.</p>
<h2>Goal</h2>
<ul>
<li>Full control of camera movement</li>
<li>A rendered model should be able to visibly move in all three dimensions</li>
<li>As with orthographic 3D, moving an object to a different position should not affect its shape. Every instance of the same object should look identical regardless of position.</li>
</ul>
<h2>Explanation</h2>
<p><a href="https://i.sstatic.net/7qL1Y.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/7qL1Y.png" alt="Setting up a 3D camera" /></a></p>
<p>In the scene, Z (blue) is the vertical axis (<code>up = [0, 0, -1]</code>), while X (red) and Y (green) represents the horizontal plane. The reason for this is that my scene is actually a map with a real world coordinate system. In this coordinate system, Z represents elevation, X represents East-West and and Y represents North-South. Z increases with elevation, X increases to the East and Y increases to the North.</p>
<p>Also, the scene is viewed from an angle. The viewing point is located somewhere to the South-East of origo. Because of this, the Y axis is pointing to the upper right instead of straight up. The X axis is pointing to the lower right instead of straight to the right.</p>
<p>You may notice that the camera position and up direction is inverted. I believe this is necessary for the axes to point in the right directions according to my particular requirements. Please let me know if this is not the case.</p>
<h2>Questions</h2>
<ol>
<li>How would you typically move the camera? My guess would be that you work with matrix calculations rather than adjusting <code>cameraPosition</code> and <code>cameraTarget</code> directly.</li>
<li>My first idea was to position the camera straight above the target (<code>cameraTarget = [0, 0, 0]; cameraPosition = [0, 0, distance]; up = [0, 0, -1];</code>) and then add transformations to reposition the camera in relation to that position. However, if I set the camera position to <code>[0, 0, distance]</code> the model disappears. Why is this?</li>
<li>How would you zoom a scene like this? By scaling the scene, or moving the camera? Well, since the scene is orthographic (in the sense that an object maintains its shape regardless of position) moving the camera won't do anything. I guess this means I need to scale the scene?</li>
<li>Let's say you want to change the viewing angle to make the top edge of the hexagon appear completely flat. This can be done by adding a 15 degree Z rotation to the view matrix (<code>viewMatrix = m4.zRotate(viewMatrix, 15 * Math.PI/180)</code>).
<a href="https://i.sstatic.net/81co7.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/81co7.png" alt="Add rotation" /></a></li>
</ol>
<p>Is this a valid approach (is the math correct)? I think the hexagon looks a bit blurry at the top, as if not completely straight. Maybe this has some other explanation.</p>
<ol start="5">
<li>Is there some serious downside to assigning the upward direction to the Z axis? Like, issues relating to mathematics or compability with external resources? I believe the conventional way would be to use the Y axis.</li>
<li>Is it a bad idea to invert the Z axis (<code>up = [0, 0, -1]</code>)? Could it cause issues with depth calculations? I haven't noticed any issues so far.</li>
</ol>
<p>Please let me know if there is some other issue I should be aware of.</p>
<h2>Code breakdown</h2>
<ol>
<li>Create an orthographic projection matrix, to convert between screen space and clip space</li>
</ol>
<pre><code>    let projectionMatrix = m4.orthographic(0, canvas.width, canvas.height, 0, -2000, 2000);
</code></pre>
<p>The orthographic function (the rest of the m4 functions can be found in the CodePen):</p>
<pre><code>orthographic: function(left, right, bottom, top, near, far) {
    return [
      2 / (right - left), 0, 0, 0,
      0, 2 / (top - bottom), 0, 0,
      0, 0, 2 / (far - near), 0,
      (left + right) / (left - right),
      (bottom + top) / (bottom - top),
      (far + near) / (far - near),
      1,
    ]
  }
</code></pre>
<ol start="2">
<li>Create a transformation matrix for the model</li>
</ol>
<pre><code>    let modelMatrix = m4.identityMatrix();
    modelMatrix = m4.translate(modelMatrix, drawInfo.position[0], drawInfo.position[1], drawInfo.position[2])
</code></pre>
<ol start="3">
<li>Create a camera matrix from a lookAt function</li>
</ol>
<pre><code>    let cameraTarget = [0, 0, 0]; // origo
    let cameraPosition = [-1, 1, -1];
    let up = [0, 0, -1];
    let cameraMatrix = m4.lookAt(cameraPosition, cameraTarget, up);
</code></pre>
<ol start="4">
<li>Create view matrix by inverting the camera matrix</li>
</ol>
<pre><code>    let viewMatrix = m4.inverse(cameraMatrix);
</code></pre>
<ol start="5">
<li>Create the view projection matrix by multiplying the projection matrix and the projection matrix</li>
</ol>
<pre><code>    let viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);
</code></pre>
<ol start="6">
<li>Add in the model transformation to create the final matrix that is sent to the vertex shader</li>
</ol>
<pre><code>    const finalMatrix = m4.multiply(viewProjectionMatrix, modelMatrix);
</code></pre>

CC BY-SA 4.0
2023-06-11T12:59:37.013Z
This question is very broad its better to ask multiple different questions. Folks are more willing to answer smaller questions and you get more thorough/complete answers. For example each of the 5 questions could be a single question by themselves.
pmw1234
CC BY-SA 4.0
2023-06-11T17:21:35.003Z
Thanks for the feedback @pmw1234. I'll probably follow your advice and divide it into multiple questions (not directly, but within the next 24 hours or so).
Candleout
CC BY-SA 4.0
2023-06-19T07:26:03.060Z
As pmw1234 already mentioned, we usually prefer a single question per topic here. I understand why it is tempting to "get all your questions answered at once", but it is more likely that people stop reading when they see a lot of text and code. Some might only be able to answer one of your questions and shy away from writing an answer at all because they can't answer the other ones. Additionally, the purpose of this site is to conserve knowledge for others with similar questions. For them, it is hard to find the answers they seek if the relevant question is hidden deep inside a topic.
wychmaster
CC BY-SA 4.0
2023-06-20T11:22:55.810Z
You bring up good points @wychmaster. Been busy this last week but will get back to this ASAP.
Candleout
<3d><webgl><camera>
How to setup a 3D camera
Candleout
# How to setup a 3D camera

(Asked by: username_0 on 2023-06-09)

I'm trying to figure out how to setup a 3D camera in WebGL. This is my first swing at 3D so a lot of the matrix stuff is new to me.

## Code

The code can be reviewed in this CodePen: <https://codepen.io/username_0/pen/poxMLPB>

For some reason, the scene is sometimes empty (white) when you load the CodePen. If this happens, you can fix it by simply running the code again. Just make any type of update to the code and it will work.

## Goal

* Full control of camera movement
* A rendered model should be able to visibly move in all three dimensions
* As with orthographic 3D, moving an object to a different position should not affect its shape. Every instance of the same object should look identical regardless of position.

## Explanation

[![Setting up a 3D camera](https://i.sstatic.net/7qL1Y.png)](https://i.sstatic.net/7qL1Y.png)

In the scene, Z (blue) is the vertical axis (`up = [0, 0, -1]`), while X (red) and Y (green) represents the horizontal plane. The reason for this is that my scene is actually a map with a real world coordinate system. In this coordinate system, Z represents elevation, X represents East-West and and Y represents North-South. Z increases with elevation, X increases to the East and Y increases to the North.

Also, the scene is viewed from an angle. The viewing point is located somewhere to the South-East of origo. Because of this, the Y axis is pointing to the upper right instead of straight up. The X axis is pointing to the lower right instead of straight to the right.

You may notice that the camera position and up direction is inverted. I believe this is necessary for the axes to point in the right directions according to my particular requirements. Please let me know if this is not the case.

## Questions

1. How would you typically move the camera? My guess would be that you work with matrix calculations rather than adjusting `cameraPosition` and `cameraTarget` directly.
2. My first idea was to position the camera straight above the target (`cameraTarget = [0, 0, 0]; cameraPosition = [0, 0, distance]; up = [0, 0, -1];`) and then add transformations to reposition the camera in relation to that position. However, if I set the camera position to `[0, 0, distance]` the model disappears. Why is this?
3. How would you zoom a scene like this? By scaling the scene, or moving the camera? Well, since the scene is orthographic (in the sense that an object maintains its shape regardless of position) moving the camera won't do anything. I guess this means I need to scale the scene?
4. Let's say you want to change the viewing angle to make the top edge of the hexagon appear completely flat. This can be done by adding a 15 degree Z rotation to the view matrix (`viewMatrix = m4.zRotate(viewMatrix, 15 * Math.PI/180)`).
   [![Add rotation](https://i.sstatic.net/81co7.png)](https://i.sstatic.net/81co7.png)

Is this a valid approach (is the math correct)? I think the hexagon looks a bit blurry at the top, as if not completely straight. Maybe this has some other explanation.

5. Is there some serious downside to assigning the upward direction to the Z axis? Like, issues relating to mathematics or compability with external resources? I believe the conventional way would be to use the Y axis.
6. Is it a bad idea to invert the Z axis (`up = [0, 0, -1]`)? Could it cause issues with depth calculations? I haven't noticed any issues so far.

Please let me know if there is some other issue I should be aware of.

## Code breakdown

1. Create an orthographic projection matrix, to convert between screen space and clip space

```
    let projectionMatrix = m4.orthographic(0, canvas.width, canvas.height, 0, -2000, 2000);

```

The orthographic function (the rest of the m4 functions can be found in the CodePen):

```
orthographic: function(left, right, bottom, top, near, far) {
    return [
      2 / (right - left), 0, 0, 0,
      0, 2 / (top - bottom), 0, 0,
      0, 0, 2 / (far - near), 0,
      (left + right) / (left - right),
      (bottom + top) / (bottom - top),
      (far + near) / (far - near),
      1,
    ]
  }

```

2. Create a transformation matrix for the model

```
    let modelMatrix = m4.identityMatrix();
    modelMatrix = m4.translate(modelMatrix, drawInfo.position[0], drawInfo.position[1], drawInfo.position[2])

```

3. Create a camera matrix from a lookAt function

```
    let cameraTarget = [0, 0, 0]; // origo
    let cameraPosition = [-1, 1, -1];
    let up = [0, 0, -1];
    let cameraMatrix = m4.lookAt(cameraPosition, cameraTarget, up);

```

4. Create view matrix by inverting the camera matrix

```
    let viewMatrix = m4.inverse(cameraMatrix);

```

5. Create the view projection matrix by multiplying the projection matrix and the projection matrix

```
    let viewProjectionMatrix = m4.multiply(projectionMatrix, viewMatrix);

```

6. Add in the model transformation to create the final matrix that is sent to the vertex shader

```
    const finalMatrix = m4.multiply(viewProjectionMatrix, modelMatrix);

```

**Tags:** 3d, webgl, camera

> **Comments:**
> **username_1**: This question is very broad its better to ask multiple different questions. Folks are more willing to answer smaller questions and you get more thorough/complete answers. For example each of the 5 questions could be a single question by themselves.  
> **username_0**: Thanks for the feedback @username_1. I'll probably follow your advice and divide it into multiple questions (not directly, but within the next 24 hours or so).  
> **username_2**: As username_1 already mentioned, we usually prefer a single question per topic here. I understand why it is tempting to "get all your questions answered at once", but it is more likely that people stop reading when they see a lot of text and code. Some might only be able to answer one of your questions and shy away from writing an answer at all because they can't answer the other ones. Additionally, the purpose of this site is to conserve knowledge for others with similar questions. For them, it is hard to find the answers they seek if the relevant question is hidden deep inside a topic.  
> **username_0**: You bring up good points @username_2. Been busy this last week but will get back to this ASAP.  

---

## 0 answers

