aframe-babia-components 1.2.9 → 1.3.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.
Files changed (52) hide show
  1. package/components/filters/babia-selector.js +33 -21
  2. package/components/filters/babia-treebuilder.js +14 -13
  3. package/components/others/babia-navigator.js +94 -37
  4. package/components/others/babia-poster.js +369 -368
  5. package/components/others/babia-slider.js +63 -25
  6. package/components/others/common.js +60 -80
  7. package/components/visualizers/babia-html.js +95 -118
  8. package/components/visualizers/babia-map.js +796 -0
  9. package/dist/aframe-babia-components.js +7249 -6492
  10. package/dist/aframe-babia-components.min.js +1 -1
  11. package/dist/aframe-babia-components.min.js.LICENSE.txt +1 -1
  12. package/dist/aframe-babia-components.min.js.map +1 -1
  13. package/docs/APIs/OTHERS.md +4 -4
  14. package/docs/CONTRIBUTING.md +34 -25
  15. package/docs/RELEASE_NOTES.md +9 -2
  16. package/docs/Tutorials/HOW_TO_USE_BABIA_MAP.md +554 -0
  17. package/docs/Tutorials/ejemplo1.png +0 -0
  18. package/docs/Tutorials/ejemplo2.png +0 -0
  19. package/docs/Tutorials/ejemplo3.png +0 -0
  20. package/docs/Tutorials/pyramids.png +0 -0
  21. package/docs/Tutorials/singular.png +0 -0
  22. package/docs/Tutorials/terrain-vr-scenario.png +0 -0
  23. package/docs/Tutorials/terrain.png +0 -0
  24. package/examples/boats/boats2/data.json +206 -13
  25. package/examples/charts/pie/index.html +0 -5
  26. package/examples/demos/map-terrain/assets/360-panorama.jpg +0 -0
  27. package/examples/demos/map-terrain/assets/floor-texture.jpg +0 -0
  28. package/examples/demos/map-terrain/assets/mapTextures/512sample.webp +0 -0
  29. package/examples/demos/map-terrain/assets/mapTextures/defaultTexture.webp +0 -0
  30. package/examples/demos/map-terrain/assets/maps/defaultMap.png +0 -0
  31. package/examples/demos/map-terrain/assets/maps/example.png +0 -0
  32. package/examples/demos/map-terrain/assets/metalic-texture.jpg +0 -0
  33. package/examples/demos/map-terrain/dist/aframe-lounge-component.min.js +1 -0
  34. package/examples/demos/map-terrain/index.html +82 -0
  35. package/examples/demos/map-terrain/index_gallery.html +188 -0
  36. package/examples/demos/map-terrain/main_data.json +1 -0
  37. package/examples/demos/map-terrain/pyramids.html +130 -0
  38. package/examples/js/aframe-orbit-controls-component.js +1060 -0
  39. package/examples/ui/pie/index.html +0 -1
  40. package/index.html +15 -0
  41. package/index.js +1 -0
  42. package/package.json +5 -5
  43. package/tests/screenshots/other_snapshots.js/pyramids.png +0 -0
  44. package/tests/screenshots/other_snapshots.js/singular.png +0 -0
  45. package/tests/screenshots/other_snapshots.js/terrain-vr-scenario.png +0 -0
  46. package/tests/screenshots/other_snapshots.js/terrain.png +0 -0
  47. package/webpack.common.js +1 -1
  48. package/webpack.dev.js +17 -0
  49. package/examples/demos/citations/babiaxr.json +0 -1
  50. package/examples/demos/citations/citations.html +0 -72
  51. package/examples/demos/citations/music.mp3 +0 -0
  52. package/examples/demos/citations/stl.js +0 -28
@@ -0,0 +1,796 @@
1
+ // let updateTitle = require('../others/common').updateTitle;
2
+ // const colors = require('../others/common').colors;
3
+ // let updateFunction = require('../others/common').updateFunction;
4
+
5
+ // const NotiBuffer = require("../../common/noti-buffer").NotiBuffer;
6
+
7
+ /* global AFRAME */
8
+ if (typeof AFRAME === 'undefined') {
9
+ throw new Error('Component attempted to register before AFRAME was available.');
10
+ }
11
+
12
+ /**
13
+ * A-Charts component for A-Frame.
14
+ */
15
+
16
+ AFRAME.registerComponent("babia-map", {
17
+ dependencies: ['raycaster'],
18
+
19
+ schema: {
20
+ width: { type: "number", default: 1000 },
21
+ height: { type: "number", default: 1000 },
22
+ horTexture: { type: "number", default: 2 },
23
+ vertTexture: { type: "number", default: 2 },
24
+ widthSegments: { type: "int", default: 200 },
25
+ heightSegments: { type: "int", default: 200 },
26
+ bumpScale: { type: "number", default: 300 },
27
+ wireframe: { type: "boolean", default: false },
28
+ token: { type: "string" },
29
+ zoom: { type: "number", default: 4 },
30
+ x: { type: "number", default: 0 },
31
+ y: { type: "number", default: 0 },
32
+ subdomain: { type: "string", default: "a" }, // a, b, c
33
+ textureType: { type: "string", default: "Standard" },
34
+ coordinates: { type: "vec2" },
35
+ handsUi: { type: "boolean", default: true},
36
+
37
+ entityRightButton: {
38
+ type: 'string',
39
+ default: JSON.stringify({
40
+ position: '0.25 201.5 -0.5',
41
+ rotation: '-30 0 0'
42
+ })
43
+ },
44
+ entityLeftButton: {
45
+ type: 'string',
46
+ default: JSON.stringify({
47
+ position: '-0.25 201.5 -0.5',
48
+ rotation: '-30 0 0'
49
+ })
50
+ },
51
+ rightButtons: {
52
+ type: 'string',
53
+ default: JSON.stringify([
54
+ { height: '0.075', width: '0.2', label: "Zoom In", color: "blue", position: "0 0.15 -0.3", rotation: "0 0 0", textSize: 0.6, className: "zoomInBtn" },
55
+ { height: '0.075', width: '0.2', label: "Zoom Out", color: "purple", position: "0 0.05 -0.3", rotation: "-0 0 0", textSize: 0.6, className: "zoomOutBtn" }
56
+ ])
57
+ },
58
+ crossEntity: {
59
+ type: 'string',
60
+ default: JSON.stringify({
61
+ position: "0 -0.15 -0.25",
62
+ rotation: "0 0 0"
63
+ })
64
+ },
65
+ crossButtons: {
66
+ type: 'string',
67
+ default: JSON.stringify([
68
+ { height: '0.06', width: '0.06', label: "^", color: "darkgray", position: "0 0.1 0", textSize: 0.6, className: "dpadUp" },
69
+ { height: '0.06', width: '0.06', label: "v", color: "darkgray", position: "0 -0.1 0", textSize: 0.6, className: "dpadDown" },
70
+ { height: '0.06', width: '0.06', label: "<", color: "darkgray", position: "-0.125 0 0", textSize: 0.6, className: "dpadLeft" },
71
+ { height: '0.06', width: '0.06', label: ">", color: "darkgray", position: "0.125 0 0", textSize: 0.6, className: "dpadRight" }
72
+ ])
73
+ },
74
+ leftButtons: {
75
+ type: 'string',
76
+ default: JSON.stringify([
77
+ { height: '0.075', width: '0.2', label: "Next Layer", color: "green", position: "0 0.05 -0.3", rotation: "0 0 0", textSize: 0.6, className: "layerUpBtn" },
78
+ { height: '0.075', width: '0.2', label: "Previous Layer", color: "orange", position: "0 -0.05 -0.3", rotation: "0 0 0", textSize: 0.6, className: "layerDownBtn" }
79
+ ])
80
+ },
81
+ coordinatesText: {
82
+ type: 'string',
83
+ default: JSON.stringify({
84
+ label: 'Coordinates: ',
85
+ color: 'black',
86
+ position: '-0.15 0.1 -0.2',
87
+ rotation: '0 0 0',
88
+ textSize: 0.6
89
+ })
90
+ }
91
+ },
92
+
93
+ init: function () {
94
+ const data = this.data;
95
+ const el = this.el;
96
+ const layers = ['Coloured', 'Cycle', 'Transport', 'Standard', 'Satellite', 'Hot'];
97
+ let currentLayerIndex = layers.indexOf(el.getAttribute('babia-map').textureType);
98
+ if (currentLayerIndex === -1) {
99
+ // El valor no está en la lista
100
+ currentLayerIndex = 0;
101
+ }
102
+
103
+ const BABIA_MAP_PRESET_UI = {
104
+ rightButtons: [
105
+ { height: '0.075', width: '0.2', label: 'Zoom In', color: 'blue', position: '-0.2 0.1 -0.3', rotation: '-30 0 0', textSize: 0.6, className: 'zoomInBtn' },
106
+ { height: '0.075', width: '0.2', label: 'Zoom Out', color: 'purple', position: '-0.2 0 -0.25', rotation: '-30 0 0', textSize: 0.6, className: 'zoomOutBtn' }
107
+ ],
108
+ crossEntity: {
109
+ position: '0.2 0 -0.2',
110
+ rotation: '-30 0 0'
111
+ },
112
+ crossButtons: [
113
+ { height: '0.06', width: '0.06', label: '^', color: 'darkgray', position: '-0.125 0.175 0', textSize: 0.6, className: 'dpadUp' },
114
+ { height: '0.06', width: '0.06', label: 'v', color: 'darkgray', position: '-0.125 0.025 0', textSize: 0.6, className: 'dpadDown' },
115
+ { height: '0.06', width: '0.06', label: '<', color: 'darkgray', position: '-0.2 0.1 0', textSize: 0.6, className: 'dpadLeft' },
116
+ { height: '0.06', width: '0.06', label: '>', color: 'darkgray', position: '-0.05 0.1 0', textSize: 0.6, className: 'dpadRight' }
117
+ ],
118
+ leftButtons: [
119
+ { height: '0.075', width: '0.2', label: 'Next Layer', color: 'green', position: '0 0.2 -0.3', rotation: '-30 0 0', textSize: 0.6, className: 'layerUpBtn' },
120
+ { height: '0.075', width: '0.2', label: 'Previous Layer', color: 'orange', position: '0 0.1 -0.25', rotation: '-30 0 0', textSize: 0.6, className: 'layerDownBtn' }
121
+ ],
122
+ coordinatesText: {
123
+ label: 'Coordinates: ',
124
+ color: 'black',
125
+ position: '-0.15 0 -0.2',
126
+ rotation: '-30 0 0',
127
+ textSize: 0.6
128
+ }
129
+ };
130
+
131
+ let crossButtons = [];
132
+ let entityRightButton = [];
133
+ let entityLeftButton = [];
134
+ let rightButtons = [];
135
+ let crossEntity = [];
136
+ let leftButtons = [];
137
+ let coordinatesText = [];
138
+
139
+ try {
140
+ // BOTONES EN RV
141
+
142
+ const scene = document.querySelector('a-scene');
143
+
144
+ function findHandEntity(handedness) {
145
+ // 1. Buscar por ID directo
146
+ const idSelector = `#${handedness}Hand`;
147
+ let entity = document.querySelector(idSelector);
148
+ if (entity) return entity;
149
+
150
+ // 2. Buscar entidad laser-controls con hand: left o right
151
+ entity = document.querySelector(`[laser-controls][hand="${handedness}"]`);
152
+ if (entity) return entity;
153
+
154
+ // 3. Buscar entidad oculus-touch-controls con hand: left o right
155
+ entity = document.querySelector(`[oculus-touch-controls][hand="${handedness}"]`);
156
+ if (entity) return entity;
157
+
158
+ // Si no se encontró nada
159
+ return null;
160
+ }
161
+
162
+ // Ejemplo de uso:
163
+ const leftHand = findHandEntity("left");
164
+ const rightHand = findHandEntity("right");
165
+
166
+ let stateHands = false;
167
+
168
+ const handlers = {
169
+ layerUp: () => {
170
+ if (currentLayerIndex < layers.length - 1) {
171
+ currentLayerIndex++;
172
+ updateLayer();
173
+ }
174
+ },
175
+ layerDown: () => {
176
+ if (currentLayerIndex > 0) {
177
+ currentLayerIndex--;
178
+ updateLayer();
179
+ }
180
+ },
181
+ zoomIn: () => updateZoom(true),
182
+ zoomOut: () => updateZoom(false),
183
+ mouseEnter: (e) => {
184
+ e.target.setAttribute('material', 'color', 'yellow');
185
+ },
186
+ mouseLeave: (e) => {
187
+ const el = e.target;
188
+ const defaultColor = el.classList.contains('zoomInBtn') ? 'blue' :
189
+ el.classList.contains('zoomOutBtn') ? 'purple' :
190
+ el.classList.contains('layerUpBtn') ? 'green' :
191
+ el.classList.contains('layerDownBtn') ? 'orange' :
192
+ 'darkgray';
193
+ el.setAttribute('material', 'color', defaultColor);
194
+ },
195
+ moveUp: () => move('up'),
196
+ moveDown: () => move('down'),
197
+ moveRight: () => move('right'),
198
+ moveLeft: () => move('left'),
199
+ };
200
+
201
+ function toggleClickEvents(enable, ...parents) {
202
+ const toggleEvent = (el, event, handler) => {
203
+ el[enable ? 'addEventListener' : 'removeEventListener'](event, handler);
204
+ };
205
+
206
+ parents.forEach(parent => {
207
+ // Mapear clases a handlers de click
208
+ const clickMap = {
209
+ '.layerUpBtn': handlers.layerUp,
210
+ '.layerDownBtn': handlers.layerDown,
211
+ '.zoomInBtn': handlers.zoomIn,
212
+ '.zoomOutBtn': handlers.zoomOut,
213
+ '.dpadUp': handlers.moveUp,
214
+ '.dpadDown': handlers.moveDown,
215
+ '.dpadLeft': handlers.moveLeft,
216
+ '.dpadRight': handlers.moveRight,
217
+ };
218
+
219
+ const allContainers = [parent, ...parent.querySelectorAll('.cross')];
220
+ allContainers.forEach(container => {
221
+ for (const [selector, handler] of Object.entries(clickMap)) {
222
+ container.querySelectorAll(selector).forEach(btn => toggleEvent(btn, 'click', handler));
223
+ }
224
+ });
225
+
226
+ // Para los eventos mouseenter/mouseleave en botones interactivos
227
+ parent.querySelectorAll('.interactive-button').forEach(btn => {
228
+ toggleEvent(btn, 'mouseenter', handlers.mouseEnter);
229
+ toggleEvent(btn, 'mouseleave', handlers.mouseLeave);
230
+ });
231
+ });
232
+ }
233
+
234
+ let openCloseMenu = (entity) => {
235
+ entity.addEventListener('gripdown', function () {
236
+ const children = entity.children;
237
+ // Alternar el estado
238
+ stateHands = !stateHands;
239
+ for (let i = 0; i < children.length; i++) {
240
+ if (children[i].setAttribute) {
241
+ children[i].setAttribute('visible', stateHands);
242
+ }
243
+ }
244
+ })
245
+ }
246
+
247
+ crossButtons = JSON.parse(data.crossButtons);
248
+ entityRightButton = JSON.parse(data.entityRightButton);
249
+ entityLeftButton = JSON.parse(data.entityLeftButton);
250
+ rightButtons = JSON.parse(data.rightButtons);
251
+ crossEntity = JSON.parse(data.crossEntity);
252
+ leftButtons = JSON.parse(data.leftButtons);
253
+ coordinatesText = JSON.parse(data.coordinatesText);
254
+
255
+ let leftDesktopHolder = document.createElement('a-entity');
256
+ leftDesktopHolder.setAttribute('position', entityLeftButton.position);
257
+ leftDesktopHolder.setAttribute('rotation', entityLeftButton.rotation);
258
+ leftDesktopHolder.classList.add('left-desktop-ui-position');
259
+ el.appendChild(leftDesktopHolder);
260
+
261
+ let rightDesktopHolder = document.createElement('a-entity');
262
+ rightDesktopHolder.setAttribute('position', entityRightButton.position);
263
+ rightDesktopHolder.setAttribute('rotation', entityRightButton.rotation);
264
+ rightDesktopHolder.classList.add('right-desktop-ui-position');
265
+ el.appendChild(rightDesktopHolder);
266
+
267
+ addButtons(leftDesktopHolder, rightDesktopHolder, rightButtons, crossEntity, crossButtons, leftButtons, coordinatesText);
268
+
269
+ if (data.handsUi) {
270
+ addButtons(leftHand, rightHand, BABIA_MAP_PRESET_UI.rightButtons, BABIA_MAP_PRESET_UI.crossEntity, BABIA_MAP_PRESET_UI.crossButtons, BABIA_MAP_PRESET_UI.leftButtons, BABIA_MAP_PRESET_UI.coordinatesText);
271
+
272
+ scene.addEventListener('enter-vr', () => {
273
+ console.log("Conectado a VR");
274
+ stateHands = true;
275
+ leftDesktopHolder.setAttribute('visible', false);
276
+ rightDesktopHolder.setAttribute('visible', false);
277
+ leftHand.setAttribute('visible', true);
278
+ rightHand.setAttribute('visible', true);
279
+ openCloseMenu(leftHand);
280
+ openCloseMenu(rightHand);
281
+ toggleClickEvents(true, leftHand, rightHand);
282
+ toggleClickEvents(false, leftDesktopHolder, rightDesktopHolder);
283
+ });
284
+
285
+ scene.addEventListener('exit-vr', () => {
286
+ console.log("Saliendo de VR");
287
+ stateHands = false;
288
+ leftDesktopHolder.setAttribute('visible', true);
289
+ rightDesktopHolder.setAttribute('visible', true);
290
+ leftHand.setAttribute('visible', false);
291
+ rightHand.setAttribute('visible', false);
292
+ toggleClickEvents(false, leftHand, rightHand);
293
+ toggleClickEvents(true, leftDesktopHolder, rightDesktopHolder);
294
+ });
295
+ }
296
+
297
+ const updateLayer = () => {
298
+ const newLayer = layers[currentLayerIndex];
299
+ console.log('Cambiando a capa:', newLayer);
300
+ el.setAttribute('babia-map', 'textureType', newLayer);
301
+ this.buildMesh(data, el); // Redibujar el mapa con la nueva capa
302
+ };
303
+
304
+ const updateZoom = (zoomIn) => {
305
+ const MIN_ZOOM = 0;
306
+ const MAX_ZOOM = 19;
307
+
308
+ let currentZoom = el.getAttribute('babia-map').zoom;
309
+ let currentX = el.getAttribute('babia-map').x;
310
+ let currentY = el.getAttribute('babia-map').y;
311
+
312
+ if (zoomIn === true && currentZoom < MAX_ZOOM) {
313
+ currentZoom += 1;
314
+ currentX = Math.min(currentX * 2, Math.pow(2, currentZoom) - 1);
315
+ currentY = Math.min(currentY * 2, Math.pow(2, currentZoom) - 1);
316
+ } else if (!zoomIn && currentZoom > MIN_ZOOM) {
317
+ currentZoom -= 1;
318
+ currentX = Math.max(0, Math.trunc(currentX / 2));
319
+ currentY = Math.max(0, Math.trunc(currentY / 2));
320
+ }
321
+
322
+ el.setAttribute('babia-map', 'zoom', currentZoom);
323
+ el.setAttribute('babia-map', 'x', currentX);
324
+ el.setAttribute('babia-map', 'y', currentY);
325
+
326
+ this.buildMesh(data, el);
327
+ };
328
+
329
+ const move = (where) => {
330
+ let currentZoom = el.getAttribute('babia-map').zoom;
331
+ let currentX = el.getAttribute('babia-map').x;
332
+ let currentY = el.getAttribute('babia-map').y;
333
+
334
+ const maxX = Math.pow(2, currentZoom) - 1;
335
+ const maxY = maxX;
336
+
337
+ console.log(where);
338
+
339
+ switch (where) {
340
+ case 'up':
341
+ if (currentY > 0) currentY -= 1;
342
+ break;
343
+ case 'down':
344
+ if (currentY < maxY) currentY += 1;
345
+ break;
346
+ case 'right':
347
+ if (currentX < maxX) currentX += 1;
348
+ break;
349
+ case 'left':
350
+ if (currentX > 0) currentX -= 1;
351
+ break;
352
+ default:
353
+ console.error("Opción de movimiento no permitida.");
354
+ }
355
+
356
+ el.setAttribute('babia-map', 'x', currentX);
357
+ el.setAttribute('babia-map', 'y', currentY);
358
+
359
+ this.buildMesh(data, el);
360
+ };
361
+
362
+ // Convierte coordenadas de tile a lat/lon (como las usa OSM)
363
+ function localCoordsToLatLon(localX, localZ, el) {
364
+ const zoom = el.getAttribute('babia-map').zoom;
365
+ const tileX = el.getAttribute('babia-map').x;
366
+ const tileY = el.getAttribute('babia-map').y;
367
+ const width = el.getAttribute('babia-map').width;
368
+ const height = el.getAttribute('babia-map').height;
369
+
370
+ // Convertimos coordenadas locales en [0, 1]
371
+ const u = (localX + width / 2) / width;
372
+ const v = 1 - (localZ + height / 2) / height;
373
+
374
+ // Coordenadas reales de tesela (decimales)
375
+ const n = Math.pow(2, zoom);
376
+ const globalTileX = tileX + u;
377
+ const globalTileY = tileY + v;
378
+
379
+ console.log(`Global: ${globalTileX}, ${globalTileY}`);
380
+
381
+ // Conversión a lat/lon usando fórmula de Web Mercator
382
+ const lon = globalTileX / n * 360 - 180;
383
+ const latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * globalTileY / n)));
384
+ const lat = latRad * (180 / Math.PI);
385
+
386
+ return { lat, lon };
387
+ }
388
+
389
+ leftHand.addEventListener('click', (evt) => {
390
+ const intersection = evt.detail.intersection;
391
+ if (!intersection) return;
392
+
393
+ const targetEl = intersection.object.el;
394
+ // Si no es el mapa, no sigue
395
+ if (targetEl !== el) return;
396
+
397
+ const point = intersection.point.clone();
398
+ const localPoint = el.object3D.worldToLocal(point);
399
+ const localX = localPoint.x;
400
+ const localY = localPoint.y;
401
+ const localZ = localPoint.z;
402
+
403
+ const geoCoords = localCoordsToLatLon(localX, localZ, el);
404
+ el.setAttribute('babia-map', 'coordinates', { x: geoCoords.lat, y: geoCoords.lon });
405
+
406
+ let marker = el.querySelector('.marker');
407
+ if (!marker) {
408
+ marker = document.createElement('a-entity');
409
+ marker.setAttribute('geometry', { primitive: 'sphere', radius: data.width/100 });
410
+ marker.setAttribute('material', { color: 'red' });
411
+ marker.setAttribute('position', { x: localX, y: localY+(data.bumpScale/1.5), z: localZ });
412
+ marker.classList.add('marker');
413
+ el.appendChild(marker);
414
+ } else {
415
+ marker.object3D.position.set(localX, localY+(data.bumpScale/1.5), localZ);
416
+ marker.setAttribute('visible', 'true');
417
+ }
418
+
419
+ const coords = el.getAttribute('babia-map').coordinates;
420
+ console.log(`Coordenadas: ${coords.x.toFixed(2)}, ${coords.y.toFixed(2)}`)
421
+ let textBlocks = el.querySelectorAll('.coordinates-text');
422
+ textBlocks.forEach (textBlock => {
423
+ textBlock.setAttribute('value', `Coordenadas: ${coords.x.toFixed(2)}, ${coords.y.toFixed(2)}`);
424
+ })
425
+
426
+ if(data.handsUi) {
427
+ let textBlock = leftHand.querySelector('.coordinates-text');
428
+ textBlock.setAttribute('value', `Coordenadas: ${coords.x.toFixed(2)}, ${coords.y.toFixed(2)}`);
429
+ }
430
+ });
431
+
432
+ toggleClickEvents(true, leftDesktopHolder, rightDesktopHolder);
433
+
434
+ // GUARDAR EL TOKEN
435
+
436
+ const form = document.querySelector("#token-form");
437
+ const input = document.querySelector("#token-input");
438
+
439
+ const savedToken = localStorage.getItem("babia-map-token");
440
+ if (savedToken) {
441
+ input.value = savedToken;
442
+ data.token = savedToken;
443
+ this.buildMesh(data, el);
444
+ }
445
+
446
+ if (form && input) {
447
+ form.addEventListener("submit", (e) => {
448
+ e.preventDefault(); // ← esto evita que la página se recargue
449
+
450
+ const token = input.value.trim();
451
+ if (token) {
452
+ data.token = token;
453
+ localStorage.setItem("babia-map-token", token);
454
+ console.log("Token actualizado:", token);
455
+ this.buildMesh(data, el);
456
+ } else {
457
+ alert("Por favor, introduce un token válido.");
458
+ }
459
+ });
460
+ } else {
461
+ console.warn("Formulario de token no encontrado en el DOM.");
462
+ }
463
+ } catch (e) {
464
+ console.warn('Error:', e);
465
+ }
466
+ },
467
+
468
+ remove: function () {
469
+ this.el.removeObject3D("mesh");
470
+ },
471
+
472
+ update: function (oldData) {
473
+ const data = this.data;
474
+ const el = this.el;
475
+
476
+ if (data.token !== oldData.token || data.textureType !== oldData.textureType) {
477
+ el.removeObject3D("mesh");
478
+ this.buildMesh(data, el);
479
+ }
480
+ },
481
+
482
+ buildMesh: function (data, el) {
483
+ let minHeight;
484
+ let maxHeight;
485
+
486
+ const vertexShader1 = `
487
+ uniform sampler2D bumpTexture;
488
+ uniform float bumpScale;
489
+ varying float vAmount;
490
+ void main() {
491
+ vec4 bumpData = texture2D(bumpTexture, uv);
492
+ vAmount = bumpData.r;
493
+ vec3 newPosition = position + normal * bumpScale * vAmount;
494
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
495
+ }
496
+ `;
497
+
498
+ const fragmentShader1 = `
499
+ uniform float minHeight;
500
+ uniform float maxHeight;
501
+ varying float vAmount;
502
+ void main() {
503
+ float totalHeight = maxHeight - minHeight;
504
+ float maxWater = minHeight + totalHeight * 0.55;
505
+ float minSand = minHeight + totalHeight * 0.54;
506
+ float maxSand = minHeight + totalHeight * 0.57;
507
+ float minGrass = minHeight + totalHeight * 0.56;
508
+ float maxGrass = minHeight + totalHeight * 0.7;
509
+ float minRock = minHeight + totalHeight * 0.60;
510
+ float maxRock = minHeight + totalHeight * 0.80;
511
+ float minSnow = minHeight + totalHeight * 0.65;
512
+
513
+ vec3 water = (smoothstep(0.00, maxWater, vAmount) - smoothstep(minSand, maxWater, vAmount)) * vec3(0.0, 0.0, 1.0);
514
+ vec3 sand = (smoothstep(minSand, maxSand, vAmount) - smoothstep(minGrass, maxSand, vAmount)) * vec3(0.76, 0.7, 0.5);
515
+ vec3 grass = (smoothstep(minGrass, maxGrass, vAmount) - smoothstep(minRock, maxGrass, vAmount)) * vec3(0.0, 0.6, 0.01);
516
+ vec3 rock = (smoothstep(minRock, maxRock, vAmount) - smoothstep(minSnow, maxRock, vAmount)) * vec3(0.28, 0.25, 0.23);
517
+ vec3 snow = (smoothstep(minSnow, 1.0, vAmount)) * vec3(1.0, 1.0, 1.0);
518
+
519
+ gl_FragColor = vec4(water + sand + grass + rock + snow, 1.0);
520
+ }
521
+ `;
522
+
523
+ const vertexShader2 = `
524
+ uniform sampler2D bumpTexture;
525
+ uniform float bumpScale;
526
+ varying vec2 vUv;
527
+
528
+ varying float vAmount;
529
+ void main() {
530
+ vUv = uv;
531
+ vec4 bumpData = texture2D(bumpTexture, uv);
532
+ vAmount = bumpData.r; // Solo canal rojo
533
+ vec3 newPosition = position + normal * bumpScale * vAmount;
534
+
535
+ // Posición final del vértice con transformación del modelo, vista y proyección
536
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(newPosition, 1.0);
537
+ }
538
+ `;
539
+
540
+ const fragmentShader2 = `
541
+ uniform sampler2D mapTexture;
542
+ varying vec2 vUv;
543
+
544
+ void main() {
545
+ vec3 textureColor = texture2D(mapTexture, vUv).rgb;
546
+ gl_FragColor = vec4(textureColor, 1.0);
547
+ }
548
+ `;
549
+
550
+ // CREAR TEXTURA DESDE IMAGEN
551
+ async function loadDisplacementMap(url) {
552
+ let img = new Image();
553
+ img.src = url;
554
+ img.crossOrigin = "Anonymous"; // Evitar problemas CORS
555
+
556
+ return new Promise((resolve, reject) => {
557
+ img.onload = () => {
558
+ const canvas = document.createElement("canvas");
559
+ canvas.width = img.width;
560
+ canvas.height = img.height;
561
+ const ctx = canvas.getContext("2d");
562
+
563
+ // Dibujar la imagen en el canvas de forma invertida (la orientación de la imagen es diferente en canvas respecto a WebGL)
564
+ ctx.translate(0, canvas.height);
565
+ ctx.scale(1, -1);
566
+ ctx.drawImage(img, 0, 0);
567
+ const imageData = ctx.getImageData(0, 0, img.width, img.height);
568
+ const data = imageData.data;
569
+
570
+ // Crear un array para la textura de desplazamiento
571
+ const displacement = new Float32Array(img.width * img.height);
572
+
573
+ let elevation;
574
+ let auxMinHeight = 1;
575
+ let auxMaxHeight = 0;
576
+
577
+ for (let i = 0; i < data.length; i += 4) {
578
+ const R = data[i];
579
+ const G = data[i + 1];
580
+ const B = data[i + 2];
581
+
582
+ // Fórmula de Mapbox terrain-RGB -> Elevación en metros
583
+ elevation = (R * 256 * 256 + G * 256 + B) * 0.1 - 10000;
584
+
585
+ // Normalizar para Three.js (opcional, si necesitas valores entre 0 y 1)
586
+ elevation = (elevation + 10000) / 20000; // Elevación entre 0 y 1
587
+
588
+ // Comprobar el valor más bajo y más alto
589
+ if (elevation < auxMinHeight) {
590
+ auxMinHeight = elevation;
591
+ }
592
+ if (elevation > auxMaxHeight) {
593
+ auxMaxHeight = elevation;
594
+ }
595
+
596
+ displacement[i / 4] = elevation;
597
+ }
598
+
599
+ // Guardar el valor más bajo y más alto
600
+ minHeight = auxMinHeight;
601
+ maxHeight = auxMaxHeight;
602
+
603
+ // Crear textura de desplazamiento
604
+ const texture = new THREE.DataTexture(
605
+ displacement,
606
+ img.width,
607
+ img.height,
608
+ THREE.RedFormat, // Un canal para el desplazamiento
609
+ THREE.FloatType // Usamos valores en coma flotante
610
+ );
611
+
612
+ texture.needsUpdate = true;
613
+ resolve(texture);
614
+ };
615
+ img.onerror = reject;
616
+ });
617
+ };
618
+
619
+ let urlMapbox = `https://api.mapbox.com/v4/mapbox.terrain-rgb/${data.zoom}/${data.x}/${data.y}@2x.pngraw?access_token=${data.token}`
620
+
621
+ // CREAR MALLA
622
+ loadDisplacementMap(urlMapbox).then((texture) => {
623
+ console.log("Displacement map cargado:", urlMapbox);
624
+
625
+ // Horizontal & vertical texture repetition
626
+ texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
627
+ texture.repeat.set(data.horTexture, data.vertTexture);
628
+
629
+ // Añadir uniformes
630
+ let uniforms;
631
+ let groundMaterial;
632
+
633
+ // Si el tipo de textura es 0 (Openstreetmap)
634
+ // Si el tipo de textura es 1 (Shaders)
635
+ if (data.textureType === "Coloured") {
636
+ uniforms = {
637
+ bumpTexture: { type: "t", value: texture },
638
+ bumpScale: { type: "f", value: data.bumpScale },
639
+ minHeight: { value: minHeight },
640
+ maxHeight: { value: maxHeight },
641
+ };
642
+ console.log("Uniforms:", uniforms);
643
+
644
+ // Añadir shader
645
+ groundMaterial = new THREE.ShaderMaterial({
646
+ uniforms: uniforms,
647
+ vertexShader: vertexShader1,
648
+ fragmentShader: fragmentShader1,
649
+ });
650
+ } else {
651
+ let url;
652
+
653
+ switch (data.textureType) {
654
+ case "Standard":
655
+ // Si el tipo de textura es Openstreetmap Estándar
656
+ url = `https://tile.openstreetmap.org/${data.zoom}/${data.x}/${data.y}.png`;
657
+ break;
658
+ case "Satellite":
659
+ // Si el tipo de textura es Satélite
660
+ url = `https://api.mapbox.com/styles/v1/mapbox/satellite-v9/tiles/256/${data.zoom}/${data.x}/${data.y}?access_token=${data.token}`;
661
+ break;
662
+ case "Hot":
663
+ // Si el tipo de textura es Humanitaian OpenStreetMap Team
664
+ url = `https://tile-a.openstreetmap.fr/hot/${data.zoom}/${data.x}/${data.y}.png`;
665
+ break;
666
+ case "Cycle":
667
+ // Si el tipo de textura es OpenCycleMap
668
+ url = `https://${data.subdomain}.tile.thunderforest.com/cycle/${data.zoom}/${data.x}/${data.y}.png`;
669
+ break;
670
+ case "Transport":
671
+ // Si el tipo de textura es Thunderforest Transport
672
+ url = `https://${data.subdomain}.tile.thunderforest.com/transport/${data.zoom}/${data.x}/${data.y}.png`;
673
+ break;
674
+ default:
675
+ console.error("Tipo de textura no soportado");
676
+ };
677
+
678
+ const textureLoader = new THREE.TextureLoader();
679
+ const mapTexture = textureLoader.load(url);
680
+
681
+ uniforms = {
682
+ bumpTexture: { type: "t", value: texture },
683
+ bumpScale: { type: "f", value: data.bumpScale },
684
+ mapTexture: { value: mapTexture },
685
+ };
686
+ console.log("Uniforms:", uniforms);
687
+
688
+ // Añadir shader
689
+ groundMaterial = new THREE.ShaderMaterial({
690
+ uniforms: uniforms,
691
+ vertexShader: vertexShader2,
692
+ fragmentShader: fragmentShader2,
693
+ });
694
+ }
695
+
696
+ // Crear geometría del terreno
697
+ const groundGeo = new THREE.PlaneGeometry(
698
+ data.width,
699
+ data.height,
700
+ data.widthSegments,
701
+ data.heightSegments
702
+ );
703
+
704
+ // Crear malla
705
+ let groundMesh = new THREE.Mesh(groundGeo, groundMaterial);
706
+ groundMesh.rotation.x = -Math.PI / 2;
707
+ groundMesh.position.y = 0;
708
+
709
+ // Añadir la malla a la entidad
710
+ el.setObject3D("mesh", groundMesh);
711
+
712
+ console.log(data)
713
+
714
+ },
715
+ (error) => {
716
+ console.error("Error al cargar el displacement map:", error);
717
+ }
718
+ );
719
+ }
720
+ });
721
+
722
+ function addButtons(leftMenu, rightMenu, rightButtons, crossEntity, crossButtons, leftButtons, coordinatesText) {
723
+ leftButtons.forEach(btnData => {
724
+ const btn = createButton(
725
+ `primitive: plane; height: ${btnData.height}; width: ${btnData.width}`,
726
+ btnData.label,
727
+ btnData.color,
728
+ btnData.position,
729
+ btnData.rotation,
730
+ btnData.textSize,
731
+ [btnData.className]
732
+ );
733
+ leftMenu.appendChild(btn);
734
+ });
735
+
736
+ rightButtons.forEach(btnData => {
737
+ const btn = createButton(
738
+ `primitive: plane; height: ${btnData.height}; width: ${btnData.width}`,
739
+ btnData.label,
740
+ btnData.color,
741
+ btnData.position,
742
+ btnData.rotation,
743
+ btnData.textSize,
744
+ [btnData.className]
745
+ );
746
+ rightMenu.appendChild(btn);
747
+ });
748
+
749
+ let cross = document.createElement('a-entity');
750
+ cross.setAttribute('rotation', crossEntity.rotation); // este es el tamaño del texto
751
+ cross.setAttribute('position', crossEntity.position);
752
+ cross.classList.add('cross');
753
+ rightMenu.appendChild(cross);
754
+
755
+ crossButtons.forEach(btnData => {
756
+ const btn = createButton(
757
+ `primitive: plane; height: ${btnData.height}; width: ${btnData.width}`,
758
+ btnData.label,
759
+ btnData.color,
760
+ btnData.position,
761
+ btnData.rotation,
762
+ btnData.textSize,
763
+ [btnData.className]
764
+ );
765
+ cross.appendChild(btn);
766
+ });
767
+
768
+ let textBlock = document.createElement('a-text');
769
+ textBlock.setAttribute('value', coordinatesText.label);
770
+ textBlock.setAttribute('color', coordinatesText.color);
771
+ textBlock.setAttribute('position', coordinatesText.position);
772
+ textBlock.setAttribute('rotation', coordinatesText.rotation);
773
+ textBlock.setAttribute('width', coordinatesText.textSize);
774
+ textBlock.classList.add('coordinates-text');
775
+ leftMenu.appendChild(textBlock);
776
+ }
777
+
778
+ function createButton(geometry, label, color, position, rotation = null, textSize = 0.5, classes = []) {
779
+ const button = document.createElement('a-text');
780
+
781
+ button.setAttribute('geometry', geometry);
782
+ button.setAttribute('material', `color: ${color}`);
783
+ button.setAttribute('value', label);
784
+ button.setAttribute('align', 'center');
785
+ button.setAttribute('width', textSize);
786
+ button.setAttribute('position', position);
787
+
788
+ if (rotation) {
789
+ button.setAttribute('rotation', rotation);
790
+ }
791
+
792
+ button.classList.add('collidable', 'interactive-button', ...classes);
793
+ return button;
794
+ }
795
+
796
+