Display Name
Display Name

Reputation: 137

How to create a geometry out of an array in JavaScript with Three.js?

Which one is the best (fastest) method to create a geometry out of this data-array? I create the Array on-the-fly and can also create a object instead of an array. Everything that I can do to improve this would be perfect.

Data (x,y,z):

var data = [            
    [-500,0,-500],
    [-496,0,-500],
    [-492,0,-500],
    //..
    [488,0,496],
    [492,0,496],
    [496,0,496]
];
//data.length: 62500

My way:

var geo = new THREE.Geometry();
for(i = 0; i < data.length; i++)
    geo.vertices.push(data[i][0],data[i][1],data[i][2]);

And then I loop trough all vertices and create the faces to get a terrain (like the following picture, but not flat)

Geometry

Upvotes: 1

Views: 2881

Answers (1)

Brendan Annable
Brendan Annable

Reputation: 2747

If you are looking for speed, I suggest using BufferGeometry.

It uses a flat Float23Array to reduce the cost of sending data to the GPU.

e.g.

var geometry = new THREE.BufferGeometry();
// create a simple square shape. We duplicate the top left and bottom right
// vertices because each vertex needs to appear once per triangle. 
var vertices = new Float32Array([ 
    -1.0, -1.0,  1.0,
     1.0, -1.0,  1.0,
     1.0,  1.0,  1.0,

     1.0,  1.0,  1.0,
    -1.0,  1.0,  1.0,
    -1.0, -1.0,  1.0
]);

// itemSize = 3 because there are 3 values (components) per vertex
geometry.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
var material = new THREE.MeshBasicMaterial( { color: 0xff0000 } );
var mesh = new THREE.Mesh( geometry, material );

Source https://threejs.org/docs/#api/en/core/BufferGeometry

Upvotes: 4

Related Questions