Load single image on multiple surface of BoxGeometry - Three.js - javascript

I am using three.js for creating 3D Objects. I want to create 3d canvas similar like this in my project.
I want to render a single image on all side of object (box) except back.
I have found one similar example here:
https://www.geofx.com/graphics/nehe-three-js/lessons17-24/lesson17/lesson17.html.
I am planing to BoxGeomatry along with 2D faceVertexUvs (custom alignment) to cover surfaces.Is there any way I can do it easily rather than managing Vector2 (2D)? Any way I can use Vector3 (3D) or provide pixel to manage easily?
As I am new to Threejs, please suggest better approach if any?

An option with uvs of BoxBufferGeometry:
body {
overflow: hidden;
margin: 0;
}
<script type="module">
import * as THREE from "https://threejs.org/build/three.module.js";
import {OrbitControls} from "https://threejs.org/examples/jsm/controls/OrbitControls.js";
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
camera.position.set(0, 0, 10);
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
var controls = new OrbitControls(camera, renderer.domElement);
var g = new THREE.BoxBufferGeometry(10, 5, 1);
var uv = g.getAttribute("uv");
// +x
uv.setXY(0, 1, 1);
uv.setXY(1, 0.9, 1);
uv.setXY(2, 1, 0);
uv.setXY(3, 0.9, 0);
// -x
uv.setXY(4, 0.1, 1);
uv.setXY(5, 0, 1);
uv.setXY(6, 0.1, 0);
uv.setXY(7, 0, 0);
// +y
uv.setXY(8, 0, 0.8);
uv.setXY(9, 1, 0.8);
uv.setXY(10, 0, 1);
uv.setXY(11, 1, 1);
// -y
uv.setXY(12, 0, 0);
uv.setXY(13, 1, 0);
uv.setXY(14, 0, 0.2);
uv.setXY(15, 1, 0.2);
// -z ("back") - white area from 0,0 of map
uv.setXY(20, 0, 0);
uv.setXY(21, 0, 0);
uv.setXY(22, 0, 0);
uv.setXY(23, 0, 0);
var m = new THREE.MeshBasicMaterial({map: new THREE.TextureLoader().load("https://threejs.org/examples/textures/uv_grid_opengl.jpg")});
var o = new THREE.Mesh(g, m);
scene.add(o);
renderer.setAnimationLoop(()=>{
renderer.render(scene, camera);
});
</script>

Related

How do I detect if X and Z position is intersecting a certain mesh (not using mouse)? - Three.js

Background of Question
I am working on a game that is a mix between Europa Universalis 4 and Age of Empires 3. The game is made in JavaScript and utilizes Three.js (r109) library. As of right now I have made randomly generated low-poly terrain with trees and reflective water. In the beginning I want the game to spawn a Navy, represented by a galleon (in screenshot below). I want to make it so when its called to spawn, it will pick a random location within the bounds of the water. The water mesh is represented by a semi-opaque plane spanning the size of the map- with a THREE.Reflector object underneath it. The terrain is also a plane but has been altered using a SimplexNoise heightmap.
The Question
How do I detect if an x and z position intersects with the water mesh and not the terrain mesh? THREE.Raycaster seems to be useful for what I am trying to do, but I wan't to know if there is a better solution. If using THREE.Raycaster is the best option, how would I go about implementing it for this purpose? Should I make an individual THREE.Raycaster for every object I am doing this with? Keep in mind I'm not placing this object with the mouse, I want to place it with a method that checks the position as stated above.
It's difficult to give specific advice without knowing anything at all about your code, but it sounds like all you need to do is create a collision list for your valid water surfaces and then check that when you want to spawn something.
A very simple jsfiddle is here. It creates a "land" mesh (green) and a "water" mesh (blue), adds the "water" mesh to a variable called collisionList. It then calls a spawn function for coordinates diagonally across both surfaces. The function uses a raycaster to check if the coordinates are over the "water" mesh and spawns a red cube if it is.
Here's the code:
window.onload = function() {
var camera = null, land = null, water = null, renderer = null, lights;
var collisionList;
var d, n, scene = null, animID;
n = document.getElementById('canvas');
function load() {
var height = 600, width = 800;
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(60, width/height, 1, 1000);
camera.position.set(0, 0, -10);
camera.lookAt(new THREE.Vector3(0, 0, 0));
scene.add(camera);
lights = [];
lights[0] = new THREE.PointLight(0xffffff, 1, 0);
lights[1] = new THREE.PointLight(0xffffff, 1, 0);
lights[2] = new THREE.PointLight(0xffffff, 1, 0);
lights[0].position.set(0, 200, 0);
lights[1].position.set(100, 200, 100);
lights[2].position.set(-100, -200, -100);
scene.add(lights[0]);
scene.add(lights[1]);
scene.add(lights[2]);
water = new THREE.Mesh(new THREE.PlaneGeometry(7, 7, 10),
new THREE.MeshStandardMaterial({
color: 0x0000ff,
side: THREE.DoubleSide,
}));
water.position.set(0, 0, 0);
scene.add(water);
land = new THREE.Mesh(new THREE.PlaneGeometry(12, 12, 10),
new THREE.MeshStandardMaterial({
color: 0x00ff00,
side: THREE.DoubleSide,
}));
land.position.set(0, 0, 1);
scene.add(land);
renderer = new THREE.WebGLRenderer();
renderer.setSize(width, height);
n.appendChild(renderer.domElement);
collisionList = [ water ];
for(var i = -6; i < 6; i++)
spawn(i);
animate();
}
function spawn(x) {
var dir, intersect, mesh, ray, v;
v = new THREE.Vector3(x, x, -1);
dir = new THREE.Vector3(0, 0, 1);
ray = new THREE.Raycaster(v, dir.normalize(), 0, 100);
intersect = ray.intersectObjects(collisionList);
if(intersect.length <= 0)
return;
mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1, 1, 1, 1),
new THREE.MeshStandardMaterial({ color: 0xff0000 }));
mesh.position.set(x, x, 0);
scene.add(mesh);
}
function animate() {
if(!scene) return;
animID = requestAnimationFrame(animate);
render();
update();
}
function render() {
if(!scene || !camera || !renderer) return;
renderer.render(scene, camera);
}
function update() {
if(!scene || !camera) return;
}
load();
As for whether this is a smart way to do it, that really depends on the design of the rest of your game.
If your world is procgen then it may be more efficient/less error prone to generate the spawn points (and any other "functional" parts of the world) first and use that to generate the geography instead of the other way around.

Meaning of this code snippet in three JS

As I am new in the 3D world and three JS world, I understood most of the things, but always gets confused when it comes to matrices.
What I am trying to do is that I want to drag a small object on top of other objects and small object should face the same direction of the main object (an example is like hanging a wall clock on the wall).
To do this, I first tried placing an axis helper on top of rotating cube and applied the simple logic that, an Intersecting point will give the position for putting a small object and intersecting objects face normal will give direction for small object lookAt. I did and found success but not appropriate.
Then I did some calculation and searched some codes for calculating the same things, I got success now. But didn't understand the whole logic behind, WHY we did this.
this.normalMatrix.getNormalMatrix(intersects[i].object.matrixWorld);
this.worldNormal.copy(intersects[i].face.normal).applyMatrix3(this.normalMatrix).normalize();
this.object.position.addVectors(intersects[i].point, this.worldNormal);
this.lookAtVec.addVectors(this.object.position,this.worldNormal.multiplyScalar(15));
this.object.lookAt(this.lookAtVec);
One guy actually created a wall and placed a small object on top. He changed this line
this.object.position.addVectors(intersects[i].point, this.worldNormal);
to
this.object.position.copy(intersects[i].point);
and it is working for him, but the same thing for my axis helper is not working.
Just an option of how you can do it. Look at the end of the onMouseMove() function:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(-3, 5, 8);
camera.lookAt(scene.position);
var renderer = new THREE.WebGLRenderer({
antialias: true
});
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0x404040);
document.body.appendChild(renderer.domElement);
var controls = new THREE.OrbitControls(camera, renderer.domElement);
var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
var walls = [];
makeWall(Math.PI * 0.5);
makeWall(0);
makeWall(Math.PI * -0.5);
var clockGeom = new THREE.BoxBufferGeometry(1, 1, 0.1);
clockGeom.translate(0, 0, 0.05);
var clockMat = new THREE.MeshBasicMaterial({
color: "orange"
});
var clock = new THREE.Mesh(clockGeom, clockMat);
scene.add(clock);
var raycaster = new THREE.Raycaster();
var mouse = new THREE.Vector2();
var intersects = [];
var lookAt = new THREE.Vector3();
renderer.domElement.addEventListener("mousemove", onMouseMove, false);
function onMouseMove(event) {
mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
raycaster.setFromCamera(mouse, camera);
intersects = raycaster.intersectObjects(walls);
if (intersects.length === 0) return;
clock.position.copy(intersects[0].point);
clock.lookAt(lookAt.copy(intersects[0].point).add(intersects[0].face.normal));
}
render();
function render() {
requestAnimationFrame(render);
renderer.render(scene, camera);
}
function makeWall(rotY, color) {
let geom = new THREE.BoxBufferGeometry(8, 8, 0.1);
geom.translate(0, 0, -4);
geom.rotateY(rotY);
let mat = new THREE.MeshLambertMaterial({
color: Math.random() * 0x777777 + 0x777777
});
let wall = new THREE.Mesh(geom, mat);
scene.add(wall);
walls.push(wall);
}
body {
overflow: hidden;
margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/94/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

How to create a custom mesh in Babylon.js?

I'm using the babylonjs 3D WebGL library.
It's great library, but I can't find the same, which exists in THREE.JS library.
For example, I have 2D polygons in database, I'm fetching the polygon data from it and then create a custom mesh and extruding it.
With the THREE.JS, there isn't any problem, I can add to some array:
...
points.push( new THREE.Vector2( part.x, -part.y ) );
...
var shape = new THREE.Shape( points );
var extrusion = {
amount: building.height,
bevelEnabled: false
};
var geometry = new THREE.ExtrudeGeometry( shape, extrusion );
var mesh = new THREE.Mesh( geometry, new THREE.MeshLambertMaterial({
ambient: 0xbbbbb,
color: 0xff0000
});
...
scene.add( mesh );
It's very simple. How to do the same, I couldn't find.
I've found only some information here:
http://www.html5gamedevs.com/topic/4530-create-a-mesh-from-a-list-of-vertices-and-faces/
http://blogs.msdn.com/b/eternalcoding/archive/2013/06/27/babylon-js-a-complete-javascript-framework-for-building-3d-games-with-html-5-and-webgl.aspx
With such an example (from msdn by Ctrl + F -> You can also create a mesh from a list of vertices and faces):
var plane = new BABYLON.Mesh(name, scene);
var indices = [];
var positions = [];
var normals = [];
var uvs = [];
// Vertices
var halfSize = size / 2.0;
positions.push(-halfSize, -halfSize, 0);
normals.push(0, 0, -1.0);
uvs.push(0.0, 0.0);
positions.push(halfSize, -halfSize, 0);
normals.push(0, 0, -1.0);
uvs.push(1.0, 0.0);
positions.push(halfSize, halfSize, 0);
normals.push(0, 0, -1.0);
uvs.push(1.0, 1.0);
positions.push(-halfSize, halfSize, 0);
normals.push(0, 0, -1.0);
uvs.push(0.0, 1.0);
// Indices
indices.push(0);
indices.push(1);
indices.push(2);
indices.push(0);
indices.push(2);
indices.push(3);
plane.setVerticesData(positions, BABYLON.VertexBuffer.PositionKind);
plane.setVerticesData(normals, BABYLON.VertexBuffer.NormalKind);
plane.setVerticesData(uvs, BABYLON.VertexBuffer.UVKind);
plane.setIndices(indices);
return plane;
But's it's rather not the same as with the THREE.JS. For example I need to count index buffer manually where in THREE.JS I don't need it, also it's a sample with plane only and I didn't find any info about extruding exactly.
So... Maybe, there are some easy ways in BabylonJS?
There is no support for extrusion right now but this could be a great feature to add :) I will definitely add it to our roadmap. If you would like to discuss the issue further please ask on the babylon.js forum.
EDIT:
Have ability to create custom shapes now.
http://doc.babylonjs.com/tutorials/parametric_shapes#extrusion
Update 2019 PolygonMeshBuilder allows to create custom mesh from the collection of vertexes
Please note that the PolygonMeshBuilder uses Earcut, so, in non
playground projects, you will have to add a reference to their cdn or
download their npm package
Add Earcut as dependency in your index HTML
<script src="https://preview.babylonjs.com/earcut.min.js"></script>
Now you can use Pramaetric shapes to extrude polygon and punch holes.
//Polygon shape in XoZ plane
var shape = [
new BABYLON.Vector3(4, 0, -4),
new BABYLON.Vector3(2, 0, 0),
new BABYLON.Vector3(5, 0, 2),
new BABYLON.Vector3(1, 0, 2),
new BABYLON.Vector3(-5, 0, 5),
new BABYLON.Vector3(-3, 0, 1),
new BABYLON.Vector3(-4, 0, -4),
new BABYLON.Vector3(-2, 0, -3),
new BABYLON.Vector3(2, 0, -3)
];
//Holes in XoZ plane
var holes = [];
holes[0] = [ new BABYLON.Vector3(1, 0, -1),
new BABYLON.Vector3(1.5, 0, 0),
new BABYLON.Vector3(1.4, 0, 1),
new BABYLON.Vector3(0.5, 0, 1.5)
];
holes[1] = [ new BABYLON.Vector3(0, 0, -2),
new BABYLON.Vector3(0.5, 0, -1),
new BABYLON.Vector3(0.4, 0, 0),
new BABYLON.Vector3(-1.5, 0, 0.5)
];
var polygon = BABYLON.MeshBuilder.ExtrudePolygon("polygon",{
shape:shape,
holes:holes,
depth: 2,
sideOrientation: BABYLON.Mesh.DOUBLESIDE }, scene);
Result:
See this playground for reference:
https://playground.babylonjs.com/#4G18GY#7
Advance usage
building Staircases:
https://www.babylonjs-playground.com/#RNCYVM#74

How do I rotate an object to another object's up/normal/facing vectors

If I have a custom plane geometry like so:
planeGeometry.vertices[0] = new THREE.Vector3(0, 10, 0);
planeGeometry.vertices[1] = new THREE.Vector3(10, 10, 0);
planeGeometry.vertices[2] = new THREE.Vector3(0, 0, 0);
planeGeometry.vertices[3] = new THREE.Vector3(10, 0, 0);
// faceUVs, mesh etc omitted
var right = planeGeometry.vertices[0].clone().sub(planeGeometry.vertices[1]);
var up = planeGeometry.vertices[1].clone().sub(planeGeometry.vertices[3]);
var up = up.normalize();
var normal = up.clone().cross(right).normalize();
How can I rotate another Object3D (CSS3DObject in my case) to have this facing normal and up vector? Can I create a quaternion or rotation matrix to do this?

Three.js - Issues with shapes and inside holes

I'm having an issue, how can I obtain a kind of "open ring" like the torus but squared?
I tried with a shape plus a path as a hole:
var arcShape = new THREE.Shape();
arcShape.moveTo( 40, 0 );
arcShape.arc( 0, 0, 40, 0, 2*Math.PI, false );
var holePath = new THREE.Path();
holePath.moveTo( 30,0 )
holePath.arc( 0, 0, 30, 0, 2*Math.PI, true );
And until now, making a mesh:
new THREE.Mesh( arcShape.extrude({ amount: 5, bevelEnabled: false }), MATERIAL );
it works, but how to make a middle ring? I mean, with:
var arcShape = new THREE.Shape();
arcShape.moveTo( 40, 0 );
arcShape.arc( 0, 0, 40, 0, Math.PI, false );
var holePath = new THREE.Path();
holePath.moveTo( 30,0 );
holePath.arc( 0, 0, 30, 0, Math.PI, true );
It works, but it remains a subtle face between the terminal parts... is there a way to make it completely open?
Rather than start from square one, try changing the parameters in the Torus geometry constructor:
// Torus geometry parameters:
// radius of entire torus,
// diameter of tube (should be less than total radius),
// segments around radius,
// segments around torus ("sides")
var torusGeom = new THREE.TorusGeometry( 25, 10, 4, 4 );

Categories

Resources