Home Perspective - Orthogonal Projection WebGL
Reply: 0

Perspective - Orthogonal Projection WebGL

user52843
1#
user52843 Published in September 19, 2018, 9:08 am

I need to complete a task where it is asked to me to build a rotating cube and to add it some functions. I had no problem to rotate , translate and scale it. Then I had to to apply a orthogonal projection and that's ok , it works.

Now the next task is to add a button that switches orthogonal/perspective projection and to use the same slider to che modify near and far plane both in perspective and orthogonal view. I start the program with orthogonal projection and it works , the problem is that if I switch to perspective the field of view is too big and using the slider I can see only a part of the rotating cube.

Probably I'm using not appropriate parameters. Here is the code :

HTML

<!DOCTYPE html>
<html>

<button id = "ButtonX">Rotate X</button>
<button id = "ButtonY">Rotate Y</button>
<button id = "ButtonZ">Rotate Z</button>
<button id = "ButtonT">Toggle Rotation</button>
<button id="Direction">Change Direction</button>
<button id="OrthoPersp">Change Ortho/Persp</button>


<div>Traslation on X -1 <input id="slideX" type="range"
    min="-1" max="1" step="0.1" value="0" />
    1 </div>

<div>Traslation on Y -1 <input id="slideY" type="range"
    min="-1" max="1" step="0.1" value="0" />
    1 </div>

<div>Traslation on Z -1 <input id="slideZ" type="range"
    min="-1" max="1" step="0.1" value="0" />
    1 </div>

<div>Scaling on X -1 <input id="ScalingX" type="range"
    min="0" max="1" step="0.1" value="0" />
    1 </div>
<div>Scaling on Y -1 <input id="ScalingY" type="range"
    min="0" max="1" step="0.1" value="0" />
    1 </div>
<div>Scaling on Z -1 <input id="ScalingZ" type="range"
    min="0" max="1" step="0.1" value="0" />
    1 </div>
<div>
    Ortho Increase
    <input id="depthSlider" type="range"
    min="0.5" max="10" step="0.1" value ="2" />
    Decrease
</div>







<script id="vertex-shader" type="x-shader/x-vertex">

attribute  vec4 vPosition;
attribute  vec4 vColor;

varying vec4 fColor;

//uniform vec3 theta;

// Point 2 -> Move the matrices
// Per spostare le matrici le abbiamo dovuto dichiarare nel file GLSL come uniform
// le matrici rx ry e rz sono rispettivamente le matrici di rotazione sugli assi
uniform mat4 rx;
uniform mat4 ry;
uniform mat4 rz;

// Points 3 -> Traslation Matrix
uniform mat4 traslation;
// Points 3 -> Scaling Matrix
uniform mat4 scaling;

//Point 4 -> MV and P matrices
uniform mat4 modelView;
uniform mat4 projection;

void main()
{
    // Compute the sines and cosines of theta for each of
    //   the three axes in one computation.
    //vec3 angles = radians( theta );
    //vec3 c = cos( angles );
    //vec3 s = sin( angles );

    // Remember: the matrices are column-major
    /*
    mat4 rx = mat4( 1.0,  0.0,  0.0, 0.0,
            0.0,  c.x,  s.x, 0.0,
            0.0, -s.x,  c.x, 0.0,
            0.0,  0.0,  0.0, 1.0 );

    mat4 ry = mat4( c.y, 0.0, -s.y, 0.0,
            0.0, 1.0,  0.0, 0.0,
            s.y, 0.0,  c.y, 0.0,
            0.0, 0.0,  0.0, 1.0 );


    mat4 rz = mat4( c.z, s.z, 0.0, 0.0,
            -s.z,  c.z, 0.0, 0.0,
            0.0,  0.0, 1.0, 0.0,
            0.0,  0.0, 0.0, 1.0 );
     */

    fColor = vColor;
    //gl_Position = scaling *rz * ry * rx * traslation * vPosition ;  // ORDINE : scaling -> rotazione -> traslation

    gl_Position = projection*modelView*scaling *rz * ry * rx * traslation *vPosition ;
    gl_Position.z = -gl_Position.z;

}
</script>

<script id="fragment-shader" type="x-shader/x-fragment">

precision mediump float;

varying vec4 fColor;

void
main()
{
    gl_FragColor = fColor;

}
</script>

<script type="text/javascript" src="../Common/webgl-utils.js"></script>
<script type="text/javascript" src="../Common/initShaders.js"></script>
<script type="text/javascript" src="../Common/MV.js"></script>
<script type="text/javascript" src="Homework1.js"></script>



<body>
<canvas id="gl-canvas" width="1024" height="1024">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>
</body>
</html>

JS

"use strict";

var canvas;
var gl;

var numVertices  = 36;

var numChecks = 8;

var program;

var c;

var flag = true;

var direction = true;

var rx;
var ry;
var rz;
var traslation_loc;
var tx = 0 ;
var ty = 0;
var tz = 0;
var scaling_loc;
var sx = 1.0;
var sy = 1.0;
var sz = 1.0;

var pointsArray = [];
var colorsArray = [];


//Point 4
var near = -1;
var far = 1;
var radius = 1.0;
var theta  = 0.0;
var phi    = 0.0;
var dr = 5.0 * Math.PI/180.0;

var left = -1.0;
var right = 1.0;
var ytop = 1.0;
var bottom = -1.0;

var mvMatrix, pMatrix;
var modelView, projection;
var eye;

const at = vec3(0.0, 0.0, 0.0);
const up = vec3(0.0, 1.0, 0.0);

var eye = vec3(0.02, 0.02, 0.02);
//

//Point 5
var fovy = 45.0;
var aspect;
var orthoBool = true;
//


var vertices = [
    vec4( -0.5, -0.5,  0.5, 1.0 ),
    vec4( -0.5,  0.5,  0.5, 1.0 ),
    vec4( 0.5,  0.5,  0.5, 1.0 ),
    vec4( 0.5, -0.5,  0.5, 1.0 ),
    vec4( -0.5, -0.5, -0.5, 1.0 ),
    vec4( -0.5,  0.5, -0.5, 1.0 ),
    vec4( 0.5,  0.5, -0.5, 1.0 ),
    vec4( 0.5, -0.5, -0.5, 1.0 )
];

var vertexColors = [
    vec4( 0.0, 0.0, 0.0, 1.0 ),  // black
    vec4( 1.0, 0.0, 0.0, 1.0 ),  // red
    vec4( 1.0, 1.0, 0.0, 1.0 ),  // yellow
    vec4( 0.0, 1.0, 0.0, 1.0 ),  // green
    vec4( 0.0, 0.0, 1.0, 1.0 ),  // blue
    vec4( 1.0, 0.0, 1.0, 1.0 ),  // magenta
    vec4( 0.0, 1.0, 1.0, 1.0 ),  // white
    vec4( 0.0, 1.0, 1.0, 1.0 )   // cyan
];

var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = xAxis;

var theta = [45.0, 45.0, 45.0];

//var thetaLoc;






function quad(a, b, c, d) {
     pointsArray.push(vertices[a]);
     colorsArray.push(vertexColors[a]);

     pointsArray.push(vertices[b]);
     colorsArray.push(vertexColors[a]);

     pointsArray.push(vertices[c]);
     colorsArray.push(vertexColors[a]);

     pointsArray.push(vertices[a]);
     colorsArray.push(vertexColors[a]);

     pointsArray.push(vertices[c]);
     colorsArray.push(vertexColors[a]);

     pointsArray.push(vertices[d]);
     colorsArray.push(vertexColors[a]);
}

function colorCube()
{
    quad( 1, 0, 3, 2 );
    quad( 2, 3, 7, 6 );
    quad( 3, 0, 4, 7 );
    quad( 6, 5, 1, 2 );
    quad( 4, 5, 6, 7 );
    quad( 5, 4, 0, 1 );
}


window.onload = function init() {

    canvas = document.getElementById( "gl-canvas" );

    gl = WebGLUtils.setupWebGL( canvas );
    if ( !gl ) { alert( "WebGL isn't available" ); }

    gl.viewport( 0, 0, canvas.width, canvas.height );

    // Point 5 -> define aspect
    aspect =  canvas.width/canvas.height;


    gl.clearColor( 1.0, 1.0, 1.0, 1.0 );

    gl.enable(gl.DEPTH_TEST);

    //
    //  Load shaders and initialize attribute buffers
    //
    program = initShaders( gl, "vertex-shader", "fragment-shader" );


    gl.useProgram( program );

    colorCube();




    var cBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
    gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );

    var vColor = gl.getAttribLocation( program, "vColor" );
    gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vColor );

    var vBuffer = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer);
    gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );

    var vPosition = gl.getAttribLocation( program, "vPosition" );
    gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );
    gl.enableVertexAttribArray( vPosition );

    // Possiamo commentare quello che riguarda il theta per il punto 2
    //thetaLoc = gl.getUniformLocation(program, "theta");

    // Point 2 - Rotation

    //X AXIS

    rx = gl.getUniformLocation(program, "rx");


    //Y AXIS

    ry = gl.getUniformLocation(program, "ry");



    //Z AXIS

     rz = gl.getUniformLocation(program, "rz");


    // Traslation Matrix

    traslation_loc = gl.getUniformLocation(program , "traslation");

    // Scaling Matrix

    scaling_loc = gl.getUniformLocation(program , "scaling");

    // Projection and Model matrix
    modelView = gl.getUniformLocation( program, "modelView" );
    projection = gl.getUniformLocation( program, "projection" );





    //**************


 document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
 document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
 document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
 document.getElementById("ButtonT").onclick = function(){flag = !flag;};
 document.getElementById("Direction").onclick = function() { direction = !direction;};
 document.getElementById( "slideX" ).oninput = function(){ tx = parseFloat(event.target.value,10); };
 document.getElementById( "slideY" ).oninput = function(){ ty = parseFloat(event.target.value,10); };
 document.getElementById( "slideZ" ).oninput = function(){ tz = parseFloat(event.target.value,10); };
 document.getElementById( "ScalingX" ).oninput = function(){ sx = parseFloat(event.target.value,10); };
 document.getElementById( "ScalingY" ).oninput = function(){ sy = parseFloat(event.target.value,10); };
 document.getElementById( "ScalingZ" ).oninput = function(){ sz = parseFloat(event.target.value,10); };
 // Point 5
 document.getElementById("OrthoPersp").onclick = function(){orthoBool = !orthoBool;};

 // Point 4

    // per documentazine leggi la parte sotto il codice a pag 244 con spiegazione sul clip out
    // occhio che qua accorcia sia il piano vicino che quello lontano , se commentassi riga 225 o 226 , e accorcerei solo uno


    document.getElementById("depthSlider").onchange = function() {
        far = event.srcElement.value/2;
        near = -event.srcElement.value/2;
    };

    render();
}








var render = function() {
    gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);


    // Point 4
    //*************************************
    //eye = vec3(radius*Math.sin(phi), radius*Math.sin(theta),
              // radius*Math.cos(phi)); RIMANE COMMENTATO

    //mvMatrix = lookAt(eye, at , up);
    //pMatrix = ortho(left, right, bottom, ytop, near, far);

    //gl.uniformMatrix4fv( modelView, false, flatten(mvMatrix) );
    //gl.uniformMatrix4fv( projection, false, flatten(pMatrix) );


    //*************************************



    //Point 5
    //*************************************
    mvMatrix = lookAt(eye, at , up);

    if (orthoBool) {
        pMatrix = ortho(left, right, bottom, ytop, near, far); }
    else {

        pMatrix=perspective(fovy , aspect , near , far); }

    gl.uniformMatrix4fv( modelView, false, flatten(mvMatrix) );
    gl.uniformMatrix4fv( projection, false, flatten(pMatrix) );


    //*************************************


    // Point 3 -> Scaling

    var scaling = [sx , 0.0 , 0.0 , 0.0,
                   0.0  , sy, 0.0 , 0.0,
                   0.0 , 0.0 , sz , 0.0,
                   0.0 , 0.0 , 0.0 , 1];
    gl.uniformMatrix4fv(scaling_loc,false,scaling);


    // ****************************************
    //X AXIS - Point 2
    var theta_x_degree  = theta[0];
    var theta_x_radians = theta_x_degree * Math.PI / 180;
    var s_x = Math.sin(theta_x_radians);
    var c_x = Math.cos(theta_x_radians);
    var rx_loc = [ 1.0,  0.0,  0.0, 0.0,
                  0.0,  c_x,  s_x, 0.0,
                  0.0, -s_x,  c_x, 0.0,
                  0.0,  0.0,  0.0, 1.0 ];
    gl.uniformMatrix4fv(rx, false, rx_loc);

    //Y AXIS - Point 2
    var theta_y_degree  = theta[1];
    var theta_y_radians = theta_y_degree * Math.PI / 180;
    var s_y = Math.sin(theta_y_radians);
    var c_y = Math.cos(theta_y_radians);
    var ry_loc = [ c_y, 0.0, -s_y, 0.0,
                  0.0, 1.0,  0.0, 0.0,
                  s_y, 0.0,  c_y, 0.0,
                  0.0, 0.0,  0.0, 1.0 ];
    gl.uniformMatrix4fv(ry, false, ry_loc);


    //Z AXIS - Point 2
    var theta_z_degree  = theta[2];
    var theta_z_radians = theta_z_degree * Math.PI / 180;
    var s_z = Math.sin(theta_z_radians);
    var c_z = Math.cos(theta_z_radians);
    var rz_loc = [ c_z, s_z, 0.0, 0.0,
                  -s_z,  c_z, 0.0, 0.0,
                  0.0,  0.0, 1.0, 0.0,
                  0.0,  0.0, 0.0, 1.0  ];
    gl.uniformMatrix4fv(rz, false, rz_loc);

    // ****************************************

    // Point 3 -> Traslation

    var traslation = [1.0 , 0.0 , 0.0 , 0.0,
                      0.0 , 1.0 , 0.0 , 0.0,
                      0.0 , 0.0 , 1.0 , 0.0,
                       tx , ty , tz , 1.0];

    gl.uniformMatrix4fv(traslation_loc,false,traslation);


    // ****************************************




    // ****************************************

    // Point 1 --> Change and Toggle Rotation
    if((direction)&&(!flag)) theta[axis] += -2.0;
    if((!direction)&&(!flag)) theta[axis] += +2.0;

    if(!direction) {theta[axis] += -2.0; }
    if(direction) {theta[axis] += 2.0 ; }

    // ****************************************

    //gl.uniform3fv(thetaLoc, theta);
    gl.drawArrays( gl.TRIANGLES, 0, numVertices );
    requestAnimFrame(render);
}
share|improve this question

active oldest votes

Your Answer

StackExchange.ifUsing("editor", function () { StackExchange.using("externalEditor", function () { StackExchange.using("snippets", function () { StackExchange.snippets.init(); }); }); }, "code-snippets"); StackExchange.ready(function() { var channelOptions = { tags: "".split(" "), id: "1" }; initTagRenderer("".split(" "), "".split(" "), channelOptions); StackExchange.using("externalEditor", function() { // Have to fire editor after snippets, if snippets enabled if (StackExchange.settings.snippets.snippetsEnabled) { StackExchange.using("snippets", function() { createEditor(); }); } else { createEditor(); } }); function createEditor() { StackExchange.prepareEditor({ heartbeatType: 'answer', convertImagesToLinks: true, noModals: false, showLowRepImageUploadWarning: true, reputationToPostImages: 10, bindNavPrevention: true, postfix: "", onDemand: true, discardSelector: ".discard-answer" ,immediatelyShowMarkdownHelp:true }); } });
 
StackExchange.ready( function () { StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f49875876%2fperspective-orthogonal-projection-webgl%23new-answer', 'question_page'); } );

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

StackExchange.ready(function(){$.get('/posts/49875876/ivc/c4f0');});
StackExchange.ready(function () { StackExchange.responsiveness.addSwitcher(); }) (function(i, s, o, g, r, a, m) { i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function() { (i[r].q = i[r].q || []).push(arguments) }, i[r].l = 1 * new Date(); a = s.createElement(o), m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m); })(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga'); StackExchange.ready(function () { StackExchange.ga.init({ sendTitles: true, tracker: window.ga, trackingCodes: [ 'UA-108242619-1' ] }); StackExchange.ga.setDimension('dimension2', '|html|webgl|projection|'); StackExchange.ga.setDimension('dimension3', 'Questions/Show'); StackExchange.ga.trackPageView(); }); /**/ var _qevents = _qevents || [], _comscore = _comscore || []; (function() { var ssl = 'https:' == document.location.protocol, s = document.getElementsByTagName('script')[0], qc = document.createElement('script'); qc.async = true; qc.src = (ssl ? 'https://secure' : 'http://edge') + '.quantserve.com/quant.js'; s.parentNode.insertBefore(qc, s); _qevents.push({ qacct: "p-c1rF4kxgLUzNc" }); /**/ var sc = document.createElement('script'); sc.async = true; sc.src = (ssl ? 'https://sb' : 'http://b') + '.scorecardresearch.com/beacon.js'; s.parentNode.insertBefore(sc, s); _comscore.push({ c1: "2", c2: "17440561" }); })();
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.392575 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO