Пример #1
0
  constructor(main, xSym) {
    this._mesh = null; // mesh
    this._main = main; // the camera
    this._pickedFace = -1; // face picked
    this._pickedVertices = []; // vertices selected
    this._interPoint = [0.0, 0.0, 0.0]; // intersection point (mesh local space)
    this._rLocal2 = 0.0; // radius of the selection area (local/object space)
    this._rWorld2 = 0.0; // radius of the selection area (world space)
    this._eyeDir = [0.0, 0.0, 0.0]; // eye direction

    this._xSym = !!xSym;

    this._pickedNormal = [0.0, 0.0, 0.0];
    // alpha stuffs
    this._alphaOrigin = [0.0, 0.0, 0.0];
    this._alphaSide = 0.0;
    this._alphaLookAt = mat4.create();
    this._alpha = null;
  }
Пример #2
0
    getViewMatrix(): Mat4 {
        const position = glm.vec3.create();
        const translation = glm.mat4.create();
        
        glm.vec3.scale(position,this._position,-1.0);

        return glm.mat4.clone(
            glm.mat4.mul(
                this._viewMatrix,
                glm.mat4.fromQuat(glm.mat4.create(),this._rotation),
                glm.mat4.fromTranslation(translation,position),
            )
        );
    }
export function makeProjectionMatrixFromMercatorParams({
  width,
  height,
  pitch,
  altitude,
  farZMultiplier = 10
}) {
  const {nearZ, farZ} = getClippingPlanes({altitude, pitch});
  const fov = getFov({height, altitude});

  const projectionMatrix = mat4.perspective(
    createMat4(),
    fov,              // fov in radians
    width / height,   // aspect ratio
    nearZ,            // near plane
    farZ * farZMultiplier // far plane
  );

  return projectionMatrix;
}
Пример #4
0
	project2: function(position, out) {
		// var near = 0;
		// var far = 100;

		var halfWidth = this.width/2;
		var halfHeight = this.height/2;
		// var aspect = this.width/this.height;

		this.tmpVec[0] = position.x;
		this.tmpVec[1] = position.y;
		this.tmpVec[2] = position.z;


		mat4.multiply(this.transformMatrix, this.viewMatrix, this.projectionMatrix);

		vec3.transformMat4( this.tmpVec2, this.tmpVec, this.transformMatrix );

		out.x = this.tmpVec2[0] * this.width + this.width/2;
		out.y = -this.tmpVec2[1] * this.height + this.height/2;
		out.z = this.tmpVec2[2];
	},
Пример #5
0
  updateAlpha(keepOrigin) {
    var dir = _TMP_V1;
    var nor = _TMP_V2;

    var radius = Math.sqrt(this._rLocal2);
    this._alphaSide = radius * Math.SQRT1_2;

    vec3.sub(dir, this._interPoint, this._alphaOrigin);
    if (vec3.len(dir) === 0) return;
    vec3.normalize(dir, dir);

    var normal = this._pickedNormal;
    vec3.scaleAndAdd(dir, dir, normal, -vec3.dot(dir, normal));
    vec3.normalize(dir, dir);

    if (!keepOrigin)
      vec3.copy(this._alphaOrigin, this._interPoint);

    vec3.scaleAndAdd(nor, this._alphaOrigin, normal, radius);
    mat4.lookAt(this._alphaLookAt, this._alphaOrigin, nor, dir);
  }
Пример #6
0
/*
 * Returns a matrix for converting from the correct label coordinate space to gl coords.
 */
function getGlCoordMatrix(posMatrix: mat4,
                          pitchWithMap: boolean,
                          rotateWithMap: boolean,
                          transform: Transform,
                          pixelsToTileUnits: number) {
    const m = mat4.identity(new Float32Array(16));
    if (pitchWithMap) {
        mat4.multiply(m, m, posMatrix);
        mat4.scale(m, m, [pixelsToTileUnits, pixelsToTileUnits, 1]);
        if (!rotateWithMap) {
            mat4.rotateZ(m, m, -transform.angle);
        }
    } else {
        mat4.scale(m, m, [1, -1, 1]);
        mat4.translate(m, m, [-1, -1, 0]);
        mat4.scale(m, m, [2 / transform.width, 2 / transform.height, 1]);
    }
    return m;
}
Пример #7
0
  /**
   *
   */
  constructor() {
    // Rendered viewport.
    this.rect = vec4.create();

    // Perspective values.
    this.isPerspective = true;
    this.fov = 0;
    this.aspect = 0;

    // Orthogonal values.
    this.isOrtho = false;
    this.leftClipPlane = 0;
    this.rightClipPlane = 0;
    this.bottomClipPlane = 0;
    this.topClipPlane = 0;

    // Shared values.
    this.nearClipPlane = 0;
    this.farClipPlane = 0;

    // World values.
    this.location = vec3.create();
    this.rotation = quat.create();

    // Derived values.
    this.inverseRotation = quat.create();
    this.worldMatrix = mat4.create();
    this.projectionMatrix = mat4.create();
    this.worldProjectionMatrix = mat4.create();
    this.inverseWorldMatrix = mat4.create();
    this.inverseRotationMatrix = mat4.create();
    this.inverseWorldProjectionMatrix = mat4.create();
    this.directionX = vec3.create();
    this.directionY = vec3.create();
    this.directionZ = vec3.create();

    // First four vectors are the corners of a 2x2 rectangle, the last three vectors are the unit axes
    this.vectors = [vec3.fromValues(-1, -1, 0), vec3.fromValues(-1, 1, 0), vec3.fromValues(1, 1, 0), vec3.fromValues(1, -1, 0), vec3.fromValues(1, 0, 0), vec3.fromValues(0, 1, 0), vec3.fromValues(0, 0, 1)];

    // First four vectors are the corners of a 2x2 rectangle billboarded to the camera, the last three vectors are the unit axes billboarded
    this.billboardedVectors = [vec3.create(), vec3.create(), vec3.create(), vec3.create(), vec3.create(), vec3.create(), vec3.create()];

    // Left, right, top, bottom, near, far
    this.planes = [vec4.create(), vec4.create(), vec4.create(), vec4.create(), vec4.create(), vec4.create()];

    this.dirty = true;
  }
Пример #8
0
function drawDebugTile(painter, source, coord) {
    var gl = painter.gl;

    gl.disable(gl.STENCIL_TEST);
    painter.lineWidth(1 * browser.devicePixelRatio);

    var posMatrix = coord.posMatrix;
    var program = painter.useProgram('debug');

    gl.uniformMatrix4fv(program.u_matrix, false, posMatrix);
    gl.uniform4f(program.u_color, 1, 0, 0, 1);
    painter.debugVAO.bind(gl, program, painter.debugBuffer);
    gl.drawArrays(gl.LINE_STRIP, 0, painter.debugBuffer.length);

    var vertices = textVertices(coord.toString(), 50, 200, 5);
    var debugTextArray = new painter.PosArray();
    for (var v = 0; v < vertices.length; v += 2) {
        debugTextArray.emplaceBack(vertices[v], vertices[v + 1]);
    }
    var debugTextBuffer = new Buffer(debugTextArray.serialize(), painter.PosArray.serialize(), Buffer.BufferType.VERTEX);
    var debugTextVAO = new VertexArrayObject();
    debugTextVAO.bind(gl, program, debugTextBuffer);
    gl.uniform4f(program.u_color, 1, 1, 1, 1);

    // Draw the halo with multiple 1px lines instead of one wider line because
    // the gl spec doesn't guarantee support for lines with width > 1.
    var tileSize = source.getTile(coord).tileSize;
    var onePixel = EXTENT / (Math.pow(2, painter.transform.zoom - coord.z) * tileSize);
    var translations = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
    for (var i = 0; i < translations.length; i++) {
        var translation = translations[i];
        gl.uniformMatrix4fv(program.u_matrix, false, mat4.translate([], posMatrix, [onePixel * translation[0], onePixel * translation[1], 0]));
        gl.drawArrays(gl.LINES, 0, debugTextBuffer.length);
    }

    gl.uniform4f(program.u_color, 0, 0, 0, 1);
    gl.uniformMatrix4fv(program.u_matrix, false, posMatrix);
    gl.drawArrays(gl.LINES, 0, debugTextBuffer.length);
}
Пример #9
0
    calculateOrientationForRayDirection: (function () {
        var tmpX = vec3.create();
        var tmpY = vec3.create();
        var tmpZ = vec3.create();
        var up = vec3.create();
        var q = quat.create();
        var m = mat4.create();

        return function (ray) {
            vec3.set(up, 0, 1, 0);
            vec3.cross(tmpX, ray.direction.data, up);
            if (!vec3.length(tmpX)) {
                vec3.set(tmpX, 1, 0, 0);
            }
            vec3.cross(tmpY, tmpX, ray.direction.data);
            vec3.negate(tmpZ, ray.direction.data);

            XML3D.math.quat.setFromBasis(q, tmpX, tmpY, tmpZ);
            mat4.fromRotationTranslation(m, q, [0,0,0]);
            return m;
        }
    })(),
Пример #10
0
    translatePosMatrix(matrix, tile, translate, anchor) {
        if (!translate[0] && !translate[1]) return matrix;

        if (anchor === 'viewport') {
            const sinA = Math.sin(-this.transform.angle);
            const cosA = Math.cos(-this.transform.angle);
            translate = [
                translate[0] * cosA - translate[1] * sinA,
                translate[0] * sinA + translate[1] * cosA
            ];
        }

        const translation = [
            pixelsToTileUnits(tile, translate[0], this.transform.zoom),
            pixelsToTileUnits(tile, translate[1], this.transform.zoom),
            0
        ];

        const translatedMatrix = new Float32Array(16);
        mat4.translate(translatedMatrix, matrix, translation);
        return translatedMatrix;
    }
Пример #11
0
    constructor(
        program,
        gldata,
        world,
        proj,
        position = [15, 0, eyeHeight],
        lookAt = [-10000, 0, eyeHeight],
        up = [0, 0, 1]
    ) {
        this.program = program;
        this.gldata = gldata;
        this.world = world;
        this.proj = proj;
        this.forward = vec3.create();
        this.up = vec3.fromValues(...up);
        this.right = vec3.create();
        this.resistance = vec3.create();
        this.thirdPerson = false;

        this.position = vec3.fromValues(...position);

        this.mView = mat4.create();

        // get what I'm looking at from my perspective
        this.lookAt = vec3.fromValues(...lookAt);
        //vec3.normalize(this.lookAt, this.lookAt);
        vec3.subtract(this.forward, this.lookAt, this.position);
        //vec3.add(this.up, this.up, up);

        this.renorm();

        this.rotSpeed = 0.001;
        this.moveSpeed = 0.05;
        this.slowSpeed = 0.05;
        this.fastSpeed = 0.1;

        this.accelDown = 0.02;
        this.velUp = 0;
    }
Пример #12
0
const Rotatable = (rotation) => {
    if (Object.prototype.toString.call(rotation) !== "[object Float32Array]" || rotation.length != 3) {
        throw new TypeError("Invalid rotation provided to Rotatable factory.");
    }

    return RenderComponent({
        name: "Rotatable",
        proto: RotatableProto,
        properties: {
            rotation: rotation,
            quaternion: GLMatrix.quat.create(),
            rotationMatrix: GLMatrix.mat4.create()
        },
        initializer: instance => {
            instance.rotate(rotation);
        },
        renderFn: (instance, gl, programInfo, modelViewMatrix) => {
            GLMatrix.mat4.multiply(modelViewMatrix, modelViewMatrix, instance.rotationMatrix);
            return modelViewMatrix;
        }
    });
};
Пример #13
0
Painter.prototype.translatePosMatrix = function(matrix, tile, translate, anchor) {
    if (!translate[0] && !translate[1]) return matrix;

    if (anchor === 'viewport') {
        var sinA = Math.sin(-this.transform.angle);
        var cosA = Math.cos(-this.transform.angle);
        translate = [
            translate[0] * cosA - translate[1] * sinA,
            translate[0] * sinA + translate[1] * cosA
        ];
    }

    var translation = [
        pixelsToTileUnits(tile, translate[0], this.transform.zoom),
        pixelsToTileUnits(tile, translate[1], this.transform.zoom),
        0
    ];

    var translatedMatrix = new Float32Array(16);
    mat4.translate(translatedMatrix, matrix, translation);
    return translatedMatrix;
};
Пример #14
0
Cloth.prototype.initMatrices = function () {
  var mat = this.mat;
  mat.model = mat4.create();
  mat.view = mat4.create();
  mat.projection = mat4.create();
  mat.mvp = mat4.create();

  mat4.translate(mat.model, mat.model, [-this.width / 2, -this.height, 0]);

  // In Camera Frame is L.H.S (looking at -ve Z direction)
  // However all those coorindate given to lookAt is measure in World Coordinate frame which is R.H.S

  // near and for must > 0
  mat4.perspective(mat.projection, 0.25 * Math.PI, this.viewport.width / this.viewport.height, 1, 10000);

  this.updateMVP();
};
Пример #15
0
  publicAPI.computeMatrix = () => {
    if (model.isIdentity) {
      return;
    }

    // check whether or not need to rebuild the matrix
    if (publicAPI.getMTime() > model.matrixMTime.getMTime()) {
      mat4.identity(model.matrix);
      mat4.translate(model.matrix, model.matrix, [-model.origin[0], -model.origin[1], -model.origin[2]]);
      mat4.scale(model.matrix, model.matrix, model.scale);
      mat4.translate(model.matrix, model.matrix, model.position);
      mat4.translate(model.matrix, model.matrix, model.origin);
      mat4.transpose(model.matrix, model.matrix);

      model.matrixMTime.modified();
    }
  };
Пример #16
0
    renderObjects: (function () {
        var c_mvp = mat4.create(), c_uniformCollection = {
            envBase: {},
            envOverride: null,
            sysBase: {}
        }, c_systemUniformNames = ["id", "modelViewProjectionMatrix"];

        return function (objects, program, viewMatrix, projMatrix) {
            for (var i=0; i < objects.length; i++) {
                var obj = objects[i];
                var mesh = obj.mesh;

                if (!obj.visible)
                    continue;

                if (viewMatrix && projMatrix) {
                    obj.updateModelViewMatrix(viewMatrix);
                    obj.updateModelViewProjectionMatrix(projMatrix);
                }

                obj.getModelViewProjectionMatrix(c_mvp);

                var objId = ++this.objCount;
                obj.pickId = objId;
                var c1 = objId & 255;
                objId = objId >> 8;
                var c2 = objId & 255;
                objId = objId >> 8;
                var c3 = objId & 255;

                c_uniformCollection.sysBase["id"] = [c3 / 255.0, c2 / 255.0, c1 / 255.0];
                c_uniformCollection.sysBase["modelViewProjectionMatrix"] = c_mvp;

                program.setUniformVariables(null, c_systemUniformNames, c_uniformCollection);
                mesh.draw(program);
            }
        };
    }()),
Пример #17
0
shell.on('gl-render', function() {
  var t = performance.now() - start;
  shader.bind();

  var proj = mat4.create();
  mat4.perspective(proj, Math.PI / 4, shell.width / shell.height, 0.1, 1000);

  var mv = mat4.create();
  mat4.lookAt(mv, [0, 0, 20], [0, 4, 0], [0, 1, 0]);
  mat4.rotateX(mv, mv, Math.PI / 8);
  mat4.rotateY(mv, mv, 2 * Math.PI * (t / 1000) / 10 * -1);

  // cycle through levels every second / 2
  var curLevel = parseInt(t / 1000 * 2) % 16 + 1;

  if(curLevel !== level) {
    level = curLevel;

    console.log('rendering level', level);

    // slice "level" levels from the pop buffer
    var pb = {
      bounds: popBuffer.bounds,
      levels: popBuffer.levels.slice(0, level)
    };

    var mesh = decode(pb);
    mesh.normals = normals.vertexNormals(mesh.cells, mesh.positions);

    geom.dispose();
    geom = createGeometry(shell.gl)
      .attr('position', mesh.positions)
      .attr('normal', mesh.normals)
      .faces(mesh.cells);
  }

  geom.bind(shader);

  shader.uniforms.proj = proj;
  shader.uniforms.mv = mv;
  shader.uniforms.ambient = [0.5, 0.5, 0.5];
  shader.uniforms.diffuse = [0.5, 0.5, 0.5];

  geom.draw();
});
Пример #18
0
        return function (canvasX, canvasY) {

            var glY = canvasToGlY(this._canvasHandler.getCanvas(), canvasY);

            // setup input to unproject
            var viewport = new Float32Array(4);
            viewport[0] = 0;
            viewport[1] = 0;
            viewport[2] = this.width;
            viewport[3] = this.height;

            // get view and projection matrix arrays
            var view = this.scene.getActiveView();
            view.getWorldToViewMatrix(c_viewMatrix);
            view.getProjectionMatrix(c_projectionMatrix, viewport[2] / viewport[3]);

            var ray = new XML3D.Ray();

            var nearHit = new Float32Array(3);
            var farHit = new Float32Array(3);

            // do unprojections
            if (false === GLU.unProject(canvasX, glY, 0, c_viewMatrix, c_projectionMatrix, viewport, nearHit)) {
                return ray;
            }

            if (false === GLU.unProject(canvasX, glY, 1, c_viewMatrix, c_projectionMatrix, viewport, farHit)) {
                return ray;
            }

            // calculate ray
            mat4.invert(c_viewMatrix, c_viewMatrix);
            ray.origin = vec3.fromValues(c_viewMatrix[12], c_viewMatrix[13], c_viewMatrix[14]);
            ray.direction = vec3.fromValues(farHit[0] - nearHit[0], farHit[1] - nearHit[1], farHit[2] - nearHit[2]);

            return ray;
        }
Пример #19
0
  /** Intersection between a ray the mouse position for every meshes */
  intersectionMouseMeshes(meshes = this._main.getMeshes(), mouseX = this._main._mouseX, mouseY = this._main._mouseY) {

    var vNear = this.unproject(mouseX, mouseY, 0.0);
    var vFar = this.unproject(mouseX, mouseY, 0.1);
    var nearDistance = Infinity;
    var nearMesh = null;
    var nearFace = -1;

    for (var i = 0, nbMeshes = meshes.length; i < nbMeshes; ++i) {
      var mesh = meshes[i];
      if (!mesh.isVisible())
        continue;

      mat4.invert(_TMP_INV, mesh.getMatrix());
      vec3.transformMat4(_TMP_NEAR_1, vNear, _TMP_INV);
      vec3.transformMat4(_TMP_FAR, vFar, _TMP_INV);
      if (!this.intersectionRayMesh(mesh, _TMP_NEAR_1, _TMP_FAR))
        continue;

      var interTest = this.getIntersectionPoint();
      var testDistance = vec3.dist(_TMP_NEAR_1, interTest) * mesh.getScale();
      if (testDistance < nearDistance) {
        nearDistance = testDistance;
        nearMesh = mesh;
        vec3.copy(_TMP_INTER_1, interTest);
        nearFace = this.getPickedFace();
      }
    }

    this._mesh = nearMesh;
    vec3.copy(this._interPoint, _TMP_INTER_1);
    this._pickedFace = nearFace;
    if (nearFace !== -1)
      this.updateLocalAndWorldRadius2();
    return !!nearMesh;
  }
Пример #20
0
function drawDebugTile(painter, source, coord) {
    var gl = painter.gl;

    gl.disable(gl.STENCIL_TEST);
    painter.lineWidth(1 * browser.devicePixelRatio);

    var posMatrix = painter.calculatePosMatrix(coord, source.maxzoom);
    var program = painter.useProgram('debug', posMatrix);

    // draw bounding rectangle
    gl.bindBuffer(gl.ARRAY_BUFFER, painter.debugBuffer);
    gl.vertexAttribPointer(program.a_pos, painter.debugBuffer.itemSize, gl.SHORT, false, 0, 0);
    gl.uniform4f(program.u_color, 1, 0, 0, 1);
    gl.drawArrays(gl.LINE_STRIP, 0, painter.debugBuffer.itemCount);

    var vertices = textVertices(coord.toString(), 50, 200, 5);
    gl.bindBuffer(gl.ARRAY_BUFFER, painter.debugTextBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Int16Array(vertices), gl.STREAM_DRAW);
    gl.vertexAttribPointer(program.a_pos, painter.debugTextBuffer.itemSize, gl.SHORT, false, 0, 0);
    gl.uniform4f(program.u_color, 1, 1, 1, 1);

    // Draw the halo with multiple 1px lines instead of one wider line because
    // the gl spec doesn't guarantee support for lines with width > 1.
    var tileSize = source.getTile(coord).tileSize;
    var onePixel = EXTENT / (Math.pow(2, painter.transform.zoom - coord.z) * tileSize);
    var translations = [[-1, -1], [-1, 1], [1, -1], [1, 1]];
    for (var i = 0; i < translations.length; i++) {
        var translation = translations[i];
        painter.setPosMatrix(mat4.translate([], posMatrix, [onePixel * translation[0], onePixel * translation[1], 0]));
        gl.drawArrays(gl.LINES, 0, vertices.length / painter.debugTextBuffer.itemSize);
    }

    gl.uniform4f(program.u_color, 0, 0, 0, 1);
    painter.setPosMatrix(posMatrix);
    gl.drawArrays(gl.LINES, 0, vertices.length / painter.debugTextBuffer.itemSize);
}
Пример #21
0
    createPlacementMatrixFromParent (parentM2, attachment, scale){
        var parentM2File = parentM2.m2Geom.m2File;
        var attIndex = parentM2File.attachLookups[attachment];
        var attachInfo = parentM2File.attachments[attIndex];

        var boneId = attachInfo.bone;
        var parentBoneTransMat = parentM2.bones[boneId].tranformMat;

        var placementMatrix = mat4.create();
        mat4.identity(placementMatrix);
        mat4.multiply(placementMatrix,placementMatrix, parentM2.placementMatrix);

        mat4.multiply(placementMatrix, placementMatrix, parentBoneTransMat);
        mat4.translate(placementMatrix, placementMatrix, [
            attachInfo.pos.x,
            attachInfo.pos.y,
            attachInfo.pos.z,
            0
        ]);

        var placementInvertMatrix = mat4.create();
        mat4.invert(placementInvertMatrix, placementMatrix);

        this.placementInvertMatrix = placementInvertMatrix;
        this.placementMatrix = placementMatrix;

        var bb = super.getBoundingBox();
        if (bb) {
            var a_ab = vec4.fromValues(bb.ab.x,bb.ab.y,bb.ab.z,1);
            var a_cd = vec4.fromValues(bb.cd.x,bb.cd.y,bb.cd.z,1);

            var worldAABB = mathHelper.transformAABBWithMat4(this.placementMatrix, [a_ab, a_cd]);

            this.diameter = vec3.distance(worldAABB[0],worldAABB[1]);
            this.aabb = worldAABB;
        }
    }
Пример #22
0
  render: function() {
    var rot_angle = Math.PI;

    var mt_left_pupil = mt4_identity.create();
    mt4.translate(mt_left_pupil, mt_left_pupil, [-kPUPIL_WIDTH - kPUPIL_SPACE_BETWEEN/2.0, kPUPIL_TOP, 0]);
    mt4.rotateZ(mt_left_pupil, mt_left_pupil, -rot_angle);
    mt4.scale(mt_left_pupil, mt_left_pupil, [0.5, 1, 1]);

    var mt_right_pupil = mt4_identity.create();
    mt4.translate(mt_right_pupil, mt_right_pupil, [kPUPIL_SPACE_BETWEEN/2.0, kPUPIL_TOP, 0]);
    mt4.rotateZ(mt_right_pupil, mt_right_pupil, rot_angle);
    mt4.scale(mt_right_pupil, mt_right_pupil, [0.5, 1, 1]);

    return (
      <View style={styles.eyes}>        
        <View style={[styles.pupil, {transformMatrix:mt_left_pupil}]} />
        <View style={[styles.pupil, {transformMatrix:mt_right_pupil}]} />
      </View>
    );
  }
Пример #23
0
    /**
     * Update matrix
     *
     * @param {?Array.<number>|glMatrix.mat4} parentMatrix Parent transformable's matrix
     * @param {boolean} forceUpdate True to force an update
     * @return {boolean} True if the matrix have been updated, otherwise false
     */
    computeTransformationMatrix(parentMatrix, forceUpdate)
    {
        // Avoid useless updates
        if (!forceUpdate && !this.needTransformUpdate)
            return false;

        // Compute matrix
        glMatrix.mat4.identity(this.matrix);
        glMatrix.mat4.translate(this.matrix, this.matrix, this.position);
        glMatrix.mat4.multiply(this.matrix, this.matrix, this.rotationMatrix);
        glMatrix.mat4.scale(this.matrix, this.matrix, this.scale);

        // Apply parent's transformations
        if (parentMatrix)
            glMatrix.mat4.multiply(this.matrix, parentMatrix, this.matrix);

        // Compute inverse matrix
        glMatrix.mat4.invert(this.normalMatrix, this.matrix);
        glMatrix.mat4.transpose(this.normalMatrix, this.normalMatrix);

        this.needTransformUpdate = false;

        return true;
    }
Пример #24
0
  // Transforms from Web Mercator Tile 0 [0-512,0-512] to "clip space"
  _calculateGLProjectionMatrix() {
    const m = mat4.create();

    mat4.perspective(m,
      2 * Math.atan((this.height / 2) / this.altitude),
      this.width / this.height,
      0.1,
      this.farZ
    );

    // Move camera to altitude
    mat4.translate(m, m, [0, 0, -this.altitude]);

    // After the rotateX, z values are in pixel units. Convert them to
    // altitude units. 1 altitude unit = the screen height.
    mat4.scale(m, m, [1, -1, 1 / this.height]);

    mat4.rotateX(m, m, this.pitchRadians);
    mat4.rotateZ(m, m, -this.bearingRadians);
    mat4.translate(m, m, [-this.centerX, -this.centerY, 0]);
    // mat4.scale(m, m, [this.scale, this.scale, this.scale]);

    return m;
  }
Пример #25
0
    getProjMatrix: function() {
        var m = new Float64Array(16);

        // Find the distance from the center point to the center top in altitude units using law of sines.
        var halfFov = Math.atan(0.5 / this.altitude);
        var topHalfSurfaceDistance = Math.sin(halfFov) * this.altitude / Math.sin(Math.PI / 2 - this._pitch - halfFov);
        // Calculate z value of the farthest fragment that should be rendered.
        var farZ = Math.cos(Math.PI / 2 - this._pitch) * topHalfSurfaceDistance + this.altitude;

        mat4.perspective(m, 2 * Math.atan((this.height / 2) / this.altitude), this.width / this.height, 0.1, farZ);

        mat4.translate(m, m, [0, 0, -this.altitude]);

        // After the rotateX, z values are in pixel units. Convert them to
        // altitude unites. 1 altitude unit = the screen height.
        mat4.scale(m, m, [1, -1, 1 / this.height]);

        mat4.rotateX(m, m, this._pitch);
        mat4.rotateZ(m, m, this.angle);
        mat4.translate(m, m, [-this.x, -this.y, 0]);
        return m;
    }
Пример #26
0
 updateMatrix(entity) {
   // Calculate matrix
   let matrix = this.matrices[entity.id];
   if (matrix == null) {
     matrix = this.matrices[entity.id] = Mat4.create();
   }
   Mat4.fromRotationTranslation(matrix,
     entity.transform.rotation, entity.transform.position);
   Mat4.scale(matrix, matrix, entity.transform.scale);
   // Calculate inverse matrix. This should be much cheaper than matrix
   // inverse, which is expensive.
   let inverseMatrix = this.inverseMatrices[entity.id];
   if (inverseMatrix == null) {
     inverseMatrix = this.inverseMatrices[entity.id] = Mat4.create();
   }
   // TODO maybe we can use conjugate function
   let quat = Quat.invert(QUAT_BUFFER, entity.transform.rotation);
   let vec = Vec3.negate(VEC3_BUFFER, entity.transform.position);
   Mat4.fromRotationTranslation(inverseMatrix, quat, vec);
   vec = Vec3.negate(VEC3_BUFFER, entity.transform.scale);
   Mat4.scale(inverseMatrix, inverseMatrix, vec);
 }
Пример #27
0
     lines.push( i2, i0 );
  }

  geoWire = glGeometry( gl );
  geoWire.attr( 'aPosition', positions );
  geoWire.faces( lines, { size: 2 } )
} );


// Set the canvas size to fill the window and its pixel density
var mobile = isMobile( navigator.userAgent );
var dpr = mobile ? 1 : ( window.devicePixelRatio || 1 );
window.addEventListener( 'resize', fit( canvas, null, dpr ), false );

// Setup Matricies
var projection = mat4.create();
var model = mat4.create();
var normalm4 = mat4.create();
var normalm3 = mat3.create();
var view = mat4.create();

// Setup Shaders
var vertexShader = glslify( './shaders/loadObjshader.vert' );
var fragmentShader = glslify( './shaders/loadObjshader.frag' );
var shader = glShader( gl, vertexShader, fragmentShader );

var vertexWireframeShader = glslify( './shaders/loadObjWireframe.vert' );
var fragmentWireframeShader = glslify( './shaders/loadObjWireframe.frag' );
var shaderWireframe = glShader( gl, vertexWireframeShader, fragmentWireframeShader );

var color = [ 1.0, 1.0, 1.0, 1.0 ];
Пример #28
0
 test('update on viewport change', function() {
   view.setSize({ width: 100, height: 150 });
   newProj = view.projection();
   assert.notDeepEqual(newProj, oldProj);
   mat4.copy(oldProj, newProj);
 });
Пример #29
0
 test('update on media aspect ratio change', function() {
   view.setMediaAspectRatio(0.5);
   newProj = view.projection();
   assert.notDeepEqual(newProj, oldProj);
   mat4.copy(oldProj, newProj);
 });
Пример #30
0
 test('update on zoom change', function() {
   view.setZoom(0.1);
   newProj = view.projection();
   assert.notDeepEqual(newProj, oldProj);
   mat4.copy(oldProj, newProj);
 });