-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMER-traverse-3d.html
520 lines (445 loc) · 19.4 KB
/
MER-traverse-3d.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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
<!DOCTYPE html>
<html>
<head>
<title>RVF File Processor & 3D Viewer</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babylonjs/6.37.1/babylon.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babylonjs-loaders/6.37.1/babylonjs.loaders.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babylonjs-gui/6.37.1/babylonjs.gui.min.js"></script>
<style>
body { margin: 0; padding: 20px; font-family: Arial, sans-serif; }
.container { display: flex; gap: 20px; }
.controls { width: 300px; }
.viewer { flex-grow: 1; }
#renderCanvas { width: 100%; height: 600px; border: 1px solid #ccc; }
.file-input { margin: 10px 0; }
button { padding: 10px; margin: 5px 0; width: 100%; }
.model-info {
margin: 10px 0;
padding: 10px;
background: #f0f0f0;
border-radius: 4px;
}
</style>
</head>
<body>
<div class="container">
<div class="controls">
<h2>File Input</h2>
<div class="file-input">
<label>Master SVF:</label><br>
<input type="file" id="masterFile" accept=".svf">
</div>
<div class="file-input">
<label>Secondary RVF Files:</label><br>
<input type="file" id="secondaryFiles" accept=".rvf" multiple>
</div>
<div class="file-input">
<label>3D Model:</label><br>
<input type="file" id="modelFile" accept=".gltf,.glb,.obj">
<div class="model-info">
Formati supportati:
<ul>
<li>glTF/GLB (.gltf, .glb) - Consigliato</li>
<li>OBJ (.obj)</li>
</ul>
</div>
</div>
<button id="processButton" disabled>ELABORA</button>
</div>
<div class="viewer">
<canvas id="renderCanvas"></canvas>
</div>
</div>
<script>
let masterData = null;
let secondaryData = [];
let modelFile = null;
let siteOffsets = [];
let drives = {};
// Funzione per convertire quaternione in Euler angles (yaw, pitch, roll)
function quaternionToEuler(q) {
let yaw = Math.atan2(2*(q.s*q.v3 + q.v1*q.v2), 1 - 2*(q.v2*q.v2 + q.v3*q.v3));
let pitch = Math.asin(2*(q.s*q.v2 - q.v3*q.v1));
let roll = Math.atan2(2*(q.s*q.v1 + q.v2*q.v3), 1 - 2*(q.v1*q.v1 + q.v2*q.v2));
return { yaw, pitch, roll };
}
// Event listeners per i file
document.getElementById('masterFile').addEventListener('change', async (e) => {
const file = e.target.files[0];
const text = await file.text();
masterData = new DOMParser().parseFromString(text, 'text/xml');
updateProcessButton();
processMasterFile();
});
document.getElementById('secondaryFiles').addEventListener('change', async (e) => {
secondaryData = [];
for (let file of e.target.files) {
const text = await file.text();
secondaryData.push(new DOMParser().parseFromString(text, 'text/xml'));
}
updateProcessButton();
processSecondaryFiles();
});
document.getElementById('modelFile').addEventListener('change', (e) => {
modelFile = e.target.files[0];
updateProcessButton();
});
function updateProcessButton() {
const button = document.getElementById('processButton');
button.disabled = !(masterData && secondaryData.length > 0 && modelFile);
}
function processMasterFile() {
siteOffsets = [];
const solutions = masterData.getElementsByTagName('solution');
let cumulativeOffset = { x: 0, y: 0, z: 0 };
for (let solution of solutions) {
//console.log("solution", solution);
if (solution.getAttribute('name') === 'SITE_FRAME') {
const index1 = parseInt(solution.getAttribute('index1'));
//console.log(" site found", index1);
const offset = solution.getElementsByTagName('offset')[0];
//console.log(" offset=", offset);
const relativeOffset = {
x: parseFloat(offset.getAttribute('x')),
y: parseFloat(offset.getAttribute('y')),
z: parseFloat(offset.getAttribute('z'))
};
//console.log(" relativeOffset=", relativeOffset);
cumulativeOffset = {
x: cumulativeOffset.x + relativeOffset.x,
y: cumulativeOffset.y + relativeOffset.y,
z: cumulativeOffset.z + relativeOffset.z
};
//console.log(" cumulativeOffset=", cumulativeOffset);
siteOffsets.push({
index1,
relativeOffset,
cumulativeOffset: {...cumulativeOffset}
});
}
}
}
function processSecondaryFiles() {
drives = {};
// Per ogni documento XML secondario
for (let doc of secondaryData) {
const solutions = doc.getElementsByTagName('solution');
// Per ogni solution nel documento
for (let solution of solutions) {
console.log("solution=", solution);
if (solution.getAttribute('name') === 'ROVER_FRAME') {
const site = parseInt(solution.getAttribute('index1'));
const drive = parseInt(solution.getAttribute('index2'));
console.log(" site,drive=", site,drive);
// Ottieni offset e orientamento dalla solution
const offset = solution.getElementsByTagName('offset')[0];
const orientation = solution.getElementsByTagName('orientation')[0];
// Crea oggetto quaternione dai dati
const quaternion = {
s: parseFloat(orientation.getAttribute('s')),
v1: parseFloat(orientation.getAttribute('v1')),
v2: parseFloat(orientation.getAttribute('v2')),
v3: parseFloat(orientation.getAttribute('v3'))
};
console.log(" offset,orientation=", offset,orientation);
// Cerca l'offset cumulativo corrispondente al site
let siteOffset = { x: 0, y: 0, z: 0 }; // valore di default
// Cerca nell'array siteOffsets l'elemento con l'index1 corrispondente
for (let i = 0; i < siteOffsets.length; i++) {
if (siteOffsets[i].index1 === site) {
siteOffset = siteOffsets[i].cumulativeOffset;
break; // Esce dal ciclo appena trova il match
}
}
console.log(" siteOffset=", siteOffset);
// Crea oggetto con l'offset del drive
const driveOffset = {
x: parseFloat(offset.getAttribute('x')),
y: parseFloat(offset.getAttribute('y')),
z: parseFloat(offset.getAttribute('z'))
};
// Calcola l'offset totale sommando siteOffset e driveOffset
const totalOffset = {
x: siteOffset.x + driveOffset.x,
y: siteOffset.y + driveOffset.y,
z: siteOffset.z + driveOffset.z
};
// Inizializza l'oggetto per il site se non esiste
if (!drives[site]) {
drives[site] = {};
}
// Memorizza tutti i dati per questa combinazione site/drive
drives[site][drive] = {
offset: driveOffset,
quaternion: quaternion,
euler: quaternionToEuler(quaternion),
totalOffset: totalOffset
};
}
}
}
}
// Inizializzazione BabylonJS
const canvas = document.getElementById('renderCanvas');
const engine = new BABYLON.Engine(canvas, true);
function createScene() {
const scene = new BABYLON.Scene(engine);
// Configurazione camera e luci
const camera = new BABYLON.ArcRotateCamera(
"camera",
0, // alfa (rotazione orizzontale)
Math.PI / 3, // beta (rotazione verticale)
30, // raggio (distanza) - aumentato per vedere meglio la scena
new BABYLON.Vector3(0, 0, 0),
scene
);
camera.attachControl(canvas, true);
camera.wheelPrecision = 50;
camera.lowerRadiusLimit = 2;
camera.upperRadiusLimit = 100;
// Luci con intensità aumentata
const hemLight = new BABYLON.HemisphericLight(
"hemLight",
new BABYLON.Vector3(0, 1, 0),
scene
);
hemLight.intensity = 1.0; // aumentata da 0.7
const dirLight = new BABYLON.DirectionalLight(
"dirLight",
new BABYLON.Vector3(-1, -2, -1),
scene
);
dirLight.intensity = 0.7; // aumentata da 0.5
// Griglia di riferimento più grande
const gridSize = 100; // aumentato da 10
const grid = BABYLON.MeshBuilder.CreateGround(
"grid",
{
width: gridSize,
height: gridSize,
subdivisions: 20 // modificato per una griglia più visibile
},
scene
);
// Aggiungiamo un materiale alla griglia per renderla visibile
const gridMaterial = new BABYLON.StandardMaterial("gridMat", scene);
gridMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
gridMaterial.wireframe = true;
grid.material = gridMaterial;
// Aggiungi assi di riferimento
const showAxis = function(size) {
const makeTextPlane = function(text, color, size) {
const dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", 50, scene, true);
dynamicTexture.hasAlpha = true;
dynamicTexture.drawText(text, 5, 40, "bold 36px Arial", color , "transparent", true);
const plane = BABYLON.MeshBuilder.CreatePlane("TextPlane", { size: size }, scene);
plane.material = new BABYLON.StandardMaterial("TextPlaneMaterial", scene);
plane.material.backFaceCulling = false;
plane.material.specularColor = new BABYLON.Color3(0, 0, 0);
plane.material.diffuseTexture = dynamicTexture;
return plane;
};
const axisX = BABYLON.MeshBuilder.CreateLines("axisX", {
points: [
new BABYLON.Vector3(0, 0, 0),
new BABYLON.Vector3(size, 0, 0)
]
}, scene);
axisX.color = new BABYLON.Color3(1, 0, 0);
const xChar = makeTextPlane("X", "red", size / 10);
xChar.position = new BABYLON.Vector3(size * 0.9, 0.1, 0);
const axisY = BABYLON.MeshBuilder.CreateLines("axisY", {
points: [
new BABYLON.Vector3(0, 0, 0),
new BABYLON.Vector3(0, size, 0)
]
}, scene);
axisY.color = new BABYLON.Color3(0, 1, 0);
const yChar = makeTextPlane("Y", "green", size / 10);
yChar.position = new BABYLON.Vector3(0, size * 0.9, 0);
const axisZ = BABYLON.MeshBuilder.CreateLines("axisZ", {
points: [
new BABYLON.Vector3(0, 0, 0),
new BABYLON.Vector3(0, 0, size)
]
}, scene);
axisZ.color = new BABYLON.Color3(0, 0, 1);
const zChar = makeTextPlane("Z", "blue", size / 10);
zChar.position = new BABYLON.Vector3(0, 0.1, size * 0.9);
};
showAxis(20);
return scene;
}
//DEBUG
document.getElementById('processButton').addEventListener('click', async () => {
debugWithBoxes(scene);
});
/*
document.getElementById('processButton').addEventListener('click', async () => {
// Rimuovi modelli esistenti
scene.meshes.slice().forEach(mesh => {
if (mesh.name !== "grid") mesh.dispose();
});
const modelUrl = URL.createObjectURL(modelFile);
const fileExtension = modelFile.name.split('.').pop().toLowerCase();
// Funzione per caricare e clonare i modelli
const loadAndPlaceModel = (meshes, particleSystems, skeletons) => {
const rootMesh = meshes[0];
// Crea una copia del modello per ogni posizione
Object.keys(drives).forEach(site => {
Object.keys(drives[site]).forEach(drive => {
const driveData = drives[site][drive];
const clone = rootMesh.clone("model_" + site + "_" + drive);
// Posiziona il modello
clone.position = new BABYLON.Vector3(
driveData.totalOffset.x,
driveData.totalOffset.y,
driveData.totalOffset.z
);
// Applica la rotazione dal quaternione
clone.rotationQuaternion = new BABYLON.Quaternion(
driveData.quaternion.v1,
driveData.quaternion.v2,
driveData.quaternion.v3,
driveData.quaternion.s
);
});
});
// Rimuovi il modello originale
rootMesh.dispose();
};
// Carica il modello in base al formato
if (fileExtension === 'obj') {
BABYLON.SceneLoader.ImportMesh("", "", modelUrl, scene, loadAndPlaceModel);
} else if (fileExtension === 'gltf' || fileExtension === 'glb') {
BABYLON.SceneLoader.ImportMesh("", "", modelUrl, scene, loadAndPlaceModel, null, null, ".gltf");
}
URL.revokeObjectURL(modelUrl);
});
*/
// Crea la scena
const scene = createScene();
// Renderizza continuamente
engine.runRenderLoop(() => {
scene.render();
});
window.addEventListener('resize', () => {
engine.resize();
});
// Funzione di debug che usa cubi al posto del modello 3D
function debugWithBoxes(scene) {
console.log("Inizio debugWithBoxes");
// Verifica che scene sia valido
if (!scene) {
console.error("Scene non valida");
return;
}
// Verifica che drives sia definito e non vuoto
if (!drives || Object.keys(drives).length === 0) {
console.error("Nessun dato drives disponibile");
return;
}
// Rimuovi modelli esistenti
scene.meshes.slice().forEach(mesh => {
if (mesh.name !== "grid") {
console.log("Rimuovo mesh:", mesh.name);
mesh.dispose();
}
});
// Crea un materiale per i cubi
const boxMaterial = new BABYLON.StandardMaterial("boxMat", scene);
boxMaterial.wireframe = true;
boxMaterial.emissiveColor = new BABYLON.Color3(0, 1, 0);
boxMaterial.alpha = 1; // Assicurati che sia completamente opaco
boxMaterial.backFaceCulling = false; // Mostra entrambi i lati
// Contatore per debug
let boxCount = 0;
// Per ogni posizione nei drives, crea un cubo
Object.keys(drives).forEach(site => {
Object.keys(drives[site]).forEach(drive => {
const driveData = drives[site][drive];
// Verifica che i dati siano validi
if (!driveData.totalOffset || !driveData.quaternion) {
console.warn(`Dati mancanti per ${site}_${drive}`);
return;
}
// Crea un cubo
const box = BABYLON.MeshBuilder.CreateBox(
`box_${site}_${drive}`,
{
width: 1, // Dimensioni aumentate per maggiore visibilità
height: 1,
depth: 2
},
scene
);
// Imposta il materiale
box.material = boxMaterial;
// Posiziona il cubo
box.position = new BABYLON.Vector3(
driveData.totalOffset.x,
driveData.totalOffset.y,
driveData.totalOffset.z
);
console.log(`Box ${boxCount} posizionato a:`, box.position);
// Applica la rotazione dal quaternione
box.rotationQuaternion = new BABYLON.Quaternion(
driveData.quaternion.v1,
driveData.quaternion.v2,
driveData.quaternion.v3,
driveData.quaternion.s
);
boxCount++;
});
});
console.log(`Creati ${boxCount} cubi`);
// Assicurati che la camera sia posizionata correttamente
if (scene.activeCamera) {
// Imposta la camera a una posizione da cui si vedono i cubi
scene.activeCamera.position = new BABYLON.Vector3(0, 5, -10);
scene.activeCamera.setTarget(BABYLON.Vector3.Zero());
} else {
console.error("Camera non trovata nella scena");
}
}
/**
* Calcola la differenza tra i campi euler e totalOffset di due elementi dell'array drives
* @param {Object} drives - Array bidimensionale con indici site e drive
* @param {string|number} site1 - Primo indice site
* @param {string|number} drive1 - Primo indice drive
* @param {string|number} site2 - Secondo indice site
* @param {string|number} drive2 - Secondo indice drive
* @returns {Object} Oggetto contenente le differenze calcolate
*/
function calculateDrivesDifferences(site1, drive1, site2, drive2) {
// Costante per convertire da radianti a gradi
const RAD_TO_DEG = 180 / Math.PI;
// Ottieni i due elementi dall'array
const element1 = drives[site1][drive1];
const element2 = drives[site2][drive2];
// Calcola le differenze per gli angoli di Euler e converti in gradi
const eulerDiffRad = {
yaw: (element1.euler.yaw - element2.euler.yaw),
pitch: (element1.euler.pitch - element2.euler.pitch),
roll: (element1.euler.roll - element2.euler.roll)
};
const eulerDiffDeg = {
yaw: (element1.euler.yaw - element2.euler.yaw) * RAD_TO_DEG,
pitch: (element1.euler.pitch - element2.euler.pitch) * RAD_TO_DEG,
roll: (element1.euler.roll - element2.euler.roll) * RAD_TO_DEG
};
// Calcola le differenze per totalOffset
const totalOffsetDiff = {
x: element1.totalOffset.x - element2.totalOffset.x,
y: element1.totalOffset.y - element2.totalOffset.y,
z: element1.totalOffset.z - element2.totalOffset.z
};
return {
eulerDiffRad,
eulerDiffDeg,
totalOffsetDiff
};
}
</script>
</body>
</html>