-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBvh_Particle_Sample01.html
291 lines (245 loc) · 8.77 KB
/
Bvh_Particle_Sample01.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bvh_Particle_Sample02</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<style>
body {
overflow: hidden;
margin: 0px;
}
</style>
</head>
<body>
<div id="app"></div>
<script type="importmap">
{
"imports": {
"three": "./three.module.js",
"three/addons/": "./jsm/",
"three/addons/module_more": "./jsm/module_more"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import Stats from 'three/addons/stats.module.js';
import { GUI } from 'three/addons/lil-gui.module.min.js';
import { OrbitControls } from 'three/addons/OrbitControls.js';
import { EffectComposer } from "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/EffectComposer.js";
import { RenderPass } from "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/RenderPass.js";
import { UnrealBloomPass } from "https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/UnrealBloomPass.js";
import { AfterimagePass } from 'https://cdn.jsdelivr.net/npm/[email protected]/examples/jsm/postprocessing/AfterimagePass.js';
import { GLTFLoader } from 'three/addons/GLTFLoader.js';
import { DRACOLoader } from 'three/addons/DRACOLoader.js';
import {
computeBoundsTree,
disposeBoundsTree,
acceleratedRaycast
} from "https://cdn.jsdelivr.net/npm/[email protected]/build/index.module.min.js";
import { BufferGeometryUtils } from "three/addons/module_more/BufferGeometryUtils.js";
THREE.BufferGeometry.prototype.computeBoundsTree = computeBoundsTree;
THREE.BufferGeometry.prototype.disposeBoundsTree = disposeBoundsTree;
THREE.Mesh.prototype.raycast = acceleratedRaycast;
let scene = new THREE.Scene();
let camera = new THREE.PerspectiveCamera(
60,
window.innerWidth / window.innerHeight,
1,
1000
);
camera.position.set(0, 2, 3).setLength(7);
let renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputEncoding = THREE.sRGBEncoding;
document.getElementById("app").appendChild(renderer.domElement);
let controls = new OrbitControls(camera, renderer.domElement);
let light = new THREE.DirectionalLight(0xffffff, 1);
light.position.setScalar(1);
scene.add(light, new THREE.AmbientLight(0xffffff, 0.5));
scene.add(new THREE.GridHelper());
let loader = new GLTFLoader();
// https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/DragonAttenuation/glTF-Binary/DragonAttenuation.glb
loader.load("./models/DragonAttenuation.glb", (gltf) => {
let model = gltf.scene.children[1];
model.material = new THREE.MeshLambertMaterial({
side: THREE.DoubleSide,
wireframe: false,
color: 0x7fffff,
transparent: true,
opacity: 0.125
});
//console.log(model);
model.visible = false;
scene.add(model);
let bbox = new THREE.Box3().setFromObject(model);
let bboxHelper = new THREE.Box3Helper(bbox, "yellow");
scene.add(bboxHelper);
console.time('getDataTexture3D');
// Gọi hàm và lưu kết quả
let samples = getDataTexture3D(model);
// Kết thúc đo thời gian và in ra thời gian đã trôi qua
console.timeEnd('getDataTexture3D');
console.log(samples.texture)
let pg = new THREE.BufferGeometry().setFromPoints(samples.points);
let pm = new THREE.PointsMaterial({ size: 0.05, color: "aqua" });
let p = new THREE.Points(pg, pm);
p.visible = false;
scene.add(p);
// check the texture
let uniforms = {
spatialTex: {
value: samples.texture
},
bbox: {
value: [bbox.min, bbox.max]
},
noDiscard: {
value: false
}
};
let lg = makeGrid(5, 100);
let lm = new THREE.LineBasicMaterial({
color: "red",
onBeforeCompile: (shader) => {
shader.uniforms.spatialTex = uniforms.spatialTex;
shader.uniforms.bbox = uniforms.bbox;
shader.uniforms.noDiscard = uniforms.noDiscard;
shader.vertexShader = `
varying vec3 vPos;
${shader.vertexShader}
`.replace(
`#include <begin_vertex>`,
`#include <begin_vertex>
vPos = position;
`
);
//console.log(shader.vertexShader);
shader.fragmentShader = `
precision highp float;
precision highp sampler3D;
uniform sampler3D spatialTex;
uniform vec3[2] bbox;
uniform bool noDiscard;
varying vec3 vPos;
${shader.fragmentShader}
`.replace(
`#include <clipping_planes_fragment>`,
`#include <clipping_planes_fragment>
vec3 uvSpatial = (vPos - bbox[0]) / (bbox[1] - bbox[0]);
vec3 uvCenter = abs(uvSpatial - 0.5);
float uvVal = max(uvCenter.x, max(uvCenter.y, uvCenter.z));
float spatialSample = texture(spatialTex, uvSpatial).r;
if (!noDiscard) {
if(spatialSample < 0.5 || uvVal > 0.5) discard;
}
`
);
console.log(shader.fragmentShader);
}
});
let l = new THREE.LineSegments(lg, lm);
scene.add(l);
let gui = new GUI();
gui.add(model, "visible").name("model");
gui.add(p, "visible").name("points");
gui.add(l, "visible").name("3d grid");
gui.add(uniforms.noDiscard, "value").name("noDiscard");
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
});
renderer.setAnimationLoop((_) => {
renderer.render(scene, camera);
});
function makeGrid(side, segs) {
let step = side / segs;
let geoms = [];
let grid = new THREE.GridHelper(side, segs);
let gridGeom = grid.geometry;
gridGeom.translate(0, side * -0.5, 0);
geoms.push(gridGeom.clone());
for (let i = 0; i < segs; i++) {
gridGeom.translate(0, step, 0);
geoms.push(gridGeom.clone());
}
gridGeom.rotateX(Math.PI * -0.5);
geoms.push(gridGeom.clone());
for (let i = 0; i < segs; i++) {
gridGeom.translate(0, 0, step);
geoms.push(gridGeom.clone());
}
let mainGeom = BufferGeometryUtils.mergeBufferGeometries(geoms);
mainGeom.deleteAttribute("color");
console.log(mainGeom)
return mainGeom;
}
function getDataTexture3D(mesh) {
mesh.geometry.computeBoundsTree();
let bbox = new THREE.Box3().setFromObject(mesh);
let size = new THREE.Vector3();
bbox.getSize(size);
let minSize = Math.min(size.x, size.y, size.z);
let size32 = new THREE.Vector3()
.copy(size)
.divideScalar(minSize)
.floor()
.multiplyScalar(64);
console.log(size32);
let step = new THREE.Vector3().copy(size).divide(size32);
let halfStep = new THREE.Vector3().copy(step).multiplyScalar(0.5);
let steps = new THREE.Vector3();
let ray = new THREE.Raycaster();
ray.firstHitOnly = true;
let meshInvMatrix = new THREE.Matrix4();
meshInvMatrix.copy(mesh.matrixWorld).invert();
let localRay = new THREE.Ray();
let ori = new THREE.Vector3();
let dir = new THREE.Vector3();
let intersects = [];
let pts = [];
let data = [];
for (let z = 0; z < size32.z; z++) {
for (let y = 0; y < size32.y; y++) {
for (let x = 0; x < size32.x; x++) {
dir.random().subScalar(0.5).normalize();
ori.copy(bbox.min).add(halfStep);
steps.set(x, y, z).multiply(step);
ori.add(steps);
let inside = isInside(ori, dir);
data.push(inside ? 1 : 0);
if (inside) pts.push(ori.clone());
}
}
}
let texture = new THREE.Data3DTexture(
new Float32Array(data),
size32.x,
size32.y,
size32.z
);
texture.format = THREE.RedFormat;
texture.type = THREE.FloatType;
texture.minFilter = texture.magFilter = THREE.LinearFilter;
texture.unpackAlignment = 1;
return {
texture: texture,
points: pts
};
function isInside(ori, dir) {
ray.set(ori, dir);
intersects = [];
intersects = ray.intersectObjects([mesh]);
localRay.copy(ray.ray).applyMatrix4(meshInvMatrix);
if (intersects.length > 0) {
if (intersects[0].face.normal.dot(localRay.direction) > 0) return true;
}
return false;
}
}
</script>
</body>
</html>