// create scene with sphere
NewScene( null, false );
CreatePrim("Sphere", "MeshSurface", null, null);
// get selected elements from scene
if ( Selection.count == 0 ) {
LogMessage( "Nothing selected", siError );
} else {
var objs = Selection;
// get selected meshes from selection list
var meshes = SIFilter( objs, "polygon_mesh", true, siQuickSearch );
if ( !meshes ) {
LogMessage( "No polygon meshes selected", siError );
}
// process selected models
freezeNormalColors( meshes );
}
function freezeNormalColors( objs )
{
// process all meshes
for ( var i = 0; i < objs.count; i++ ) {
// get current mesh (type : "polyMsh")
var obj = objs( i );
// get obj material
var mat = obj.Material;
// if material is not local add one
if ( mat.IsA(siSharedPSet) ) {
mat = obj.AddMaterial();
}
// get polygon mesh geometry
var polymesh = obj.ActivePrimitive.Geometry;
// get current vertex color property
var vc = polymesh.CurrentVertexColor;
// current vertex color property not set yet
if ( vc == null ) {
// no vertex color properties installed, add one.
vc = polymesh.AddVertexColor();
// set the vertex color to be used by the polgon obj's
// material.
polymesh.CurrentVertexColor = vc;
}
// set vertex colours from shading normal vectors
// the parent of the vertex color is
// a cluster. This maintains the relationship
// between the actual node index and the corresponding
// cluster index.
var vcClsElems = vc.parent.elements;
var nodes2 = new VBArray( vc.Elements.Array );
var nodes = nodes2.toArray();
var clsElemIndex = 0;
// visit all polygons
for ( var j = 0; j < polymesh.Polygons.Count; j++ ) {
// get pointer on polygon
poly = polymesh.Polygons( j );
// visit all polynodes
var polynodes = poly.Nodes
for ( var k = 0; k < polynodes.Count; k++ ) {
var node = polynodes( k );
// get polynode normal
var normal = node.normal;
// lookup node index for vertex color
clsElemIndex = vcClsElems.FindIndex( node.Index ) * 4;
// compute corresponding color channels
nodes[ clsElemIndex ] = ( normal.x + 1.0 ) * 0.5;
nodes[ clsElemIndex + 1 ] = ( normal.y + 1.0 ) * 0.5;
nodes[ clsElemIndex + 2 ] = ( normal.z + 1.0 ) * 0.5;
nodes[ clsElemIndex + 3 ] = 1.0;
}
}
// put the new colors back into the vertex colour
vc.Elements.Array = nodes;
}
return;
} |