Compare commits

...

34 Commits

Author SHA1 Message Date
3e0c44e689 add segment proof of concept 2024-02-28 20:20:00 +11:00
8666989c85 add issue template (#1547)
* add issue template

* change report a bug link

* add issue form and delete issue template, update link
2024-02-27 14:10:50 -08:00
bdf49c2084 short term cam fix (#1543)
* short term cam fix

* fix

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* trigger ci

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-28 06:26:53 +11:00
a06b9d560a improve export test logs (#1536) 2024-02-27 15:19:14 +11:00
b81ff66f2b Sketch on face of face (#1524)
* add test

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* add negative extrude

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix sketch on face of face

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* generate stdlib

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-02-26 14:54:42 -08:00
c0e6947170 update cli to reestablish export test (#1523)
* update cli to reestablish export test

* update cli v

* tweak
2024-02-27 09:41:09 +11:00
65ebde0b34 Disable actions when stream disconnected (#1483)
* pull out network indicator logic

* rename callbacks

* re-execute on reconnection

* make sure tool bar is disabled on start up

* clean up

* node safety

* disable toolbar buttons properly

* grey scale action icon icons dodgy

* test tweaks

* Revert "grey scale action icon icons dodgy"

This reverts commit c3d12a0f05.

* Disable modeling commands when network is bad (#1486)

* Disable modeling commands when network is bad

* disabel on execute too

* fmt

---------

Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>

* disable playwright snapshots temporarily

* disable export test instead

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

---------

Co-authored-by: Frank Noirot <frank@zoo.dev>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-26 21:02:33 +11:00
0d6618b60a solve a couple of scene scale bugs (#1496)
* solve a couple of scene scale bugs

* Some cam fixes (#1520)

* rotate and zoom basics working

* intergrate mouse guards, and add pan

* implement orthographic camera again

* implement switch to perspective camera again

* migrate dollyzoom

* make pan robust for differnt FOV and orthographic cam

* tween to quaternion and default plane selection working with quirks

* fix pan

It the up and right was derived from the camera's up, which is a static [0,0,1] not the camera's current cameras real up, which aligns itself as best to [0,0,1] but is not that especially when looking straight up or down, and the pan felt very awkward in these vertical look sintuations

* fix raycastRing to use new camera

* fix tween to quaternion for camera lock situations

And get all playwright tests passing

* fix up CamToggle, even thought this component is not setup properly to use react properties from our scene class

* add animation to cameras back in

* first big clean up of sceneInfra

* move more cam stuff out of sceneInfra

* clean up mouse guard logic

* clean up camera change callbacks

* fix some sitations where animation to xy doesn't work great

* needs to take the target into consideration

* last bits of clean up

* more clean up

* make vitest happ

* fix up remaining interaction guards

* make scrolling less sensative for trackpads

* remove debug cube

* fix snapshot tests
2024-02-26 19:53:44 +11:00
f0c44d11b3 Revert "tauri-driver latest"
This reverts commit 44e71cd4bc.
2024-02-25 20:35:11 -05:00
44e71cd4bc tauri-driver latest 2024-02-25 20:33:14 -05:00
a9f716dad8 fixing discord automation to ignore nightly runs (#1516)
adding release if statement
2024-02-24 01:44:25 -07:00
a2455832e7 Honor mod+z and mod+shift+z even with editor not in focus (#1513)
Resolves #1504 and was way easier than I thought when I tried it a while back!
2024-02-23 17:37:05 -05:00
8f5034f997 Remove Sentry from production (#1515) 2024-02-23 22:07:33 +00:00
af1c2c7ae1 Update KNOWN-ISSUES.md 2024-02-23 13:19:03 -08:00
ff38ae091e Replace number command bar arg input type with kcl expression input (#1474)
* Rename useCalc

* Move CommandBar so it has access to settings and kcl

* Create codemirror variable mention extension

* Make project path a dep of TextEditor useMemo

* Add incomplete KCL input for CommandBar
to replace current number arg type

* Add previous variables autocompletion to kcl input

* Fix missed typos from merge

* Working AST mods, not working variable additions

* Add ability to create a new variable

* Add icon and tooltip to command arg tag if a variable is added

* Polish variable naming logic, preserve when going back

* Allow stepping back from KCL input

* Don't prevent keydown of enter, it's used by autocomplete

* Round the variable value in cmd bar header

* Add Playwright test

* Formatting, polish TS types

* More type wrangling

* Needed to fmt after above type wrangling

* Update snapshot tests to account for new variable name autogeneration

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* Merge branch 'main' into cmd-bar-make-variable

* Update all test instances of var name with number index after merge with main

* Partial revert of "Polish variable naming logic, preserve when going back"

This reverts commit dddcb13c36.

* Revert "Update all test instances of var name with number index after merge with main"

This reverts commit 8c4b63b523.

* Revert "Update snapshot tests to account for new variable name autogeneration"

This reverts commit 11bfce3832.

* Retry a refactoring of findUniqueName

* minor feedback from @jgomez720
- better highlighting of kcl input
- consistent hotkeys
- disallow invalid var names

* Polish stepping back state logic

* Fix tests now that keyboard shortcut changed

* Remove unused imports

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* Fix tests

* Trigger CI

* Update src/components/ProjectSidebarMenu.test.tsx

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* re-trigger CI

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
Co-authored-by: Kurt Hutten <k.hutten@protonmail.ch>
2024-02-23 11:24:22 -05:00
1dd7c95b8c Sketch on arc error (#1495)
* add error for sketch on arc

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fixes

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* generate std lib

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-02-22 19:07:17 -08:00
20042ec87c Release derive-docs 0.1.7 (#1491)
Release derive-docs 0.1.7
2024-02-22 21:24:02 +00:00
fccf3508a7 Trim space off the return type before continuing (#1487)
* Trim space off the return type before continuing

My nightly compiler has a space at the end that the stable compiler
doesn't. This will trim space, if it exists, before removing the generic
bracket, which will work for both stable and current nightly, future
stable.

In the future this may be worth doing a trim on "> " but I don't reckon
today is that day.

Signed-off-by: Paul R. Tagliamonte <paul@kittycad.io>
2024-02-22 15:59:51 -05:00
8dab5527b8 bump ahash to fix the nightly builds (#1488)
Specifically, i'm hitting https://github.com/tkaitchuck/aHash/issues/200
ahash FTBFS because of https://github.com/rust-lang/rust/pull/117372
which is fixed in 0.8.7.

This rolls us forward which should fix future builds.
2024-02-22 15:30:03 -05:00
f72eb0e8a7 Cube example didn't actually work (#1478)
* Cube example didn't actually work

* Bump h2 in fuzz tests
2024-02-22 12:03:05 -06:00
40479d177f Bump ip from 1.1.8 to 1.1.9 (#1471)
Bumps [ip](https://github.com/indutny/node-ip) from 1.1.8 to 1.1.9.
- [Commits](https://github.com/indutny/node-ip/compare/v1.1.8...v1.1.9)

---
updated-dependencies:
- dependency-name: ip
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Pierre Jacquier <pierrejacquier39@gmail.com>
2024-02-22 04:59:03 -05:00
b88359dee2 Move discord automation into ci.yml (#1479)
* updating ci.yml with discord release automation

* removed line
2024-02-21 17:35:35 -07:00
f4c0347104 Cut release v0.15.2 (#1467)
Co-authored-by: Kurt Hutten <k.hutten@protonmail.ch>
2024-02-22 08:36:38 +11:00
ad36b5f5fa add make release bash script (#1475)
* add make release bash script

* read me details

* uncomment git uncommited changes

* typo

* tweaks

* use package.json as source of truth, not git tags
2024-02-22 07:01:45 +11:00
b798cf19d3 Bump kcl-lib (#1477)
* bump version

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* bump version

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* Revert "bump version"

This reverts commit 44e0b6ac6e.

* bump version

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-02-21 11:05:10 -08:00
7cfa897561 add modulo and power operators (#1341)
* add modulo and power operators

* format

* point to main instead of serena branch

* reset cargo lock

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

---------

Co-authored-by: gserena <serena@zoo.dev>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-21 11:11:57 -05:00
0d8804005a improve vitest hang (#1470)
* improve vitest hang

* fmt

* make types happy

* fix types

* fix
2024-02-21 13:23:50 +11:00
cbd26d29fa updates for units (#1458)
* updates for units

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* scene units

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* start passing in units to tests

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* units tests

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* add more images

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* hacky code for now

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* get settings context outside of react

* fmt

* pull through settings

* fix

* fmt

* move camera with units (#1461)

* temp patch tsc

* update kittycad.rs

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* trait

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix compile

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* update screenshots

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* execute on settings change

* Update src/clientSideScene/sceneInfra.ts

* try zoom

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* more shit image

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* new screenshots

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* udpates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* tests

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* update cam

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* new

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates for units

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fixles

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* ;scale

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fixes

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fmt

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* tweak playwright draft segments test

* another test tweak

* last test tweak

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* update default plane snapshot scale

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

* number tweaks for playwright flow checks

* up[date

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
Co-authored-by: Kurt Hutten Irev-Dev <k.hutten@protonmail.ch>
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-20 17:55:06 -08:00
e501a542ac Add arc icon, replace settings icon (#1469)
* Add icons for arc and settings

* Update arc icon in toolbar

* Use settings icon instead of gear for settings

* A snapshot a day keeps the bugs away! 📷🐛 (OS: ubuntu)

---------

Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2024-02-20 18:34:03 +00:00
7cb4f4d101 deselect line bug (#1457) 2024-02-20 11:04:42 +11:00
1162f5f4c4 Bump kcl-lib (#1455)
* update version

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* update version

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* fix

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-02-19 14:23:16 -08:00
3975e6d8f5 auto complete test more robust (#1456) 2024-02-20 09:22:33 +11:00
d68d7a7e00 Cut release v0.15.1 (#1452)
cut release v0.15.1
2024-02-20 08:10:26 +11:00
b135b97de6 Code mirror plugin lsp interface (#1444)
* better named dirs

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* move some stuff around

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* more logging

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* less logging

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* add fs in

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* file reader

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* workspace

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* start of workspace folders

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* start of workspace folders

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* cleanup workspace folders

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* cleanup logs

Signed-off-by: Jess Frazelle <github@jessfraz.com>

* updates

Signed-off-by: Jess Frazelle <github@jessfraz.com>

---------

Signed-off-by: Jess Frazelle <github@jessfraz.com>
2024-02-19 12:33:16 -08:00
186 changed files with 10850 additions and 3126 deletions

View File

@ -3,4 +3,4 @@ VITE_KC_API_BASE_URL=https://api.zoo.dev
VITE_KC_SITE_BASE_URL=https://zoo.dev
VITE_KC_SKIP_AUTH=false
VITE_KC_CONNECTION_TIMEOUT_MS=15000
VITE_KC_SENTRY_DSN=https://a814f2f66734989a90367f48feee28ca@o1042111.ingest.sentry.io/4505789425844224
VITE_KC_SENTRY_DSN=

85
.github/ISSUE_TEMPLATE/bug_report.yml vendored Normal file
View File

@ -0,0 +1,85 @@
name: Bug Report
description: File a bug report for the Zoo Modeling App
title: "[BUG]: "
labels: ["bug"]
assignees: []
body:
- type: markdown
attributes:
value: "Thank you for taking the time to report a bug. Please provide as much information as possible to help us resolve it."
- type: textarea
id: describe-bug
attributes:
label: Describe the bug
description: A clear and concise description of what the bug is.
placeholder: "Explain the bug..."
validations:
required: true
- type: textarea
id: reproduce-bug
attributes:
label: Steps to Reproduce
description: Steps to reproduce the behavior.
placeholder: |
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
validations:
required: true
- type: textarea
id: expected-behavior
attributes:
label: Expected Behavior
description: Description of what you expected to happen.
placeholder: "I expected that..."
validations:
required: true
- type: textarea
id: screenshots
attributes:
label: Screenshots and Recordings
description: If applicable, add screenshots to help explain your problem. Maximum upload size is 10MB.
placeholder: "You can attach images or video recordings here."
validations:
required: false
- type: input
id: desktop-os
attributes:
label: Desktop OS
description: "Your operating system"
placeholder: "example: Windows 10, MacOS Big Sur"
validations:
required: true
- type: input
id: browser
attributes:
label: Browser
description: "If you are using the web version, please specify the browser you are using."
placeholder: "example: Chrome, Safari"
validations:
required: false
- type: input
id: version
attributes:
label: Version
description: "The version of the Zoo Modeling App you're using."
placeholder: "example: v0.15.0. You can find this in the settings."
validations:
required: true
- type: textarea
id: additional-context
attributes:
label: Additional Context
description: Add any other context about the problem here.
placeholder: "Anything else you want to add..."
validations:
required: false

View File

@ -1,29 +0,0 @@
name: Announce Release
on:
release:
types: [published]
jobs:
announce_release:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Announce Release
env:
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
RELEASE_VERSION: ${{ github.event.release.tag_name }}
RELEASE_BODY: ${{ github.event.release.body}}
run: python public/announce_release.py

View File

@ -86,8 +86,6 @@ jobs:
- run: yarn test:nowatch
- run: yarn test:cov
prepare-json-files:
runs-on: ubuntu-latest # seperate job on Ubuntu for easy string manipulations (compared to Windows)
@ -372,3 +370,28 @@ jobs:
uses: softprops/action-gh-release@v1
with:
files: 'artifact/*/Zoo*'
announce_release:
needs: [publish-apps-release]
runs-on: ubuntu-latest
if: github.event_name == 'release'
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.x'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install requests
- name: Announce Release
env:
DISCORD_WEBHOOK_URL: ${{ secrets.DISCORD_WEBHOOK_URL }}
RELEASE_VERSION: ${{ github.event.release.tag_name }}
RELEASE_BODY: ${{ github.event.release.body}}
run: python public/announce_release.py

View File

@ -14,7 +14,7 @@ jobs:
with:
node-version-file: '.nvmrc'
cache: 'yarn'
- uses: KittyCAD/action-install-cli@v0.2.16
- uses: KittyCAD/action-install-cli@v0.2.21
- name: Install dependencies
run: yarn
- name: Install Playwright Browsers

View File

@ -136,6 +136,11 @@ Before you submit a contribution PR to this repo, please ensure that:
VERSION=x.y.z yarn run bump-jsons
```
Alternatively you can try the experimental `make-release.sh` bash script that will create the branch with the updated json files for you.
run `./make-release.sh` for a patch update
run `./make-release.sh "minor"` for minor
run `./make-release.sh "major"` for major
The PR may serve as a place to discuss the human-readable changelog and extra QA. A quick way of getting PR's merged since the last bump is to [use this PR filter](https://github.com/KittyCAD/modeling-app/pulls?q=is%3Apr+sort%3Aupdated-desc+is%3Amerged+), open up the browser console and past in the following
```typescript

View File

@ -6,11 +6,13 @@ once fixed in engine will just start working here with no language changes.
- **Sketch on Face**: If your sketch is outside the edges of the face (on which you
are sketching) you will get multiple models returned instead of one single
model for that sketch and its underlying 3D object.
If you see a red line around your model, it means this is happening.
- **Patterns**: If you try and pass a pattern to `hole` currently only the first
item in the pattern is being subtracted. This is an engine bug that is being
worked on.
- **Import**: Right now you can import a file, even if that file has brep data
you cannot edit it. You also cannot move or transform the imported objects at
all. In the future, after v1, the engine will account for this.
you cannot edit it, after v1, the engine will account for this. You also cannot
currently move or transform the imported objects at all, once we have assemblies
this will work.

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 193 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 259 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 220 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 80 KiB

After

Width:  |  Height:  |  Size: 193 KiB

View File

@ -19,59 +19,59 @@ DATA;
);
#4 = CARTESIAN_POINT('NONE', (0, 0, -0));
#5 = VERTEX_POINT('NONE', #4);
#6 = CARTESIAN_POINT('NONE', (0, -0.0254, -0));
#6 = CARTESIAN_POINT('NONE', (0, -0.64516, -0));
#7 = VERTEX_POINT('NONE', #6);
#8 = CARTESIAN_POINT('NONE', (0, -0.0254, 0.1016));
#8 = CARTESIAN_POINT('NONE', (0, -0.64516, 2.58064));
#9 = VERTEX_POINT('NONE', #8);
#10 = CARTESIAN_POINT('NONE', (0, 0, 0.1016));
#10 = CARTESIAN_POINT('NONE', (0, 0, 2.58064));
#11 = VERTEX_POINT('NONE', #10);
#12 = CARTESIAN_POINT('NONE', (0.07861346939195568, -0.0254, -0));
#12 = CARTESIAN_POINT('NONE', (1.996782122555674, -0.64516, -0));
#13 = VERTEX_POINT('NONE', #12);
#14 = CARTESIAN_POINT('NONE', (0.07861346939195568, -0.0254, 0.1016));
#14 = CARTESIAN_POINT('NONE', (1.996782122555674, -0.64516, 2.58064));
#15 = VERTEX_POINT('NONE', #14);
#16 = CARTESIAN_POINT('NONE', (0.1511633881344551, -0.07619999999999998, -0));
#16 = CARTESIAN_POINT('NONE', (3.839550058615159, -1.9354799999999992, -0));
#17 = VERTEX_POINT('NONE', #16);
#18 = CARTESIAN_POINT('NONE', (0.1511633881344551, -0.07619999999999998, 0.1016));
#18 = CARTESIAN_POINT('NONE', (3.839550058615159, -1.9354799999999992, 2.58064));
#19 = VERTEX_POINT('NONE', #18);
#20 = CARTESIAN_POINT('NONE', (0.2413, -0.0762, -0));
#20 = CARTESIAN_POINT('NONE', (6.12902, -1.93548, -0));
#21 = VERTEX_POINT('NONE', #20);
#22 = CARTESIAN_POINT('NONE', (0.2413, -0.0762, 0.1016));
#22 = CARTESIAN_POINT('NONE', (6.12902, -1.93548, 2.58064));
#23 = VERTEX_POINT('NONE', #22);
#24 = CARTESIAN_POINT('NONE', (0.2413, -0.0635, -0));
#24 = CARTESIAN_POINT('NONE', (6.12902, -1.6129, -0));
#25 = VERTEX_POINT('NONE', #24);
#26 = CARTESIAN_POINT('NONE', (0.2413, -0.0635, 0.1016));
#26 = CARTESIAN_POINT('NONE', (6.12902, -1.6129, 2.58064));
#27 = VERTEX_POINT('NONE', #26);
#28 = CARTESIAN_POINT('NONE', (0.1551676827532182, -0.0635, -0));
#28 = CARTESIAN_POINT('NONE', (3.9412591419317424, -1.6129, -0));
#29 = VERTEX_POINT('NONE', #28);
#30 = CARTESIAN_POINT('NONE', (0.1551676827532182, -0.0635, 0.1016));
#30 = CARTESIAN_POINT('NONE', (3.9412591419317424, -1.6129, 2.58064));
#31 = VERTEX_POINT('NONE', #30);
#32 = CARTESIAN_POINT('NONE', (0.06448028432509392, 0, -0));
#32 = CARTESIAN_POINT('NONE', (1.6377992218573856, 0, -0));
#33 = VERTEX_POINT('NONE', #32);
#34 = CARTESIAN_POINT('NONE', (0.06448028432509392, 0, 0.1016));
#34 = CARTESIAN_POINT('NONE', (1.6377992218573856, 0, 2.58064));
#35 = VERTEX_POINT('NONE', #34);
#36 = CARTESIAN_POINT('NONE', (0.14618599799650817, 0.03810000000000001, -0));
#36 = CARTESIAN_POINT('NONE', (3.7131243491113075, 0.9677400000000002, -0));
#37 = VERTEX_POINT('NONE', #36);
#38 = CARTESIAN_POINT('NONE', (0.14618599799650817, 0.03810000000000001, 0.1016));
#38 = CARTESIAN_POINT('NONE', (3.7131243491113075, 0.9677400000000002, 2.58064));
#39 = VERTEX_POINT('NONE', #38);
#40 = CARTESIAN_POINT('NONE', (0.2413, 0.0381, -0));
#40 = CARTESIAN_POINT('NONE', (6.12902, 0.9677399999999998, -0));
#41 = VERTEX_POINT('NONE', #40);
#42 = CARTESIAN_POINT('NONE', (0.2413, 0.0381, 0.1016));
#42 = CARTESIAN_POINT('NONE', (6.12902, 0.9677399999999998, 2.58064));
#43 = VERTEX_POINT('NONE', #42);
#44 = CARTESIAN_POINT('NONE', (0.2413, 0.0508, -0));
#44 = CARTESIAN_POINT('NONE', (6.12902, 1.29032, -0));
#45 = VERTEX_POINT('NONE', #44);
#46 = CARTESIAN_POINT('NONE', (0.2413, 0.0508, 0.1016));
#46 = CARTESIAN_POINT('NONE', (6.12902, 1.29032, 2.58064));
#47 = VERTEX_POINT('NONE', #46);
#48 = CARTESIAN_POINT('NONE', (0.14337047578094278, 0.0508, -0));
#48 = CARTESIAN_POINT('NONE', (3.6416100848359463, 1.29032, -0));
#49 = VERTEX_POINT('NONE', #48);
#50 = CARTESIAN_POINT('NONE', (0.14337047578094278, 0.0508, 0.1016));
#50 = CARTESIAN_POINT('NONE', (3.6416100848359463, 1.29032, 2.58064));
#51 = VERTEX_POINT('NONE', #50);
#52 = CARTESIAN_POINT('NONE', (0.08889999999999999, 0.0254, -0));
#52 = CARTESIAN_POINT('NONE', (2.2580599999999995, 0.64516, -0));
#53 = VERTEX_POINT('NONE', #52);
#54 = CARTESIAN_POINT('NONE', (0.08889999999999999, 0.0254, 0.1016));
#54 = CARTESIAN_POINT('NONE', (2.2580599999999995, 0.64516, 2.58064));
#55 = VERTEX_POINT('NONE', #54);
#56 = CARTESIAN_POINT('NONE', (0, 0.0254, -0));
#56 = CARTESIAN_POINT('NONE', (0, 0.64516, -0));
#57 = VERTEX_POINT('NONE', #56);
#58 = CARTESIAN_POINT('NONE', (0, 0.0254, 0.1016));
#58 = CARTESIAN_POINT('NONE', (0, 0.64516, 2.58064));
#59 = VERTEX_POINT('NONE', #58);
#60 = DIRECTION('NONE', (0, -1, 0));
#61 = VECTOR('NONE', #60, 1);
@ -79,11 +79,11 @@ DATA;
#63 = LINE('NONE', #62, #61);
#64 = DIRECTION('NONE', (0, 0, 1));
#65 = VECTOR('NONE', #64, 1);
#66 = CARTESIAN_POINT('NONE', (0, -0.0254, -0));
#66 = CARTESIAN_POINT('NONE', (0, -0.64516, -0));
#67 = LINE('NONE', #66, #65);
#68 = DIRECTION('NONE', (0, -1, 0));
#69 = VECTOR('NONE', #68, 1);
#70 = CARTESIAN_POINT('NONE', (0, 0, 0.1016));
#70 = CARTESIAN_POINT('NONE', (0, 0, 2.58064));
#71 = LINE('NONE', #70, #69);
#72 = DIRECTION('NONE', (0, 0, 1));
#73 = VECTOR('NONE', #72, 1);
@ -91,155 +91,155 @@ DATA;
#75 = LINE('NONE', #74, #73);
#76 = DIRECTION('NONE', (1, 0, 0));
#77 = VECTOR('NONE', #76, 1);
#78 = CARTESIAN_POINT('NONE', (0, -0.0254, -0));
#78 = CARTESIAN_POINT('NONE', (0, -0.64516, -0));
#79 = LINE('NONE', #78, #77);
#80 = DIRECTION('NONE', (0, 0, 1));
#81 = VECTOR('NONE', #80, 1);
#82 = CARTESIAN_POINT('NONE', (0.07861346939195568, -0.0254, -0));
#82 = CARTESIAN_POINT('NONE', (1.996782122555674, -0.64516, -0));
#83 = LINE('NONE', #82, #81);
#84 = DIRECTION('NONE', (1, 0, 0));
#85 = VECTOR('NONE', #84, 1);
#86 = CARTESIAN_POINT('NONE', (0, -0.0254, 0.1016));
#86 = CARTESIAN_POINT('NONE', (0, -0.64516, 2.58064));
#87 = LINE('NONE', #86, #85);
#88 = DIRECTION('NONE', (0.8191520442889919, -0.5735764363510459, 0));
#88 = DIRECTION('NONE', (0.819152044288992, -0.5735764363510459, 0));
#89 = VECTOR('NONE', #88, 1);
#90 = CARTESIAN_POINT('NONE', (0.07861346939195568, -0.0254, -0));
#90 = CARTESIAN_POINT('NONE', (1.996782122555674, -0.64516, -0));
#91 = LINE('NONE', #90, #89);
#92 = DIRECTION('NONE', (0, 0, 1));
#93 = VECTOR('NONE', #92, 1);
#94 = CARTESIAN_POINT('NONE', (0.1511633881344551, -0.07619999999999998, -0));
#94 = CARTESIAN_POINT('NONE', (3.839550058615159, -1.9354799999999992, -0));
#95 = LINE('NONE', #94, #93);
#96 = DIRECTION('NONE', (0.8191520442889919, -0.5735764363510459, 0));
#96 = DIRECTION('NONE', (0.819152044288992, -0.5735764363510459, 0));
#97 = VECTOR('NONE', #96, 1);
#98 = CARTESIAN_POINT('NONE', (0.07861346939195568, -0.0254, 0.1016));
#98 = CARTESIAN_POINT('NONE', (1.996782122555674, -0.64516, 2.58064));
#99 = LINE('NONE', #98, #97);
#100 = DIRECTION('NONE', (1, -0.0000000000000003079278779307945, 0));
#100 = DIRECTION('NONE', (1, -0.00000000000000038794063361359933, 0));
#101 = VECTOR('NONE', #100, 1);
#102 = CARTESIAN_POINT('NONE', (0.1511633881344551, -0.07619999999999998, -0));
#102 = CARTESIAN_POINT('NONE', (3.839550058615159, -1.9354799999999992, -0));
#103 = LINE('NONE', #102, #101);
#104 = DIRECTION('NONE', (0, 0, 1));
#105 = VECTOR('NONE', #104, 1);
#106 = CARTESIAN_POINT('NONE', (0.2413, -0.0762, -0));
#106 = CARTESIAN_POINT('NONE', (6.12902, -1.93548, -0));
#107 = LINE('NONE', #106, #105);
#108 = DIRECTION('NONE', (1, -0.0000000000000003079278779307945, 0));
#108 = DIRECTION('NONE', (1, -0.00000000000000038794063361359933, 0));
#109 = VECTOR('NONE', #108, 1);
#110 = CARTESIAN_POINT('NONE', (0.1511633881344551, -0.07619999999999998, 0.1016));
#110 = CARTESIAN_POINT('NONE', (3.839550058615159, -1.9354799999999992, 2.58064));
#111 = LINE('NONE', #110, #109);
#112 = DIRECTION('NONE', (0, 1, 0));
#113 = VECTOR('NONE', #112, 1);
#114 = CARTESIAN_POINT('NONE', (0.2413, -0.0762, -0));
#114 = CARTESIAN_POINT('NONE', (6.12902, -1.93548, -0));
#115 = LINE('NONE', #114, #113);
#116 = DIRECTION('NONE', (0, 0, 1));
#117 = VECTOR('NONE', #116, 1);
#118 = CARTESIAN_POINT('NONE', (0.2413, -0.0635, -0));
#118 = CARTESIAN_POINT('NONE', (6.12902, -1.6129, -0));
#119 = LINE('NONE', #118, #117);
#120 = DIRECTION('NONE', (0, 1, 0));
#121 = VECTOR('NONE', #120, 1);
#122 = CARTESIAN_POINT('NONE', (0.2413, -0.0762, 0.1016));
#122 = CARTESIAN_POINT('NONE', (6.12902, -1.93548, 2.58064));
#123 = LINE('NONE', #122, #121);
#124 = DIRECTION('NONE', (-1, 0, 0));
#125 = VECTOR('NONE', #124, 1);
#126 = CARTESIAN_POINT('NONE', (0.2413, -0.0635, -0));
#126 = CARTESIAN_POINT('NONE', (6.12902, -1.6129, -0));
#127 = LINE('NONE', #126, #125);
#128 = DIRECTION('NONE', (0, 0, 1));
#129 = VECTOR('NONE', #128, 1);
#130 = CARTESIAN_POINT('NONE', (0.1551676827532182, -0.0635, -0));
#130 = CARTESIAN_POINT('NONE', (3.9412591419317424, -1.6129, -0));
#131 = LINE('NONE', #130, #129);
#132 = DIRECTION('NONE', (-1, 0, 0));
#133 = VECTOR('NONE', #132, 1);
#134 = CARTESIAN_POINT('NONE', (0.2413, -0.0635, 0.1016));
#134 = CARTESIAN_POINT('NONE', (6.12902, -1.6129, 2.58064));
#135 = LINE('NONE', #134, #133);
#136 = DIRECTION('NONE', (-0.8191520442889919, 0.573576436351046, 0));
#137 = VECTOR('NONE', #136, 1);
#138 = CARTESIAN_POINT('NONE', (0.1551676827532182, -0.0635, -0));
#138 = CARTESIAN_POINT('NONE', (3.9412591419317424, -1.6129, -0));
#139 = LINE('NONE', #138, #137);
#140 = DIRECTION('NONE', (0, 0, 1));
#141 = VECTOR('NONE', #140, 1);
#142 = CARTESIAN_POINT('NONE', (0.06448028432509392, 0, -0));
#142 = CARTESIAN_POINT('NONE', (1.6377992218573856, 0, -0));
#143 = LINE('NONE', #142, #141);
#144 = DIRECTION('NONE', (-0.8191520442889919, 0.573576436351046, 0));
#145 = VECTOR('NONE', #144, 1);
#146 = CARTESIAN_POINT('NONE', (0.1551676827532182, -0.0635, 0.1016));
#146 = CARTESIAN_POINT('NONE', (3.9412591419317424, -1.6129, 2.58064));
#147 = LINE('NONE', #146, #145);
#148 = DIRECTION('NONE', (0.90630778703665, 0.4226182617406993, 0));
#148 = DIRECTION('NONE', (0.90630778703665, 0.4226182617406992, 0));
#149 = VECTOR('NONE', #148, 1);
#150 = CARTESIAN_POINT('NONE', (0.06448028432509392, 0, -0));
#150 = CARTESIAN_POINT('NONE', (1.6377992218573856, 0, -0));
#151 = LINE('NONE', #150, #149);
#152 = DIRECTION('NONE', (0, 0, 1));
#153 = VECTOR('NONE', #152, 1);
#154 = CARTESIAN_POINT('NONE', (0.14618599799650817, 0.03810000000000001, -0));
#154 = CARTESIAN_POINT('NONE', (3.7131243491113075, 0.9677400000000002, -0));
#155 = LINE('NONE', #154, #153);
#156 = DIRECTION('NONE', (0.90630778703665, 0.4226182617406993, 0));
#156 = DIRECTION('NONE', (0.90630778703665, 0.4226182617406992, 0));
#157 = VECTOR('NONE', #156, 1);
#158 = CARTESIAN_POINT('NONE', (0.06448028432509392, 0, 0.1016));
#158 = CARTESIAN_POINT('NONE', (1.6377992218573856, 0, 2.58064));
#159 = LINE('NONE', #158, #157);
#160 = DIRECTION('NONE', (1, -0.00000000000000007295344279228718, 0));
#160 = DIRECTION('NONE', (1, -0.0000000000000001378647737807002, 0));
#161 = VECTOR('NONE', #160, 1);
#162 = CARTESIAN_POINT('NONE', (0.14618599799650817, 0.03810000000000001, -0));
#162 = CARTESIAN_POINT('NONE', (3.7131243491113075, 0.9677400000000002, -0));
#163 = LINE('NONE', #162, #161);
#164 = DIRECTION('NONE', (0, 0, 1));
#165 = VECTOR('NONE', #164, 1);
#166 = CARTESIAN_POINT('NONE', (0.2413, 0.0381, -0));
#166 = CARTESIAN_POINT('NONE', (6.12902, 0.9677399999999998, -0));
#167 = LINE('NONE', #166, #165);
#168 = DIRECTION('NONE', (1, -0.00000000000000007295344279228718, 0));
#168 = DIRECTION('NONE', (1, -0.0000000000000001378647737807002, 0));
#169 = VECTOR('NONE', #168, 1);
#170 = CARTESIAN_POINT('NONE', (0.14618599799650817, 0.03810000000000001, 0.1016));
#170 = CARTESIAN_POINT('NONE', (3.7131243491113075, 0.9677400000000002, 2.58064));
#171 = LINE('NONE', #170, #169);
#172 = DIRECTION('NONE', (0, 1, 0));
#173 = VECTOR('NONE', #172, 1);
#174 = CARTESIAN_POINT('NONE', (0.2413, 0.0381, -0));
#174 = CARTESIAN_POINT('NONE', (6.12902, 0.9677399999999998, -0));
#175 = LINE('NONE', #174, #173);
#176 = DIRECTION('NONE', (0, 0, 1));
#177 = VECTOR('NONE', #176, 1);
#178 = CARTESIAN_POINT('NONE', (0.2413, 0.0508, -0));
#178 = CARTESIAN_POINT('NONE', (6.12902, 1.29032, -0));
#179 = LINE('NONE', #178, #177);
#180 = DIRECTION('NONE', (0, 1, 0));
#181 = VECTOR('NONE', #180, 1);
#182 = CARTESIAN_POINT('NONE', (0.2413, 0.0381, 0.1016));
#182 = CARTESIAN_POINT('NONE', (6.12902, 0.9677399999999998, 2.58064));
#183 = LINE('NONE', #182, #181);
#184 = DIRECTION('NONE', (-1, 0, 0));
#185 = VECTOR('NONE', #184, 1);
#186 = CARTESIAN_POINT('NONE', (0.2413, 0.0508, -0));
#186 = CARTESIAN_POINT('NONE', (6.12902, 1.29032, -0));
#187 = LINE('NONE', #186, #185);
#188 = DIRECTION('NONE', (0, 0, 1));
#189 = VECTOR('NONE', #188, 1);
#190 = CARTESIAN_POINT('NONE', (0.14337047578094278, 0.0508, -0));
#190 = CARTESIAN_POINT('NONE', (3.6416100848359463, 1.29032, -0));
#191 = LINE('NONE', #190, #189);
#192 = DIRECTION('NONE', (-1, 0, 0));
#193 = VECTOR('NONE', #192, 1);
#194 = CARTESIAN_POINT('NONE', (0.2413, 0.0508, 0.1016));
#194 = CARTESIAN_POINT('NONE', (6.12902, 1.29032, 2.58064));
#195 = LINE('NONE', #194, #193);
#196 = DIRECTION('NONE', (-0.90630778703665, -0.42261826174069944, 0));
#196 = DIRECTION('NONE', (-0.90630778703665, -0.4226182617406995, 0));
#197 = VECTOR('NONE', #196, 1);
#198 = CARTESIAN_POINT('NONE', (0.14337047578094278, 0.0508, -0));
#198 = CARTESIAN_POINT('NONE', (3.6416100848359463, 1.29032, -0));
#199 = LINE('NONE', #198, #197);
#200 = DIRECTION('NONE', (0, 0, 1));
#201 = VECTOR('NONE', #200, 1);
#202 = CARTESIAN_POINT('NONE', (0.08889999999999999, 0.0254, -0));
#202 = CARTESIAN_POINT('NONE', (2.2580599999999995, 0.64516, -0));
#203 = LINE('NONE', #202, #201);
#204 = DIRECTION('NONE', (-0.90630778703665, -0.42261826174069944, 0));
#204 = DIRECTION('NONE', (-0.90630778703665, -0.4226182617406995, 0));
#205 = VECTOR('NONE', #204, 1);
#206 = CARTESIAN_POINT('NONE', (0.14337047578094278, 0.0508, 0.1016));
#206 = CARTESIAN_POINT('NONE', (3.6416100848359463, 1.29032, 2.58064));
#207 = LINE('NONE', #206, #205);
#208 = DIRECTION('NONE', (-1, 0, 0));
#209 = VECTOR('NONE', #208, 1);
#210 = CARTESIAN_POINT('NONE', (0.08889999999999999, 0.0254, -0));
#210 = CARTESIAN_POINT('NONE', (2.2580599999999995, 0.64516, -0));
#211 = LINE('NONE', #210, #209);
#212 = DIRECTION('NONE', (0, 0, 1));
#213 = VECTOR('NONE', #212, 1);
#214 = CARTESIAN_POINT('NONE', (0, 0.0254, -0));
#214 = CARTESIAN_POINT('NONE', (0, 0.64516, -0));
#215 = LINE('NONE', #214, #213);
#216 = DIRECTION('NONE', (-1, 0, 0));
#217 = VECTOR('NONE', #216, 1);
#218 = CARTESIAN_POINT('NONE', (0.08889999999999999, 0.0254, 0.1016));
#218 = CARTESIAN_POINT('NONE', (2.2580599999999995, 0.64516, 2.58064));
#219 = LINE('NONE', #218, #217);
#220 = DIRECTION('NONE', (0, -1, 0));
#221 = VECTOR('NONE', #220, 1);
#222 = CARTESIAN_POINT('NONE', (0, 0.0254, -0));
#222 = CARTESIAN_POINT('NONE', (0, 0.64516, -0));
#223 = LINE('NONE', #222, #221);
#224 = DIRECTION('NONE', (0, -1, 0));
#225 = VECTOR('NONE', #224, 1);
#226 = CARTESIAN_POINT('NONE', (0, 0.0254, 0.1016));
#226 = CARTESIAN_POINT('NONE', (0, 0.64516, 2.58064));
#227 = LINE('NONE', #226, #225);
#228 = EDGE_CURVE('NONE', #5, #7, #63, .T.);
#229 = EDGE_CURVE('NONE', #7, #9, #67, .T.);
@ -383,59 +383,59 @@ DATA;
#367 = ORIENTED_EDGE('NONE', *, *, #267, .T.);
#368 = ORIENTED_EDGE('NONE', *, *, #269, .T.);
#369 = EDGE_LOOP('NONE', (#355, #356, #357, #358, #359, #360, #361, #362, #363, #364, #365, #366, #367, #368));
#370 = CARTESIAN_POINT('NONE', (0, -0.0127, 0.0508));
#370 = CARTESIAN_POINT('NONE', (0, -0.3225799999999985, 1.2903199999999995));
#371 = DIRECTION('NONE', (-1, -0, 0));
#372 = AXIS2_PLACEMENT_3D('NONE', #370, #371, $);
#373 = PLANE('NONE', #372);
#374 = CARTESIAN_POINT('NONE', (0.039306734695977924, -0.025399999999999995, 0.0508));
#374 = CARTESIAN_POINT('NONE', (0.9983910612778368, -0.6451599999999998, 1.2903199999999997));
#375 = DIRECTION('NONE', (0, -1, 0));
#376 = AXIS2_PLACEMENT_3D('NONE', #374, #375, $);
#377 = PLANE('NONE', #376);
#378 = CARTESIAN_POINT('NONE', (0.11488842876320533, -0.05079999999999996, 0.05079999999999999));
#378 = CARTESIAN_POINT('NONE', (2.918166090585415, -1.2903199999999988, 1.2903199999999997));
#379 = DIRECTION('NONE', (-0.5735764363510459, -0.8191520442889919, 0));
#380 = AXIS2_PLACEMENT_3D('NONE', #378, #379, $);
#381 = PLANE('NONE', #380);
#382 = CARTESIAN_POINT('NONE', (0.19623169406722757, -0.07619999999999999, 0.0508));
#382 = CARTESIAN_POINT('NONE', (4.984285029307579, -1.9354799999999992, 1.2903199999999997));
#383 = DIRECTION('NONE', (0, -1, 0));
#384 = AXIS2_PLACEMENT_3D('NONE', #382, #383, $);
#385 = PLANE('NONE', #384);
#386 = CARTESIAN_POINT('NONE', (0.2413, -0.06985, 0.0508));
#386 = CARTESIAN_POINT('NONE', (6.129019999999999, -1.7741899999999997, 1.2903199999999997));
#387 = DIRECTION('NONE', (1, -0, 0));
#388 = AXIS2_PLACEMENT_3D('NONE', #386, #387, $);
#389 = PLANE('NONE', #388);
#390 = CARTESIAN_POINT('NONE', (0.19823384137660915, -0.0635, 0.0508));
#390 = CARTESIAN_POINT('NONE', (5.035139570965871, -1.6128999999999998, 1.2903199999999997));
#391 = DIRECTION('NONE', (0, 1, -0));
#392 = AXIS2_PLACEMENT_3D('NONE', #390, #391, $);
#393 = PLANE('NONE', #392);
#394 = CARTESIAN_POINT('NONE', (0.10982398353915601, -0.03174999999999997, 0.0508));
#395 = DIRECTION('NONE', (0.5735764363510459, 0.8191520442889917, -0));
#394 = CARTESIAN_POINT('NONE', (2.7895291818945633, -0.8064499999999998, 1.2903199999999995));
#395 = DIRECTION('NONE', (0.5735764363510459, 0.8191520442889918, -0));
#396 = AXIS2_PLACEMENT_3D('NONE', #394, #395, $);
#397 = PLANE('NONE', #396);
#398 = CARTESIAN_POINT('NONE', (0.105333141160801, 0.019049999999999987, 0.0508));
#399 = DIRECTION('NONE', (0.4226182617406993, -0.90630778703665, 0));
#398 = CARTESIAN_POINT('NONE', (2.6754617854843468, 0.4838700000000003, 1.2903199999999997));
#399 = DIRECTION('NONE', (0.4226182617406992, -0.90630778703665, 0));
#400 = AXIS2_PLACEMENT_3D('NONE', #398, #399, $);
#401 = PLANE('NONE', #400);
#402 = CARTESIAN_POINT('NONE', (0.19374299899825406, 0.0381, 0.0508));
#402 = CARTESIAN_POINT('NONE', (4.921072174555653, 0.9677399999999998, 1.2903199999999995));
#403 = DIRECTION('NONE', (0, -1, 0));
#404 = AXIS2_PLACEMENT_3D('NONE', #402, #403, $);
#405 = PLANE('NONE', #404);
#406 = CARTESIAN_POINT('NONE', (0.2413, 0.044449999999999996, 0.0508));
#406 = CARTESIAN_POINT('NONE', (6.129019999999998, 1.1290299999999989, 1.2903199999999995));
#407 = DIRECTION('NONE', (1, -0, 0));
#408 = AXIS2_PLACEMENT_3D('NONE', #406, #407, $);
#409 = PLANE('NONE', #408);
#410 = CARTESIAN_POINT('NONE', (0.19233523789047138, 0.0508, 0.0508));
#410 = CARTESIAN_POINT('NONE', (4.8853150424179725, 1.2903199999999997, 1.2903199999999997));
#411 = DIRECTION('NONE', (0, 1, -0));
#412 = AXIS2_PLACEMENT_3D('NONE', #410, #411, $);
#413 = PLANE('NONE', #412);
#414 = CARTESIAN_POINT('NONE', (0.11613523789047137, 0.0381, 0.05079999999999999));
#415 = DIRECTION('NONE', (-0.42261826174069966, 0.90630778703665, -0));
#414 = CARTESIAN_POINT('NONE', (2.9498350424179733, 0.9677399999999998, 1.2903199999999997));
#415 = DIRECTION('NONE', (-0.42261826174069933, 0.9063077870366499, -0));
#416 = AXIS2_PLACEMENT_3D('NONE', #414, #415, $);
#417 = PLANE('NONE', #416);
#418 = CARTESIAN_POINT('NONE', (0.044449999999999996, 0.0254, 0.0508));
#418 = CARTESIAN_POINT('NONE', (1.1290299999999998, 0.6451599999999998, 1.29032));
#419 = DIRECTION('NONE', (0, 1, -0));
#420 = AXIS2_PLACEMENT_3D('NONE', #418, #419, $);
#421 = PLANE('NONE', #420);
#422 = CARTESIAN_POINT('NONE', (0, 0.0127, 0.0508));
#422 = CARTESIAN_POINT('NONE', (0, 0.32257999999999987, 1.2903199999999995));
#423 = DIRECTION('NONE', (-1, -0, 0));
#424 = AXIS2_PLACEMENT_3D('NONE', #422, #423, $);
#425 = PLANE('NONE', #424);
@ -443,7 +443,7 @@ DATA;
#427 = DIRECTION('NONE', (0, 0, 1));
#428 = AXIS2_PLACEMENT_3D('NONE', #426, #427, $);
#429 = PLANE('NONE', #428);
#430 = CARTESIAN_POINT('NONE', (0, 0, 0.1016));
#430 = CARTESIAN_POINT('NONE', (0, 0, 2.58064));
#431 = DIRECTION('NONE', (0, 0, 1));
#432 = AXIS2_PLACEMENT_3D('NONE', #430, #431, $);
#433 = PLANE('NONE', #432);

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 221 KiB

View File

@ -1,478 +1,478 @@
solid unnamed
facet normal -1 0 0
outer loop
vertex 0 -4 0
vertex 0 -101.600006 0
vertex 0 -0 0
vertex 0 -4 -1
vertex 0 -101.600006 -25.400002
endloop
endfacet
facet normal -1 0 0
outer loop
vertex 0 -4 -1
vertex 0 -101.600006 -25.400002
vertex 0 -0 0
vertex 0 -0 -1
vertex 0 -0 -25.400002
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 0 -4 -1
vertex 0 -0 -1
vertex 3.0950184 -4 -1
vertex 0 -101.600006 -25.400002
vertex 0 -0 -25.400002
vertex 78.613464 -101.600006 -25.400002
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 3.0950184 -4 -1
vertex 0 -0 -1
vertex 3.0950184 -0 -1
vertex 78.613464 -101.600006 -25.400002
vertex 0 -0 -25.400002
vertex 78.613464 -0 -25.400002
endloop
endfacet
facet normal -0.57357645 0 -0.81915206
facet normal -0.5735764 0 -0.8191522
outer loop
vertex 3.0950184 -4 -1
vertex 3.0950184 -0 -1
vertex 5.9513144 -4 -3
vertex 78.613464 -101.600006 -25.400002
vertex 78.613464 -0 -25.400002
vertex 151.16339 -101.600006 -76.2
endloop
endfacet
facet normal -0.57357645 0 -0.81915206
facet normal -0.5735764 0 -0.8191522
outer loop
vertex 5.9513144 -4 -3
vertex 3.0950184 -0 -1
vertex 5.9513144 -0 -3
vertex 151.16339 -101.600006 -76.2
vertex 78.613464 -0 -25.400002
vertex 151.16339 -0 -76.2
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 5.9513144 -4 -3
vertex 5.9513144 -0 -3
vertex 9.5 -4 -3
vertex 151.16339 -101.600006 -76.2
vertex 151.16339 -0 -76.2
vertex 241.3 -101.600006 -76.2
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 9.5 -4 -3
vertex 5.9513144 -0 -3
vertex 9.5 -0 -3
vertex 241.3 -101.600006 -76.2
vertex 151.16339 -0 -76.2
vertex 241.3 -0 -76.2
endloop
endfacet
facet normal 1 0 0
outer loop
vertex 9.5 -4 -3
vertex 9.5 -0 -3
vertex 9.5 -4 -2.5
vertex 241.3 -101.600006 -76.2
vertex 241.3 -0 -76.2
vertex 241.3 -101.600006 -63.5
endloop
endfacet
facet normal 1 -0 0
outer loop
vertex 9.5 -4 -2.5
vertex 9.5 -0 -3
vertex 9.5 -0 -2.5
vertex 241.3 -101.600006 -63.5
vertex 241.3 -0 -76.2
vertex 241.3 -0 -63.5
endloop
endfacet
facet normal 0 -0 1
outer loop
vertex 241.3 -101.600006 -63.5
vertex 241.3 -0 -63.5
vertex 155.16768 -101.600006 -63.5
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 155.16768 -101.600006 -63.5
vertex 241.3 -0 -63.5
vertex 155.16768 -0 -63.5
endloop
endfacet
facet normal 0.5735765 0 0.81915194
outer loop
vertex 87.15214 -101.600006 -15.875
vertex 109.82398 -101.600006 -31.75
vertex 109.82398 -0 -31.75
endloop
endfacet
facet normal 0.57357645 0 0.819152
outer loop
vertex 109.82398 -101.600006 -31.75
vertex 155.16768 -101.600006 -63.5
vertex 155.16768 -0 -63.5
endloop
endfacet
facet normal 0.57357645 0 0.81915206
outer loop
vertex 87.15214 -0 -15.875
vertex 64.480286 -101.600006 0
vertex 87.15214 -101.600006 -15.875
endloop
endfacet
facet normal 0.5735765 0 0.81915194
outer loop
vertex 109.82398 -0 -31.75
vertex 87.15214 -0 -15.875
vertex 87.15214 -101.600006 -15.875
endloop
endfacet
facet normal 0.57357645 -0 0.819152
outer loop
vertex 109.82398 -101.600006 -31.75
vertex 155.16768 -0 -63.5
vertex 109.82398 -0 -31.75
endloop
endfacet
facet normal 0.57357645 -0 0.81915206
outer loop
vertex 64.480286 -101.600006 0
vertex 87.15214 -0 -15.875
vertex 64.480286 -0 0
endloop
endfacet
facet normal 0.4226182 0 -0.9063078
outer loop
vertex 84.906715 -101.600006 9.525
vertex 64.480286 -101.600006 0
vertex 64.480286 -0 0
endloop
endfacet
facet normal 0.42261833 0 -0.90630776
outer loop
vertex 105.33314 -101.600006 19.05
vertex 84.906715 -101.600006 9.525
vertex 84.906715 -0 9.525
endloop
endfacet
facet normal 0.4226182 0 -0.9063078
outer loop
vertex 84.906715 -0 9.525
vertex 84.906715 -101.600006 9.525
vertex 64.480286 -0 0
endloop
endfacet
facet normal 0.4226183 0 -0.9063078
outer loop
vertex 105.33314 -0 19.05
vertex 146.18599 -101.600006 38.1
vertex 105.33314 -101.600006 19.05
endloop
endfacet
facet normal 0.42261833 0 -0.90630776
outer loop
vertex 105.33314 -101.600006 19.05
vertex 84.906715 -0 9.525
vertex 105.33314 -0 19.05
endloop
endfacet
facet normal 0.4226183 0 -0.9063078
outer loop
vertex 146.18599 -101.600006 38.1
vertex 105.33314 -0 19.05
vertex 146.18599 -0 38.1
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 146.18599 -101.600006 38.1
vertex 146.18599 -0 38.1
vertex 241.3 -101.600006 38.1
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 241.3 -101.600006 38.1
vertex 146.18599 -0 38.1
vertex 241.3 -0 38.1
endloop
endfacet
facet normal 1 0 0
outer loop
vertex 241.3 -101.600006 38.1
vertex 241.3 -0 38.1
vertex 241.3 -101.600006 50.800003
endloop
endfacet
facet normal 1 -0 0
outer loop
vertex 241.3 -101.600006 50.800003
vertex 241.3 -0 38.1
vertex 241.3 -0 50.800003
endloop
endfacet
facet normal 0 -0 0.99999994
outer loop
vertex 9.5 -4 -2.5
vertex 9.5 -0 -2.5
vertex 6.108964 -4 -2.5
vertex 241.3 -101.600006 50.800003
vertex 241.3 -0 50.800003
vertex 143.37048 -101.600006 50.800003
endloop
endfacet
facet normal 0 0 0.99999994
outer loop
vertex 6.108964 -4 -2.5
vertex 9.5 -0 -2.5
vertex 6.108964 -0 -2.5
vertex 143.37048 -101.600006 50.800003
vertex 241.3 -0 50.800003
vertex 143.37048 -0 50.800003
endloop
endfacet
facet normal 0.5735763 0 0.8191522
facet normal -0.42261827 0 0.9063078
outer loop
vertex 3.4311862 -4 -0.625
vertex 4.323779 -4 -1.25
vertex 4.323779 -0 -1.25
vertex 143.37048 -101.600006 50.800003
vertex 143.37048 -0 50.800003
vertex 88.9 -101.600006 25.400002
endloop
endfacet
facet normal 0.57357645 0 0.819152
facet normal -0.42261827 0 0.9063078
outer loop
vertex 4.323779 -4 -1.25
vertex 6.108964 -4 -2.5
vertex 6.108964 -0 -2.5
endloop
endfacet
facet normal 0.57357645 0 0.819152
outer loop
vertex 3.4311862 -0 -0.625
vertex 2.5385938 -4 0
vertex 3.4311862 -4 -0.625
endloop
endfacet
facet normal 0.5735763 0 0.8191522
outer loop
vertex 4.323779 -0 -1.25
vertex 3.4311862 -0 -0.625
vertex 3.4311862 -4 -0.625
endloop
endfacet
facet normal 0.57357645 -0 0.819152
outer loop
vertex 4.323779 -4 -1.25
vertex 6.108964 -0 -2.5
vertex 4.323779 -0 -1.25
endloop
endfacet
facet normal 0.57357645 -0 0.819152
outer loop
vertex 2.5385938 -4 0
vertex 3.4311862 -0 -0.625
vertex 2.5385938 -0 0
endloop
endfacet
facet normal 0.42261824 0 -0.9063078
outer loop
vertex 3.342784 -4 0.375
vertex 2.5385938 -4 0
vertex 2.5385938 -0 0
endloop
endfacet
facet normal 0.42261824 0 -0.9063078
outer loop
vertex 4.146974 -4 0.75
vertex 3.342784 -4 0.375
vertex 3.342784 -0 0.375
endloop
endfacet
facet normal 0.42261824 0 -0.9063078
outer loop
vertex 3.342784 -0 0.375
vertex 3.342784 -4 0.375
vertex 2.5385938 -0 0
endloop
endfacet
facet normal 0.42261833 0 -0.90630776
outer loop
vertex 4.146974 -0 0.75
vertex 5.755354 -4 1.5
vertex 4.146974 -4 0.75
endloop
endfacet
facet normal 0.42261824 0 -0.9063078
outer loop
vertex 4.146974 -4 0.75
vertex 3.342784 -0 0.375
vertex 4.146974 -0 0.75
endloop
endfacet
facet normal 0.42261833 0 -0.90630776
outer loop
vertex 5.755354 -4 1.5
vertex 4.146974 -0 0.75
vertex 5.755354 -0 1.5
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 5.755354 -4 1.5
vertex 5.755354 -0 1.5
vertex 9.5 -4 1.5
endloop
endfacet
facet normal 0 0 -1
outer loop
vertex 9.5 -4 1.5
vertex 5.755354 -0 1.5
vertex 9.5 -0 1.5
endloop
endfacet
facet normal 1 0 0
outer loop
vertex 9.5 -4 1.5
vertex 9.5 -0 1.5
vertex 9.5 -4 2
endloop
endfacet
facet normal 1 -0 0
outer loop
vertex 9.5 -4 2
vertex 9.5 -0 1.5
vertex 9.5 -0 2
vertex 88.9 -101.600006 25.400002
vertex 143.37048 -0 50.800003
vertex 88.9 -0 25.400002
endloop
endfacet
facet normal 0 -0 1
outer loop
vertex 9.5 -4 2
vertex 9.5 -0 2
vertex 5.644507 -4 2
vertex 88.9 -101.600006 25.400002
vertex 88.9 -0 25.400002
vertex 0 -101.600006 25.400002
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 5.644507 -4 2
vertex 9.5 -0 2
vertex 5.644507 -0 2
endloop
endfacet
facet normal -0.42261824 0 0.90630776
outer loop
vertex 5.644507 -4 2
vertex 5.644507 -0 2
vertex 3.5 -4 1
endloop
endfacet
facet normal -0.42261824 0 0.90630776
outer loop
vertex 3.5 -4 1
vertex 5.644507 -0 2
vertex 3.5 -0 1
endloop
endfacet
facet normal 0 -0 1
outer loop
vertex 3.5 -4 1
vertex 3.5 -0 1
vertex 0 -4 1
endloop
endfacet
facet normal 0 0 1
outer loop
vertex 0 -4 1
vertex 3.5 -0 1
vertex 0 -0 1
vertex 0 -101.600006 25.400002
vertex 88.9 -0 25.400002
vertex 0 -0 25.400002
endloop
endfacet
facet normal -1 0 0
outer loop
vertex 0 -4 1
vertex 0 -0 1
vertex 0 -4 0
vertex 0 -101.600006 25.400002
vertex 0 -0 25.400002
vertex 0 -101.600006 0
endloop
endfacet
facet normal -1 0 0
outer loop
vertex 0 -4 0
vertex 0 -0 1
vertex 0 -101.600006 0
vertex 0 -0 25.400002
vertex 0 -0 0
endloop
endfacet
facet normal 0 1 -0
outer loop
vertex 3.342784 -0 0.375
vertex 2.5385938 -0 0
vertex 3.5 -0 1
vertex 84.906715 -0 9.525
vertex 64.480286 -0 0
vertex 88.9 -0 25.400002
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 4.146974 -0 0.75
vertex 3.342784 -0 0.375
vertex 3.5 -0 1
vertex 105.33314 -0 19.05
vertex 84.906715 -0 9.525
vertex 88.9 -0 25.400002
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 3.4311862 -0 -0.625
vertex 4.323779 -0 -1.25
vertex 3.0950184 -0 -1
vertex 87.15214 -0 -15.875
vertex 109.82398 -0 -31.75
vertex 78.613464 -0 -25.400002
endloop
endfacet
facet normal 0 0.99999994 0
facet normal 0 1 0
outer loop
vertex 4.146974 -0 0.75
vertex 5.644507 -0 2
vertex 5.755354 -0 1.5
vertex 105.33314 -0 19.05
vertex 143.37048 -0 50.800003
vertex 146.18599 -0 38.1
endloop
endfacet
facet normal -0 1 0
outer loop
vertex 0 -0 1
vertex 3.5 -0 1
vertex 2.5385938 -0 0
vertex 0 -0 25.400002
vertex 88.9 -0 25.400002
vertex 64.480286 -0 0
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 0 -0 1
vertex 2.5385938 -0 0
vertex 0 -0 25.400002
vertex 64.480286 -0 0
vertex 0 -0 0
endloop
endfacet
facet normal -0 1 0
outer loop
vertex 5.644507 -0 2
vertex 9.5 -0 2
vertex 5.755354 -0 1.5
vertex 143.37048 -0 50.800003
vertex 241.3 -0 50.800003
vertex 146.18599 -0 38.1
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 9.5 -0 2
vertex 9.5 -0 1.5
vertex 5.755354 -0 1.5
vertex 241.3 -0 50.800003
vertex 241.3 -0 38.1
vertex 146.18599 -0 38.1
endloop
endfacet
facet normal 0 1 -0
outer loop
vertex 4.146974 -0 0.75
vertex 3.5 -0 1
vertex 5.644507 -0 2
vertex 105.33314 -0 19.05
vertex 88.9 -0 25.400002
vertex 143.37048 -0 50.800003
endloop
endfacet
facet normal 0 0.99999994 0
outer loop
vertex 2.5385938 -0 0
vertex 3.4311862 -0 -0.625
vertex 3.0950184 -0 -1
endloop
endfacet
facet normal 0 0.99999994 0
outer loop
vertex 4.323779 -0 -1.25
vertex 5.9513144 -0 -3
vertex 3.0950184 -0 -1
vertex 64.480286 -0 0
vertex 87.15214 -0 -15.875
vertex 78.613464 -0 -25.400002
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 6.108964 -0 -2.5
vertex 5.9513144 -0 -3
vertex 4.323779 -0 -1.25
endloop
endfacet
facet normal 0 0.99999994 0
outer loop
vertex 9.5 -0 -2.5
vertex 9.5 -0 -3
vertex 6.108964 -0 -2.5
vertex 109.82398 -0 -31.75
vertex 151.16339 -0 -76.2
vertex 78.613464 -0 -25.400002
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 6.108964 -0 -2.5
vertex 9.5 -0 -3
vertex 5.9513144 -0 -3
vertex 155.16768 -0 -63.5
vertex 151.16339 -0 -76.2
vertex 109.82398 -0 -31.75
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 2.5385938 -0 0
vertex 3.0950184 -0 -1
vertex 0 -0 -1
vertex 241.3 -0 -63.5
vertex 241.3 -0 -76.2
vertex 155.16768 -0 -63.5
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 0 -0 -1
vertex 155.16768 -0 -63.5
vertex 241.3 -0 -76.2
vertex 151.16339 -0 -76.2
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 64.480286 -0 0
vertex 78.613464 -0 -25.400002
vertex 0 -0 -25.400002
endloop
endfacet
facet normal 0 1 0
outer loop
vertex 0 -0 -25.400002
vertex 0 -0 0
vertex 2.5385938 -0 0
vertex 64.480286 -0 0
endloop
endfacet
facet normal -0 -1 0
outer loop
vertex 3.342784 -4 0.375
vertex 3.5 -4 1
vertex 2.5385938 -4 0
vertex 84.906715 -101.600006 9.525
vertex 88.9 -101.600006 25.400002
vertex 64.480286 -101.600006 0
endloop
endfacet
facet normal -0 -1 0
outer loop
vertex 4.146974 -4 0.75
vertex 3.5 -4 1
vertex 3.342784 -4 0.375
vertex 105.33314 -101.600006 19.05
vertex 88.9 -101.600006 25.400002
vertex 84.906715 -101.600006 9.525
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 3.4311862 -4 -0.625
vertex 3.0950184 -4 -1
vertex 4.323779 -4 -1.25
vertex 87.15214 -101.600006 -15.875
vertex 78.613464 -101.600006 -25.400002
vertex 109.82398 -101.600006 -31.75
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 105.33314 -101.600006 19.05
vertex 146.18599 -101.600006 38.1
vertex 143.37048 -101.600006 50.800003
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 0 -101.600006 25.400002
vertex 64.480286 -101.600006 0
vertex 88.9 -101.600006 25.400002
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 0 -101.600006 25.400002
vertex 0 -101.600006 0
vertex 64.480286 -101.600006 0
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 143.37048 -101.600006 50.800003
vertex 146.18599 -101.600006 38.1
vertex 241.3 -101.600006 50.800003
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 241.3 -101.600006 50.800003
vertex 146.18599 -101.600006 38.1
vertex 241.3 -101.600006 38.1
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 105.33314 -101.600006 19.05
vertex 143.37048 -101.600006 50.800003
vertex 88.9 -101.600006 25.400002
endloop
endfacet
facet normal 0 -0.99999994 0
outer loop
vertex 4.146974 -4 0.75
vertex 5.755354 -4 1.5
vertex 5.644507 -4 2
vertex 64.480286 -101.600006 0
vertex 78.613464 -101.600006 -25.400002
vertex 87.15214 -101.600006 -15.875
endloop
endfacet
facet normal 0 -1 0
facet normal -0 -1 -0
outer loop
vertex 0 -4 1
vertex 2.5385938 -4 0
vertex 3.5 -4 1
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 0 -4 1
vertex 0 -4 0
vertex 2.5385938 -4 0
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 5.644507 -4 2
vertex 5.755354 -4 1.5
vertex 9.5 -4 2
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 9.5 -4 2
vertex 5.755354 -4 1.5
vertex 9.5 -4 1.5
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 4.146974 -4 0.75
vertex 5.644507 -4 2
vertex 3.5 -4 1
endloop
endfacet
facet normal 0 -0.99999994 0
outer loop
vertex 2.5385938 -4 0
vertex 3.0950184 -4 -1
vertex 3.4311862 -4 -0.625
endloop
endfacet
facet normal -0 -0.99999994 -0
outer loop
vertex 4.323779 -4 -1.25
vertex 3.0950184 -4 -1
vertex 5.9513144 -4 -3
vertex 109.82398 -101.600006 -31.75
vertex 78.613464 -101.600006 -25.400002
vertex 151.16339 -101.600006 -76.2
endloop
endfacet
facet normal -0 -1 0
outer loop
vertex 6.108964 -4 -2.5
vertex 4.323779 -4 -1.25
vertex 5.9513144 -4 -3
vertex 155.16768 -101.600006 -63.5
vertex 109.82398 -101.600006 -31.75
vertex 151.16339 -101.600006 -76.2
endloop
endfacet
facet normal -0 -0.99999994 -0
facet normal -0 -1 -0
outer loop
vertex 9.5 -4 -2.5
vertex 6.108964 -4 -2.5
vertex 9.5 -4 -3
vertex 241.3 -101.600006 -63.5
vertex 155.16768 -101.600006 -63.5
vertex 241.3 -101.600006 -76.2
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 6.108964 -4 -2.5
vertex 5.9513144 -4 -3
vertex 9.5 -4 -3
vertex 155.16768 -101.600006 -63.5
vertex 151.16339 -101.600006 -76.2
vertex 241.3 -101.600006 -76.2
endloop
endfacet
facet normal 0 -1 -0
outer loop
vertex 2.5385938 -4 0
vertex 0 -4 -1
vertex 3.0950184 -4 -1
vertex 64.480286 -101.600006 0
vertex 0 -101.600006 -25.400002
vertex 78.613464 -101.600006 -25.400002
endloop
endfacet
facet normal 0 -1 0
outer loop
vertex 0 -4 -1
vertex 2.5385938 -4 0
vertex 0 -4 0
vertex 0 -101.600006 -25.400002
vertex 64.480286 -101.600006 0
vertex 0 -101.600006 0
endloop
endfacet
endsolid unnamed

Binary file not shown.

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 221 KiB

View File

@ -14,6 +14,12 @@ document.addEventListener('mousemove', (e) =>
)
*/
const commonPoints = {
startAt: '[26.38, -35.59]',
num1: 26.63,
num2: 53.01,
}
test.beforeEach(async ({ context, page }) => {
// wait for Vite preview server to be up
await waitOn({
@ -52,6 +58,9 @@ test('Basic sketch', async ({ page }) => {
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await expect(page.getByRole('button', { name: 'Start Sketch' })).toBeVisible()
// click on "Start Sketch" button
@ -72,35 +81,34 @@ test('Basic sketch', async ({ page }) => {
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
const startAt = '[23.89, -32.23]'
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)`)
|> startProfileAt(${commonPoints.startAt}, %)`)
await page.waitForTimeout(100)
await u.closeDebugPanel()
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
const num = 24.11
const num = 26.63
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)`)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)`)
await page.mouse.click(startXPx, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)
|> line([-48, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)
|> line([-${commonPoints.num2}, 0], %)`)
// deselect line tool
await page.getByRole('button', { name: 'Line' }).click()
@ -122,9 +130,9 @@ test('Basic sketch', async ({ page }) => {
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line({ to: [${num}, 0], tag: 'seg01' }, %)
|> line([0, ${num + 0.01}], %)
|> startProfileAt(${commonPoints.startAt}, %)
|> line({ to: [${commonPoints.num1}, 0], tag: 'seg01' }, %)
|> line([0, ${commonPoints.num1}], %)
|> angledLine([180, segLen('seg01', %)], %)`)
})
@ -305,11 +313,9 @@ test('Can create sketches on all planes and their back sides', async ({
}
const codeTemplate = (
plane = 'XY',
rounded = false,
otherThing = '1'
plane = 'XY'
) => `const part001 = startSketchOn('${plane}')
|> startProfileAt([28.9${otherThing}, -39${rounded ? '' : '.01'}], %)`
|> startProfileAt([32.13, -43.34], %)`
await TestSinglePlane({
viewCmd: camPos,
expectedCode: codeTemplate('XY'),
@ -318,7 +324,7 @@ test('Can create sketches on all planes and their back sides', async ({
})
await TestSinglePlane({
viewCmd: camPos,
expectedCode: codeTemplate('YZ', true),
expectedCode: codeTemplate('YZ'),
clickCoords: { x: 700, y: 300 }, // green plane
})
await TestSinglePlane({
@ -329,7 +335,7 @@ test('Can create sketches on all planes and their back sides', async ({
const camCmdBackSide: [number, number, number] = [-100, -100, -100]
await TestSinglePlane({
viewCmd: camCmdBackSide,
expectedCode: codeTemplate('-XY', false, '3'),
expectedCode: codeTemplate('-XY'),
clickCoords: { x: 601, y: 118 }, // back of red plane
})
await TestSinglePlane({
@ -339,7 +345,7 @@ test('Can create sketches on all planes and their back sides', async ({
})
await TestSinglePlane({
viewCmd: camCmdBackSide,
expectedCode: codeTemplate('-XZ', true),
expectedCode: codeTemplate('-XZ'),
clickCoords: { x: 680, y: 427 }, // back of blue plane
})
})
@ -375,6 +381,7 @@ test('Auto complete works', async ({ page }) => {
await page.keyboard.type(' |> lin')
await expect(page.locator('.cm-tooltip-autocomplete')).toBeVisible()
await page.waitForTimeout(100)
// press arrow down twice then enter to accept xLine
await page.keyboard.press('ArrowDown')
await page.keyboard.press('ArrowDown')
@ -452,6 +459,9 @@ test('Selections work on fresh and edited sketch', async ({ page }) => {
page.mouse.click(767, 396).then(() => page.waitForTimeout(100))
await u.clearCommandLogs()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await page.getByRole('button', { name: 'Start Sketch' }).click()
// select a plane
@ -460,35 +470,32 @@ test('Selections work on fresh and edited sketch', async ({ page }) => {
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
const startAt = '[23.89, -32.23]'
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)`)
|> startProfileAt(${commonPoints.startAt}, %)`)
await u.closeDebugPanel()
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
const num = 24.11
const num2 = '48'
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)`)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)`)
await page.mouse.click(startXPx, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)
|> line([-${num2}, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)
|> line([-${commonPoints.num2}, 0], %)`)
// deselect line tool
await page.getByRole('button', { name: 'Line' }).click()
@ -538,7 +545,7 @@ test('Selections work on fresh and edited sketch', async ({ page }) => {
await emptySpaceClick()
// check the same selection again by putting cursor in code first then selecting axis
await page.getByText(` |> line([-${num2}, 0], %)`).click()
await page.getByText(` |> line([-${commonPoints.num2}, 0], %)`).click()
await page.keyboard.down('Shift')
await expect(absYButton).toBeDisabled()
await xAxisClick()
@ -549,7 +556,7 @@ test('Selections work on fresh and edited sketch', async ({ page }) => {
await emptySpaceClick()
// select segment in editor than another segment in scene and check there are two cursors
await page.getByText(` |> line([-${num2}, 0], %)`).click()
await page.getByText(` |> line([-${commonPoints.num2}, 0], %)`).click()
await page.waitForTimeout(300)
await page.keyboard.down('Shift')
await expect(page.locator('.cm-cursor')).toHaveCount(1)
@ -573,12 +580,13 @@ test('Selections work on fresh and edited sketch', async ({ page }) => {
await u.closeDebugPanel()
// select a line
await topHorzSegmentClick()
await page.waitForTimeout(200)
// await topHorzSegmentClick()
await page.getByText(commonPoints.startAt).click() // TODO remove this and reinstate // await topHorzSegmentClick()
await page.waitForTimeout(100)
// enter sketch again
await page.getByRole('button', { name: 'Edit Sketch' }).click()
await page.waitForTimeout(700) // wait for animation
await page.waitForTimeout(300) // wait for animation
// hover again and check it works
await selectionSequence()
@ -635,12 +643,15 @@ test('Can extrude from the command bar', async ({ page, context }) => {
await context.addInitScript(async (token) => {
localStorage.setItem(
'persistCode',
`const part001 = startSketchOn('-XZ')
|> startProfileAt([-6.95, 4.98], %)
|> line([25.1, 0.41], %)
|> line([0.73, -14.93], %)
|> line([-23.44, 0.52], %)
|> close(%)`
`
const distance = sqrt(20)
const part001 = startSketchOn('-XZ')
|> startProfileAt([-6.95, 4.98], %)
|> line([25.1, 0.41], %)
|> line([0.73, -14.93], %)
|> line([-23.44, 0.52], %)
|> close(%)
`
)
})
@ -665,24 +676,42 @@ test('Can extrude from the command bar', async ({ page, context }) => {
// Click to select face and set distance
await page.getByText('|> startProfileAt([-6.95, 4.98], %)').click()
await page.getByRole('button', { name: 'Continue' }).click()
// Assert that we're on the distance step
await expect(page.getByRole('button', { name: 'distance' })).toBeDisabled()
await page.keyboard.press('Enter')
// Assert that the an alternative variable name is chosen,
// since the default variable name is already in use (distance)
await page.getByRole('button', { name: 'Create new variable' }).click()
await expect(page.getByPlaceholder('Variable name')).toHaveValue(
'distance001'
)
await expect(page.getByRole('button', { name: 'Continue' })).toBeEnabled()
await page.getByRole('button', { name: 'Continue' }).click()
// Review step and argument hotkeys
await page.keyboard.press('2')
await expect(page.getByRole('button', { name: '5' })).toBeDisabled()
await expect(
page.getByRole('button', { name: 'Submit command' })
).toBeEnabled()
await page.keyboard.press('Backspace')
await expect(
page.getByRole('button', { name: 'Distance 12', exact: false })
).toBeDisabled()
await page.keyboard.press('Enter')
// Check that the code was updated
await page.keyboard.press('Enter')
// Unfortunately this indentation seems to matter for the test
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('-XZ')
|> startProfileAt([-6.95, 4.98], %)
|> line([25.1, 0.41], %)
|> line([0.73, -14.93], %)
|> line([-23.44, 0.52], %)
|> close(%)
|> extrude(5, %)`
`const distance = sqrt(20)
const distance001 = 5 + 7
const part001 = startSketchOn('-XZ')
|> startProfileAt([-6.95, 4.98], %)
|> line([25.1, 0.41], %)
|> line([0.73, -14.93], %)
|> line([-23.44, 0.52], %)
|> close(%)
|> extrude(distance001, %)`.replace(/(\r\n|\n|\r)/gm, '') // remove newlines
)
})
@ -694,6 +723,9 @@ test('Can add multiple sketches', async ({ page }) => {
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await expect(page.getByRole('button', { name: 'Start Sketch' })).toBeVisible()
// click on "Start Sketch" button
@ -714,34 +746,32 @@ test('Can add multiple sketches', async ({ page }) => {
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
const startAt = '[23.89, -32.23]'
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)`)
|> startProfileAt(${commonPoints.startAt}, %)`)
await page.waitForTimeout(100)
await u.closeDebugPanel()
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
const num = 24.11
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)`)
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 20)
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)`)
await page.mouse.click(startXPx, 500 - PUR * 20)
const finalCodeFirstSketch = `const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)
|> line([0, ${num + 0.01}], %)
|> line([-48, 0], %)`
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)
|> line([0, ${commonPoints.num1}], %)
|> line([-${commonPoints.num2}, 0], %)`
await expect(page.locator('.cm-content')).toHaveText(finalCodeFirstSketch)
// exit the sketch
@ -763,7 +793,7 @@ test('Can add multiple sketches', async ({ page }) => {
await u.clearAndCloseDebugPanel()
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
const startAt2 = '[23.61, -31.85]'
const startAt2 = '[26.23, -35.39]'
await expect(
(await page.locator('.cm-content').innerText()).replace(/\s/g, '')
).toBe(
@ -777,7 +807,7 @@ const part002 = startSketchOn('XY')
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
const num2 = 23.83
const num2 = 26.48
await expect(
(await page.locator('.cm-content').innerText()).replace(/\s/g, '')
).toBe(
@ -806,7 +836,7 @@ const part002 = startSketchOn('XY')
|> startProfileAt(${startAt2}, %)
|> line([${num2}, 0], %)
|> line([0, ${num2}], %)
|> line([-47.44, 0], %)`.replace(/\s/g, '')
|> line([-52.71, 0], %)`.replace(/\s/g, '')
)
})
@ -849,7 +879,10 @@ test('ProgramMemory can be serialised', async ({ page, context }) => {
})
})
test('edit selections', async ({ page, context }) => {
test("Various pipe expressions should and shouldn't allow edit and or extrude", async ({
page,
context,
}) => {
const u = getUtils(page)
const selectionsSnippets = {
extrudeAndEditBlocked: '|> startProfileAt([10.81, 32.99], %)',
@ -913,6 +946,11 @@ fn yohey = (pos) => {
await u.expectCmdLog('[data-message-type="execution-done"]')
await u.closeDebugPanel()
// wait for start sketch as a proxy for the stream being ready
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await page.getByText(selectionsSnippets.extrudeAndEditBlocked).click()
await expect(page.getByRole('button', { name: 'Extrude' })).toBeDisabled()
await expect(
@ -948,3 +986,67 @@ fn yohey = (pos) => {
/part005 = startSketchOn\('-XZ'\)/
)
})
test('Deselecting line tool should mean nothing happens on click', async ({
page,
}) => {
const u = getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
const PUR = 400 / 37.5 //pixeltoUnitRatio
await page.goto('/')
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await expect(page.getByRole('button', { name: 'Start Sketch' })).toBeVisible()
// click on "Start Sketch" button
await u.clearCommandLogs()
await u.doAndWaitForImageDiff(
() => page.getByRole('button', { name: 'Start Sketch' }).click(),
200
)
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).toHaveText(
`const part001 = startSketchOn('-XZ')`
)
await page.waitForTimeout(300)
let previousCodeContent = await page.locator('.cm-content').innerText()
// deselect the line tool by clicking it
await page.getByRole('button', { name: 'Line' }).click()
await page.mouse.click(700, 200)
await page.waitForTimeout(100)
await page.mouse.click(700, 250)
await page.waitForTimeout(100)
await page.mouse.click(750, 200)
await page.waitForTimeout(100)
// expect no change
await expect(page.locator('.cm-content')).toHaveText(previousCodeContent)
// select line tool again
await page.getByRole('button', { name: 'Line' }).click()
await u.closeDebugPanel()
// line tool should work as expected again
await page.mouse.click(700, 200)
await expect(page.locator('.cm-content')).not.toHaveText(previousCodeContent)
previousCodeContent = await page.locator('.cm-content').innerText()
await page.mouse.click(700, 300)
await expect(page.locator('.cm-content')).not.toHaveText(previousCodeContent)
previousCodeContent = await page.locator('.cm-content').innerText()
await page.mouse.click(750, 300)
await expect(page.locator('.cm-content')).not.toHaveText(previousCodeContent)
previousCodeContent = await page.locator('.cm-content').innerText()
})

View File

@ -31,6 +31,12 @@ test.beforeEach(async ({ context, page }) => {
test.setTimeout(60000)
const commonPoints = {
startAt: '[26.38, -35.59]',
num1: 26.63,
num2: 53.01,
}
test('change camera, show planes', async ({ page, context }) => {
const u = getUtils(page)
await page.setViewportSize({ width: 1200, height: 500 })
@ -160,7 +166,7 @@ const part001 = startSketchOn('-XZ')
}, %)
|> angledLineToY([segAng('seg02', %) + 180, -baseHeight], %)
|> xLineTo(ZERO, %)
|> close(%)
|> close(%)
|> extrude(4, %)`
)
})
@ -342,24 +348,33 @@ const part001 = startSketchOn('-XZ')
// snapshot exports, good compromise to capture that exports are healthy without getting bogged down in "did the formatting change" changes
// context: https://github.com/KittyCAD/modeling-app/issues/1222
for (const { modelPath, imagePath, outputType } of exportLocations) {
const cliCommand = `export KITTYCAD_TOKEN=${secrets.snapshottoken} && kittycad file snapshot --output-format=png --src-format=${outputType} ${modelPath} ${imagePath}`
console.log(
`taking snapshot of using: "zoo file snapshot --output-format=png --src-format=${outputType} ${modelPath} ${imagePath}"`
)
const cliCommand = `export ZOO_TOKEN=${secrets.snapshottoken} && zoo file snapshot --output-format=png --src-format=${outputType} ${modelPath} ${imagePath}`
const child = spawn(cliCommand, { shell: true })
await new Promise((resolve, reject) => {
const result = await new Promise<string>((resolve, reject) => {
child.on('error', (code: any, msg: any) => {
console.log('error', code, msg)
reject()
reject('error')
})
child.on('exit', (code, msg) => {
console.log('exit', code, msg)
if (code !== 0) {
reject(`exit code ${code} for model ${modelPath}`)
} else {
resolve(true)
resolve('success')
}
})
child.stderr.on('data', (data) => console.log(`stderr: ${data}`))
child.stdout.on('data', (data) => console.log(`stdout: ${data}`))
})
expect(result).toBe('success')
if (result === 'success') {
console.log(`snapshot taken for ${modelPath}`)
} else {
console.log(`snapshot failed for ${modelPath}`)
}
}
})
@ -369,13 +384,13 @@ test('extrude on each default plane should be stable', async ({
}) => {
const u = getUtils(page)
const makeCode = (plane = 'XY') => `const part001 = startSketchOn('${plane}')
|> startProfileAt([14.06, 8.88], %)
|> line([12.98, -0.15], %)
|> line([5.56, 9.89], %)
|> line([-11.28, 8.96], %)
|> line([-10.81, -7.57], %)
|> startProfileAt([0.70, 0.44], %)
|> line([0.66, -0.02], %)
|> line([0.28, 0.50], %)
|> line([-0.56, 0.44], %)
|> line([-0.54, -0.38], %)
|> close(%)
|> extrude(20, %)
|> extrude(1.00, %)
`
await context.addInitScript(async (code) => {
localStorage.setItem('persistCode', code)
@ -428,6 +443,9 @@ test('Draft segments should look right', async ({ page }) => {
await u.waitForAuthSkipAppStart()
await u.openDebugPanel()
await expect(
page.getByRole('button', { name: 'Start Sketch' })
).not.toBeDisabled()
await expect(page.getByRole('button', { name: 'Start Sketch' })).toBeVisible()
// click on "Start Sketch" button
@ -448,10 +466,9 @@ test('Draft segments should look right', async ({ page }) => {
const startXPx = 600
await page.mouse.click(startXPx + PUR * 10, 500 - PUR * 10)
const startAt = '[23.89, -32.23]'
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)`)
|> startProfileAt(${commonPoints.startAt}, %)`)
await page.waitForTimeout(100)
await u.closeDebugPanel()
@ -463,11 +480,10 @@ test('Draft segments should look right', async ({ page }) => {
await page.mouse.click(startXPx + PUR * 20, 500 - PUR * 10)
await page.waitForTimeout(100)
const num = 24.11
await expect(page.locator('.cm-content'))
.toHaveText(`const part001 = startSketchOn('-XZ')
|> startProfileAt(${startAt}, %)
|> line([${num}, 0], %)`)
|> startProfileAt(${commonPoints.startAt}, %)
|> line([${commonPoints.num1}, 0], %)`)
await page.getByRole('button', { name: 'Tangential Arc' }).click()

Binary file not shown.

Before

Width:  |  Height:  |  Size: 40 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 43 KiB

After

Width:  |  Height:  |  Size: 44 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 95 KiB

After

Width:  |  Height:  |  Size: 120 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 79 KiB

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 111 KiB

After

Width:  |  Height:  |  Size: 94 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 51 KiB

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 52 KiB

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 47 KiB

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 46 KiB

After

Width:  |  Height:  |  Size: 52 KiB

69
make-release.sh Executable file
View File

@ -0,0 +1,69 @@
#!/bin/bash
if ! git diff-index --quiet HEAD --; then
echo "Please stash uncommitted changes before running release script"
exit 1
fi
git checkout main
git pull
git fetch --all
# Get the latest semver tag from git
latest_tag=$(jq -r '.version' package.json)
latest_tag="v$latest_tag"
# Print the latest semver tag
echo "Latest semver tag: $latest_tag"
# Function to bump version numbers
bump_version() {
local version=$1
local bump_type=$2
local major=$(echo $version | cut -d '.' -f 1 | sed 's/v//')
local minor=$(echo $version | cut -d '.' -f 2)
local patch=$(echo $version | cut -d '.' -f 3)
case "$bump_type" in
major)
major=$((major + 1))
minor=0
patch=0
;;
minor)
minor=$((minor + 1))
patch=0
;;
*)
patch=$((patch + 1))
;;
esac
echo "v${major}.${minor}.${patch}"
}
# Determine the type of bump based on the argument
bump_type=${1:-patch}
# Bump the version
new_version=$(bump_version $latest_tag $bump_type)
# Print the new semver tag
echo "New semver tag: $new_version"
new_version_number=${new_version:1}
echo "New version number without 'v': $new_version_number"
git checkout -b "cut-release-$new_version"
echo "$(jq --arg v "$new_version_number" '.version=$v' package.json --indent 2)" > package.json
echo "$(jq --arg v "$new_version_number" '.package.version=$v' src-tauri/tauri.conf.json --indent 2)" > src-tauri/tauri.conf.json
git add package.json src-tauri/tauri.conf.json
git commit -m "Cut release $new_version"
echo ""
echo "Versions has been bumped in relevant json files, a branch has been created and committed to."
echo ""
echo "What's left for you to do is, push the branch and make the release PR."
echo ""

View File

@ -1,6 +1,6 @@
{
"name": "untitled-app",
"version": "0.15.0",
"version": "0.15.2",
"private": true,
"dependencies": {
"@codemirror/autocomplete": "^6.10.2",
@ -34,6 +34,7 @@
"fuse.js": "^7.0.0",
"http-server": "^14.1.1",
"json-rpc-2.0": "^1.6.0",
"node-fetch": "^3.3.2",
"re-resizable": "^6.9.11",
"react": "^18.2.0",
"react-dom": "^18.2.0",
@ -51,7 +52,7 @@
"ts-node": "^10.9.1",
"typescript": "^5.2.2",
"uuid": "^9.0.1",
"vitest": "^0.34.6",
"vitest": "^1.3.1",
"vscode-jsonrpc": "^8.1.0",
"vscode-languageserver-protocol": "^3.17.5",
"wasm-pack": "^0.12.1",
@ -72,7 +73,6 @@
"test": "vitest --mode development",
"test:nowatch": "vitest run --mode development",
"test:rust": "(cd src/wasm-lib && cargo test --all && cargo clippy --all --tests --benches)",
"test:cov": "vitest run --coverage --mode development",
"test:e2e:tauri": "E2E_TAURI_ENABLED=true TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\"}' wdio run wdio.conf.ts",
"simpleserver:ci": "yarn pretest && http-server ./public --cors -p 3000 &",
"simpleserver": "yarn pretest && http-server ./public --cors -p 3000",
@ -85,7 +85,7 @@
"wasm-prep": "rm -rf src/wasm-lib/pkg && mkdir src/wasm-lib/pkg && rm -rf src/wasm-lib/kcl/bindings",
"lint": "eslint --fix src",
"bump-jsons": "echo \"$(jq --arg v \"$VERSION\" '.version=$v' package.json --indent 2)\" > package.json && echo \"$(jq --arg v \"$VERSION\" '.package.version=$v' src-tauri/tauri.conf.json --indent 2)\" > src-tauri/tauri.conf.json",
"postinstall": "patch-package && yarn xstate:typegen",
"postinstall": "yarn xstate:typegen",
"xstate:typegen": "yarn xstate typegen \"src/**/*.ts?(x)\""
},
"prettier": {
@ -113,7 +113,6 @@
"@tauri-apps/cli": "^1.5.6",
"@types/crypto-js": "^4.1.1",
"@types/debounce-promise": "^3.1.8",
"@types/isomorphic-fetch": "^0.0.36",
"@types/pixelmatch": "^5.2.6",
"@types/pngjs": "^6.0.4",
"@types/react-modal": "^3.16.3",
@ -122,8 +121,7 @@
"@types/wait-on": "^5.3.4",
"@types/wicg-file-system-access": "^2020.9.6",
"@types/ws": "^8.5.5",
"@vitejs/plugin-react": "^4.1.1",
"@vitest/coverage-istanbul": "^0.34.6",
"@vitejs/plugin-react": "^4.2.1",
"@wdio/cli": "^8.24.3",
"@wdio/globals": "^8.24.3",
"@wdio/local-runner": "^8.24.3",
@ -136,7 +134,6 @@
"eslint-plugin-css-modules": "^2.12.0",
"happy-dom": "^10.8.0",
"husky": "^8.0.3",
"patch-package": "^8.0.0",
"pixelmatch": "^5.3.0",
"pngjs": "^7.0.0",
"postcss": "^8.4.31",
@ -144,10 +141,10 @@
"prettier": "^2.8.0",
"setimmediate": "^1.0.5",
"tailwindcss": "^3.3.6",
"vite": "^4.5.2",
"vite": "^5.1.3",
"vite-plugin-eslint": "^1.8.1",
"vite-plugin-package-version": "^1.1.0",
"vite-tsconfig-paths": "^4.2.1",
"vite-tsconfig-paths": "^4.3.1",
"vitest-webgl-canvas-mock": "^1.1.0",
"wait-on": "^7.2.0",
"yarn": "^1.22.19"

View File

@ -1,138 +0,0 @@
diff --git a/node_modules/three/examples/jsm/controls/OrbitControls.js b/node_modules/three/examples/jsm/controls/OrbitControls.js
index f29e7fe..0ef636b 100644
--- a/node_modules/three/examples/jsm/controls/OrbitControls.js
+++ b/node_modules/three/examples/jsm/controls/OrbitControls.js
@@ -113,6 +113,25 @@ class OrbitControls extends EventDispatcher {
// public methods
//
+ this.interactionGuards = {
+ pan: {
+ description: 'Right click + Shift + drag or middle click + drag',
+ callback: (e) => e.button === 2 && !e.ctrlKey,
+ },
+ zoom: {
+ description: 'Scroll wheel or Right click + Ctrl + drag',
+ dragCallback: (e) => e.button === 2 && e.ctrlKey,
+ scrollCallback: () => true,
+ },
+ rotate: {
+ description: 'Right click + drag',
+ callback: (e) => e.button === 0,
+ },
+ }
+ this.setMouseGuards = (interactionGuards) => {
+ this.interactionGuards = interactionGuards
+ }
+
this.getPolarAngle = function () {
return spherical.phi;
@@ -1057,92 +1076,21 @@ class OrbitControls extends EventDispatcher {
function onMouseDown( event ) {
- let mouseAction;
-
- switch ( event.button ) {
-
- case 0:
-
- mouseAction = scope.mouseButtons.LEFT;
- break;
-
- case 1:
-
- mouseAction = scope.mouseButtons.MIDDLE;
- break;
-
- case 2:
-
- mouseAction = scope.mouseButtons.RIGHT;
- break;
-
- default:
-
- mouseAction = - 1;
-
- }
-
- switch ( mouseAction ) {
-
- case MOUSE.DOLLY:
-
- if ( scope.enableZoom === false ) return;
-
- handleMouseDownDolly( event );
-
- state = STATE.DOLLY;
-
- break;
-
- case MOUSE.ROTATE:
-
- if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
-
- if ( scope.enablePan === false ) return;
-
- handleMouseDownPan( event );
-
- state = STATE.PAN;
-
- } else {
-
- if ( scope.enableRotate === false ) return;
-
- handleMouseDownRotate( event );
-
- state = STATE.ROTATE;
-
- }
-
- break;
-
- case MOUSE.PAN:
-
- if ( event.ctrlKey || event.metaKey || event.shiftKey ) {
-
- if ( scope.enableRotate === false ) return;
-
- handleMouseDownRotate( event );
-
- state = STATE.ROTATE;
-
- } else {
-
- if ( scope.enablePan === false ) return;
-
- handleMouseDownPan( event );
-
- state = STATE.PAN;
-
- }
-
- break;
-
- default:
-
- state = STATE.NONE;
-
- }
+ if (scope.interactionGuards.pan.callback(event)) {
+ if (scope.enablePan === false) return
+ handleMouseDownPan(event)
+ state = STATE.PAN
+ } else if (scope.interactionGuards.rotate.callback(event)) {
+ if (scope.enableRotate === false) return
+ handleMouseDownRotate(event)
+ state = STATE.ROTATE
+ } else if (scope.interactionGuards.zoom.dragCallback(event)) {
+ if (scope.enableZoom === false) return
+ handleMouseDownDolly(event)
+ state = STATE.DOLLY
+ } else {
+ return
+ }
if ( state !== STATE.NONE ) {

View File

@ -7,7 +7,7 @@
},
"package": {
"productName": "zoo-modeling-app",
"version": "0.15.0"
"version": "0.15.2"
},
"tauri": {
"allowlist": {

View File

@ -35,7 +35,9 @@ import {
settingsMachine,
} from './machines/settingsMachine'
import { ContextFrom } from 'xstate'
import CommandBarProvider from 'components/CommandBar/CommandBar'
import CommandBarProvider, {
CommandBar,
} from 'components/CommandBar/CommandBar'
import { TEST, VITE_KC_SENTRY_DSN } from './env'
import * as Sentry from '@sentry/react'
import ModelingMachineProvider from 'components/ModelingMachineProvider'
@ -117,6 +119,7 @@ const router = createBrowserRouter(
<ModelingMachineProvider>
<Outlet />
<App />
<CommandBar />
</ModelingMachineProvider>
<WasmErrBanner />
</FileMachineProvider>
@ -216,6 +219,7 @@ const router = createBrowserRouter(
<Auth>
<Outlet />
<Home />
<CommandBar />
</Auth>
),
loader: async (): Promise<HomeLoaderData | Response> => {

View File

@ -6,7 +6,12 @@ import { useCommandsContext } from 'hooks/useCommandsContext'
import { ActionButton } from 'components/ActionButton'
import usePlatform from 'hooks/usePlatform'
import { isSingleCursorInPipe } from 'lang/queryAst'
import { kclManager } from 'lang/KclSingleton'
import { kclManager, useKclContext } from 'lang/KclSingleton'
import {
NetworkHealthState,
useNetworkStatus,
} from 'components/NetworkHealthIndicator'
import { useStore } from 'useStore'
export const Toolbar = () => {
const platform = usePlatform()
@ -24,6 +29,13 @@ export const Toolbar = () => {
context.selectionRanges
)
}, [engineCommandManager.artifactMap, context.selectionRanges])
const { overallState } = useNetworkStatus()
const { isExecuting } = useKclContext()
const { isStreamReady } = useStore((s) => ({
isStreamReady: s.isStreamReady,
}))
const disableAllButtons =
overallState !== NetworkHealthState.Ok || isExecuting || !isStreamReady
function handleToolbarButtonsWheelEvent(ev: WheelEvent<HTMLSpanElement>) {
const span = toolbarButtonsRef.current
@ -60,6 +72,7 @@ export const Toolbar = () => {
icon: 'sketch',
bgClassName,
}}
disabled={disableAllButtons}
>
<span data-testid="start-sketch">Start Sketch</span>
</ActionButton>
@ -74,6 +87,7 @@ export const Toolbar = () => {
icon: 'sketch',
bgClassName,
}}
disabled={disableAllButtons}
>
Edit Sketch
</ActionButton>
@ -88,6 +102,7 @@ export const Toolbar = () => {
icon: 'arrowLeft',
bgClassName,
}}
disabled={disableAllButtons}
>
Exit Sketch
</ActionButton>
@ -109,6 +124,7 @@ export const Toolbar = () => {
icon: 'line',
bgClassName,
}}
disabled={disableAllButtons}
>
Line
</ActionButton>
@ -124,12 +140,13 @@ export const Toolbar = () => {
aria-pressed={state.matches('Sketch.Tangential arc to')}
className="pressed:bg-energy-10/20 dark:pressed:bg-energy-80"
icon={{
icon: 'line',
icon: 'arc',
bgClassName,
}}
disabled={
!state.can('Equip tangential arc to') &&
!state.matches('Sketch.Tangential arc to')
(!state.can('Equip tangential arc to') &&
!state.matches('Sketch.Tangential arc to')) ||
disableAllButtons
}
>
Tangential Arc
@ -169,7 +186,7 @@ export const Toolbar = () => {
disabled={
!state.nextEvents
.filter((event) => state.can(event as any))
.includes(eventName)
.includes(eventName) || disableAllButtons
}
title={eventName}
icon={{
@ -194,7 +211,7 @@ export const Toolbar = () => {
data: { name: 'Extrude', ownerMachine: 'modeling' },
})
}
disabled={!state.can('Extrude')}
disabled={!state.can('Extrude') || disableAllButtons}
title={
state.can('Extrude')
? 'extrude'

View File

@ -0,0 +1,879 @@
import { MouseGuard } from 'lib/cameraControls'
import {
Euler,
MathUtils,
Matrix4,
OrthographicCamera,
PerspectiveCamera,
Quaternion,
Spherical,
Vector2,
Vector3,
} from 'three'
import {
DEBUG_SHOW_INTERSECTION_PLANE,
INTERSECTION_PLANE_LAYER,
SKETCH_LAYER,
ZOOM_MAGIC_NUMBER,
} from './sceneInfra'
import { EngineCommand, engineCommandManager } from 'lang/std/engineConnection'
import { v4 as uuidv4 } from 'uuid'
import { deg2Rad } from 'lib/utils2d'
import { isReducedMotion, roundOff, throttle } from 'lib/utils'
import * as TWEEN from '@tweenjs/tween.js'
import { isQuaternionVertical } from './helpers'
const ORTHOGRAPHIC_CAMERA_SIZE = 20
const FRAMES_TO_ANIMATE_IN = 30
const tempQuaternion = new Quaternion() // just used for maths
interface ThreeCamValues {
position: Vector3
quaternion: Quaternion
zoom: number
isPerspective: boolean
target: Vector3
}
export type ReactCameraProperties =
| {
type: 'perspective'
fov?: number
position: [number, number, number]
quaternion: [number, number, number, number]
}
| {
type: 'orthographic'
zoom?: number
position: [number, number, number]
quaternion: [number, number, number, number]
}
const lastCmdDelay = 50
const throttledUpdateEngineCamera = throttle((threeValues: ThreeCamValues) => {
const cmd: EngineCommand = {
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
...convertThreeCamValuesToEngineCam(threeValues),
},
}
engineCommandManager.sendSceneCommand(cmd)
}, 1000 / 15)
let lastPerspectiveCmd: EngineCommand | null = null
let lastPerspectiveCmdTime: number = Date.now()
let lastPerspectiveCmdTimeoutId: number | null = null
const sendLastPerspectiveReliableChannel = () => {
if (
lastPerspectiveCmd &&
Date.now() - lastPerspectiveCmdTime >= lastCmdDelay
) {
engineCommandManager.sendSceneCommand(lastPerspectiveCmd, true)
lastPerspectiveCmdTime = Date.now()
}
}
const throttledUpdateEngineFov = throttle(
(vals: {
position: Vector3
quaternion: Quaternion
zoom: number
fov: number
target: Vector3
}) => {
const cmd: EngineCommand = {
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_perspective_settings',
...convertThreeCamValuesToEngineCam({
...vals,
isPerspective: true,
}),
fov_y: vals.fov,
...calculateNearFarFromFOV(vals.fov),
},
}
engineCommandManager.sendSceneCommand(cmd)
lastPerspectiveCmd = cmd
lastPerspectiveCmdTime = Date.now()
if (lastPerspectiveCmdTimeoutId !== null) {
clearTimeout(lastPerspectiveCmdTimeoutId)
}
lastPerspectiveCmdTimeoutId = setTimeout(
sendLastPerspectiveReliableChannel,
lastCmdDelay
) as any as number
},
1000 / 15
)
export class CameraControls {
camera: PerspectiveCamera | OrthographicCamera
target: Vector3
domElement: HTMLCanvasElement
isDragging: boolean
mouseDownPosition: Vector2
mouseNewPosition: Vector2
rotationSpeed = 0.3
enableRotate = true
enablePan = true
enableZoom = true
lastPerspectiveFov: number = 45
pendingZoom: number | null = null
pendingRotation: Vector2 | null = null
pendingPan: Vector2 | null = null
interactionGuards: MouseGuard = {
pan: {
description: 'Right click + Shift + drag or middle click + drag',
callback: (e) => !!(e.buttons & 4) && !e.ctrlKey,
},
zoom: {
description: 'Scroll wheel or Right click + Ctrl + drag',
dragCallback: (e) => e.button === 2 && e.ctrlKey,
scrollCallback: () => true,
},
rotate: {
description: 'Right click + drag',
callback: (e) => {
console.log('event', e)
return !!(e.buttons & 2)
},
},
}
isFovAnimationInProgress = false
fovBeforeOrtho = 45
get isPerspective() {
return this.camera instanceof PerspectiveCamera
}
// reacts hooks into some of this singleton's properties
reactCameraProperties: ReactCameraProperties = {
type: 'perspective',
fov: 12,
position: [0, 0, 0],
quaternion: [0, 0, 0, 1],
}
setCam = (camProps: ReactCameraProperties) => {
if (
camProps.type === 'perspective' &&
this.camera instanceof OrthographicCamera
) {
this.usePerspectiveCamera()
} else if (
camProps.type === 'orthographic' &&
this.camera instanceof PerspectiveCamera
) {
this.useOrthographicCamera()
}
this.camera.position.set(...camProps.position)
this.camera.quaternion.set(...camProps.quaternion)
if (
camProps.type === 'perspective' &&
this.camera instanceof PerspectiveCamera
) {
// not sure what to do here, calling dollyZoom here is buggy because it updates the position
// at the same time
} else if (
camProps.type === 'orthographic' &&
this.camera instanceof OrthographicCamera
) {
this.camera.zoom = camProps.zoom || 1
}
this.camera.updateProjectionMatrix()
this.update(true)
}
constructor(isOrtho = false, domElement: HTMLCanvasElement) {
this.camera = isOrtho ? new OrthographicCamera() : new PerspectiveCamera()
this.camera.up.set(0, 0, 1)
this.camera.far = 20000
this.target = new Vector3()
this.domElement = domElement
this.isDragging = false
this.mouseDownPosition = new Vector2()
this.mouseNewPosition = new Vector2()
this.domElement.addEventListener('pointerdown', this.onMouseDown)
this.domElement.addEventListener('pointermove', this.onMouseMove)
this.domElement.addEventListener('pointerup', this.onMouseUp)
this.domElement.addEventListener('wheel', this.onMouseWheel)
window.addEventListener('resize', this.onWindowResize)
this.onWindowResize()
this.update()
}
private _isCamMovingCallback: (isMoving: boolean, isTween: boolean) => void =
() => {}
setIsCamMovingCallback(cb: (isMoving: boolean, isTween: boolean) => void) {
this._isCamMovingCallback = cb
}
private _camChangeCallbacks: { [key: string]: () => void } = {}
subscribeToCamChange(cb: () => void) {
const cbId = uuidv4()
this._camChangeCallbacks[cbId] = cb
const unsubscribe = () => {
delete this._camChangeCallbacks[cbId]
}
return unsubscribe
}
onWindowResize = () => {
if (this.camera instanceof PerspectiveCamera) {
this.camera.aspect = window.innerWidth / window.innerHeight
} else if (this.camera instanceof OrthographicCamera) {
const aspect = window.innerWidth / window.innerHeight
this.camera.left = -ORTHOGRAPHIC_CAMERA_SIZE * aspect
this.camera.right = ORTHOGRAPHIC_CAMERA_SIZE * aspect
this.camera.top = ORTHOGRAPHIC_CAMERA_SIZE
this.camera.bottom = -ORTHOGRAPHIC_CAMERA_SIZE
}
this.camera.updateProjectionMatrix()
}
onMouseDown = (event: MouseEvent) => {
this.isDragging = true
this.mouseDownPosition.set(event.clientX, event.clientY)
}
onMouseMove = (event: MouseEvent) => {
if (this.isDragging) {
this.mouseNewPosition.set(event.clientX, event.clientY)
const deltaMove = this.mouseNewPosition
.clone()
.sub(this.mouseDownPosition)
this.mouseDownPosition.copy(this.mouseNewPosition)
let state: 'pan' | 'rotate' | 'zoom' = 'pan'
if (this.interactionGuards.pan.callback(event as any)) {
if (this.enablePan === false) return
// handleMouseDownPan(event)
state = 'pan'
} else if (this.interactionGuards.rotate.callback(event as any)) {
if (this.enableRotate === false) return
// handleMouseDownRotate(event)
state = 'rotate'
} else if (this.interactionGuards.zoom.dragCallback(event as any)) {
if (this.enableZoom === false) return
// handleMouseDownDolly(event)
state = 'zoom'
} else {
return
}
// Implement camera movement logic here based on deltaMove
// For example, for rotating the camera around the target:
if (state === 'rotate') {
this.pendingRotation = this.pendingRotation
? this.pendingRotation
: new Vector2()
this.pendingRotation.x += deltaMove.x
this.pendingRotation.y += deltaMove.y
} else if (state === 'zoom') {
this.pendingZoom = this.pendingZoom ? this.pendingZoom : 1
this.pendingZoom *= 1 + deltaMove.y * 0.01
} else if (state === 'pan') {
this.pendingPan = this.pendingPan ? this.pendingPan : new Vector2()
let distance = this.camera.position.distanceTo(this.target)
if (this.camera instanceof OrthographicCamera) {
const zoomFudgeFactor = 2280
distance = zoomFudgeFactor / (this.camera.zoom * 45)
}
const panSpeed = (distance / 1000 / 45) * this.fovBeforeOrtho
this.pendingPan.x += -deltaMove.x * panSpeed
this.pendingPan.y += deltaMove.y * panSpeed
}
}
}
onMouseUp = (event: MouseEvent) => {
this.isDragging = false
}
onMouseWheel = (event: WheelEvent) => {
// Assume trackpad if the deltas are small and integers
const isTrackpad = Math.abs(event.deltaY) <= 1 || event.deltaY % 1 === 0
const zoomSpeed = isTrackpad ? 0.02 : 0.1 // Reduced zoom speed for trackpad
this.pendingZoom = this.pendingZoom ? this.pendingZoom : 1
this.pendingZoom *= 1 + (event.deltaY > 0 ? zoomSpeed : -zoomSpeed)
}
useOrthographicCamera = () => {
if (this.camera instanceof OrthographicCamera) return
const { x: px, y: py, z: pz } = this.camera.position
const { x: qx, y: qy, z: qz, w: qw } = this.camera.quaternion
const aspect = window.innerWidth / window.innerHeight
this.lastPerspectiveFov = this.camera.fov
const { z_near, z_far } = calculateNearFarFromFOV(this.lastPerspectiveFov)
this.camera = new OrthographicCamera(
-ORTHOGRAPHIC_CAMERA_SIZE * aspect,
ORTHOGRAPHIC_CAMERA_SIZE * aspect,
ORTHOGRAPHIC_CAMERA_SIZE,
-ORTHOGRAPHIC_CAMERA_SIZE,
z_near,
z_far
)
this.camera.up.set(0, 0, 1)
this.camera.layers.enable(SKETCH_LAYER)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camera.layers.enable(INTERSECTION_PLANE_LAYER)
this.camera.position.set(px, py, pz)
const distance = this.camera.position.distanceTo(this.target.clone())
const fovFactor = 45 / this.lastPerspectiveFov
this.camera.zoom = (ZOOM_MAGIC_NUMBER * fovFactor * 0.8) / distance
this.camera.quaternion.set(qx, qy, qz, qw)
this.camera.updateProjectionMatrix()
engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_orthographic',
},
})
this.onCameraChange()
}
private createPerspectiveCamera = () => {
const { z_near, z_far } = calculateNearFarFromFOV(this.lastPerspectiveFov)
this.camera = new PerspectiveCamera(
this.lastPerspectiveFov,
window.innerWidth / window.innerHeight,
z_near,
z_far
)
this.camera.up.set(0, 0, 1)
this.camera.layers.enable(SKETCH_LAYER)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camera.layers.enable(INTERSECTION_PLANE_LAYER)
return this.camera
}
usePerspectiveCamera = () => {
const { x: px, y: py, z: pz } = this.camera.position
const { x: qx, y: qy, z: qz, w: qw } = this.camera.quaternion
const zoom = this.camera.zoom
this.camera = this.createPerspectiveCamera()
this.camera.position.set(px, py, pz)
this.camera.quaternion.set(qx, qy, qz, qw)
const zoomFudgeFactor = 2280
const distance = zoomFudgeFactor / (zoom * this.lastPerspectiveFov)
const direction = new Vector3().subVectors(
this.camera.position,
this.target
)
direction.normalize()
this.camera.position.copy(this.target).addScaledVector(direction, distance)
engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_perspective',
parameters: {
fov_y: this.camera.fov,
...calculateNearFarFromFOV(this.lastPerspectiveFov),
},
},
})
this.onCameraChange()
this.update()
return this.camera
}
dollyZoom = (newFov: number) => {
if (!(this.camera instanceof PerspectiveCamera)) {
console.warn('Dolly zoom is only applicable to perspective cameras.')
return
}
this.lastPerspectiveFov = newFov
// Calculate the direction vector from the camera towards the controls target
const direction = new Vector3()
.subVectors(this.target, this.camera.position)
.normalize()
// Calculate the distance to the controls target before changing the FOV
const distanceBefore = this.camera.position.distanceTo(this.target)
// Calculate the scale factor for the new FOV compared to the old one
// This needs to be calculated before updating the camera's FOV
const oldFov = this.camera.fov
const viewHeightFactor = (fov: number) => {
/* *
/|
/ |
/ |
/ |
/ | viewHeight/2
/ |
/ |
/↙fov/2 |
/________|
\ |
\._._._.|
*/
return Math.tan(deg2Rad(fov / 2))
}
const scaleFactor = viewHeightFactor(oldFov) / viewHeightFactor(newFov)
this.camera.fov = newFov
this.camera.updateProjectionMatrix()
const distanceAfter = distanceBefore * scaleFactor
const newPosition = this.target
.clone()
.add(direction.multiplyScalar(-distanceAfter))
this.camera.position.copy(newPosition)
const { z_near, z_far } = calculateNearFarFromFOV(this.lastPerspectiveFov)
this.camera.near = z_near
this.camera.far = z_far
throttledUpdateEngineFov({
fov: newFov,
position: newPosition,
quaternion: this.camera.quaternion,
zoom: this.camera.zoom,
target: this.target,
})
}
update = (forceUpdate = false) => {
// If there are any changes that need to be applied to the camera, apply them here.
let didChange = forceUpdate
if (this.pendingRotation) {
this.rotateCamera(this.pendingRotation.x, this.pendingRotation.y)
this.pendingRotation = null // Clear the pending rotation after applying it
didChange = true
}
if (this.pendingZoom) {
if (this.camera instanceof PerspectiveCamera) {
// move camera towards or away from the target
const distance = this.camera.position.distanceTo(this.target)
const newDistance = distance * this.pendingZoom
const direction = this.camera.position
.clone()
.sub(this.target)
.normalize()
const newPosition = this.target
.clone()
.add(direction.multiplyScalar(newDistance))
this.camera.position.copy(newPosition)
this.camera.updateProjectionMatrix()
this.pendingZoom = null // Clear the pending zoom after applying it
} else {
// TODO change ortho zoom
this.camera.zoom = this.camera.zoom / this.pendingZoom
this.pendingZoom = null
}
didChange = true
}
if (this.pendingPan) {
// move camera left/right and up/down
const offset = this.camera.position.clone().sub(this.target)
const direction = offset.clone().normalize()
const cameraQuaternion = this.camera.quaternion
const up = new Vector3(0, 1, 0).applyQuaternion(cameraQuaternion)
const right = new Vector3().crossVectors(up, direction)
right.multiplyScalar(this.pendingPan.x)
up.multiplyScalar(this.pendingPan.y)
const newPosition = this.camera.position.clone().add(right).add(up)
this.target.add(right)
this.target.add(up)
this.camera.position.copy(newPosition)
this.pendingPan = null
didChange = true
}
this.safeLookAtTarget()
// Update the camera's matrices
this.camera.updateMatrixWorld()
if (didChange) {
this.onCameraChange()
}
// damping would be implemented here in update if we choose to add it.
}
rotateCamera = (deltaX: number, deltaY: number) => {
const quat = new Quaternion().setFromUnitVectors(
new Vector3(0, 0, 1),
new Vector3(0, 1, 0)
)
const quatInverse = quat.clone().invert()
const angleX = deltaX * this.rotationSpeed // rotationSpeed is a constant that defines how fast the camera rotates
const angleY = deltaY * this.rotationSpeed
// Convert angles to radians
const radianX = MathUtils.degToRad(angleX)
const radianY = MathUtils.degToRad(angleY)
// Get the offset from the camera to the target
const offset = new Vector3().subVectors(this.camera.position, this.target)
// spherical is a y-up paradigm, need to conform to that for now
offset.applyQuaternion(quat)
// Convert offset to spherical coordinates
const spherical = new Spherical().setFromVector3(offset)
// Apply the rotations
spherical.theta -= radianX
spherical.phi -= radianY
// Restrict the phi angle to avoid the camera flipping at the poles
spherical.phi = Math.max(0.1, Math.min(Math.PI - 0.1, spherical.phi))
// Convert back to Cartesian coordinates
offset.setFromSpherical(spherical)
// put the offset back into the z-up paradigm
offset.applyQuaternion(quatInverse)
// Update the camera's position
this.camera.position.copy(this.target).add(offset)
// Look at the target
this.camera.updateMatrixWorld()
}
safeLookAtTarget(up = new Vector3(0, 0, 1)) {
const quaternion = _lookAt(this.camera.position, this.target, up)
this.camera.quaternion.copy(quaternion)
this.camera.updateMatrixWorld()
}
tweenCamToNegYAxis(
// -90 degrees from the x axis puts the camera on the negative y axis
targetAngle = -Math.PI / 2,
duration = 500
): Promise<void> {
// should tween the camera so that it has an xPosition of 0, and forcing it's yPosition to be negative
// zPosition should stay the same
const xyRadius = Math.sqrt(
(this.target.x - this.camera.position.x) ** 2 +
(this.target.y - this.camera.position.y) ** 2
)
const xyAngle = Math.atan2(
this.camera.position.y - this.target.y,
this.camera.position.x - this.target.x
)
this._isCamMovingCallback(true, true)
return new Promise((resolve) => {
new TWEEN.Tween({ angle: xyAngle })
.to({ angle: targetAngle }, duration)
.onUpdate((obj) => {
const x = xyRadius * Math.cos(obj.angle)
const y = xyRadius * Math.sin(obj.angle)
this.camera.position.set(
this.target.x + x,
this.target.y + y,
this.camera.position.z
)
this.update()
this.onCameraChange()
})
.onComplete((obj) => {
const x = xyRadius * Math.cos(obj.angle)
const y = xyRadius * Math.sin(obj.angle)
this.camera.position.set(
this.target.x + x,
this.target.y + y,
this.camera.position.z
)
this.update()
this.onCameraChange()
this._isCamMovingCallback(false, true)
// resolve after a couple of frames
requestAnimationFrame(() => {
requestAnimationFrame(() => resolve())
})
})
.start()
})
}
async tweenCameraToQuaternion(
targetQuaternion: Quaternion,
duration = 500,
toOrthographic = true
): Promise<void> {
const isVertical = isQuaternionVertical(targetQuaternion)
let remainingDuration = duration
if (isVertical) {
remainingDuration = duration * 0.5
const orbitRotationDuration = duration * 0.65
let targetAngle = -Math.PI / 2
const v = new Vector3(0, 0, 1).applyQuaternion(targetQuaternion)
if (v.z < 0) targetAngle = Math.PI / 2
await this.tweenCamToNegYAxis(targetAngle, orbitRotationDuration)
}
await this._tweenCameraToQuaternion(
targetQuaternion,
remainingDuration,
toOrthographic
)
}
_tweenCameraToQuaternion(
targetQuaternion: Quaternion,
duration = 500,
toOrthographic = false
): Promise<void> {
return new Promise((resolve) => {
const camera = this.camera
this._isCamMovingCallback(true, true)
const initialQuaternion = camera.quaternion.clone()
const isVertical = isQuaternionVertical(targetQuaternion)
let tweenEnd = isVertical ? 0.99 : 1
const controlsTarget = this.target.clone()
const initialDistance = controlsTarget.distanceTo(camera.position.clone())
const cameraAtTime = (animationProgress: number /* 0 - 1 */) => {
const currentQ = tempQuaternion.slerpQuaternions(
initialQuaternion,
targetQuaternion,
animationProgress
)
if (this.camera instanceof PerspectiveCamera)
// changing the camera position back when it's orthographic doesn't do anything
// and it messes up animating back to perspective later
this.camera.position
.set(0, 0, 1)
.applyQuaternion(currentQ)
.multiplyScalar(initialDistance)
.add(controlsTarget)
this.camera.up.set(0, 1, 0).applyQuaternion(currentQ).normalize()
this.camera.quaternion.copy(currentQ)
this.target.copy(controlsTarget)
// this.controls.update()
this.camera.updateProjectionMatrix()
this.update()
this.onCameraChange()
}
const onComplete = async () => {
if (isReducedMotion() && toOrthographic) {
cameraAtTime(0.99)
this.useOrthographicCamera()
} else if (toOrthographic) {
await this.animateToOrthographic()
}
this.enableRotate = false
this._isCamMovingCallback(false, true)
resolve()
}
if (isReducedMotion()) {
onComplete()
return
}
new TWEEN.Tween({ t: 0 })
.to({ t: tweenEnd }, duration)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(({ t }) => cameraAtTime(t))
.onComplete(onComplete)
.start()
})
}
animateToOrthographic = () =>
new Promise((resolve) => {
this.isFovAnimationInProgress = true
let currentFov = this.lastPerspectiveFov
this.fovBeforeOrtho = currentFov
const targetFov = 4
const fovAnimationStep = (currentFov - targetFov) / FRAMES_TO_ANIMATE_IN
let frameWaitOnFinish = 10
const animateFovChange = () => {
if (this.camera instanceof PerspectiveCamera) {
if (this.camera.fov > targetFov) {
// Decrease the FOV
currentFov = Math.max(currentFov - fovAnimationStep, targetFov)
this.camera.updateProjectionMatrix()
this.dollyZoom(currentFov)
requestAnimationFrame(animateFovChange) // Continue the animation
} else if (frameWaitOnFinish > 0) {
frameWaitOnFinish--
requestAnimationFrame(animateFovChange) // Continue the animation
} else {
// Once the target FOV is reached, switch to the orthographic camera
// Needs to wait a couple frames after the FOV animation is complete
this.useOrthographicCamera()
this.isFovAnimationInProgress = false
resolve(true)
}
}
}
animateFovChange() // Start the animation
})
animateToPerspective = () =>
new Promise((resolve) => {
this.isFovAnimationInProgress = true
// Immediately set the camera to perspective with a very low FOV
const targetFov = this.fovBeforeOrtho // Target FOV for perspective
this.lastPerspectiveFov = 4
let currentFov = 4
this.camera.updateProjectionMatrix()
const fovAnimationStep = (targetFov - currentFov) / FRAMES_TO_ANIMATE_IN
this.usePerspectiveCamera()
const animateFovChange = () => {
if (this.camera instanceof OrthographicCamera) return
if (this.camera.fov < targetFov) {
// Increase the FOV
currentFov = Math.min(currentFov + fovAnimationStep, targetFov)
// this.camera.fov = currentFov
this.camera.updateProjectionMatrix()
this.dollyZoom(currentFov)
requestAnimationFrame(animateFovChange) // Continue the animation
} else {
// Set the flag to false as the FOV animation is complete
this.isFovAnimationInProgress = false
resolve(true)
}
}
animateFovChange() // Start the animation
})
reactCameraPropertiesCallback: (a: ReactCameraProperties) => void = () => {}
setReactCameraPropertiesCallback = (
cb: (a: ReactCameraProperties) => void
) => {
this.reactCameraPropertiesCallback = cb
}
deferReactUpdate = throttle((a: ReactCameraProperties) => {
this.reactCameraPropertiesCallback(a)
}, 200)
onCameraChange = () => {
const distance = this.target.distanceTo(this.camera.position)
if (this.camera.far / 2.1 < distance || this.camera.far / 1.9 > distance) {
this.camera.far = distance * 2
this.camera.near = distance / 10
this.camera.updateProjectionMatrix()
}
throttledUpdateEngineCamera({
quaternion: this.camera.quaternion,
position: this.camera.position,
zoom: this.camera.zoom,
isPerspective: this.isPerspective,
target: this.target,
})
this.deferReactUpdate({
type: this.isPerspective ? 'perspective' : 'orthographic',
[this.isPerspective ? 'fov' : 'zoom']:
this.camera instanceof PerspectiveCamera
? this.camera.fov
: this.camera.zoom,
position: [
roundOff(this.camera.position.x, 2),
roundOff(this.camera.position.y, 2),
roundOff(this.camera.position.z, 2),
],
quaternion: [
roundOff(this.camera.quaternion.x, 2),
roundOff(this.camera.quaternion.y, 2),
roundOff(this.camera.quaternion.z, 2),
roundOff(this.camera.quaternion.w, 2),
],
})
Object.values(this._camChangeCallbacks).forEach((cb) => cb())
}
}
// currently duplicated, delete one
function calculateNearFarFromFOV(fov: number) {
const nearFarRatio = (fov - 3) / (45 - 3)
// const z_near = 0.1 + nearFarRatio * (5 - 0.1)
const z_far = 1000 + nearFarRatio * (100000 - 1000)
return { z_near: 0.1, z_far }
}
// currently duplicated, delete one
function convertThreeCamValuesToEngineCam({
target,
position,
quaternion,
zoom,
isPerspective,
}: ThreeCamValues): {
center: Vector3
up: Vector3
vantage: Vector3
} {
// Something to consider is that the orbit controls have a target,
// we're kind of deriving the target/lookAtVector here when it might not be needed
// leaving for now since it's working but maybe revisit later
const euler = new Euler().setFromQuaternion(quaternion, 'XYZ')
const lookAtVector = new Vector3(0, 0, -1)
.applyEuler(euler)
.normalize()
.add(position)
const upVector = new Vector3(0, 1, 0).applyEuler(euler).normalize()
if (isPerspective) {
return {
center: target,
up: upVector,
vantage: position,
}
}
const fudgeFactor2 = zoom * 0.9979224466814468 - 0.03473692325839295
const zoomFactor = (-ZOOM_MAGIC_NUMBER + fudgeFactor2) / zoom
const direction = lookAtVector.clone().sub(position).normalize()
const newVantage = position.clone().add(direction.multiplyScalar(zoomFactor))
return {
center: lookAtVector,
up: upVector,
vantage: newVantage,
}
}
// Pure function helpers
function _lookAt(position: Vector3, target: Vector3, up: Vector3): Quaternion {
// Direction from position to target, normalized.
let direction = new Vector3().subVectors(target, position).normalize()
// Calculate a new "effective" up vector that is orthogonal to the direction.
// This step ensures that the up vector does not affect the direction the camera is looking.
let right = new Vector3().crossVectors(direction, up).normalize()
let orthogonalUp = new Vector3().crossVectors(right, direction).normalize()
// Create a lookAt matrix using the position, and the recalculated orthogonal up vector.
let lookAtMatrix = new Matrix4()
lookAtMatrix.lookAt(position, target, orthogonalUp)
// Create a quaternion from the lookAt matrix.
let quaternion = new Quaternion().setFromRotationMatrix(lookAtMatrix)
return quaternion
}

View File

@ -4,11 +4,8 @@ import { useModelingContext } from 'hooks/useModelingContext'
import { cameraMouseDragGuards } from 'lib/cameraControls'
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
import { useStore } from 'useStore'
import {
DEBUG_SHOW_BOTH_SCENES,
ReactCameraProperties,
sceneInfra,
} from './sceneInfra'
import { DEBUG_SHOW_BOTH_SCENES, sceneInfra } from './sceneInfra'
import { ReactCameraProperties } from './CameraControls'
import { throttle } from 'lib/utils'
function useShouldHideScene(): { hideClient: boolean; hideServer: boolean } {
@ -18,7 +15,7 @@ function useShouldHideScene(): { hideClient: boolean; hideServer: boolean } {
const { state } = useModelingContext()
useEffect(() => {
sceneInfra.setIsCamMovingCallback((isMoving, isTween) => {
sceneInfra.camControls.setIsCamMovingCallback((isMoving, isTween) => {
setIsCamMoving(isMoving)
setIsTween(isTween)
})
@ -52,7 +49,8 @@ export const ClientSideScene = ({
// Listen for changes to the camera controls setting
// and update the client-side scene's controls accordingly.
useEffect(() => {
sceneInfra.setInteractionGuards(cameraMouseDragGuards[cameraControls])
sceneInfra.camControls.interactionGuards =
cameraMouseDragGuards[cameraControls]
}, [cameraControls])
useEffect(() => {
sceneInfra.updateOtherSelectionColors(
@ -93,7 +91,7 @@ export const ClientSideScene = ({
const throttled = throttle((a: ReactCameraProperties) => {
if (a.type === 'perspective' && a.fov) {
sceneInfra.dollyZoom(a.fov)
sceneInfra.camControls.dollyZoom(a.fov)
}
}, 1000 / 15)
@ -107,7 +105,7 @@ export const CamDebugSettings = () => {
const [fov, setFov] = useState(12)
useEffect(() => {
sceneInfra.setReactCameraPropertiesCallback(setCamSettings)
sceneInfra.camControls.setReactCameraPropertiesCallback(setCamSettings)
}, [sceneInfra])
useEffect(() => {
if (camSettings.type === 'perspective' && camSettings.fov) {
@ -124,9 +122,9 @@ export const CamDebugSettings = () => {
checked={camSettings.type === 'perspective'}
onChange={(e) => {
if (camSettings.type === 'perspective') {
sceneInfra.useOrthographicCamera()
sceneInfra.camControls.useOrthographicCamera()
} else {
sceneInfra.usePerspectiveCamera()
sceneInfra.camControls.usePerspectiveCamera()
}
}}
/>
@ -156,7 +154,7 @@ export const CamDebugSettings = () => {
value={camSettings.fov}
className="text-black w-16"
onChange={(e) => {
sceneInfra.setCam({
sceneInfra.camControls.setCam({
...camSettings,
fov: parseFloat(e.target.value),
})
@ -173,7 +171,7 @@ export const CamDebugSettings = () => {
value={camSettings.zoom}
className="text-black w-16"
onChange={(e) => {
sceneInfra.setCam({
sceneInfra.camControls.setCam({
...camSettings,
zoom: parseFloat(e.target.value),
})
@ -194,7 +192,7 @@ export const CamDebugSettings = () => {
value={camSettings.position[0]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.setCam({
sceneInfra.camControls.setCam({
...camSettings,
position: [
parseFloat(e.target.value),
@ -214,7 +212,7 @@ export const CamDebugSettings = () => {
value={camSettings.position[1]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.setCam({
sceneInfra.camControls.setCam({
...camSettings,
position: [
camSettings.position[0],
@ -234,7 +232,7 @@ export const CamDebugSettings = () => {
value={camSettings.position[2]}
className="text-black w-16"
onChange={(e) => {
sceneInfra.setCam({
sceneInfra.camControls.setCam({
...camSettings,
position: [
camSettings.position[0],

View File

@ -1,5 +1,5 @@
import { Quaternion } from 'three'
import { isQuaternionVertical } from './sceneInfra'
import { isQuaternionVertical } from './helpers'
describe('isQuaternionVertical', () => {
it('should identify vertical quaternions', () => {

View File

@ -1,3 +1,4 @@
import { compareVec2Epsilon2 } from 'lang/std/sketch'
import {
GridHelper,
LineBasicMaterial,
@ -5,6 +6,8 @@ import {
PerspectiveCamera,
Group,
Mesh,
Quaternion,
Vector3,
} from 'three'
export function createGridHelper({
@ -31,3 +34,9 @@ export const orthoScale = (cam: OrthographicCamera | PerspectiveCamera) =>
export const perspScale = (cam: PerspectiveCamera, group: Group | Mesh) =>
(group.position.distanceTo(cam.position) * cam.fov) / 4000
export function isQuaternionVertical(q: Quaternion) {
const v = new Vector3(0, 0, 1).applyQuaternion(q)
// no x or y components means it's vertical
return compareVec2Epsilon2([v.x, v.y], [0, 0])
}

View File

@ -13,6 +13,7 @@ import {
Quaternion,
Scene,
Shape,
SphereGeometry,
Vector2,
Vector3,
} from 'three'
@ -24,7 +25,6 @@ import {
defaultPlaneColor,
getSceneScale,
INTERSECTION_PLANE_LAYER,
isQuaternionVertical,
RAYCASTABLE_PLANE,
sceneInfra,
SKETCH_GROUP_SEGMENTS,
@ -34,6 +34,7 @@ import {
Y_AXIS,
YZ_PLANE,
} from './sceneInfra'
import { isQuaternionVertical } from './helpers'
import {
CallExpression,
getTangentialArcToInfo,
@ -85,6 +86,7 @@ export const TANGENTIAL_ARC_TO_SEGMENT = 'tangential-arc-to-segment'
export const TANGENTIAL_ARC_TO_SEGMENT_BODY = 'tangential-arc-to-segment-body'
export const TANGENTIAL_ARC_TO__SEGMENT_DASH =
'tangential-arc-to-segment-body-dashed'
export const EXTRA_SEGMENT_HANDLE = 'extraSegmentHandle'
// This singleton Class is responsible for all of the things the user sees and interacts with.
// That mostly mean sketch elements.
@ -98,17 +100,17 @@ class SceneEntities {
currentSketchQuaternion: Quaternion | null = null
constructor() {
this.scene = sceneInfra?.scene
sceneInfra?.setOnCamChange(this.onCamChange)
sceneInfra?.camControls.subscribeToCamChange(this.onCamChange)
}
onCamChange = () => {
const orthoFactor = orthoScale(sceneInfra.camera)
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
Object.values(this.activeSegments).forEach((segment) => {
const factor =
sceneInfra.camera instanceof OrthographicCamera
sceneInfra.camControls.camera instanceof OrthographicCamera
? orthoFactor
: perspScale(sceneInfra.camera, segment)
: perspScale(sceneInfra.camControls.camera, segment)
if (
segment.userData.from &&
segment.userData.to &&
@ -139,9 +141,9 @@ class SceneEntities {
})
if (this.axisGroup) {
const factor =
sceneInfra.camera instanceof OrthographicCamera
sceneInfra.camControls.camera instanceof OrthographicCamera
? orthoFactor
: perspScale(sceneInfra.camera, this.axisGroup)
: perspScale(sceneInfra.camControls.camera, this.axisGroup)
const x = this.axisGroup.getObjectByName(X_AXIS)
x?.scale.set(1, factor, 1)
const y = this.axisGroup.getObjectByName(Y_AXIS)
@ -150,7 +152,12 @@ class SceneEntities {
}
createIntersectionPlane() {
const planeGeometry = new PlaneGeometry(100000, 100000)
if (sceneInfra.scene.getObjectByName(RAYCASTABLE_PLANE)) {
console.warn('createIntersectionPlane called when it already exists')
return
}
const hundredM = 1000000
const planeGeometry = new PlaneGeometry(hundredM, hundredM)
const planeMaterial = new MeshBasicMaterial({
color: 0xff0000,
side: DoubleSide,
@ -195,11 +202,12 @@ class SceneEntities {
this.axisGroup = new Group()
const gridHelper = createGridHelper({ size: 100, divisions: 10 })
gridHelper.position.z = -0.01
gridHelper.renderOrder = -3 // is this working?
gridHelper.name = 'gridHelper'
const sceneScale = getSceneScale(
sceneInfra.camera,
sceneInfra.controls.target
sceneInfra.camControls.camera,
sceneInfra.camControls.target
)
gridHelper.scale.set(sceneScale, sceneScale, sceneScale)
this.axisGroup.add(xAxisMesh, yAxisMesh, gridHelper)
@ -233,21 +241,17 @@ class SceneEntities {
ast,
// is draft line assumes the last segment is a draft line, and mods it as the user moves the mouse
draftSegment,
skipListeners,
}: {
sketchPathToNode: PathToNode
ast?: Program
draftSegment?: DraftSegment
skipListeners?: boolean
}) {
this.createIntersectionPlane()
const distance = sceneInfra.controls.target.distanceTo(
sceneInfra.camera.position
)
// TODO this should probably be distance to the sketch group, more important after sketch on face
// since sketches won't always so close to the origin
// is this the best place to adjust camera far?
if (sceneInfra.camera.far < distance * 1.5) {
sceneInfra.camera.far = distance * 2
if (!skipListeners) {
sceneInfra.resetMouseListeners()
}
this.createIntersectionPlane()
const { truncatedAst, programMemoryOverride, variableDeclarationName } =
this.prepareTruncatedMemoryAndAst(
@ -279,11 +283,11 @@ class SceneEntities {
sketchGroup.position[1],
sketchGroup.position[2]
)
const orthoFactor = orthoScale(sceneInfra.camera)
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
const factor =
sceneInfra.camera instanceof OrthographicCamera
sceneInfra.camControls.camera instanceof OrthographicCamera
? orthoFactor
: perspScale(sceneInfra.camera, dummy)
: perspScale(sceneInfra.camControls.camera, dummy)
sketchGroup.value.forEach((segment, index) => {
let segPathToNode = getNodePathFromSourceRange(
draftSegment ? truncatedAst : kclManager.ast,
@ -328,11 +332,60 @@ class SceneEntities {
this.currentSketchQuaternion
)
let addingNewSegmentStatus: 'nothing' | 'pending' | 'added' = 'nothing'
this.scene.add(group)
if (!draftSegment) {
if (!draftSegment && !skipListeners) {
sceneInfra.setCallbacks({
onDrag: (args) => {
onDragEnd: async () => {
if (addingNewSegmentStatus !== 'nothing') {
await this.tearDownSketch({ removeAxis: false })
this.setupSketch({ sketchPathToNode })
}
},
onDrag: async (args) => {
if (args.event.which !== 1) return
const group = getParentGroup(args.object, [EXTRA_SEGMENT_HANDLE])
if (group?.name === EXTRA_SEGMENT_HANDLE) {
const segGroup = getParentGroup(args.object)
const pathToNode: PathToNode = segGroup?.userData?.pathToNode
const pathToNodeIndex = pathToNode.findIndex(
(x) => x[1] === 'PipeExpression'
)
const pipeIndex = pathToNode[pathToNodeIndex + 1][0] as number
if (addingNewSegmentStatus === 'nothing') {
const prevSegment = sketchGroup.value[pipeIndex - 2]
const yo = addNewSketchLn({
node: kclManager.ast,
programMemory: kclManager.programMemory,
to: [args.intersection2d.x, args.intersection2d.y],
from: [prevSegment.from[0], prevSegment.from[1]],
fnName:
prevSegment.type === 'TangentialArcTo'
? 'tangentialArcTo'
: 'line',
pathToNode: pathToNode,
})
addingNewSegmentStatus = 'pending'
await kclManager.executeAstMock(yo.modifiedAst, {
updates: 'code',
})
await this.tearDownSketch({ removeAxis: false })
this.setupSketch({ sketchPathToNode, skipListeners: true })
addingNewSegmentStatus = 'added'
} else if (addingNewSegmentStatus === 'added') {
const pathToNodeForNewSegment = pathToNode.slice(
0,
pathToNodeIndex
)
pathToNodeForNewSegment.push([pipeIndex - 2, 'index'])
this.onDragSegment({
...args,
sketchPathToNode: pathToNodeForNewSegment,
})
}
return
}
this.onDragSegment({
...args,
sketchPathToNode,
@ -393,7 +446,7 @@ class SceneEntities {
}
},
})
} else {
} else if (draftSegment && !skipListeners) {
sceneInfra.setCallbacks({
onDrag: () => {},
onClick: async (args) => {
@ -450,7 +503,7 @@ class SceneEntities {
},
})
}
sceneInfra.controls.enableRotate = false
sceneInfra.camControls.enableRotate = false
}
updateAstAndRejigSketch = async (
sketchPathToNode: PathToNode,
@ -502,6 +555,7 @@ class SceneEntities {
variableDeclarationName: string
}
}) {
if (object.name === STRAIGHT_SEGMENT_BODY) return
const group = getParentGroup(object)
if (!group) return
const pathToNode: PathToNode = JSON.parse(
@ -553,7 +607,7 @@ class SceneEntities {
this.sceneProgramMemory = programMemory
const sketchGroup = programMemory.root[variableDeclarationName]
.value as Path[]
const orthoFactor = orthoScale(sceneInfra.camera)
const orthoFactor = orthoScale(sceneInfra.camControls.camera)
sketchGroup.forEach((segment, index) => {
const segPathToNode = getNodePathFromSourceRange(
modifiedAst,
@ -569,9 +623,9 @@ class SceneEntities {
// const prevSegment = sketchGroup.slice(index - 1)[0]
const type = group?.userData?.type
const factor =
sceneInfra.camera instanceof OrthographicCamera
sceneInfra.camControls.camera instanceof OrthographicCamera
? orthoFactor
: perspScale(sceneInfra.camera, group)
: perspScale(sceneInfra.camControls.camera, group)
if (type === TANGENTIAL_ARC_TO_SEGMENT) {
this.updateTangentialArcToSegment({
prevSegment: sketchGroup[index - 1],
@ -608,9 +662,7 @@ class SceneEntities {
group.userData.from = from
group.userData.to = to
group.userData.prevSegment = prevSegment
const arrowGroup = group.children.find(
(child) => child.userData.type === ARROWHEAD
) as Group
const arrowGroup = group.getObjectByName(ARROWHEAD) as Group
arrowGroup.position.set(to[0], to[1], 0)
@ -685,9 +737,7 @@ class SceneEntities {
const shape = new Shape()
shape.moveTo(0, -0.08 * scale)
shape.lineTo(0, 0.08 * scale) // The width of the line
const arrowGroup = group.children.find(
(child) => child.userData.type === ARROWHEAD
) as Group
const arrowGroup = group.getObjectByName(ARROWHEAD) as Group
arrowGroup.position.set(to[0], to[1], 0)
@ -700,6 +750,32 @@ class SceneEntities {
arrowGroup.quaternion.setFromUnitVectors(new Vector3(0, 1, 0), dir)
arrowGroup.scale.set(scale, scale, scale)
// TODO this should be created in setupSketch, not updateStraightSegment
// it should only be updated here
const extraSegmentHandle = (group.getObjectByName(EXTRA_SEGMENT_HANDLE) ||
(() => {
const mat = new MeshBasicMaterial({ color: 0xffffff })
const sphereMesh = new Mesh(new SphereGeometry(0.6, 12, 12), mat)
const handleGroup = new Group()
handleGroup.userData.type = EXTRA_SEGMENT_HANDLE
handleGroup.name = EXTRA_SEGMENT_HANDLE
handleGroup.add(sphereMesh)
handleGroup.layers.set(SKETCH_LAYER)
handleGroup.traverse((child) => {
child.layers.set(SKETCH_LAYER)
})
return handleGroup
})()) as Group
extraSegmentHandle.position.set(
from[0] + 0.08 * (to[0] - from[0]),
from[1] + 0.08 * (to[1] - from[1]),
0
)
extraSegmentHandle.scale.set(scale, scale, scale)
group.add(extraSegmentHandle)
const straightSegmentBody = group.children.find(
(child) => child.userData.type === STRAIGHT_SEGMENT_BODY
) as Mesh
@ -728,10 +804,10 @@ class SceneEntities {
}
async animateAfterSketch() {
if (isReducedMotion()) {
sceneInfra.usePerspectiveCamera()
} else {
await sceneInfra.animateToPerspective()
sceneInfra.camControls.usePerspectiveCamera()
return
}
await sceneInfra.camControls.animateToPerspective()
}
removeSketchGrid() {
if (this.axisGroup) this.scene.remove(this.axisGroup)
@ -763,7 +839,7 @@ class SceneEntities {
reject()
}
}
sceneInfra.controls.enableRotate = true
sceneInfra.camControls.enableRotate = true
this.activeSegments = {}
// maybe should reset onMove etc handlers
if (shouldResolve) resolve(true)
@ -796,8 +872,8 @@ class SceneEntities {
onClick: (args) => {
if (!args || !args.object) return
if (args.event.which !== 1) return
const { object, intersection } = args
const type = object?.userData?.type || ''
const { intersection } = args
const type = intersection.object.name || ''
const posNorm = Number(intersection.normal?.z) > 0
let planeString: DefaultPlaneStr = posNorm ? 'XY' : '-XY'
let normal: [number, number, number] = posNorm ? [0, 0, 1] : [0, 0, -1]

View File

@ -1,12 +1,10 @@
import {
AmbientLight,
Color,
Euler,
GridHelper,
LineBasicMaterial,
OrthographicCamera,
PerspectiveCamera,
Quaternion,
Scene,
Vector3,
WebGLRenderer,
@ -14,40 +12,32 @@ import {
Vector2,
Group,
PlaneGeometry,
EdgesGeometry,
MeshBasicMaterial,
Mesh,
LineSegments,
DoubleSide,
Intersection,
Object3D,
Object3DEventMap,
BoxGeometry,
} from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { EngineCommand, engineCommandManager } from 'lang/std/engineConnection'
import { v4 as uuidv4 } from 'uuid'
import { isReducedMotion, roundOff, throttle } from 'lib/utils'
import { compareVec2Epsilon2 } from 'lang/std/sketch'
import { useModelingContext } from 'hooks/useModelingContext'
import { deg2Rad } from 'lib/utils2d'
import * as TWEEN from '@tweenjs/tween.js'
import { MouseGuard, cameraMouseDragGuards } from 'lib/cameraControls'
import { SourceRange } from 'lang/wasm'
import { Axis } from 'lib/selections'
import { createGridHelper } from './helpers'
import { BaseUnit, SETTINGS_PERSIST_KEY } from 'machines/settingsMachine'
import { CameraControls } from './CameraControls'
type SendType = ReturnType<typeof useModelingContext>['send']
// 63.5 is definitely a bit of a magic number, play with it until it looked right
// if it were 64, that would feel like it's something in the engine where a random
// power of 2 is used, but it's the 0.5 seems to make things look much more correct
const ZOOM_MAGIC_NUMBER = 63.5
const FRAMES_TO_ANIMATE_IN = 30
const ORTHOGRAPHIC_CAMERA_SIZE = 20
export const ZOOM_MAGIC_NUMBER = 63.5
export const INTERSECTION_PLANE_LAYER = 1
export const SKETCH_LAYER = 2
const DEBUG_SHOW_INTERSECTION_PLANE = false
export const DEBUG_SHOW_INTERSECTION_PLANE = false
export const DEBUG_SHOW_BOTH_SCENES = false
export const RAYCASTABLE_PLANE = 'raycastable-plane'
@ -59,100 +49,6 @@ export const AXIS_GROUP = 'axisGroup'
export const SKETCH_GROUP_SEGMENTS = 'sketch-group-segments'
export const ARROWHEAD = 'arrowhead'
const tempQuaternion = new Quaternion() // just used for maths
interface ThreeCamValues {
position: Vector3
quaternion: Quaternion
zoom: number
isPerspective: boolean
target: Vector3
}
const lastCmdDelay = 50
let lastCmd: EngineCommand | null = null
let lastCmdTime: number = Date.now()
let lastCmdTimeoutId: number | null = null
const sendLastReliableChannel = () => {
if (lastCmd && Date.now() - lastCmdTime >= lastCmdDelay) {
engineCommandManager.sendSceneCommand(lastCmd, true)
lastCmdTime = Date.now()
}
}
const throttledUpdateEngineCamera = throttle((threeValues: ThreeCamValues) => {
const cmd: EngineCommand = {
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_look_at',
...convertThreeCamValuesToEngineCam(threeValues),
},
}
engineCommandManager.sendSceneCommand(cmd)
lastCmd = cmd
lastCmdTime = Date.now()
if (lastCmdTimeoutId !== null) {
clearTimeout(lastCmdTimeoutId)
}
lastCmdTimeoutId = setTimeout(
sendLastReliableChannel,
lastCmdDelay
) as any as number
}, 1000 / 30)
let lastPerspectiveCmd: EngineCommand | null = null
let lastPerspectiveCmdTime: number = Date.now()
let lastPerspectiveCmdTimeoutId: number | null = null
const sendLastPerspectiveReliableChannel = () => {
if (
lastPerspectiveCmd &&
Date.now() - lastPerspectiveCmdTime >= lastCmdDelay
) {
engineCommandManager.sendSceneCommand(lastPerspectiveCmd, true)
lastPerspectiveCmdTime = Date.now()
}
}
const throttledUpdateEngineFov = throttle(
(vals: {
position: Vector3
quaternion: Quaternion
zoom: number
fov: number
target: Vector3
}) => {
const cmd: EngineCommand = {
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_perspective_settings',
...convertThreeCamValuesToEngineCam({
...vals,
isPerspective: true,
}),
fov_y: vals.fov,
...calculateNearFarFromFOV(vals.fov),
},
}
engineCommandManager.sendSceneCommand(cmd)
lastPerspectiveCmd = cmd
lastPerspectiveCmdTime = Date.now()
if (lastPerspectiveCmdTimeoutId !== null) {
clearTimeout(lastPerspectiveCmdTimeoutId)
}
lastPerspectiveCmdTimeoutId = setTimeout(
sendLastPerspectiveReliableChannel,
lastCmdDelay
) as any as number
},
1000 / 15
)
interface BaseCallbackArgs2 {
object: any
event: any
@ -180,46 +76,37 @@ interface onMoveCallbackArgs {
intersection: Intersection<Object3D<Object3DEventMap>>
}
export type ReactCameraProperties =
| {
type: 'perspective'
fov?: number
position: [number, number, number]
quaternion: [number, number, number, number]
}
| {
type: 'orthographic'
zoom?: number
position: [number, number, number]
quaternion: [number, number, number, number]
}
// This singleton class is responsible for all of the under the hood setup for the client side scene.
// That is the cameras and switching between them, raycasters for click mouse events and their abstractions (onClick etc), setting up controls.
// Anything that added the the scene for the user to interact with is probably in SceneEntities.ts
class SceneInfra {
static instance: SceneInfra
scene: Scene
camera: PerspectiveCamera | OrthographicCamera
renderer: WebGLRenderer
controls: OrbitControls
camControls: CameraControls
isPerspective = true
fov = 45
fovBeforeAnimate = 45
isFovAnimationInProgress = false
interactionGuards: MouseGuard = cameraMouseDragGuards.KittyCAD
onDragStartCallback: (arg: OnDragCallbackArgs) => void = () => {}
onDragEndCallback: (arg: OnDragCallbackArgs) => void = () => {}
onDragCallback: (arg: OnDragCallbackArgs) => void = () => {}
onMoveCallback: (arg: onMoveCallbackArgs) => void = () => {}
onClickCallback: (arg?: OnClickCallbackArgs) => void = () => {}
onMouseEnter: (arg: BaseCallbackArgs2) => void = () => {}
onMouseLeave: (arg: BaseCallbackArgs2) => void = () => {}
setCallbacks = (callbacks: {
onDragStart?: (arg: OnDragCallbackArgs) => void
onDragEnd?: (arg: OnDragCallbackArgs) => void
onDrag?: (arg: OnDragCallbackArgs) => void
onMove?: (arg: onMoveCallbackArgs) => void
onClick?: (arg?: OnClickCallbackArgs) => void
onMouseEnter?: (arg: BaseCallbackArgs2) => void
onMouseLeave?: (arg: BaseCallbackArgs2) => void
}) => {
console.trace('setting callbacks')
this.onDragStartCallback = callbacks.onDragStart || this.onDragStartCallback
this.onDragEndCallback = callbacks.onDragEnd || this.onDragEndCallback
this.onDragCallback = callbacks.onDrag || this.onDragCallback
this.onMoveCallback = callbacks.onMove || this.onMoveCallback
this.onClickCallback = callbacks.onClick || this.onClickCallback
@ -227,6 +114,17 @@ class SceneInfra {
this.onMouseLeave = callbacks.onMouseLeave || this.onMouseLeave
this.selected = null // following selections between callbacks being set is too tricky
}
resetMouseListeners = () => {
sceneInfra.setCallbacks({
onDragStart: () => {},
onDragEnd: () => {},
onDrag: () => {},
onMove: () => {},
onClick: () => {},
onMouseEnter: () => {},
onMouseLeave: () => {},
})
}
highlightCallback: (a: SourceRange) => void = () => {}
setHighlightCallback(cb: (a: SourceRange) => void) {
this.highlightCallback = cb
@ -249,75 +147,41 @@ class SceneInfra {
selectedObject: null | any = null
mouseDownVector: null | Vector2 = null
// reacts hooks into some of this singleton's properties
reactCameraProperties: ReactCameraProperties = {
type: 'perspective',
fov: 12,
position: [0, 0, 0],
quaternion: [0, 0, 0, 1],
}
reactCameraPropertiesCallback: (a: ReactCameraProperties) => void = () => {}
setReactCameraPropertiesCallback = (
cb: (a: ReactCameraProperties) => void
) => {
this.reactCameraPropertiesCallback = cb
}
setCam = (camProps: ReactCameraProperties) => {
if (
camProps.type === 'perspective' &&
this.camera instanceof OrthographicCamera
) {
this.usePerspectiveCamera()
} else if (
camProps.type === 'orthographic' &&
this.camera instanceof PerspectiveCamera
) {
this.useOrthographicCamera()
}
this.camera.position.set(...camProps.position)
this.camera.quaternion.set(...camProps.quaternion)
if (
camProps.type === 'perspective' &&
this.camera instanceof PerspectiveCamera
) {
// not sure what to do here, calling dollyZoom here is buggy because it updates the position
// at the same time
} else if (
camProps.type === 'orthographic' &&
this.camera instanceof OrthographicCamera
) {
this.camera.zoom = camProps.zoom || 1
}
this.camera.updateProjectionMatrix()
this.controls.update()
}
constructor() {
// SCENE
this.scene = new Scene()
this.scene.background = new Color(0x000000)
this.scene.background = null
// CAMERA
this.camera = this.createPerspectiveCamera()
this.camera.position.set(0, -128, 64)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camera.layers.enable(INTERSECTION_PLANE_LAYER)
// RENDERER
this.renderer = new WebGLRenderer({ antialias: true, alpha: true }) // Enable transparency
this.renderer.setSize(window.innerWidth, window.innerHeight)
this.renderer.setClearColor(0x000000, 0) // Set clear color to black with 0 alpha (fully transparent)
window.addEventListener('resize', this.onWindowResize)
// CAMERA
const camHeightDistanceRatio = 0.5
const baseUnit: BaseUnit =
JSON.parse(localStorage?.getItem(SETTINGS_PERSIST_KEY) || ('{}' as any))
.baseUnit || 'mm'
const baseRadius = 5.6
const length = baseUnitTomm(baseUnit) * baseRadius
const ang = Math.atan(camHeightDistanceRatio)
const x = Math.cos(ang) * length
const y = Math.sin(ang) * length
this.camControls = new CameraControls(false, this.renderer.domElement)
this.camControls.subscribeToCamChange(() => this.onCameraChange())
this.camControls.camera.layers.enable(SKETCH_LAYER)
this.camControls.camera.position.set(0, -x, y)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camControls.camera.layers.enable(INTERSECTION_PLANE_LAYER)
// RAYCASTERS
this.raycaster.layers.enable(SKETCH_LAYER)
this.raycaster.layers.disable(0)
this.planeRaycaster.layers.enable(INTERSECTION_PLANE_LAYER)
// CONTROLS
this.controls = this.setupOrbitControls()
// GRID
const size = 100
const divisions = 10
@ -337,415 +201,40 @@ class SceneInfra {
SceneInfra.instance = this
}
private _isCamMovingCallback: (isMoving: boolean, isTween: boolean) => void =
() => {}
setIsCamMovingCallback(cb: (isMoving: boolean, isTween: boolean) => void) {
this._isCamMovingCallback = cb
}
private _onCamChange: () => void = () => {}
setOnCamChange(cb: () => void) {
this._onCamChange = cb
}
setInteractionGuards = (guard: MouseGuard) => {
this.interactionGuards = guard
// setMouseGuards is oun patch-package patch to orbit controls
// see patches/three+0.160.0.patch
;(this.controls as any).setMouseGuards(guard)
}
private createPerspectiveCamera = () => {
const { z_near, z_far } = calculateNearFarFromFOV(this.fov)
this.camera = new PerspectiveCamera(
this.fov,
window.innerWidth / window.innerHeight,
z_near,
z_far
)
this.camera.up.set(0, 0, 1)
this.camera.layers.enable(SKETCH_LAYER)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camera.layers.enable(INTERSECTION_PLANE_LAYER)
return this.camera
}
setupOrbitControls = (target?: [number, number, number]): OrbitControls => {
if (this.controls) this.controls.dispose()
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
if (target) {
// if we're swapping from perspective to orthographic,
// we'll need to recreate the orbit controls
// and most likely want the target to be the same
this.controls.target.set(...target)
}
this.controls.update()
this.controls.addEventListener('change', this.onCameraChange)
// debounce is needed because the start and end events are fired too often for zoom on scroll
let debounceTimer = 0
const handleStart = () => {
if (debounceTimer) clearTimeout(debounceTimer)
this._isCamMovingCallback(true, false)
}
const handleEnd = () => {
debounceTimer = setTimeout(() => {
this._isCamMovingCallback(false, false)
}, 400) as any as number
}
this.controls.addEventListener('start', handleStart)
this.controls.addEventListener('end', handleEnd)
// setMouseGuards is oun patch-package patch to orbit controls
// see patches/three+0.160.0.patch
;(this.controls as any).setMouseGuards(this.interactionGuards)
return this.controls
}
onStreamStart = () => this.onCameraChange()
deferReactUpdate = throttle((a: ReactCameraProperties) => {
this.reactCameraPropertiesCallback(a)
}, 200)
onCameraChange = () => {
const scale = getSceneScale(this.camera, this.controls.target)
const scale = getSceneScale(
this.camControls.camera,
this.camControls.target
)
const planesGroup = this.scene.getObjectByName(DEFAULT_PLANES)
const axisGroup = this.scene
.getObjectByName(AXIS_GROUP)
?.getObjectByName('gridHelper')
planesGroup && planesGroup.scale.set(scale, scale, scale)
axisGroup?.name === 'gridHelper' && axisGroup.scale.set(scale, scale, scale)
throttledUpdateEngineCamera({
quaternion: this.camera.quaternion,
position: this.camera.position,
zoom: this.camera.zoom,
isPerspective: this.isPerspective,
target: this.controls.target,
})
this.deferReactUpdate({
type:
this.camera instanceof PerspectiveCamera
? 'perspective'
: 'orthographic',
[this.camera instanceof PerspectiveCamera ? 'fov' : 'zoom']:
this.camera instanceof PerspectiveCamera
? this.camera.fov
: this.camera.zoom,
position: [
roundOff(this.camera.position.x, 2),
roundOff(this.camera.position.y, 2),
roundOff(this.camera.position.z, 2),
],
quaternion: [
roundOff(this.camera.quaternion.x, 2),
roundOff(this.camera.quaternion.y, 2),
roundOff(this.camera.quaternion.z, 2),
roundOff(this.camera.quaternion.w, 2),
],
})
this._onCamChange()
}
onWindowResize = () => {
if (this.camera instanceof PerspectiveCamera) {
this.camera.aspect = window.innerWidth / window.innerHeight
} else if (this.camera instanceof OrthographicCamera) {
const aspect = window.innerWidth / window.innerHeight
this.camera.left = -ORTHOGRAPHIC_CAMERA_SIZE * aspect
this.camera.right = ORTHOGRAPHIC_CAMERA_SIZE * aspect
this.camera.top = ORTHOGRAPHIC_CAMERA_SIZE
this.camera.bottom = -ORTHOGRAPHIC_CAMERA_SIZE
}
this.camera.updateProjectionMatrix()
this.renderer.setSize(window.innerWidth, window.innerHeight)
}
animate = () => {
requestAnimationFrame(this.animate)
TWEEN.update() // This will update all tweens during the animation loop
if (!this.isFovAnimationInProgress)
this.renderer.render(this.scene, this.camera)
}
async tweenCameraToQuaternion(
targetQuaternion: Quaternion,
duration = 500,
toOrthographic = true
): Promise<void> {
const isVertical = isQuaternionVertical(targetQuaternion)
let _duration = duration
if (isVertical) {
_duration = duration * 0.6
await this._tweenCameraToQuaternion(new Quaternion(), _duration, false)
if (!this.isFovAnimationInProgress) {
// console.log('animation frame', this.cameraControls.camera)
this.camControls.update()
this.renderer.render(this.scene, this.camControls.camera)
}
await this._tweenCameraToQuaternion(
targetQuaternion,
_duration,
toOrthographic
)
}
_tweenCameraToQuaternion(
targetQuaternion: Quaternion,
duration = 500,
toOrthographic = false
): Promise<void> {
return new Promise((resolve) => {
const camera = this.camera
this._isCamMovingCallback(true, true)
const initialQuaternion = camera.quaternion.clone()
const isVertical = isQuaternionVertical(targetQuaternion)
let tweenEnd = isVertical ? 0.99 : 1
const controlsTarget = this.controls.target.clone()
const initialDistance = controlsTarget.distanceTo(camera.position.clone())
const cameraAtTime = (animationProgress: number /* 0 - 1 */) => {
const currentQ = tempQuaternion.slerpQuaternions(
initialQuaternion,
targetQuaternion,
animationProgress
)
if (this.camera instanceof PerspectiveCamera)
// changing the camera position back when it's orthographic doesn't do anything
// and it messes up animating back to perspective later
this.camera.position
.set(0, 0, 1)
.applyQuaternion(currentQ)
.multiplyScalar(initialDistance)
.add(controlsTarget)
this.camera.up.set(0, 1, 0).applyQuaternion(currentQ).normalize()
this.camera.quaternion.copy(currentQ)
this.controls.target.copy(controlsTarget)
this.controls.update()
this.camera.updateProjectionMatrix()
}
const onComplete = async () => {
if (isReducedMotion() && toOrthographic) {
cameraAtTime(0.99)
this.useOrthographicCamera()
} else if (toOrthographic) {
await this.animateToOrthographic()
}
if (isVertical) cameraAtTime(1)
this.camera.up.set(0, 0, 1)
this.controls.enableRotate = false
this._isCamMovingCallback(false, true)
resolve()
}
if (isReducedMotion()) {
onComplete()
return
}
new TWEEN.Tween({ t: 0 })
.to({ t: tweenEnd }, duration)
.easing(TWEEN.Easing.Quadratic.InOut)
.onUpdate(({ t }) => cameraAtTime(t))
.onComplete(onComplete)
.start()
})
}
animateToOrthographic = () =>
new Promise((resolve) => {
this.isFovAnimationInProgress = true
let currentFov = this.fov
this.fovBeforeAnimate = this.fov
const targetFov = 4
const fovAnimationStep = (currentFov - targetFov) / FRAMES_TO_ANIMATE_IN
let frameWaitOnFinish = 10
const animateFovChange = () => {
if (this.camera instanceof PerspectiveCamera) {
if (this.camera.fov > targetFov) {
// Decrease the FOV
currentFov = Math.max(currentFov - fovAnimationStep, targetFov)
this.camera.updateProjectionMatrix()
this.dollyZoom(currentFov)
requestAnimationFrame(animateFovChange) // Continue the animation
} else if (frameWaitOnFinish > 0) {
frameWaitOnFinish--
requestAnimationFrame(animateFovChange) // Continue the animation
} else {
// Once the target FOV is reached, switch to the orthographic camera
// Needs to wait a couple frames after the FOV animation is complete
this.useOrthographicCamera()
this.isFovAnimationInProgress = false
resolve(true)
}
}
}
animateFovChange() // Start the animation
})
animateToPerspective = () =>
new Promise((resolve) => {
this.isFovAnimationInProgress = true
// Immediately set the camera to perspective with a very low FOV
this.fov = 4
let currentFov = 4
this.camera.updateProjectionMatrix()
const targetFov = this.fovBeforeAnimate // Target FOV for perspective
const fovAnimationStep = (targetFov - currentFov) / FRAMES_TO_ANIMATE_IN
this.usePerspectiveCamera()
const animateFovChange = () => {
if (this.camera instanceof OrthographicCamera) return
if (this.camera.fov < targetFov) {
// Increase the FOV
currentFov = Math.min(currentFov + fovAnimationStep, targetFov)
// this.camera.fov = currentFov
this.camera.updateProjectionMatrix()
this.dollyZoom(currentFov)
requestAnimationFrame(animateFovChange) // Continue the animation
} else {
// Set the flag to false as the FOV animation is complete
this.isFovAnimationInProgress = false
resolve(true)
}
}
animateFovChange() // Start the animation
})
dispose = () => {
// Dispose of scene resources, renderer, and controls
this.renderer.dispose()
window.removeEventListener('resize', this.onWindowResize)
// Dispose of any other resources like geometries, materials, textures
}
useOrthographicCamera = () => {
this.isPerspective = false
const { x: px, y: py, z: pz } = this.camera.position
const { x: qx, y: qy, z: qz, w: qw } = this.camera.quaternion
const { x: tx, y: ty, z: tz } = this.controls.target
const aspect = window.innerWidth / window.innerHeight
const { z_near, z_far } = calculateNearFarFromFOV(this.fov)
this.camera = new OrthographicCamera(
-ORTHOGRAPHIC_CAMERA_SIZE * aspect,
ORTHOGRAPHIC_CAMERA_SIZE * aspect,
ORTHOGRAPHIC_CAMERA_SIZE,
-ORTHOGRAPHIC_CAMERA_SIZE,
z_near,
z_far
)
this.camera.up.set(0, 0, 1)
this.camera.layers.enable(SKETCH_LAYER)
if (DEBUG_SHOW_INTERSECTION_PLANE)
this.camera.layers.enable(INTERSECTION_PLANE_LAYER)
this.camera.position.set(px, py, pz)
const distance = this.camera.position.distanceTo(new Vector3(tx, ty, tz))
const fovFactor = 45 / this.fov
this.camera.zoom = (ZOOM_MAGIC_NUMBER * fovFactor * 0.8) / distance
this.setupOrbitControls([tx, ty, tz])
this.camera.quaternion.set(qx, qy, qz, qw)
this.camera.updateProjectionMatrix()
this.controls.update()
engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_orthographic',
},
})
}
usePerspectiveCamera = () => {
this.isPerspective = true
const { x: px, y: py, z: pz } = this.camera.position
const { x: qx, y: qy, z: qz, w: qw } = this.camera.quaternion
const { x: tx, y: ty, z: tz } = this.controls.target
const zoom = this.camera.zoom
this.camera = this.createPerspectiveCamera()
this.camera.position.set(px, py, pz)
this.camera.quaternion.set(qx, qy, qz, qw)
const zoomFudgeFactor = 2280
const distance = zoomFudgeFactor / (zoom * this.fov)
const direction = new Vector3().subVectors(
this.camera.position,
this.controls.target
)
direction.normalize()
this.camera.position
.copy(this.controls.target)
.addScaledVector(direction, distance)
this.setupOrbitControls([tx, ty, tz])
engineCommandManager.sendSceneCommand({
type: 'modeling_cmd_req',
cmd_id: uuidv4(),
cmd: {
type: 'default_camera_set_perspective',
parameters: {
fov_y: this.camera.fov,
...calculateNearFarFromFOV(this.fov),
},
},
})
this.onCameraChange()
return this.camera
}
dollyZoom = (newFov: number) => {
if (!(this.camera instanceof PerspectiveCamera)) {
console.warn('Dolly zoom is only applicable to perspective cameras.')
return
}
this.fov = newFov
// Calculate the direction vector from the camera towards the controls target
const direction = new Vector3()
.subVectors(this.controls.target, this.camera.position)
.normalize()
// Calculate the distance to the controls target before changing the FOV
const distanceBefore = this.camera.position.distanceTo(this.controls.target)
// Calculate the scale factor for the new FOV compared to the old one
// This needs to be calculated before updating the camera's FOV
const oldFov = this.camera.fov
const viewHeightFactor = (fov: number) => {
/* *
/|
/ |
/ |
/ |
/ | viewHeight/2
/ |
/ |
/↙fov/2 |
/________|
\ |
\._._._.|
*/
return Math.tan(deg2Rad(fov / 2))
}
const scaleFactor = viewHeightFactor(oldFov) / viewHeightFactor(newFov)
this.camera.fov = newFov
this.camera.updateProjectionMatrix()
const distanceAfter = distanceBefore * scaleFactor
const newPosition = this.controls.target
.clone()
.add(direction.multiplyScalar(-distanceAfter))
this.camera.position.copy(newPosition)
const { z_near, z_far } = calculateNearFarFromFOV(this.fov)
this.camera.near = z_near
this.camera.far = z_far
throttledUpdateEngineFov({
fov: newFov,
position: newPosition,
quaternion: this.camera.quaternion,
zoom: this.camera.zoom,
target: this.controls.target,
})
}
getPlaneIntersectPoint = (): {
intersection2d?: Vector2
intersectPoint: Vector3
@ -753,7 +242,7 @@ class SceneInfra {
} | null => {
this.planeRaycaster.setFromCamera(
this.currentMouseVector,
sceneInfra.camera
sceneInfra.camControls.camera
)
const planeIntersects = this.planeRaycaster.intersectObjects(
this.scene.children,
@ -891,7 +380,7 @@ class SceneInfra {
}
// Check the center point
this.raycaster.setFromCamera(mouseDownVector, this.camera)
this.raycaster.setFromCamera(mouseDownVector, this.camControls.camera)
updateClosestIntersection(
this.raycaster.intersectObjects(this.scene.children, true)
)
@ -906,7 +395,7 @@ class SceneInfra {
mouseDownVector.x + offsetX,
mouseDownVector.y - offsetY
)
this.raycaster.setFromCamera(ringVector, this.camera)
this.raycaster.setFromCamera(ringVector, this.camControls.camera)
updateClosestIntersection(
this.raycaster.intersectObjects(this.scene.children, true)
)
@ -940,8 +429,13 @@ class SceneInfra {
if (this.selected) {
if (this.selected.hasBeenDragged) {
// this is where we could fire a onDragEnd event
// console.log('onDragEnd', this.selected)
// TODO do the types properly here
this.onDragEndCallback({
object: this.selected.object,
event,
intersection2d: planeIntersectPoint?.intersection2d,
...planeIntersectPoint,
} as any)
} else if (planeIntersectPoint) {
// fire onClick event as there was no drags
this.onClickCallback({
@ -999,7 +493,10 @@ class SceneInfra {
}
})
planesGroup.layers.enable(SKETCH_LAYER)
const sceneScale = getSceneScale(this.camera, this.controls.target)
const sceneScale = getSceneScale(
this.camControls.camera,
this.camControls.target
)
planesGroup.scale.set(sceneScale, sceneScale, sceneScale)
this.scene.add(planesGroup)
}
@ -1034,52 +531,6 @@ class SceneInfra {
export const sceneInfra = new SceneInfra()
function convertThreeCamValuesToEngineCam({
target,
position,
quaternion,
zoom,
isPerspective,
}: ThreeCamValues): {
center: Vector3
up: Vector3
vantage: Vector3
} {
// Something to consider is that the orbit controls have a target,
// we're kind of deriving the target/lookAtVector here when it might not be needed
// leaving for now since it's working but maybe revisit later
const euler = new Euler().setFromQuaternion(quaternion, 'XYZ')
const lookAtVector = new Vector3(0, 0, -1)
.applyEuler(euler)
.normalize()
.add(position)
const upVector = new Vector3(0, 1, 0).applyEuler(euler).normalize()
if (isPerspective) {
return {
center: target,
up: upVector,
vantage: position,
}
}
const zoomFactor = -ZOOM_MAGIC_NUMBER / zoom
const direction = lookAtVector.clone().sub(position).normalize()
const newVantage = position.clone().add(direction.multiplyScalar(zoomFactor))
return {
center: lookAtVector,
up: upVector,
vantage: newVantage,
}
}
function calculateNearFarFromFOV(fov: number) {
const nearFarRatio = (fov - 3) / (45 - 3)
// const z_near = 0.1 + nearFarRatio * (5 - 0.1)
const z_far = 1000 + nearFarRatio * (100000 - 1000)
return { z_near: 0.1, z_far }
}
export function getSceneScale(
camera: PerspectiveCamera | OrthographicCamera,
target: Vector3
@ -1098,10 +549,21 @@ export function getSceneScale(
return 1
}
export function isQuaternionVertical(q: Quaternion) {
const v = new Vector3(0, 0, 1).applyQuaternion(q)
// no x or y components means it's vertical
return compareVec2Epsilon2([v.x, v.y], [0, 0])
function baseUnitTomm(baseUnit: BaseUnit) {
switch (baseUnit) {
case 'mm':
return 1
case 'cm':
return 10
case 'm':
return 1000
case 'in':
return 25.4
case 'ft':
return 304.8
case 'yd':
return 914.4
}
}
export type DefaultPlane =

View File

@ -81,6 +81,7 @@ export function straightSegment({
pathToNode,
isSelected: false,
}
group.name = STRAIGHT_SEGMENT
const arrowGroup = createArrowhead(scale)
arrowGroup.position.set(to[0], to[1], 0)
@ -169,6 +170,7 @@ export function tangentialArcToSegment({
pathToNode,
isSelected: false,
}
group.name = TANGENTIAL_ARC_TO_SEGMENT
const arrowGroup = createArrowhead(scale)
arrowGroup.position.set(to[0], to[1], 0)

View File

@ -87,7 +87,7 @@ export function useCalc({
inputRef: React.RefObject<HTMLInputElement>
valueNode: Value | null
calcResult: string
prevVariables: PrevVariable<any>[]
prevVariables: PrevVariable<unknown>[]
newVariableName: string
isNewVariableNameUnique: boolean
newVariableInsertIndex: number

View File

@ -4,7 +4,7 @@ import { engineCommandManager } from 'lang/std/engineConnection'
import { throttle, isReducedMotion } from 'lib/utils'
const updateDollyZoom = throttle(
(newFov: number) => sceneInfra.dollyZoom(newFov),
(newFov: number) => sceneInfra.camControls.dollyZoom(newFov),
1000 / 15
)
@ -15,19 +15,19 @@ export const CamToggle = () => {
useEffect(() => {
engineCommandManager.waitForReady.then(async () => {
sceneInfra.dollyZoom(fov)
sceneInfra.camControls.dollyZoom(fov)
})
}, [])
const toggleCamera = () => {
if (isPerspective) {
isReducedMotion()
? sceneInfra.useOrthographicCamera()
: sceneInfra.animateToOrthographic()
? sceneInfra.camControls.useOrthographicCamera()
: sceneInfra.camControls.animateToOrthographic()
} else {
isReducedMotion()
? sceneInfra.usePerspectiveCamera()
: sceneInfra.animateToPerspective()
? sceneInfra.camControls.usePerspectiveCamera()
: sceneInfra.camControls.animateToPerspective()
}
setIsPerspective(!isPerspective)
}
@ -60,9 +60,9 @@ export const CamToggle = () => {
<button
onClick={() => {
if (enableRotate) {
sceneInfra.controls.enableRotate = false
sceneInfra.camControls.enableRotate = false
} else {
sceneInfra.controls.enableRotate = true
sceneInfra.camControls.enableRotate = true
}
setEnableRotate(!enableRotate)
}}

View File

@ -27,6 +27,7 @@ export const CommandBarProvider = ({
}) => {
const { pathname } = useLocation()
const [commandBarState, commandBarSend] = useMachine(commandBarMachine, {
devTools: true,
guards: {
'Arguments are ready': (context, _) => {
return context.selectedCommand?.args
@ -56,12 +57,11 @@ export const CommandBarProvider = ({
}}
>
{children}
<CommandBar />
</CommandsContext.Provider>
)
}
const CommandBar = () => {
export const CommandBar = () => {
const { commandBarState, commandBarSend } = useCommandsContext()
const {
context: { selectedCommand, currentArgument, commands },
@ -83,17 +83,25 @@ const CommandBar = () => {
if (commandBarState.matches('Review')) {
const entries = Object.entries(selectedCommand?.args || {})
commandBarSend({
type: commandBarState.matches('Review')
? 'Edit argument'
: 'Change current argument',
data: {
arg: {
name: entries[entries.length - 1][0],
...entries[entries.length - 1][1],
const currentArgName = entries[entries.length - 1][0]
const currentArg = {
name: currentArgName,
...entries[entries.length - 1][1],
}
if (commandBarState.matches('Review')) {
commandBarSend({
type: 'Edit argument',
data: {
arg: currentArg,
},
},
})
})
} else {
commandBarSend({
type: 'Remove argument',
data: { [currentArgName]: currentArg },
})
}
} else {
commandBarSend({ type: 'Deselect command' })
}
@ -116,6 +124,11 @@ const CommandBar = () => {
}
}
useEffect(
() => console.log(commandBarState.context.argumentsToSubmit),
[commandBarState.context.argumentsToSubmit]
)
return (
<Transition.Root
show={!commandBarState.matches('Closed') || false}

View File

@ -4,6 +4,7 @@ import CommandBarSelectionInput from './CommandBarSelectionInput'
import { CommandArgument } from 'lib/commandTypes'
import { useCommandsContext } from 'hooks/useCommandsContext'
import CommandBarHeader from './CommandBarHeader'
import CommandBarKclInput from './CommandBarKclInput'
function CommandBarArgument({ stepBack }: { stepBack: () => void }) {
const { commandBarState, commandBarSend } = useCommandsContext()
@ -17,10 +18,7 @@ function CommandBarArgument({ stepBack }: { stepBack: () => void }) {
commandBarSend({
type: 'Submit argument',
data: {
[currentArgument.name]:
currentArgument.inputType === 'number'
? parseFloat((data as string) || '0')
: data,
[currentArgument.name]: data,
},
})
}
@ -68,6 +66,10 @@ function ArgumentInput({
onSubmit={onSubmit}
/>
)
case 'kcl':
return (
<CommandBarKclInput arg={arg} stepBack={stepBack} onSubmit={onSubmit} />
)
default:
return (
<CommandBarBasicInput

View File

@ -9,7 +9,7 @@ function CommandBarBasicInput({
onSubmit,
}: {
arg: CommandArgument<unknown> & {
inputType: 'number' | 'string'
inputType: 'string'
name: string
}
stepBack: () => void
@ -18,7 +18,6 @@ function CommandBarBasicInput({
const { commandBarSend, commandBarState } = useCommandsContext()
useHotkeys('mod + k, mod + /', () => commandBarSend({ type: 'Close' }))
const inputRef = useRef<HTMLInputElement>(null)
const inputType = arg.inputType === 'number' ? 'number' : 'text'
useEffect(() => {
if (inputRef.current) {
@ -40,9 +39,9 @@ function CommandBarBasicInput({
</span>
<input
id="arg-form"
name={inputType}
name={arg.inputType}
ref={inputRef}
type={inputType}
type={arg.inputType}
required
className="flex-grow px-2 py-1 border-b border-b-chalkboard-100 dark:border-b-chalkboard-80 !bg-transparent focus:outline-none"
placeholder="Enter a value"

View File

@ -4,6 +4,9 @@ import React, { ReactNode, useState } from 'react'
import { ActionButton } from '../ActionButton'
import { Selections, getSelectionTypeDisplayText } from 'lib/selections'
import { useHotkeys } from 'react-hotkeys-hook'
import { KclCommandValue, KclExpressionWithVariable } from 'lib/commandTypes'
import Tooltip from 'components/Tooltip'
import { roundOff } from 'lib/utils'
function CommandBarHeader({ children }: React.PropsWithChildren<{}>) {
const { commandBarState, commandBarSend } = useCommandsContext()
@ -45,6 +48,7 @@ function CommandBarHeader({ children }: React.PropsWithChildren<{}>) {
parseInt(b.keys[0], 10) - 1
]
const arg = selectedCommand?.args[argName]
if (!argName || !arg) return
commandBarSend({
type: 'Change current argument',
data: { arg: { ...arg, name: argName } },
@ -59,7 +63,7 @@ function CommandBarHeader({ children }: React.PropsWithChildren<{}>) {
selectedCommand &&
argumentsToSubmit && (
<>
<div className="px-4 text-sm flex gap-4 items-start">
<div className="group px-4 text-sm flex gap-4 items-start">
<div className="flex flex-1 flex-wrap gap-2">
<p
data-command-name={selectedCommand?.name}
@ -91,25 +95,50 @@ function CommandBarHeader({ children }: React.PropsWithChildren<{}>) {
: 'bg-chalkboard-20/50 dark:bg-chalkboard-80/50 border-chalkboard-20 dark:border-chalkboard-80'
}`}
>
<span className="capitalize">{argName}</span>
{argumentsToSubmit[argName] ? (
arg.inputType === 'selection' ? (
getSelectionTypeDisplayText(
argumentsToSubmit[argName] as Selections
)
) : arg.inputType === 'kcl' ? (
roundOff(
Number(
(argumentsToSubmit[argName] as KclCommandValue)
.valueCalculated
),
4
)
) : typeof argumentsToSubmit[argName] === 'object' ? (
JSON.stringify(argumentsToSubmit[argName])
) : (
<em>{argumentsToSubmit[argName] as ReactNode}</em>
)
) : (
<em>{argName}</em>
)}
) : null}
{showShortcuts && (
<small className="absolute -top-[1px] right-full translate-x-1/2 px-0.5 rounded-sm bg-chalkboard-80 text-chalkboard-10 dark:bg-energy-10 dark:text-chalkboard-100">
<span className="sr-only">Hotkey: </span>
{i + 1}
</small>
)}
{arg.inputType === 'kcl' &&
!!argumentsToSubmit[argName] &&
'variableName' in
(argumentsToSubmit[argName] as KclCommandValue) && (
<>
<CustomIcon name="make-variable" className="w-4 h-4" />
<Tooltip position="blockEnd">
New variable:{' '}
{
(
argumentsToSubmit[
argName
] as KclExpressionWithVariable
).variableName
}
</Tooltip>
</>
)}
</button>
)
)}

View File

@ -0,0 +1,17 @@
.editor {
@apply text-base flex-1;
}
.editor :global(.cm-editor) {
@apply bg-transparent;
}
.editor :global(.cm-line)::selection {
@apply px-1;
@apply text-chalkboard-100;
@apply bg-energy-10/50;
}
:global(.dark) .editor :global(.cm-line)::selection {
@apply text-energy-10;
@apply bg-energy-10/20;
}

View File

@ -0,0 +1,221 @@
import { Completion } from '@codemirror/autocomplete'
import { EditorState, EditorView, useCodeMirror } from '@uiw/react-codemirror'
import { CustomIcon } from 'components/CustomIcon'
import { useCommandsContext } from 'hooks/useCommandsContext'
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
import { CommandArgument, KclCommandValue } from 'lib/commandTypes'
import { getSystemTheme } from 'lib/theme'
import { useCalculateKclExpression } from 'lib/useCalculateKclExpression'
import { roundOff } from 'lib/utils'
import { varMentions } from 'lib/varCompletionExtension'
import { useEffect, useRef, useState } from 'react'
import { useHotkeys } from 'react-hotkeys-hook'
import styles from './CommandBarKclInput.module.css'
import { createIdentifier, createVariableDeclaration } from 'lang/modifyAst'
function CommandBarKclInput({
arg,
stepBack,
onSubmit,
}: {
arg: CommandArgument<unknown> & {
inputType: 'kcl'
name: string
}
stepBack: () => void
onSubmit: (event: unknown) => void
}) {
const { commandBarSend, commandBarState } = useCommandsContext()
const previouslySetValue = commandBarState.context.argumentsToSubmit[
arg.name
] as KclCommandValue | undefined
const { settings } = useGlobalStateContext()
const defaultValue = (arg.defaultValue as string) || ''
const [value, setValue] = useState(
previouslySetValue?.valueText || defaultValue || ''
)
const [createNewVariable, setCreateNewVariable] = useState(
previouslySetValue && 'variableName' in previouslySetValue
)
const [canSubmit, setCanSubmit] = useState(true)
useHotkeys('mod + k, mod + /', () => commandBarSend({ type: 'Close' }))
const editorRef = useRef<HTMLDivElement>(null)
const {
prevVariables,
calcResult,
newVariableInsertIndex,
valueNode,
newVariableName,
setNewVariableName,
isNewVariableNameUnique,
} = useCalculateKclExpression({
value,
initialVariableName:
previouslySetValue && 'variableName' in previouslySetValue
? previouslySetValue.variableName
: arg.name,
})
const varMentionData: Completion[] = prevVariables.map((v) => ({
label: v.key,
detail: String(roundOff(v.value as number)),
}))
const { setContainer } = useCodeMirror({
container: editorRef.current,
value,
indentWithTab: false,
basicSetup: false,
autoFocus: true,
selection: {
anchor: 0,
head:
previouslySetValue && 'valueText' in previouslySetValue
? previouslySetValue.valueText.length
: defaultValue.length,
},
accessKey: 'command-bar',
theme:
settings.context.theme === 'system'
? getSystemTheme()
: settings.context.theme,
extensions: [
EditorView.domEventHandlers({
keydown: (event) => {
if (event.key === 'Backspace' && value === '') {
event.preventDefault()
stepBack()
}
},
}),
varMentions(varMentionData),
EditorState.transactionFilter.of((tr) => {
if (tr.newDoc.lines > 1) {
handleSubmit()
return []
}
return tr
}),
],
onChange: (newValue) => setValue(newValue),
})
useEffect(() => {
if (editorRef.current) {
setContainer(editorRef.current)
}
}, [arg, editorRef])
useEffect(() => {
setCanSubmit(
calcResult !== 'NAN' && (!createNewVariable || isNewVariableNameUnique)
)
}, [calcResult, createNewVariable, isNewVariableNameUnique])
function handleSubmit(e?: React.FormEvent<HTMLFormElement>) {
e?.preventDefault()
if (!canSubmit || valueNode === null) return
onSubmit(
createNewVariable
? ({
valueAst: valueNode,
valueText: value,
valueCalculated: calcResult,
variableName: newVariableName,
insertIndex: newVariableInsertIndex,
variableIdentifierAst: createIdentifier(newVariableName),
variableDeclarationAst: createVariableDeclaration(
newVariableName,
valueNode
),
} satisfies KclCommandValue)
: ({
valueAst: valueNode,
valueText: value,
valueCalculated: calcResult,
} satisfies KclCommandValue)
)
}
return (
<form id="arg-form" onSubmit={handleSubmit} data-can-submit={canSubmit}>
<label className="flex gap-4 items-center mx-4 my-4 border-solid border-b border-chalkboard-50">
<span className="capitalize text-chalkboard-80 dark:text-chalkboard-20">
{arg.name}
</span>
<div ref={editorRef} className={styles.editor} />
<CustomIcon
name="equal"
className="w-5 h-5 text-chalkboard-70 dark:text-chalkboard-40"
/>
<span
className={
calcResult === 'NAN'
? 'text-destroy-80 dark:text-destroy-40'
: 'text-energy-60 dark:text-energy-20'
}
>
{calcResult === 'NAN'
? "Can't calculate"
: roundOff(Number(calcResult), 4)}
</span>
</label>
{createNewVariable ? (
<div className="flex items-baseline gap-4 mx-4 border-solid border-0 border-b border-chalkboard-50">
<label
htmlFor="variable-name"
className="text-base text-chalkboard-80 dark:text-chalkboard-20"
>
Variable name
</label>
<input
type="text"
id="variable-name"
name="variable-name"
className="flex-1 border-none bg-transparent"
placeholder="Variable name"
value={newVariableName}
autoCapitalize="off"
autoCorrect="off"
autoComplete="off"
spellCheck="false"
autoFocus
onChange={(e) => setNewVariableName(e.target.value)}
onKeyDown={(e) => {
if (e.currentTarget.value === '' && e.key === 'Backspace') {
setCreateNewVariable(false)
}
}}
onKeyUp={(e) => {
if (e.key === 'Enter') {
handleSubmit()
}
}}
/>
<span
className={
isNewVariableNameUnique
? 'text-energy-60 dark:text-energy-20'
: 'text-destroy-60 dark:text-destroy-40'
}
>
{isNewVariableNameUnique ? 'Available' : 'Unavailable'}
</span>
</div>
) : (
<div className="flex justify-between gap-2 px-4">
<button
onClick={() => setCreateNewVariable(true)}
className="text-blue border-none bg-transparent font-sm flex gap-1 items-center pl-0 pr-1"
>
<CustomIcon name="plus" className="w-5 h-5" />
Create new variable
</button>
</div>
)}
</form>
)
}
export default CommandBarKclInput

View File

@ -14,7 +14,18 @@ function CommandBarReview({ stepBack }: { stepBack: () => void }) {
})
useHotkeys(
'1, 2, 3, 4, 5, 6, 7, 8, 9, 0',
[
'alt+1',
'alt+2',
'alt+3',
'alt+4',
'alt+5',
'alt+6',
'alt+7',
'alt+8',
'alt+9',
'alt+0',
],
(_, b) => {
if (b.keys && !Number.isNaN(parseInt(b.keys[0], 10))) {
if (!selectedCommand?.args) return

View File

@ -1,4 +1,5 @@
export type CustomIconName =
| 'arc'
| 'arrowDown'
| 'arrowLeft'
| 'arrowRight'
@ -17,11 +18,14 @@ export type CustomIconName =
| 'horizontal'
| 'horizontalDash'
| 'line'
| 'make-variable'
| 'move'
| 'network'
| 'networkCrossedOut'
| 'parallel'
| 'plus'
| 'search'
| 'settings'
| 'sketch'
| 'vertical'
@ -32,6 +36,22 @@ export const CustomIcon = ({
name: CustomIconName
} & React.SVGProps<SVGSVGElement>) => {
switch (name) {
case 'arc':
return (
<svg
{...props}
viewBox="0 0 20 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M10 1.5C8.60217 1.5 7.22591 1.84474 5.99313 2.50367C4.76035 3.1626 3.70911 4.1154 2.93251 5.27765C2.15592 6.43991 1.67794 7.77575 1.54093 9.16685C1.40392 10.558 1.6121 11.9614 2.14703 13.2528C2.68195 14.5442 3.52712 15.6838 4.60766 16.5706C5.6882 17.4574 6.97076 18.064 8.34173 18.3367C9.71271 18.6094 11.1298 18.5398 12.4674 18.134C13.8051 17.7282 15.022 16.9988 16.0104 16.0104C16.3068 15.714 16.5796 15.3974 16.8273 15.0634L16.0241 14.4677C15.8055 14.7624 15.5648 15.0418 15.3033 15.3033C14.4312 16.1754 13.3574 16.819 12.1771 17.1771C10.9969 17.5351 9.74651 17.5965 8.53682 17.3559C7.32714 17.1153 6.19547 16.58 5.24205 15.7976C4.28863 15.0151 3.5429 14.0096 3.07091 12.8701C2.59891 11.7306 2.41522 10.4923 2.53612 9.26487C2.65701 8.03743 3.07875 6.85874 3.76398 5.83322C4.44921 4.8077 5.37678 3.967 6.46453 3.38559C7.55227 2.80418 8.76662 2.5 10 2.5C10.3699 2.5 10.7376 2.52734 11.1005 2.58117L11.2472 1.59199C10.836 1.53099 10.4192 1.5 10 1.5ZM13.2067 3.22008C13.5383 3.37691 13.8593 3.5585 14.1668 3.76398C14.4743 3.96946 14.7649 4.19652 15.0367 4.44286L15.7083 3.70191C15.4002 3.42271 15.0709 3.16538 14.7223 2.93251C14.3738 2.69964 14.0101 2.49384 13.6342 2.31609L13.2067 3.22008ZM16.433 6.14423C16.6216 6.45886 16.7876 6.78818 16.9291 7.12987C17.0706 7.47157 17.1861 7.82181 17.2752 8.17765L18.2453 7.93467C18.1443 7.53138 18.0134 7.13444 17.853 6.74719C17.6926 6.35995 17.5044 5.98672 17.2907 5.63012L16.433 6.14423ZM17.491 10.368C17.473 10.7344 17.428 11.1004 17.3559 11.4632C17.2837 11.8259 17.1852 12.1813 17.0616 12.5267L18.0031 12.8636C18.1432 12.4721 18.2549 12.0694 18.3367 11.6583C18.4184 11.2472 18.4694 10.8323 18.4898 10.4171L17.491 10.368Z"
fill="currentColor"
/>
</svg>
)
case 'arrowDown':
return (
<svg
@ -318,6 +338,22 @@ export const CustomIcon = ({
/>
</svg>
)
case 'make-variable':
return (
<svg
{...props}
viewBox="0 0 20 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M4.07178 6.57735L9.99998 3.1547L15.9282 6.57735V13.4227L9.99998 16.8453L4.07178 13.4227V6.57735ZM9.99998 2L16.9282 6V14L9.99998 18L3.07178 14V6L9.99998 2ZM9.45068 6.854C9.20802 6.798 8.97468 6.78867 8.75068 6.826C8.39602 6.90067 8.06468 7.04533 7.75668 7.26C7.73802 7.26933 7.72402 7.27867 7.71468 7.288C7.45335 7.484 7.24802 7.694 7.09868 7.918C6.96802 8.09533 6.86068 8.282 6.77668 8.478C6.69268 8.65533 6.63668 8.814 6.60868 8.954C6.60868 9.00067 6.62268 9.038 6.65068 9.066L6.69268 9.108H6.95868C7.13602 9.108 7.23402 9.09867 7.25268 9.08C7.28068 9.052 7.30868 8.982 7.33668 8.87C7.45802 8.52467 7.65402 8.212 7.92468 7.932C8.13002 7.72667 8.36802 7.58667 8.63868 7.512C8.83468 7.456 9.02602 7.456 9.21268 7.512C9.40868 7.57733 9.53002 7.68467 9.57668 7.834C9.62335 7.96467 9.61402 8.198 9.54868 8.534L8.77868 11.614C8.65735 11.9593 8.47535 12.216 8.23268 12.384C8.10202 12.4587 7.97602 12.4913 7.85468 12.482C7.68668 12.482 7.53735 12.4307 7.40668 12.328L7.36468 12.286L7.42068 12.272C7.50468 12.244 7.57002 12.216 7.61668 12.188C7.93402 12.02 8.10668 11.7493 8.13468 11.376C8.15335 11.1053 8.05535 10.9187 7.84068 10.816C7.60735 10.6853 7.34135 10.69 7.04268 10.83C6.73468 10.9793 6.54802 11.2547 6.48268 11.656C6.45468 11.8893 6.47335 12.1087 6.53868 12.314C6.56668 12.4073 6.60868 12.4913 6.66468 12.566C6.92602 12.986 7.32268 13.182 7.85468 13.154C8.31202 13.126 8.72268 12.8787 9.08668 12.412L9.12868 12.37L9.21268 12.496C9.44602 12.8133 9.80068 13.0233 10.2767 13.126C10.5474 13.1633 10.79 13.1633 11.0047 13.126C11.6954 12.9767 12.2507 12.58 12.6707 11.936C12.6894 11.9173 12.7034 11.894 12.7127 11.866C12.9553 11.474 13.0767 11.18 13.0767 10.984C13.0767 10.9373 13.0674 10.9047 13.0487 10.886C13.0207 10.8673 12.918 10.858 12.7407 10.858C12.61 10.858 12.526 10.8627 12.4887 10.872C12.442 10.8813 12.4047 10.9327 12.3767 11.026C12.2834 11.3807 12.092 11.7073 11.8027 12.006C11.56 12.23 11.3174 12.3793 11.0747 12.454C11.0094 12.4727 10.9067 12.482 10.7667 12.482C10.6174 12.482 10.5194 12.4727 10.4727 12.454C10.314 12.398 10.1974 12.3 10.1227 12.16C10.0667 12.0573 10.062 11.8613 10.1087 11.572C10.1087 11.5347 10.132 11.4367 10.1787 11.278C10.58 9.542 10.8274 8.55733 10.9207 8.324C11.0887 7.88533 11.3127 7.61467 11.5927 7.512C11.6114 7.50267 11.63 7.498 11.6487 7.498C11.8914 7.43267 12.0967 7.47467 12.2647 7.624L12.3207 7.68L12.2087 7.722C11.8354 7.85267 11.6207 8.128 11.5647 8.548C11.5367 8.76267 11.5927 8.94 11.7327 9.08C11.77 9.11733 11.8167 9.15 11.8727 9.178C12.1714 9.32733 12.4887 9.28067 12.8247 9.038C12.9367 8.954 13.03 8.83267 13.1047 8.674C13.282 8.26333 13.2774 7.87133 13.0907 7.498C12.9787 7.26467 12.7874 7.078 12.5167 6.938C12.162 6.77933 11.8074 6.76533 11.4527 6.896C11.1447 7.01733 10.8787 7.20867 10.6547 7.47L10.5707 7.582C10.552 7.582 10.524 7.554 10.4867 7.498C10.2627 7.17133 9.91735 6.95667 9.45068 6.854Z"
fill="currentColor"
/>
</svg>
)
case 'move':
return (
<svg
@ -382,6 +418,22 @@ export const CustomIcon = ({
/>
</svg>
)
case 'plus':
return (
<svg
{...props}
viewBox="0 0 20 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M9.5 9.5V5.5H10.5V9.5H14.5V10.5H10.5V14.5H9.5V10.5H5.5V9.5H9.5Z"
fill="currentColor"
/>
</svg>
)
case 'search':
return (
<svg
@ -398,6 +450,22 @@ export const CustomIcon = ({
/>
</svg>
)
case 'settings':
return (
<svg
{...props}
viewBox="0 0 20 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fillRule="evenodd"
clipRule="evenodd"
d="M8 5.5C8 5.77614 7.77614 6 7.5 6C7.22386 6 7 5.77614 7 5.5C7 5.22386 7.22386 5 7.5 5C7.77614 5 8 5.22386 8 5.5ZM6.08535 6C6.29127 6.5826 6.84689 7 7.5 7C8.32843 7 9 6.32843 9 5.5C9 4.67157 8.32843 4 7.5 4C6.84689 4 6.29127 4.4174 6.08535 5H5V6H6.08535ZM15 6H9.94999C9.98278 5.83844 10 5.67123 10 5.5C10 5.32877 9.98278 5.16155 9.94999 5H15V6ZM11 14.5C11 14.7761 10.7761 15 10.5 15C10.2239 15 10 14.7761 10 14.5C10 14.2239 10.2239 14 10.5 14C10.7761 14 11 14.2239 11 14.5ZM9.08535 15C9.29127 15.5826 9.84689 16 10.5 16C11.3284 16 12 15.3284 12 14.5C12 13.6716 11.3284 13 10.5 13C9.84689 13 9.29127 13.4174 9.08535 14H5V15H9.08535ZM15 15H12.95C12.9828 14.8384 13 14.6712 13 14.5C13 14.3288 12.9828 14.1616 12.95 14H15V15ZM11.5 10.5C11.7761 10.5 12 10.2761 12 10C12 9.72386 11.7761 9.5 11.5 9.5C11.2239 9.5 11 9.72386 11 10C11 10.2761 11.2239 10.5 11.5 10.5ZM11.5 8.5C12.1531 8.5 12.7087 8.9174 12.9146 9.5H15V10.5H12.9146C12.7087 11.0826 12.1531 11.5 11.5 11.5C10.6716 11.5 10 10.8284 10 10C10 9.17157 10.6716 8.5 11.5 8.5ZM9.05001 10.5C9.01722 10.3384 9 10.1712 9 10C9 9.82877 9.01722 9.66155 9.05001 9.5H5V10.5H9.05001Z"
fill="currentColor"
/>
</svg>
)
case 'sketch':
return (
<svg

View File

@ -13,7 +13,7 @@ type OutputTypeKey = OutputFormat['type']
type ExtractStorageTypes<T> = T extends { storage: infer U } ? U : never
type StorageUnion = ExtractStorageTypes<OutputFormat>
interface ExportButtonProps extends React.PropsWithChildren {
export interface ExportButtonProps extends React.PropsWithChildren {
className?: {
button?: string
icon?: string

View File

@ -30,6 +30,12 @@ type GlobalContext = {
settings: MachineContext<typeof settingsMachine>
}
// a little hacky for sure, open to changing it
// this implies that we should only even have one instance of this provider mounted at any one time
// but I think that's a safe assumption
let settingsStateRef: (typeof settingsMachine)['context'] | undefined
export const getSettingsState = () => settingsStateRef
export const GlobalStateContext = createContext({} as GlobalContext)
export const GlobalStateProvider = ({
@ -71,6 +77,7 @@ export const GlobalStateProvider = ({
},
},
})
settingsStateRef = settingsState.context
useStateMachineCommands({
machineId: 'settings',

View File

@ -213,7 +213,7 @@ export const ModelingMachineProvider = ({
)
await kclManager.updateAst(modifiedAst, false)
const quaternion = getSketchQuaternion(pathToNode, normal)
await sceneInfra.tweenCameraToQuaternion(quaternion)
await sceneInfra.camControls.tweenCameraToQuaternion(quaternion)
return {
sketchPathToNode: pathToNode,
sketchNormalBackUp: normal,
@ -227,7 +227,7 @@ export const ModelingMachineProvider = ({
sketchPathToNode || [],
sketchNormalBackUp
)
await sceneInfra.tweenCameraToQuaternion(quaternion)
await sceneInfra.camControls.tweenCameraToQuaternion(quaternion)
},
'Get horizontal info': async ({
selectionRanges,
@ -374,6 +374,7 @@ export const ModelingMachineProvider = ({
send: modelingSend,
actor: modelingActor,
commandBarConfig: modelingMachineConfig,
allCommandsRequireNetwork: true,
onCancel: () => modelingSend({ type: 'Cancel' }),
})

View File

@ -80,7 +80,7 @@ const overallConnectionStateIcon: Record<
[NetworkHealthState.Disconnected]: 'networkCrossedOut',
}
export const NetworkHealthIndicator = () => {
export function useNetworkStatus() {
const [steps, setSteps] = useState(initialConnectingTypeGroupState)
const [internetConnected, setInternetConnected] = useState<boolean>(true)
const [overallState, setOverallState] = useState<NetworkHealthState>(
@ -118,18 +118,18 @@ export const NetworkHealthIndicator = () => {
}, [hasIssues, internetConnected])
useEffect(() => {
const cb1 = () => {
const onlineCallback = () => {
setSteps(initialConnectingTypeGroupState)
setInternetConnected(true)
}
const cb2 = () => {
const offlineCallback = () => {
setInternetConnected(false)
}
window.addEventListener('online', cb1)
window.addEventListener('offline', cb2)
window.addEventListener('online', onlineCallback)
window.addEventListener('offline', offlineCallback)
return () => {
window.removeEventListener('online', cb1)
window.removeEventListener('offline', cb2)
window.removeEventListener('online', onlineCallback)
window.removeEventListener('offline', offlineCallback)
}
}, [])
@ -183,6 +183,30 @@ export const NetworkHealthIndicator = () => {
)
}, [])
return {
hasIssues,
overallState,
internetConnected,
steps,
issues,
error,
setHasCopied,
hasCopied,
}
}
export const NetworkHealthIndicator = () => {
const {
hasIssues,
overallState,
internetConnected,
steps,
issues,
error,
setHasCopied,
hasCopied,
} = useNetworkStatus()
return (
<Popover className="relative">
<Popover.Button

View File

@ -3,8 +3,9 @@ import { BrowserRouter } from 'react-router-dom'
import ProjectSidebarMenu from './ProjectSidebarMenu'
import { type ProjectWithEntryPointMetadata } from 'lib/types'
import { GlobalStateProvider } from './GlobalStateProvider'
import CommandBarProvider from './CommandBar/CommandBar'
import { APP_NAME } from 'lib/constants'
import { vi } from 'vitest'
import { ExportButtonProps } from './ExportButton'
const now = new Date()
const projectWellFormed = {
@ -37,15 +38,22 @@ const projectWellFormed = {
},
} satisfies ProjectWithEntryPointMetadata
const mockExportButton = vi.fn()
vi.mock('/src/components/ExportButton', () => ({
// engineCommandManager method call in ExportButton causes vitest to hang
ExportButton: (props: ExportButtonProps) => {
mockExportButton(props)
return <button>Fake export button</button>
},
}))
describe('ProjectSidebarMenu tests', () => {
test('Renders the project name', () => {
render(
<BrowserRouter>
<CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu project={projectWellFormed} />
</GlobalStateProvider>
</CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu project={projectWellFormed} />
</GlobalStateProvider>
</BrowserRouter>
)
@ -62,11 +70,9 @@ describe('ProjectSidebarMenu tests', () => {
test('Renders app name if given no project', () => {
render(
<BrowserRouter>
<CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu />
</GlobalStateProvider>
</CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu />
</GlobalStateProvider>
</BrowserRouter>
)
@ -78,14 +84,9 @@ describe('ProjectSidebarMenu tests', () => {
test('Renders as a link if set to do so', () => {
render(
<BrowserRouter>
<CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu
project={projectWellFormed}
renderAsLink={true}
/>
</GlobalStateProvider>
</CommandBarProvider>
<GlobalStateProvider>
<ProjectSidebarMenu project={projectWellFormed} renderAsLink={true} />
</GlobalStateProvider>
</BrowserRouter>
)

View File

@ -5,10 +5,10 @@ import { Value } from '../lang/wasm'
import {
AvailableVars,
addToInputHelper,
useCalc,
CalcResult,
CreateNewVariable,
} from './AvailableVarsHelpers'
import { useCalculateKclExpression } from 'lib/useCalculateKclExpression'
type ModalResolve = {
value: string
@ -55,7 +55,7 @@ export const SetAngleLengthModal = ({
setNewVariableName,
inputRef,
newVariableInsertIndex,
} = useCalc({
} = useCalculateKclExpression({
value,
initialVariableName: valueName,
})

View File

@ -5,10 +5,10 @@ import { Value } from '../lang/wasm'
import {
AvailableVars,
addToInputHelper,
useCalc,
CalcResult,
CreateNewVariable,
} from './AvailableVarsHelpers'
import { useCalculateKclExpression } from 'lib/useCalculateKclExpression'
type ModalResolve = {
value: string
@ -59,7 +59,7 @@ export const GetInfoModal = ({
newVariableName,
isNewVariableNameUnique,
newVariableInsertIndex,
} = useCalc({ value: value, initialVariableName })
} = useCalculateKclExpression({ value: value, initialVariableName })
return (
<Transition appear show={isOpen} as={Fragment}>

View File

@ -1,10 +1,11 @@
import { Dialog, Transition } from '@headlessui/react'
import { Fragment } from 'react'
import { useCalc, CreateNewVariable } from './AvailableVarsHelpers'
import { CreateNewVariable } from './AvailableVarsHelpers'
import { ActionButton } from './ActionButton'
import { faPlus } from '@fortawesome/free-solid-svg-icons'
import { toast } from 'react-hot-toast'
import { type InstanceProps, create } from 'react-modal-promise'
import { useCalculateKclExpression } from 'lib/useCalculateKclExpression'
type ModalResolve = { variableName: string }
type ModalReject = boolean
@ -25,7 +26,7 @@ export const SetVarNameModal = ({
valueName,
}: SetVarNameModalProps) => {
const { isNewVariableNameUnique, newVariableName, setNewVariableName } =
useCalc({ value: '', initialVariableName: valueName })
useCalculateKclExpression({ value: '', initialVariableName: valueName })
return (
<Transition appear show={isOpen} as={Fragment}>

View File

@ -16,6 +16,7 @@ import { engineCommandManager } from '../lang/std/engineConnection'
import { useModelingContext } from 'hooks/useModelingContext'
import { useKclContext } from 'lang/KclSingleton'
import { ClientSideScene } from 'clientSideScene/ClientSideSceneComp'
import { NetworkHealthState, useNetworkStatus } from './NetworkHealthIndicator'
export const Stream = ({ className = '' }: { className?: string }) => {
const [isLoading, setIsLoading] = useState(true)
@ -38,6 +39,8 @@ export const Stream = ({ className = '' }: { className?: string }) => {
const cameraControls = settings?.context?.cameraControls
const { state } = useModelingContext()
const { isExecuting } = useKclContext()
const { overallState } = useNetworkStatus()
const isNetworkOkay = overallState === NetworkHealthState.Ok
useEffect(() => {
if (
@ -164,6 +167,13 @@ export const Stream = ({ className = '' }: { className?: string }) => {
style={{ transitionDuration: '200ms', transitionProperty: 'filter' }}
/>
<ClientSideScene cameraControls={settings.context.cameraControls} />
{!isNetworkOkay && !isLoading && (
<div className="text-center absolute inset-0">
<Loading>
<span data-testid="loading-stream">Stream disconnected</span>
</Loading>
</div>
)}
{isLoading && (
<div className="text-center absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2">
<Loading>

View File

@ -1,22 +1,23 @@
import { undo, redo } from '@codemirror/commands'
import ReactCodeMirror, {
Extension,
ViewUpdate,
keymap,
} from '@uiw/react-codemirror'
import { FromServer, IntoServer } from 'editor/lsp/codec'
import Server from '../editor/lsp/server'
import Client from '../editor/lsp/client'
import { FromServer, IntoServer } from 'editor/plugins/lsp/codec'
import Server from '../editor/plugins/lsp/server'
import Client from '../editor/plugins/lsp/client'
import { TEST } from 'env'
import { useCommandsContext } from 'hooks/useCommandsContext'
import { useGlobalStateContext } from 'hooks/useGlobalStateContext'
import { useConvertToVariable } from 'hooks/useToolbarGuards'
import { Themes } from 'lib/theme'
import { useMemo, useRef } from 'react'
import { useEffect, useMemo, useRef } from 'react'
import { linter, lintGutter } from '@codemirror/lint'
import { useStore } from 'useStore'
import { processCodeMirrorRanges } from 'lib/selections'
import { LanguageServerClient } from 'editor/lsp'
import kclLanguage from 'editor/lsp/language'
import { LanguageServerClient } from 'editor/plugins/lsp'
import kclLanguage from 'editor/plugins/lsp/kcl/language'
import { EditorView, lineHighlightField } from 'editor/highlightextension'
import { roundOff } from 'lib/utils'
import { kclErrToDiagnostic } from 'lang/errors'
@ -25,9 +26,14 @@ import { useModelingContext } from 'hooks/useModelingContext'
import interact from '@replit/codemirror-interact'
import { engineCommandManager } from '../lang/std/engineConnection'
import { kclManager, useKclContext } from 'lang/KclSingleton'
import { useFileContext } from 'hooks/useFileContext'
import { ModelingMachineEvent } from 'machines/modelingMachine'
import { sceneInfra } from 'clientSideScene/sceneInfra'
import { copilotBundle } from 'editor/copilot'
import { copilotPlugin } from 'editor/plugins/lsp/copilot'
import { isTauri } from 'lib/isTauri'
import type * as LSP from 'vscode-languageserver-protocol'
import { NetworkHealthState, useNetworkStatus } from './NetworkHealthIndicator'
import { useHotkeys } from 'react-hotkeys-hook'
export const editorShortcutMeta = {
formatCode: {
@ -40,6 +46,15 @@ export const editorShortcutMeta = {
},
}
function getWorkspaceFolders(): LSP.WorkspaceFolder[] {
// We only use workspace folders in Tauri since that is where we use more than
// one file.
if (isTauri()) {
return [{ uri: 'file://', name: 'ProjectRoot' }]
}
return []
}
export const TextEditor = ({
theme,
}: {
@ -64,6 +79,28 @@ export const TextEditor = ({
}))
const { code, errors } = useKclContext()
const lastEvent = useRef({ event: '', time: Date.now() })
const { overallState } = useNetworkStatus()
const isNetworkOkay = overallState === NetworkHealthState.Ok
useEffect(() => {
if (typeof window === 'undefined') return
const onlineCallback = () => kclManager.setCodeAndExecute(kclManager.code)
window.addEventListener('online', onlineCallback)
return () => window.removeEventListener('online', onlineCallback)
}, [])
useHotkeys('mod+z', (e) => {
e.preventDefault()
if (editorView) {
undo(editorView)
}
})
useHotkeys('mod+shift+z', (e) => {
e.preventDefault()
if (editorView) {
redo(editorView)
}
})
const {
context: { selectionRanges, selectionRangeTypeMap },
@ -74,6 +111,9 @@ export const TextEditor = ({
const { settings: { context: { textWrapping } = {} } = {}, auth } =
useGlobalStateContext()
const { commandBarSend } = useCommandsContext()
const {
context: { project },
} = useFileContext()
const { enable: convertEnabled, handleClick: convertCallback } =
useConvertToVariable()
@ -91,12 +131,12 @@ export const TextEditor = ({
})
}
const lspClient = new LanguageServerClient({ client })
const lspClient = new LanguageServerClient({ client, name: 'kcl' })
return { lspClient }
}, [setIsKclLspServerReady])
// Here we initialize the plugin which will start the client.
// When we have multi-file support the name of the file will be a dep of
// Now that we have multi-file support the name of the file is a dep of
// this use memo, as well as the directory structure, which I think is
// a good setup because it will restart the client but not the server :)
// We do not want to restart the server, its just wasteful.
@ -107,7 +147,7 @@ export const TextEditor = ({
const lsp = kclLanguage({
// When we have more than one file, we'll need to change this.
documentUri: `file:///we-just-have-one-file-for-now.kcl`,
workspaceFolders: null,
workspaceFolders: getWorkspaceFolders(),
client: kclLspClient,
})
@ -128,7 +168,7 @@ export const TextEditor = ({
})
}
const lspClient = new LanguageServerClient({ client })
const lspClient = new LanguageServerClient({ client, name: 'copilot' })
return { lspClient }
}, [setIsCopilotLspServerReady])
@ -141,10 +181,10 @@ export const TextEditor = ({
let plugin = null
if (isCopilotLspServerReady && !TEST) {
// Set up the lsp plugin.
const lsp = copilotBundle({
const lsp = copilotPlugin({
// When we have more than one file, we'll need to change this.
documentUri: `file:///we-just-have-one-file-for-now.kcl`,
workspaceFolders: null,
workspaceFolders: getWorkspaceFolders(),
client: copilotLspClient,
allowHTMLContent: true,
})
@ -152,11 +192,12 @@ export const TextEditor = ({
plugin = lsp
}
return plugin
}, [copilotLspClient, isCopilotLspServerReady])
}, [copilotLspClient, isCopilotLspServerReady, project])
// const onChange = React.useCallback((value: string, viewUpdate: ViewUpdate) => {
const onChange = (newCode: string) => {
kclManager.setCodeAndExecute(newCode)
const onChange = async (newCode: string) => {
if (isNetworkOkay) kclManager.setCodeAndExecute(newCode)
else kclManager.setCode(newCode)
} //, []);
const onUpdate = (viewUpdate: ViewUpdate) => {
if (!editorView) {

View File

@ -117,7 +117,7 @@ const UserSidebarMenu = ({ user }: { user?: User }) => {
<div className="p-4 flex flex-col gap-2">
<ActionButton
Element="button"
icon={{ icon: 'gear' }}
icon={{ icon: 'settings' }}
className="border-transparent dark:border-transparent hover:bg-transparent"
onClick={() => {
// since /settings is a nested route the sidebar doesn't close
@ -142,7 +142,7 @@ const UserSidebarMenu = ({ user }: { user?: User }) => {
</ActionButton>
<ActionButton
Element="externalLink"
to="https://github.com/KittyCAD/modeling-app/issues/new"
to="https://github.com/KittyCAD/modeling-app/issues/new/choose"
icon={{ icon: faBug, className: 'p-1', size: 'sm' }}
className="border-transparent dark:border-transparent"
>

View File

@ -65,6 +65,7 @@ export default class Client extends jsrpc.JSONRPCServerAndClient {
afterInitializedHooks: (() => Promise<void>)[] = []
#fromServer: FromServer
private serverCapabilities: LSP.ServerCapabilities<any> = {}
private notifyFn: ((message: LSP.NotificationMessage) => void) | null = null
constructor(fromServer: FromServer, intoServer: IntoServer) {
super(
@ -167,9 +168,15 @@ export default class Client extends jsrpc.JSONRPCServerAndClient {
return this.serverCapabilities
}
setNotifyFn(fn: (message: LSP.NotificationMessage) => void): void {
this.notifyFn = fn
}
async processNotifications(): Promise<void> {
for await (const notification of this.#fromServer.notifications) {
await this.receiveAndSend(notification)
if (this.notifyFn) {
this.notifyFn(notification)
}
}
}

View File

@ -11,30 +11,20 @@ import {
Annotation,
EditorState,
Extension,
Facet,
Prec,
StateEffect,
StateField,
Transaction,
} from '@codemirror/state'
import { completionStatus } from '@codemirror/autocomplete'
import { docPathFacet, offsetToPos, posToOffset } from 'editor/lsp/util'
import { LanguageServerPlugin } from 'editor/lsp/plugin'
import { LanguageServerOptions } from 'editor/lsp/plugin'
import { LanguageServerClient } from 'editor/lsp'
// Create Facet for the current docPath
export const docPath = Facet.define<string, string>({
combine(value: readonly string[]) {
return value[value.length - 1]
},
})
export const relDocPath = Facet.define<string, string>({
combine(value: readonly string[]) {
return value[value.length - 1]
},
})
import { offsetToPos, posToOffset } from 'editor/plugins/lsp/util'
import { LanguageServerOptions, LanguageServerClient } from 'editor/plugins/lsp'
import {
LanguageServerPlugin,
documentUri,
languageId,
workspaceFolders,
} from 'editor/plugins/lsp/plugin'
const ghostMark = Decoration.mark({ class: 'cm-ghostText' })
@ -361,9 +351,9 @@ const completionRequester = (client: LanguageServerClient) => {
const pos = state.selection.main.head
const source = state.doc.toString()
const path = state.facet(docPath)
const relativePath = state.facet(relDocPath)
const languageId = 'kcl'
const dUri = state.facet(documentUri)
const path = dUri.split('/').pop()!
const relativePath = dUri.replace('file://', '')
// Set a new timeout to request completion
timeout = setTimeout(async () => {
@ -378,9 +368,9 @@ const completionRequester = (client: LanguageServerClient) => {
indentSize: 1,
insertSpaces: true,
path,
uri: `file://${path}`,
uri: dUri,
relativePath,
languageId,
languageId: state.facet(languageId),
position: offsetToPos(state.doc, pos),
},
})
@ -483,21 +473,24 @@ const completionRequester = (client: LanguageServerClient) => {
})
}
export function copilotServer(options: LanguageServerOptions) {
let plugin: LanguageServerPlugin
return ViewPlugin.define(
(view) =>
(plugin = new LanguageServerPlugin(view, options.allowHTMLContent))
)
}
export const copilotPlugin = (options: LanguageServerOptions): Extension => {
let plugin: LanguageServerPlugin | null = null
export const copilotBundle = (options: LanguageServerOptions): Extension => [
docPath.of(options.documentUri.split('/').pop()!),
docPathFacet.of(options.documentUri.split('/').pop()!),
relDocPath.of(options.documentUri.replace('file://', '')),
completionDecoration,
Prec.highest(completionPlugin(options.client)),
Prec.highest(viewCompletionPlugin(options.client)),
completionRequester(options.client),
copilotServer(options),
]
return [
documentUri.of(options.documentUri),
languageId.of('kcl'),
workspaceFolders.of(options.workspaceFolders),
ViewPlugin.define(
(view) =>
(plugin = new LanguageServerPlugin(
options.client,
view,
options.allowHTMLContent
))
),
completionDecoration,
Prec.highest(completionPlugin(options.client)),
Prec.highest(viewCompletionPlugin(options.client)),
completionRequester(options.client),
]
}

View File

@ -1,7 +1,7 @@
import type * as LSP from 'vscode-languageserver-protocol'
import Client from './client'
import { LanguageServerPlugin } from './plugin'
import { SemanticToken, deserializeTokens } from './semantic_tokens'
import { SemanticToken, deserializeTokens } from './kcl/semantic_tokens'
import { LanguageServerPlugin } from 'editor/plugins/lsp/plugin'
export interface CopilotGetCompletionsParams {
doc: {
@ -90,26 +90,22 @@ interface LSPNotifyMap {
'textDocument/didOpen': LSP.DidOpenTextDocumentParams
}
// Server to client
interface LSPEventMap {
'textDocument/publishDiagnostics': LSP.PublishDiagnosticsParams
}
export type Notification = {
[key in keyof LSPEventMap]: {
jsonrpc: '2.0'
id?: null | undefined
method: key
params: LSPEventMap[key]
}
}[keyof LSPEventMap]
export interface LanguageServerClientOptions {
client: Client
name: string
}
export interface LanguageServerOptions {
// We assume this is the main project directory, we are currently working in.
workspaceFolders: LSP.WorkspaceFolder[]
documentUri: string
allowHTMLContent: boolean
client: LanguageServerClient
}
export class LanguageServerClient {
private client: Client
private name: string
public ready: boolean
@ -124,6 +120,7 @@ export class LanguageServerClient {
constructor(options: LanguageServerClientOptions) {
this.plugins = []
this.client = options.client
this.name = options.name
this.ready = false
@ -133,11 +130,16 @@ export class LanguageServerClient {
async initialize() {
// Start the client in the background.
this.client.setNotifyFn(this.processNotifications.bind(this))
this.client.start()
this.ready = true
}
getName(): string {
return this.name
}
getServerCapabilities(): LSP.ServerCapabilities<any> {
return this.client.getServerCapabilities()
}
@ -156,6 +158,11 @@ export class LanguageServerClient {
}
async updateSemanticTokens(uri: string) {
const serverCapabilities = this.getServerCapabilities()
if (!serverCapabilities.semanticTokensProvider) {
return
}
// Make sure we can only run, if we aren't already running.
if (!this.isUpdatingSemanticTokens) {
this.isUpdatingSemanticTokens = true
@ -180,10 +187,18 @@ export class LanguageServerClient {
}
async textDocumentHover(params: LSP.HoverParams) {
const serverCapabilities = this.getServerCapabilities()
if (!serverCapabilities.hoverProvider) {
return
}
return await this.request('textDocument/hover', params)
}
async textDocumentCompletion(params: LSP.CompletionParams) {
const serverCapabilities = this.getServerCapabilities()
if (!serverCapabilities.completionProvider) {
return
}
return await this.request('textDocument/completion', params)
}
@ -234,11 +249,12 @@ export class LanguageServerClient {
async acceptCompletion(params: CopilotAcceptCompletionParams) {
return await this.request('notifyAccepted', params)
}
async rejectCompletions(params: CopilotRejectCompletionParams) {
return await this.request('notifyRejected', params)
}
private processNotification(notification: Notification) {
private processNotifications(notification: LSP.NotificationMessage) {
for (const plugin of this.plugins) plugin.processNotification(notification)
}
}

View File

@ -0,0 +1,75 @@
import { autocompletion } from '@codemirror/autocomplete'
import { Extension } from '@codemirror/state'
import { ViewPlugin, hoverTooltip, tooltips } from '@codemirror/view'
import { CompletionTriggerKind } from 'vscode-languageserver-protocol'
import { offsetToPos } from 'editor/plugins/lsp/util'
import { LanguageServerOptions } from 'editor/plugins/lsp'
import {
LanguageServerPlugin,
documentUri,
languageId,
workspaceFolders,
} from 'editor/plugins/lsp/plugin'
export function kclPlugin(options: LanguageServerOptions): Extension {
let plugin: LanguageServerPlugin | null = null
return [
documentUri.of(options.documentUri),
languageId.of('kcl'),
workspaceFolders.of(options.workspaceFolders),
ViewPlugin.define(
(view) =>
(plugin = new LanguageServerPlugin(
options.client,
view,
options.allowHTMLContent
))
),
hoverTooltip(
(view, pos) =>
plugin?.requestHoverTooltip(view, offsetToPos(view.state.doc, pos)) ??
null
),
tooltips({
position: 'absolute',
}),
autocompletion({
override: [
async (context) => {
if (plugin == null) return null
const { state, pos, explicit } = context
const line = state.doc.lineAt(pos)
let trigKind: CompletionTriggerKind = CompletionTriggerKind.Invoked
let trigChar: string | undefined
if (
!explicit &&
plugin.client
.getServerCapabilities()
.completionProvider?.triggerCharacters?.includes(
line.text[pos - line.from - 1]
)
) {
trigKind = CompletionTriggerKind.TriggerCharacter
trigChar = line.text[pos - line.from - 1]
}
if (
trigKind === CompletionTriggerKind.Invoked &&
!context.matchBefore(/\w+$/)
) {
return null
}
return await plugin.requestCompletion(
context,
offsetToPos(state.doc, pos),
{
triggerKind: trigKind,
triggerCharacter: trigChar,
}
)
},
],
}),
]
}

View File

@ -5,8 +5,8 @@ import {
defineLanguageFacet,
LanguageSupport,
} from '@codemirror/language'
import { LanguageServerClient } from '.'
import { kclPlugin } from './plugin'
import { LanguageServerClient } from 'editor/plugins/lsp'
import { kclPlugin } from '.'
import type * as LSP from 'vscode-languageserver-protocol'
import { parser as jsParser } from '@lezer/javascript'
import { EditorState } from '@uiw/react-codemirror'
@ -14,7 +14,7 @@ import { EditorState } from '@uiw/react-codemirror'
const data = defineLanguageFacet({})
export interface LanguageOptions {
workspaceFolders: LSP.WorkspaceFolder[] | null
workspaceFolders: LSP.WorkspaceFolder[]
documentUri: string
client: LanguageServerClient
}

View File

@ -9,8 +9,8 @@ import {
NodeType,
NodeSet,
} from '@lezer/common'
import { LanguageServerClient } from '.'
import { posToOffset } from 'editor/lsp/util'
import { LanguageServerClient } from 'editor/plugins/lsp'
import { posToOffset } from 'editor/plugins/lsp/util'
import { SemanticToken } from './semantic_tokens'
import { DocInput } from '@codemirror/language'
import { tags, styleTags } from '@lezer/highlight'

View File

@ -1,13 +1,7 @@
import { autocompletion, completeFromList } from '@codemirror/autocomplete'
import { completeFromList } from '@codemirror/autocomplete'
import { setDiagnostics } from '@codemirror/lint'
import { Facet } from '@codemirror/state'
import {
EditorView,
ViewPlugin,
Tooltip,
hoverTooltip,
tooltips,
} from '@codemirror/view'
import { EditorView, Tooltip } from '@codemirror/view'
import {
DiagnosticSeverity,
CompletionItemKind,
@ -23,9 +17,17 @@ import type {
import type { PublishDiagnosticsParams } from 'vscode-languageserver-protocol'
import type { ViewUpdate, PluginValue } from '@codemirror/view'
import type * as LSP from 'vscode-languageserver-protocol'
import { LanguageServerClient, Notification } from '.'
import { LanguageServerClient } from 'editor/plugins/lsp'
import { Marked } from '@ts-stack/markdown'
import { offsetToPos, posToOffset } from 'editor/lsp/util'
import { posToOffset } from 'editor/plugins/lsp/util'
const useLast = (values: readonly any[]) => values.reduce((_, v) => v, '')
export const documentUri = Facet.define<string, string>({ combine: useLast })
export const languageId = Facet.define<string, string>({ combine: useLast })
export const workspaceFolders = Facet.define<
LSP.WorkspaceFolder[],
LSP.WorkspaceFolder[]
>({ combine: useLast })
const changesDelay = 500
@ -33,31 +35,22 @@ const CompletionItemKindMap = Object.fromEntries(
Object.entries(CompletionItemKind).map(([key, value]) => [value, key])
) as Record<CompletionItemKind, string>
const useLast = (values: readonly any[]) => values.reduce((_, v) => v, '')
const documentUri = Facet.define<string, string>({ combine: useLast })
const languageId = Facet.define<string, string>({ combine: useLast })
const client = Facet.define<LanguageServerClient, LanguageServerClient>({
combine: useLast,
})
export interface LanguageServerOptions {
workspaceFolders: LSP.WorkspaceFolder[] | null
documentUri: string
allowHTMLContent: boolean
client: LanguageServerClient
}
export class LanguageServerPlugin implements PluginValue {
public client: LanguageServerClient
private documentUri: string
private languageId: string
private workspaceFolders: LSP.WorkspaceFolder[]
private documentVersion: number
constructor(private view: EditorView, private allowHTMLContent: boolean) {
this.client = this.view.state.facet(client)
constructor(
client: LanguageServerClient,
private view: EditorView,
private allowHTMLContent: boolean
) {
this.client = client
this.documentUri = this.view.state.facet(documentUri)
this.languageId = this.view.state.facet(languageId)
this.workspaceFolders = this.view.state.facet(workspaceFolders)
this.documentVersion = 0
this.client.attachPlugin(this)
@ -238,11 +231,28 @@ export class LanguageServerPlugin implements PluginValue {
return completeFromList(options)(context)
}
processNotification(notification: Notification) {
processNotification(notification: LSP.NotificationMessage) {
try {
switch (notification.method) {
case 'textDocument/publishDiagnostics':
this.processDiagnostics(notification.params)
this.processDiagnostics(
notification.params as PublishDiagnosticsParams
)
break
case 'window/logMessage':
console.log(
'[lsp] [window/logMessage]',
this.client.getName(),
notification.params
)
break
case 'window/showMessage':
console.log(
'[lsp] [window/showMessage]',
this.client.getName(),
notification.params
)
break
}
} catch (error) {
console.error(error)
@ -284,65 +294,6 @@ export class LanguageServerPlugin implements PluginValue {
}
}
export function kclPlugin(options: LanguageServerOptions) {
let plugin: LanguageServerPlugin | null = null
return [
client.of(options.client),
documentUri.of(options.documentUri),
languageId.of('kcl'),
ViewPlugin.define(
(view) =>
(plugin = new LanguageServerPlugin(view, options.allowHTMLContent))
),
hoverTooltip(
(view, pos) =>
plugin?.requestHoverTooltip(view, offsetToPos(view.state.doc, pos)) ??
null
),
tooltips({
position: 'absolute',
}),
autocompletion({
override: [
async (context) => {
if (plugin == null) return null
const { state, pos, explicit } = context
const line = state.doc.lineAt(pos)
let trigKind: CompletionTriggerKind = CompletionTriggerKind.Invoked
let trigChar: string | undefined
if (
!explicit &&
plugin.client
.getServerCapabilities()
.completionProvider?.triggerCharacters?.includes(
line.text[pos - line.from - 1]
)
) {
trigKind = CompletionTriggerKind.TriggerCharacter
trigChar = line.text[pos - line.from - 1]
}
if (
trigKind === CompletionTriggerKind.Invoked &&
!context.matchBefore(/\w+$/)
) {
return null
}
return await plugin.requestCompletion(
context,
offsetToPos(state.doc, pos),
{
triggerKind: trigKind,
triggerCharacter: trigChar,
}
)
},
],
}),
]
}
function formatContents(
contents: LSP.MarkupContent | LSP.MarkedString | LSP.MarkedString[]
): string {

View File

@ -34,6 +34,8 @@ const ServerCapabilitiesProviders: IMethodServerCapabilityProviderDictionary = {
'textDocument/foldingRange': 'foldingRangeProvider',
'textDocument/declaration': 'declarationProvider',
'textDocument/executeCommand': 'executeCommandProvider',
'textDocument/semanticTokens/full': 'semanticTokensProvider',
'textDocument/publishDiagnostics': 'diagnosticsProvider',
}
function registerServerCapability(

View File

@ -3,8 +3,9 @@ import init, {
InitOutput,
kcl_lsp_run,
ServerConfig,
} from '../../wasm-lib/pkg/wasm_lib'
} from 'wasm-lib/pkg/wasm_lib'
import { FromServer, IntoServer } from './codec'
import { fileSystemManager } from 'lang/std/fileSystemManager'
export default class Server {
readonly initOutput: InitOutput
@ -31,7 +32,11 @@ export default class Server {
}
async start(type_: 'kcl' | 'copilot', token?: string): Promise<void> {
const config = new ServerConfig(this.#intoServer, this.#fromServer)
const config = new ServerConfig(
this.#intoServer,
this.#fromServer,
fileSystemManager
)
if (type_ === 'copilot') {
if (!token) {
throw new Error('auth token is required for copilot')

View File

@ -1,4 +1,4 @@
import { Facet, Text } from '@codemirror/state'
import { Text } from '@codemirror/state'
export function posToOffset(
doc: Text,
@ -17,7 +17,3 @@ export function offsetToPos(doc: Text, offset: number) {
character: offset - line.from,
}
}
export const docPathFacet = Facet.define<string, string>({
combine: (values) => values[values.length - 1],
})

View File

@ -7,6 +7,12 @@ import { authMachine } from 'machines/authMachine'
import { settingsMachine } from 'machines/settingsMachine'
import { homeMachine } from 'machines/homeMachine'
import { Command, CommandSetConfig, CommandSetSchema } from 'lib/commandTypes'
import {
NetworkHealthState,
useNetworkStatus,
} from 'components/NetworkHealthIndicator'
import { useKclContext } from 'lang/KclSingleton'
import { useStore } from 'useStore'
// This might not be necessary, AnyStateMachine from xstate is working
export type AllMachines =
@ -24,6 +30,7 @@ interface UseStateMachineCommandsArgs<
send: Function
actor?: InterpreterFrom<T>
commandBarConfig?: CommandSetConfig<T, S>
allCommandsRequireNetwork?: boolean
onCancel?: () => void
}
@ -36,12 +43,21 @@ export default function useStateMachineCommands<
send,
actor,
commandBarConfig,
allCommandsRequireNetwork = false,
onCancel,
}: UseStateMachineCommandsArgs<T, S>) {
const { commandBarSend } = useCommandsContext()
const { overallState } = useNetworkStatus()
const { isExecuting } = useKclContext()
const { isStreamReady } = useStore((s) => ({
isStreamReady: s.isStreamReady,
}))
useEffect(() => {
const disableAllButtons =
overallState !== NetworkHealthState.Ok || isExecuting || !isStreamReady
const newCommands = state.nextEvents
.filter((_) => !allCommandsRequireNetwork || !disableAllButtons)
.filter((e) => !['done.', 'error.'].some((n) => e.includes(n)))
.map((type) =>
createMachineCommand<T, S>({
@ -64,5 +80,5 @@ export default function useStateMachineCommands<
data: { commands: newCommands },
})
}
}, [state])
}, [state, overallState, isExecuting, isStreamReady])
}

View File

@ -211,7 +211,7 @@ class KclManager {
console.error('error parsing code', e)
if (e instanceof KCLError) {
this.kclErrors = [e]
if (e.msg === 'file is empty') engineCommandManager.endSession()
if (e.msg === 'file is empty') engineCommandManager?.endSession()
}
return null
}
@ -239,8 +239,8 @@ class KclManager {
const currentExecutionId = executionId || Date.now()
this._cancelTokens.set(currentExecutionId, false)
await this.ensureWasmInit()
this.isExecuting = true
await this.ensureWasmInit()
const { logs, errors, programMemory } = await executeAst({
ast,
engineCommandManager: this.engineCommandManager,

View File

@ -1,4 +1,4 @@
import { parse, recast, initPromise } from './wasm'
import { parse, recast, initPromise, Identifier } from './wasm'
import {
createLiteral,
createIdentifier,
@ -90,7 +90,17 @@ describe('Testing createPipeExpression', () => {
describe('Testing findUniqueName', () => {
it('should find a unique name', () => {
const result = findUniqueName(
'yo01 yo02 yo03 yo04 yo05 yo06 yo07 yo08 yo09',
JSON.stringify([
{ type: 'Identifier', name: 'yo01', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo02', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo03', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo04', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo05', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo06', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo07', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo08', start: 0, end: 0 },
{ type: 'Identifier', name: 'yo09', start: 0, end: 0 },
] satisfies Identifier[]),
'yo',
2
)

View File

@ -162,18 +162,32 @@ export function findUniqueName(
pad = 3,
index = 1
): string {
let searchStr = ''
if (typeof ast === 'string') {
searchStr = ast
} else {
searchStr = JSON.stringify(ast)
let searchStr: string = typeof ast === 'string' ? ast : JSON.stringify(ast)
const indexStr = String(index).padStart(pad, '0')
const endingDigitsMatcher = /\d+$/
const nameEndsInDigits = name.match(endingDigitsMatcher)
let nameIsInString = searchStr.includes(`:"${name}"`)
if (nameEndsInDigits !== null) {
// base case: name is unique and ends in digits
if (!nameIsInString) return name
// recursive case: name is not unique and ends in digits
const newPad = nameEndsInDigits[1].length
const newIndex = parseInt(nameEndsInDigits[1]) + 1
const nameWithoutDigits = name.replace(endingDigitsMatcher, '')
return findUniqueName(searchStr, nameWithoutDigits, newPad, newIndex)
}
const indexStr = `${index}`.padStart(pad, '0')
const newName = `${name}${indexStr}`
const isInString = searchStr.includes(newName)
if (!isInString) {
return newName
}
nameIsInString = searchStr.includes(`:"${newName}"`)
// base case: name is unique and does not end in digits
if (!nameIsInString) return newName
// recursive case: name is not unique and does not end in digits
return findUniqueName(searchStr, name, pad, index + 1)
}
@ -273,7 +287,7 @@ export function extrudeSketch(
node: Program,
pathToNode: PathToNode,
shouldPipe = true,
distance = 4
distance = createLiteral(4) as Value
): {
modifiedAst: Program
pathToNode: PathToNode
@ -299,7 +313,7 @@ export function extrudeSketch(
getNodeFromPath<VariableDeclarator>(_node, pathToNode, 'VariableDeclarator')
const extrudeCall = createCallExpressionStdLib('extrude', [
createLiteral(distance),
distance,
shouldPipe
? createPipeSubstitution()
: {

View File

@ -996,9 +996,6 @@ export class EngineCommandManager {
}
},
onEngineConnectionOpen: () => {
this.resolveReady()
setIsStreamReady(true)
// Make the axis gizmo.
// We do this after the connection opened to avoid a race condition.
// Connected opened is the last thing that happens when the stream
@ -1017,9 +1014,11 @@ export class EngineCommandManager {
gizmo_mode: true,
},
})
sceneInfra.onStreamStart()
sceneInfra.camControls.onCameraChange()
this.initPlanes().then(() => {
this.resolveReady()
setIsStreamReady(true)
executeCode(undefined, true)
})
},

View File

@ -1,4 +1,8 @@
import { readBinaryFile, exists as tauriExists } from '@tauri-apps/api/fs'
import {
readDir,
readBinaryFile,
exists as tauriExists,
} from '@tauri-apps/api/fs'
import { isTauri } from 'lib/isTauri'
import { join } from '@tauri-apps/api/path'
@ -53,6 +57,30 @@ class FileSystemManager {
return tauriExists(file)
})
}
getAllFiles(path: string): Promise<string[] | void> {
// Using local file system only works from Tauri.
if (!isTauri()) {
throw new Error(
'This function can only be called from a Tauri application'
)
}
return join(this.dir, path)
.catch((error) => {
throw new Error(`Error joining dir: ${error}`)
})
.then((p) => {
readDir(p, { recursive: true })
.catch((error) => {
throw new Error(`Error reading dir: ${error}`)
})
.then((files) => {
return files.map((file) => file.path)
})
})
}
}
export const fileSystemManager = new FileSystemManager()

View File

@ -181,6 +181,10 @@ export const line: SketchLineHelper = {
pathToNode,
'PipeExpression'
)
const { node: callExpression } = getNodeFromPath<
PipeExpression | CallExpression
>(_node, pathToNode, 'CallExpression')
const { node: varDec } = getNodeFromPath<VariableDeclarator>(
_node,
pathToNode,
@ -190,6 +194,38 @@ export const line: SketchLineHelper = {
const newXVal = createLiteral(roundOff(to[0] - from[0], 2))
const newYVal = createLiteral(roundOff(to[1] - from[1], 2))
const isAddingSegmentBetween =
callExpression.type === 'CallExpression' &&
callExpression.start >= pipe.start &&
callExpression.end <= pipe.end
if (
isAddingSegmentBetween &&
!createCallback &&
pipe.type === 'PipeExpression'
) {
const callExp = createCallExpression('line', [
createArrayExpression([newXVal, newYVal]),
createPipeSubstitution(),
])
const pathToNodeIndex = pathToNode.findIndex(
(x) => x[1] === 'PipeExpression'
)
const pipeIndex = pathToNode[pathToNodeIndex + 1][0]
if (typeof pipeIndex === 'undefined' || typeof pipeIndex === 'string') {
console.warn('pipeIndex is undefined')
return
}
pipe.body = [
...pipe.body.slice(0, pipeIndex),
callExp,
...pipe.body.slice(pipeIndex),
]
return {
modifiedAst: _node,
pathToNode,
}
}
if (replaceExisting && createCallback && pipe.type !== 'CallExpression') {
const { index: callIndex } = splitPathAtPipeExpression(pathToNode)
const { callExp, valueUsedInTransform } = createCallback(
@ -1011,15 +1047,6 @@ export function changeSketchArguments(
throw new Error(`not a sketch line helper: ${callExpression?.callee?.name}`)
}
interface CreateLineFnCallArgs {
node: Program
programMemory: ProgramMemory
to: [number, number]
from: [number, number]
fnName: ToolTip
pathToNode: PathToNode
}
export function compareVec2Epsilon(
vec1: [number, number],
vec2: [number, number],
@ -1044,6 +1071,15 @@ export function compareVec2Epsilon2(
return distance < compareEpsilon
}
interface CreateLineFnCallArgs {
node: Program
programMemory: ProgramMemory
to: [number, number]
from: [number, number]
fnName: ToolTip
pathToNode: PathToNode
}
export function addNewSketchLn({
node: _node,
programMemory: previousProgramMemory,

View File

@ -136,15 +136,21 @@ export const executor = async (
return _programMemory
}
const getSettingsState = import('components/GlobalStateProvider').then(
(module) => module.getSettingsState
)
export const _executor = async (
node: Program,
programMemory: ProgramMemory = { root: {}, return: null },
engineCommandManager: EngineCommandManager
): Promise<ProgramMemory> => {
try {
const baseUnit = (await getSettingsState)()?.baseUnit || 'mm'
const memory: ProgramMemory = await execute_wasm(
JSON.stringify(node),
JSON.stringify(programMemory),
baseUnit,
engineCommandManager,
fileSystemManager
)

View File

@ -39,30 +39,36 @@ export interface MouseGuard {
rotate: MouseGuardHandler
}
const butName = (e: React.MouseEvent) => ({
middle: !!(e.buttons & 4),
right: !!(e.buttons & 2),
left: !!(e.buttons & 1),
})
export const cameraMouseDragGuards: Record<CameraSystem, MouseGuard> = {
KittyCAD: {
pan: {
description: 'Right click + Shift + drag or middle click + drag',
callback: (e) =>
(e.button === 1 && noModifiersPressed(e)) ||
(e.button === 2 && e.shiftKey),
(butName(e).middle && noModifiersPressed(e)) ||
(butName(e).right && e.shiftKey),
},
zoom: {
description: 'Scroll wheel or Right click + Ctrl + drag',
dragCallback: (e) => e.button === 2 && e.ctrlKey,
dragCallback: (e) => !!(e.buttons & 2) && e.ctrlKey,
scrollCallback: () => true,
},
rotate: {
description: 'Right click + drag',
callback: (e) => e.button === 2 && noModifiersPressed(e),
callback: (e) => butName(e).right && noModifiersPressed(e),
},
},
OnShape: {
pan: {
description: 'Right click + Ctrl + drag or middle click + drag',
callback: (e) =>
(e.button === 2 && e.ctrlKey) ||
(e.button === 1 && noModifiersPressed(e)),
(butName(e).right && e.ctrlKey) ||
(butName(e).middle && noModifiersPressed(e)),
},
zoom: {
description: 'Scroll wheel',
@ -71,77 +77,77 @@ export const cameraMouseDragGuards: Record<CameraSystem, MouseGuard> = {
},
rotate: {
description: 'Right click + drag',
callback: (e) => e.button === 2 && noModifiersPressed(e),
callback: (e) => butName(e).right && noModifiersPressed(e),
},
},
'Trackpad Friendly': {
pan: {
description: 'Left click + Alt + Shift + drag or middle click + drag',
callback: (e) =>
(e.button === 0 && e.altKey && e.shiftKey && !e.metaKey) ||
(e.button === 1 && noModifiersPressed(e)),
(butName(e).left && e.altKey && e.shiftKey && !e.metaKey) ||
(butName(e).middle && noModifiersPressed(e)),
},
zoom: {
description: 'Scroll wheel or Left click + Alt + OS + drag',
dragCallback: (e) => e.button === 0 && e.altKey && e.metaKey,
dragCallback: (e) => butName(e).left && e.altKey && e.metaKey,
scrollCallback: () => true,
},
rotate: {
description: 'Left click + Alt + drag',
callback: (e) => e.button === 0 && e.altKey && !e.shiftKey && !e.metaKey,
callback: (e) => butName(e).left && e.altKey && !e.shiftKey && !e.metaKey,
lenientDragStartButton: 0,
},
},
Solidworks: {
pan: {
description: 'Right click + Ctrl + drag',
callback: (e) => e.button === 2 && e.ctrlKey,
callback: (e) => butName(e).right && e.ctrlKey,
lenientDragStartButton: 2,
},
zoom: {
description: 'Scroll wheel or Middle click + Shift + drag',
dragCallback: (e) => e.button === 1 && e.shiftKey,
dragCallback: (e) => butName(e).middle && e.shiftKey,
scrollCallback: () => true,
},
rotate: {
description: 'Middle click + drag',
callback: (e) => e.button === 1 && noModifiersPressed(e),
callback: (e) => butName(e).middle && noModifiersPressed(e),
},
},
NX: {
pan: {
description: 'Middle click + Shift + drag',
callback: (e) => e.button === 1 && e.shiftKey,
callback: (e) => butName(e).middle && e.shiftKey,
},
zoom: {
description: 'Scroll wheel or Middle click + Ctrl + drag',
dragCallback: (e) => e.button === 1 && e.ctrlKey,
dragCallback: (e) => butName(e).middle && e.ctrlKey,
scrollCallback: () => true,
},
rotate: {
description: 'Middle click + drag',
callback: (e) => e.button === 1 && noModifiersPressed(e),
callback: (e) => butName(e).middle && noModifiersPressed(e),
},
},
Creo: {
pan: {
description: 'Middle click + Shift + drag',
callback: (e) => e.button === 1 && e.shiftKey,
callback: (e) => butName(e).middle && e.shiftKey,
},
zoom: {
description: 'Scroll wheel or Middle click + Ctrl + drag',
dragCallback: (e) => e.button === 1 && e.ctrlKey,
dragCallback: (e) => butName(e).middle && e.ctrlKey,
scrollCallback: () => true,
},
rotate: {
description: 'Middle click + drag',
callback: (e) => e.button === 1 && noModifiersPressed(e),
callback: (e) => butName(e).middle && noModifiersPressed(e),
},
},
AutoCAD: {
pan: {
description: 'Middle click + drag',
callback: (e) => e.button === 1 && noModifiersPressed(e),
callback: (e) => butName(e).middle && noModifiersPressed(e),
},
zoom: {
description: 'Scroll wheel',
@ -150,7 +156,7 @@ export const cameraMouseDragGuards: Record<CameraSystem, MouseGuard> = {
},
rotate: {
description: 'Middle click + Shift + drag',
callback: (e) => e.button === 1 && e.shiftKey,
callback: (e) => butName(e).middle && e.shiftKey,
},
},
}

View File

@ -1,4 +1,4 @@
import { CommandSetConfig } from 'lib/commandTypes'
import { CommandSetConfig, KclCommandValue } from 'lib/commandTypes'
import { Selections } from 'lib/selections'
import { modelingMachine } from 'machines/modelingMachine'
@ -14,7 +14,7 @@ export type ModelingCommandSchema = {
Extrude: {
selection: Selections // & { type: 'face' } would be cool to lock that down
// result: (typeof EXTRUSION_RESULTS)[number]
distance: number
distance: KclCommandValue
}
}
@ -50,8 +50,8 @@ export const modelingMachineConfig: CommandSetConfig<
// })),
// },
distance: {
inputType: 'number',
defaultValue: 5,
inputType: 'kcl',
defaultValue: '5 + 7',
required: true,
},
},

View File

@ -36,7 +36,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
SettingsCommandSchema
> = {
'Set Base Unit': {
icon: 'gear',
icon: 'settings',
args: {
baseUnit: {
inputType: 'options',
@ -52,7 +52,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
},
},
'Set Camera Controls': {
icon: 'gear',
icon: 'settings',
args: {
cameraControls: {
inputType: 'options',
@ -68,7 +68,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
},
},
'Set Default Project Name': {
icon: 'gear',
icon: 'settings',
hide: 'web',
args: {
defaultProjectName: {
@ -79,7 +79,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
},
},
'Set Text Wrapping': {
icon: 'gear',
icon: 'settings',
args: {
textWrapping: {
inputType: 'options',
@ -101,7 +101,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
},
},
'Set Theme': {
icon: 'gear',
icon: 'settings',
args: {
theme: {
inputType: 'options',
@ -117,7 +117,7 @@ export const settingsCommandBarConfig: CommandSetConfig<
},
},
'Set Unit System': {
icon: 'gear',
icon: 'settings',
args: {
unitSystem: {
inputType: 'options',

View File

@ -7,10 +7,23 @@ import {
InterpreterFrom,
} from 'xstate'
import { Selection } from './selections'
import { Identifier, Value, VariableDeclaration } from 'lang/wasm'
type Icon = CustomIconName
const PLATFORMS = ['both', 'web', 'desktop'] as const
const INPUT_TYPES = ['options', 'string', 'number', 'selection'] as const
const INPUT_TYPES = ['options', 'string', 'kcl', 'selection'] as const
export interface KclExpression {
valueAst: Value
valueText: string
valueCalculated: string
}
export interface KclExpressionWithVariable extends KclExpression {
variableName: string
variableDeclarationAst: VariableDeclaration
variableIdentifierAst: Identifier
insertIndex: number
}
export type KclCommandValue = KclExpression | KclExpressionWithVariable
export type CommandInputType = (typeof INPUT_TYPES)[number]
export type CommandSetSchema<T extends AnyStateMachine> = Partial<{
@ -82,20 +95,24 @@ export type CommandArgumentConfig<
description?: string
required: boolean
skip?: true
defaultValue?: OutputType | ((context: ContextFrom<T>) => OutputType)
} & (
| {
inputType: Extract<CommandInputType, 'options'>
options:
| CommandArgumentOption<OutputType>[]
| ((context: ContextFrom<T>) => CommandArgumentOption<OutputType>[])
defaultValue?: OutputType | ((context: ContextFrom<T>) => OutputType)
}
| {
inputType: Extract<CommandInputType, 'selection'>
selectionTypes: Selection['type'][]
multiple: boolean
}
| { inputType: Exclude<CommandInputType, 'options' | 'selection'> }
| { inputType: Extract<CommandInputType, 'kcl'>; defaultValue?: string } // KCL expression inputs have simple strings as default values
| {
inputType: Extract<CommandInputType, 'string'>
defaultValue?: OutputType | ((context: ContextFrom<T>) => OutputType)
}
)
export type CommandArgument<
@ -106,11 +123,11 @@ export type CommandArgument<
description?: string
required: boolean
skip?: true
defaultValue?: OutputType | ((context: ContextFrom<T>) => OutputType)
} & (
| {
inputType: Extract<CommandInputType, 'options'>
options: CommandArgumentOption<OutputType>[]
defaultValue?: OutputType
}
| {
inputType: Extract<CommandInputType, 'selection'>
@ -118,7 +135,11 @@ export type CommandArgument<
actor: InterpreterFrom<T>
multiple: boolean
}
| { inputType: Exclude<CommandInputType, 'options' | 'selection'> }
| { inputType: Extract<CommandInputType, 'kcl'>; defaultValue?: string } // KCL expression inputs have simple strings as default values
| {
inputType: Extract<CommandInputType, 'string'>
defaultValue?: OutputType
}
)
export type CommandArgumentWithName<

Some files were not shown because too many files have changed in this diff Show More