| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041 |
- /*
- 3D Modeler - application shell
- Wires the document, the kernel worker, the viewport, the model browser and
- the ribbon together (PROPOSAL.md milestone M1). The document is the single
- source of truth: every change to it triggers a rebuild in the worker, and
- the viewport and the browser are redrawn from the result.
- Three kinds of document share the window (state.env): a part, handled
- here, an assembly, handled by js/assembly/assembly.js, and a drawing
- (2D views on a sheet), handled by js/drawing/drawing.js. File > New
- asks which; opening a file picks by its format. Several documents can
- be open, one tab each under the view (see "document tabs" below). The ribbon shows the
- tabs of the open kind (ribbon.setMode), and the shared commands (files,
- view, Measure, Section View) ask activeDoc() which document they act on.
- jQuery and ao_module.js are classic scripts loaded by index.html; they are
- reached through window so this module also runs outside the ArozOS desktop.
- */
- import { createRibbon } from './ribbon.js';
- import { createViewport, ORIGIN_PLANES, orbitRing } from './viewport.js';
- import { createBrowser } from './browser.js';
- import { createKernel } from './kernel/client.js';
- import { createDocument } from './document/document.js';
- import { sampleDocument } from './document/sample.js';
- import { sampleAssembly } from './document/sampleasm.js';
- import { sampleDrawing } from './document/sampledrw.js';
- import { createAssembly } from './assembly/assembly.js';
- import { createDrawing } from './drawing/drawing.js';
- import { createMeasure } from './inspect/measure.js';
- import { createSectionPanel } from './inspect/section.js';
- import { createAppearancePanel } from './features/appearance.js';
- import { createPaintPanel } from './features/paint.js';
- import { createMaterialPanel, massOf } from './features/material.js';
- import { createParameterTable } from './features/paramtable.js';
- import { evaluateParameters, applyParameters } from './parameters.js';
- import { setScope } from './expr.js';
- import { normalizeScene, lightingById } from './appearance.js';
- import { toTextureImage, IMAGE_EXTENSIONS } from './io/image.js';
- import { askMeshExport } from './io/exportdialog.js';
- import { createOffsetBox } from './offsetbox.js';
- import * as files from './io/files.js';
- import * as native from './io/native.js';
- import * as preview from './io/preview.js';
- import { createLoading, megabytes, buildText } from './loading.js';
- import { toSTL, toSTLText, toOBJ, to3MF, meshCheck, scaled, parseSTL, parseOBJ, encodeMesh, decodeMesh, meshInfo } from './io/exchange.js';
- import * as solver from './sketch/solver.js';
- import { createSketcher } from './sketch/sketcher.js';
- import { addProjected, applyFollow } from './sketch/project.js';
- import { createExtrude } from './features/extrude.js';
- import { createRevolve } from './features/revolve.js';
- import { createShell } from './features/shell.js';
- import { createPattern } from './features/pattern.js';
- import { createEdgeFeature } from './features/edges.js';
- import { createHole } from './features/hole.js';
- import { createWorkFeature } from './features/workfeature.js';
- import { createRepair } from './features/repair.js';
- import { createSweep } from './features/sweep.js';
- import { createLoft } from './features/loft.js';
- import { createDraft } from './features/draft.js';
- import { createCheckPanel } from './inspect/check.js';
- import * as sketchModel from './sketch/model.js';
- import { sample } from './sketch/geom.js';
- import { planeFrame, toWorld, workPlaneFrame, resolveFace, resolveWork, workAxisLine, workPoint } from './kernel/profile.js';
- import { icon, openMenu, closeMenu, ask, tell, chooseNew } from './ui.js';
- import { createTabBar, freeName } from './tabs.js';
- import { validate as validatePart, sketchesOf } from './document/document.js';
- import { validateAssembly } from './assembly/document.js';
- import { validateDrawing } from './drawing/document.js';
- const $ = function (id) {
- return document.getElementById(id);
- };
- const state = {
- env: 'part', // the kind of document open: 'part' | 'assembly' | 'drawing'
- mode: 'model', // 'model' | 'pick-sketch-plane' | 'pick-lookat' | 'sketch' | 'feature'
- rebuildDeferred: false, // the document changed while a sketch was open
- rollbackAt: null, // an earlier sketch is edited: the model is shown as it was before it
- leftDrag: 'select', // what dragging the left button does: 'select' | 'orbit' | 'pan'
- originVisible: false,
- kernelReady: false,
- fitNext: false, // zoom to the part after the next rebuild (new or opened part)
- keepView: false, // a part tab shown again: keep the view it was left with
- pickText: null // the prompt while a plane is being picked
- };
- const doc = createDocument();
- /* ================= loading overlay ================= */
- // The kernel's start, and each document being opened, from reading its
- // file to its first build (loading.js), with the picture saved in the file
- const loading = createLoading($('splash'));
- const kernelTask = loading.start({ title: 'Starting the modelling kernel', text: 'Downloading...', delay: 0, blocking: true });
- let opening = null; // { task, tab, kind } while a document is being opened
- let restoring = null; // the task of an assembly or drawing shown again, reading its models
- function beginOpening(name) {
- endOpening();
- opening = { task: loading.start({ title: 'Opening ' + name, text: 'Reading the file' }), tab: null, kind: '' };
- return opening;
- }
- // which: only that opening (a later one may have taken its place)
- function endOpening(which) {
- if (opening && (!which || opening === which)) {
- opening.task.done();
- opening = null;
- }
- }
- // How far the assembly or drawing on show is with its models: { text,
- // fraction }, or null when everything is loaded
- function documentProgress(info) {
- const tab = activeTab;
- if (opening && (!opening.tab || opening.tab === tab)) {
- opening.tab = tab;
- if (info) {
- opening.task.update(info);
- } else {
- endOpening(opening);
- }
- return;
- }
- if (info) {
- if (!restoring) {
- restoring = loading.start({ title: 'Loading ' + (tab ? tabName(tab) : ''), delay: 400 });
- }
- restoring.update(info);
- } else if (restoring) {
- restoring.done();
- restoring = null;
- }
- }
- /* ================= status bar ================= */
- function setStatus(text) {
- $('status-msg').textContent = text;
- }
- function setPrompt(text) {
- $('prompt').hidden = !text;
- $('prompt').textContent = text || '';
- }
- function setEngine(id, cls, title) {
- const el = $(id);
- el.classList.remove('ok', 'bad');
- if (cls) {
- el.classList.add(cls);
- }
- el.title = title;
- }
- function mm(value, digits) {
- return value.toFixed(digits === undefined ? 2 : digits);
- }
- function describe(item) {
- if (item.kind === 'edge') {
- return 'Edge, length ' + mm(item.length) + ' mm';
- }
- if (item.kind !== 'face' || typeof item.area !== 'number') {
- return 'Body'; // a whole component; parts never pick these
- }
- const names = { plane: 'Planar face', cylinder: 'Cylindrical face', other: 'Face' };
- return (names[item.type] || 'Face') + ', area ' + mm(item.area) + ' mm2';
- }
- /* ================= theme ================= */
- function applyTheme(theme) {
- const dark = theme === 'dark';
- document.body.classList.toggle('dark', dark);
- document.querySelector('meta[name=theme-color]').setAttribute('content', dark ? '#1b1d21' : '#f3f4f6');
- try {
- window.ao_module_setWindowTheme(dark ? 'dark' : 'white');
- } catch (e) {
- // Not inside an ArozOS float window
- }
- }
- function initTheme() {
- if (native.available()) {
- // The Mac app follows the system's appearance, also when it changes
- const query = window.matchMedia('(prefers-color-scheme: dark)');
- applyTheme(query.matches ? 'dark' : 'light');
- query.addEventListener('change', function (event) {
- applyTheme(event.matches ? 'dark' : 'light');
- });
- return;
- }
- const inDesktop = !!window.ao_module_virtualDesktop;
- if (!inDesktop && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
- applyTheme('dark');
- }
- files.hasBackend().then(function (ok) {
- if (!ok) {
- return; // the theme preference lives on the server
- }
- // The stored preference is "darkTheme" / "whiteTheme"
- window.ao_module_getSystemThemeColor(function (pref) {
- applyTheme(pref === 'darkTheme' || pref === 'dark' ? 'dark' : 'light');
- });
- });
- try {
- window.ao_module_onThemeChanged(applyTheme);
- } catch (e) {
- // Standalone page without ao_module
- }
- }
- /* ================= ribbon, viewport, browser ================= */
- const ribbon = createRibbon({ tabs: $('tabs'), panels: $('panels'), openMenu: openMenu }, onCommand);
- const viewport = createViewport({
- canvas: $('viewport'),
- viewCube: $('viewcube-cam'),
- triad: $('triad'),
- onHoverPlane: function (key) {
- browser.setHotPlane(key);
- if (state.pickText) {
- setStatus(key ? { xy: 'XY Plane', xz: 'XZ Plane', yz: 'YZ Plane' }[key] + ': click to use it' : state.pickText);
- }
- },
- onHover: function (item) {
- if (state.env === 'drawing') {
- drawing.onHover(item);
- return;
- }
- if (state.env === 'assembly') {
- if (!activeInspect) {
- assembly.onHover(item);
- }
- return;
- }
- if (state.mode === 'model') {
- setStatus(item ? describe(item) : selectionText());
- } else if (state.pickText) {
- // Waiting for a plane: say what the face under the pointer is
- setStatus(item ? describe(item) + ': click to use it' : state.pickText);
- }
- },
- onSelect: function (items) {
- if (state.env === 'drawing') {
- drawing.onSelect(items);
- return;
- }
- if (state.env === 'assembly') {
- assembly.onSelect(items);
- return;
- }
- if (state.mode === 'model') {
- setStatus(selectionText());
- }
- }
- });
- const browser = createBrowser($('tree'), doc, {
- onPlaneHover: function (key) {
- viewport.setHotPlane(key);
- },
- // A feature row hovered: outline in the model what it made
- onFeatureHover: function (id) {
- viewport.setFeatureMark(id);
- },
- onPlaneClick: function (key) {
- // A work feature panel waiting for a plane takes it
- if (viewport.offerRef({ kind: 'plane', target: { kind: 'origin', key: key } })) {
- return;
- }
- if (picking()) {
- viewport.stopPlanePick();
- planePicked({ kind: 'origin', key: key });
- }
- },
- onOriginClick: function (what) {
- if (what.axis) {
- const d = { x: [1, 0, 0], y: [0, 1, 0], z: [0, 0, 1] }[what.axis];
- viewport.offerRef({ kind: 'axis', ref: { ref: 'origin:' + what.axis }, line: { o: [0, 0, 0], d: d } });
- } else {
- viewport.offerRef({ kind: 'point', ref: { ref: 'origin' }, at: [0, 0, 0] });
- }
- },
- onFeatureSelect: function (id) {
- // A work feature panel waiting for a plane, an axis or a point takes
- // a work feature clicked in the browser
- const work = id ? doc.feature(id) : null;
- if (work && !work.suppressed) {
- if (work.type === 'plane' && viewport.offerRef({ kind: 'plane', target: { kind: 'work', id: id } })) {
- return;
- }
- const line = work.type === 'axis' ? workAxisLine(work, doc.features()) : null;
- if (line && viewport.offerRef({ kind: 'axis', ref: { ref: 'axis', id: id }, line: line })) {
- return;
- }
- const at = work.type === 'point' ? workPoint(work, doc.features()) : null;
- if (at && viewport.offerRef({ kind: 'point', ref: { ref: 'point', id: id }, at: at })) {
- return;
- }
- }
- // While a pattern or mirror is set up, the browser picks what it repeats
- if (activeFeature && activeFeature.tool.pickFeature) {
- activeFeature.tool.pickFeature(id);
- return;
- }
- const feature = id && doc.feature(id);
- if (feature && state.mode === 'model') {
- const status = featureReport[id];
- setStatus(status && status.status === 'error' ? feature.name + ': ' + status.message : status && status.note ? feature.name + ': ' + status.note : feature.name);
- }
- },
- onFeatureAction: function (action, id, value) {
- const feature = doc.feature(id);
- if (!feature) {
- return;
- }
- if (action === 'rename') {
- doc.rename(id, value);
- } else if (action === 'suppress' || action === 'unsuppress') {
- doc.setSuppressed(id, action === 'suppress');
- } else if (action === 'hide' || action === 'show') {
- doc.setHidden(id, action === 'hide');
- setStatus(feature.name + (action === 'hide' ? ' hidden: the eye on its row (or Show in its right click menu) brings it back' : ' shown'));
- } else if (action === 'share' || action === 'unshare') {
- doc.setShared(id, action === 'share');
- setStatus(action === 'share' ? feature.name + ' is shared: its areas are offered again to Extrude, Revolve and Hole'
- : feature.name + ' is no longer shared');
- } else if (action === 'endhere') {
- doc.setEnd(id);
- setStatus(endStatus());
- } else if (action === 'delete') {
- deleteFeature(id);
- } else if (action === 'edit' && feature.type === 'sketch') {
- openSketch(id);
- } else if (action === 'editsketch' && doc.feature(feature.sketch)) {
- openSketch(feature.sketch);
- } else if (action === 'edit' && FEATURE_HINTS[toolKind(feature)]) {
- startFeature(toolKind(feature), id);
- } else if (action === 'edit') {
- setStatus(feature.name + ' cannot be edited in this version');
- }
- },
- // A row dragged to another place in the history
- onMoveFeature: function (id, beforeId, built) {
- const feature = doc.feature(id);
- const reason = doc.canMove(id, beforeId);
- if (!feature) {
- return;
- }
- if (reason) {
- setStatus(feature.name + ' cannot go there: ' + reason);
- return;
- }
- if (doc.move(id, beforeId, built)) {
- setStatus(feature.name + ' moved' + (doc.features().indexOf(doc.feature(id)) > doc.endIndex() ? ' below End of Part: it is not built until End of Part is moved past it' : ''));
- }
- },
- // End of Part dropped: after a feature, above them all ("") or at the bottom (null)
- onMoveEnd: function (afterId) {
- doc.setEnd(afterId);
- setStatus(endStatus());
- },
- onBodyVisibility: function (index, hidden) {
- doc.setBodyHidden(index, hidden);
- setStatus('Solid' + (index + 1) + (hidden ? ' hidden: the eye on its row brings it back' : ' shown'));
- },
- onHint: function (text) {
- setStatus(text || 'Ready');
- }
- });
- // What End of Part leaves out, for the status bar
- function endStatus() {
- const list = doc.features();
- const out = list.length - 1 - doc.endIndex();
- return out > 0 ? 'End of Part moved: ' + out + (out === 1 ? ' feature below it is' : ' features below it are') +
- ' not built, and new features are added there. Right-click End of Part > Move to End to build them all again.'
- : 'End of Part is at the bottom: every feature is built';
- }
- /* ================= sketcher ================= */
- // Ribbon button of each sketch tool, to show which one is active
- const TOOL_BUTTONS = {
- line: 'sk.line', rect: 'sk.rect', circle: 'sk.circle', arc: 'sk.arcs', arc3: 'sk.arcs', arctan: 'sk.arcs', point: 'sk.point',
- fillet: 'sk.fillet', chamfer: 'sk.chamfer', 'con:concentric': 'con.concentric',
- mirror: 'sk.mirror', polygon: 'sk.polygon', slot: 'sk.slot',
- trim: 'sk.trim', extend: 'sk.extend', dimension: 'sk.dimension', project: 'sk.project',
- 'con:coincident': 'con.coincident', 'con:collinear': 'con.collinear', 'con:horizontal': 'con.horizontal', 'con:vertical': 'con.vertical',
- 'con:parallel': 'con.parallel', 'con:perpendicular': 'con.perpendicular', 'con:tangent': 'con.tangent',
- 'con:equal': 'con.equal', 'con:fix': 'con.fix', 'con:midpoint': 'con.midpoint', 'con:symmetric': 'con.symmetric'
- };
- let activeTool = 'select';
- const sketcher = createSketcher({
- stage: $('stage'),
- canvas: $('viewport'),
- viewport: viewport,
- doc: doc,
- onPrompt: setPrompt,
- onStatus: setStatus,
- onState: function (s) {
- activeTool = s.tool;
- // Several tools share a button (the three arcs): light the one in use
- const on = TOOL_BUTTONS[s.tool];
- Object.values(TOOL_BUTTONS).forEach(function (button) {
- ribbon.setOn(button, button === on);
- });
- ribbon.setOn('sk.construction', s.construction);
- }
- });
- // Sketches nothing has been built from yet are drawn in the model, so they
- // can be seen and picked; the one open in the sketcher draws itself.
- function refreshSketches() {
- const limit = Math.min(rollbackIndex(), doc.endIndex() + 1);
- // A sketch used only by features after the rolled back point (or below
- // End of Part) is unused there; a shared one is always drawn
- const used = new Set([].concat.apply([], doc.features().filter(function (f, i) {
- return i < limit;
- }).map(sketchesOf)));
- const list = [];
- doc.features().forEach(function (feature, i) {
- const frame = feature.type === 'sketch' && i <= Math.min(rollbackIndex(), doc.endIndex()) && !feature.hidden ? planeFrame(feature.plane, doc.features()) : null;
- if (!frame || feature.suppressed || (used.has(feature.id) && !feature.shared) || feature.id === sketcher.featureId()) {
- return;
- }
- const out = [];
- sketchModel.curves(sketchModel.clone(feature)).forEach(function (curve) {
- const pts = sample(curve).map(function (p) {
- return toWorld(frame, p[0], p[1]);
- });
- for (let i = 1; i < pts.length; i++) {
- out.push(pts[i - 1][0], pts[i - 1][1], pts[i - 1][2], pts[i][0], pts[i][1], pts[i][2]);
- }
- });
- list.push({ id: feature.id, segments: new Float32Array(out) });
- });
- viewport.setSketches(list);
- refreshMeshes();
- }
- // Reference meshes (STL / OBJ brought in) are drawn pale; decoded once
- const decodedMeshes = new Map(); // feature id -> { stored, mesh }
- function refreshMeshes() {
- const limit = Math.min(rollbackIndex(), doc.endIndex());
- const list = [];
- doc.features().forEach(function (feature, i) {
- if (feature.type !== 'mesh' || feature.suppressed || feature.hidden || i > limit || !feature.data) {
- return;
- }
- let entry = decodedMeshes.get(feature.id);
- if (!entry || entry.stored !== feature.data) {
- try {
- entry = { stored: feature.data, mesh: decodeMesh(feature.data) };
- } catch (err) {
- entry = { stored: feature.data, mesh: null };
- }
- decodedMeshes.set(feature.id, entry);
- }
- if (entry.mesh) {
- list.push({ id: feature.id, positions: entry.mesh.positions, indices: entry.mesh.indices });
- }
- });
- viewport.setMeshes(state.env === 'part' ? list : []);
- }
- // Work planes, axes and points are drawn in the model; the drafts are the
- // one being set up in its panel ({ frame } / { line } / { at }, with the
- // id of the feature it replaces while editing)
- let draftPlane = null;
- let draftAxis = null;
- let draftPoint = null;
- function refreshWorkPlanes() {
- const limit = Math.min(rollbackIndex(), doc.endIndex() + 1);
- const list = [];
- const axes = [];
- const points = [];
- const features = doc.features();
- features.forEach(function (feature, i) {
- if (feature.suppressed || feature.hidden || i >= limit) {
- return;
- }
- // One being edited is shown by its draft instead
- if (feature.type === 'plane' && !(draftPlane && draftPlane.id === feature.id)) {
- const frame = workPlaneFrame(feature, features);
- if (frame) {
- list.push({ id: feature.id, frame: frame });
- }
- } else if (feature.type === 'axis' && !(draftAxis && draftAxis.id === feature.id)) {
- const line = workAxisLine(feature, features);
- if (line) {
- axes.push({ id: feature.id, o: line.o, d: line.d });
- }
- } else if (feature.type === 'point' && !(draftPoint && draftPoint.id === feature.id)) {
- const at = workPoint(feature, features);
- if (at) {
- points.push({ id: feature.id, at: at });
- }
- }
- });
- if (draftPlane) {
- list.push({ id: null, frame: draftPlane.frame, draft: true });
- }
- if (draftAxis) {
- axes.push({ id: null, o: draftAxis.line.o, d: draftAxis.line.d, draft: true });
- }
- if (draftPoint) {
- points.push({ id: null, at: draftPoint.at, draft: true });
- }
- viewport.setWorkPlanes(list);
- viewport.setWorkAxes(axes);
- viewport.setWorkPoints(points);
- }
- // The coordinate system of a sketch on a picked planar face: X runs level
- // (or along world X on a horizontal face), the origin is the point of the
- // plane nearest the part origin, so sketch and model coordinates line up.
- // Sketches and work planes on faces, where the rebuild found the faces now
- function takeFaceFrames(frames, lines) {
- Object.keys(frames || {}).forEach(function (id) {
- const feature = doc.feature(id);
- if (feature) {
- resolveFace(feature.type === 'plane' ? feature.base : feature.plane, frames[id]);
- }
- });
- // Work axes (and tangent planes) on edges and round faces, where the
- // rebuild found them now
- Object.keys(lines || {}).forEach(function (id) {
- resolveWork(doc.feature(id), lines[id]);
- });
- }
- function faceFrame(target) {
- const n = target.normal;
- const d = n[0] * target.origin[0] + n[1] * target.origin[1] + n[2] * target.origin[2];
- let x = [1, 0, 0];
- if (Math.abs(n[2]) < 0.99) {
- const len = Math.hypot(n[0], n[1]);
- x = [-n[1] / len, n[0] / len, 0];
- }
- const y = [n[1] * x[2] - n[2] * x[1], n[2] * x[0] - n[0] * x[2], n[0] * x[1] - n[1] * x[0]];
- return { o: [n[0] * d, n[1] * d, n[2] * d], x: x, y: y, n: n };
- }
- // Where the model is rolled back to while an earlier sketch is edited:
- // features after it are not shown (Infinity when nothing is rolled back)
- function rollbackIndex() {
- if (!state.rollbackAt) {
- return Infinity;
- }
- const i = doc.features().findIndex(function (f) {
- return f.id === state.rollbackAt;
- });
- return i < 0 ? Infinity : i;
- }
- // Editing a sketch that features come after: show the model as it was
- // before the sketch, so later solids, sketches and planes are out of the way
- // (and cannot be picked or projected, which would loop back on the sketch)
- function rollBackTo(id) {
- const features = doc.features();
- const at = features.findIndex(function (f) {
- return f.id === id;
- });
- const later = features.slice(at + 1).some(function (f) {
- return !f.suppressed;
- });
- if (at < 0 || !later) {
- return;
- }
- state.rollbackAt = id;
- browser.setRollback(id);
- refreshWorkPlanes();
- kernel.call('rebuild', { document: doc.data(), upto: id }).then(function (result) {
- if (state.rollbackAt !== id || state.env !== 'part') {
- return; // closed again, or another document is on show
- }
- takeFaceFrames(result.frames, result.lines);
- viewport.setBodies(result.bodies);
- }).catch(function (err) {
- setStatus('The model could not be rolled back: ' + err.message);
- });
- }
- function openSketch(id) {
- if (picking()) {
- leaveMode();
- }
- if (sketcher.isOpen()) {
- closeSketch();
- }
- sketcher.open(id).then(function (ok) {
- if (!ok) {
- setStatus('This sketch cannot be opened: the plane it was drawn on is missing');
- if (state.rebuildDeferred) {
- requestRebuild();
- }
- return;
- }
- state.mode = 'sketch';
- viewport.clearSelection();
- viewport.setOriginVisible(false);
- rollBackTo(id);
- viewport.lookAlong(sketcher.frame().n);
- ribbon.setTabVisible('sketch', true);
- ribbon.showTab('sketch');
- browser.setEditing(id);
- refreshSketches();
- });
- }
- // Leave the sketch environment. The model is rebuilt now, not on every
- // stroke, because features built from the sketch may be slow to recompute.
- function closeSketch() {
- if (!sketcher.isOpen()) {
- return;
- }
- sketcher.close();
- state.mode = 'model';
- viewport.setOriginVisible(state.originVisible);
- ribbon.setTabVisible('sketch', false);
- ribbon.showTab('model');
- browser.setEditing(null);
- if (state.rollbackAt) {
- // The whole model comes back with the next rebuild (finishSketch,
- // or the change that closed the sketch)
- state.rollbackAt = null;
- state.rebuildDeferred = true;
- state.keepView = true; // the solids coming back are not a new part to zoom to
- browser.setRollback(null);
- refreshSketches();
- refreshWorkPlanes();
- }
- setPrompt('');
- setStatus('Ready');
- }
- /* ================= feature panels ================= */
- // What the status bar says while a new feature of each kind is set up
- const FEATURE_HINTS = {
- extrude: 'Extrude: pick a profile, choose how far it goes (Distance, To a plane, To Next, Through All), then OK',
- revolve: 'Revolve: pick a profile and the axis line to turn it about, then OK',
- shell: 'Shell: click the faces to leave open, set the wall thickness, then OK',
- rectpattern: 'Rectangular Pattern: click the features to repeat in the browser, set the directions, then OK',
- circpattern: 'Circular Pattern: click the features to repeat in the browser, pick the axis, then OK',
- mirror: 'Mirror: click the features to mirror in the browser (none: the whole solid), pick the plane, then OK',
- fillet: 'Fillet: click the edges to round, set the radius (Add a set for edges with another radius), then OK',
- chamfer: 'Chamfer: choose the type, click the edges to break, set the sizes, then OK',
- hole: 'Hole: place it at sketch points or by two edges (Linear), set the type, size and thread, then OK',
- plane: 'Work Plane: pick what it is defined by in the model, set the values, then OK',
- axis: 'Work Axis: pick an edge, a round face, two planes or two points, then OK',
- point: 'Work Point: pick a corner, type coordinates, or pick an axis and a plane, then OK',
- repair: 'Repair: the solid is checked and healed (gaps, slivers, open edges); compare before and after, then OK',
- sweep: 'Sweep: pick a profile, then the path (curves of another sketch), then OK',
- loft: 'Loft: click a closed area of each section sketch in order, choose Smooth or Ruled, then OK',
- draft: 'Draft: click the faces to tilt, pick the fixed plane, set the angle, then OK'
- };
- let activeFeature = null; // { kind, tool, rolledBack } while a feature panel is open
- // The ribbon button of a feature kind
- function featureButton(kind) {
- return { plane: 'work.plane', axis: 'work.axis', point: 'work.point', rectpattern: 'pat.rect', circpattern: 'pat.circ', mirror: 'pat.mirror' }[kind] || 'feat.' + kind;
- }
- // The panel kind that edits a feature (patterns come in two kinds)
- function toolKind(feature) {
- return feature.type === 'pattern' ? (feature.kind === 'circ' ? 'circpattern' : 'rectpattern') : feature.type;
- }
- // Open a feature panel: for a new feature, or to edit one (featureId).
- // While a feature is edited the model is shown as it was before it, so what
- // the feature was built on can be seen and picked again.
- function startFeature(kind, featureId) {
- if (picking()) {
- leaveMode();
- }
- if (sketcher.isOpen()) {
- finishSketch(); // as in desktop CAD, a feature command inside a sketch finishes it first
- }
- // A feature already open (the same one opened twice): closed first, so
- // the whole model it asks back for is drawn before this one rolls back
- if (activeFeature) {
- activeFeature.tool.cancel();
- }
- const tool = featureTools[kind];
- const preselected = viewport.selection();
- viewport.clearSelection();
- const shown = featureId ? kernel.call('rebuild', { document: doc.data(), upto: featureId }).then(function (result) {
- takeFaceFrames(result.frames, result.lines);
- viewport.setBodies(result.bodies);
- }) : Promise.resolve();
- shown.then(function () {
- // Fillet and chamfer pick edges of the model; the others must not react to it
- viewport.setPicking(['fillet', 'chamfer', 'shell', 'draft', 'rectpattern', 'circpattern', 'mirror'].indexOf(kind) >= 0);
- return tool.start(featureId || null, preselected, browser.selected());
- }).then(function (ok) {
- if (!ok) {
- viewport.setPicking(true);
- if (featureId) {
- requestRebuild(); // put the full model back
- }
- return;
- }
- activeFeature = { kind: kind, tool: tool, rolledBack: !!featureId };
- state.mode = 'feature';
- ribbon.showTab('model');
- ribbon.setOn(featureButton(kind), true);
- setStatus(featureId ? 'Editing ' + doc.feature(featureId).name + ': change the values, then OK' : FEATURE_HINTS[kind]);
- }).catch(function (err) {
- setStatus('The feature could not be opened: ' + err.message);
- requestRebuild();
- });
- }
- function featureClosed(kind) {
- const was = activeFeature;
- activeFeature = null;
- if (was && was.tool.pickFeature) {
- // The browser picked what a pattern repeats; that pick is done with
- browser.select(null);
- }
- state.mode = sketcher.isOpen() ? 'sketch' : 'model';
- ribbon.setOn(featureButton(kind), false);
- viewport.setPicking(true);
- setStatus('Ready');
- if (was && was.rolledBack) {
- requestRebuild(); // show the whole model again
- }
- }
- function finishSketch() {
- // Turn to the face the sketch is on, at an angle, so an extrusion out of
- // it shows (also when Extrude is what finished the sketch)
- const frame = sketcher.isOpen() ? sketcher.frame() : null;
- closeSketch();
- refreshSketches();
- if (frame && frame.n) {
- viewport.viewFace(frame.n);
- } else {
- viewport.home();
- }
- if (state.rebuildDeferred) {
- requestRebuild();
- }
- }
- function selectionText() {
- const items = viewport.selection();
- if (!items.length) {
- return 'Ready';
- }
- if (items.length === 1) {
- return 'Selected: ' + describe(items[0]);
- }
- const faces = items.filter(function (i) {
- return i.kind === 'face';
- }).length;
- return 'Selected: ' + faces + ' face' + (faces === 1 ? '' : 's') + ', ' + (items.length - faces) + ' edge' + (items.length - faces === 1 ? '' : 's');
- }
- /* ================= quick access + navigation bar ================= */
- function iconButton(parent, id, iconName, title) {
- const button = document.createElement('button');
- button.className = 'qa-btn';
- button.title = title;
- button.innerHTML = icon(iconName);
- button.addEventListener('click', function () {
- onCommand(id);
- });
- parent.appendChild(button);
- return button;
- }
- iconButton($('quickaccess'), 'file.new', 'new', 'New');
- iconButton($('quickaccess'), 'file.open', 'open', 'Open (Ctrl+O)');
- iconButton($('quickaccess'), 'file.save', 'save', 'Save (Ctrl+S)');
- const undoButton = iconButton($('quickaccess'), 'edit.undo', 'undo', 'Undo (Ctrl+Z)');
- const redoButton = iconButton($('quickaccess'), 'edit.redo', 'redo', 'Redo (Ctrl+Y)');
- $('viewcube-home').addEventListener('click', function () {
- onCommand('nav.home');
- });
- iconButton($('navbar'), 'nav.zoomall', 'zoomall', 'Zoom All');
- iconButton($('navbar'), 'nav.home', 'home', 'Home View');
- iconButton($('navbar'), 'nav.lookat', 'lookat', 'Look At');
- const orbitButton = iconButton($('navbar'), 'nav.orbit', 'orbit', 'Orbit: drag with the left button inside the circle to turn the view, outside it to roll the view (or hold F4; Shift + middle button turns it)');
- const panButton = iconButton($('navbar'), 'nav.pan', 'pan', 'Pan: drag with the left button to move the view (or drag with the middle button)');
- // Lend the left button to the view ('orbit' or 'pan'), or give it back ('select')
- function setLeftDrag(mode) {
- state.leftDrag = mode;
- viewport.setLeftDrag(mode);
- ribbon.setOn('nav.pan', mode === 'pan');
- ribbon.setOn('nav.orbit', mode === 'orbit');
- orbitButton.classList.toggle('on', mode === 'orbit');
- panButton.classList.toggle('on', mode === 'pan');
- drawOrbitMark();
- }
- // Orbit and Pan are for looking around. Commands that only move the
- // camera or restyle the view leave them on; any other command gives the
- // left button back to selecting, so the tool it starts can pick at once
- // (a chamfer its edges, a sketch its plane). So does working in a tool's
- // panel or in the model browser: a click on a chamfer's edge selector
- // means the next click in the view picks an edge.
- const VIEW_ONLY_COMMANDS = /^(nav\.(pan|orbit|zoomall|home)|style\.|proj\.|view\.origin$)/;
- function releaseLeftButton() {
- if (state.leftDrag === 'select') {
- return;
- }
- const was = state.leftDrag;
- heldOrbit = null; // letting go of F4 later brings nothing back
- setLeftDrag('select');
- setStatus((was === 'orbit' ? 'Orbit' : 'Pan') + ' off: the left button selects again');
- }
- ['pointerdown', 'focusin'].forEach(function (type) {
- document.addEventListener(type, function (event) {
- const target = event.target;
- if (state.leftDrag !== 'select' && target && target.closest && target.closest('.props, #browser')) {
- releaseLeftButton();
- }
- }, true);
- });
- // The circle shown over the model while the left button orbits: four
- // ticks outside it at the quarters and a small cross in the middle. Its
- // zones (inside, outside, the ticks) are in viewport.js orbitRing().
- function drawOrbitMark() {
- const mark = $('orbit-mark');
- // An SVG element has no `hidden` property: set the attribute itself
- const off = state.leftDrag !== 'orbit';
- mark.toggleAttribute('hidden', off);
- if (off) {
- return;
- }
- const w = $('stage').clientWidth;
- const h = $('stage').clientHeight;
- const ring = orbitRing(w, h);
- const cx = ring.cx;
- const cy = ring.cy;
- const r = ring.r;
- const t = ring.tick;
- const c = 30;
- mark.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
- mark.innerHTML = '<circle cx="' + cx + '" cy="' + cy + '" r="' + r + '"/>' +
- '<path d="M' + cx + ' ' + (cy - r - t) + 'V' + (cy - r) + 'M' + cx + ' ' + (cy + r) + 'V' + (cy + r + t) +
- 'M' + (cx - r - t) + ' ' + cy + 'H' + (cx - r) + 'M' + (cx + r) + ' ' + cy + 'H' + (cx + r + t) +
- 'M' + (cx - c) + ' ' + cy + 'H' + (cx + c) + 'M' + cx + ' ' + (cy - c) + 'V' + (cy + c) + '"/>';
- }
- if (window.ResizeObserver) {
- new ResizeObserver(drawOrbitMark).observe($('stage'));
- }
- /* ================= document -> rebuild -> display ================= */
- let featureReport = {};
- let rebuildRunning = false;
- let rebuildWanted = false;
- let lastFailed = false;
- let lastFailureText = ''; // what the status bar said about them
- // The document the shared commands (files, undo, title) act on
- function activeDoc() {
- return state.env === 'assembly' ? assembly.doc : state.env === 'drawing' ? drawing.doc : doc;
- }
- // What each kind of document is saved as
- const EXT = { part: '.aopart', assembly: '.aoasm', drawing: '.aodrw' };
- const KIND_NAMES = { part: 'part', assembly: 'assembly', drawing: 'drawing' };
- /* ================= document tabs ================= */
- // Every open document has a tab under the view (js/tabs.js). The shown one
- // lives in its environment's document (doc, assembly.doc, drawing.doc); the
- // others are kept as snapshots, undo history and view included, and come
- // back when their tab is clicked. Each tab has its own key space in the
- // kernel, so its solids, assembly parts and drawing views are found cached
- // when it is shown again. Assemblies and drawings read the parts they use
- // through files.readPath, which hands out a document open in a tab as it is
- // there (unsaved edits too): showing their tab again brings the edits in.
- const tabs = []; // { id, kind, snap, view }
- let activeTab = null;
- let tabSeq = 0;
- const tabBar = createTabBar($('doctabs'), {
- onSelect: function (id) {
- switchTo(tabById(id));
- },
- onClose: function (id) {
- const tab = tabById(id);
- if (tab) {
- closeTab(tab);
- }
- },
- onNew: function () {
- newDocument();
- }
- });
- function tabById(id) {
- return tabs.filter(function (t) {
- return t.id === id;
- })[0] || null;
- }
- function docOf(kind) {
- return kind === 'assembly' ? assembly.doc : kind === 'drawing' ? drawing.doc : doc;
- }
- function tabName(tab) {
- return tab === activeTab ? docOf(tab.kind).name : tab.snap ? tab.snap.name : '';
- }
- function tabPath(tab) {
- return tab === activeTab ? docOf(tab.kind).path : tab.snap ? tab.snap.path : '';
- }
- function tabDirty(tab) {
- return tab === activeTab ? docOf(tab.kind).isDirty() : !!tab.snap && tab.snap.data !== tab.snap.saved;
- }
- function tabData(tab) {
- return tab === activeTab ? docOf(tab.kind).data() : JSON.parse(tab.snap.data);
- }
- function renderTabs() {
- tabBar.render(tabs.map(function (t) {
- return { id: t.id, kind: t.kind, name: tabName(t), path: files.displayPath(tabPath(t)), dirty: tabDirty(t) };
- }), activeTab ? activeTab.id : null);
- scheduleAutosave();
- }
- /* ================= autosave ================= */
- // Unsaved documents are copied to the browser's storage a moment after each
- // change, so a crash or a closed browser tab does not lose them: the next
- // start offers them back. Each window has an entry of its own and keeps an
- // "alive" stamp fresh while it runs, so a window still open elsewhere is
- // never offered (PROPOSAL.md 14.8, 14.26).
- const AUTOSAVE_PREFIX = '3dmodeler.autosave.';
- const AUTOSAVE_KEY = AUTOSAVE_PREFIX + Date.now().toString(36) + Math.random().toString(36).slice(2, 7);
- const AUTOSAVE_STALE = 15000; // ms without an alive stamp: that window is gone
- let autosaveTimer = null;
- let autosaveOn = false; // this window has an entry
- let autosaveClosed = false; // closed on purpose: nothing more is kept
- function autosaveStore() {
- try {
- return window.localStorage || null;
- } catch (e) {
- return null; // storage blocked: no autosave
- }
- }
- function writeAutosave() {
- clearTimeout(autosaveTimer);
- autosaveTimer = null;
- const store = autosaveStore();
- if (!store || autosaveClosed) {
- return;
- }
- const dirty = tabs.filter(tabDirty);
- try {
- if (!dirty.length) {
- dropAutosave(AUTOSAVE_KEY);
- autosaveOn = false;
- return;
- }
- store.setItem(AUTOSAVE_KEY, JSON.stringify({
- time: Date.now(),
- tabs: dirty.map(function (t) {
- return { kind: t.kind, name: tabName(t), path: tabPath(t), text: JSON.stringify(tabData(t)) };
- })
- }));
- store.setItem(AUTOSAVE_KEY + '.alive', String(Date.now()));
- autosaveOn = true;
- } catch (e) {
- // full or blocked: this change is not kept
- }
- }
- function dropAutosave(key) {
- const store = autosaveStore();
- try {
- if (store) {
- store.removeItem(key);
- store.removeItem(key + '.alive');
- }
- } catch (e) {
- // nothing to drop
- }
- }
- function scheduleAutosave() {
- if (!autosaveTimer) {
- autosaveTimer = setTimeout(writeAutosave, 1500);
- }
- }
- // The alive stamp, while this window has unsaved work stored
- setInterval(function () {
- const store = autosaveStore();
- if (autosaveOn && store) {
- try {
- store.setItem(AUTOSAVE_KEY + '.alive', String(Date.now()));
- } catch (e) {
- // storage went away
- }
- }
- }, 5000);
- // Entries left by windows that are gone: [{ key, time, tabs }]
- function orphanedAutosaves() {
- const store = autosaveStore();
- const out = [];
- if (!store) {
- return out;
- }
- try {
- for (let i = 0; i < store.length; i++) {
- const key = store.key(i);
- if (!key || key.indexOf(AUTOSAVE_PREFIX) !== 0 || /\.alive$/.test(key) || key === AUTOSAVE_KEY) {
- continue;
- }
- const alive = Number(store.getItem(key + '.alive')) || 0;
- if (Date.now() - alive < AUTOSAVE_STALE) {
- out.pending = true; // another window still open, or one that just stopped
- continue;
- }
- try {
- const entry = JSON.parse(store.getItem(key));
- if (entry && Array.isArray(entry.tabs) && entry.tabs.length) {
- out.push({ key: key, time: entry.time, tabs: entry.tabs });
- continue;
- }
- } catch (e) {
- // unreadable: dropped below
- }
- out.push({ key: key, tabs: [] });
- }
- } catch (e) {
- return [];
- }
- return out;
- }
- // On start: offer what a crashed or closed window did not save. An entry
- // whose stamp is still fresh is looked at again once it would be stale.
- let autosaveChecks = 0;
- function offerAutosaves() {
- const found = orphanedAutosaves();
- if (found.pending && ++autosaveChecks < 2) {
- setTimeout(offerAutosaves, AUTOSAVE_STALE + 1000);
- }
- const usable = found.filter(function (f) {
- return f.tabs.length;
- });
- found.filter(function (f) {
- return !f.tabs.length;
- }).forEach(function (f) {
- dropAutosave(f.key);
- });
- if (!usable.length) {
- return;
- }
- const docs = [].concat.apply([], usable.map(function (f) {
- return f.tabs;
- }));
- const when = Math.max.apply(null, usable.map(function (f) {
- return f.time || 0;
- }));
- const names = docs.map(function (d) {
- return d.name + (d.path ? ' (' + files.displayPath(d.path) + ')' : ' (never saved)');
- });
- ask('Restore unsaved work?', '3D Modeler was closed' + (when ? ' at ' + new Date(when).toLocaleString() : '') +
- ' with changes that were not saved:\n\n' + names.join('\n') +
- '\n\nRestore opens them in tabs, still unsaved, so you can look and save them. Discard throws them away.', [
- { label: 'Discard', value: false },
- { label: 'Restore', value: true, primary: true }
- ], null).then(function (answer) {
- if (answer === null) {
- return; // asked again next time
- }
- if (answer) {
- let restored = 0;
- docs.forEach(function (d) {
- try {
- if (loadDocument(JSON.parse(d.text), d.name, d.path)) {
- docOf(d.kind).markUnsaved();
- restored++;
- }
- } catch (e) {
- // a document that cannot be read is skipped
- }
- });
- refreshChrome();
- setStatus('Restored ' + restored + (restored === 1 ? ' document' : ' documents') + ': save to keep the changes');
- }
- usable.forEach(function (f) {
- dropAutosave(f.key);
- });
- });
- }
- // An empty document nobody has touched: a file opened next takes its place
- function isPristine(tab) {
- if (tab !== activeTab || tabDirty(tab) || tabPath(tab)) {
- return false;
- }
- if (tab.kind === 'assembly') {
- return !assembly.doc.components().length;
- }
- if (tab.kind === 'drawing') {
- return !drawing.doc.views().length && !drawing.doc.annotations().length;
- }
- return !doc.features().length;
- }
- // Put away whatever is open in the shown document before another is shown
- function leaveDocument() {
- closeInspect(true);
- if (activeFeature) {
- activeFeature.tool.cancel();
- }
- appearanceTool.cancel();
- paintTool.cancel();
- if (picking()) {
- leaveMode();
- }
- if (sketcher.isOpen()) {
- closeSketch();
- }
- if (state.env === 'assembly') {
- assembly.stopTools();
- } else if (state.env === 'drawing') {
- drawing.stopTools();
- }
- setLeftDrag('select');
- viewport.setSection('none');
- ribbon.setLabel('view.section', 'Section View');
- viewport.setPreview(null);
- viewport.clearSelection();
- setPrompt('');
- }
- // F5 Previous View: the views before each change of view, newest last
- // (viewport.onViewChange); started over with every tab switch
- const viewHistory = [];
- viewport.onViewChange = function (view) {
- viewHistory.push(view);
- if (viewHistory.length > 30) {
- viewHistory.shift();
- }
- };
- // Keep the shown document (and where it was looked at) in its tab
- function stash() {
- viewHistory.length = 0;
- if (activeTab) {
- activeTab.snap = docOf(activeTab.kind).snapshot();
- activeTab.view = activeTab.kind === 'drawing' ? drawing.viewState() : viewport.viewState();
- }
- }
- // "Sample Part", then "Sample Part 2" while the first is still open
- function sampleName(base) {
- const names = tabs.map(tabName);
- let name = base;
- for (let n = 2; names.indexOf(name) >= 0; n++) {
- name = base + ' ' + n;
- }
- return name;
- }
- // Show a tab's document: a new one (fresh: { data, name, path }) or the
- // snapshot it was kept as
- function enter(tab, fresh) {
- activeTab = tab;
- if (tab.kind === 'part') {
- kernel.call('useRebuilder', { key: 'part:' + tab.id }).catch(function () {
- // The kernel failed to start; the status bar says so
- });
- state.fitNext = !!fresh;
- state.keepView = !fresh;
- if (fresh) {
- doc.reset(fresh.data, fresh.name, fresh.path);
- state.reportOnOpen = fresh.data ? doc.data() : null;
- } else {
- doc.restore(tab.snap);
- }
- } else if (tab.kind === 'assembly') {
- assembly.setKeySpace(tab.id);
- if (fresh) {
- assembly.doc.reset(fresh.data, fresh.name, fresh.path);
- } else {
- assembly.doc.restore(tab.snap);
- }
- } else {
- drawing.setKeySpace(tab.id);
- if (fresh) {
- drawing.doc.reset(fresh.data, fresh.name, fresh.path);
- } else {
- drawing.doc.restore(tab.snap);
- }
- }
- tab.snap = null;
- setEnv(tab.kind);
- // Parts and drawings pick faces and edges, never whole components
- if (tab.kind !== 'assembly') {
- viewport.setComponentMode(false);
- }
- if (!fresh && tab.view) {
- if (tab.kind === 'drawing') {
- drawing.setViewState(tab.view);
- } else {
- viewport.setViewState(tab.view);
- }
- }
- refreshChrome();
- }
- function switchTo(tab) {
- if (!tab || tab === activeTab) {
- return;
- }
- leaveDocument();
- stash();
- enter(tab, null);
- setStatus(tabName(tab) + (tabPath(tab) ? ' (' + files.displayPath(tabPath(tab)) + ')' : ''));
- }
- // Open a document in a tab of its own: a file already open shows its tab,
- // and an untouched empty document gives its place
- function openTab(kind, data, name, path) {
- if (path) {
- const open = tabs.filter(function (t) {
- return tabPath(t) === path;
- })[0];
- if (open) {
- switchTo(open);
- return open;
- }
- }
- leaveDocument();
- let tab = activeTab && isPristine(activeTab) ? activeTab : null;
- if (tab) {
- tab.kind = kind;
- tab.view = null;
- } else {
- stash();
- tab = { id: 't' + (++tabSeq), kind: kind, snap: null, view: null };
- tabs.push(tab);
- }
- enter(tab, { data: data, name: name, path: path });
- return tab;
- }
- function removeTab(tab) {
- const i = tabs.indexOf(tab);
- if (i < 0) {
- return;
- }
- const wasShown = tab === activeTab;
- if (wasShown) {
- leaveDocument();
- }
- tabs.splice(i, 1);
- // Free what the kernel kept for it
- kernel.call('dropRebuilder', { key: 'part:' + tab.id }).catch(function () {
- // The kernel is gone
- });
- assembly.forget(tab.id);
- drawing.forget(tab.id);
- if (wasShown) {
- activeTab = null;
- const next = tabs[Math.min(i, tabs.length - 1)];
- if (next) {
- enter(next, null);
- } else {
- const fresh = { id: 't' + (++tabSeq), kind: 'part', snap: null, view: null };
- tabs.push(fresh);
- enter(fresh, { data: null, name: 'Part1', path: '' });
- }
- }
- renderTabs();
- }
- function closeTab(tab) {
- if (tab !== activeTab && !tabDirty(tab)) {
- removeTab(tab);
- return;
- }
- // Show it, so the question is about what is on the screen
- switchTo(tab);
- confirmDiscard().then(function (ok) {
- if (ok) {
- removeTab(tab);
- }
- });
- }
- // Assemblies and drawings read the documents open in tabs as they are
- files.setOpenDocuments(function (path) {
- const tab = tabs.filter(function (t) {
- return tabPath(t) === path;
- })[0];
- return tab ? { data: tabData(tab), name: tabName(tab) } : null;
- });
- function refreshChrome() {
- const d = activeDoc();
- const title = d.name + (d.isDirty() ? ' *' : '');
- $('doctitle').textContent = title;
- undoButton.disabled = !d.canUndo();
- redoButton.disabled = !d.canRedo();
- try {
- window.ao_module_setWindowTitle('3D Modeler - ' + title);
- } catch (e) {
- // Not inside an ArozOS float window
- }
- if (native.available()) {
- // The Mac window: its title, the close button's unsaved dot, the
- // file in the title bar, and which File menu items apply
- document.title = d.name;
- native.windowInfo({ edited: tabs.some(tabDirty), path: d.path, kind: state.env });
- }
- renderTabs();
- }
- // Only one rebuild runs at a time. Changes made meanwhile collapse into one
- // further rebuild of the then current document.
- function requestRebuild() {
- if (rebuildRunning) {
- rebuildWanted = true;
- return;
- }
- rebuildRunning = true;
- rebuildWanted = false;
- state.rebuildDeferred = false;
- const asked = doc.data();
- // The first build of a part that is being opened shows how far it is
- // (the document's reset asks for it before the tab is known)
- const shown = opening && opening.kind === 'part' && (!opening.tab || opening.tab === activeTab) ? opening : null;
- if (shown) {
- shown.tab = activeTab;
- shown.task.update({ text: 'Building the part', fraction: null });
- }
- kernel.call('rebuild', { document: asked }, shown ? function (info) {
- shown.task.update(buildText(info));
- } : null).then(function (result) {
- if (state.env !== 'part') {
- return; // an assembly is on show; the (empty) part waits
- }
- const opened = state.reportOnOpen === asked;
- if (opened) {
- state.reportOnOpen = null;
- }
- featureReport = result.features;
- takeFaceFrames(result.frames, result.lines);
- followModel(result.projections);
- // A feature or an earlier sketch being edited keeps its rolled back
- // view; closing it asks again
- if (!(activeFeature && activeFeature.rolledBack) && !state.rollbackAt) {
- const first = !viewport.bodyCount() && result.bodies.length > 0;
- viewport.setBodies(result.bodies);
- refreshWorkPlanes(); // their size follows the part
- if (first && !state.fitNext && !state.keepView) {
- viewport.zoomAll(); // the first solid of the part: bring it into view
- }
- if (result.bodies.length) {
- state.keepView = false;
- }
- }
- browser.render(featureReport, result.bodies.length);
- if (state.fitNext) {
- state.fitNext = false;
- viewport.home();
- }
- const failed = doc.features().filter(function (f) {
- return featureReport[f.id] && featureReport[f.id].status === 'error';
- });
- const hadFailures = lastFailed;
- lastFailed = failed.length > 0;
- if (failed.length && opened) {
- reportOpenFailures(failed);
- }
- if (failed.length) {
- lastFailureText = failed.length === 1 ? failed[0].name + ' could not be built: ' + featureReport[failed[0].id].message
- : failed.length + ' features could not be built, see the model browser';
- setStatus(lastFailureText);
- } else if (hadFailures && state.mode === 'model' && $('status-msg').textContent === lastFailureText) {
- setStatus('Ready'); // clear the error text once the part builds again (not a newer message)
- }
- // A solid that does not close up (or one the mesher patched) is
- // said once, when it turns up
- const unhealthy = result.bodies.some(function (b) {
- return b.health && (b.health.open || b.health.multiple || b.health.empty || b.health.patched);
- });
- if (unhealthy && !state.unhealthy && !failed.length) {
- setStatus('The solid has open edges or faces that did not mesh cleanly: Inspect > Check Geometry shows where, 3D Model > Repair fixes it');
- }
- state.unhealthy = unhealthy;
- checkPanel.refresh();
- }).catch(function (err) {
- setStatus('Rebuild failed: ' + err.message);
- }).then(function () {
- if (shown) {
- endOpening(shown);
- }
- rebuildRunning = false;
- if (rebuildWanted) {
- requestRebuild();
- }
- });
- }
- // A part that was just opened and has features that cannot be built: say
- // which and why at once, rather than leaving it to red rows in the tree
- function reportOpenFailures(failed) {
- const lines = failed.slice(0, 8).map(function (f) {
- return f.name + ': ' + featureReport[f.id].message;
- });
- if (failed.length > 8) {
- lines.push('and ' + (failed.length - 8) + ' more');
- }
- tell(failed.length === 1 ? 'A feature could not be built' : failed.length + ' features could not be built',
- doc.name + ' opened, but ' + (failed.length === 1 ? 'this feature fails' : 'these features fail') + ':\n\n' + lines.join('\n') +
- '\n\nThey are marked red in the model browser. Edit them, Suppress them, or drag End of Part above them to work on the rest of the part.');
- }
- doc.onChange(function (reason) {
- // Every size box understands the part's parameter names
- setScope(evaluateParameters(doc.data().parameters).values);
- if (state.env === 'part') {
- viewport.setHiddenBodies(doc.data().hiddenBodies || []);
- }
- if (reason === 'visual') {
- // Hidden, shown or shared: nothing to rebuild, nothing to close
- refreshChrome();
- browser.render();
- refreshSketches();
- refreshWorkPlanes();
- return;
- }
- refreshChrome();
- if (reason === 'amend') {
- // The app's own follow-up (projected geometry following the model):
- // rebuild, but leave open panels and the sketcher alone
- browser.render();
- refreshSketches();
- refreshWorkPlanes();
- if (sketcher.isOpen()) {
- state.rebuildDeferred = true;
- } else {
- requestRebuild();
- }
- return;
- }
- if (appearanceTool.isOpen() && reason !== 'saved') {
- appearanceTool.cancel(); // undo or another part pulled the look from under the panel
- }
- if (paintTool.isOpen() && reason !== 'saved') {
- paintTool.cancel();
- }
- if (state.env === 'part') {
- viewport.setAppearance(doc.data().appearance || null);
- }
- if (activeFeature) {
- activeFeature.tool.cancel(); // undo, redo or a new part pulled the model from under the panel
- }
- if (sketcher.isOpen()) {
- // Another part was loaded, the open sketch was deleted or undone away,
- // or undo / redo changed it under the sketcher
- const gone = reason === 'reset' || reason === 'restore' || !doc.feature(sketcher.featureId());
- if (gone || ((reason === 'undo' || reason === 'redo') && !sketcher.reload())) {
- closeSketch();
- }
- }
- browser.render();
- refreshSketches();
- refreshWorkPlanes();
- if (reason === 'saved') {
- return;
- }
- if (sketcher.isOpen()) {
- state.rebuildDeferred = true;
- } else {
- requestRebuild();
- }
- });
- /* ================= files ================= */
- function fail(title, err) {
- setStatus(title + ': ' + err.message);
- return tell(title, err.message);
- }
- // Resolves to true when it is fine to throw the current document away
- function confirmDiscard() {
- const d = activeDoc();
- if (!d.isDirty()) {
- return Promise.resolve(true);
- }
- return ask('Unsaved changes', 'Save the changes to ' + d.name + ' first?', [
- { label: 'Cancel', value: 'cancel' },
- { label: 'Do Not Save', value: 'discard' },
- { label: 'Save', value: 'save', primary: true }
- ], 'cancel').then(function (answer) {
- if (answer === 'discard') {
- return true;
- }
- return answer === 'save' ? saveDocument(false) : false;
- });
- }
- // Switch the window between the part, assembly and drawing environments.
- // What was open in the other one is put away; its document stays (the tab
- // it belongs to was stashed before, see enter()).
- function setEnv(env) {
- if (state.env === env) {
- return;
- }
- const was = state.env;
- closeInspect(true);
- if (activeFeature) {
- activeFeature.tool.cancel();
- }
- if (picking()) {
- leaveMode();
- }
- if (sketcher.isOpen()) {
- closeSketch();
- }
- setLeftDrag('select');
- viewport.setSection('none');
- ribbon.setLabel('view.section', 'Section View');
- viewport.setPreview(null);
- viewport.clearSelection();
- // Put away what was open
- if (was === 'assembly') {
- assembly.deactivate();
- } else if (was === 'drawing') {
- drawing.deactivate();
- showSheetChrome(false);
- }
- viewport.setBodies([]);
- viewport.setHiddenBodies(env === 'part' ? doc.data().hiddenBodies || [] : []);
- state.env = env;
- refreshMeshes(); // a part's reference meshes only show in the part
- ribbon.setMode(env);
- ribbon.setTabVisible('sketch', false);
- $('tree').hidden = env !== 'part';
- $('asm-tree').hidden = env !== 'assembly';
- $('drw-tree').hidden = env !== 'drawing';
- $('browser-head').textContent = { part: 'Model', assembly: 'Assembly', drawing: 'Drawing' }[env];
- // Only a part shows through the shared body material; assemblies and
- // drawings give each body its own
- viewport.setAppearance(env === 'part' ? doc.data().appearance || null : null);
- if (env === 'assembly') {
- assembly.activate();
- ribbon.showTab('assemble');
- } else if (env === 'drawing') {
- drawing.activate();
- ribbon.showTab('drawviews');
- } else {
- ribbon.showTab('model');
- requestRebuild();
- }
- refreshChrome();
- }
- // While a drawing shows its sheet the 3D view's own controls are put away;
- // the Drawing View panel brings the 3D view back to pick a direction
- function showSheetChrome(sheet) {
- $('stage').classList.toggle('sheet-mode', !!sheet);
- }
- // A part, an assembly or a drawing, by its format, in a tab of its own.
- // picture: the one saved in the file (io/preview.js), shown while it loads
- function loadDocument(data, name, path, picture) {
- const kind = data && data.format === 'aodrw' ? 'drawing' : data && data.format === 'aoasm' ? 'assembly' : 'part';
- let clean = null;
- try {
- if (data) {
- const copy = preview.stripPreview(JSON.parse(JSON.stringify(data)));
- clean = kind === 'drawing' ? validateDrawing(copy) : kind === 'assembly' ? validateAssembly(copy) : validatePart(copy);
- }
- } catch (err) {
- endOpening();
- fail('The ' + KIND_NAMES[kind] + ' could not be opened', err);
- return false;
- }
- // A file open in a tab already only shows that tab; an empty part has
- // nothing to build
- const already = path && tabs.some(function (t) {
- return tabPath(t) === path;
- });
- if (clean && !already) {
- if (!opening) {
- beginOpening(name + EXT[kind]);
- }
- opening.task.update({ title: 'Opening ' + name + EXT[kind], text: 'Building the ' + KIND_NAMES[kind], fraction: null, preview: picture || '' });
- opening.tab = null; // the tab openTab gives
- opening.kind = kind;
- } else {
- endOpening();
- }
- const which = opening;
- const tab = openTab(kind, clean, name, path);
- if (which && which === opening) {
- which.tab = tab;
- // An assembly or drawing with nothing to read is there at once
- const env = kind === 'assembly' ? assembly : kind === 'drawing' ? drawing : null;
- if (env && !env.isLoading()) {
- endOpening(which);
- }
- }
- return true;
- }
- // The model a new drawing starts from: the part or assembly that was open
- // (by its file when it is saved, else kept inside the drawing), or null
- function drawingSuggestion() {
- const copy = function (d) {
- return JSON.parse(JSON.stringify(d));
- };
- if (state.env === 'part' && doc.features().some(function (f) {
- return f.type !== 'sketch' && f.type !== 'plane';
- })) {
- return { data: copy(doc.data()), name: doc.name, path: doc.isDirty() ? '' : doc.path };
- }
- if (state.env === 'assembly' && assembly.doc.components().length) {
- return { data: copy(assembly.doc.data()), name: assembly.doc.name, path: assembly.doc.isDirty() ? '' : assembly.doc.path };
- }
- return null;
- }
- // A new document in a tab of its own (the open ones stay open)
- function newDocument() {
- chooseNew().then(function (kind) {
- if (!kind) {
- return;
- }
- const names = tabs.map(tabName);
- if (kind === 'drawing') {
- // The part or assembly on show is what the drawing starts from
- const suggest = drawingSuggestion();
- openTab('drawing', null, freeName('Drawing', names), '');
- drawing.startNew(suggest);
- } else if (kind === 'assembly') {
- openTab('assembly', null, freeName('Assembly', names), '');
- setStatus('New assembly: Assemble > Place puts in the first part, which is grounded at the origin');
- } else {
- openTab('part', null, freeName('Part', names), '');
- setStatus('New part: Start 2D Sketch on an origin plane');
- }
- });
- }
- function openDocument() {
- let reading = null;
- files.open(function (name) {
- reading = beginOpening(name);
- }).then(function (file) {
- if (file && loadDocument(file.data, file.name, file.path, file.preview)) {
- setStatus('Opened ' + (files.displayPath(file.path) || file.name));
- } else if (!file) {
- endOpening(reading);
- }
- }).catch(function (err) {
- endOpening(reading);
- fail('The part could not be opened', err);
- });
- }
- // The picture saved in the file, which the ArozOS File Manager shows as
- // its thumbnail (io/preview.js): a drawing's sheet, else the solids as the
- // view looks at them. Resolves to a JPEG data URL, or null without one.
- function documentPreview() {
- let canvas = null;
- try {
- canvas = state.env === 'drawing' ? drawing.previewCanvas(preview.PREVIEW_SIDE)
- : viewport.capturePreview(preview.PREVIEW_SIDE);
- } catch (err) {
- canvas = null; // the file is saved without its picture
- }
- return preview.encode(canvas);
- }
- // Resolves to true when the part (or assembly) was written
- function saveDocument(askWhere) {
- const d = activeDoc();
- const ext = EXT[state.env];
- const kind = state.env;
- // The picture is taken now, as the document is on screen; encoding it
- // runs in a worker and gives up rather than hold the save up for long
- return documentPreview().then(function (picture) {
- // Assemblies and drawings write their links relative to where they land
- const text = d.serializeFor ? function (target) {
- return preview.withPreview(d.serializeFor(target), picture);
- } : preview.withPreview(d.serialize(), picture);
- return files.save(text, d.name, d.path, askWhere, ext);
- }).then(function (saved) {
- if (!saved) {
- return false;
- }
- d.name = saved.name;
- d.path = saved.path;
- d.markSaved();
- setStatus(saved.path ? 'Saved to ' + files.displayPath(saved.path) : 'Downloaded ' + saved.name + ext);
- return true;
- }).catch(function (err) {
- fail('The ' + KIND_NAMES[kind] + ' could not be saved', err);
- return false;
- });
- }
- /* ================= inspect ================= */
- // The mass from the part's material (Appearance > Material), or an example
- function massLines(volume) {
- const mass = massOf(volume, doc.data().material);
- return mass ? ['Mass: ' + mass.text + ' in ' + mass.material]
- : ['Mass = volume x density of your material, for example PLA 1.24 g/cm3: ' + mm(volume / 1000 * 1.24, 2) + ' g.',
- 'Appearance > Material sets the material of the part.'];
- }
- // The threads of the part's holes, as notes (threads are not modelled)
- function threadNotes() {
- const lines = [];
- doc.features().forEach(function (f) {
- if (f.type === 'hole' && !f.suppressed && f.thread && f.thread.designation) {
- const sketch = doc.feature(f.sketch);
- const count = sketch ? sketchModel.holePoints(sketch).length : 0;
- lines.push(f.name + ': ' + count + ' x ' + f.thread.designation + (f.thread.depth ? ', ' + mm(f.thread.depth, 2) + ' mm deep' : ', through'));
- }
- });
- return lines.length ? ['', 'Threads (notes, not in the volume):'].concat(lines) : [];
- }
- function showMassProperties() {
- if (!viewport.bodyCount()) {
- setStatus('There is no solid to measure yet');
- return;
- }
- kernel.call('massProperties').then(function (m) {
- const line = function (label, values, unit) {
- return label + ': ' + values.map(function (v) {
- return mm(v, 3);
- }).join(' x ') + ' ' + unit;
- };
- tell('Mass Properties of ' + doc.name, [
- 'Solid bodies: ' + m.bodies,
- line('Volume', [m.volume], 'mm3') + ' (' + mm(m.volume / 1000, 3) + ' cm3)',
- line('Surface area', [m.area], 'mm2'),
- line('Overall size (X x Y x Z)', m.size, 'mm'),
- 'Centre of gravity: X ' + mm(m.centre[0], 3) + ', Y ' + mm(m.centre[1], 3) + ', Z ' + mm(m.centre[2], 3) + ' mm',
- ''
- ].concat(massLines(m.volume)).concat(threadNotes()).join('\n'));
- }).catch(function (err) {
- fail('The part could not be measured', err);
- });
- }
- // Measure and Section View: panels shared by parts and assemblies
- let activeInspect = null; // { kind: "measure" | "section", tool }
- function partDistance(a, b) {
- const ref = function (item) {
- return item.kind === 'edge' ? { type: 'edge', body: item.body, mid: item.mid, length: item.length }
- : { type: 'face', body: item.body, index: item.index };
- };
- return kernel.call('distance', { a: ref(a), b: ref(b) });
- }
- function startInspect(kind, arg) {
- closeInspect(true);
- if (sketcher.isOpen()) {
- finishSketch();
- }
- if (activeFeature) {
- activeFeature.tool.cancel();
- }
- if (state.env === 'assembly') {
- assembly.stopTools();
- }
- const tool = kind === 'section' ? sectionPanel : kind === 'check' ? checkPanel : state.env === 'assembly' ? measureAssembly : measurePart;
- if (!viewport.bodyCount()) {
- setStatus(kind === 'section' ? 'There is nothing to cut yet' : kind === 'check' ? 'There is nothing to check yet' : 'There is nothing to measure yet');
- return;
- }
- if (tool.start(arg)) {
- activeInspect = { kind: kind, tool: tool };
- ribbon.setOn('ins.measure', kind === 'measure');
- ribbon.setOn('ins.check', kind === 'check');
- setStatus(kind === 'measure' ? 'Measure: click a face or an edge, then a second one' : kind === 'check' ? 'Check Geometry: checking the solid'
- : 'Section View: pick the plane and drag its position');
- }
- }
- // Put an open Measure or Section panel away (a section is kept)
- function closeInspect(keep) {
- if (activeInspect) {
- if (activeInspect.kind === 'section' && keep) {
- activeInspect.tool.accept();
- } else {
- activeInspect.tool.cancel();
- }
- }
- }
- function inspectClosed(kind) {
- if (!activeInspect || activeInspect.kind !== kind) {
- return;
- }
- activeInspect = null;
- ribbon.setOn('ins.measure', false);
- ribbon.setOn('ins.check', false);
- if (state.env === 'assembly') {
- viewport.setComponentMode(true);
- }
- if (kind === 'section') {
- const mode = viewport.sectionSpec().mode;
- ribbon.setLabel('view.section', mode === 'none' ? 'Section View' : 'Section: ' + { half: 'Half', quarter: 'Quarter', threequarter: '3/4' }[mode]);
- }
- setStatus('Ready');
- }
- /* ================= import and export ================= */
- // How fine the triangles of a mesh export are (the largest gap allowed
- // between a curved face and its triangles, and between neighbours) is
- // picked in io/exportdialog.js, which shows the size each choice makes
- const MESH_TEXT = {
- stl: 'STL keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.',
- obj: 'OBJ keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.',
- '3mf': '3MF keeps triangles, not the exact curves. How closely should they follow curved faces? Finer makes a larger file.'
- };
- function exportPart(format) {
- if (!viewport.bodyCount()) {
- setStatus('There is nothing to export yet');
- return;
- }
- const name = activeDoc().name;
- const base = name + '.' + format;
- let made;
- if (state.env === 'assembly' && (format === 'step' || format === 'brep')) {
- setStatus('Writing ' + format.toUpperCase() + '...');
- made = assembly.exportContent(format);
- } else if (format === 'step' || format === 'brep') {
- setStatus('Writing ' + format.toUpperCase() + '...');
- made = kernel.call('exportText', { format: format }).then(function (out) {
- return { text: out.text };
- });
- } else {
- const choices = [{ key: 'units', label: 'Units', items: [{ id: 'mm', label: 'Millimetres' }, { id: 'in', label: 'Inches' }] }];
- if (format === 'stl') {
- choices.push({ key: 'encoding', label: 'Encoding', items: [{ id: 'binary', label: 'Binary (small)' }, { id: 'ascii', label: 'ASCII text' }] });
- }
- made = askMeshExport({
- title: 'Export ' + format.toUpperCase(),
- text: MESH_TEXT[format],
- format: format,
- choices: choices,
- // The whole file at one fineness: its size is shown, and it is
- // what is saved when that fineness is exported
- make: function (level, picked) {
- const quality = { deflection: level.deflection, angle: level.angle };
- const meshed = state.env === 'assembly' ? assembly.exportContent(format, quality) : kernel.call('mesh', quality);
- return meshed.then(function (raw) {
- // Inches: every coordinate over 25.4 (the file has no unit of its own)
- const out = Object.assign({}, raw, { bodies: scaled(raw.bodies, picked && picked.units === 'in' ? 1 / 25.4 : 1) });
- let triangles = 0;
- out.bodies.forEach(function (b) {
- triangles += b.indices.length / 3;
- });
- let content;
- const units = picked && picked.units === 'in' ? 'in' : 'mm';
- if (format === 'obj') {
- content = { text: toOBJ(out.bodies, name, units) };
- } else if (format === 'stl' && picked && picked.encoding === 'ascii') {
- content = { text: toSTLText(out.bodies, name) };
- } else {
- content = { bytes: format === 'stl' ? toSTL(out.bodies, units) : to3MF(out.bodies, units) };
- }
- const size = content.text !== undefined ? new Blob([content.text]).size : content.bytes.length;
- // What a slicer will say: each solid checked on its own
- let open = 0;
- let multiple = 0;
- out.bodies.forEach(function (b) {
- const check = meshCheck(b);
- open += check.open;
- multiple += check.multiple;
- });
- const warning = open || multiple ? 'Not watertight: ' + [open ? open + ' open' : '', multiple ? multiple + ' non-manifold' : ''].filter(Boolean).join(' and ') +
- ' edges. Inspect > Check Geometry shows where' : '';
- return { content: content, size: size, triangles: triangles, warning: warning };
- });
- }
- }).then(function (chosen) {
- if (chosen) {
- setStatus('Saving ' + format.toUpperCase() + ' (' + chosen.level.label.toLowerCase() + ')...');
- }
- return chosen ? chosen.content : null;
- });
- }
- made.then(function (content) {
- return content ? files.saveAs(base, content) : null;
- }).then(function (saved) {
- setStatus(saved ? (saved.path ? 'Exported to ' + files.displayPath(saved.path) : 'Downloaded ' + saved.name) : 'Ready');
- }).catch(function (err) {
- fail('The part could not be exported', err);
- });
- }
- // A STEP file becomes a feature of its own that later features build on.
- // file: { name, text }
- function addImport(file) {
- setStatus('Reading ' + file.name + '...');
- return kernel.call('importInfo', { text: file.text }).then(function (info) {
- const id = doc.newId();
- const name = doc.newName('import');
- doc.change('Import ' + file.name, function (d) {
- d.features.push({ id: id, type: 'import', name: name, format: 'step', source: file.name, data: file.text });
- });
- state.fitNext = true;
- setStatus('Imported ' + info.solids + (info.solids === 1 ? ' solid' : ' solids') + ' from ' + file.name);
- });
- }
- function importStep() {
- files.openOther(['step', 'stp'], false).then(function (file) {
- return file ? addImport(file) : null;
- }).catch(function (err) {
- fail('The file could not be imported', err);
- });
- }
- // An STL or OBJ file becomes a reference mesh: drawn pale to model around,
- // not a solid (the kernel ignores it; it is not exported or weighed)
- const MESH_WARN_BYTES = 8 * 1024 * 1024;
- function importMesh(format) {
- files.openOther([format], format === 'stl').then(function (file) {
- if (!file) {
- return null;
- }
- setStatus('Reading ' + file.name + '...');
- const mesh = format === 'stl' ? parseSTL(file.bytes) : parseOBJ(file.text);
- const data = encodeMesh(mesh);
- const size = data.positions.length + data.indices.length;
- const info = meshInfo(mesh);
- const go = size < MESH_WARN_BYTES ? Promise.resolve(true) : ask('Large mesh', file.name + ' has ' + info.triangles.toLocaleString('en-US') +
- ' triangles and adds about ' + Math.round(size / 1048576) + ' MB to the part file. Bring it in anyway?',
- [{ label: 'Cancel', value: false }, { label: 'Bring In', value: true, primary: true }], false);
- return go.then(function (ok) {
- if (!ok) {
- setStatus('Ready');
- return;
- }
- const id = doc.newId();
- const name = doc.newName('mesh');
- doc.change('Bring in ' + file.name, function (d) {
- d.features.push({ id: id, type: 'mesh', name: name, format: format, source: file.name, data: data });
- });
- const span = info.max.map(function (v, k) {
- return +(v - info.min[k]).toFixed(2);
- });
- setStatus(name + ': ' + file.name + ', ' + info.triangles.toLocaleString('en-US') + ' triangles, ' + span.join(' x ') +
- ' mm. A reference to model around: it is not a solid and is not exported.');
- });
- }).catch(function (err) {
- fail('The mesh could not be brought in', err);
- });
- }
- function deleteFeature(id) {
- const feature = doc.feature(id);
- const dependents = doc.dependents(id);
- const go = !dependents.length ? Promise.resolve(true) : ask('Delete ' + feature.name,
- dependents.map(function (f) {
- return f.name;
- }).join(', ') + (dependents.length === 1 ? ' is' : ' are') + ' built from it and will be deleted too.',
- [{ label: 'Cancel', value: false }, { label: 'Delete', value: true, primary: true }], false);
- go.then(function (ok) {
- if (ok) {
- doc.remove(id);
- }
- });
- }
- // The desktop calls ao_module_close() when the window's close button is
- // pressed: unsaved work is asked about first.
- const closeWindow = window.ao_module_closeHandler;
- // Resolves to true when the window may close: nothing unsaved, or the
- // person said so
- function confirmCloseAll() {
- closeInspect(true);
- const dirty = tabs.filter(tabDirty);
- if (!dirty.length) {
- return Promise.resolve(true);
- }
- if (dirty.length === 1 && dirty[0] === activeTab) {
- return confirmDiscard();
- }
- return ask('Unsaved changes', dirty.map(tabName).join(', ') + (dirty.length === 1 ? ' has' : ' have') +
- ' changes that are not saved. Close 3D Modeler anyway?', [
- { label: 'Close Without Saving', value: true },
- { label: 'Cancel', value: false, primary: true }
- ], false);
- }
- // Closed on purpose (saved, or not saved on purpose): nothing to restore
- function closingOnPurpose() {
- clearTimeout(autosaveTimer);
- autosaveTimer = null;
- autosaveClosed = true;
- autosaveOn = false;
- dropAutosave(AUTOSAVE_KEY);
- }
- window.ao_module_close = function () {
- confirmCloseAll().then(function (ok) {
- if (ok) {
- closingOnPurpose();
- }
- if (ok && typeof closeWindow === 'function') {
- closeWindow();
- }
- });
- };
- // The page goes away (closed, reloaded): its entry is stale at once, so the
- // next start offers it without waiting for the stamp to age
- window.addEventListener('pagehide', function () {
- if (autosaveTimer || autosaveOn) {
- writeAutosave(); // a change of the last moment too
- }
- if (autosaveOn) {
- try {
- autosaveStore().setItem(AUTOSAVE_KEY + '.alive', '0');
- } catch (e) {
- // storage went away
- }
- }
- });
- window.addEventListener('beforeunload', function (event) {
- // Covers a browser tab; inside the desktop the handler above runs first
- if (tabs.some(tabDirty) && !window.ao_module_virtualDesktop) {
- event.preventDefault();
- }
- });
- /* ================= commands ================= */
- function picking() {
- return state.mode === 'pick-sketch-plane' || state.mode === 'pick-lookat' || state.mode === 'pick-workplane';
- }
- function leaveMode() {
- viewport.stopPlanePick();
- state.pickText = null;
- ribbon.setOn('sketch.start', false);
- ribbon.setOn('nav.lookat', false);
- ribbon.setOn('work.plane', false);
- setPrompt('');
- state.mode = sketcher.isOpen() ? 'sketch' : 'model';
- }
- // The plane reference a sketch or work plane stores for a picked target.
- // A face also remembers its normal and the point clicked, so the sketch
- // (or work plane) can follow the face when an earlier feature moves it
- function referenceOf(target) {
- return target.kind === 'origin' ? { ref: 'origin:' + target.key }
- : target.kind === 'work' ? { ref: 'plane', id: target.id }
- : target.point ? { ref: 'face', frame: faceFrame(target), face: target.name ? { normal: target.normal, point: target.point, name: target.name } : { normal: target.normal, point: target.point } }
- : { ref: 'face', frame: faceFrame(target) };
- }
- /* ---- dragging a plane into an offset sketch plane (planedrag.js) ---- */
- const offsetBox = createOffsetBox($('stage'));
- function offsetFrame(target, offset) {
- const base = planeFrame(referenceOf(target), doc.features());
- return base ? {
- o: [base.o[0] + base.n[0] * offset, base.o[1] + base.n[1] * offset, base.o[2] + base.n[2] * offset],
- x: base.x, y: base.y, n: base.n
- } : null;
- }
- function showOffsetDraft(target, offset) {
- const frame = offsetFrame(target, offset);
- draftPlane = frame ? { frame: frame, id: null } : null;
- refreshWorkPlanes();
- }
- const SKETCH_PLANE_DRAG = {
- frameOf: function (target) {
- return planeFrame(referenceOf(target), doc.features());
- },
- move: function (target, offset, at) {
- showOffsetDraft(target, offset);
- offsetBox.show(at[0], at[1], offset);
- setStatus('Offset ' + offset + ' mm: release, then type the exact distance');
- },
- end: function (target, offset, at) {
- leaveMode();
- showOffsetDraft(target, offset);
- setPrompt('Enter the offset of the new sketch plane');
- offsetBox.edit(at[0], at[1], offset, function (value) {
- showOffsetDraft(target, value);
- }).then(function (value) {
- draftPlane = null;
- refreshWorkPlanes();
- setPrompt('');
- if (value === null) {
- setStatus('Ready');
- } else if (Math.abs(value) < 1e-9) {
- planePicked(target); // no offset: a sketch on the plane itself
- } else {
- sketchOnOffsetPlane(target, value);
- }
- });
- }
- };
- // A work plane offset from the target and a new sketch on it, one undo step
- function sketchOnOffsetPlane(target, offset) {
- const planeId = doc.newId();
- let k = Number(planeId.slice(1)) + 1;
- while (doc.feature('f' + k)) {
- k++;
- }
- const sketchId = 'f' + k;
- const planeName = doc.newName('plane');
- const sketchName = doc.newName('sketch');
- doc.change('Sketch on ' + planeName, function (d) {
- d.features.push({ id: planeId, type: 'plane', name: planeName, base: referenceOf(target), offset: offset });
- d.features.push({ id: sketchId, type: 'sketch', name: sketchName, plane: { ref: 'plane', id: planeId }, geometry: [], constraints: [] });
- });
- setStatus(planeName + ' made ' + offset + ' mm from the plane; sketching on it');
- openSketch(sketchId);
- }
- // target: { kind: "origin", key }, { kind: "face", body, face, origin, normal }
- // or { kind: "work", id } for a work plane feature
- function planePicked(target) {
- state.pickText = null;
- const work = target.kind === 'work' ? doc.feature(target.id) : null;
- const label = target.kind === 'origin' ? ORIGIN_PLANES[target.key].label : work ? work.name : 'the selected face';
- const reference = referenceOf(target);
- const turn = function () {
- if (target.kind === 'origin') {
- viewport.lookAtPlane(target.key);
- } else {
- viewport.lookAlong(work ? workPlaneFrame(work, doc.features()).n : target.normal);
- }
- };
- if (state.mode === 'pick-workplane') {
- // The base of a new work plane: hand it to the panel
- leaveMode();
- featureTools.plane.prepare(reference);
- startFeature('plane', null);
- return;
- }
- if (state.mode === 'pick-lookat') {
- leaveMode();
- turn();
- setStatus('Looking at ' + label);
- return;
- }
- // A new sketch on the picked plane, opened in the sketcher
- leaveMode();
- const id = doc.newId();
- const plane = reference;
- // A sketch on a face starts with the edges of that face as reference
- // geometry, so new geometry can be snapped, constrained and dimensioned
- // to the model (and the face outline can bound a profile)
- const start = { geometry: [], constraints: [] };
- if (target.kind === 'face') {
- viewport.curvesOf({ type: 'face', body: target.body, index: target.face }).forEach(function (curve) {
- addProjected(start, plane.frame, curve);
- });
- }
- doc.change('Create sketch', function (d) {
- d.features.push({ id: id, type: 'sketch', name: doc.newName('sketch'), plane: plane, geometry: start.geometry, constraints: [] });
- });
- openSketch(id);
- }
- function startPlanePick(mode, button, what) {
- state.mode = mode;
- ribbon.setOn(button, true);
- // Orbit or Pan would keep the left button: the pick (and dragging an
- // offset plane off the one picked) needs it back
- if (state.leftDrag !== 'select') {
- setLeftDrag('select');
- }
- // With a solid in the part the user picks one of its planar faces; the
- // origin planes are only offered in an empty part (or from the browser)
- const text = viewport.bodyCount() ? 'Select a planar face ' + what : 'Select plane ' + what;
- state.pickText = text;
- setPrompt(text);
- setStatus(text);
- // Start 2D Sketch: dragging off a plane makes an offset plane to sketch on
- viewport.startPlanePick(planePicked, mode === 'pick-workplane', mode === 'pick-sketch-plane' ? SKETCH_PLANE_DRAG : null);
- }
- function runSelfTest() {
- if (!state.kernelReady) {
- setStatus('The modelling kernel is still loading');
- return;
- }
- setStatus('Running kernel self-test...');
- kernel.call('selftest').then(function (out) {
- const s = out.stats;
- setStatus('Kernel self-test passed: extrude, hole, fillet and chamfer in ' + s.buildMs + ' ms, ' + s.faces + ' faces, ' +
- s.triangles + ' triangles, volume ' + s.volume.toFixed(1) + ' mm3, STEP export ' + (s.stepBytes / 1024).toFixed(1) + ' KB');
- }).catch(function (err) {
- setStatus('Kernel self-test failed: ' + err.message);
- });
- }
- function onCommand(id) {
- closeMenu();
- if (offsetBox.isOpen()) {
- offsetBox.hide(); // another command: the offset plane is dropped
- }
- // The scene (lighting, shadows, ...) changes how things look, nothing more
- if (sceneCommand(id)) {
- return;
- }
- if (!VIEW_ONLY_COMMANDS.test(id)) {
- releaseLeftButton();
- }
- const wasPicking = picking() ? state.mode : null;
- if (wasPicking) {
- leaveMode();
- }
- // Any command other than looking around puts an open feature panel away
- const wasFeature = activeFeature ? activeFeature.kind : null;
- if (activeFeature && !/^(nav|view|style|proj)\./.test(id)) {
- activeFeature.tool.cancel();
- }
- // ... and an open Measure or Section panel (a section stays on)
- const wasInspect = activeInspect ? activeInspect.kind : null;
- if (activeInspect && !/^(nav|view|style|proj)\./.test(id)) {
- closeInspect(true);
- }
- // ... and the Appearance panel (its own button toggles it)
- const wasAppearance = appearanceTool.isOpen();
- if (wasAppearance && !/^(nav|view|style|proj)\./.test(id)) {
- appearanceTool.cancel();
- }
- const wasPaint = paintTool.isOpen();
- if (wasPaint && !/^(nav|view|style|proj)\./.test(id)) {
- paintTool.cancel();
- }
- const wasMaterial = materialTool.isOpen();
- if (wasMaterial && !/^(nav|view|style|proj)\./.test(id)) {
- materialTool.cancel();
- }
- const wasParams = paramTable.isOpen();
- if (wasParams && !/^(nav|view|style|proj)\./.test(id)) {
- paramTable.cancel();
- }
- if (id === 'manage.params') {
- if (!wasParams && state.env === 'part') {
- if (sketcher.isOpen()) {
- finishSketch();
- }
- paramTable.start();
- ribbon.setOn('manage.params', true);
- }
- return;
- }
- if (state.env === 'assembly' && assembly.command(id)) {
- return;
- }
- if (state.env === 'drawing' && drawing.command(id)) {
- return;
- }
- if (id === 'app.appearance') {
- if (!wasAppearance && state.env === 'part') {
- if (sketcher.isOpen()) {
- finishSketch();
- }
- appearanceTool.start();
- ribbon.setOn('app.appearance', true);
- }
- return;
- }
- if (id === 'app.material') {
- if (!wasMaterial && state.env === 'part') {
- if (sketcher.isOpen()) {
- finishSketch();
- }
- materialTool.start();
- ribbon.setOn('app.material', true);
- }
- return;
- }
- if (id === 'app.paint') {
- if (!wasPaint && state.env === 'part') {
- if (sketcher.isOpen()) {
- finishSketch();
- }
- if (paintTool.start()) {
- ribbon.setOn('app.paint', true);
- }
- }
- return;
- }
- if (id === 'sketch.start') {
- if (wasPicking === 'pick-sketch-plane' || state.mode === 'sketch') {
- return; // second click cancels the pick; already sketching does nothing
- }
- startPlanePick('pick-sketch-plane', 'sketch.start', 'to create sketch');
- } else if (id === 'nav.lookat') {
- if (wasPicking !== 'pick-lookat') {
- startPlanePick('pick-lookat', 'nav.lookat', 'to look at');
- }
- } else if (id === 'sketch.finish') {
- finishSketch();
- } else if (id === 'work.plane' || id === 'plane.offset') {
- // First the plane or face to offset from, then the panel
- if (wasPicking !== 'pick-workplane' && wasFeature !== 'plane') {
- if (sketcher.isOpen()) {
- finishSketch();
- }
- startPlanePick('pick-workplane', 'work.plane', 'to offset a work plane from');
- }
- } else if (id.indexOf('plane.') === 0) {
- // The other kinds of work plane pick their references in the panel
- featureTools.plane.prepareKind(id.slice(6));
- startFeature('plane', null);
- } else if (id === 'work.axis' || id === 'work.point') {
- if (wasFeature !== id.slice(5)) {
- startFeature(id.slice(5), null);
- }
- } else if (id.indexOf('pat.') === 0) {
- const kind = { rect: 'rectpattern', circ: 'circpattern', mirror: 'mirror' }[id.slice(4)];
- if (kind && wasFeature !== kind) {
- startFeature(kind, null);
- }
- } else if (id.indexOf('feat.') === 0 && featureTools[id.slice(5)]) {
- if (wasFeature !== id.slice(5)) {
- startFeature(id.slice(5), null); // a second click on the button only closed the panel
- }
- } else if (state.mode === 'sketch' && id === 'sk.construction') {
- sketcher.toggleConstruction();
- } else if (state.mode === 'sketch' && id.indexOf('con.') === 0) {
- // A second click on the active constraint tool puts it away
- if (activeTool === 'con:' + id.slice(4)) {
- sketcher.setTool('select');
- } else {
- sketcher.constrain(id.slice(4));
- }
- } else if (state.mode === 'sketch' && id.indexOf('sk.') === 0 && TOOL_BUTTONS[id.slice(3)]) {
- const tool = id.slice(3);
- sketcher.setTool(activeTool === tool ? 'select' : tool);
- } else if (id === 'nav.zoomall') {
- viewport.zoomAll();
- } else if (id === 'nav.home') {
- viewport.home();
- } else if (id === 'view.origin') {
- state.originVisible = !state.originVisible;
- ribbon.setOn('view.origin', state.originVisible);
- viewport.setOriginVisible(state.originVisible);
- } else if (id === 'section.end') {
- // "End Section View" puts the model back whole
- viewport.setSection('none');
- ribbon.setLabel('view.section', 'Section View');
- setStatus('Section view ended');
- } else if (id.indexOf('section.') === 0) {
- startInspect('section', id.slice(8));
- } else if (id === 'nav.pan' || id === 'nav.orbit') {
- // Clicking the active one gives the left button back to selecting
- const mode = id.slice(4);
- setLeftDrag(state.leftDrag === mode ? 'select' : mode);
- setStatus(state.leftDrag === 'select' ? 'Ready' : (mode === 'orbit' ? 'Orbit: drag inside the circle to turn, outside it to roll, on a tick to turn about one axis' : 'Pan: drag with the left button') +
- '. Esc, the button again or any tool gives it back to selecting.');
- } else if (id === 'ins.mass') {
- showMassProperties();
- } else if (id === 'ins.measure') {
- if (wasInspect !== 'measure') {
- startInspect('measure');
- }
- } else if (id === 'ins.check') {
- if (wasInspect !== 'check') {
- startInspect('check');
- }
- } else if (id.indexOf('style.') === 0) {
- viewport.setVisualStyle(id.slice(6));
- } else if (id.indexOf('proj.') === 0) {
- viewport.setProjection(id.slice(5));
- ribbon.setLabel('view.projection', id === 'proj.perspective' ? 'Perspective' : 'Orthographic');
- } else if (id === 'diag.selftest') {
- runSelfTest();
- } else if (id === 'file.new') {
- newDocument();
- } else if (id === 'file.open') {
- openDocument();
- } else if (id === 'file.save') {
- saveDocument(false);
- } else if (id === 'file.saveas') {
- saveDocument(true);
- } else if (id.indexOf('export.') === 0) {
- exportPart(id.slice(7));
- } else if (id === 'import.step') {
- importStep();
- } else if (id === 'import.stl' || id === 'import.obj') {
- importMesh(id.slice(7));
- } else if (id === 'file.sample') {
- loadDocument(sampleDocument(), sampleName('Sample Part'), '');
- } else if (id === 'file.sampledrw') {
- if (loadDocument(sampleDrawing(), sampleName('Sample Drawing'), '')) {
- setStatus('Sample Drawing: views of the sample part and assembly with dimensions. Double click anything to edit it; Annotate > Dimension adds more.');
- }
- } else if (id === 'file.sampleasm') {
- if (loadDocument(sampleAssembly(), sampleName('Sample Assembly'), '')) {
- setStatus('Sample Assembly: a plate, two inserted pins and a block mated and flush. Try Free Move on a pin, or Inspect > Degrees of Freedom.');
- }
- } else if (id === 'edit.undo' || id === 'edit.redo') {
- const label = id === 'edit.undo' ? activeDoc().undo() : activeDoc().redo();
- if (label) {
- setStatus((id === 'edit.undo' ? 'Undo: ' : 'Redo: ') + label);
- }
- } else {
- const command = ribbon.find(id);
- if (command && command.planned) {
- setStatus(command.label + ' is not built yet. Planned for ' + command.planned + ', see PROPOSAL.md.');
- } else {
- setStatus('This command is not built yet, see PROPOSAL.md.');
- }
- }
- }
- document.addEventListener('keydown', function (event) {
- const typing = event.target instanceof Element && event.target.closest('input, textarea');
- if (typing || document.querySelector('.veil')) {
- return; // typing in a field, or a dialog is open
- }
- if (appearanceTool.isOpen() && event.key === 'Escape') {
- appearanceTool.cancel();
- event.preventDefault();
- return;
- }
- if (paintTool.isOpen() && event.key === 'Escape') {
- paintTool.cancel();
- event.preventDefault();
- return;
- }
- if (offsetBox.isOpen() && event.key === 'Escape') {
- offsetBox.hide();
- event.preventDefault();
- return;
- }
- if (activeInspect && activeInspect.tool.handleKey(event)) {
- event.preventDefault();
- return;
- }
- if (state.env === 'assembly' && !(event.ctrlKey || event.metaKey) && assembly.handleKey(event)) {
- event.preventDefault();
- return;
- }
- if (state.env === 'drawing' && !(event.ctrlKey || event.metaKey) && drawing.handleKey(event)) {
- event.preventDefault();
- return;
- }
- if (state.mode === 'feature' && activeFeature && activeFeature.tool.handleKey(event)) {
- event.preventDefault();
- return;
- }
- // An open sketch gets the first go: typed sizes, Esc, Delete
- if (state.mode === 'sketch' && sketcher.handleKey(event)) {
- event.preventDefault();
- return;
- }
- const ctrl = event.ctrlKey || event.metaKey;
- const key = event.key.toLowerCase();
- let command = null;
- if (ctrl && key === 'z') {
- command = event.shiftKey ? 'edit.redo' : 'edit.undo';
- } else if (ctrl && key === 'y') {
- command = 'edit.redo';
- } else if (ctrl && key === 's') {
- command = event.shiftKey ? 'file.saveas' : 'file.save';
- } else if (ctrl && key === 'o') {
- command = 'file.open';
- } else if (key === 'home') {
- command = 'nav.home';
- }
- if (command) {
- event.preventDefault();
- onCommand(command);
- return;
- }
- if (key === 'f5' && !ctrl && state.env !== 'drawing') {
- // Previous View, as in desktop CAD (the browser's reload is Ctrl+F5 / Ctrl+R)
- event.preventDefault();
- const view = viewHistory.pop();
- if (view) {
- viewport.setViewState(view);
- setStatus('Previous view' + (viewHistory.length ? '' : ': this was the first one kept'));
- } else {
- setStatus('No previous view: the view has not changed yet');
- }
- return;
- }
- if (key === 'f6' && state.env !== 'drawing') {
- event.preventDefault();
- onCommand('nav.home'); // Home View
- return;
- }
- if (key === 'f4' && !event.repeat && state.leftDrag !== 'orbit') {
- // Held down, F4 turns the left button into orbit, as in desktop CAD
- event.preventDefault();
- heldOrbit = state.leftDrag;
- setLeftDrag('orbit');
- return;
- }
- if (key === 'escape' && state.leftDrag !== 'select') {
- setLeftDrag('select');
- setStatus('Ready');
- return;
- }
- if (key === 'escape') {
- closeMenu();
- if (picking()) {
- leaveMode();
- setStatus('Ready');
- } else if (state.mode === 'model') {
- viewport.clearSelection();
- }
- } else if (state.env === 'part' && state.mode === 'model' && browser.selected()) {
- if (key === 'delete') {
- deleteFeature(browser.selected());
- } else if (key === 'f2') {
- event.preventDefault();
- browser.startRename(browser.selected());
- }
- }
- });
- let heldOrbit = null; // what the left button did before F4 was pressed
- document.addEventListener('keyup', function (event) {
- if (event.key === 'F4' && heldOrbit !== null) {
- setLeftDrag(heldOrbit);
- heldOrbit = null;
- }
- });
- /* ================= engines ================= */
- const kernel = createKernel({
- onProgress: function (info) {
- if (info.step === 'download') {
- kernelTask.update({
- text: 'Downloading the modelling kernel: ' + megabytes(info.loaded, info.total),
- fraction: info.total > 0 ? info.loaded / info.total : null
- });
- } else if (info.step === 'compile') {
- kernelTask.update({ text: 'Preparing the modelling kernel', fraction: null });
- }
- },
- onReady: function (ms) {
- state.kernelReady = true;
- setEngine('status-kernel', 'ok', 'OpenCascade geometry kernel ready (started in ' + (ms / 1000).toFixed(1) + ' s)');
- kernelTask.done();
- },
- onFailed: function (error) {
- setEngine('status-kernel', 'bad', 'The geometry kernel failed to start: ' + error);
- endOpening();
- kernelTask.update({ title: 'The modelling kernel could not be loaded', text: error, error: true });
- setStatus('The modelling kernel could not be loaded: ' + error);
- }
- });
- function featureOptions(kind) {
- return {
- kind: kind,
- stage: $('stage'),
- viewport: viewport,
- kernel: kernel,
- doc: doc,
- onStatus: setStatus,
- // The plane reference of a picked plane or face (To, Linear holes)
- referenceOf: referenceOf,
- onClose: function () {
- featureClosed(kind);
- }
- };
- }
- const featureTools = {
- extrude: createExtrude(featureOptions('extrude')),
- revolve: createRevolve(featureOptions('revolve')),
- shell: createShell(featureOptions('shell')),
- rectpattern: createPattern(Object.assign(featureOptions('rectpattern'), { kind: 'rect' })),
- circpattern: createPattern(Object.assign(featureOptions('circpattern'), { kind: 'circ' })),
- mirror: createPattern(Object.assign(featureOptions('mirror'), { kind: 'mirror' })),
- fillet: createEdgeFeature(featureOptions('fillet')),
- chamfer: createEdgeFeature(featureOptions('chamfer')),
- hole: createHole(featureOptions('hole')),
- plane: createWorkFeature('plane', workOptions('plane')),
- axis: createWorkFeature('axis', workOptions('axis')),
- point: createWorkFeature('point', workOptions('point')),
- repair: createRepair(featureOptions('repair')),
- sweep: createSweep(featureOptions('sweep')),
- loft: createLoft(featureOptions('loft')),
- draft: createDraft(featureOptions('draft'))
- };
- // The work feature panels show what they set up as drafts, and take plane
- // picks as the references sketches use
- function workOptions(kind) {
- return Object.assign(featureOptions(kind), {
- referenceOf: referenceOf,
- onDraft: function (draft, editing) {
- const id = editing || null;
- draftPlane = draft && draft.frame ? { frame: draft.frame, id: id } : null;
- draftAxis = draft && draft.line ? { line: draft.line, id: id } : null;
- draftPoint = draft && draft.at ? { at: draft.at, id: id } : null;
- refreshWorkPlanes();
- }
- });
- }
- // The assembly environment (js/assembly/), and the Measure and Section
- // View panels both environments share
- const assembly = createAssembly({
- viewport: viewport,
- kernel: kernel,
- files: files,
- ribbon: ribbon,
- stage: $('stage'),
- canvas: $('viewport'),
- tree: $('asm-tree'),
- setStatus: setStatus,
- setPrompt: setPrompt,
- ask: ask,
- tell: tell,
- onChange: refreshChrome,
- // Open Part: the part's file in a tab of this window
- onProgress: documentProgress,
- openPath: function (path) {
- const reading = beginOpening(String(path).split('/').pop());
- files.readPath(path).then(function (file) {
- if (loadDocument(file.data, file.name, file.path, file.preview)) {
- setStatus('Opened ' + files.displayPath(path) + ' in a tab. Changes show in the assembly when its tab is shown again.');
- }
- }).catch(function (err) {
- endOpening(reading);
- fail('The part could not be opened', err);
- });
- }
- });
- const drawing = createDrawing({
- onProgress: documentProgress,
- viewport: viewport,
- kernel: kernel,
- files: files,
- ribbon: ribbon,
- stage: $('stage'),
- canvas: $('viewport'),
- sheetHost: $('sheet-stage'),
- tree: $('drw-tree'),
- setStatus: setStatus,
- setPrompt: setPrompt,
- ask: ask,
- tell: tell,
- openMenu: openMenu,
- onCommand: function (id) {
- onCommand(id);
- },
- onChange: refreshChrome,
- onShow3D: function (on) {
- showSheetChrome(!on);
- }
- });
- const measurePart = createMeasure({
- stage: $('stage'),
- viewport: viewport,
- onStatus: setStatus,
- measure: partDistance,
- onClose: function () {
- inspectClosed('measure');
- }
- });
- // Inspect > Check Geometry; its Repair... button opens the Repair feature
- const checkPanel = createCheckPanel({
- stage: $('stage'),
- viewport: viewport,
- kernel: kernel,
- onStatus: setStatus,
- onRepair: function () {
- startFeature('repair', null);
- },
- onClose: function () {
- inspectClosed('check');
- }
- });
- const measureAssembly = createMeasure({
- stage: $('stage'),
- viewport: viewport,
- onStatus: setStatus,
- components: true,
- measure: function (a, b) {
- return assembly.measure(a, b);
- },
- name: function (item) {
- return assembly.nameOf(item);
- },
- onClose: function () {
- inspectClosed('measure');
- }
- });
- const appearanceTool = createAppearancePanel({
- stage: $('stage'),
- viewport: viewport,
- doc: doc,
- onStatus: setStatus,
- onClose: function () {
- ribbon.setOn('app.appearance', false);
- },
- // A picture for the Image finish, made smaller and kept in the part
- pickImage: function () {
- return files.openOther(IMAGE_EXTENSIONS, true).then(function (file) {
- return file ? toTextureImage(file.bytes, file.name) : null;
- });
- }
- });
- // Projected sketch geometry follows its model edges (PROPOSAL.md 14.5 C):
- // the rebuild reports projected curves whose edges moved; they are moved
- // in the sketch, the sketch is solved again (headless) so what is tied to
- // them follows, and the part rebuilds. Not an undo step of its own. A
- // sketch that cannot be solved that way keeps its geometry (said once).
- let followPasses = 0;
- const followSaid = new Set();
- function followModel(projections) {
- const ids = Object.keys(projections || {}).filter(function (id) {
- return doc.feature(id) && !(sketcher.isOpen() && sketcher.featureId() === id) &&
- !followSaid.has(id + JSON.stringify(projections[id]));
- });
- if (!ids.length) {
- followPasses = 0;
- return;
- }
- if (++followPasses > 4) {
- followPasses = 0;
- setStatus('Projected sketch geometry could not settle on the model; open the sketch to check it');
- return;
- }
- if (!headlessSolver) {
- headlessSolver = solver.createSolver();
- }
- headlessSolver.then(function (s) {
- const said = [];
- doc.amend(function (d) {
- ids.forEach(function (id) {
- const sketch = d.features.find(function (f) {
- return f.id === id;
- });
- if (!sketch) {
- return;
- }
- const before = JSON.stringify(sketch.geometry);
- const out = applyFollow(sketch, projections[id]);
- if (out.lost.length) {
- followSaid.add(id + JSON.stringify(projections[id]));
- said.push(sketch.name + ': ' + (out.lost.length === 1 ? 'a projected edge is' : out.lost.length + ' projected edges are') +
- ' no longer in the model and stay' + (out.lost.length === 1 ? 's' : '') + ' where ' + (out.lost.length === 1 ? 'it was' : 'they were'));
- }
- if (out.moved && !s.solve(sketch).ok) {
- // The constraints cannot be met with the edges where they
- // are now: keep the sketch as it was
- sketch.geometry = JSON.parse(before);
- followSaid.add(id + JSON.stringify(projections[id]));
- said.push(sketch.name + ' cannot follow the model: its constraints cannot be met with the edges where they are now. Open it to fix them');
- }
- });
- });
- if (said.length) {
- setStatus(said[0]);
- }
- }).catch(function (err) {
- setStatus('Projected sketch geometry could not follow the model: ' + err.message);
- });
- }
- // Manage > Parameters. OK works every kept formula out again and solves
- // the sketches whose dimensions changed (the sketch solver, headless), as
- // one undo step; a sketch that cannot meet its new sizes keeps its old ones
- let headlessSolver = null;
- const paramTable = createParameterTable({
- stage: $('stage'),
- doc: doc,
- onStatus: setStatus,
- onClose: function () {
- ribbon.setOn('manage.params', false);
- },
- onApply: function (list) {
- if (!headlessSolver) {
- headlessSolver = solver.createSolver();
- }
- headlessSolver.then(function (s) {
- const problems = [];
- doc.change('Parameters', function (d) {
- if (list.length) {
- d.parameters = list;
- } else {
- delete d.parameters;
- }
- const before = {};
- d.features.forEach(function (f) {
- if (f.type === 'sketch') {
- before[f.id] = (f.constraints || []).map(function (c) {
- return c.value;
- });
- }
- });
- const out = applyParameters(d);
- problems.push.apply(problems, out.problems);
- out.sketches.forEach(function (id) {
- const sketch = d.features.find(function (f) {
- return f.id === id;
- });
- // Only the dimensions whose value changed move anything
- const changed = (sketch.constraints || []).filter(function (c, i) {
- return c.value !== before[id][i];
- }).map(function (c) {
- return c.id;
- });
- const solved = s.solveChange(sketch, changed);
- if (!solved.ok) {
- (sketch.constraints || []).forEach(function (c, i) {
- c.value = before[id][i];
- });
- problems.push(sketch.name + ' cannot meet its dimensions with these values: it keeps its old sizes');
- }
- });
- });
- setStatus(problems.length ? problems[0] + (problems.length > 1 ? ' (and ' + (problems.length - 1) + ' more)' : '')
- : 'Parameters applied' + (list.length ? ': ' + list.length + (list.length === 1 ? ' parameter' : ' parameters') : ''));
- }).catch(function (err) {
- fail('The parameters could not be applied', err);
- });
- }
- });
- const materialTool = createMaterialPanel({
- stage: $('stage'),
- doc: doc,
- onStatus: setStatus,
- onClose: function () {
- ribbon.setOn('app.material', false);
- }
- });
- const paintTool = createPaintPanel({
- stage: $('stage'),
- viewport: viewport,
- doc: doc,
- onStatus: setStatus,
- onClose: function () {
- ribbon.setOn('app.paint', false);
- }
- });
- /* ================= the scene (Appearance tab) ================= */
- // How this viewer likes to see models; kept in this browser, not in parts
- const SCENE_KEY = '3dmodeler.scene';
- let sceneOpts = normalizeScene(null);
- try {
- sceneOpts = normalizeScene(JSON.parse(window.localStorage.getItem(SCENE_KEY) || 'null'));
- } catch (e) {
- // No storage (private window, blocked site data): the defaults
- }
- function applyScene(save) {
- viewport.setScene(sceneOpts);
- ribbon.setOn('scene.reflections', sceneOpts.reflections);
- ribbon.setOn('scene.shadows', sceneOpts.shadows);
- ribbon.setOn('scene.ground', sceneOpts.ground);
- ribbon.setOn('scene.textures', sceneOpts.textures);
- if (save) {
- try {
- window.localStorage.setItem(SCENE_KEY, JSON.stringify(sceneOpts));
- } catch (e) {
- // Not kept: it still applies until the window closes
- }
- }
- }
- const SCENE_FLAGS = {
- 'scene.reflections': ['reflections', 'Reflections'],
- 'scene.shadows': ['shadows', 'Ground shadow'],
- 'scene.ground': ['ground', 'Ground plane'],
- 'scene.textures': ['textures', 'Textures']
- };
- function sceneCommand(id) {
- const flag = SCENE_FLAGS[id];
- if (flag) {
- sceneOpts[flag[0]] = !sceneOpts[flag[0]];
- applyScene(true);
- setStatus(flag[1] + (sceneOpts[flag[0]] ? ' on' : ' off'));
- return true;
- }
- if (id.indexOf('light.') === 0) {
- sceneOpts.lighting = lightingById(id.slice(6)).id;
- applyScene(true);
- setStatus('Lighting: ' + lightingById(sceneOpts.lighting).label);
- return true;
- }
- return false;
- }
- applyScene(false);
- const sectionPanel = createSectionPanel({
- stage: $('stage'),
- viewport: viewport,
- onStatus: setStatus,
- onClose: function () {
- inspectClosed('section');
- }
- });
- solver.selfTest().then(function (result) {
- if (result.ok) {
- setEngine('status-solver', 'ok', 'planegcs sketch solver ready (test sketch solved in ' + result.ms.toFixed(1) + ' ms)');
- } else {
- setEngine('status-solver', 'bad', 'The sketch solver returned a wrong answer on its test sketch');
- }
- }).catch(function (err) {
- setEngine('status-solver', 'bad', 'The sketch solver failed to start: ' + (err && err.message ? err.message : err));
- });
- /* ================= start ================= */
- // The first tab: an empty part, until a file is opened into its place
- const firstTab = { id: 't' + (++tabSeq), kind: 'part', snap: null, view: null };
- tabs.push(firstTab);
- activeTab = firstTab;
- kernel.call('useRebuilder', { key: 'part:' + firstTab.id }).catch(function () {
- // The kernel failed to start; the status bar says so
- });
- initTheme();
- browser.render();
- refreshSketches();
- refreshWorkPlanes();
- ribbon.setMode('part');
- refreshChrome();
- ribbon.showTab('model');
- // Unsaved work of a window that crashed, was reloaded or was closed
- setTimeout(offerAutosaves, 600);
- // A file handed over from outside the window: the File Manager's "Open
- // with 3D Modeler", or in the Mac app Finder, the Dock and Open Recent
- function openHandedOver(path) {
- if (/\.(step|stp)$/i.test(path)) {
- // A STEP file opened with 3D Modeler starts a new part with it imported
- return files.readText(path).then(function (file) {
- loadDocument(null, file.name.replace(/\.[^.]+$/, ''), '');
- return addImport(file);
- }).catch(function (err) {
- fail('The file could not be imported', err);
- });
- }
- // A part, an assembly or a drawing: loadDocument goes by the file's format
- const reading = beginOpening(String(path).split('/').pop());
- return files.readPath(path).then(function (file) {
- if (loadDocument(file.data, file.name, file.path, file.preview)) {
- setStatus('Opened ' + files.displayPath(file.path));
- }
- }).catch(function (err) {
- endOpening(reading);
- fail('The file could not be opened', err);
- });
- }
- const launch = files.launchPath();
- if (launch) {
- openHandedOver(launch);
- }
- /* ================= the Mac app (io/native.js) ================= */
- // The menu bar items the page carries out. Undo and Redo in a text field
- // being typed in act on the typing, as the keys do.
- const MENU_COMMANDS = /^(file\.(new|open|save|saveas)|import\.step|export\.(step|stl|obj|3mf|brep)|dexport\.(pdf|dxf|svg|png)|nav\.(home|zoomall))$/;
- function nativeMenu(command) {
- const el = document.activeElement;
- const typing = el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);
- if ((command === 'edit.undo' || command === 'edit.redo') && typing) {
- document.execCommand(command === 'edit.undo' ? 'undo' : 'redo');
- return;
- }
- if (document.querySelector('.veil')) {
- return; // a question is open: it is answered first, as with the keys
- }
- if (command === 'tab.close') {
- if (activeTab) {
- closeTab(activeTab);
- }
- } else if (command === 'edit.undo' || command === 'edit.redo' || MENU_COMMANDS.test(command)) {
- onCommand(command);
- }
- }
- // Files waiting in the shell, one tab each, in the order they came
- function takeHandedOver() {
- native.takeOpened().then(function (list) {
- return list.reduce(function (chain, file) {
- return chain.then(function () {
- return openHandedOver(file.path);
- });
- }, Promise.resolve());
- }).catch(function (err) {
- fail('The file could not be opened', err);
- });
- }
- if (native.available()) {
- native.handle({
- // The close button or Quit: true closes now; otherwise the page asks
- // and tells the shell what the person chose
- requestClose: function () {
- if (!tabs.some(tabDirty)) {
- closingOnPurpose();
- return true;
- }
- confirmCloseAll().then(function (ok) {
- if (ok) {
- closingOnPurpose();
- return native.closeWindow();
- }
- return native.closeCancelled();
- }).catch(function () {
- native.closeCancelled();
- });
- return false;
- },
- menu: nativeMenu,
- opened: takeHandedOver
- });
- takeHandedOver();
- }
|