一、应用场景
如果想实现不给Mesh上材质,且还想让Mesh有颜色,那么可以考虑使用顶点着色方案。通常应用与一下场景:
- Mesh全合并后,上色问题。比如rvt/ifc格式有很多mesh,会引起dc问题,所以可以全部合并Mesh,后通过顶点上色的方案优化帧率。
二、技术测试
下面的代码,创建了8个顶点,给顶点分别上色后,实现了各个三角面的固定颜色、渐变色效果。

var createScene = function () {
var scene = new BABYLON.Scene(engine);
var light = new BABYLON.DirectionalLight("direct", new BABYLON.Vector3(0, 0, 10), scene);
var light1 = new BABYLON.DirectionalLight("direct", new BABYLON.Vector3(0, 0, -10), scene);
var camera = new BABYLON.ArcRotateCamera("camera1", 0, 0, 0, new BABYLON.Vector3(0, 0, 0), scene);
camera.setPosition(new BABYLON.Vector3(0, 5, -30));
camera.attachControl(canvas, true);
var mat = new BABYLON.StandardMaterial('mat'); //这个StandardMaterial 主要打开背面剔除,没其它作用(不显示背面的话,不要也行)
//mat.diffuseColor = new BABYLON.Color3(0, 1, 1); //其漫反射颜色(diffuseColor)直接决定物体基础色。
mat.backFaceCulling = false; //打开背面剔除
mat.vertexColors = true;
//Create a custom mesh
var customMesh = new BABYLON.Mesh("custom", scene);
customMesh.material = mat;
//Set arrays for positions and indices
var positions = [-5, 2, -3, -7, -2, -3, -3, -2, -3, 5, 2, 3, 7, -2, 3, 3, -2, 3, -5, 2, -3, -3, -2, -3, 0, 0, -3]; //9个顶点
var indices = [0, 1, 2, 3, 4, 5, 6, 7, 8]; //3个三角形
var colors = [1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]; //9个顶点,各个顶点的RGBA值
//Empty array to contain calculated values
var normals = [];
var vertexData = new BABYLON.VertexData();
BABYLON.VertexData.ComputeNormals(positions, indices, normals);
//Assign positions, indices and normals to vertexData
vertexData.positions = positions;
vertexData.indices = indices;
vertexData.normals = normals;
vertexData.colors = colors;
//Apply vertexData to custom mesh
vertexData.applyToMesh(customMesh);
return scene;
};