@wonder-partners/model-viewer-stats 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # @wonder/model-viewer-stats
1
+ # `<model-viewer-stats>`
2
2
 
3
3
  A lightweight web component that displays comprehensive statistics for 3D models rendered with Google's `<model-viewer>`.
4
4
 
@@ -19,7 +19,7 @@ A lightweight web component that displays comprehensive statistics for 3D models
19
19
  ## Installation
20
20
 
21
21
  ```bash
22
- npm install @wonder/model-viewer-stats
22
+ npm install @wonder-partners/model-viewer-stats
23
23
  ```
24
24
 
25
25
  ### Peer Dependencies
@@ -33,7 +33,7 @@ Import the package and use the `<model-stats>` element inside your `<model-viewe
33
33
  ```html
34
34
  <script type="module">
35
35
  import '@google/model-viewer';
36
- import '@wonder/model-viewer-stats';
36
+ import '@wonder-partners/model-viewer-stats';
37
37
  </script>
38
38
 
39
39
  <model-viewer src="/path/to/model.glb" camera-controls>
@@ -45,13 +45,13 @@ Import the package and use the `<model-stats>` element inside your `<model-viewe
45
45
  ### ES Module Import
46
46
 
47
47
  ```javascript
48
- import { ModelStats } from '@wonder/model-viewer-stats';
48
+ import { ModelStats } from '@wonder-partners/model-viewer-stats';
49
49
  ```
50
50
 
51
51
  ### UMD (CommonJS)
52
52
 
53
53
  ```javascript
54
- const { ModelStats } = require('@wonder/model-viewer-stats');
54
+ const { ModelStats } = require('@wonder-partners/model-viewer-stats');
55
55
  ```
56
56
 
57
57
  ## API & Interaction
@@ -0,0 +1,133 @@
1
+ import { Box3 as u, Vector3 as v } from "three";
2
+ const f = String.raw;
3
+ class x extends HTMLElement {
4
+ constructor() {
5
+ super(), this.attachShadow({ mode: "open" }), this.viewer = null;
6
+ }
7
+ connectedCallback() {
8
+ this.render(), this.viewer = this.closest("model-viewer"), this.viewer && this.viewer.addEventListener("load", () => {
9
+ console.log("Model Viewer loaded"), this.calculateStats();
10
+ });
11
+ }
12
+ toggle() {
13
+ this.hasAttribute("visible") ? this.removeAttribute("visible") : this.setAttribute("visible", "");
14
+ }
15
+ render() {
16
+ this.shadowRoot.innerHTML = f`
17
+ <style>
18
+ :host {
19
+ position: absolute;
20
+ top: 1rem;
21
+ left: 1rem;
22
+ z-index: 1000;
23
+ background-color: rgba(0, 0, 0, 0.33);
24
+ color: white;
25
+ padding: 1rem;
26
+ border-radius: 0.5rem;
27
+ pointer-events: none;
28
+ opacity: 0;
29
+ transition: opacity 0.3s;
30
+ font-family: sans-serif;
31
+ font-size: 0.9rem;
32
+ }
33
+
34
+ :host([visible]) {
35
+ opacity: 1;
36
+ }
37
+
38
+ .row {
39
+ display: flex;
40
+ justify-content: space-between;
41
+ gap: 20px;
42
+ margin-bottom: 4px;
43
+ }
44
+
45
+ .row:last-child {
46
+ margin-bottom: 0;
47
+ }
48
+
49
+ .label {
50
+ opacity: 0.8;
51
+ }
52
+
53
+ .val {
54
+ font-weight: bold;
55
+ font-family: monospace;
56
+ }
57
+ </style>
58
+
59
+ <div class="row"><span class="label">File size:</span><span class="val" id="file">-</span></div>
60
+ <div class="row"><span class="label">Dimensions (W x H x D):</span><span class="val" id="size">-</span></div>
61
+ <div class="row"><span class="label">Triangles:</span><span class="val" id="tri">-</span></div>
62
+ <div class="row"><span class="label">Meshes:</span><span class="val" id="mesh">-</span></div>
63
+ <div class="row"><span class="label">Materials:</span><span class="val" id="mat">-</span></div>
64
+ <div class="row"><span class="label">Textures:</span><span class="val" id="tex">-</span></div>
65
+ <div class="row"><span class="label">Animations:</span><span class="val" id="anim">-</span></div>
66
+ `;
67
+ }
68
+ async calculateStats() {
69
+ if (!this.viewer) return;
70
+ const t = this.viewer.src;
71
+ t && fetch(t, { method: "HEAD" }).then((e) => {
72
+ const a = e.headers.get("content-length");
73
+ a ? this.updateText("file", this.formatBytes(Number(a))) : this.updateText("file", "N/A");
74
+ }).catch(() => {
75
+ this.updateText("file", "Unknown");
76
+ });
77
+ const i = this.getInternalScene(this.viewer);
78
+ if (!i) {
79
+ console.warn("[ModelStats] Could not access internal Three.js scene.");
80
+ return;
81
+ }
82
+ let s = 0, n = 0;
83
+ const o = /* @__PURE__ */ new Set(), l = /* @__PURE__ */ new Set(), r = new u();
84
+ if (i.traverse((e) => {
85
+ if (e.isMesh && e.geometry) {
86
+ n++;
87
+ const a = e.geometry;
88
+ s += a.index ? a.index.count / 3 : a.attributes.position.count / 3, r.expandByObject(e), (Array.isArray(e.material) ? e.material : [e.material]).forEach((c) => {
89
+ o.add(c);
90
+ for (const m in c) {
91
+ const p = c[m];
92
+ p?.isTexture && l.add(p.uuid);
93
+ }
94
+ });
95
+ }
96
+ }), r.isEmpty())
97
+ this.updateText("size", "0m");
98
+ else {
99
+ const e = new v();
100
+ r.getSize(e);
101
+ const a = (d) => `${d.toFixed(2)}`;
102
+ this.updateText("size", `${a(e.x)} x ${a(e.y)} x ${a(e.z)}`);
103
+ }
104
+ const h = this.viewer.availableAnimations ? this.viewer.availableAnimations.length : 0;
105
+ this.updateText("tri", Math.round(s).toLocaleString()), this.updateText("mesh", n.toLocaleString()), this.updateText("mat", o.size.toString()), this.updateText("tex", l.size.toString()), this.updateText("anim", h.toString());
106
+ }
107
+ updateText(t, i) {
108
+ const s = this.shadowRoot.getElementById(t);
109
+ s && (s.innerText = i);
110
+ }
111
+ formatBytes(t, i = 2) {
112
+ if (!+t) return "0 Bytes";
113
+ const s = 1024, n = i < 0 ? 0 : i, o = ["Bytes", "KB", "MB", "GB", "TB"], l = Math.floor(Math.log(t) / Math.log(s));
114
+ return `${parseFloat((t / s ** l).toFixed(n))} ${o[l]}`;
115
+ }
116
+ /**
117
+ * Retrieves the internal Three.js Scene from a <model-viewer> instance.
118
+ * * This function bypasses the public API to access the underlying symbol
119
+ * that holds the scene context. It is robust against minification and
120
+ * internal naming changes (e.g., 'model-viewer-scene' vs 'model-viewer-artboard').
121
+ * * @param {HTMLElement} viewer - The <model-viewer> DOM element.
122
+ * @returns {Object|null} The THREE.Scene object, or null if not found.
123
+ */
124
+ getInternalScene(t) {
125
+ if (!t) return null;
126
+ const s = Object.getOwnPropertySymbols(t).find((n) => t[n]?.scene?.isScene);
127
+ return s ? t[s].scene : null;
128
+ }
129
+ }
130
+ customElements.get("model-stats") || customElements.define("model-stats", x);
131
+ export {
132
+ x as ModelStats
133
+ };
@@ -0,0 +1,51 @@
1
+ (function(a,o){typeof exports=="object"&&typeof module<"u"?o(exports,require("three")):typeof define=="function"&&define.amd?define(["exports","three"],o):(a=typeof globalThis<"u"?globalThis:a||self,o(a["Model Viewer Stats"]={},a.THREE))})(this,(function(a,o){"use strict";const f=String.raw;class h extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"}),this.viewer=null}connectedCallback(){this.render(),this.viewer=this.closest("model-viewer"),this.viewer&&this.viewer.addEventListener("load",()=>{console.log("Model Viewer loaded"),this.calculateStats()})}toggle(){this.hasAttribute("visible")?this.removeAttribute("visible"):this.setAttribute("visible","")}render(){this.shadowRoot.innerHTML=f`
2
+ <style>
3
+ :host {
4
+ position: absolute;
5
+ top: 1rem;
6
+ left: 1rem;
7
+ z-index: 1000;
8
+ background-color: rgba(0, 0, 0, 0.33);
9
+ color: white;
10
+ padding: 1rem;
11
+ border-radius: 0.5rem;
12
+ pointer-events: none;
13
+ opacity: 0;
14
+ transition: opacity 0.3s;
15
+ font-family: sans-serif;
16
+ font-size: 0.9rem;
17
+ }
18
+
19
+ :host([visible]) {
20
+ opacity: 1;
21
+ }
22
+
23
+ .row {
24
+ display: flex;
25
+ justify-content: space-between;
26
+ gap: 20px;
27
+ margin-bottom: 4px;
28
+ }
29
+
30
+ .row:last-child {
31
+ margin-bottom: 0;
32
+ }
33
+
34
+ .label {
35
+ opacity: 0.8;
36
+ }
37
+
38
+ .val {
39
+ font-weight: bold;
40
+ font-family: monospace;
41
+ }
42
+ </style>
43
+
44
+ <div class="row"><span class="label">File size:</span><span class="val" id="file">-</span></div>
45
+ <div class="row"><span class="label">Dimensions (W x H x D):</span><span class="val" id="size">-</span></div>
46
+ <div class="row"><span class="label">Triangles:</span><span class="val" id="tri">-</span></div>
47
+ <div class="row"><span class="label">Meshes:</span><span class="val" id="mesh">-</span></div>
48
+ <div class="row"><span class="label">Materials:</span><span class="val" id="mat">-</span></div>
49
+ <div class="row"><span class="label">Textures:</span><span class="val" id="tex">-</span></div>
50
+ <div class="row"><span class="label">Animations:</span><span class="val" id="anim">-</span></div>
51
+ `}async calculateStats(){if(!this.viewer)return;const t=this.viewer.src;t&&fetch(t,{method:"HEAD"}).then(e=>{const i=e.headers.get("content-length");i?this.updateText("file",this.formatBytes(Number(i))):this.updateText("file","N/A")}).catch(()=>{this.updateText("file","Unknown")});const n=this.getInternalScene(this.viewer);if(!n){console.warn("[ModelStats] Could not access internal Three.js scene.");return}let s=0,l=0;const r=new Set,c=new Set,d=new o.Box3;if(n.traverse(e=>{if(e.isMesh&&e.geometry){l++;const i=e.geometry;s+=i.index?i.index.count/3:i.attributes.position.count/3,d.expandByObject(e),(Array.isArray(e.material)?e.material:[e.material]).forEach(p=>{r.add(p);for(const x in p){const m=p[x];m?.isTexture&&c.add(m.uuid)}})}}),d.isEmpty())this.updateText("size","0m");else{const e=new o.Vector3;d.getSize(e);const i=u=>`${u.toFixed(2)}`;this.updateText("size",`${i(e.x)} x ${i(e.y)} x ${i(e.z)}`)}const v=this.viewer.availableAnimations?this.viewer.availableAnimations.length:0;this.updateText("tri",Math.round(s).toLocaleString()),this.updateText("mesh",l.toLocaleString()),this.updateText("mat",r.size.toString()),this.updateText("tex",c.size.toString()),this.updateText("anim",v.toString())}updateText(t,n){const s=this.shadowRoot.getElementById(t);s&&(s.innerText=n)}formatBytes(t,n=2){if(!+t)return"0 Bytes";const s=1024,l=n<0?0:n,r=["Bytes","KB","MB","GB","TB"],c=Math.floor(Math.log(t)/Math.log(s));return`${parseFloat((t/s**c).toFixed(l))} ${r[c]}`}getInternalScene(t){if(!t)return null;const s=Object.getOwnPropertySymbols(t).find(l=>t[l]?.scene?.isScene);return s?t[s].scene:null}}customElements.get("model-stats")||customElements.define("model-stats",h),a.ModelStats=h,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"})}));
package/package.json CHANGED
@@ -1,19 +1,22 @@
1
1
  {
2
2
  "name": "@wonder-partners/model-viewer-stats",
3
3
  "private": false,
4
- "version": "1.0.0",
4
+ "version": "1.0.2",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/wonder-partners/model-viewer-stats.git"
8
8
  },
9
9
  "type": "module",
10
10
  "files": [
11
- "dist"
11
+ "dist",
12
+ "src"
12
13
  ],
13
14
  "main": "./dist/model-viewer-stats.umd.cjs",
14
15
  "module": "./dist/model-viewer-stats.js",
16
+ "types": "./src/index.d.ts",
15
17
  "exports": {
16
18
  ".": {
19
+ "types": "./src/index.d.ts",
17
20
  "import": "./dist/model-viewer-stats.js",
18
21
  "require": "./dist/model-viewer-stats.umd.cjs"
19
22
  }
@@ -0,0 +1,19 @@
1
+ export class ModelStats extends HTMLElement {
2
+ constructor();
3
+ viewer: HTMLElement | null;
4
+ connectedCallback(): void;
5
+ toggle(): void;
6
+ render(): void;
7
+ calculateStats(): Promise<void>;
8
+ updateText(id: string, text: string): void;
9
+ formatBytes(bytes: number, decimals?: number): string;
10
+ /**
11
+ * Retrieves the internal Three.js Scene from a <model-viewer> instance.
12
+ * * This function bypasses the public API to access the underlying symbol
13
+ * that holds the scene context. It is robust against minification and
14
+ * internal naming changes (e.g., 'model-viewer-scene' vs 'model-viewer-artboard').
15
+ * * @param {HTMLElement} viewer - The <model-viewer> DOM element.
16
+ * @returns {Object|null} The THREE.Scene object, or null if not found.
17
+ */
18
+ getInternalScene(viewer: HTMLElement): any;
19
+ }
@@ -0,0 +1,212 @@
1
+ import { Box3, Vector3 } from "three";
2
+
3
+ const html = String.raw;
4
+
5
+ export class ModelStats extends HTMLElement {
6
+ constructor() {
7
+ super();
8
+ this.attachShadow({ mode: "open" });
9
+ this.viewer = null;
10
+ }
11
+
12
+ connectedCallback() {
13
+ this.render();
14
+ this.viewer = this.closest("model-viewer");
15
+
16
+ if (this.viewer) {
17
+ this.viewer.addEventListener("load", () => {
18
+ console.log("Model Viewer loaded");
19
+ this.calculateStats();
20
+ });
21
+ }
22
+ }
23
+
24
+ toggle() {
25
+ if (this.hasAttribute("visible")) {
26
+ this.removeAttribute("visible");
27
+ } else {
28
+ this.setAttribute("visible", "");
29
+ }
30
+ }
31
+
32
+ render() {
33
+ this.shadowRoot.innerHTML = html`
34
+ <style>
35
+ :host {
36
+ position: absolute;
37
+ top: 1rem;
38
+ left: 1rem;
39
+ z-index: 1000;
40
+ background-color: rgba(0, 0, 0, 0.33);
41
+ color: white;
42
+ padding: 1rem;
43
+ border-radius: 0.5rem;
44
+ pointer-events: none;
45
+ opacity: 0;
46
+ transition: opacity 0.3s;
47
+ font-family: sans-serif;
48
+ font-size: 0.9rem;
49
+ }
50
+
51
+ :host([visible]) {
52
+ opacity: 1;
53
+ }
54
+
55
+ .row {
56
+ display: flex;
57
+ justify-content: space-between;
58
+ gap: 20px;
59
+ margin-bottom: 4px;
60
+ }
61
+
62
+ .row:last-child {
63
+ margin-bottom: 0;
64
+ }
65
+
66
+ .label {
67
+ opacity: 0.8;
68
+ }
69
+
70
+ .val {
71
+ font-weight: bold;
72
+ font-family: monospace;
73
+ }
74
+ </style>
75
+
76
+ <div class="row"><span class="label">File size:</span><span class="val" id="file">-</span></div>
77
+ <div class="row"><span class="label">Dimensions (W x H x D):</span><span class="val" id="size">-</span></div>
78
+ <div class="row"><span class="label">Triangles:</span><span class="val" id="tri">-</span></div>
79
+ <div class="row"><span class="label">Meshes:</span><span class="val" id="mesh">-</span></div>
80
+ <div class="row"><span class="label">Materials:</span><span class="val" id="mat">-</span></div>
81
+ <div class="row"><span class="label">Textures:</span><span class="val" id="tex">-</span></div>
82
+ <div class="row"><span class="label">Animations:</span><span class="val" id="anim">-</span></div>
83
+ `;
84
+ }
85
+
86
+ async calculateStats() {
87
+ if (!this.viewer) return;
88
+
89
+ // --- File Size ---
90
+ const src = this.viewer.src;
91
+ if (src) {
92
+ fetch(src, { method: "HEAD" })
93
+ .then((res) => {
94
+ const size = res.headers.get("content-length");
95
+ if (size) {
96
+ this.updateText("file", this.formatBytes(Number(size)));
97
+ } else {
98
+ this.updateText("file", "N/A");
99
+ }
100
+ })
101
+ .catch(() => {
102
+ this.updateText("file", "Unknown");
103
+ });
104
+ }
105
+
106
+ // --- Scene traversal for geometry stats ---
107
+ const scene = this.getInternalScene(this.viewer);
108
+
109
+ if (!scene) {
110
+ console.warn("[ModelStats] Could not access internal Three.js scene.");
111
+ return;
112
+ }
113
+
114
+ let triCount = 0;
115
+ let meshCount = 0;
116
+ const materials = new Set();
117
+ const textures = new Set();
118
+ const box = new Box3();
119
+
120
+ scene.traverse((obj) => {
121
+ if (obj.isMesh && obj.geometry) {
122
+ meshCount++;
123
+ const geom = obj.geometry;
124
+ triCount += geom.index ? geom.index.count / 3 : geom.attributes.position.count / 3;
125
+
126
+ // Bounding Box
127
+ // We assume the object is part of the model.
128
+ // expandByObject computes the world-axis-aligned box
129
+ box.expandByObject(obj);
130
+
131
+ // Materials
132
+ const mats = Array.isArray(obj.material) ? obj.material : [obj.material];
133
+ mats.forEach((m) => {
134
+ materials.add(m);
135
+ // Textures
136
+ for (const key in m) {
137
+ const val = m[key];
138
+ if (val?.isTexture) {
139
+ textures.add(val.uuid);
140
+ }
141
+ }
142
+ });
143
+ }
144
+ });
145
+
146
+ // Size
147
+ if (!box.isEmpty()) {
148
+ const size = new Vector3();
149
+ box.getSize(size);
150
+ // Format as W x H x D
151
+ // box.getSize returns width, height, depth.
152
+ // Let's assume Y is up, but just printing dimensions is fine.
153
+ const fmt = (n) => `${n.toFixed(2)}`;
154
+ this.updateText("size", `${fmt(size.x)} x ${fmt(size.y)} x ${fmt(size.z)}`);
155
+ } else {
156
+ this.updateText("size", "0m");
157
+ }
158
+
159
+ const animationCount = this.viewer.availableAnimations
160
+ ? this.viewer.availableAnimations.length
161
+ : 0;
162
+
163
+ this.updateText("tri", Math.round(triCount).toLocaleString());
164
+ this.updateText("mesh", meshCount.toLocaleString());
165
+ this.updateText("mat", materials.size.toString());
166
+ this.updateText("tex", textures.size.toString());
167
+ this.updateText("anim", animationCount.toString());
168
+ }
169
+
170
+ updateText(id, text) {
171
+ const el = this.shadowRoot.getElementById(id);
172
+ if (el) el.innerText = text;
173
+ }
174
+
175
+ formatBytes(bytes, decimals = 2) {
176
+ if (!+bytes) return "0 Bytes";
177
+ const k = 1024;
178
+ const dm = decimals < 0 ? 0 : decimals;
179
+ const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
180
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
181
+ return `${parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
182
+ }
183
+
184
+ /**
185
+ * Retrieves the internal Three.js Scene from a <model-viewer> instance.
186
+ * * This function bypasses the public API to access the underlying symbol
187
+ * that holds the scene context. It is robust against minification and
188
+ * internal naming changes (e.g., 'model-viewer-scene' vs 'model-viewer-artboard').
189
+ * * @param {HTMLElement} viewer - The <model-viewer> DOM element.
190
+ * @returns {Object|null} The THREE.Scene object, or null if not found.
191
+ */
192
+ getInternalScene(viewer) {
193
+ if (!viewer) return null;
194
+
195
+ // We cannot rely on the symbol name (e.g., 'model-viewer-scene') because
196
+ // it changes between versions (v3.0 vs v3.4) and is stripped in minified builds.
197
+ // Instead, we inspect the symbols to find the one holding a valid Three.js scene.
198
+
199
+ // 1. Get all symbols from the element
200
+ const symbols = Object.getOwnPropertySymbols(viewer);
201
+
202
+ // 2. Find the symbol that points to an object containing a valid THREE scene.
203
+ const sceneSymbol = symbols.find((sym) => {
204
+ const value = viewer[sym];
205
+ return value?.scene?.isScene;
206
+ });
207
+
208
+ if (!sceneSymbol) return null;
209
+
210
+ return viewer[sceneSymbol].scene;
211
+ }
212
+ }
package/src/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import { ModelStats } from "./ModelStats.js";
2
+ export { ModelStats };
package/src/index.js ADDED
@@ -0,0 +1,7 @@
1
+ import { ModelStats } from "./ModelStats.js";
2
+
3
+ export { ModelStats };
4
+
5
+ if (!customElements.get("model-stats")) {
6
+ customElements.define("model-stats", ModelStats);
7
+ }