1
votes

What I want to achieve is to color the geometry's vertices in a visual way and render ONLY its vertices in Three.js.

Cube in Blender in Vertex Paint mode

What I want to get:

cube with vetext colored in Three.js

I use Blender to mark the color but can't get the vertex colors in Three.js.

My steps:

  1. Make a cube in Blender. Paint each of the 8 vetices a different color in "Vertex Paint" mode in Blender
  2. Export the cube to json file via the Bender addon Three.js Blender Export
  3. Load the json file in Three.js as below:

    (new THREE.JSONLoader()).load('cube.json', function(geometry) {
        console.log(geometry.colors); //an empty array ? why?
    })
    

content of cube.json :

{
    "materials":[],
    "colors":[16725291,16748308,16770898,16720850,5562367,6553492,11599643,2046719,16777215],
    "faces":[131,0,1,2,3,0,0,1,2,3,131,4,7,6,5,0,4,5,6,7,131,0,4,5,1,0,0,4,7,1,131,1,5,6,2,0,1,7,6,2,131,2,6,7,3,0,2,6,8,3,131,4,0,3,7,0,4,0,3,5],
    "vertices":[1,-1,-1,1,-1,1,-1,-1,1,-1,-1,-1,1,1,-1,0.999999,1,1,-1,1,1,-1,1,-1],
    "metadata":{
        "generator":"io_three",
        "materials":0,
        "colors":9,
        "type":"Geometry",
        "vertices":8,
        "faces":6,
        "version":3
    }
}

Is there a way in Three.js to get the vertex colors I paint? or is there another visual method to color the vertices and render it out in Three.js?

1

1 Answers

1
votes

Rendering the vertices of a model as points in three.js is easiest using THREE.PointsMaterial. This material supports per-vertex colors, read from the colors property of the geometry.

However, the tricky part is that while your cube.json contains exactly this set of colors, the THREE JSONLoader interprets them as per-face-vertex colors (for face rendering). We have to convert them back to per-vertex colors in order to render them as part of the vertex point cloud.

// Convert face-vertexcolors to .colors array
geometry.colors = [];
for (var faceIndex = 0; faceIndex < geometry.faces.length; faceIndex++) {
    var face = geometry.faces[faceIndex];
    geometry.colors[face.a] = face.vertexColors[0];
    geometry.colors[face.b] = face.vertexColors[1];
    geometry.colors[face.c] = face.vertexColors[2];
}

// Render mesh as THREE.POINTS
var pointsMaterial = new THREE.PointsMaterial({
    size: 40,
    sizeAttenuation: true,
    vertexColors: THREE.VertexColors // This triggers  actual usage of the colors
});
var mesh = new THREE.Points(geometry, pointsMaterial);
mesh.scale.x = mesh.scale.y = mesh.scale.z = 250;
scene.add(mesh);

Working example: Colored vertices