SolidToMeshTool.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. /*
  2. * SolidToMeshTool.js
  3. *
  4. * @author realor
  5. */
  6. import { Tool } from './Tool.js'
  7. import { Selection } from '../utils/Selection.js'
  8. import { ObjectUtils } from '../utils/ObjectUtils.js'
  9. import { Solid } from '../core/Solid.js'
  10. import * as THREE from '../lib/three.module.js'
  11. class SolidToMeshTool extends Tool {
  12. constructor(application, options) {
  13. super(application)
  14. this.name = 'solid_to_mesh'
  15. this.label = 'tool.solid_to_mesh.label'
  16. this.help = 'tool.solid_to_mesh.help'
  17. this.className = 'solid_to_mesh'
  18. this.setOptions(options)
  19. this.immediate = true
  20. }
  21. execute() {
  22. const application = this.application
  23. const roots = application.selection.roots
  24. const newRoots = this.convert(roots)
  25. application.selection.set(...newRoots)
  26. }
  27. convert(roots) {
  28. const replacements = new Map()
  29. const application = this.application
  30. const parents = new Selection()
  31. for (let root of roots) {
  32. parents.add(root.parent)
  33. this.traverse(root, replacements)
  34. }
  35. application.baseObject.traverse(object => {
  36. if (object.builder) {
  37. let updated = object.builder.updateReferences(object, ref => replacements.get(ref) || null)
  38. if (updated) {
  39. object.needsRebuild = true
  40. }
  41. }
  42. })
  43. const changed = parents.roots
  44. application.notifyObjectsChanged(changed, this, 'structureChanged')
  45. return roots.map(object => replacements.get(object) || object)
  46. }
  47. traverse(object, replacements) {
  48. if (object instanceof Solid) {
  49. let solid = object
  50. let mesh = this.solidToMesh(solid)
  51. replacements.set(solid, mesh)
  52. } else {
  53. let children = object.children
  54. for (let child of children) {
  55. this.traverse(child, replacements)
  56. }
  57. }
  58. }
  59. solidToMesh(solid) {
  60. const parent = solid.parent
  61. const parentIndex = parent.children.indexOf(solid)
  62. let mesh = new THREE.Mesh()
  63. mesh.geometry.copy(solid.geometry)
  64. parent.children[parentIndex] = mesh
  65. mesh.name = solid.name
  66. mesh.userData = solid.userData
  67. mesh.visible = solid.visible && solid.facesVisible
  68. mesh.parent = parent
  69. solid.matrix.decompose(mesh.position, mesh.rotation, mesh.scale)
  70. mesh.updateMatrix()
  71. if (solid.material) mesh.material = solid.material
  72. solid.parent = null
  73. ObjectUtils.dispose(solid)
  74. return mesh
  75. }
  76. }
  77. export { SolidToMeshTool }