ThreeJS: applying edge geometry to ArrowHelper - javascript

I'm trying to create an arrow using ArrowHelper in ThreeJS:
let arrow = new THREE.ArrowHelper(direction.normalize(), new THREE.Vector3(), length, color, headLength, headWidth);
Also I want to use a separate color for edges. I realize that I need to use THREE.EdgesGeometry, but how to apply it I don't quite understand. Could anybody help me?
Update
sorry for confusion, I thought the arrow uses pyramid, not cone. Is there a way to replace cone with pyramid and use different color for edges?
Update
Thank you all for your answers, they were really helpful. I ended up with creating custom arrow class (copied most of the code from ArrowHelper):
class CustomArrow extends THREE.Object3D {
constructor( dir, origin, length, color, edgeColor, headLength, headWidth ) {
super();
// dir is assumed to be normalized
this.type = 'CustomArrow';
if ( dir === undefined ) dir = new THREE.Vector3( 0, 0, 1 );
if ( origin === undefined ) origin = new THREE.Vector3( 0, 0, 0 );
if ( length === undefined ) length = 1;
if ( color === undefined ) color = 0xffff00;
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
if ( this._lineGeometry === undefined ) {
this._lineGeometry = new THREE.BufferGeometry();
this._lineGeometry.setAttribute( 'position', new THREE.Float32BufferAttribute( [ 0, 0, 0, 0, 1, 0 ], 3 ) );
this._coneGeometry = new THREE.ConeBufferGeometry( 0.5, 1, 6);
this._coneGeometry.translate( 0, - 0.5, 0 );
this._axis = new THREE.Vector3();
}
this.position.copy( origin );
this.line = new THREE.Line( this._lineGeometry, new THREE.LineBasicMaterial( { color: color, toneMapped: false, linewidth: 4 } ) );
this.line.matrixAutoUpdate = false;
this.add( this.line )
// base material
this.cone = new THREE.Mesh( this._coneGeometry, new THREE.MeshBasicMaterial( { color: color, toneMapped: false } ) );
this.add(this.cone);
// wire frame
this.wireframe = new THREE.Mesh( this._coneGeometry, new THREE.MeshBasicMaterial( {
color: edgeColor,
toneMapped: false,
wireframe: true,
wireframeLinewidth: 2 } ) );
this.add(this.wireframe);
this.setDirection( dir );
this.setLength( length, headLength, headWidth );
}
setDirection( dir ) {
// dir is assumed to be normalized
if ( dir.y > 0.99999 ) {
this.quaternion.set( 0, 0, 0, 1 );
} else if ( dir.y < - 0.99999 ) {
this.quaternion.set( 1, 0, 0, 0 );
} else {
this._axis.set( dir.z, 0, - dir.x ).normalize();
const radians = Math.acos( dir.y );
this.quaternion.setFromAxisAngle( this._axis, radians );
}
}
setLength( length, headLength, headWidth ) {
if ( headLength === undefined ) headLength = 0.2 * length;
if ( headWidth === undefined ) headWidth = 0.2 * headLength;
this.line.scale.set( 1, Math.max( 0.0001, length - headLength ), 1 ); // see #17458
this.line.updateMatrix();
this.cone.scale.set( headWidth, headLength, headWidth );
this.cone.position.y = length;
this.cone.updateMatrix();
this.wireframe.scale.set( headWidth, headLength, headWidth );
this.wireframe.position.y = length;
this.wireframe.updateMatrix();
}
setColor( color ) {
this.line.material.color.set( color );
// this.cone.material.color.set( color );
// this.wireframe.material.color.set( color );
}
copy( source ) {
super.copy( source, false );
this.line.copy( source.line );
this.cone.copy( source.cone );
this.wireframe.copy( source.wireframe );
return this;
}
}
For some reason linewidth and wireframeLinewidth don't affect lines widths. Any idea why?

edit: A pyramid is a cone with 4 radial segments, if you want that, look at how the arrowhelper constructs it's cone (which is with a tapered CylinderGeometry) and line based on the parameters and replace it with a cone geometry constructed as follows:
original:
_coneGeometry = new CylinderBufferGeometry( 0, 0.5, 1, 5, 1 );
new:
_coneGeometry = new ConeBufferGeometry( 0.5, 1, 4);
Then you don't have to use the EdgesGeometry, but use the wireframe material option (per #prisoner849's comment):
let wireframeMaterial = new THREE.MeshBasicMaterial({color: "aqua", wireframe: true});
let coneEdgeMesh = new THREE.Mesh(_coneGeometry, wireframeMaterial);
Original answer:
THREE.ArrowHelper consists of 2 Object3Ds: one THREE.Line for the line and one THREE.Mesh for the cone of the arrow. The Line geometry only consists of 2 points and has no edges because it is a line, but for the cone you can use:
let coneEdgeGeometry = new THREE.EdgesGeometry(arrow.cone.geometry);
Then you construct a LineSegments object with the edge geometry and the color you want:
let line = new THREE.LineSegments( coneEdgeGeometry, new THREE.LineBasicMaterial( { color: 0xffffff } ) );
arrow.add(line);
If the cone edge is not showing, try setting the renderOrder of the THREE.LineSegments to -1 (this might give other issues)

You can change the colour of arrow's cone like this:
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";
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight,
1, 100);
camera.position.set(0, 5, 10);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
new OrbitControls(camera, renderer.domElement);
scene.add(new THREE.GridHelper());
// different colors
let ah = new THREE.ArrowHelper(
new THREE.Vector3(0, 1, 0),
new THREE.Vector3(-4, 0, 0),
5,
"magenta" /* default colour */);
ah.cone.material.color.set("red"); // change color of cone
scene.add(ah);
// colourful pyramid
let cg = new THREE.SphereBufferGeometry(0.5, 4, 2).toNonIndexed();
let pos = cg.attributes.position;
for (let i = 0; i < pos.count; i++){
if (pos.getY(i) < 0) pos.setY(i, 0);
}
console.log(cg);
let cls = [
new THREE.Color("red"),
new THREE.Color("green"),
new THREE.Color("blue"),
new THREE.Color("yellow")
]
let colors = [];
for(let i = 0; i < 2; i++){
cls.forEach( (c) => {
colors.push(c.r, c.g, c.b);
colors.push(c.r, c.g, c.b);
colors.push(c.r, c.g, c.b);
});
}
cg.setAttribute("color", new THREE.Float32BufferAttribute(colors, 3));
let cm = new THREE.MeshBasicMaterial({vertexColors: true});
let co = new THREE.Mesh(cg, cm);
co.scale.set(1, 5, 1);
scene.add(co);
renderer.setAnimationLoop(()=>{
renderer.render(scene, camera);
});
</script>

Related

How to render caps with clipping planes and stencil in Threejs with outer and inner mesh objects

I’m new to three.js and stackoverflow. I’m trying to clip and cap three.js objects that have been rendered so I can move the helperPlane back and forth through the object to see inside it. There's an object inside it. What I’m looking to do is similar to this description of advanced clipping techniques in OpenGL here: More OpenGL Game Programming - Bonus - Advanced Clip Planes. So, if this can be done in OpenGL, there must be some way to do it in WebGL too?
I adapted the clipping_stencil example from threejs ( webgl - clipping stencil ), and everything looks right as long as I don’t move the helperPlanes. When the helperPlanes are moved, some of the cap faces of the larger mesh disappear, there’s some rendering artifacts-I think this is z-fighting-and the caps might not be rendered in the desired position.
Setting the renderingOrder property for the meshes was the big trick to getting the inner mesh to be rendered in the scene, but I don't know what to do about the z-fighting? when I move the clipping planes on the sliders.
I also posted this on discourse.threejs. Everything is on a JSFiddle. Any help would be greatly appreciated.
import * as THREE from 'three';
import Stats from 'https://threejs.org/examples/jsm/libs/stats.module.js';
import {GUI} from 'https://threejs.org/examples/jsm/libs/lil-gui.module.min.js';
import { OrbitControls } from 'https://threejs.org/examples/jsm/controls/OrbitControls.js';
let camera, scene, renderer, object, object2, stats;
let planes, planeObjects, planeObjects2, planeHelpers;
let clock;
const params = {
animate: false,
planeX: {
constant: 1,
negated: false,
displayHelper: false
},
planeY: {
constant: 1,
negated: false,
displayHelper: false
},
planeZ: {
constant: 0,
negated: false,
displayHelper: false
}
};
init();
animate();
function createPlaneStencilGroup( geometry, plane, renderOrder ) {
const group = new THREE.Group();
const baseMat = new THREE.MeshBasicMaterial();
baseMat.depthWrite = false;
baseMat.depthTest = false;
baseMat.colorWrite = false;
baseMat.stencilWrite = true;
baseMat.stencilFunc = THREE.AlwaysStencilFunc;
/* Subtract the mask created from the front-facing image
from the mask created from the back-facing image, we get
a new mask that represents the area where the clip edge
would be. Set the stencil buffer operation to increment
when rederering back-facing polygons and decrement on
front-facing polygons. This results in the desired mask
stored in the stencil buffer : http://glbook.gamedev.net/GLBOOK/glbook.gamedev.net/moglgp/advclip.html */
// back faces
const mat0 = baseMat.clone();
mat0.side = THREE.BackSide;
mat0.clippingPlanes = [ plane ];
mat0.stencilFail = THREE.IncrementWrapStencilOp;
mat0.stencilZFail = THREE.IncrementWrapStencilOp;
mat0.stencilZPass = THREE.IncrementWrapStencilOp;
//mat0.depthFunc = THREE.LessDepth; // See reference above
const mesh0 = new THREE.Mesh( geometry, mat0 );
mesh0.renderOrder = renderOrder;
group.add( mesh0 );
// front faces
const mat1 = baseMat.clone();
mat1.side = THREE.FrontSide;
mat1.clippingPlanes = [ plane ];
mat1.stencilFail = THREE.DecrementWrapStencilOp;
mat1.stencilZFail = THREE.DecrementWrapStencilOp;
mat1.stencilZPass = THREE.DecrementWrapStencilOp;
//mat1.depthFunc = THREE.LessDepth;
const mesh1 = new THREE.Mesh( geometry, mat1 );
mesh1.renderOrder = renderOrder;
group.add( mesh1 );
return group;
}
function init(){
//clock
clock = new THREE.Clock();
// scene
scene = new THREE.Scene();
// camera
camera = new THREE.PerspectiveCamera(36, window.innerWidth/window.innerHeight, 1,100);
camera.position.set(2,2,2);
// Lights
scene.add(new THREE.AmbientLight(0xffffff, 0.5));
const dirLight = new THREE.DirectionalLight(0xffffff,1);
dirLight.position.set(5,10,7.5);
dirLight.castShadow = true;
dirLight.shadow.camera.right = 2;
dirLight.shadow.camera.left = -2;
dirLight.shadow.camera.top = 2;
dirLight.shadow.camera.bottom = -2;
dirLight.shadow.mapSize.width = 1024;
dirLight.shadow.mapSize.height = 1024;
scene.add(dirLight);
//Clipping planes
planes = [
new THREE.Plane( new THREE.Vector3( - 1, 0, 0 ), 1 ),
new THREE.Plane( new THREE.Vector3( 0, - 1, 0 ), 1 ),
new THREE.Plane( new THREE.Vector3( 0, 0, - 1 ), 0 )
];
planeHelpers = planes.map( p => new THREE.PlaneHelper( p, 2, 0xffffff ) );
planeHelpers.forEach( ph => {
ph.visible = false;
scene.add( ph );
} );
//Inner Cube
const geometry = new THREE.BoxGeometry( 0.5,0.5,0.5 );
//Outer Cube
const geometry2 = new THREE.BoxGeometry( 1,1,1 );
object = new THREE.Group();
scene.add(object);
//Set up clip plane rendering
/*
See https://discourse.threejs.org/t/capping-two-clipped-geometries-using-two-planes-which-are-negated-to-each-other/32643
Object 1
Render order 1: Draw front face / back face clipped and front face
/ back face not clipped (4 meshes)
Render order 2: Draw planar clip cap
Object 2
Render order 3: Draw front face / back face clipped and front face
/ back face not clipped (4 meshes)
Render order 4: Draw planar clip cap
*/
planeObjects = [];
planeObjects2 = [];
const planeGeom = new THREE.PlaneGeometry( 4, 4 );
for ( let i = 0; i < 3; i ++ ) {
const poGroup = new THREE.Group();
const poGroup2 = new THREE.Group()
const plane = planes[ i ];
// Object 1
const stencilGroup = createPlaneStencilGroup( geometry,
plane, i + 4 ); // Render after first group
// Object 2
const stencilGroup2 = createPlaneStencilGroup( geometry2,
plane, i + 1 ); // Render this first
// PLANAR CLIP CAP
// plane is clipped by the other clipping planes
const planeMat =
new THREE.MeshStandardMaterial( {
color: 0xfff000, // inner torus colour
metalness: 0.1,
roughness: 0.75,
clippingPlanes: planes.filter( p => p !== plane ),
//depthFunc: THREE.LessDepth,
stencilWrite: true,
stencilRef: 0,
stencilFunc: THREE.NotEqualStencilFunc,
stencilFail: THREE.ReplaceStencilOp,
stencilZFail: THREE.ReplaceStencilOp,
stencilZPass: THREE.ReplaceStencilOp,
} );
const planeMat2 =
new THREE.MeshStandardMaterial( {
color: 0xff0000, // inner torus colour
metalness: 0.1,
roughness: 0.75,
clippingPlanes: planes.filter( p => p !== plane ),
//depthFunc: THREE.LessDepth,
stencilWrite: true,
stencilRef: 0,
stencilFunc: THREE.NotEqualStencilFunc,
stencilFail: THREE.ReplaceStencilOp,
stencilZFail: THREE.ReplaceStencilOp,
stencilZPass: THREE.ReplaceStencilOp,
} );
const po = new THREE.Mesh( planeGeom, planeMat );
const po2 = new THREE.Mesh( planeGeom, planeMat2 );
po.onAfterRender = function ( renderer ) {
renderer.clearStencil();
};
po2.onAfterRender = function ( renderer ) {
renderer.clearStencil();
};
// Draw Planar Clip Cap
po.renderOrder = i + 4.1; // Render last (slightly)
po2.renderOrder = i + 1.1; // Render slightly after first group
object.add( stencilGroup );
object.add( stencilGroup2 );
poGroup.add( po );
poGroup2.add( po2 );
planeObjects.push( po );
planeObjects2.push( po2 );
scene.add( poGroup );
scene.add( poGroup2 );
}
// Object 1
const material = new THREE.MeshStandardMaterial( {
color: 0xfff000, // outer torus colour
metalness: 0.1,
roughness: 0.75,
clippingPlanes: planes,
clipShadows: true,
shadowSide: THREE.DoubleSide,
} );
// add the color
const clippedColorFront = new THREE.Mesh( geometry, material );
clippedColorFront.castShadow = true;
clippedColorFront.renderOrder = 6;
object.add( clippedColorFront );
// Object 2
const material2 = new THREE.MeshStandardMaterial( {
color: 0xff0000, // outer colour
metalness: 0.1,
roughness: 0.75,
side: THREE.DoubleSide,
clippingPlanes: planes,
clipShadows: true,
shadowSide: THREE.DoubleSide,
} );
// add the color
const clippedColorFront2 = new THREE.Mesh( geometry2, material2 );
clippedColorFront2.castShadow = true;
clippedColorFront2.renderOrder = 3;
object.add( clippedColorFront2 );
//Ground
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(9,9,1,1),
new THREE.MeshPhongMaterial({color:0x999999, opacity:0.25, side:THREE.DoubleSide})
);
ground.rotation.x = - Math.PI/2; // rotates x/y to x/z
ground.position.y = -1;
ground.receiveShadow = true;
scene.add(ground);
//Stats
stats = new Stats();
document.body.appendChild(stats.dom);
//Renderer
renderer = new THREE.WebGLRenderer({antialias:true});
renderer.shadowMap.enabled = true;
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor( 0x263238 );
window.addEventListener('resize',onWindowResize);
document.body.appendChild(renderer.domElement);
renderer.localClippingEnabled = true;
const controls = new OrbitControls(camera, renderer.domElement);
controls.minDistance = 2;
controls.maxDistance = 20;
controls.update();
//GUI
const gui = new GUI();
gui.add(params, 'animate');
const planeX = gui.addFolder( 'planeX' );
planeX.add( params.planeX, 'displayHelper' ).onChange( v => planeHelpers[ 0 ].visible = v );
planeX.add( params.planeX, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 0 ].constant = d );
planeX.add( params.planeX, 'negated' ).onChange( () => {
planes[ 0 ].negate();
params.planeX.constant = planes[ 0 ].constant;
} );
planeX.open();
const planeY = gui.addFolder( 'planeY' );
planeY.add( params.planeY, 'displayHelper' ).onChange( v => planeHelpers[ 1 ].visible = v );
planeY.add( params.planeY, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 1 ].constant = d );
planeY.add( params.planeY, 'negated' ).onChange( () => {
planes[ 1 ].negate();
params.planeY.constant = planes[ 1 ].constant;
} );
planeY.open();
const planeZ = gui.addFolder( 'planeZ' );
planeZ.add( params.planeZ, 'displayHelper' ).onChange( v => planeHelpers[ 2 ].visible = v );
planeZ.add( params.planeZ, 'constant' ).min( - 1 ).max( 1 ).onChange( d => planes[ 2 ].constant = d );
planeZ.add( params.planeZ, 'negated' ).onChange( () => {
planes[ 2 ].negate();
params.planeZ.constant = planes[ 2 ].constant;
} );
planeZ.open();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
function animate() {
const delta = clock.getDelta();
requestAnimationFrame( animate );
if ( params.animate ) {
object.rotation.x += delta * 0.5;
object.rotation.y += delta * 0.2;
}
for ( let i = 0; i < planeObjects.length; i ++ ) {
const plane = planes[ i ];
// Planar clip cap for object 1
const po = planeObjects[ i ];
plane.coplanarPoint( po.position );
// planar clip cap for object 2
const po2 = planeObjects[ i ];
plane.coplanarPoint( po2.position );
// planar clip cap for object 1
po.lookAt(
po.position.x - plane.normal.x,
po.position.y - plane.normal.y,
po.position.z - plane.normal.z,
);
// planar clip cap for object 2
po2.lookAt(
po2.position.x - plane.normal.x,
po2.position.y - plane.normal.y,
po2.position.z - plane.normal.z,
);
}
stats.begin();
renderer.render( scene, camera );
stats.end();
}
I had some success with what I set out to do. This is an updated JSFiddle. I was able to implement capping an object inside another object with clipping and stencils. I included drag and orbit controls and gui to select the plane (x,y,z) to section along. I noticed some strange behaviour in rendering the caps depending on the object position and the rotation of the camera.
I needed to move the object further away from the camera to see the caps rendered when sectioning in the x and y planes, but not z
The caps seemed to disappear like a sliding door if I rotated the camera from positive x to negative x
So I think the caps are rendering in the same place as the clipping plane and depth testing can’t discriminate between the two at some camera points. I think moving the caps away from the clipping plane by some tolerance along a vector normal to the plane will get the caps to render at more angles when I move the camera. I tried this in my animate function:
innerCap.translateOnAxis(clipPlane.normal, -1.5);
This gets the caps to render for a little more of an angle in the direction of negative x. I think this tolerance is some function of the distance from the object to the camera, but I’m not sure how to implement this. Thanks for your help.

Why model renders with a blade color with Three.js?

Hi, I imported my model (obj + mtl + texture) but it renders with a blade color.
Normally it should be like this :
Currently the code of the scene configuration is:
loadModel()
scene.current.background = new THREE.Color( 'transparent' );
scene.current.add(new THREE.AxesHelper( 5 ));
const mesh = new THREE.Mesh( new THREE.PlaneGeometry( 100, 100 ), new THREE.MeshPhongMaterial( { color: 0xffffff, depthWrite: false } ) );
mesh.rotation.x = - Math.PI / 2;
mesh.receiveShadow = true;
scene.current.add( mesh );
controls.current.enableDamping = true; // an animation loop is required when either damping or auto-rotation are enabled
controls.current.dampingFactor = 0.2;
controls.current.screenSpacePanning = false;
controls.current.maxPolarAngle = Math.PI / 2;
controls.current.maxDistance = 200
controls.current.minDistance = 20
controls.current.target = new THREE.Vector3(0, 16, 0)
camera.current.position.set( -3, 17, 8 );
camera.current.lookAt(new THREE.Vector3( 0, 15, 0 ));
controls.current.update();
scene.current.background = new THREE.Color( 0xFFFFFF );
const ambilentLight = new THREE.AmbientLight( 0xffffff, 0.5)
scene.current.add(ambilentLight)
const hemiLight = new THREE.HemisphereLight( 0xffffff, 0xffffff );
hemiLight.position.set( 0, 500, 30 );
hemiLight.castShadow = true
scene.current.add( hemiLight );
scene.current.add(new THREE.HemisphereLightHelper( hemiLight, 5 ));
const dirLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
dirLight.position.set( -10, 50, 50 );
dirLight.castShadow = true;
scene.current.add( dirLight );
scene.current.add(new THREE.DirectionalLightHelper( dirLight, 5 ));
renderer.current.shadowMap.enabled = true;
renderer.current.setPixelRatio( window.devicePixelRatio );
renderer.current.setSize( window.innerWidth, window.innerHeight );
renderer.current.outputEncoding = THREE.sRGBEncoding;
renderer.current.toneMapping = THREE.ACESFilmicToneMapping;
renderer.current.toneMappingExposure = 1;
renderer.current.physicallyCorrectLights = true;
container.current.appendChild(renderer.current.domElement);
window.addEventListener( 'resize', onWindowResize );
animate();
I dont know if it's a problem of lighting or another thing.
Anybody know this problem ?
If you are working with OBJ/MTL and set WebGLRenderer.outputEncoding to THREE.sRGBEncoding;, I suspect the issue is caused by an incomplete color space configuration. You can solve this in two way:
Do no touch outputEncoding.
Set the encoding property of all color textures to THREE.sRGBEncoding;.
Since OBJLoader returns an instance of THREE.Group, you can update the textures like so:
group.traverse( function( object ) {
if ( object.isMesh === true && object.material.map !== null ) {
object.material.map.encoding = THREE.sRGBEncoding;
}
} );
BTW: You normally use tone mapping only if you apply HDR textures to your scene.

Extrude 3d shape from THREE.Line object in three.js

In three.js I have created an ellipseCurve for which I want to extrude and make 3d.
CODE USE TO MAKE THIS:
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
10, 13.3, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
var path = new THREE.Path( curve.getPoints( 100 ) );
var geometrycirc = path.createPointsGeometry( 50 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object to add to the scene
var ellipse = new THREE.Line( geometrycirc, materialcirc );
this.scene.add( ellipse );
I want to use this ellipseCurve as a basis to create an extruded shape similar to these examples.
https://threejs.org/examples/#webgl_geometry_extrude_splines
These examples seem to use vectors to do this, so I assume I need to convert the curve into one.
I am not sure how to do this since I have been unable to find references on this matter.
Any help to do this?
UPDATE: 22/03/2017
Right so I tried to implement the same method of extrusion as found on:
https://threejs.org/examples/#webgl_geometry_extrude_splines
I was able to but this spline into my scene:
HERE IS THE CODE TO DO THIS:
/////////////////////////////////////////////////////////////////////////
// My line curve //
/////////////////////////////////////////////////////////////////////////
var curve = new THREE.EllipseCurve(
0, 0, // ax, aY
10, 13.3, // xRadius, yRadius
0, 2 * Math.PI, // aStartAngle, aEndAngle
false, // aClockwise
0 // aRotation
);
var path = new THREE.Path( curve.getPoints( 100 ) );
var geometrycirc = path.createPointsGeometry( 50 );
var materialcirc = new THREE.LineBasicMaterial( {
color : 0xff0000
} );
// Create the final object based on points and material
var ellipse = new THREE.Line( geometrycirc, materialcirc );
this.scene.add( ellipse );
////////////////////////////////////////////////////////////////////////
// Example of sample closed spine //
////////////////////////////////////////////////////////////////////////
var sampleClosedSpline = new THREE.CatmullRomCurve3( [
new THREE.Vector3( 0, -40, -40 ),
new THREE.Vector3( 0, 40, -40 ),
new THREE.Vector3( 0, 140, -40 ),
new THREE.Vector3( 0, 40, 40 ),
new THREE.Vector3( 0, -40, 40 )
] );
sampleClosedSpline.type = 'catmullrom';
sampleClosedSpline.closed = true;
//////////////////////////////////////////////////////////////////////////////
// Extrusion method to covert the spline/vector data into 3d object //
//////////////////////////////////////////////////////////////////////////////
// I used this method and have tried the following properties but these do not work
//
// var tube = new THREE.TubeBufferGeometry( curve, 12, 2, 20, true);
//
// 1. ellipse.clone()
// 2. geometrycirc.clone()
// 3. materialcirc.clone()
// 4. path.clone()
// 5. curve
//
// Therefore I am either doing something wrong or there must be a further process that needs
// to be implemented.
// this works as standard
var tube = new THREE.TubeBufferGeometry( sampleClosedSpline, 12, 2, 20, true);
var tubeMesh = THREE.SceneUtils.createMultiMaterialObject( tube, [
new THREE.MeshLambertMaterial( {
color: 0xffffff
} ),
new THREE.MeshBasicMaterial( {
color: 0xff00ff,
opacity: 0.3,
wireframe: true,
transparent: true
} ) ] );
tubeMesh.scale.set( .2, .2, .2 );
this.scene.add( tubeMesh );
///////////////////////////////////////////////////////////////////////////////
So when I place the spline property for the one that I have created i get a black screen and the following error msgs:
var curve;
and the other variables used (refer to code to see what I have tried)
EDIT: 23/03/2017
WestLangley's method was the ideal solution
You want to create a TubeGeometry or TubeBufferGeometry in the shape of an ellipse.
Here is one way to do it that is general enough for others to use, too.
First, create a new class that defines your path:
// Ellipse class, which extends the virtual base class Curve
class Ellipse extends THREE.Curve {
constructor( xRadius, yRadius ) {
super();
// add radius as a property
this.xRadius = xRadius;
this.yRadius = yRadius;
}
getPoint( t, optionalTarget = new THREE.Vector3() ) {
const point = optionalTarget;
var radians = 2 * Math.PI * t;
return new THREE.Vector3( this.xRadius * Math.cos( radians ),
this.yRadius * Math.sin( radians ),
0 );
}
}
Then create the geometry from the path.
// path
var path = new Ellipse( 5, 10 );
// params
var pathSegments = 64;
var tubeRadius = 0.5;
var radiusSegments = 16;
var closed = true;
var geometry = new THREE.TubeBufferGeometry( path, pathSegments, tubeRadius, radiusSegments, closed );
Super easy. :)
Fiddle: http://jsfiddle.net/62qhxags/
three.js r.129

three.js fails to render the normals in a THREE.Points Geometry

I am quite new to threejs. I am currently working on a project that needs to render a point cloud using three.js via the Qt5 Canvas3D. According to the examples of threejs.org, I use a BufferGeometry and set its attributes(position and normal). Then I use a THREE.Points and THREE.PointsMaterial to wrap it. The result is that I can render the points in the scene, however, the normals set on each vertex seem to be ignored. The code snippet is shown below:
var vertexPositions = [
[10, 10, 0, 1, 0, 0],
[10, -10, 0, 1, 0, 0],
[-10, -10, 0, 1, 0, 0]
];
geometry = new THREE.BufferGeometry();
var vertices = new Float32Array( vertexPositions.length * 3 );
for ( var i = 0; i < vertexPositions.length; i++ )
{
vertices[ i*3 + 0 ] = vertexPositions[i][0];
vertices[ i*3 + 1 ] = vertexPositions[i][1];
vertices[ i*3 + 2 ] = vertexPositions[i][2];
}
var normals = new Float32Array( vertexPositions.length * 3 );
for ( i = 0; i < vertexPositions.length; i++ )
{
normals[ i*3 + 0 ] = vertexPositions[i][3];
normals[ i*3 + 1 ] = vertexPositions[i][4];
normals[ i*3 + 2 ] = vertexPositions[i][5];
}
var colors = new Float32Array( vertexPositions.length * 3 );
for ( i = 0; i < vertexPositions.length; i++ )
{
colors[ i*3 + 0 ] = 1;
colors[ i*3 + 1 ] = 0;
colors[ i*3 + 2 ] = 0;
}
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
geometry.addAttribute( 'normal', new THREE.BufferAttribute( normals, 3 ) );
geometry.addAttribute( 'color', new THREE.BufferAttribute( colors, 3 ) );
material = new THREE.PointsMaterial({size:50, vertexColors:THREE.VertexColors});
mesh = new THREE.Points(geometry, material);
scene.add(mesh);
How to render the point cloud with normals set on vertices? What am I missing? Any suggestions would be appreciated. Thanks!
You want to render a point cloud and have it interact with lights.
To do so, you must create a custom ShaderMaterial.
In this answer you will find an example of a custom ShaderMaterial that is used with THREE.Points.
three.js r.75

Three.js mesh based on BufferGeometry not appearing

I'm working on a WebGL game using Three.js & I've decided to switch to a THREE.BufferGeometry implementation from my (working) regular THREE.Geometry solution. I'm messing something up, because the mesh does not draw. I've given the relevant parts of my code below. If I switch to a regular geometry, everything works fine.
It's a voxel based game and I've pre-created each face of each cube as a regular THREE.Geometry. The positionVertices function takes the vertices and faces from each face geometry, positions them so that they correspond to the voxel, and generates the buffer data for the THREE.BufferGeometry. There are no errors or warnings, the final mesh just doesn't appear. I suspect my problem has less to do with Three.js and more with my limited understanding of 3D graphics programming. My best guess right now is that it has something to do with the indexes not being correct. If I remove the indexes, the object appears, but half of the triangles have their normals in the opposite direction.
Chunk.prototype.positionVertices = function( position, vertices, faces, vertexBuffer, indexBuffer, normalBuffer, colorBuffer ) {
var vertexOffset = vertexBuffer.length / 3;
for( var i = 0; i < faces.length; ++i ) {
indexBuffer.push( faces[i].a + vertexOffset );
indexBuffer.push( faces[i].b + vertexOffset );
indexBuffer.push( faces[i].c + vertexOffset );
normalBuffer.push( faces[i].vertexNormals[0].x );
normalBuffer.push( faces[i].vertexNormals[0].y );
normalBuffer.push( faces[i].vertexNormals[0].z );
normalBuffer.push( faces[i].vertexNormals[1].x );
normalBuffer.push( faces[i].vertexNormals[1].y );
normalBuffer.push( faces[i].vertexNormals[1].z );
normalBuffer.push( faces[i].vertexNormals[2].x );
normalBuffer.push( faces[i].vertexNormals[2].y );
normalBuffer.push( faces[i].vertexNormals[2].z );
}
var color = new THREE.Color();
color.setRGB( 0, 0, 1 );
for( var i = 0; i < vertices.length; ++i ) {
vertexBuffer.push( vertices[i].x + position.x );
vertexBuffer.push( vertices[i].y + position.y );
vertexBuffer.push( vertices[i].z + position.z );
colorBuffer.push( color.r );
colorBuffer.push( color.g );
colorBuffer.push( color.b );
}
};
// This will need to change when more than one type of block exists.
Chunk.prototype.buildMesh = function() {
var cube = new THREE.Mesh();
var vertexBuffer = []; // [0] = v.x, [1] = v.y, etc
var faceBuffer = [];
var normalBuffer = [];
var colorBuffer = [];
for( var k = 0; k < this.size; ++k )
for( var j = 0; j < this.size; ++j )
for( var i = 0; i < this.size; ++i ) {
// Iterates over all of the voxels in this chunk and calls
// positionVertices( position, vertices, faces, vertexBuffer, indexBuffer, normalBuffer, colorBuffer ) for each face in the chunk
}
var bGeo = new THREE.BufferGeometry();
bGeo.attributes = {
index: {
itemSize: 1,
array: new Uint16Array( faceBuffer ),
numItems: faceBuffer.length
},
position: {
itemSize: 3,
array: new Float32Array( vertexBuffer ),
numItems: vertexBuffer.length
},
normal: {
itemSize: 3,
array: new Float32Array( normalBuffer ),
numItems: normalBuffer.length
},
color: {
itemSize: 3,
array: new Float32Array( colorBuffer ),
numItems: colorBuffer.length
}
}
var mesh = new THREE.Mesh( bGeo, VOXEL_MATERIALS["ROCK"]);
return mesh;
}
I needed to set a single offset on the geometry.
bGeo.offsets = [
{
start: 0,
index: 0,
count: faceBuffer.length
}
];
Fixed it. The triangles are still displaying wrong, so I guess the faces are messed up, but I can figure that out easily enough.

Categories

Resources