Display wireframe and solid color
To do that, a possibility is to use a GLSL fragment shader that changes the fragment color when the fragment is near one edge of the triangle. Here is the GLSL shader that I am using. As input, it takes the barycentric coordinates of the fragment in the triangle, and an edge mask that selects for each edge whether it should be drawn or not. (rem: I had to use it with the compatibility profile for backward compatibility reasons, if you do not want to do that, it can easily be adapted):
(fragment source)
#version 150 compatibility
flat in float diffuse;
flat in float specular;
flat in vec3 edge_mask;
in vec2 bary;
uniform float mesh_width = 1.0;
uniform vec3 mesh_color = vec3(0.0, 0.0, 0.0);
uniform bool lighting = true;
out vec4 frag_color;
float edge_factor(){
vec3 bary3 = vec3(bary.x, bary.y, 1.0-bary.x-bary.y);
vec3 d = fwidth(bary3);
vec3 a3 = smoothstep(vec3(0.0,0.0,0.0), d*mesh_width, bary3);
a3 = vec3(1.0, 1.0, 1.0) - edge_mask + edge_mask*a3;
return min(min(a3.x, a3.y), a3.z);
}
void main() {
float s = (lighting && gl_FrontFacing) ? 1.0 : -1.0;
vec4 Kdiff = gl_FrontFacing ?
gl_FrontMaterial.diffuse : gl_BackMaterial.diffuse;
float sdiffuse = s * diffuse;
vec4 result = vec4(0.1, 0.1, 0.1, 1.0);
if(sdiffuse > 0.0) {
result += sdiffuse*Kdiff +
specular*gl_FrontMaterial.specular;
}
frag_color = (mesh_width != 0.0) ?
mix(vec4(mesh_color,1.0),result,edge_factor()) :
result;
}
To render both a model and its wireframe, you can use a pattern like this one:
// mesh
var material = new THREE.MeshPhongMaterial( {
color: 0xff0000,
polygonOffset: true,
polygonOffsetFactor: 1, // positive value pushes polygon further away
polygonOffsetUnits: 1
} );
var mesh = new THREE.Mesh( geometry, material );
scene.add( mesh )
// wireframe
var geo = new THREE.EdgesGeometry( mesh.geometry ); // or WireframeGeometry
var mat = new THREE.LineBasicMaterial( { color: 0xffffff } );
var wireframe = new THREE.LineSegments( geo, mat );
mesh.add( wireframe );
The use of polygonOffset
will help prevent z-fighting between the mesh material and the wireframe line. Consequently, the wireframe will look a lot better.
three.js r.126
This can also be achieved with WireframeGeometry: https://threejs.org/docs/#api/en/geometries/WireframeGeometry. (and give plane and line the same position, you can also play with opacity see the docs).
let geometryWithFillAndWireFrame = () => {
let geometry = new THREE.PlaneGeometry(250, 250, 10, 10);
let material = new THREE.MeshBasicMaterial( { color: 0xd3d3d3} );
let plane = new THREE.Mesh(geometry, material);
scene.add(plane);
let wireframe = new THREE.WireframeGeometry( geometry );
let line = new THREE.LineSegments( wireframe );
line.material.color.setHex(0x000000);
scene.add(line);
};