frontend complete migration from parcel to vite for much better production builds

This commit is contained in:
Yeicor
2024-03-03 17:54:53 +01:00
parent 0fad65d7b2
commit da0dcea44a
30 changed files with 1142 additions and 1651 deletions

View File

@@ -1,6 +0,0 @@
// noinspection JSUnusedGlobalSymbols,JSUnresolvedReference
module.exports = {
compilerOptions: {
isCustomElement: tag => tag === 'model-viewer'
}
}

BIN
assets/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

View File

@@ -1288,6 +1288,70 @@ third-party archives.
-----------
The following npm package may be included in this product:
- typescript@5.3.3
This package contains the following license and notice below:
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this License; and
You must cause any modified files to carry prominent notices stating that You changed the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
-----------
The following npm packages may be included in this product:
- @lit/reactive-element@1.6.3

View File

@@ -4,4 +4,4 @@ import subprocess
if __name__ == "__main__":
# When building the backend, make sure the frontend is built first
subprocess.run(['yarn', 'install'], check=True)
subprocess.run(['yarn', 'build', '--dist-dir', 'yacv_server/frontend'], check=True)
subprocess.run(['yarn', 'build', '--outDir', 'yacv_server/frontend'], check=True)

View File

@@ -1,11 +1,11 @@
<!--suppress SillyAssignmentJS -->
<script setup lang="ts">
import {defineAsyncComponent, provide, Ref, ref, shallowRef, triggerRef} from "vue";
import {defineAsyncComponent, provide, type Ref, ref, shallowRef, triggerRef} from "vue";
import Sidebar from "./misc/Sidebar.vue";
import Loading from "./misc/Loading.vue";
import Tools from "./tools/Tools.vue";
import Models from "./models/Models.vue";
import {VBtn, VLayout, VMain, VToolbarTitle} from "vuetify/lib/components";
import {VBtn, VLayout, VMain, VToolbarTitle} from "vuetify/lib/components/index.mjs";
import {settings} from "./misc/settings";
import {NetworkManager, NetworkUpdateEvent} from "./misc/network";
import {SceneMgr} from "./misc/scene";
@@ -44,7 +44,7 @@ async function onModelRemoveRequest(name: string) {
// Set up the load model event listener
let networkMgr = new NetworkManager();
networkMgr.addEventListener('update', onModelLoadRequest);
networkMgr.addEventListener('update', (e) => onModelLoadRequest(e as NetworkUpdateEvent));
// Start loading all configured models ASAP
for (let model of settings.preloadModels) {
networkMgr.load(model);
@@ -65,7 +65,7 @@ async function loadModelManual() {
</v-main>
<!-- The left collapsible sidebar has the list of models -->
<sidebar :opened-init="openSidebarsByDefault" side="left">
<sidebar :opened-init="openSidebarsByDefault" side="left" :width="300">
<template #toolbar>
<v-toolbar-title>Models</v-toolbar-title>
</template>
@@ -82,7 +82,7 @@ async function loadModelManual() {
<template #toolbar>
<v-toolbar-title>Tools</v-toolbar-title>
</template>
<tools :viewer="viewer" @findModel="(name) => models.findModel(name)"/>
<tools :viewer="viewer" @findModel="(name) => models?.findModel(name)"/>
</sidebar>
</v-layout>

View File

@@ -1,12 +1,8 @@
globalThis.__VUE_OPTIONS_API__ = process.env.NODE_ENV === "development"
globalThis.__VUE_PROD_DEVTOOLS__ = process.env.NODE_ENV === "development"
globalThis.__VUE_PROD_HYDRATION_MISMATCH_DETAILS__ = process.env.NODE_ENV === "development"
import {createApp} from 'vue'
import App from './App.vue'
import {createVuetify} from 'vuetify';
import * as directives from 'vuetify/lib/directives';
import * as directives from 'vuetify/lib/directives/index.mjs';
import 'vuetify/dist/vuetify.css';
const vuetify = createVuetify({

View File

@@ -1,5 +1,5 @@
<script setup lang="ts">
import {VContainer, VRow, VCol, VProgressCircular} from "vuetify/lib/components";
import {VContainer, VRow, VCol, VProgressCircular} from "vuetify/lib/components/index.mjs";
</script>
<template>

View File

@@ -1,16 +1,16 @@
<script setup lang="ts">
import {ref} from "vue";
import {VBtn, VNavigationDrawer, VToolbar, VToolbarItems} from "vuetify/lib/components";
import {mdiClose, mdiChevronRight, mdiChevronLeft} from '@mdi/js'
import {VBtn, VNavigationDrawer, VToolbar, VToolbarItems} from "vuetify/lib/components/index.mjs";
import {mdiChevronLeft, mdiChevronRight, mdiClose} from '@mdi/js'
import SvgIcon from '@jamescoyle/vue-icon';
const props = defineProps({
const props = defineProps<{
openedInit: Boolean,
side: String,
width: Number
});
side: "left" | "right",
width: number
}>();
let opened = ref(props.openedInit);
let opened = ref(props.openedInit.valueOf());
const openIcon = props.side === 'left' ? mdiChevronRight : mdiChevronLeft;
</script>

View File

@@ -3,13 +3,13 @@ import type {MObject3D} from "../tools/Selection.vue";
import type { ModelScene } from '@google/model-viewer/lib/three-components/ModelScene';
function getCenterAndVertexList(obj: InstanceType<typeof MObject3D>, scene: ModelScene): {
function getCenterAndVertexList(obj: MObject3D, scene: ModelScene): {
center: Vector3,
vertices: Array<Vector3>
} {
obj.updateMatrixWorld();
let pos: InterleavedBufferAttribute = obj.geometry.getAttribute('position');
let ind: BufferAttribute = obj.geometry.index;
let pos: BufferAttribute | InterleavedBufferAttribute = obj.geometry.getAttribute('position');
let ind: BufferAttribute | null = obj.geometry.index;
if (!ind) {
ind = new BufferAttribute(new Uint16Array(pos.count), 1);
for (let i = 0; i < pos.count; i++) {
@@ -34,7 +34,7 @@ function getCenterAndVertexList(obj: InstanceType<typeof MObject3D>, scene: Mode
* Given two THREE.Object3D objects, returns their closest and farthest vertices, and the geometric centers.
* All of them are approximated and should not be used for precise calculations.
*/
export function distances(a: InstanceType<typeof MObject3D>, b: InstanceType<typeof MObject3D>, scene: ModelScene): {
export function distances(a: MObject3D, b: MObject3D, scene: ModelScene): {
min: Array<Vector3>,
center: Array<Vector3>,
max: Array<Vector3>

View File

@@ -1,4 +1,4 @@
import {Document, Scene, Transform, WebIO, Buffer} from "@gltf-transform/core";
import {Document, Scene, type Transform, WebIO, Buffer} from "@gltf-transform/core";
import {unpartition} from "@gltf-transform/functions";
let io = new WebIO();

View File

@@ -1,7 +1,7 @@
import {Document, TypedArray} from '@gltf-transform/core'
import {Vector2} from 'three/src/math/Vector2'
import {Vector3} from 'three/src/math/Vector3'
import {Matrix4} from 'three/src/math/Matrix4'
import {Document, type TypedArray} from '@gltf-transform/core'
import {Vector2} from "three/src/math/Vector2.js"
import {Vector3} from "three/src/math/Vector3.js"
import {Matrix4} from "three/src/math/Matrix4.js"
/** Exports the colors used for the axes, primary and secondary. They match the orientation gizmo. */
@@ -22,10 +22,13 @@ function buildSimpleGltf(doc: Document, rawPositions: number[], rawIndices: numb
.setArray(new Uint32Array(rawIndices) as TypedArray)
.setType('SCALAR')
.setBuffer(buffer)
const colors = doc.createAccessor(name + 'Color')
let colors = null;
if (rawColors) {
colors = doc.createAccessor(name + 'Color')
.setArray(new Float32Array(rawColors) as TypedArray)
.setType('VEC3')
.setBuffer(buffer)
.setBuffer(buffer);
}
const material = doc.createMaterial(name + 'Material')
.setAlphaMode('OPAQUE')
const geometry = doc.createPrimitive()

View File

@@ -13,7 +13,7 @@ export class NetworkUpdateEvent extends Event {
/** Listens for updates and emits events when a model changes */
export class NetworkManager extends EventTarget {
private knownObjectHashes: { [name: string]: string } = {};
private knownObjectHashes: { [name: string]: string | null } = {};
/**
* Tries to load a new model (.glb) from the given URL.
@@ -55,7 +55,7 @@ export class NetworkManager extends EventTarget {
ws.onopen = () => clearTimeout(timeoutFaster);
}
private foundModel(name: string, hash: string, url: string) {
private foundModel(name: string, hash: string | null, url: string) {
let prevHash = this.knownObjectHashes[name];
if (!hash || hash !== prevHash) {
this.knownObjectHashes[name] = hash;

View File

@@ -1,10 +1,10 @@
import {Ref} from 'vue';
import {type Ref} from 'vue';
import {Document} from '@gltf-transform/core';
import {extrasNameKey, extrasNameValueHelpers, mergeFinalize, mergePartial, removeModel, toBuffer} from "./gltf";
import {newAxes, newGridBox} from "./helpers";
import {Vector3} from 'three/src/math/Vector3'
import {Box3} from 'three/src/math/Box3'
import {Matrix4} from 'three/src/math/Matrix4'
import {Vector3} from "three/src/math/Vector3.js"
import {Box3} from "three/src/math/Box3.js"
import {Matrix4} from "three/src/math/Matrix4.js"
/** This class helps manage SceneManagerData. All methods are static to support reactivity... */
export class SceneMgr {

View File

@@ -23,11 +23,11 @@ export const settings = {
background: '',
}
const firstTimeNames = []; // Needed for array values, which clear the array when overridden
const firstTimeNames: Array<string> = []; // Needed for array values, which clear the array when overridden
function parseSetting(name: string, value: string): any {
let arrayElem = name.endsWith(".0")
if (arrayElem) name = name.slice(0, -2);
let prevValue = settings[name];
let prevValue = (settings as any)[name];
if (prevValue === undefined) throw new Error(`Unknown setting: ${name}`);
if (Array.isArray(prevValue) && !arrayElem) {
let toExtend = []
@@ -54,5 +54,5 @@ function parseSetting(name: string, value: string): any {
// Auto-override any settings from the URL
const url = new URL(window.location.href);
url.searchParams.forEach((value, key) => {
if (key in settings) settings[key] = parseSetting(key, value);
if (key in settings) (settings as any)[key] = parseSetting(key, value);
})

View File

@@ -10,10 +10,10 @@ import {
VSlider,
VSpacer,
VTooltip,
} from "vuetify/lib/components";
} from "vuetify/lib/components/index.mjs";
import {extrasNameKey, extrasNameValueHelpers} from "../misc/gltf";
import {Document, Mesh} from "@gltf-transform/core";
import {inject, ref, ShallowRef, watch, Ref} from "vue";
import {inject, ref, type ShallowRef, watch} from "vue";
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
import {
mdiCircleOpacity,
@@ -26,11 +26,12 @@ import {
} from '@mdi/js'
import SvgIcon from '@jamescoyle/vue-icon';
import {SceneMgr} from "../misc/scene";
import {BackSide, FrontSide} from "three/src/constants";
import {Box3} from "three/src/math/Box3";
import {Color} from "three/src/math/Color";
import {Plane} from "three/src/math/Plane";
import {Vector3} from "three/src/math/Vector3";
import {BackSide, FrontSide} from "three/src/constants.js";
import {Box3} from "three/src/math/Box3.js";
import {Color} from "three/src/math/Color.js";
import {Plane} from "three/src/math/Plane.js";
import {Vector3} from "three/src/math/Vector3.js";
import type {MObject3D} from "../tools/Selection.vue";
const props = defineProps<{
meshes: Array<Mesh>,
@@ -69,7 +70,7 @@ function onEnabledFeaturesChange(newEnabledFeatures: Array<number>) {
// Iterate all primitives of the mesh and set their visibility based on the enabled features
// Use the scene graph instead of the document to avoid reloading the same model, at the cost
// of not actually removing the primitives from the scene graph
sceneModel.traverse((child) => {
sceneModel.traverse((child: MObject3D) => {
if (child.userData[extrasNameKey] === modelName) {
let childIsFace = child.type == 'Mesh' || child.type == 'SkinnedMesh'
let childIsEdge = child.type == 'Line' || child.type == 'LineSegments'
@@ -96,7 +97,7 @@ function onOpacityChange(newOpacity: number) {
// Use the scene graph instead of the document to avoid reloading the same model, at the cost
// of not actually removing the primitives from the scene graph
// console.log('Opacity may have changed', newOpacity)
sceneModel.traverse((child) => {
sceneModel.traverse((child: MObject3D) => {
if (child.userData[extrasNameKey] === modelName) {
if (child.material && child.material.opacity !== newOpacity) {
child.material.transparent = newOpacity < 1;
@@ -110,7 +111,7 @@ function onOpacityChange(newOpacity: number) {
watch(opacity, onOpacityChange);
let {sceneDocument}: {sceneDocument: ShallowRef<Document>} = inject('sceneDocument');
let {sceneDocument} = inject<{ sceneDocument: ShallowRef<Document> }>('sceneDocument')!!;
function onClipPlanesChange() {
let scene = props.viewer?.scene;
@@ -128,7 +129,7 @@ function onClipPlanesChange() {
bbox = SceneMgr.getBoundingBox(sceneDocument.value);
bbox.translate(scene.getTarget());
}
sceneModel.traverse((child) => {
sceneModel.traverse((child: MObject3D) => {
if (child.userData[extrasNameKey] === modelName) {
if (child.material) {
if (bbox) {
@@ -165,7 +166,7 @@ watch(clipPlaneSwappedX, onClipPlanesChange);
watch(clipPlaneSwappedY, onClipPlanesChange);
watch(clipPlaneSwappedZ, onClipPlanesChange);
// Clip planes are also affected by the camera position, so we need to listen to camera changes
props.viewer.onElemReady((elem) => elem.addEventListener('camera-change', onClipPlanesChange))
props.viewer!!.onElemReady((elem) => elem.addEventListener('camera-change', onClipPlanesChange))
function onModelLoad() {
let scene = props.viewer?.scene;
@@ -174,8 +175,8 @@ function onModelLoad() {
// Iterate all primitives of the mesh and set their visibility based on the enabled features
// Use the scene graph instead of the document to avoid reloading the same model, at the cost
// of not actually removing the primitives from the scene graph
let childrenToAdd = [];
sceneModel.traverse((child) => {
let childrenToAdd: Array<MObject3D> = [];
sceneModel.traverse((child: MObject3D) => {
if (child.userData[extrasNameKey] === modelName) {
if (child.type == 'Mesh' || child.type == 'SkinnedMesh') {
// We could implement cutting planes using the stencil buffer:
@@ -192,7 +193,7 @@ function onModelLoad() {
backChild.material.side = BackSide;
backChild.material.color = new Color(0.25, 0.25, 0.25)
child.userData.backChild = backChild;
childrenToAdd.push(backChild);
childrenToAdd.push(backChild as MObject3D);
}
}
// if (child.type == 'Line' || child.type == 'LineSegments') {
@@ -200,12 +201,12 @@ function onModelLoad() {
// If wide lines are really needed, we need https://threejs.org/examples/?q=line#webgl_lines_fat
// }
if (child.type == 'Points') {
child.material.size = 5;
(child.material as any).size = 5;
child.material.needsUpdate = true;
}
}
});
childrenToAdd.forEach((child) => sceneModel.add(child));
childrenToAdd.forEach((child: MObject3D) => sceneModel.add(child));
scene.queueRender()
// Furthermore...
@@ -218,7 +219,7 @@ function onModelLoad() {
}
// props.viewer.elem may not yet be available, so we need to wait for it
props.viewer.onElemReady((elem) => elem.addEventListener('load', onModelLoad))
props.viewer!!.onElemReady((elem) => elem.addEventListener('load', onModelLoad))
</script>
<template>

View File

@@ -1,16 +1,15 @@
<script setup lang="ts">
import {VExpansionPanels} from "vuetify/lib/components";
import {VExpansionPanels} from "vuetify/lib/components/index.mjs";
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
import Loading from "../misc/Loading.vue";
import {Document, Mesh} from "@gltf-transform/core";
import {extrasNameKey} from "../misc/gltf";
import Model from "./Model.vue";
import {ref, watch, inject, Ref} from "vue";
import {inject, ref, type Ref} from "vue";
const props = defineProps<{ viewer: InstanceType<typeof ModelViewerWrapper> | null }>();
const emit = defineEmits<{ remove: [string] }>()
let {sceneDocument} = inject<{ sceneDocument: Ref<Document> }>('sceneDocument');
let {sceneDocument} = inject<{ sceneDocument: Ref<Document> }>('sceneDocument')!!;
let expandedNames = ref<Array<string>>([]);

3
frontend/shims.d.ts vendored Normal file
View File

@@ -0,0 +1,3 @@
// Avoids typescript error when importing some files
declare module '@jamescoyle/vue-icon'
declare module 'three-orientation-gizmo/src/OrientationGizmo'

View File

@@ -1,7 +1,7 @@
<script setup lang="ts">
// License text for all dependencies, only downloaded when/if needed
// @ts-ignore
import licenseText from "bundle-text:../../assets/licenses.txt";
import licenseText from "../../assets/licenses.txt?raw";
</script>
<template>

View File

@@ -10,11 +10,13 @@ import {Matrix4} from "three/src/math/Matrix4.js";
globalThis.THREE = {Vector3, Matrix4} as any // HACK: Required for the gizmo to work
const OrientationGizmo = OrientationGizmoRaw.default;
const props = defineProps<{ elem: ModelViewerElement | null, scene: ModelScene }>();
function createGizmo(expectedParent: HTMLElement, scene: ModelScene): HTMLElement {
// noinspection SpellCheckingInspection
let gizmo = new OrientationGizmoRaw(scene.camera, {
let gizmo = new OrientationGizmoRaw.default(scene.camera, {
size: expectedParent.clientWidth,
bubbleSizePrimary: expectedParent.clientWidth / 12,
bubbleSizeSeconday: expectedParent.clientWidth / 14,
@@ -22,8 +24,8 @@ function createGizmo(expectedParent: HTMLElement, scene: ModelScene): HTMLElemen
});
// HACK: Swap axes to fake the CAD orientation
for (let swap of [["y", "-z"], ["z", "-y"], ["z", "-z"]]) {
let indexA = gizmo.bubbles.findIndex((bubble) => bubble.axis == swap[0])
let indexB = gizmo.bubbles.findIndex((bubble) => bubble.axis == swap[1])
let indexA = gizmo.bubbles.findIndex((bubble: any) => bubble.axis == swap[0])
let indexB = gizmo.bubbles.findIndex((bubble: any) => bubble.axis == swap[1])
let dirA = gizmo.bubbles[indexA].direction.clone();
let dirB = gizmo.bubbles[indexB].direction.clone();
gizmo.bubbles[indexA].direction.copy(dirB);
@@ -63,6 +65,7 @@ function updateGizmo() {
}
let reinstall = () => {
if(!container.value) return;
if (gizmo) container.value.removeChild(gizmo);
gizmo = createGizmo(container.value, props.scene as ModelScene) as typeof gizmo;
container.value.appendChild(gizmo);

View File

@@ -1,27 +1,27 @@
<script setup lang="ts">
import {defineModel, inject, ref, ShallowRef, watch} from "vue";
import {VBtn, VSelect, VTooltip} from "vuetify/lib/components";
import SvgIcon from '@jamescoyle/vue-icon/lib/svg-icon.vue';
import {defineModel, inject, ref, type ShallowRef, watch} from "vue";
import {VBtn, VSelect, VTooltip} from "vuetify/lib/components/index.mjs";
import SvgIcon from '@jamescoyle/vue-icon';
import type {ModelViewerElement} from '@google/model-viewer';
import type {ModelScene} from "@google/model-viewer/lib/three-components/ModelScene";
import {mdiCubeOutline, mdiCursorDefaultClick, mdiFeatureSearch, mdiRuler} from '@mdi/js';
import type {Intersection, Material, Object3D} from "three";
import type {Intersection, Material, Mesh, Object3D} from "three";
import {Box3, Matrix4, Raycaster, Vector3} from "three";
import type ModelViewerWrapperT from "./ModelViewerWrapper.vue";
import type ModelViewerWrapperT from "../viewer/ModelViewerWrapper.vue";
import {extrasNameKey} from "../misc/gltf";
import {SceneMgr} from "../misc/scene";
import {Document} from "@gltf-transform/core";
import {AxesColors} from "../misc/helpers";
import {distances} from "../misc/distances";
export type MObject3D = Object3D & {
export type MObject3D = Mesh & {
userData: { noHit?: boolean },
material: Material & { color: { r: number, g: number, b: number }, __prevBaseColorFactor?: [number, number, number] }
};
let props = defineProps<{ viewer: typeof ModelViewerWrapperT | null }>();
let emit = defineEmits<{ findModel: [string] }>();
let {setDisableTap} = inject<{ setDisableTap: (boolean) => void }>('disableTap');
let {setDisableTap} = inject<{ setDisableTap: (arg0: boolean) => void }>('disableTap')!!;
let selectionEnabled = ref(false);
let selected = defineModel<Array<Intersection<MObject3D>>>({default: []});
let highlightNextSelection = ref([false, false]); // Second is whether selection was enabled before
@@ -87,13 +87,16 @@ let selectionListener = (event: MouseEvent) => {
// Find all hit objects and select the wanted one based on the filter
const hits = raycaster.intersectObject(scene, true);
let hit = hits.find((hit) => {
let hit = hits.find((hit: Intersection<Object3D>) => {
if (!hit.object || !(hit.object as any).isMesh) return false;
const kind = hit.object.type
console.log(kind)
let isFace = kind === 'Mesh' || kind === 'SkinnedMesh';
let isEdge = kind === 'Line' || kind === 'LineSegments';
let isVertex = kind === 'Points';
const kindOk = (selectFilter.value === 'Any (S)') ||
((kind === 'Mesh' || kind === 'SkinnedMesh') && selectFilter.value === '(F)aces') ||
((kind === 'Line' || kind === 'LineSegments') && selectFilter.value === '(E)dges') ||
(kind === 'Points' && selectFilter.value === '(V)ertices');
(isFace && selectFilter.value === '(F)aces') ||
(isEdge && selectFilter.value === '(E)dges') ||
(isVertex && selectFilter.value === '(V)ertices');
return hit.object.visible && !hit.object.userData.noHit && kindOk;
}) as Intersection<MObject3D> | undefined;
//console.log('Hit', hit)
@@ -102,7 +105,7 @@ let selectionListener = (event: MouseEvent) => {
// If we are selecting, toggle the selection or deselect all if no hit
if (hit) {
// Toggle selection
const wasSelected = selected.value.find((m) => m.object.name === hit.object.name) !== undefined;
const wasSelected = selected.value.find((m) => m.object.name === hit?.object?.name) !== undefined;
if (wasSelected) {
deselect(hit)
} else {
@@ -113,7 +116,7 @@ let selectionListener = (event: MouseEvent) => {
}
updateBoundingBox();
updateDistances();
} else {
} else if (hit) {
// Otherwise, highlight the model that owns the hit
emit('findModel', hit.object.userData[extrasNameKey])
// And reset the selection mode
@@ -144,10 +147,12 @@ function deselect(hit: Intersection<MObject3D>, alsoRemove = true) {
let toRemove = selected.value.findIndex((m) => m.object.name === hit.object.name);
selected.value.splice(toRemove, 1);
}
if (hit.object.material.__prevBaseColorFactor) {
hit.object.material.color.r = hit.object.material.__prevBaseColorFactor[0]
hit.object.material.color.g = hit.object.material.__prevBaseColorFactor[1]
hit.object.material.color.b = hit.object.material.__prevBaseColorFactor[2]
delete hit.object.material.__prevBaseColorFactor;
}
}
function deselectAll(alsoRemove = true) {
@@ -206,10 +211,10 @@ let onCameraChange = () => {
};
setTimeout(waitingHandler, 100); // Wait for the camera to stop moving
};
let onViewerReady = (viewer) => {
let onViewerReady = (viewer: typeof ModelViewerWrapperT) => {
if (!viewer) return;
// props.viewer.elem may not yet be available, so we need to wait for it
viewer.onElemReady((elem) => {
viewer.onElemReady((elem: ModelViewerElement) => {
if (hasListeners) return;
hasListeners = true;
elem.addEventListener('mouseup', selectionListener);
@@ -226,9 +231,9 @@ let onViewerReady = (viewer) => {
});
};
if (props.viewer) onViewerReady(props.viewer);
else watch(() => props.viewer, onViewerReady);
else watch(() => props.viewer, () => onViewerReady(props.viewer as any));
let {sceneDocument}: { sceneDocument: ShallowRef<Document> } = inject('sceneDocument');
let {sceneDocument} = inject<{ sceneDocument: ShallowRef<Document> }>('sceneDocument')!!;
let boundingBoxLines: { [points: string]: number } = {}
function updateBoundingBox() {
@@ -294,7 +299,7 @@ function updateBoundingBox() {
if (matchingLine) {
boundingBoxLinesToRemove = boundingBoxLinesToRemove.filter((l) => l !== lineCacheKey);
} else {
let newLineId = props.viewer.addLine3D(from, to,
let newLineId = props.viewer?.addLine3D(from, to,
to.clone().sub(from).length().toFixed(1) + "mm", {
"stroke": "rgb(" + color.join(',') + ")",
"stroke-width": "2"
@@ -306,7 +311,7 @@ function updateBoundingBox() {
}
// Remove the lines that are no longer needed
for (let lineLocator of boundingBoxLinesToRemove) {
if (props.viewer.removeLine3D(boundingBoxLines[lineLocator])) {
if (props.viewer?.removeLine3D(boundingBoxLines[lineLocator])) {
delete boundingBoxLines[lineLocator];
}
}

View File

@@ -9,18 +9,18 @@ import {
VToolbar,
VToolbarTitle,
VTooltip,
} from "vuetify/lib/components";
} from "vuetify/lib/components/index.mjs";
import OrientationGizmo from "./OrientationGizmo.vue";
import type {PerspectiveCamera} from "three/src/cameras/PerspectiveCamera";
import {OrthographicCamera} from "three/src/cameras/OrthographicCamera";
import type {PerspectiveCamera} from "three/src/cameras/PerspectiveCamera.js";
import {OrthographicCamera} from "three/src/cameras/OrthographicCamera.js";
import {mdiClose, mdiCrosshairsGps, mdiDownload, mdiGithub, mdiLicense, mdiProjector} from '@mdi/js'
import SvgIcon from '@jamescoyle/vue-icon/lib/svg-icon.vue';
import SvgIcon from '@jamescoyle/vue-icon';
import type {ModelViewerElement} from '@google/model-viewer';
import type {Intersection} from "three";
import type {MObject3D} from "./Selection.vue";
import Loading from "../misc/Loading.vue";
import type ModelViewerWrapper from "./viewer/ModelViewerWrapper.vue";
import {defineAsyncComponent, Ref, ref} from "vue";
import type ModelViewerWrapper from "../viewer/ModelViewerWrapper.vue";
import {defineAsyncComponent, type Ref, ref} from "vue";
const SelectionComponent = defineAsyncComponent({
loader: () => import("./Selection.vue"),
@@ -39,7 +39,7 @@ const LicensesDialogContent = defineAsyncComponent({
let props = defineProps<{ viewer: InstanceType<typeof ModelViewerWrapper> | null }>();
const emit = defineEmits<{ findModel: [string] }>()
let selection: Ref<Array<Intersection<typeof MObject3D>>> = ref([]);
let selection: Ref<Array<Intersection<MObject3D>>> = ref([]);
let selectionFaceCount = () => selection.value.filter((s) => s.object.type == "Mesh" || s.object.type == "SkinnedMesh").length
let selectionEdgeCount = () => selection.value.filter((s) => s.object.type == "Line").length
let selectionVertexCount = () => selection.value.filter((s) => s.object.type == "Points").length
@@ -56,7 +56,7 @@ function syncOrthoCamera(force: boolean) {
(scene as any).camera = new OrthographicCamera(-w, w, h, -h, perspectiveCam.near, perspectiveCam.far);
scene.camera.position.copy(perspectiveCam.position);
scene.camera.lookAt(scene.getTarget().clone().add(scene.target.position));
if (force) props.viewer.scene.queueRender() // Force rerender of model-viewer
if (force) scene.queueRender() // Force rerender of model-viewer
requestAnimationFrame(() => syncOrthoCamera(false));
}
}
@@ -74,7 +74,7 @@ function toggleProjection() {
} else {
// Restore the default perspective camera
scene.camera = (scene as any).__perspectiveCamera;
props.viewer.scene.queueRender() // Force rerender of model-viewer
scene.queueRender() // Force rerender of model-viewer
}
toggleProjectionText.value = wasPerspectiveCamera ? 'ORTHO' : 'PERSP';
// The camera change may take a few frames to take effect, dispatch the event after a delay
@@ -83,14 +83,16 @@ function toggleProjection() {
}
async function centerCamera() {
let viewerEl: ModelViewerElement = props.viewer.elem;
let viewerEl: ModelViewerElement | null | undefined = props.viewer?.elem;
if (!viewerEl) return;
await viewerEl.updateFraming();
viewerEl.zoom(3);
}
async function downloadSceneGlb() {
let viewerEl: ModelViewerElement = props.viewer.elem;
let viewerEl: ModelViewerElement | null | undefined = props.viewer?.elem;
if (!viewerEl) return;
const glTF = await viewerEl.exportScene({onlyVisible: true, binary: true});
const file = new File([glTF], "export.glb");
const link = document.createElement("a");
@@ -114,7 +116,7 @@ window.addEventListener('keydown', (event) => {
</script>
<template>
<orientation-gizmo :scene="props.viewer.scene" :elem="props.viewer?.elem" v-if="props.viewer?.scene"/>
<orientation-gizmo :scene="props.viewer.scene as any" :elem="props.viewer.elem" v-if="props.viewer?.scene"/>
<v-divider/>
<h5>Camera</h5>
<v-btn icon @click="toggleProjection"><span class="icon-detail">{{ toggleProjectionText }}</span>
@@ -129,7 +131,7 @@ window.addEventListener('keydown', (event) => {
</v-btn>
<v-divider/>
<h5>Selection ({{ selectionFaceCount() }}F {{ selectionEdgeCount() }}E {{ selectionVertexCount() }}V)</h5>
<selection-component :ref="selectionComp" :viewer="props.viewer" v-model="selection"
<selection-component :ref="selectionComp as any" :viewer="props.viewer as any" v-model="selection"
@findModel="(name) => emit('findModel', name)"/>
<v-divider/>
<v-spacer></v-spacer>

View File

@@ -3,7 +3,7 @@
<script setup lang="ts">
import {settings} from "../misc/settings";
import {onMounted, inject, Ref} from "vue";
import {onMounted, inject, type Ref} from "vue";
import {$scene, $renderer} from "@google/model-viewer/lib/model-viewer-base";
import Loading from "../misc/Loading.vue";
import {ref, watch} from "vue";
@@ -24,7 +24,9 @@ const scene = ref<ModelScene | null>(null);
const renderer = ref<Renderer | null>(null);
onMounted(() => {
if (!elem.value) return;
elem.value.addEventListener('load', async () => {
if (!elem.value) return;
// Delete the initial load banner
let banner = elem.value.querySelector('.initial-load-banner');
if (banner) banner.remove();
@@ -37,15 +39,14 @@ onMounted(() => {
elem.value.addEventListener('camera-change', onCameraChange);
});
class Line3DData {
startHotspot: HTMLElement;
endHotspot: HTMLElement;
start2D: [number, number];
end2D: [number, number];
lineAttrs: { [key: string]: string };
centerText?: string;
centerTextSize?: [number, number]
startHotspot: HTMLElement = document.body
endHotspot: HTMLElement = document.body
start2D: [number, number] = [-1000, -1000];
end2D: [number, number] = [-1000, -1000];
lineAttrs: { [key: string]: string } = {"stroke-width": "2", "stroke": "red"}
centerText?: string = undefined;
centerTextSize: [number, number] = [0, 0];
}
let nextLineId = 1; // Avoid 0 (falsy!)
@@ -55,20 +56,19 @@ function positionToHotspot(position: Vector3): string {
return position.x + ' ' + position.y + ' ' + position.z;
}
function addLine3D(p1: Vector3, p2: Vector3, centerText: string = "",
lineAttrs: { [key: string]: string } = {
function addLine3D(p1: Vector3, p2: Vector3, centerText?: string = undefined, lineAttrs: { [key: string]: string } = {
"stroke-width": "2",
"stroke": "red",
}): number | null {
if (!scene.value) return null
}): number | null {
if (!scene.value || !elem.value?.shadowRoot) return null
let id = nextLineId++;
let hotspotName1 = 'line' + id + '_start';
let hotspotName2 = 'line' + id + '_end';
scene.value.addHotspot(new Hotspot({name: hotspotName1, position: positionToHotspot(p1)}));
scene.value.addHotspot(new Hotspot({name: hotspotName2, position: positionToHotspot(p2)}));
lines.value[id] = {
startHotspot: elem.value.shadowRoot.querySelector('slot[name="' + hotspotName1 + '"]').parentElement,
endHotspot: elem.value.shadowRoot.querySelector('slot[name="' + hotspotName2 + '"]').parentElement,
startHotspot: elem.value.shadowRoot.querySelector('slot[name="' + hotspotName1 + '"]')!!.parentElement!!,
endHotspot: elem.value.shadowRoot.querySelector('slot[name="' + hotspotName2 + '"]')!!.parentElement!!,
start2D: [-1000, -1000],
end2D: [-1000, -1000],
centerText: centerText,
@@ -83,9 +83,9 @@ function addLine3D(p1: Vector3, p2: Vector3, centerText: string = "",
function removeLine3D(id: number): boolean {
if (!scene.value || !(id in lines.value)) return false;
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_start'}));
lines.value[id].startHotspot.parentElement.remove()
lines.value[id].startHotspot.parentElement?.remove()
scene.value.removeHotspot(new Hotspot({name: 'line' + id + '_end'}));
lines.value[id].endHotspot.parentElement.remove()
lines.value[id].endHotspot.parentElement?.remove()
delete lines.value[id];
scene.value.queueRender() // Needed to update the hotspots
return true;
@@ -101,7 +101,7 @@ function onCameraChange() {
let svg = ref<SVGElement | null>(null);
function onCameraChangeLine(lineId: number) {
if (!(lineId in lines.value)) return // Silently ignore (not updated yet)
if (!(lineId in lines.value) || !(elem.value)) return // Silently ignore (not updated yet)
// Update start and end 2D positions
let {x: xB, y: yB} = elem.value.getBoundingClientRect();
let {x, y} = lines.value[lineId].startHotspot.getBoundingClientRect();
@@ -110,7 +110,7 @@ function onCameraChangeLine(lineId: number) {
lines.value[lineId].end2D = [x2 - xB, y2 - yB];
// Update the center text size if needed
if (lines.value[lineId].centerText && lines.value[lineId].centerTextSize[0] == 0) {
if (svg.value && lines.value[lineId].centerText && lines.value[lineId].centerTextSize[0] === 0) {
let text = svg.value.getElementsByClassName('line' + lineId + '_text')[0] as SVGTextElement | undefined;
if (text) {
let bbox = text.getBBox();
@@ -135,7 +135,7 @@ function entries(lines: { [id: number]: Line3DData }): [string, Line3DData][] {
defineExpose({elem, onElemReady, scene, renderer, addLine3D, removeLine3D});
let {disableTap} = inject<{ disableTap: Ref<boolean> }>('disableTap');
let {disableTap} = inject<{ disableTap: Ref<boolean> }>('disableTap')!!;
watch(disableTap, (value) => {
// Rerender not auto triggered? This works anyway...
if (value) elem.value?.setAttribute('disable-tap', '');
@@ -147,7 +147,7 @@ watch(disableTap, (value) => {
<!-- The main 3D model viewer -->
<model-viewer ref="elem" style="width: 100%; height: 100%" :src="props.src" alt="The 3D model(s)" camera-controls
camera-orbit="30deg 75deg auto" max-camera-orbit="Infinity 180deg auto"
min-camera-orbit="-Infinity 0deg 5%" :disable-tap="disableTap.value" :exposure="settings.exposure"
min-camera-orbit="-Infinity 0deg 5%" :disable-tap="disableTap" :exposure="settings.exposure"
:shadow-intensity="settings.shadowIntensity" interaction-prompt="none" :autoplay="settings.autoplay"
:ar="settings.arModes.length > 0" :ar-modes="settings.arModes" :skybox-image="settings.background"
:environment-image="settings.background">
@@ -161,6 +161,7 @@ watch(disableTap, (value) => {
<g v-for="[lineId, line] in entries(lines)" :key="lineId">
<line :x1="line.start2D[0]" :y1="line.start2D[1]" :x2="line.end2D[0]"
:y2="line.end2D[1]" v-bind="line.lineAttrs"/>
<g v-if="line.centerText !== undefined">
<rect :x="(line.start2D[0] + line.end2D[0]) / 2 - line.centerTextSize[0]/2 - 4"
:y="(line.start2D[1] + line.end2D[1]) / 2 - line.centerTextSize[1]/2 - 2"
:width="line.centerTextSize[0] + 8" :height="line.centerTextSize[1] + 4"
@@ -171,6 +172,7 @@ watch(disableTap, (value) => {
{{ line.centerText }}
</text>
</g>
</g>
</svg>
</div>
</template>

12
index.html Normal file
View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="icon" href="assets/favicon.ico">
<title>Yet Another CAD Viewer</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="module" src="frontend/index.ts"></script>
</head>
<body>
</body>
</html>

View File

@@ -1,12 +1,16 @@
{
"name": "yet-another-cad-viewer",
"version": "0.0.1",
"version": "0.1.0",
"description": "",
"license": "MIT",
"author": "Yeicor",
"author": "Yeicor <4929005+Yeicor@users.noreply.github.com>",
"type": "module",
"scripts": {
"start": "parcel src/index.html",
"build": "yarn update-licenses && parcel build src/index.html --reporter @parcel/reporter-bundle-analyzer --detailed-report --public-url ./ --no-scope-hoist",
"dev": "vite",
"build": "run-s update-licenses && run-p type-check \"build-only {@}\" --",
"preview": "vite preview",
"build-only": "vite build",
"type-check": "vue-tsc --build --force",
"update-licenses": "generate-license-file --input package.json --output assets/licenses.txt --overwrite"
},
"dependencies": {
@@ -22,15 +26,19 @@
"vuetify": "^3.5.3"
},
"devDependencies": {
"@parcel/optimizer-data-url": "2.11.0",
"@parcel/reporter-bundle-analyzer": "^2.11.0",
"@parcel/transformer-inline-string": "2.11.0",
"@parcel/transformer-sass": "^2.11.0",
"@parcel/transformer-vue": "2.11.0",
"@tsconfig/node20": "^20.1.2",
"@types/node": "^20.11.17",
"@types/three": "^0.160.0",
"@vitejs/plugin-vue": "^5.0.3",
"@vitejs/plugin-vue-jsx": "^3.1.0",
"@vue/tsconfig": "^0.5.1",
"buffer": "^5.5.0||^6.0.0",
"commander": "^12.0.0",
"generate-license-file": "^3.0.1",
"parcel": "^2.11.0"
"npm-run-all2": "^6.1.1",
"terser": "^5.28.1",
"typescript": "~5.3.0",
"vite": "^5.0.11",
"vue-tsc": "^1.8.27"
}
}

View File

@@ -1,6 +1,6 @@
[tool.poetry]
name = "yacv-server"
version = "0.1.0" # TODO: Update automatically by CI on release
version = "0.1.0" # TODO: Update automatically by CI on release (also for package.json!)
description = "Yet Another CAD Viewer (server)"
authors = ["Yeicor <4929005+Yeicor@users.noreply.github.com>"]
license = "MIT"

View File

@@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Yet Another CAD Viewer</title>
<meta name='viewport' content='width=device-width, initial-scale=1'/>
<script type="module" src="./index.ts"></script>
</head>
<body>
</body>
</html>

8
src/shims.d.ts vendored
View File

@@ -1,8 +0,0 @@
// Avoids typescript error when importing files
declare module '*.vue'
declare module '@jamescoyle/vue-icon'
declare module 'three-orientation-gizmo/src/OrientationGizmo'
declare module 'vuetify/lib/styles/main.sass'
declare module '@mdi/font/css/materialdesignicons.css'
declare module 'vuetify/lib/components'
declare module 'vuetify/lib/directives'

View File

@@ -1,5 +1,19 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts",
"frontend/**/*",
"frontend/**/*.vue"
],
"exclude": [
"frontend/**/__tests__/*"
],
"compilerOptions": {
"lib": ["es2015", "DOM"]
"composite": true,
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
}
}

29
vite.config.ts Normal file
View File

@@ -0,0 +1,29 @@
import {fileURLToPath, URL} from 'node:url'
import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue({
template: {
compilerOptions: {
isCustomElement: tag => tag == 'model-viewer'
}
}
}),
vueJsx(),
],
resolve: {
alias: {
// @ts-ignore
'@': fileURLToPath(new URL('./src', import.meta.url))
}
},
build: {
assetsDir: '.',
cssCodeSplit: false, // Small enough to inline
}
})

2331
yarn.lock

File diff suppressed because it is too large Load Diff