UNPKG

awv3

Version:
1,420 lines (1,226 loc) 47.6 kB
import _regeneratorRuntime from "@babel/runtime/regenerator"; import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator"; import _extends from "@babel/runtime/helpers/extends"; import _inheritsLoose from "@babel/runtime/helpers/inheritsLoose"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; var _class, _temp; import * as THREE from 'three'; import Trackball from '../../controls/trackball'; import Orbit from '../../controls/orbit'; import { Button, Checkbox, Console, Group, Label, Link, Selection, Slider, Spacer, Divider } from '../../session/elements'; import { arrayDiff, createObserver } from '../../session/helpers'; //import Selector from '../../session/selection/selector'; import Selector from '../../session/selector'; import Plugin from '../../session/plugin'; import { actions as connectionActions } from '../../session/store/connections'; import Object3 from '../../three/object3'; import Dimensions from '../dimensions/'; import Ccref from './ccref'; import ConstraintGenerator from './constraint/generator'; import * as ConstraintType from './constraint/type'; import ConstraintVisualizer from './constraint/visualizer'; import commandRunner from './command/commandrunner'; import { addCommand, removeCommands, setPlaneCommands, createAndSetPlaneCommands } from './command/highlevel'; import { CopyObjects, IdToReal, MoveObjects, Recalc, SolveConstraints, GetLoop, UpdateSketchRegion, UpdateWorkAxis, CreateNewExtrusion, CreateNewRevolve, UpdateDimensions, Return, Sequence, GlobalObjId } from './command/lowlevel'; import MultiRunner from './command/multirunner'; import { Graphics } from './graphics'; import Handler from './handlers'; import DuplicateHandler from './handlers/duplicate'; //import help from './help'; var resourcesPaths = { 'help': 'help.png', 'cancel': 'cancel.png', 's': 's.png', 'ac': 'ac.png', 'duplicate': 'duplicate.png', 'line': 'line.png', 'point': 'point.png', 'arc-center': 'TODO/arc-center.png', 'arc-3points': 'arc-3points.png', 'arc-tangential': 'arc-tangential.png', 'circle-center-radius': 'circle-center-radius.png', 'fillet-sketch': 'fillet-sketch.png', 'trim': 'sketch.png', 'fixation': 'fixation.png', 'horizontality': 'horizontality.png', 'verticality': 'verticality.png', 'incidence': 'coincident.png', 'tangency': 'tangency.png', 'parallelity': 'parallelity.png', 'perpendicularity': 'perpendicularity.png', 'colinear': 'colinear.png', 'concentric': 'concentric.png', 'midpoint': 'midpoint.png', 'symmetric': 'symmetric.png', 'equalDistance': 'equal.png', 'equalRadius': 'equal.png', 'horizontalDistance': 'hdimension.png', 'verticalDistance': 'vdimension.png', 'distance': 'dimension.png', 'radius': 'TODO/radius.png', 'diameter': 'dimension.png', 'angle': 'TODO/angle.png', 'angleox': 'TODO/angleox.png' }; var resources = {}; for (var name in resourcesPaths) { var path = resourcesPaths[name]; resources[name] = require('!!url-loader!awv3-icons/32x32/' + path); } var textures = {}, textureLoader = new THREE.TextureLoader(); var _loop = function _loop(url, _name) { textures[_name] = new Promise(function (resolve, reject) { return textureLoader.load(url, resolve, undefined, reject); }); }; var _arr = Object.entries(resources); for (var _i = 0; _i < _arr.length; _i++) { var _ref = _arr[_i]; var _name = _ref[0]; var url = _ref[1]; _loop(url, _name); } var defaultGraphicsScale = 0.1; var Sketcher = (_temp = _class = /*#__PURE__*/ function (_Plugin) { _inheritsLoose(Sketcher, _Plugin); function Sketcher(session, args) { var _this; _this = _Plugin.call(this, session, _extends({ type: 'Sketch', icon: 'sketch', resources: resources }, args)) || this; Object.defineProperty(_assertThisInitialized(_this), "clearGraphics", { configurable: true, enumerable: true, writable: true, value: function value() { var revGraphicIds = Array.from(_this.graphics.keys()); revGraphicIds.forEach(function (id) { return _this.onSketchObjectRemove(id, false); }); } }); Object.defineProperty(_assertThisInitialized(_this), "switchToPrevFeature", { configurable: true, enumerable: true, writable: true, value: function value() { var activateFeatureInfo = _this.connection.getState().activeFeatureActivationInfo; if (activateFeatureInfo === undefined) return; var prevFeatureId = activateFeatureInfo.prevFeatureId; _this.store.dispatch(connectionActions.setActiveFeature(_this.connection.id, prevFeatureId)); } }); _this.activeSketch = new Ccref(_assertThisInitialized(_this), _this.feature); _this.autoconstraintIncremental = true; _this.constraintVisualizer = new ConstraintVisualizer(_assertThisInitialized(_this)); _this.dimension = new Dimensions(_this.session, { name: 'Dimensions', recalc: false, collapsed: true, closeable: false, parent: _this.id }); _this.dimension.afterSetCallback = function (arg) { if (arg === undefined) { //user dragged position handle! if (!_this.solveIncremental) _this.namedElements.incremental.value = 1; } _this.incrementalSolveConstraints(); }; _this.dimension.sketcher = _assertThisInitialized(_this); _this.dependencies.push(_this.dimension); _this.graphics = new Map(); _this.graphicScale = defaultGraphicsScale; //radius of a sketch point _this.gridStep = 0.1; //size of grid cell _this.multiRunner = new MultiRunner(commandRunner.bind(undefined, _this.connection)); _this.onPlaneChange = _this.onPlaneChange.bind(_assertThisInitialized(_this)); _this.onSketchObjectChange = _this.onSketchObjectChange.bind(_assertThisInitialized(_this)); _this.onSketchObjectRemove = _this.onSketchObjectRemove.bind(_assertThisInitialized(_this)); _this.recalcIncremental = false; /*this.selector = new Selector(session); this.selector.hoveredProps = { ...this.selector.hoveredProps, polygonOffsetFactor: -10, polygonOffsetUnits: -50, }; this.selector.selectedProps = { ...this.selector.selectedProps, polygonOffsetFactor: -5, polygonOffsetUnits: -25, };*/ /*this.selector = new Selector(session, { name: 'Selection', types: ['SketcherMesh', 'DimensionHandle'], whitelist: ['SketcherMesh', 'DimensionHandle'], target: new THREE.Object3D(), }); this.dimension.selector = this.selector;*/ _this.solveIncremental = false; _this.textures = textures; _this.transientGeomParams = new Map(); _this.instantiated = false; _this.addElements(); _this.connection.observe(function (state) { var _state$tree$_this$fea, _state$tree$_this$fea2; return (_state$tree$_this$fea = (_state$tree$_this$fea2 = state.tree[_this.feature]) === null || _state$tree$_this$fea2 === void 0 ? void 0 : _state$tree$_this$fea2.visible) !== null && _state$tree$_this$fea !== void 0 ? _state$tree$_this$fea : false; }, function (visible) { console.log('sketch instantiated: ' + _this.instantiated); if (_this.instantiated) return; var sketchObj = _this.session.tree[_this.activeSketch.id]; if (visible) { _this.onSketchObjectChange(sketchObj); } else { _this.clearGraphics(); } }, { fireOnStart: false }); return _this; } var _proto = Sketcher.prototype; _proto.addElements = function addElements() { var GF = Group.Format, BF = Button.Format; this.namedElements = { plane: new Selection(this, { name: 'plane', active: false, types: ['Mesh'], limit: 1 }), //selection: new Selection(this, { name: 'Selection', types: ['SketcherMesh', 'DimensionHandle'] }), console: new Console(this, { name: 'Console' }), dimension: new Link(this, { name: 'Dimensions', value: this.dimension.id, collapsable: true }), incremental: new Slider(this, { name: 'Increment', value: Math.max(1 * this.solveIncremental, 2 * this.recalcIncremental), max: 2, positions: { 0: 'None', 1: 'Solve', 2: 'Recalc' } }), constrvis: new Slider(this, { name: 'Constraints', value: this.constraintVisualizer.mode, max: 2, positions: { 0: 'Never', 1: 'Hover', 2: 'Always' } }), handlers: { drag: new Button(this, { format: BF.Toggle, name: 'drag' }), point: new Button(this, { format: BF.Toggle, name: 'point', icon: 'point' }), line: new Button(this, { format: BF.Toggle, name: 'line', icon: 'line' }), arccenter: new Button(this, { format: BF.Toggle, name: 'arc center', icon: 'arc-center' }), arcmiddle: new Button(this, { format: BF.Toggle, name: 'arc middle', icon: 'arc-3points' }), arctangent: new Button(this, { format: BF.Toggle, name: 'arc tangent', icon: 'arc-tangential' }), circle: new Button(this, { format: BF.Toggle, name: 'circle', icon: 'circle-center-radius' }), fillet: new Button(this, { format: BF.Toggle, name: 'fillet', icon: 'fillet-sketch' }), duplicate: new Button(this, { format: BF.Toggle, name: 'duplicate', icon: 'duplicate' }), trim: new Button(this, { format: BF.Toggle, name: 'trim', icon: 'trim' }) }, constraints: { incidence: new Button(this, { name: 'incidence', icon: 'incidence' }), tangency: new Button(this, { name: 'tangency', icon: 'tangency' }), verticality: new Button(this, { name: 'verticality', icon: 'verticality' }), horizontality: new Button(this, { name: 'horizontality', icon: 'horizontality' }), parallelity: new Button(this, { name: 'parallelity', icon: 'parallelity' }), perpendicularity: new Button(this, { name: 'perpendicularity', icon: 'perpendicularity' }), fixation: new Button(this, { name: 'fixation', icon: 'fixation' }), colinear: new Button(this, { name: 'colinear', icon: 'colinear' }), concentric: new Button(this, { name: 'concentric', icon: 'concentric' }), midpoint: new Button(this, { name: 'midpoint', icon: 'midpoint' }), symmetric: new Button(this, { name: 'symmetric', icon: 'symmetric' }), equalDistance: new Button(this, { name: 'equal length', icon: 'equalDistance' }), equalRadius: new Button(this, { name: 'equal radius', icon: 'equalRadius' }), distance: new Button(this, { name: 'distance', icon: 'distance' }), horizontalDistance: new Button(this, { name: 'horizontal distance', icon: 'horizontalDistance' }), verticalDistance: new Button(this, { name: 'vertical distance', icon: 'verticalDistance' }), radius: new Button(this, { name: 'radius', icon: 'radius' }), diameter: new Button(this, { name: 'diameter', icon: 'diameter' }), angle: new Button(this, { name: 'angle', icon: 'angle' }), angleox: new Button(this, { name: 'angleox', icon: 'angleox' }) }, actions: { solve: new Button(this, { name: 'Solve', icon: 's' }), autoconstr: new Button(this, { name: 'Autoconstr', icon: 'ac' }), delete: new Button(this, { name: 'Delete', icon: 'cancel' }), help: new Button(this, { name: /*help*/ 'Help', icon: 'help' }) }, solids: { getLoop: new Button(this, { name: 'Get Loop', icon: 'ac' }), extrude: new Button(this, { name: 'Extrude', icon: 'extrusion' }), revolve: new Button(this, { format: BF.Toggle, name: 'Revolve', icon: 'revolve' }), finishSketchRegionMode: new Button(this, { name: 'Finish Sketch Region Editing', icon: 'chamfer', visible: false }) }, coordinateShower: { xLabel: new Label(this, { value: 'X', header: true, flex: 'inherit' }), xCoord: new Label(this, { value: 0, flex: 1 }), yLabel: new Label(this, { value: 'Y', header: true, flex: 'inherit' }), yCoord: new Label(this, { value: 0, flex: 1 }) } }; this.namedElements.handlers.revolve = this.namedElements.solids.revolve; this.namedElements.arcs = new Button(this, { format: BF.Menu, name: 'arctangent', icon: 'arc-tangential', children: [new Group(this, { name: 'arc group', format: GF.Buttons, children: [this.namedElements.handlers.arctangent, this.namedElements.handlers.arccenter, this.namedElements.handlers.arcmiddle, this.namedElements.handlers.circle] })] }); this.namedElements.toolsGroup = new Group(this, { name: 'Tools', format: GF.Buttons, children: [this.namedElements.handlers.point, this.namedElements.handlers.line, this.namedElements.arcs, this.namedElements.handlers.fillet, this.namedElements.handlers.duplicate, this.namedElements.handlers.trim], limit: 7 }); this.namedElements.actionsGroup = new Group(this, { name: 'Actions', format: GF.Buttons, children: Object.values(this.namedElements.actions), limit: 7 }); this.namedElements.solidsGroup = new Group(this, { name: 'Solids', format: GF.Buttons, children: Object.values(this.namedElements.solids), limit: 7 }); Object.values(this.namedElements.constraints).forEach(function (item) { return item.visible = false; }); this.namedElements.constraintsGroup = new Group(this, { name: 'Constraints', format: GF.Buttons, children: Object.values(this.namedElements.constraints), limit: 7, visible: false }); this.namedElements.mouseGroup = new Group(this, { name: 'Mouse', format: GF.Rows, children: [this.namedElements.coordinateShower.xLabel, this.namedElements.coordinateShower.xCoord, this.namedElements.coordinateShower.yLabel, this.namedElements.coordinateShower.yCoord] }); this.addElement(new Group(this, { format: GF.Table, children: [this.namedElements.plane, this.namedElements.incremental, this.namedElements.constrvis, this.namedElements.toolsGroup, this.namedElements.actionsGroup, this.namedElements.solidsGroup, this.namedElements.constraintsGroup, this.namedElements.console, this.namedElements.mouseGroup] })); this.setCursorCoordinates(undefined); this.addElement(this.namedElements.dimension); }; _proto.getSelected = function getSelected() { var _this2 = this; return this.selector.selectedIds.map(function (id) { return new Ccref(_this2, id); }); }; _proto.getSelectedIds = function getSelectedIds() { return this.selector.selectedIds.map(function (id) { return id; }); }; _proto.observeElements = function observeElements() { var _this3 = this; var value = function value(s) { return s.value; }, click = function click(s) { return s.lastEvent; }, items = function items(s) { return s.items; }; this.namedElements.plane.observe(items, function (x) { return _this3.setPlaneFromSelection(); }); this.selector.on(['add', 'remove', 'removeAll'], function () { var entities = _this3.getSelected(); var items = Object.entries(_this3.namedElements.constraints); for (var _i2 = 0; _i2 < items.length; _i2++) { var _ref2 = items[_i2]; var _name2 = _ref2[0]; var element = _ref2[1]; element.visible = Boolean(ConstraintType[_name2].adapt(entities)); } _this3.namedElements.constraintsGroup.visible = items.some(function (_ref3) { var name = _ref3[0], element = _ref3[1]; return element.visible; }); var someLineSelected = false; entities.forEach(function (entity) { someLineSelected = entity.isCurve() ? true : someLineSelected; }); _this3.namedElements.solids.extrude.active = someLineSelected; _this3.namedElements.solids.revolve.active = someLineSelected; _this3.namedElements.solids.getLoop.active = someLineSelected; _this3.namedElements.solids.finishSketchRegionMode.active = someLineSelected; }); this.namedElements.console.observe(click, /*#__PURE__*/ function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee(event) { return _regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (!(event.key === 'Enter' && event.target)) { _context.next = 5; break; } _context.next = 3; return _this3.activeHandler.consoleExecute(event.target.value); case 3: _this3.namedElements.console.value = ''; _this3.refresh(); case 5: case "end": return _context.stop(); } } }, _callee, this); })); return function (_x) { return _ref4.apply(this, arguments); }; }()); this.namedElements.console.observe(value, /*#__PURE__*/ function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee2(x) { var completions; return _regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: completions = _this3.activeHandler.consoleComplete(x); _this3.namedElements.console.items = completions.filter(function (c) { return c.trim() !== ''; }); _this3.activeHandler.parseRestrictions(x); _this3.refresh(); case 4: case "end": return _context2.stop(); } } }, _callee2, this); })); return function (_x2) { return _ref5.apply(this, arguments); }; }()); this.namedElements.incremental.observe(value, function (x) { _this3.solveIncremental = x >= 1; _this3.recalcIncremental = x >= 2; _this3.incrementalSolveConstraints(); }); this.namedElements.constrvis.observe(value, function (x) { return _this3.constraintVisualizer.updateAll(x); }); this.namedElements.arcs.observe(click, function (x) { var button = _this3.namedElements.handlers[_this3.namedElements.arcs.name]; button.value = !button.value; }); var _loop2 = function _loop2(archandler) { var arcelement = _this3.namedElements.handlers[archandler]; arcelement.observe(click, function (x) { _this3.namedElements.arcs.name = archandler; _this3.namedElements.arcs.icon = arcelement.icon; }); }; var _arr2 = ['arctangent', 'arccenter', 'arcmiddle', 'circle']; for (var _i3 = 0; _i3 < _arr2.length; _i3++) { var archandler = _arr2[_i3]; _loop2(archandler); } var _loop3 = function _loop3(handler, element) { if (handler !== 'duplicate' && handler !== 'revolve') element.observe(value, function (flag) { return _this3.onHandlerToggle(handler, flag); }); }; var _arr3 = Object.entries(this.namedElements.handlers); for (var _i4 = 0; _i4 < _arr3.length; _i4++) { var _ref6 = _arr3[_i4]; var handler = _ref6[0]; var element = _ref6[1]; _loop3(handler, element); } this.namedElements.handlers.duplicate.observe(value, function (flag) { if (flag) { var objects = _this3.getSelected(); objects = DuplicateHandler.normalizeSelection(objects); if (objects.length > 0) { _this3.onHandlerToggle('duplicate', true); _this3.activeHandler.init(objects); } else _this3.namedElements.handlers.duplicate.value = false; } else _this3.onHandlerToggle('duplicate', false); }); this.namedElements.handlers.revolve.observe(value, function (flag) { return _this3.onHandlerToggle('revolve', flag, { selectedObjs: _this3.getSelected() }); }); var _loop4 = function _loop4(constraint, element) { element.observe(click, /*#__PURE__*/ function () { var _ref8 = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee3(x) { var ct, entities, value, oldHandler, cmd, dimId; return _regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: ct = ConstraintType[constraint]; entities = ct.adapt(_this3.getSelected()), value = {}; if (!(ct.type === 'CC_2DAngleConstraint')) { _context3.next = 13; break; } _this3.activeHandler.removeInteractions(); oldHandler = _this3.activeHandler; _this3.activeHandler = Handler(_this3, 'angle'); _this3.activeHandler.setLines(entities); _context3.next = 9; return new Promise(function (resolve) { return _this3.activeHandler.resolve = resolve; }); case 9: value = _context3.sent; _this3.activeHandler.destroy(); _this3.activeHandler = oldHandler; _this3.activeHandler.addInteractions(); case 13: if (entities) { _context3.next = 15; break; } return _context3.abrupt("return"); case 15: _this3.selector.unselectAll().removeAll(); if (value) { _context3.next = 18; break; } return _context3.abrupt("return"); case 18: // cancelled angle cmd = addCommand(_this3.activeSketch, { class: ct.type, entities: entities, value: value }); if (ct.isParametric) cmd = IdToReal(cmd); dimId = _this3.run(cmd); _this3.incrementalSolveConstraints(); case 22: case "end": return _context3.stop(); } } }, _callee3, this); })); return function (_x3) { return _ref8.apply(this, arguments); }; }()); }; var _arr4 = Object.entries(this.namedElements.constraints); for (var _i5 = 0; _i5 < _arr4.length; _i5++) { var _ref7 = _arr4[_i5]; var constraint = _ref7[0]; var element = _ref7[1]; _loop4(constraint, element); } this.namedElements.actions.solve.observe(click, function (x) { return _this3.solveConstraints(); }); this.namedElements.actions.autoconstr.observe(click, function (x) { var addConstraintsStatements = _this3.generateConstraints(_this3.activeSketch); _this3.run(addConstraintsStatements); if (addConstraintsStatements.length > 0) _this3.incrementalSolveConstraints(); }); this.namedElements.actions.delete.observe(click, function (x) { return _this3.deleteSelected(); }); this.namedElements.solids.extrude.observe(click, function (x) { return _this3.createNewExtrusion(); }); this.namedElements.solids.getLoop.observe(click, function (x) { return _this3.getLoop(); }); this.namedElements.solids.finishSketchRegionMode.observe(click, function (x) { return _this3.finishSketchRegionMode(); }); if (this.connection.getState().activeFeatureActivationInfo !== undefined) { this.namedElements.solids.extrude.visible = false; this.namedElements.solids.revolve.visible = false; this.namedElements.solids.finishSketchRegionMode.visible = true; } }; _proto.onEnabled = function onEnabled() { var _pool$createInteracti, _this4 = this; this.clearGraphics(); this.selector = new Selector(session, { name: 'Selection', types: ['SketcherMesh', 'DimensionHandle'], whitelist: ['SketcherMesh', 'DimensionHandle'], //note: the following setting forces selector to NOT create any interaction //this allows to completely avoid any conflicts between several interactions //(since there would be only our interaction) //but this means our interaction handlers must call selector.hovered/unhovered/clicked/etc manually createInteraction: false, target: this.pool }); this.dimension.selector = this.selector; this.session.pool.fadeOut(); this.pool.createInteraction().on((_pool$createInteracti = {}, _pool$createInteracti[Object3.Events.Lifecycle.Rendered] = this.onRender.bind(this), _pool$createInteracti), { sync: true }); this.addSubscription(this.session.observe(function (state) { return state.globals.day; }, function () { return _this4.activeSketch.updateGraphicsRecursive(); })); this.connection.observe(function (state) { return state.tree[_this4.activeSketch.id]; }, this.onSketchObjectChange, { fireOnStart: true, unsubscribeOnUndefined: true, onRemove: this.onSketchObjectRemove, manager: this.addSubscription.bind(this) }); this.connection.observe(function (state) { return state.tree[_this4.activeSketch.id].members.planeReference.value; }, this.onPlaneChange, { fireOnStart: true, manager: this.addSubscription.bind(this) }); this.observeElements(); if (!this.activeHandler) { this.namedElements.handlers['drag'].value = true; this.dimension.enabled = true; } else { this.activeHandler.addInteractions(); } this.constraintVisualizer.updateAll(); this.addSubscription(this.view.input.subscribe('dblclick', function (event) { return _this4.rotateCamera(); })); var defaultRotateAngle = 45 * Math.PI / 180; this.rotateCamera(defaultRotateAngle, defaultRotateAngle); this.zoomMode_old = this.view.controls.zoomMode; this.view.controls.zoomMode = Orbit.ZoomMode.Mouse; var activationInfo = this.connection.getState().activeFeatureActivationInfo; if (activationInfo) { if (activationInfo.workAxisMode) { // If work axis editing mode: this.onHandlerToggle('revolve', true); } else { // If sketch region editing mode: var sketchRegionCurves = this.connection.getState().activeFeatureActivationInfo.curves.members; sketchRegionCurves = sketchRegionCurves.map(function (curve) { return curve = curve.value; }); this.selectElements(sketchRegionCurves); } } this.instantiated = true; }; _proto.onDisabled = function onDisabled() { this.session.pool.fadeIn(); // Unlock controls, fade in pool //this.session.pool.view.controls.noRotate = false; this.view.controls.focus().zoom(); this.dimension.enabled = false; if (this.activeHandler) { // disable possible complex handler (polyline) first, then disable drag this.namedElements.handlers[this.activeHandler.name].value = false; this.onHandlerToggleRecursion = true; this.namedElements.handlers['drag'].value = false; this.onHandlerToggleRecursion = false; } this.view.controls.zoomMode = this.zoomMode_old; this.graphicScale = defaultGraphicsScale; this.selector.destroy(); this.instantiated = false; }; _proto.onSketchObjectChange = function onSketchObjectChange(object, oldObject, resetCoordSystem) { var _this5 = this; if (resetCoordSystem === void 0) { resetCoordSystem = false; } var id = object.id, ccref = new Ccref(this, id); // create graphics if (!this.graphics.has(id)) { if (this.instantiated || !this.instantiated && object.class.indexOf('Constraint') == -1) { var g = Graphics(object.class, this.session); if (!g) return; this.pool.add(g); this.graphics.set(id, g); if (this.instantiated) { this.activeHandler.addInteraction(ccref); this.constraintVisualizer.addConstraint(ccref); } } } // create new children subscriptions arrayDiff(object.children, (oldObject || {}).children, function (newChildren) { return newChildren.forEach(function (child) { return _this5.connection.observe(function (state) { return state.tree[child]; }, _this5.onSketchObjectChange, { fireOnStart: true, unsubscribeOnUndefined: true, onRemove: _this5.onSketchObjectRemove, manager: _this5.addSubscription.bind(_this5) }); }); }); // update graphics ccref.updateGraphics(); // update parent line/arc graphics if this was an endpoint change or similar if (object.id !== this.activeSketch.id && object.parent !== this.activeSketch.id) new Ccref(this, object.parent).updateGraphics(); }; _proto.onPlaneChange = function onPlaneChange(planeId) { var isCorrect = Boolean(planeId); var activationInfo = this.connection.getState().activeFeatureActivationInfo; var workAxisMode = activationInfo && activationInfo.workAxisMode; var showControls = workAxisMode ? false : isCorrect; this.namedElements.incremental.visible = showControls; this.namedElements.constrvis.visible = showControls; this.namedElements.toolsGroup.visible = showControls; this.namedElements.actionsGroup.visible = showControls; this.namedElements.solidsGroup.visible = showControls; this.namedElements.constraintsGroup.visible = showControls; this.namedElements.console.visible = showControls; this.namedElements.mouseGroup.visible = showControls; this.namedElements.dimension.visible = showControls; this.pool.visible = workAxisMode ? true : isCorrect; ; this.namedElements.plane.visible = workAxisMode ? false : !isCorrect; this.namedElements.plane.active = !isCorrect; }; _proto.onSketchObjectRemove = function onSketchObjectRemove(object, unsubscribe) { var id = typeof object === "number" ? object : object.id; // destroy graphics if (this.graphics.has(id)) { var _activeHandler; var ccref = new Ccref(this, id); // pass object too because ccref.state can be undefined typeof object !== "number" && this.constraintVisualizer.removeConstraint(ccref, object); (_activeHandler = this.activeHandler) === null || _activeHandler === void 0 ? void 0 : _activeHandler.removeInteraction(ccref); this.graphics.get(id).destroy(); this.graphics.delete(id); } // free transient info if (this.transientGeomParams.has(id)) this.transientGeomParams.delete(id); // remove a reference added by addSubscription this.instantiated && this.removeSubscription(unsubscribe); }; _proto.onHandlerToggle = function onHandlerToggle(handler, value, activateHandlerInfo) { if (this.onHandlerToggleRecursion) return; this.onHandlerToggleRecursion = true; this.selector.missed(); if (value) { if (this.activeHandler) this.namedElements.handlers[this.activeHandler.name].value = false; this.activeHandler = Handler(this, handler, this.activeHandler, activateHandlerInfo); } else { this.namedElements.handlers['drag'].value = true; this.activeHandler = Handler(this, 'drag', this.activeHandler, activateHandlerInfo); } this.activeHandler.parseRestrictions(this.namedElements.console.value); this.onHandlerToggleRecursion = false; }; _proto.onRender = function onRender() { var graphicDirty = this.updateGraphicScale(); if (graphicDirty) this.activeSketch.updateGraphicsRecursive(); this.constraintVisualizer.render(); }; _proto.updateGraphicScale = function updateGraphicScale() { // just take sketch origin as scaling point var globalPnt = new THREE.Vector3(0, 0, 0).applyMatrix4(this.activeSketch.matrixWorld); // get length-to-pixels local scaling at this point var approxScale = this.view.calculateScaleFactor(globalPnt, 7); // adjust to a good number var newScale = Math.pow(10.0, Math.floor(Math.log10(approxScale) * 5) / 5); // set grid step var newStep = Math.pow(10.0, Math.floor(Math.log10(approxScale * 30) + 1e-3)); //change scale and grid step var changed = newStep !== this.gridStep || newScale !== this.graphicScale; this.gridStep = newStep; this.graphicScale = newScale; return changed; }; //only for showing them in GUI _proto.setCursorCoordinates = function setCursorCoordinates(pos) { if (pos) { this.namedElements.coordinateShower.xCoord.visible = true; this.namedElements.coordinateShower.yCoord.visible = true; this.namedElements.coordinateShower.xCoord.value = pos.x; this.namedElements.coordinateShower.yCoord.value = pos.y; } else { this.namedElements.coordinateShower.xCoord.visible = false; this.namedElements.coordinateShower.yCoord.visible = false; } }; _proto.refresh = function refresh() { this.view.invalidate(); }; _proto.run = function run(command) { return this.multiRunner.run({ command: 'Execute', task: Sequence(command).unparse() }); }; _proto.checkSolveResult = function checkSolveResult(result) { // result: 0 - fail, 1 - well-defined, 2 - solved if (result === 0) { this.namedElements.incremental.error = 'Failed to solve sketch'; this.namedElements.incremental.value = 0; return false; } this.namedElements.incremental.error = undefined; return true; }; _proto.solveConstraints = /*#__PURE__*/ function () { var _solveConstraints = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee4() { var result; return _regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: result = this.run(Return(SolveConstraints(this.activeSketch))); this.run(UpdateDimensions(this.activeSketch)); _context4.t0 = this; _context4.next = 5; return result; case 5: _context4.t1 = _context4.sent; return _context4.abrupt("return", _context4.t0.checkSolveResult.call(_context4.t0, _context4.t1)); case 7: case "end": return _context4.stop(); } } }, _callee4, this); })); return function solveConstraints() { return _solveConstraints.apply(this, arguments); }; }(); _proto.switchToFeature = function switchToFeature(featureId) { var tree = this.connection.tree; var root = this.connection.activeRoot || tree.root; var features = tree[root].features; if (features.indexOf(featureId) != -1) this.store.dispatch(connectionActions.setActiveFeature(this.connection.id, featureId)); //TODO: else throw error. }; _proto.createNewExtrusion = function createNewExtrusion() { var _this6 = this; var selected = this.getSelected(); this.run(Return(CreateNewExtrusion(this.activeSketch, selected))).then(function (msg) { var extrudeId = parseInt(msg.slice(1)); //TODO: slice - ugly hack. (IdToReal on server side) _this6.switchToFeature(extrudeId); }); }; _proto.createNewRevolve = function createNewRevolve(selectedLoop, rotateAxis) { var _this7 = this; this.run(Return(CreateNewRevolve(this.activeSketch, selectedLoop, rotateAxis))).then(function (msg) { var revolveId = parseInt(msg.slice(1)); //TODO: slice - ugly hack. (IdToReal on server side) _this7.switchToFeature(revolveId); }); }; _proto.getLoop = function getLoop() { var _this8 = this; this.run(Return(GetLoop(this.activeSketch, this.getSelected()))).then(function (msg) { var loop = JSON.parse(msg.replace(/\$/gi, '')); //TODO: ugly parsing. _this8.selectElements(loop); }); }; _proto.selectElements = function selectElements(elements) { var _this9 = this; var selectedIds = this.getSelectedIds(); elements.forEach(function (elId) { if (selectedIds.indexOf(elId) !== -1) return; var lineGr = _this9.graphics.get(elId); var object = lineGr.localMesh; var material = object.material; _this9.selector.clicked({ object: object, material: material }); }); }; _proto.finishSketchRegionMode = function finishSketchRegionMode() { var _this10 = this; var activateFeatureInfo = this.connection.getState().activeFeatureActivationInfo; if (activateFeatureInfo === undefined) return; var selected = this.getSelected(); var relatedExtrusionId = activateFeatureInfo.prevFeatureId; this.run(Return(UpdateSketchRegion(new GlobalObjId(relatedExtrusionId), this.activeSketch, selected))).then(function (msg) { _this10.switchToPrevFeature(); }); }; _proto.finishWorkAxisMode = function finishWorkAxisMode(newWorkAxis) { var _this11 = this; var activateFeatureInfo = this.connection.getState().activeFeatureActivationInfo; if (activateFeatureInfo === undefined) return; var relatedRevolveId = activateFeatureInfo.prevFeatureId; this.run(Return(UpdateWorkAxis(new GlobalObjId(relatedRevolveId), newWorkAxis))).then(function (msg) { _this11.onHandlerToggle('revolve', false); _this11.switchToPrevFeature(); }); }; _proto.recalc = function recalc() { return this.run(Recalc()); }; _proto.incrementalSolveConstraints = /*#__PURE__*/ function () { var _incrementalSolveConstraints = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee5() { var solvePromise, recalcPromise; return _regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: solvePromise = this.solveIncremental ? this.solveConstraints() : Promise.resolve(); recalcPromise = this.recalcIncremental ? this.recalc() : Promise.resolve(); _context5.next = 4; return Promise.all([solvePromise, recalcPromise]); case 4: case "end": return _context5.stop(); } } }, _callee5, this); })); return function incrementalSolveConstraints() { return _incrementalSolveConstraints.apply(this, arguments); }; }(); _proto.generateConstraints = function generateConstraints(object) { return new ConstraintGenerator(this.activeSketch).generateImpliedConstraints(object); }; _proto.autoconstraintCommands = function autoconstraintCommands(object) { return this.autoconstraintIncremental ? this.generateConstraints(object) : []; }; _proto.moveUnderConstraints = /*#__PURE__*/ function () { var _moveUnderConstraints = _asyncToGenerator( /*#__PURE__*/ _regeneratorRuntime.mark(function _callee6(objects, delta) { var command, result; return _regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: if (!(delta.lengthSq() === 0)) { _context6.next = 2; break; } return _context6.abrupt("return"); case 2: if (!this.solveInProgress) { _context6.next = 4; break; } return _context6.abrupt("return"); case 4: this.solveInProgress = true; // hack: prevent multiple concurrent requests to the server command = Return(MoveObjects(this.activeSketch, this.noMultiMoveSupport ? objects[0] : objects, delta)); _context6.prev = 6; _context6.next = 9; return this.run(command); case 9: result = _context6.sent; this.checkSolveResult(result); _context6.next = 21; break; case 13: _context6.prev = 13; _context6.t0 = _context6["catch"](6); if (!(!this.noMultiMoveSupport && _context6.t0.errorCode === 0 && _context6.t0.errorState === 2 && _context6.t0.errorMessage === '[Evaluationsfehler in SketcherCloudInterop.MoveObjects:[CCVM::callsf: objId not found]] ')) { _context6.next = 20; break; } console.warn('No support for moving multiple objects, update server classes'); this.noMultiMoveSupport = true; _context6.next = 21; break; case 20: throw _context6.t0; case 21: _context6.prev = 21; this.solveInProgress = false; return _context6.finish(21); case 24: case "end": return _context6.stop(); } } }, _callee6, this, [[6, 13, 21, 24]]); })); return function moveUnderConstraints(_x4, _x5) { return _moveUnderConstraints.apply(this, arguments); }; }(); _proto.copyObjects = function copyObjects(objects, translate, rotate) { return this.run(CopyObjects(this.activeSketch, objects, translate, rotate)); }; _proto.deleteSelected = function deleteSelected(_temp2) { var _ref9 = _temp2 === void 0 ? {} : _temp2, onlyIfConsoleIsEmpty = _ref9.onlyIfConsoleIsEmpty; if (onlyIfConsoleIsEmpty && this.namedElements.console.value !== '') return; var selected = this.getSelected(); // replace selected dimensions with their master constraints for (var i = 0; i < selected.length; i++) { var ent = selected[i]; if (ent.isDimension()) selected[i] = new Ccref(this, this.connection.tree[ent.id].members.master.value); } selected = selected.filter(function (ent) { return ent; }); if (selected.length !== 0) { // delete sketch objects this.selector.unselectAll().removeAll(); this.run(removeCommands.apply(void 0, [this.activeSketch].concat(selected))); this.incrementalSolveConstraints(); } }; _proto.setPlaneFromSelection = function setPlaneFromSelection() { var _this12 = this; if (this.session.selector) { var object = this.session.selector.selectedObjects[0]; if (object === undefined) return; var meta = object.userData.meta; if (meta === undefined) { var material = this.session.selector.selectedMaterials[0]; var face = new Ccref(this, this.session.selector.selectedMaterials[0].meta.id); this.run(createAndSetPlaneCommands(this.activeSketch, face)).then(function () { return _this12.rotateCamera(); }); this.namedElements.plane.active = false; } else { var plane = new Ccref(this, meta.id); this.run(setPlaneCommands(this.activeSketch, plane)).then(function () { return _this12.rotateCamera(); }); } this.namedElements.plane.active = false; } }; _proto.switchToOrthographicCamera = function switchToOrthographicCamera(view, sketch) { view.perspectiveControls = view.controls; view.camera = new THREE.OrthographicCamera(0, 1, 1, 0); sketch.localToWorld(view.camera.position.set(0, 0, 1000)); view.camera.up.transformDirection(sketch.matrixWorld); view.camera.size = 1; view.controls = view.controls.clone(); view.controls.noRotate = true; view.controls.zoomMode = Orbit.ZoomMode.Mouse; view.controls.focus(sketch).zoom(200).now(); }; _proto.switchToPerspectiveCamera = function switchToPerspectiveCamera(view) { view.controls = view.perspectiveControls; view.camera = view.controls.camera; view.perspectiveControls = undefined; }; _proto.rotateCamera = function rotateCamera(iTheta, iPhi) { var controls = this.view.controls; if (controls instanceof Orbit) { // NOTE: controls.up is unchanged // this means that only sketch normal is aligned, but x/y axis aren't necessary so var normal = new THREE.Vector3(); this.activeSketch.graphics.getWorldDirection(normal); // rotate to the "y-axis-is-up" space used in controls normal.applyQuaternion(controls._quat); var theta = iTheta ? iTheta : Math.atan2(normal.x, normal.z); // -π to π var phi = iPhi ? iPhi : Math.atan2(Math.hypot(normal.x, normal.z), normal.y); // 0 to π controls.focus().zoom().rotate(theta, phi); } if (controls instanceof Trackball) { var location = controls.getCurrentLocation(); var eyeDist = location.eyeVec.length(); var sketchMatrix = this.activeSketch.geomParams.coordinateSystem; var origin = new THREE.Vector3(); var xAxis = new THREE.Vector3(); var yAxis = new THREE.Vector3(); var zAxis = new THREE.Vector3(); sketchMatrix.decompose(origin, new THREE.Quaternion(), new THREE.Vector3()); sketchMatrix.extractBasis(xAxis, yAxis, zAxis); //TODO: if iTheta and iPhi defined convert it to eyeVec, upDir controls.rotateToLocation({ target: origin, eyeVec: zAxis.clone().multiplyScalar(eyeDist), upDir: yAxis }); } }; return Sketcher; }(Plugin), Object.defineProperty(_class, "measurable", { configurable: true, enumerable: true, writable: true, value: true }), Object.defineProperty(_class, "persistent", { configurable: true, enumerable: true, writable: true, value: true }), _temp); export { Sketcher as default };