@dvt3d/splat-mesh 1.0.0
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/LICENSE +201 -0
- package/README.md +161 -0
- package/dist/index.js +1 -0
- package/dist/splat-mesh.min.js +1 -0
- package/dist/workers/wasm_splat.min.js +1 -0
- package/dist/workers/wasm_splat.worker.min.js +1 -0
- package/dist/workers/wasm_splat_bg.wasm +0 -0
- package/package.json +40 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# Splat Mesh
|
|
2
|
+
|
|
3
|
+
A lightweight, high-performance 3D Gaussian Splatting renderer for Three.js. This implementation uses:
|
|
4
|
+
|
|
5
|
+
- GPU texture packing
|
|
6
|
+
- Instanced rendering
|
|
7
|
+
- View-dependent sorting in WebWorker
|
|
8
|
+
- Optional frustum-aware sorting
|
|
9
|
+
- Designed for large-scale splat datasets (100K–1M+ splats).
|
|
10
|
+
|
|
11
|
+
## Introduction
|
|
12
|
+
|
|
13
|
+
SplatMesh is a custom Three.js Mesh implementation that renders Gaussian splats using:
|
|
14
|
+
|
|
15
|
+
- DataTexture for storing splat attributes
|
|
16
|
+
- InstancedBufferGeometry for drawing
|
|
17
|
+
- WebWorker for per-frame view-space sorting
|
|
18
|
+
|
|
19
|
+
The renderer supports dynamic camera movement and maintains correct blending order by sorting splats every frame.
|
|
20
|
+
|
|
21
|
+
## Principle Overview
|
|
22
|
+
|
|
23
|
+
### Data Storage
|
|
24
|
+
|
|
25
|
+
Each splat is stored in two GPU textures:
|
|
26
|
+
|
|
27
|
+
| Texture | Format | Content |
|
|
28
|
+
|-----------------------|----------|-------------------------|
|
|
29
|
+
| centerAndScaleTexture | RGBA32F | center.xyz + scale |
|
|
30
|
+
| covAndColorTexture | RGBA32UI | rotation + packed color |
|
|
31
|
+
|
|
32
|
+
Texture size:
|
|
33
|
+
|
|
34
|
+
```js
|
|
35
|
+
|
|
36
|
+
const width = maxTextureSize
|
|
37
|
+
const height = ceil(vertexCount / width)
|
|
38
|
+
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
### Rendering Pipeline
|
|
42
|
+
|
|
43
|
+
```
|
|
44
|
+
Input buffer / geometry
|
|
45
|
+
↓
|
|
46
|
+
Worker: process splats
|
|
47
|
+
↓
|
|
48
|
+
Upload packed textures to GPU
|
|
49
|
+
↓
|
|
50
|
+
Per frame:
|
|
51
|
+
compute modelView matrix
|
|
52
|
+
worker sorts splats
|
|
53
|
+
update splatIndex buffer
|
|
54
|
+
↓
|
|
55
|
+
Instanced rendering
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Sorting is view-dependent to ensure correct blending.
|
|
59
|
+
|
|
60
|
+
## Usage
|
|
61
|
+
|
|
62
|
+
```js
|
|
63
|
+
const worker = new SplatWorker('***/wasm_splat.worker.min.js')
|
|
64
|
+
const splatMesh = new SplatMesh()
|
|
65
|
+
splatMesh.attachWorker(worker)
|
|
66
|
+
splatMesh.setVertexCount(data.numSplats)
|
|
67
|
+
await splatMesh.setDataFromBuffer(data.buffer)
|
|
68
|
+
scene.add(splatMesh)
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
## Why the Worker Is Injected
|
|
72
|
+
|
|
73
|
+
> The worker is injected externally to separate rendering logic from CPU-intensive computation. SplatMesh focuses purely
|
|
74
|
+
> on GPU resources and drawing, while the Worker handles heavy tasks such as splat processing, view-dependent sorting,
|
|
75
|
+
> and
|
|
76
|
+
> bounds computation. This design allows multiple meshes to share a single Worker (and WASM instance), reduces memory
|
|
77
|
+
> and
|
|
78
|
+
> thread overhead, improves lifecycle control, and follows a clean dependency injection architecture. In short, the mesh
|
|
79
|
+
> renders, the worker computes — keeping the system modular, efficient, and scalable.
|
|
80
|
+
|
|
81
|
+
## Examples
|
|
82
|
+
|
|
83
|
+
Live examples demonstrating different input formats:
|
|
84
|
+
|
|
85
|
+
- PLY Example: `examples/ply.html`
|
|
86
|
+
- SOG Example: `examples/sog.html`
|
|
87
|
+
- SPLAT Example: `examples/splat.html`
|
|
88
|
+
- SPZ Example : `examples/spz.html`
|
|
89
|
+
|
|
90
|
+
> You can use the [3dgs-loader](https://www.npmjs.com/package/3dgs-loader) library to load 3D Gaussian Splatting data in
|
|
91
|
+
> formats such as .ply, .splat, .spz, or .sog. It provides a unified and browser-friendly API that parses and decodes
|
|
92
|
+
> the data into a standardized { numSplats, buffer } structure, which can be passed directly to SplatMesh. The loader is
|
|
93
|
+
> available via CDN (e.g. https://cdn.jsdelivr.net/npm/3dgs-loader@1.2.0/+esm) and is recommended for simplifying data
|
|
94
|
+
> loading while keeping rendering and parsing responsibilities cleanly separated.
|
|
95
|
+
|
|
96
|
+
## SplatMesh API
|
|
97
|
+
|
|
98
|
+
### Constructor
|
|
99
|
+
|
|
100
|
+
```js
|
|
101
|
+
const mesh = new SplatMesh()
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
### Properties
|
|
105
|
+
|
|
106
|
+
- `{Number} vertexCount` : Number of splats, Must be set before loading data.
|
|
107
|
+
- `{Number} threshold` : Sorting threshold value.
|
|
108
|
+
- `{SplatWoker} worker` : Attached sorting worker.
|
|
109
|
+
- `{Array} bounds` : Bounding box (after computeBounds()).
|
|
110
|
+
- `{Boolean} useFrustumCulled` : Enable frustum planes for worker-side culling.
|
|
111
|
+
|
|
112
|
+
### Methods
|
|
113
|
+
|
|
114
|
+
- `detachWorker(worker):SplatMesh` : Attach a Worker instance.
|
|
115
|
+
|
|
116
|
+
```js
|
|
117
|
+
mesh.attachWorker(worker)
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
- `detachWorker():SplatMesh` : Detach current worker.
|
|
121
|
+
|
|
122
|
+
```js
|
|
123
|
+
mesh.detachWorker()
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
- `setVertexCount(count):SplatMesh` : Allocate textures and instance attributes, Must be called before loading splat
|
|
127
|
+
data.
|
|
128
|
+
|
|
129
|
+
```js
|
|
130
|
+
mesh.setVertexCount(1000)
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- `setDataFromBuffer(buffer):Promise<SplatMesh>` : Load splat data from ArrayBuffer.
|
|
134
|
+
|
|
135
|
+
```js
|
|
136
|
+
await mesh.setDataFromBuffer(buffer)
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
- `setDataFromGeometry(geometry):Promise<SplatMesh>` : Load splats from Three.js geometry.
|
|
140
|
+
|
|
141
|
+
```js
|
|
142
|
+
await mesh.setDataFromGeometry(geometry)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
- `setDataFromSpz(spzData):Promise<SplatMesh>` : Load splats from SPZ data structure.
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
await mesh.setDataFromSpz(spzData)
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
- `computeBounds():Promise<SplatMesh>` : Compute bounding box via worker.
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
await mesh.computeBounds()
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
- `dispose()` : Release GPU resources and unregister worker data.
|
|
158
|
+
|
|
159
|
+
```js
|
|
160
|
+
mesh.dispose()
|
|
161
|
+
```
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{BufferAttribute as I,BufferGeometry as P,CustomBlending as W,DataTexture as A,DynamicDrawUsage as V,FloatType as U,InstancedBufferAttribute as z,InstancedBufferGeometry as B,Mesh as R,OneFactor as j,RGBAFormat as G,RGBAIntegerFormat as H,ShaderMaterial as E,UnsignedIntType as q,Vector4 as $,Frustum as J,Matrix4 as L}from"three";var g="precision highp sampler2D;precision highp usampler2D;out vec4 vColor;out vec2 vPosition;uniform vec2 viewport;uniform mat4 gsModelViewMatrix;attribute uint splatIndex;uniform sampler2D centerAndScaleTexture;uniform usampler2D covAndColorTexture;vec2 unpackInt16(in uint value){int v=int(value);int v0=v>>16;int v1=(v&0xFFFF);if((v&0x8000)!=0)v1|=0xFFFF0000;return vec2(float(v1),float(v0));}vec4 calcCovVectors(vec3 viewPos,mat3 Vrk){float focal=(viewport.y/2.0)*abs(projectionMatrix[1][1]);mat3 J=mat3(focal/viewPos.z,0.,-(focal*viewPos.x)/(viewPos.z*viewPos.z),0.,focal/viewPos.z,-(focal*viewPos.y)/(viewPos.z*viewPos.z),0.,0.,0.);mat3 W=transpose(mat3(gsModelViewMatrix));mat3 T=W*J;mat3 cov=transpose(T)*Vrk*T;float diagonal1=cov[0][0]+0.3;float offDiagonal=cov[0][1];float diagonal2=cov[1][1]+0.3;float mid=0.5*(diagonal1+diagonal2);float radius=length(vec2((diagonal1-diagonal2)/2.0,offDiagonal));float lambda1=mid+radius;float lambda2=max(mid-radius,0.1);vec2 diagonalVector=normalize(vec2(offDiagonal,lambda1-diagonal1));vec2 v1=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 v2=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);return vec4(v1,v2);}void main(){ivec2 texSize=textureSize(centerAndScaleTexture,0);ivec2 texPos=ivec2(splatIndex % uint(texSize.x),splatIndex/uint(texSize.x));vec4 centerAndScaleData=texelFetch(centerAndScaleTexture,texPos,0);vec4 viewPos=gsModelViewMatrix*vec4(centerAndScaleData.xyz,1);vec4 pos2d=projectionMatrix*viewPos;float clip=1.2*pos2d.w;if(pos2d.z<-pos2d.w||pos2d.x<-clip||pos2d.x>clip||pos2d.y<-clip||pos2d.y>clip){gl_Position=vec4(0.0,0.0,2.0,1.0);return;}uvec4 covAndColorData=texelFetch(covAndColorTexture,texPos,0);vec2 cov3D_M11_M12=unpackInt16(covAndColorData.x)*centerAndScaleData.w;vec2 cov3D_M13_M22=unpackInt16(covAndColorData.y)*centerAndScaleData.w;vec2 cov3D_M23_M33=unpackInt16(covAndColorData.z)*centerAndScaleData.w;mat3 Vrk=mat3(cov3D_M11_M12.x,cov3D_M11_M12.y,cov3D_M13_M22.x,cov3D_M11_M12.y,cov3D_M13_M22.y,cov3D_M23_M33.x,cov3D_M13_M22.x,cov3D_M23_M33.x,cov3D_M23_M33.y);vec4 covVectors=calcCovVectors(viewPos.xyz,Vrk);vPosition=position.xy;uint colorUint=covAndColorData.w;vColor=vec4(float(colorUint&uint(0xFF))/255.0,float((colorUint>>uint(8))&uint(0xFF))/255.0,float((colorUint>>uint(16))&uint(0xFF))/255.0,float(colorUint>>uint(24))/255.0);vec2 vCenter=vec2(pos2d)/pos2d.w;gl_Position=vec4(vCenter+(position.x*covVectors.zw+position.y*covVectors.xy)/viewport*2.0,pos2d.z/pos2d.w,1.0);}";var S="in vec4 vColor;in vec2 vPosition;void main(){float A=-dot(vPosition,vPosition);if(A<-4.0)discard;float B=exp(A)*vColor.a;gl_FragColor=vec4(vColor.rgb,B);}";var x=class{constructor(){this._intervalTime=200,this._stableStopTime=3e3,this._isSorting=!1,this._dirty=!0,this._lastMvMatrix=null,this._lastSortTime=0,this._stableSince=0}set isSorting(t){this._isSorting=t}get isSorting(){return this._isSorting}set dirty(t){this._dirty=t}get dirty(){return this._dirty}set intervalTime(t){this._intervalTime=t}get intervalTime(){return this._intervalTime}set stableStopTime(t){this._stableStopTime=t}get stableStopTime(){return this._stableStopTime}_isMatrixChanged(t,e){return t?!t.equals(e):!0}tick(t,e){let r=performance.now(),i=this._isMatrixChanged(this._lastMvMatrix,t);i?this._stableSince=r:this._stableSince===0&&(this._stableSince=r);let s=r-this._lastSortTime>=this._intervalTime,h=r-this._stableSince<this._stableStopTime;return!this._isSorting&&s&&(this._dirty||i||h)&&(this._isSorting=!0,this._dirty=!1,this._lastSortTime=r,e()),this._lastMvMatrix=t,this}},M=x;var F="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");function y(o="D"){let t=[];t[8]=t[13]=t[18]=t[23]="-",t[14]="4";let e;for(let r=0;r<36;r++)t[r]||(e=0|Math.random()*16,t[r]=F[r===19?e&3|8:e]);return o+"-"+t.join("")}function k(){let o=document.createElement("canvas"),t=o.getContext("webgl2")||o.getContext("webgl");return t.getParameter(t.MAX_TEXTURE_SIZE)}var f=k(),O=f*f,C=new P;C.setAttribute("position",new I(new Float32Array([-2,-2,0,2,2,0,-2,2,0,2,-2,0,2,2,0,-2,-2,0]),3));var v=class extends R{constructor(){super(),this._meshId=y(),this._vertexCount=0,this._textureWidth=f,this._textureHeight=1,this._threshold=-1e-5,this._centerAndScaleData=null,this._centerAndScaleTexture=null,this._rotationAndColorData=null,this._rotationAndColorTexture=null,this.geometry=new B().copy(C),this.geometry.instanceCount=1,this.material=new E({uniforms:{viewport:{value:new Float32Array([1980,1080])},centerAndScaleTexture:{value:null},covAndColorTexture:{value:null},gsModelViewMatrix:{value:null}},vertexShader:g,fragmentShader:S,blending:W,blendSrcAlpha:j,depthTest:!0,depthWrite:!1,transparent:!0}),this.material.onBeforeRender=this._onMaterialBeforeRender.bind(this),this.frustumCulled=!1,this._bounds=null,this._sortScheduler=new M,this._worker=null,this._useFrustumCulled=!1}get isSplatMesh(){return!0}set threshold(t){this._threshold=t}get threshold(){return this._threshold}set worker(t){this._worker=t}get worker(){return this._worker}get bounds(){return this._bounds}set vertexCount(t){this.setVertexCount(t)}get vertexCount(){return this._vertexCount}set useFrustumCulled(t){this._useFrustumCulled=t}get useFrustumCulled(){return this._useFrustumCulled}get sortScheduler(){return this._sortScheduler}_getModelViewMatrix(t){return t.matrixWorld.clone().invert().multiply(this.matrixWorld)}_updateTexture(t,e){t&&this._meshId===t.meshId&&(this._centerAndScaleData.set(t.out_cs),this._rotationAndColorData.set(t.out_rc),this._centerAndScaleTexture.image.data.set(this._centerAndScaleData.subarray(0,e*4),0),this._rotationAndColorTexture.image.data.set(this._rotationAndColorData.subarray(0,e*4),0),this._centerAndScaleTexture.needsUpdate=!0,this._rotationAndColorTexture.needsUpdate=!0,this._sortScheduler.dirty=!0)}_onMaterialBeforeRender(t,e,r,i,s,h){let u=this._getModelViewMatrix(r),p=s.material;p.uniforms.gsModelViewMatrix.value=u;let m=new $;t.getCurrentViewport(m),p.uniforms.viewport.value[0]=m.z,p.uniforms.viewport.value[1]=m.w,this._sortScheduler&&this._sortScheduler.tick(u,()=>{let c=u.elements,D=new Float32Array([c[2],c[6],c[10],c[14]]),a=new Float32Array(0);if(this._useFrustumCulled){a=new Float32Array(24);let n=new L;n.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse);let l=new J;l.setFromProjectionMatrix(n),l.planes.forEach((d,_)=>{a[_*4+0]=d.normal.x,a[_*4+1]=d.normal.y,a[_*4+2]=d.normal.z,a[_*4+3]=d.constant})}this._worker&&this._worker.call("sort_splats",this._meshId,D,a,this._threshold).then(n=>{if(n||(this._sortScheduler.isSorting=!1),n&&this._meshId===n.meshId){let l=new Uint32Array(n.data);this.geometry.attributes.splatIndex.set(l),this.geometry.attributes.splatIndex.needsUpdate=!0,this.geometry.instanceCount=l.length,this._sortScheduler.isSorting=!1}})})}setVertexCount(t){if(t===this._vertexCount)return;this._vertexCount=Math.min(t,O),this._textureHeight=Math.floor((this._vertexCount-1)/this._textureWidth)+1,this._centerAndScaleData=new Float32Array(this._textureWidth*this._textureHeight*4),this._centerAndScaleTexture&&this._centerAndScaleTexture.dispose(),this._centerAndScaleTexture=new A(this._centerAndScaleData,this._textureWidth,this._textureHeight,G,U),this._rotationAndColorData=new Uint32Array(this._textureWidth*this._textureHeight*4),this._rotationAndColorTexture&&this._rotationAndColorTexture.dispose(),this._rotationAndColorTexture=new A(this._rotationAndColorData,this._textureWidth,this._textureHeight,H,q),this._rotationAndColorTexture.internalFormat="RGBA32UI";let e=new Uint32Array(this._textureWidth*this._textureHeight),r=new z(e,1,!1);return r.setUsage(V),this.geometry.setAttribute("splatIndex",r),this.material.uniforms.centerAndScaleTexture.value=this._centerAndScaleTexture,this.material.uniforms.covAndColorTexture.value=this._rotationAndColorTexture,this}attachWorker(t){return this._worker=t,this}detachWorker(){return this._worker&&this._worker.call("unregister_positions",this._bufferId),this._worker=null,this}async setDataFromBuffer(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromBuffer skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromBuffer skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_buffer",this._meshId,t,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async setDataFromGeometry(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromGeometry skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromGeometry skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_geometry",this._meshId,t.attributes.position.array,t.attributes._scale.array,t.attributes._rotation.array,t.attributes.color.array,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async setDataFromSpz(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromSpz skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromSpz skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_spz",this._meshId,t.positions,t.scales,t.rotations,t.colors,t.alphas,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async computeBounds(){if(!this._worker)return console.warn("[SplatMesh] computeBounds skipped: worker not ready"),this;if(!this._bounds){let t=await this._worker.call("compute_bounds",this._meshId);this._meshId===t.meshId&&(this._bounds=t.data)}return this}dispose(){this._bounds=null,this._centerAndScaleTexture&&(this._centerAndScaleTexture.dispose(),this._centerAndScaleData=null),this._rotationAndColorTexture&&(this._rotationAndColorTexture.dispose(),this._rotationAndColorData=null),this._worker&&this._worker.call("unregister_positions",this._bufferId),this._bufferId=null,this._sortScheduler=null,this.geometry.dispose(),this.material.dispose(),this.parent=null}},b=v;var w=class{constructor(t,{timeout:e=0}={}){this._workerUrl=t,this._worker=null,this._seq=0,this._pending=new Map,this._timeout=e,this._initPromise=null,this._ready=!1,this._createWorker()}_createWorker(){let t=e=>{e.onmessage=r=>this._handleMessage(r),e.onerror=r=>this._handleError(r),e.onmessageerror=r=>console.error("[SplatWorker] Worker message error:",r)};try{this._worker=new Worker(this._workerUrl,{type:"module"}),t(this._worker);return}catch(e){console.error("Worker error:",e)}fetch(this._workerUrl).then(e=>{if(!e.ok)throw new Error(`[SplatWorker] Failed to fetch worker: ${this._workerUrl}`);return e.text()}).then(e=>{let r=new Blob([e],{type:"application/javascript"}),i=URL.createObjectURL(r);this._worker=new Worker(i),t(this._worker)})}_handleMessage(t){let{id:e,result:r,error:i}=t.data,s=this._pending.get(e);s&&(this._pending.delete(e),i?s.reject(i):s.resolve(r))}_handleError(t){console.error("[SplatWorker] Worker error:",t);for(let[e,r]of this._pending)r.reject("[SplatWorker] Worker crashed");this._pending.clear()}_collectTransferables(t){let e=[];for(let r of t)r&&(ArrayBuffer.isView(r)?e.push(r.buffer):r instanceof ArrayBuffer&&e.push(r));return e}async init(){if(this._ready)return!0;if(this._initPromise)return this._initPromise;this._initPromise=new Promise((e,r)=>{let i=++this._seq;this._pending.set(i,{resolve:e,reject:r}),this._worker.postMessage({id:i,fn:"__init_wasm__",args:[]})});let t=await this._initPromise;return this._ready=!0,t}call(t,...e){return new Promise((r,i)=>{this._worker||i(`the worker ${this._workerUrl} does not exist`);let s=++this._seq;this._pending.set(s,{resolve:r,reject:i});let h=this._collectTransferables(e);this._worker.postMessage({id:s,fn:t,args:e},h),this._timeout>0&&setTimeout(()=>{this._pending.has(s)&&(this._pending.delete(s),i(`[SplatWorker] Task "${t}" timeout after ${this._timeout}ms`))},this._timeout)})}cancel(t,e="canceled"){let r=this._pending.get(t);return r&&(r.reject(e),this._pending.delete(t)),this}dispose(){return this._worker.terminate(),this._pending.clear(),this}},T=w;typeof window!="undefined"&&(window.SplatMesh=b,window.SplatWorker=T);export{b as SplatMesh,T as SplatWorker};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
(()=>{var W=Object.create;var S=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var z=Object.getPrototypeOf,B=Object.prototype.hasOwnProperty;var R=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var E=(o,t,e,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of U(t))!B.call(o,s)&&s!==e&&S(o,s,{get:()=>t[s],enumerable:!(r=V(t,s))||r.enumerable});return o};var H=(o,t,e)=>(e=o!=null?W(z(o)):{},E(t||!o||!o.__esModule?S(e,"default",{value:o,enumerable:!0}):e,o));var y=R(($,M)=>{M.exports=THREE});var i=H(y());var k="precision highp sampler2D;precision highp usampler2D;out vec4 vColor;out vec2 vPosition;uniform vec2 viewport;uniform mat4 gsModelViewMatrix;attribute uint splatIndex;uniform sampler2D centerAndScaleTexture;uniform usampler2D covAndColorTexture;vec2 unpackInt16(in uint value){int v=int(value);int v0=v>>16;int v1=(v&0xFFFF);if((v&0x8000)!=0)v1|=0xFFFF0000;return vec2(float(v1),float(v0));}vec4 calcCovVectors(vec3 viewPos,mat3 Vrk){float focal=(viewport.y/2.0)*abs(projectionMatrix[1][1]);mat3 J=mat3(focal/viewPos.z,0.,-(focal*viewPos.x)/(viewPos.z*viewPos.z),0.,focal/viewPos.z,-(focal*viewPos.y)/(viewPos.z*viewPos.z),0.,0.,0.);mat3 W=transpose(mat3(gsModelViewMatrix));mat3 T=W*J;mat3 cov=transpose(T)*Vrk*T;float diagonal1=cov[0][0]+0.3;float offDiagonal=cov[0][1];float diagonal2=cov[1][1]+0.3;float mid=0.5*(diagonal1+diagonal2);float radius=length(vec2((diagonal1-diagonal2)/2.0,offDiagonal));float lambda1=mid+radius;float lambda2=max(mid-radius,0.1);vec2 diagonalVector=normalize(vec2(offDiagonal,lambda1-diagonal1));vec2 v1=min(sqrt(2.0*lambda1),1024.0)*diagonalVector;vec2 v2=min(sqrt(2.0*lambda2),1024.0)*vec2(diagonalVector.y,-diagonalVector.x);return vec4(v1,v2);}void main(){ivec2 texSize=textureSize(centerAndScaleTexture,0);ivec2 texPos=ivec2(splatIndex % uint(texSize.x),splatIndex/uint(texSize.x));vec4 centerAndScaleData=texelFetch(centerAndScaleTexture,texPos,0);vec4 viewPos=gsModelViewMatrix*vec4(centerAndScaleData.xyz,1);vec4 pos2d=projectionMatrix*viewPos;float clip=1.2*pos2d.w;if(pos2d.z<-pos2d.w||pos2d.x<-clip||pos2d.x>clip||pos2d.y<-clip||pos2d.y>clip){gl_Position=vec4(0.0,0.0,2.0,1.0);return;}uvec4 covAndColorData=texelFetch(covAndColorTexture,texPos,0);vec2 cov3D_M11_M12=unpackInt16(covAndColorData.x)*centerAndScaleData.w;vec2 cov3D_M13_M22=unpackInt16(covAndColorData.y)*centerAndScaleData.w;vec2 cov3D_M23_M33=unpackInt16(covAndColorData.z)*centerAndScaleData.w;mat3 Vrk=mat3(cov3D_M11_M12.x,cov3D_M11_M12.y,cov3D_M13_M22.x,cov3D_M11_M12.y,cov3D_M13_M22.y,cov3D_M23_M33.x,cov3D_M13_M22.x,cov3D_M23_M33.x,cov3D_M23_M33.y);vec4 covVectors=calcCovVectors(viewPos.xyz,Vrk);vPosition=position.xy;uint colorUint=covAndColorData.w;vColor=vec4(float(colorUint&uint(0xFF))/255.0,float((colorUint>>uint(8))&uint(0xFF))/255.0,float((colorUint>>uint(16))&uint(0xFF))/255.0,float(colorUint>>uint(24))/255.0);vec2 vCenter=vec2(pos2d)/pos2d.w;gl_Position=vec4(vCenter+(position.x*covVectors.zw+position.y*covVectors.xy)/viewport*2.0,pos2d.z/pos2d.w,1.0);}";var A="in vec4 vColor;in vec2 vPosition;void main(){float A=-dot(vPosition,vPosition);if(A<-4.0)discard;float B=exp(A)*vColor.a;gl_FragColor=vec4(vColor.rgb,B);}";var f=class{constructor(){this._intervalTime=200,this._stableStopTime=3e3,this._isSorting=!1,this._dirty=!0,this._lastMvMatrix=null,this._lastSortTime=0,this._stableSince=0}set isSorting(t){this._isSorting=t}get isSorting(){return this._isSorting}set dirty(t){this._dirty=t}get dirty(){return this._dirty}set intervalTime(t){this._intervalTime=t}get intervalTime(){return this._intervalTime}set stableStopTime(t){this._stableStopTime=t}get stableStopTime(){return this._stableStopTime}_isMatrixChanged(t,e){return t?!t.equals(e):!0}tick(t,e){let r=performance.now(),s=this._isMatrixChanged(this._lastMvMatrix,t);s?this._stableSince=r:this._stableSince===0&&(this._stableSince=r);let n=r-this._lastSortTime>=this._intervalTime,u=r-this._stableSince<this._stableStopTime;return!this._isSorting&&n&&(this._dirty||s||u)&&(this._isSorting=!0,this._dirty=!1,this._lastSortTime=r,e()),this._lastMvMatrix=t,this}},C=f;var j="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".split("");function T(o="D"){let t=[];t[8]=t[13]=t[18]=t[23]="-",t[14]="4";let e;for(let r=0;r<36;r++)t[r]||(e=0|Math.random()*16,t[r]=j[r===19?e&3|8:e]);return o+"-"+t.join("")}function b(){let o=document.createElement("canvas"),t=o.getContext("webgl2")||o.getContext("webgl");return t.getParameter(t.MAX_TEXTURE_SIZE)}var v=b(),G=v*v,D=new i.BufferGeometry;D.setAttribute("position",new i.BufferAttribute(new Float32Array([-2,-2,0,2,2,0,-2,2,0,2,-2,0,2,2,0,-2,-2,0]),3));var w=class extends i.Mesh{constructor(){super(),this._meshId=T(),this._vertexCount=0,this._textureWidth=v,this._textureHeight=1,this._threshold=-1e-5,this._centerAndScaleData=null,this._centerAndScaleTexture=null,this._rotationAndColorData=null,this._rotationAndColorTexture=null,this.geometry=new i.InstancedBufferGeometry().copy(D),this.geometry.instanceCount=1,this.material=new i.ShaderMaterial({uniforms:{viewport:{value:new Float32Array([1980,1080])},centerAndScaleTexture:{value:null},covAndColorTexture:{value:null},gsModelViewMatrix:{value:null}},vertexShader:k,fragmentShader:A,blending:i.CustomBlending,blendSrcAlpha:i.OneFactor,depthTest:!0,depthWrite:!1,transparent:!0}),this.material.onBeforeRender=this._onMaterialBeforeRender.bind(this),this.frustumCulled=!1,this._bounds=null,this._sortScheduler=new C,this._worker=null,this._useFrustumCulled=!1}get isSplatMesh(){return!0}set threshold(t){this._threshold=t}get threshold(){return this._threshold}set worker(t){this._worker=t}get worker(){return this._worker}get bounds(){return this._bounds}set vertexCount(t){this.setVertexCount(t)}get vertexCount(){return this._vertexCount}set useFrustumCulled(t){this._useFrustumCulled=t}get useFrustumCulled(){return this._useFrustumCulled}get sortScheduler(){return this._sortScheduler}_getModelViewMatrix(t){return t.matrixWorld.clone().invert().multiply(this.matrixWorld)}_updateTexture(t,e){t&&this._meshId===t.meshId&&(this._centerAndScaleData.set(t.out_cs),this._rotationAndColorData.set(t.out_rc),this._centerAndScaleTexture.image.data.set(this._centerAndScaleData.subarray(0,e*4),0),this._rotationAndColorTexture.image.data.set(this._rotationAndColorData.subarray(0,e*4),0),this._centerAndScaleTexture.needsUpdate=!0,this._rotationAndColorTexture.needsUpdate=!0,this._sortScheduler.dirty=!0)}_onMaterialBeforeRender(t,e,r,s,n,u){let c=this._getModelViewMatrix(r),m=n.material;m.uniforms.gsModelViewMatrix.value=c;let x=new i.Vector4;t.getCurrentViewport(x),m.uniforms.viewport.value[0]=x.z,m.uniforms.viewport.value[1]=x.w,this._sortScheduler&&this._sortScheduler.tick(c,()=>{let d=c.elements,P=new Float32Array([d[2],d[6],d[10],d[14]]),l=new Float32Array(0);if(this._useFrustumCulled){l=new Float32Array(24);let a=new i.Matrix4;a.multiplyMatrices(r.projectionMatrix,r.matrixWorldInverse);let h=new i.Frustum;h.setFromProjectionMatrix(a),h.planes.forEach((_,p)=>{l[p*4+0]=_.normal.x,l[p*4+1]=_.normal.y,l[p*4+2]=_.normal.z,l[p*4+3]=_.constant})}this._worker&&this._worker.call("sort_splats",this._meshId,P,l,this._threshold).then(a=>{if(a||(this._sortScheduler.isSorting=!1),a&&this._meshId===a.meshId){let h=new Uint32Array(a.data);this.geometry.attributes.splatIndex.set(h),this.geometry.attributes.splatIndex.needsUpdate=!0,this.geometry.instanceCount=h.length,this._sortScheduler.isSorting=!1}})})}setVertexCount(t){if(t===this._vertexCount)return;this._vertexCount=Math.min(t,G),this._textureHeight=Math.floor((this._vertexCount-1)/this._textureWidth)+1,this._centerAndScaleData=new Float32Array(this._textureWidth*this._textureHeight*4),this._centerAndScaleTexture&&this._centerAndScaleTexture.dispose(),this._centerAndScaleTexture=new i.DataTexture(this._centerAndScaleData,this._textureWidth,this._textureHeight,i.RGBAFormat,i.FloatType),this._rotationAndColorData=new Uint32Array(this._textureWidth*this._textureHeight*4),this._rotationAndColorTexture&&this._rotationAndColorTexture.dispose(),this._rotationAndColorTexture=new i.DataTexture(this._rotationAndColorData,this._textureWidth,this._textureHeight,i.RGBAIntegerFormat,i.UnsignedIntType),this._rotationAndColorTexture.internalFormat="RGBA32UI";let e=new Uint32Array(this._textureWidth*this._textureHeight),r=new i.InstancedBufferAttribute(e,1,!1);return r.setUsage(i.DynamicDrawUsage),this.geometry.setAttribute("splatIndex",r),this.material.uniforms.centerAndScaleTexture.value=this._centerAndScaleTexture,this.material.uniforms.covAndColorTexture.value=this._rotationAndColorTexture,this}attachWorker(t){return this._worker=t,this}detachWorker(){return this._worker&&this._worker.call("unregister_positions",this._bufferId),this._worker=null,this}async setDataFromBuffer(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromBuffer skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromBuffer skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_buffer",this._meshId,t,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async setDataFromGeometry(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromGeometry skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromGeometry skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_geometry",this._meshId,t.attributes.position.array,t.attributes._scale.array,t.attributes._rotation.array,t.attributes.color.array,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async setDataFromSpz(t){if(this._vertexCount<=0)return console.warn("[SplatMesh] setDataFromSpz skipped: vertexCount is 0"),this;if(!this._worker)return console.warn("[SplatMesh] setDataFromSpz skipped: worker not ready"),this;let e=await this._worker.call("process_splats_from_spz",this._meshId,t.positions,t.scales,t.rotations,t.colors,t.alphas,this._vertexCount);return this._updateTexture(e,this._vertexCount),this._bounds=null,this}async computeBounds(){if(!this._worker)return console.warn("[SplatMesh] computeBounds skipped: worker not ready"),this;if(!this._bounds){let t=await this._worker.call("compute_bounds",this._meshId);this._meshId===t.meshId&&(this._bounds=t.data)}return this}dispose(){this._bounds=null,this._centerAndScaleTexture&&(this._centerAndScaleTexture.dispose(),this._centerAndScaleData=null),this._rotationAndColorTexture&&(this._rotationAndColorTexture.dispose(),this._rotationAndColorData=null),this._worker&&this._worker.call("unregister_positions",this._bufferId),this._bufferId=null,this._sortScheduler=null,this.geometry.dispose(),this.material.dispose(),this.parent=null}},F=w;var g=class{constructor(t,{timeout:e=0}={}){this._workerUrl=t,this._worker=null,this._seq=0,this._pending=new Map,this._timeout=e,this._initPromise=null,this._ready=!1,this._createWorker()}_createWorker(){let t=e=>{e.onmessage=r=>this._handleMessage(r),e.onerror=r=>this._handleError(r),e.onmessageerror=r=>console.error("[SplatWorker] Worker message error:",r)};try{this._worker=new Worker(this._workerUrl,{type:"module"}),t(this._worker);return}catch(e){console.error("Worker error:",e)}fetch(this._workerUrl).then(e=>{if(!e.ok)throw new Error(`[SplatWorker] Failed to fetch worker: ${this._workerUrl}`);return e.text()}).then(e=>{let r=new Blob([e],{type:"application/javascript"}),s=URL.createObjectURL(r);this._worker=new Worker(s),t(this._worker)})}_handleMessage(t){let{id:e,result:r,error:s}=t.data,n=this._pending.get(e);n&&(this._pending.delete(e),s?n.reject(s):n.resolve(r))}_handleError(t){console.error("[SplatWorker] Worker error:",t);for(let[e,r]of this._pending)r.reject("[SplatWorker] Worker crashed");this._pending.clear()}_collectTransferables(t){let e=[];for(let r of t)r&&(ArrayBuffer.isView(r)?e.push(r.buffer):r instanceof ArrayBuffer&&e.push(r));return e}async init(){if(this._ready)return!0;if(this._initPromise)return this._initPromise;this._initPromise=new Promise((e,r)=>{let s=++this._seq;this._pending.set(s,{resolve:e,reject:r}),this._worker.postMessage({id:s,fn:"__init_wasm__",args:[]})});let t=await this._initPromise;return this._ready=!0,t}call(t,...e){return new Promise((r,s)=>{this._worker||s(`the worker ${this._workerUrl} does not exist`);let n=++this._seq;this._pending.set(n,{resolve:r,reject:s});let u=this._collectTransferables(e);this._worker.postMessage({id:n,fn:t,args:e},u),this._timeout>0&&setTimeout(()=>{this._pending.has(n)&&(this._pending.delete(n),s(`[SplatWorker] Task "${t}" timeout after ${this._timeout}ms`))},this._timeout)})}cancel(t,e="canceled"){let r=this._pending.get(t);return r&&(r.reject(e),this._pending.delete(t)),this}dispose(){return this._worker.terminate(),this._pending.clear(),this}},I=g;typeof window!="undefined"&&(window.SplatMesh=F,window.SplatWorker=I);})();
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
let e;function n(e){l===f.length&&f.push(f.length+1);const n=l;return l=f[n],f[n]=e,n}function t(e,n){return e>>>=0,i().subarray(e/4,e/4+n)}let r=null;function o(){return(null===r||!0===r.buffer.detached||void 0===r.buffer.detached&&r.buffer!==e.memory.buffer)&&(r=new DataView(e.memory.buffer)),r}let _=null;function i(){return null!==_&&0!==_.byteLength||(_=new Float32Array(e.memory.buffer)),_}let s=null;function a(){return null!==s&&0!==s.byteLength||(s=new Uint32Array(e.memory.buffer)),s}let u=null;function c(){return null!==u&&0!==u.byteLength||(u=new Uint8Array(e.memory.buffer)),u}function p(e){return f[e]}let f=new Array(128).fill(void 0);f.push(void 0,null,!0,!1);let l=f.length;function b(e,n){const t=n(4*e.length,4)>>>0;return a().set(e,t/4),y=e.length,t}function d(e,n){const t=n(1*e.length,1)>>>0;return c().set(e,t/1),y=e.length,t}function g(e,n){const t=n(4*e.length,4)>>>0;return i().set(e,t/4),y=e.length,t}function w(e){const n=p(e);return function(e){e<132||(f[e]=l,l=e)}(e),n}let y=0;export function append_data_from_buffer(t,r,o,_,i){const s=d(r,e.__wbindgen_export),a=y;var u=g(_,e.__wbindgen_export),c=y,p=b(i,e.__wbindgen_export),f=y;e.append_data_from_buffer(t,s,a,o,u,c,n(_),p,f,n(i))}export function compute_bounds(n){try{const s=e.__wbindgen_add_to_stack_pointer(-16);e.compute_bounds(s,n);var r=o().getInt32(s+0,!0),_=o().getInt32(s+4,!0),i=t(r,_).slice();return e.__wbindgen_export2(r,4*_,4),i}finally{e.__wbindgen_add_to_stack_pointer(16)}}export function get_positions(n){try{const s=e.__wbindgen_add_to_stack_pointer(-16);e.get_positions(s,n);var r=o().getInt32(s+0,!0),_=o().getInt32(s+4,!0),i=t(r,_).slice();return e.__wbindgen_export2(r,4*_,4),i}finally{e.__wbindgen_add_to_stack_pointer(16)}}export function process_splats_from_buffer(t,r,o,_){const i=d(t,e.__wbindgen_export),s=y;var a=g(o,e.__wbindgen_export),u=y,c=b(_,e.__wbindgen_export),p=y;return e.process_splats_from_buffer(i,s,r,a,u,n(o),c,p,n(_))>>>0}export function process_splats_from_geometry(t,r,o,_,i,s,a){const u=g(t,e.__wbindgen_export),c=y,p=g(r,e.__wbindgen_export),f=y,l=g(o,e.__wbindgen_export),w=y,m=d(_,e.__wbindgen_export),x=y;var h=g(s,e.__wbindgen_export),v=y,A=b(a,e.__wbindgen_export),W=y;return e.process_splats_from_geometry(u,c,p,f,l,w,m,x,i,h,v,n(s),A,W,n(a))>>>0}export function process_splats_from_spz(t,r,o,_,i,s,a,u){const c=g(t,e.__wbindgen_export),p=y,f=g(r,e.__wbindgen_export),l=y,d=g(o,e.__wbindgen_export),w=y,m=g(_,e.__wbindgen_export),x=y,h=g(i,e.__wbindgen_export),v=y;var A=g(a,e.__wbindgen_export),W=y,I=b(u,e.__wbindgen_export),k=y;return e.process_splats_from_spz(c,p,f,l,d,w,m,x,h,v,s,A,W,n(a),I,k,n(u))>>>0}export function sort_splats(n,t,r,_){try{const f=e.__wbindgen_add_to_stack_pointer(-16),l=g(t,e.__wbindgen_export),b=y,d=g(r,e.__wbindgen_export),w=y;e.sort_splats(f,n,l,b,d,w,_);var i=o().getInt32(f+0,!0),s=o().getInt32(f+4,!0),u=(c=i,p=s,c>>>=0,a().subarray(c/4,c/4+p)).slice();return e.__wbindgen_export2(i,4*s,4),u}finally{e.__wbindgen_add_to_stack_pointer(16)}var c,p}export function unregister_positions(n){e.unregister_positions(n)}const m=new Set(["basic","cors","default"]);function x(){const e={wbg:{}};return e.wbg.__wbg___wbindgen_copy_to_typed_array_db832bc4df7216c1=function(e,n,t){var r,o;new Uint8Array(p(t).buffer,p(t).byteOffset,p(t).byteLength).set((r=e,o=n,r>>>=0,c().subarray(r/1,r/1+o)))},e.wbg.__wbindgen_object_drop_ref=function(e){w(e)},e}function h(n,t){return e=n.exports,A.__wbindgen_wasm_module=t,r=null,_=null,s=null,u=null,e}function v(n){if(void 0!==e)return e;void 0!==n&&(Object.getPrototypeOf(n)===Object.prototype?({module:n}=n):console.warn("using deprecated parameters for `initSync()`; pass a single object instead"));const t=x();n instanceof WebAssembly.Module||(n=new WebAssembly.Module(n));return h(new WebAssembly.Instance(n,t),n)}async function A(n){if(void 0!==e)return e;void 0!==n&&(Object.getPrototypeOf(n)===Object.prototype?({module_or_path:n}=n):console.warn("using deprecated parameters for the initialization function; pass a single object instead")),void 0===n&&(n=new URL("wasm_splat_bg.wasm",import.meta.url));const t=x();("string"==typeof n||"function"==typeof Request&&n instanceof Request||"function"==typeof URL&&n instanceof URL)&&(n=fetch(n));const{instance:r,module:o}=await async function(e,n){if("function"==typeof Response&&e instanceof Response){if("function"==typeof WebAssembly.instantiateStreaming)try{return await WebAssembly.instantiateStreaming(e,n)}catch(n){if(!e.ok||!m.has(e.type)||"application/wasm"===e.headers.get("Content-Type"))throw n;console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve Wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\n",n)}const t=await e.arrayBuffer();return await WebAssembly.instantiate(t,n)}{const t=await WebAssembly.instantiate(e,n);return t instanceof WebAssembly.Instance?{instance:t,module:e}:t}}(await n,t);return h(r,o)}export{v as initSync};export default A;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import t,{process_splats_from_buffer as s,append_data_from_buffer as e,process_splats_from_geometry as u,process_splats_from_spz as r,sort_splats as o,compute_bounds as l,unregister_positions as n}from"./wasm_splat.min.js";let a=!1,f=null,c={};function _(t){return{outCS:new Float32Array(new ArrayBuffer(4*t*4)),outRC:new Uint32Array(new ArrayBuffer(4*t*4))}}self.onmessage=async i=>{const{id:d,fn:p,args:m}=i.data;try{let i;if("__init_wasm__"===p)return a||(await t(),a=!0),void postMessage({id:d,result:!0});if(await async function(){return!!a||(f||(f=t().then(()=>(a=!0,!0)).catch(t=>{throw a=!1,f=null,t})),f)}(),"process_splats_from_buffer"===p){const[t,e,u]=m,r=new Uint8Array(e),{outCS:o,outRC:l}=_(u),n=s(r,u,o,l);c[t]={bufferId:n},i={meshId:t,out_cs:o,out_rc:l}}else if("append_data_from_buffer"===p){let[t,s,u]=m;const{bufferId:r}=c[t];let o=new Uint8Array(s);const{outCS:l,outRC:n}=_(u);e(r,o,u,l,n),i={out_cs:l,out_rc:n},s=null,o=null}else if("process_splats_from_geometry"===p){let[t,s,e,r,o,l]=m;const{outCS:n,outRC:a}=_(l),f=u(s,e,r,o,l,n,a);c[t]={bufferId:f},i={meshId:t,out_cs:n,out_rc:a},s=null,e=null,r=null,o=null}else if("process_splats_from_spz"===p){let[t,s,e,u,o,l,n]=m;const{outCS:a,outRC:f}=_(n),d=r(s,e,u,o,l,n,a,f);c[t]={bufferId:d},i={meshId:t,out_cs:a,out_rc:f},s=null,e=null,u=null,o=null,l=null}else if("sort_splats"===p){const[t,s,e,u]=m,{bufferId:r}=c[t];i={meshId:t,data:o(r,s,e,u)}}else if("compute_bounds"===p){const[t]=m,{bufferId:s}=c[t];i={meshId:t,data:l(s)}}else if("unregister_positions"===p){const[t]=m,{bufferId:s}=c[t];n(s),i=!0}i instanceof Uint32Array?(postMessage({id:d,result:i},[i.buffer]),i=null):i&&i.data?(postMessage({id:d,result:i},[i.data.buffer]),i.data=null,i=null):i&&i.out_cs&&i.out_rc?(postMessage({id:d,result:i},[i.out_cs.buffer,i.out_rc.buffer]),i.out_cs=null,i.out_rc=null,i=null):postMessage({id:d,result:i})}catch(t){console.error(t),postMessage({id:d,error:t?.message||String(t)})}};
|
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@dvt3d/splat-mesh",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"main": "dist/index.js",
|
|
5
|
+
"repository": "https://github.com/dvt3d/splat-mesh.git",
|
|
6
|
+
"author": "Caven Chen <cavencj@gmail.com>",
|
|
7
|
+
"license": "Apache-2.0",
|
|
8
|
+
"scripts": {
|
|
9
|
+
"dev": "rimraf dist && gulp dev",
|
|
10
|
+
"build": "rimraf dist && gulp build",
|
|
11
|
+
"build:node": "rimraf dist && gulp buildNode",
|
|
12
|
+
"build:iife": "rimraf dist && gulp buildIIFE",
|
|
13
|
+
"build:release": "rimraf dist && gulp buildRelease",
|
|
14
|
+
"prepublishOnly": "yarn run build:release",
|
|
15
|
+
"lint": "eslint --fix src"
|
|
16
|
+
},
|
|
17
|
+
"peerDependencies": {
|
|
18
|
+
"three": "^0.182.0"
|
|
19
|
+
},
|
|
20
|
+
"keywords": [
|
|
21
|
+
"Gaussian splatting",
|
|
22
|
+
"3dgs",
|
|
23
|
+
"three.js",
|
|
24
|
+
"splat-mesh"
|
|
25
|
+
],
|
|
26
|
+
"files": [
|
|
27
|
+
"dist"
|
|
28
|
+
],
|
|
29
|
+
"devDependencies": {
|
|
30
|
+
"chalk": "^5.6.2",
|
|
31
|
+
"esbuild": "^0.27.2",
|
|
32
|
+
"esbuild-plugin-globals": "^0.2.0",
|
|
33
|
+
"esbuild-plugin-glsl": "^1.4.1",
|
|
34
|
+
"fs-extra": "^11.3.3",
|
|
35
|
+
"gulp": "^5.0.1",
|
|
36
|
+
"prettier": "^3.7.4",
|
|
37
|
+
"rimraf": "^6.1.2",
|
|
38
|
+
"shelljs": "^0.10.0"
|
|
39
|
+
}
|
|
40
|
+
}
|