How to show spherical grid helper in Three JS - javascript

I am working on a project that want to move small objects and show them in a 360 image using ThreeJS library. So I am using Spherical coordinate system in a sphere with some radius to move the objects. User starts seeing the app in the center of the sphere. I want to show some grid helper lines on the sphere ( very similar to longitude and latitude lines). I found the following code from here in the library:
var radius = 10;
var radials = 16;
var circles = 8;
var divisions = 64;
var helper = new THREE.PolarGridHelper( radius, radials, circles, divisions );
scene.add( helper );
But it only adds a polar plate with some circles not a sphere shape grid helper to the scene.

PolarGridHelper is a flat circle. If you want a spherical geometry just use SphereBufferGeometry and give it a wireframe look:
var radius = 10;
var latSegments = 18; // 10° increments
var longSegments = 36; // 10° increments
var geometry = new THREE.SphereBufferGeometry( radius, longSegments, latSegments);
var material = new THREE.MeshBasicMaterial({
color: 0xffffff,
wireframe: true
});
var sphere = new THREE.Mesh( geometry, material );
scene.add( sphere );

Related

three.js only BackSide of faces on the southern hemisphere

I am trying to implement my own sphere based on a geospatial dataset.
I import a GeoJSON file that describes a grid which covers the entire earth. The coordinates for each grid cell (a grid cell has more than 3 verticies!) are given as latitude (-90 90) and longitude (-180 180). These polar coordinates are transformed to cartesian coordinates x,y,z and send to the below function:
function triangulate_grid(vertices, color) {
//http://blog.cjgammon.com/threejs-geometry
var holes = [];
var triangles, mesh;
var geometry = new THREE.Geometry();
var color = new THREE.Color(color[0], color[1], color[2]);
//http://jsfiddle.net/RnFqz/22/
var material = new THREE.MeshPhongMaterial({
color: color,
// FlatShading: THREE.FlatShading,
// side: THREE.DoubleSide,
// side: THREE.BackSide,
side: THREE.FrontSide,
wireframe: false,
transparent: false,
vertexColors: THREE.FaceColors, // CHANGED
// overdraw: true
});
var materialIndex = 0; //optional
geometry.vertices = vertices;
triangles = THREE.ShapeUtils.triangulateShape(vertices, holes);
for (var i = 0; i < triangles.length; i++) {
face = new THREE.Face3(triangles[i][0], triangles[i][1], triangles[i][2])
face.color = color;
geometry.faces.push(face);
}
geometry.computeFaceNormals();
geometry.computeVertexNormals();
mesh = new THREE.Mesh(geometry, material);
//https://stackoverflow.com/questions/28848863/threejs-how-to-rotate-around-objects-own-center-instead-of-world-center
mesh.rotation.x = -90;
scene.add(mesh)
}
The sphere that is drawn looks like this:
It would be easier to see if you could rotate it yourself. But what is happening is, that I see the surface of the faces of the northern hemisphere as an astronaut would see it (from above), while the faces of the southern hemisphere can only be seen by looking through the earth. It looks like the equator is 'flipping' the faces with latitude coordinates 0 to -90 to only show the backside.
I am using this function to make the coordinate transformation.
//https://bl.ocks.org/mbostock/2b85250396c17a79155302f91ec21224
function vertex(point) {
var lambda = (point[0]) * Math.PI / 180, // lon
phi = (point[1]) * Math.PI / 180, //lat
cosPhi = Math.cos(phi);
var radius = 1;
vector = new THREE.Vector3(
radius * cosPhi * Math.cos(lambda),
radius * cosPhi * Math.sin(lambda),
radius * Math.sin(phi)
);
// vector.applyAxisAngle( 0, 90 );
return vector
}
I have used THREE.DoubleSide, but that solves the problem only partially. First, I think it is not necessary and only takes ressources and second, there are still artifacts at the equator. See the upper left corner of the image.
Question:
How to draw all faces on the nothern and southern hemisphere, so I can see the surface and not look through?
Update:
Added a cube to make it more clear.

Merging geometries in three.js

I have a scene which contains multiple meshes, each of varying shapes and sizes.
I have looped through each Mesh and using geometry.merge() I have been able to create a new mesh from the geometries in the scene.
I want to mask the entire mesh with an alphaMask, however, each geometry has the material applied to it separately.
An example of this can be seen here - https://codepen.io/danlong/pen/KXOObr
function addObjects(scene) {
// merged geomoetry & material
var mergedGeometry = new THREE.Geometry();
var mergedMaterial = new THREE.MeshStandardMaterial({ color: "#444", transparent: true, side: THREE.DoubleSide, alphaTest: 0.5, opacity: 1, roughness: 1 });
// multiple meshes
var geometry = new THREE.IcosahedronGeometry(30, 5);
var material = new THREE.MeshStandardMaterial({ color: "#444" });
var geo1 = new THREE.IcosahedronGeometry(30, 5);
var mesh1 = new THREE.Mesh( geo1, material );
mesh1.position.x = 10;
mesh1.position.y = 10;
mesh1.position.z = 0;
var geo2 = new THREE.IcosahedronGeometry(30, 5);
var mesh2 = new THREE.Mesh( geo2, material );
mesh2.position.x = 20;
mesh2.position.y = 20;
mesh2.position.z = 0;
var geo3 = new THREE.IcosahedronGeometry(30, 5);
var mesh3 = new THREE.Mesh( geo3, material );
mesh3.position.x = 30;
mesh3.position.y = 30;
mesh3.position.z = 0;
// scene.add(mesh1, mesh2, mesh3);
mesh1.updateMatrix();
mergedGeometry.merge(mesh1.geometry, mesh1.matrix);
mesh2.updateMatrix();
mergedGeometry.merge(mesh2.geometry, mesh2.matrix);
mesh3.updateMatrix();
mergedGeometry.merge(mesh3.geometry, mesh3.matrix);
// alpha texture
var image = document.createElement('img');
var alphaMap = new THREE.Texture(image);
image.onload = function() {
alphaMap.needsUpdate = true;
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAGUlEQVQoU2NkYGD4z4AHMP7//x+/gmFhAgCXphP14bko/wAAAABJRU5ErkJggg==';
mergedMaterial.alphaMap = alphaMap;
mergedMaterial.alphaMap.magFilter = THREE.NearestFilter;
mergedMaterial.alphaMap.wrapT = THREE.RepeatWrapping;
mergedMaterial.alphaMap.repeat.y = 1;
// merged geometry with alpha mask
merge1 = new THREE.Mesh(mergedGeometry, mergedMaterial);
merge1.rotation.z = -Math.PI/4;
// merge geometry without alpha mask
var merge2 = new THREE.Mesh(mergedGeometry, material);
merge2.position.x = -100;
merge2.rotation.z = -Math.PI/4;
scene.add(merge1, merge2);
return mesh;
}
The mesh on the left is the merged geometries which I want to apply the alphaMask to. The mesh on the right is the outcome of this and instead of the map being applied to the mesh as a whole, each of the geometries has the map applied.
Is there a way to mask the entire mesh and not each geometry?
--
three.js r86
EDIT:
I've tried to apply a clipping plane to my mesh but it's not the effect I'm looking for. I want to be able to apply an alphaMask across the whole mesh and reveal it however I make my mask image. Something like this effect - https://codepen.io/supah/pen/zwJxdb
Is it something to do with the UV's being preserved from the original geometries? Do I need to change these in some way?
I think what you really want is an overlaid mask. This can be accomplished by rendering a single plane that has the alpha map applied, on top of the scene rendering. Using an orthographic camera, and controlling certain renderer settings, such as disabling automatic clearing of color.

three.js How to rotate an object around the camera coordinate?

var object = new THREE.CSS3DObject(element);
object.matrix=camera.matrix.clone();
object.matrix.setPosition(new THREE.Vector3(tarx,tary,tarz));
//object.applyMatrix(new THREE.Matrix4().makeRotationY(rY));
//object.applyMatrix(new THREE.Matrix4().makeRotationZ(rX));
It will rotate about the world coordinate Y,but I just want to rotate about the camera
1 - Create an object who copy camera.position (like you have done)
2 - Add a satellite to this object
var orbit = 100;
var geometry = new THREE.BoxGeometry(1,1,1);
var material = new THREE.MeshBasicMaterial( { color: 0xffff00, side: THREE.DoubleSide } );
satellite = new THREE.Mesh( geometry, material );
satellite.position.set(orbit,0,0);
Add satellite to object
object.add( satellite );
If you rotate object
the satellite rotate around the camera coordinate.

Using multiuple textures on a sphere [Three.js]

Is it possible to load multiple textures on a sphere?
I mean to say is there any way in Three.js to split a sphere into n pieces , texture them separately and render those pieces once again as a whole sphere?
I do not want to load the entire texture on the sphere, instead, only those parts are to be rendered which the user will first see on the screen and as the user rotates the sphere the rest part of the texture must be loaded.
Moreover, when I use a single image on a sphere it seems to converge at poles making it worse.
This should help: https://open.bekk.no/procedural-planet-in-webgl-and-three-js
Instead of using a sphere try using a cube and expanding it into a sphere. Cube logic on the cube sphere will save you a good amount of time.
var geometry = new THREE.BoxGeometry( 1, 1, 1, 8, 8, 8 );
for ( var i in geometry.vertices ) {
var vertex = geometry.vertices[ i ];
vertex.normalize().multiplyScalar(radius);
}
var materialArray = [];
var faceMaterial = new THREE.MeshLambertMaterial({
color: sphereColor,
transparent: true,
opacity: 0.4
});
for (var i = 0; i < 6; i++) {
materialArray.push(faceMaterial);
}
var material = new THREE.MeshFaceMaterial(materialArray);
var sphere = new THREE.Mesh( geometry, material );
scene.add( sphere );

Draw a circle (not shaded) with Three.js

I am trying to draw a circle very similar to the orbital patterns on this website. I would like to use Three.js instead of pure WebGL.
Three.js r50 added CircleGeometry. It can be seen (albeit with a face) in the WebGL Geometries example.
The first vertex in the geometry is created at the center of the circle (in r84, see CircleGeometry.js line 71, in r65, see CircleGeometry.js line 18), which is nifty if you are going for that "full Pac-Man" or "uninformative pie chart" look. Oh, and it appears to be necessary if you are going to use any material aside from LineBasicMaterial / LineDashedMaterial.
I've verified that the following code works in both r60 & r65:
var radius = 100,
segments = 64,
material = new THREE.LineBasicMaterial( { color: 0x0000ff } ),
geometry = new THREE.CircleGeometry( radius, segments );
// Remove center vertex
geometry.vertices.shift();
// Non closed circle with one open segment:
scene.add( new THREE.Line( geometry, material ) );
// To get a closed circle use LineLoop instead (see also #jackrugile his comment):
scene.add( new THREE.LineLoop( geometry, material ) );
PS: The "docs" now include a nice CircleGeometry interactive example: https://threejs.org/docs/#api/geometries/CircleGeometry
The API changed slightly in newer versions of threejs.
var segmentCount = 32,
radius = 100,
geometry = new THREE.Geometry(),
material = new THREE.LineBasicMaterial({ color: 0xFFFFFF });
for (var i = 0; i <= segmentCount; i++) {
var theta = (i / segmentCount) * Math.PI * 2;
geometry.vertices.push(
new THREE.Vector3(
Math.cos(theta) * radius,
Math.sin(theta) * radius,
0));
}
scene.add(new THREE.Line(geometry, material));
Modify segmentCount to make the circle smoother or more jagged as needed by your scene. 32 segments will be quite smooth for small circles. For orbits such as those on the site you link you, you may want to have a few hundred.
Modify the order of the three components within the Vector3 constructor to choose the orientation of the circle. As given here, the circle will be aligned to the x/y plane.
I used code that Mr.doob references in this github post.
var resolution = 100;
var amplitude = 100;
var size = 360 / resolution;
var geometry = new THREE.Geometry();
var material = new THREE.LineBasicMaterial( { color: 0xFFFFFF, opacity: 1.0} );
for(var i = 0; i <= resolution; i++) {
var segment = ( i * size ) * Math.PI / 180;
geometry.vertices.push( new THREE.Vertex( new THREE.Vector3( Math.cos( segment ) * amplitude, 0, Math.sin( segment ) * amplitude ) ) );
}
var line = new THREE.Line( geometry, material );
scene.add(line);
This example is in the Three.js documentation:
var material = new THREE.MeshBasicMaterial({
color: 0x0000ff
});
var radius = 5;
var segments = 32; //<-- Increase or decrease for more resolution I guess
var circleGeometry = new THREE.CircleGeometry( radius, segments );
var circle = new THREE.Mesh( circleGeometry, material );
scene.add( circle );
I had to do this lol:
function createCircle() {
let circleGeometry = new THREE.CircleGeometry(1.0, 30.0);
circleGeometry.vertices.splice(0, 1); //<= This.
return new THREE.LineLoop(circleGeometry,
new THREE.LineBasicMaterial({ color: 'blue' }));
}
let circle = createCircle();
Reason: Otherwise, it doesn't draw a "pure" circle, there's a line coming from the center to the rim of the circle, even if you use LineLoop instead of Line. Splicing (removing) the first vertex from the array is a hack but seems to do the trick. :)
(Note that apparently, according to mrienstra's answer, "Oh, and it appears to be necessary if you are going to use any material aside from LineBasicMaterial / LineDashedMaterial.")
If you want thickness, though, you're screwed ("Due to limitations of the OpenGL Core Profile with the WebGL renderer on most platforms linewidth will always be 1 regardless of the set value.")... Unless you use: https://github.com/spite/THREE.MeshLine
Code example for that is here: https://stackoverflow.com/a/61312721/1599699
Well, I dunno when they added it - but TorusGeometry should do the job...
THREE TorusGeometry
const geometry = new THREE.TorusGeometry( 10, 3, 16, 100 );
const material = new THREE.MeshBasicMaterial( { color: 0xffff00 } );
const torus = new THREE.Mesh( geometry, material );
scene.add( torus );
Dunno, but I think it shouldn't be (much) more expensive than the line thingy and it's a buffer geometry and you may adjust size and material etc...
See the three.js sample http://mrdoob.github.com/three.js/examples/webgl_lines_colors.html to see how to draw colored lines.
A circle like the ones you cite is drawn as a large # of little straight segments. (Actually, the ones you show may be ellipses)
var getStuffDashCircle2 = function () {
var segment = 100, radius = 100;
var lineGeometry = new THREE.Geometry();
var vertArray = lineGeometry.vertices;
var angle = 2 * Math.PI / segment;
for (var i = 0; i < segment; i++) {
var x = radius * Math.cos(angle * i);
var y = radius * Math.sin(angle * i);
vertArray.push(new THREE.Vector3(x, y, 0));
}
lineGeometry.computeLineDistances();
var lineMaterial = new THREE.LineDashedMaterial({ color: 0x00cc00, dashSize: 4, gapSize: 2 });
var circle = new THREE.Line(lineGeometry, lineMaterial);
circle.rotation.x = Math.PI / 2;
circle.position.y = cylinderParam.trackHeight+20;
return circle;
}
I had some issues getting the other answers to work here -- in particular, CircleGeometry had an extra point at the center of the circle, and I didn't like the hack of trying to remove that vertex.
EllipseCurve does what I wanted (verified in r135):
const curve = new THREE.EllipseCurve(
0.0, 0.0, // Center x, y
10.0, 10.0, // x radius, y radius
0.0, 2.0 * Math.PI, // Start angle, stop angle
);
const pts = curve.getSpacedPoints(256);
const geo = new THREE.BufferGeometry().setFromPoints(pts);
const mat = new THREE.LineBasicMaterial({ color: 0xFF00FF });
const circle = new THREE.LineLoop(geo, mat);
scene.add(circle);

Categories

Resources