modeling/src/primitives/cuboid.js

  1. const geom3 = require('../geometries/geom3')
  2. const poly3 = require('../geometries/poly3')
  3. const { isNumberArray } = require('./commonChecks')
  4. /**
  5. * Construct an axis-aligned solid cuboid in three dimensional space.
  6. * @param {Object} [options] - options for construction
  7. * @param {Array} [options.center=[0,0,0]] - center of cuboid
  8. * @param {Array} [options.size=[2,2,2]] - dimensions of cuboid; width, depth, height
  9. * @returns {geom3} new 3D geometry
  10. * @alias module:modeling/primitives.cuboid
  11. *
  12. * @example
  13. * let myshape = cuboid({size: [5, 10, 5]})
  14. */
  15. const cuboid = (options) => {
  16. const defaults = {
  17. center: [0, 0, 0],
  18. size: [2, 2, 2]
  19. }
  20. const { center, size } = Object.assign({}, defaults, options)
  21. if (!isNumberArray(center, 3)) throw new Error('center must be an array of X, Y and Z values')
  22. if (!isNumberArray(size, 3)) throw new Error('size must be an array of width, depth and height values')
  23. if (!size.every((n) => n >= 0)) throw new Error('size values must be positive')
  24. // if any size is zero return empty geometry
  25. if (size[0] === 0 || size[1] === 0 || size[2] === 0) return geom3.create()
  26. const result = geom3.create(
  27. // adjust a basic shape to size
  28. [
  29. [[0, 4, 6, 2], [-1, 0, 0]],
  30. [[1, 3, 7, 5], [+1, 0, 0]],
  31. [[0, 1, 5, 4], [0, -1, 0]],
  32. [[2, 6, 7, 3], [0, +1, 0]],
  33. [[0, 2, 3, 1], [0, 0, -1]],
  34. [[4, 5, 7, 6], [0, 0, +1]]
  35. ].map((info) => {
  36. const points = info[0].map((i) => {
  37. const pos = [
  38. center[0] + (size[0] / 2) * (2 * !!(i & 1) - 1),
  39. center[1] + (size[1] / 2) * (2 * !!(i & 2) - 1),
  40. center[2] + (size[2] / 2) * (2 * !!(i & 4) - 1)
  41. ]
  42. return pos
  43. })
  44. return poly3.create(points)
  45. })
  46. )
  47. return result
  48. }
  49. module.exports = cuboid