three#Vector3 JavaScript Examples
The following examples show how to use
three#Vector3.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: Map.js From BlueMapWeb with MIT License | 6 votes |
/**
* Ray-traces and returns the terrain-height at a specific location, returns <code>false</code> if there is no map-tile loaded at that location
* @param x {number}
* @param z {number}
* @returns {boolean|number}
*/
terrainHeightAt(x, z) {
if (!this.isLoaded) return false;
this.raycaster.set(
new Vector3(x, 300, z), // ray-start
new Vector3(0, -1, 0) // ray-direction
);
this.raycaster.near = 1;
this.raycaster.far = 300;
this.raycaster.layers.enableAll();
let hiresTileHash = hashTile(Math.floor((x - this.data.hires.translate.x) / this.data.hires.tileSize.x), Math.floor((z - this.data.hires.translate.z) / this.data.hires.tileSize.z));
let tile = this.hiresTileManager.tiles.get(hiresTileHash);
if (!tile || !tile.model) {
let lowresTileHash = hashTile(Math.floor((x - this.data.lowres.translate.x) / this.data.lowres.tileSize.x), Math.floor((z - this.data.lowres.translate.z) / this.data.lowres.tileSize.z));
tile = this.lowresTileManager.tiles.get(lowresTileHash);
}
if (!tile || !tile.model){
return false;
}
try {
let intersects = this.raycaster.intersectObjects([tile.model]);
if (intersects.length > 0) {
return intersects[0].point.y;
}
} catch (err) {
return false;
}
}
Example #2
Source File: ionExample.js From 3DTilesRendererJS with Apache License 2.0 | 6 votes |
function rotationBetweenDirections( dir1, dir2 ) {
const rotation = new Quaternion();
const a = new Vector3().crossVectors( dir1, dir2 );
rotation.x = a.x;
rotation.y = a.y;
rotation.z = a.z;
rotation.w = 1 + dir1.clone().dot( dir2 );
rotation.normalize();
return rotation;
}
Example #3
Source File: NURBSCurve.js From canvas with Apache License 2.0 | 6 votes |
NURBSCurve.prototype.getPoint = function ( t, optionalTarget ) {
var point = optionalTarget || new Vector3();
var u = this.knots[ this.startKnot ] + t * ( this.knots[ this.endKnot ] - this.knots[ this.startKnot ] ); // linear mapping t->u
// following results in (wx, wy, wz, w) homogeneous point
var hpoint = NURBSUtils.calcBSplinePoint( this.degree, this.knots, this.controlPoints, u );
if ( hpoint.w != 1.0 ) {
// project to 3D space: (wx, wy, wz, w) -> (x, y, z, 1)
hpoint.divideScalar( hpoint.w );
}
return point.set( hpoint.x, hpoint.y, hpoint.z );
};
Example #4
Source File: item.js From architect3d with MIT License | 6 votes |
/** */
setScale(x, y, z)
{
var scaleVec = new Vector3(x, y, z);
this.halfSize.multiply(scaleVec);
scaleVec.multiply(this.scale);
this.scale.set(scaleVec.x, scaleVec.y, scaleVec.z);
this.resized();
if(this.bhelper)
{
this.bhelper.update();
}
// this.updateCanvasTexture(canvas, context, material, w, h);
this.updateCanvasTexture(this.canvasWH, this.canvascontextWH, this.canvasMaterialWH, this.getWidth(), this.getHeight(), 'w:', 'h:');
this.updateCanvasTexture(this.canvasWD, this.canvascontextWD, this.canvasMaterialWD, this.getWidth(), this.getDepth(), 'w:', 'd:');
this.scene.needsUpdate = true;
}
Example #5
Source File: BINVOXLoader.js From three-voxel-loader with MIT License | 6 votes |
/**
* Parse BINVOX file data.
* @param {Buffer} buffer Content of BINVOX file.
* @return {Promise<PointOctree>} Promise with an octree filled with voxel data.
*/
parse(buffer) {
return new Promise((resolve, reject) => {
const parser = new Parser();
let data = parser.parse(buffer);
const depth = data.dimension.depth;
const width = data.dimension.width;
const height = data.dimension.height;
const min = new Vector3(-depth / 2, -height / 2, -width / 2);
const max = new Vector3(depth / 2, height / 2, width / 2);
const octree = new PointOctree(min, max, 0, this.LOD.maxPoints, this.LOD.maxDepth);
let voxelData = {};
data.voxels.forEach(voxel => {
let x, y, z;
x = voxel.x - (depth / 2);
y = voxel.y - (width / 2);
z = voxel.z - (height / 2);
let point = new Vector3(x, z, y);
octree.insert(point, voxelData);
});
resolve(octree);
});
}
Example #6
Source File: index.js From map33.js with MIT License | 6 votes |
constructor(camera, map, domElement, controls) {
this.vec = new Vector3(); // create once and reuse
this.position = new Vector3(); // create once and reuse
this.camera = camera
this.map = map
this.domElement = domElement
this.controls = controls
this.domElement.addEventListener('mousemove', this.onMouseMove.bind(this))
this.domElement.addEventListener('dblclick', this.onMouseClick.bind(this))
}
Example #7
Source File: DragControls.js From geometry_3d with MIT License | 6 votes |
constructor(_objects, _camera) {
this._objects = _objects;
this._camera = _camera;
this._plane = new Plane();
this._raycaster = new Raycaster();
_mouse = new Vector2();
this._offset = new Vector3();
this._intersection = new Vector3();
this._worldPosition = new Vector3();
this._inverseMatrix = new Matrix4();
this._intersections = [];
this._selected = null;
}
Example #8
Source File: obb.js From threedtiles with MIT License | 6 votes |
constructor(values) {
this.center = new Vector3(values[0], values[2], -values[1]);
var e1 = new Vector3(values[3], values[5], values[4]);
var e2 = new Vector3(values[6], values[8], values[7]);
var e3 = new Vector3(values[9], values[11], values[10]);
this.halfWidth = e1.length();
this.halfHeight = e2.length();
this.halfDepth = e3.length();
e1.normalize();
e2.normalize();
e3.normalize();
// A sphere is used for frustum culling
this.sphere = new Sphere(this.center, Math.sqrt(this.halfWidth * this.halfWidth + this.halfHeight * this.halfHeight + this.halfDepth * this.halfDepth));
this.matrixToOBBCoordinateSystem = new Matrix3();
this.matrixToOBBCoordinateSystem.set(
e1.x, e1.y, e1.z,
e2.x, e2.y, e2.z,
e3.x, e3.y, e3.z);
}
Example #9
Source File: Animation.js From CUBE.gl with MIT License | 6 votes |
/**
* @param {Array} paths an array of paths, paths[0]: {latitude: Number, longitude: Number, altitude: Number}
* @param {Number} duration how long of this animation
* @public
*/
GPSPath (paths, duration) {
this.type = 'tween'
const all = new Vector3([], [], [])
for (let i = 0; i < paths.length; i++) {
const elPath = paths[i]
// Get Position
const posi = new Coordinate('GPS', elPath).ComputeWorldCoordinate()
all.x.push(-posi.world.x)
all.y.push(posi.world.y)
all.z.push(posi.world.z)
}
this.tween = new TWEEN.Tween(this.object.position).to(all, duration).easing(TWEEN.Easing.Linear.None)
if (this.options.startNow) this.Play() // Start Now
if (this.options.repeat) this.Loop() // Repeat Loop
return this
}
Example #10
Source File: index.js From THREE.BlurredLine with MIT License | 6 votes |
getInterpolatedPoint(pos) {
// position irrespective of length between points:
let startIndex = 0;
let delta = 0.0;
var totalLength = this.length();
let currentLength = 0.0;
for (let i = 0; i < this.lineVertices.length - 1; i++) {
let l = this.lineVertices[i].distanceTo(this.lineVertices[i + 1]);
currentLength += l;
if (currentLength / totalLength > pos) {
startIndex = i;
let x = pos * totalLength;
let xStart = currentLength - l;
let xEnd = currentLength;
delta = (x - xStart) / (xEnd - xStart);
break;
}
}
var point = new Vector3();
if (startIndex < this.lineVertices.length - 1) {
point.copy(this.lineVertices[startIndex]);
point.lerp(this.lineVertices[startIndex + 1], delta);
}
return point;
}
Example #11
Source File: index.js From webmc with MIT License | 6 votes |
getRayBlock () {
const start = new Vector3().setFromMatrixPosition(this.game.camera.matrixWorld)
const end = new Vector3().set(0, 0, 1).unproject(this.game.camera)
const intersection = this.chunkTerrain.intersectsRay(start, end)
if (intersection) {
const posPlace = intersection.position.map(function (v, ndx) {
return Math.floor(v + intersection.normal[ndx] * 0.5)
})
const posBreak = intersection.position.map(function (v, ndx) {
return Math.floor(v + intersection.normal[ndx] * -0.5)
})
return { posPlace, posBreak }
} else {
return false
}
}
Example #12
Source File: CurveExtras.js From Computer-Graphics with MIT License | 6 votes |
getPoint( t, optionalTarget = new Vector3() ) {
const point = optionalTarget;
t = 2 * Math.PI * t;
const x = - 0.22 * Math.cos( t ) - 1.28 * Math.sin( t ) - 0.44 * Math.cos( 3 * t ) - 0.78 * Math.sin( 3 * t );
const y = - 0.1 * Math.cos( 2 * t ) - 0.27 * Math.sin( 2 * t ) + 0.38 * Math.cos( 4 * t ) + 0.46 * Math.sin( 4 * t );
const z = 0.7 * Math.cos( 3 * t ) - 0.4 * Math.sin( 3 * t );
return point.set( x, y, z ).multiplyScalar( 20 );
}
Example #13
Source File: aabb.js From plant-3d-explorer with GNU Affero General Public License v3.0 | 6 votes |
setBoundingBox(aabb) {
// We could maybe do without creating a new GeometryBuffer
// This is left as excercise for the next intern here :)
this.box = new Box3(
new Vector3(parseFloat(aabb.min.x), parseFloat(aabb.min.y), parseFloat(aabb.min.z)),
new Vector3(parseFloat(aabb.max.x), parseFloat(aabb.max.y), parseFloat(aabb.max.z))
)
let oldObj = this.object
const newObj = new Box3Helper(this.box, 0xffffff);
newObj.visible = oldObj.visible
//oldObj.visible = false
oldObj.parent.add(newObj)
newObj.parent.remove(oldObj)
this.object = newObj
}
Example #14
Source File: App.js From minecraft-react with MIT License | 6 votes |
App = () => (
<Canvas shadowMap sRGB gl={{ alpha: false }}>
<RecoilRoot>
<Camera />
<Sky sunPosition={new Vector3(100, 10, 100)} />
<ambientLight intensity={0.3} />
<pointLight castShadow intensity={0.8} position={[100, 100, 100]} />
<Physics gravity={[0, -30, 0]}>
<Ground />
<Player />
<Cubes />
</Physics>
</RecoilRoot>
</Canvas>
)
Example #15
Source File: Body.js From sketch-webcam with MIT License | 6 votes |
constructor() {
// Define Geometry
const geometry = new PlaneBufferGeometry(1, 1);
// Define Material
const material = new RawShaderMaterial({
uniforms: {
resolution: {
value: store.state.resolution
},
segmentation: {
value: null
},
imgRatio: {
value: new Vector2()
}
},
vertexShader: vs,
fragmentShader: fs
});
super(geometry, material);
this.size = new Vector3();
}
Example #16
Source File: utils.js From cga.js with MIT License | 6 votes |
export function toMesh(obj, materialOption) {
var renderObj = null;
if (obj instanceof cga.Point || obj.isVec3) {
var geometry = new BufferGeometry()
geometry.setAttribute('position', new Float32BufferAttribute([obj.x, obj.y, obj.z], 3));
var material = new PointsMaterial({ size: 5, sizeAttenuation: false, color: 0x0ff0f0, alphaTest: 0.9, transparent: true });
renderObj = new Points(geometry, material);
} else if (obj instanceof cga.Line) {
var geometry = new Geometry()
var v1 = obj.direction.clone().multiplyScalar(10000).add(obj.origin);
var v2 = obj.direction.clone().multiplyScalar(-10000).add(obj.origin);
geometry.vertices.push(v1, v2);
var material = new LineBasicMaterial({ color: 0xffff8f });
renderObj = new Line(geometry, material);
} else if (obj instanceof cga.Ray) {
var geometry = new Geometry()
var v1 = obj.direction.clone().multiplyScalar(10000).add(obj.origin);
geometry.vertices.push(obj.origin, v1);
var material = new LineBasicMaterial({ color: 0xff8fff });
renderObj = new Line(geometry, material);
} else if (obj instanceof cga.Segment) {
var geometry = new Geometry()
geometry.vertices.push(obj.p0, obj.p1);
var material = new LineBasicMaterial({ color: 0x8fffff });
renderObj = new Line(geometry, material);
} else if (obj instanceof cga.Triangle) {
var geometry = new Geometry()
geometry.vertices = [...obj];
geometry.faces.push(new Face3(0, 1, 2))
var material = new MeshBasicMaterial({ color: 0x8f8fff, side: DoubleSide });
renderObj = new Mesh(geometry, material);
}
else if (obj instanceof cga.Polyline) {
var geometry = new Geometry()
geometry.vertices.push(...obj);
var material = new LineBasicMaterial({ color: 0xff8fff });
renderObj = new Line(geometry, material);
} else if (obj instanceof cga.Polygon) {
} else if (obj instanceof cga.Circle) {
var geometry = new Geometry()
var radius = obj.radius;
for (let i = 0; i <= 128; i++) {
var p = new Vector3();
p.x = radius * Math.cos(Math.PI / 64 * i);
p.y = radius * Math.sin(Math.PI / 64 * i);
geometry.vertices.push(p);
}
var quaternion = getQuaternionForm2V(new Vector3(0, 0, 1), obj.normal);
var mat4 = new Matrix4();
mat4.makeRotationFromQuaternion(quaternion);
geometry.applyMatrix(mat4);
geometry.translate(obj.center.x, obj.center.y, obj.center.z);
var material = new LineBasicMaterial({ color: 0x8fffff });
renderObj = new Line(geometry, material);
renderObj.add(new toMesh(obj.center))
renderObj.add(new toMesh(new cga.Ray(obj.center, obj.normal)))
}
else if (obj instanceof cga.Disk) {
var geometry = new CircleGeometry(obj.radius, 128)
var material = new MeshBasicMaterial({ color: 0x8f8fff, side: DoubleSide });
var quaternion = getQuaternionForm2V(new Vector3(0, 0, 1), obj.normal);
var mat4 = new Matrix4();
mat4.makeRotationFromQuaternion(quaternion);
geometry.applyMatrix4(mat4);
geometry.translate(obj.center.x, obj.center.y, obj.center.z);
renderObj = new Mesh(geometry, material);
renderObj.add(new toMesh(obj.center))
renderObj.add(new toMesh(new cga.Ray(obj.center, obj.normal)))
}
return renderObj;
}
Example #17
Source File: device-orientation-controls.js From AR.js with MIT License | 5 votes |
_zee = new Vector3(0, 0, 1)
Example #18
Source File: ControlsManager.js From BlueMapWeb with MIT License | 5 votes |
updateCamera() {
let valueChanged = this.isValueChanged();
if (valueChanged) {
this.resetValueChanged();
// wrap rotation
while (this.rotation >= Math.PI) this.rotation -= Math.PI * 2;
while (this.rotation <= -Math.PI) this.rotation += Math.PI * 2;
// prevent problems with the rotation when the angle is 0 (top-down) or distance is 0 (first-person)
let rotatableAngle = this.angle;
if (Math.abs(rotatableAngle) <= 0.0001) rotatableAngle = 0.0001;
else if (Math.abs(rotatableAngle) - Math.PI <= 0.0001) rotatableAngle = rotatableAngle - 0.0001;
let rotatableDistance = this.distance;
if (Math.abs(rotatableDistance) <= 0.0001) rotatableDistance = 0.0001;
// fix distance for orthogonal-camera
if (this.ortho > 0) {
rotatableDistance = MathUtils.lerp(rotatableDistance, Math.max(rotatableDistance, 300), Math.pow(this.ortho, 8));
}
// calculate rotationVector
let rotationVector = new Vector3(Math.sin(this.rotation), 0, -Math.cos(this.rotation)); // 0 is towards north
let angleRotationAxis = new Vector3(0, 1, 0).cross(rotationVector);
rotationVector.applyAxisAngle(angleRotationAxis, (Math.PI / 2) - rotatableAngle);
rotationVector.multiplyScalar(rotatableDistance);
// position camera
this.camera.rotation.set(0, 0, 0);
this.camera.position.copy(this.position).sub(rotationVector);
this.camera.lookAt(this.position);
this.camera.rotateZ(this.tilt + rotatableAngle < 0 ? Math.PI : 0);
// optimize far/near planes
if (this.ortho <= 0) {
let near = MathUtils.clamp(rotatableDistance / 1000, 0.01, 1);
let far = MathUtils.clamp(rotatableDistance * 2, Math.max(near + 1, 2000), rotatableDistance + 5000);
if (far - near > 10000) near = far - 10000;
this.camera.near = near;
this.camera.far = far;
} else if (this.angle === 0) {
this.camera.near = 1;
this.camera.far = rotatableDistance + 300;
} else {
this.camera.near = 1;
this.camera.far = 100000;
}
// event
dispatchEvent(this.mapViewer.events, "bluemapCameraMoved", {
controlsManager: this,
camera: this.camera
});
}
// if the position changed, update map to show new position
if (this.mapViewer.map) {
let triggerDistance = 1;
if (valueChanged) {
if (this.distance > 300) {
triggerDistance = this.mapViewer.data.loadedLowresViewDistance * 0.5;
} else {
triggerDistance = this.mapViewer.data.loadedHiresViewDistance * 0.5;
}
}
if (
Math.abs(this.lastMapUpdatePosition.x - this.position.x) >= triggerDistance ||
Math.abs(this.lastMapUpdatePosition.z - this.position.z) >= triggerDistance
) {
this.lastMapUpdatePosition = this.position.clone();
this.mapViewer.loadMapArea(this.position.x, this.position.z);
}
}
}
Example #19
Source File: vr.js From 3DTilesRendererJS with Apache License 2.0 | 5 votes |
upVector = new Vector3( 0, 1, 0 )
Example #20
Source File: FaceNormalsHelper.js From canvas with Apache License 2.0 | 5 votes |
_v1 = new Vector3()
Example #21
Source File: floorplan.js From architect3d with MIT License | 5 votes |
/**
* Returns the bounding size or the center location of the full floorplan
*
* @param {boolean}
* center If true return the center else the size
* @return {Vector3} size
* @see https://threejs.org/docs/#api/en/math/Vector3
*/
getDimensions(center)
{
center = center || false; // otherwise, get size
var xMin = Infinity;
var xMax = -Infinity;
var zMin = Infinity;
var zMax = -Infinity;
this.corners.forEach((corner) => {
if (corner.x < xMin) xMin = corner.x;
if (corner.x > xMax) xMax = corner.x;
if (corner.y < zMin) zMin = corner.y;
if (corner.y > zMax) zMax = corner.y;
});
var ret;
if (xMin == Infinity || xMax == -Infinity || zMin == Infinity || zMax == -Infinity)
{
ret = new Vector3();
}
else
{
if (center)
{
// center
ret = new Vector3((xMin + xMax) * 0.5, 0, (zMin + zMax) * 0.5);
}
else
{
// size
ret = new Vector3((xMax - xMin), 0, (zMax - zMin));
}
}
return ret;
}
Example #22
Source File: VoxelLoader.js From three-voxel-loader with MIT License | 5 votes |
/**
* Generates a polygon mesh with cubes based on voxel data.
* One cube for each voxel.
* @param {PointOctree} octree Octree with voxel data stored as points in space.
* @returns {Mesh} 3D mesh based on voxel data
*/
generateMesh(octree) {
let mergedGeometry = new Geometry();
const material = this.material;
for (const leaf of octree.leaves()) {
if (leaf.points !== null) {
const pos = new Vector3();
var i;
let min = { x: leaf.points[0].x, y: leaf.points[0].y, z: leaf.points[0].z };
let max = { x: leaf.points[0].x, y: leaf.points[0].y, z: leaf.points[0].z };
for (i = 0; i < leaf.points.length; i++) {
const point = leaf.points[i];
pos.add(point);
min.x = Math.min(min.x, point.x);
min.y = Math.min(min.y, point.y);
min.z = Math.min(min.z, point.z);
max.x = Math.max(max.x, point.x);
max.y = Math.max(max.y, point.y);
max.z = Math.max(max.z, point.z);
}
let width = Math.round((this.voxelSize + (max.x - min.x)) * 100) / 100;;
let height = Math.round((this.voxelSize + (max.y - min.y)) * 100) / 100;;
let depth = Math.round((this.voxelSize + (max.z - min.z)) * 100) / 100;
let voxelGeometry = new BoxGeometry(width, height, depth);
pos.divideScalar(i);
const rgb = leaf.data[0].color;
if (rgb != null) {
const color = new Color().setRGB(rgb.r / 255, rgb.g / 255, rgb.b / 255);
for (var i = 0; i < voxelGeometry.faces.length; i++) {
let face = voxelGeometry.faces[i];
face.color.set(color);
}
}
voxelGeometry.translate(pos.x, pos.y, pos.z);
mergedGeometry.merge(voxelGeometry);
voxelGeometry.translate(-pos.x, -pos.y, -pos.z);
}
}
let bufGeometry = new BufferGeometry().fromGeometry(mergedGeometry);
bufGeometry.computeFaceNormals();
bufGeometry.computeVertexNormals();
var voxels = new Mesh(bufGeometry, material);
return voxels;
}
Example #23
Source File: index.js From map33.js with MIT License | 5 votes |
camera.up = new Vector3(0, 0, 1);