| 436 | // Compute normal of any polygon. Uses normalized vector cross product. |
| 437 | // Mutates `normalName` property of given `poly`. |
| 438 | function computePolyNormal(poly, normalName) { |
| 439 | // Store quick refs to vertices |
| 440 | const v1 = poly.vertices[0]; |
| 441 | const v2 = poly.vertices[1]; |
| 442 | const v3 = poly.vertices[2]; |
| 443 | // Calculate difference of vertices, following winding order. |
| 444 | const ax = v1.x - v2.x; |
| 445 | const ay = v1.y - v2.y; |
| 446 | const az = v1.z - v2.z; |
| 447 | const bx = v1.x - v3.x; |
| 448 | const by = v1.y - v3.y; |
| 449 | const bz = v1.z - v3.z; |
| 450 | // Cross product |
| 451 | const nx = ay*bz - az*by; |
| 452 | const ny = az*bx - ax*bz; |
| 453 | const nz = ax*by - ay*bx; |
| 454 | // Compute magnitude of normal and normalize |
| 455 | const mag = Math.hypot(nx, ny, nz); |
| 456 | const polyNormal = poly[normalName]; |
| 457 | polyNormal.x = nx / mag; |
| 458 | polyNormal.y = ny / mag; |
| 459 | polyNormal.z = nz / mag; |
| 460 | } |
| 461 | |
| 462 | // Apply translation/rotation/scale to all given vertices. |
| 463 | // If `vertices` and `target` are the same array, the vertices will be mutated in place. |