clipLine method
bool
clipLine(
- Vector4 s1,
- Vector4 s2
)
Implementation
bool clipLine(Vector4 s1, Vector4 s2) {
double alpha1 = 0;
double alpha2 = 1; // Calculate the boundary coordinate of each vertex for the near and far clip planes,
// Z = -1 and Z = +1, respectively.
num bc1near = s1.z + s1.w, bc2near = s2.z + s2.w, bc1far = -s1.z + s1.w, bc2far = -s2.z + s2.w;
if (bc1near >= 0 && bc2near >= 0 && bc1far >= 0 && bc2far >= 0) {
// Both vertices lie entirely within all clip planes.
return true;
} else if (bc1near < 0 && bc2near < 0 || bc1far < 0 && bc2far < 0) {
// Both vertices lie entirely outside one of the clip planes.
return false;
} else {
// The line segment spans at least one clip plane.
if (bc1near < 0) {
// v1 lies outside the near plane, v2 inside
alpha1 = Math.max(alpha1, bc1near / (bc1near - bc2near));
} else if (bc2near < 0) {
// v2 lies outside the near plane, v1 inside
alpha2 = Math.min(alpha2, bc1near / (bc1near - bc2near));
}
if (bc1far < 0) {
// v1 lies outside the far plane, v2 inside
alpha1 = Math.max(alpha1, bc1far / (bc1far - bc2far));
} else if (bc2far < 0) {
// v2 lies outside the far plane, v2 inside
alpha2 = Math.min(alpha2, bc1far / (bc1far - bc2far));
}
if (alpha2 < alpha1) {
// The line segment spans two boundaries, but is outside both of them.
// (This can't happen when we're only clipping against just near/far but good
// to leave the check here for future usage if other clip planes are added.)
return false;
} else {
// Update the s1 and s2 vertices to match the clipped line segment.
s1.lerp(s2, alpha1);
s2.lerp(s1, 1 - alpha2);
return true;
}
}
}