diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index df4557f..944ca0a 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -14,6 +14,8 @@ on: - 'apps/levantamiento/**' - 'scripts/grafo_campus.py' - 'scripts/test_grafo_campus.py' + - 'scripts/preparar_modelo3d.py' + - 'scripts/test_modelo3d.py' - '.github/workflows/mobile.yml' pull_request: paths: @@ -22,6 +24,8 @@ on: - 'apps/levantamiento/**' - 'scripts/grafo_campus.py' - 'scripts/test_grafo_campus.py' + - 'scripts/preparar_modelo3d.py' + - 'scripts/test_modelo3d.py' - '.github/workflows/mobile.yml' # El token de GitHub de estos jobs solo necesita leer el código. @@ -43,7 +47,7 @@ jobs: - uses: actions/setup-python@v5 with: python-version: '3.13' - - run: python -I -m unittest discover -s scripts -p test_grafo_campus.py -v + - run: python -I -m unittest discover -s scripts -p 'test_*.py' -v modulo: name: Modulo (formato, codigo generado y analisis) @@ -164,6 +168,8 @@ jobs: cache: true - run: flutter pub get + - name: Preparar maqueta 3D del campus + run: python ../../scripts/preparar_modelo3d.py - run: flutter build apk --debug - uses: actions/upload-artifact@v4 diff --git a/.gitignore b/.gitignore index 8395172..432238c 100644 --- a/.gitignore +++ b/.gitignore @@ -48,3 +48,7 @@ apps/mobile/android/app/src/assets/mapa_campus.webp # Al repo solo va el grafo que sale de ellos. levantamiento-*.json recorridos*.geojson + +# Maqueta institucional de ElMapita: scripts/preparar_modelo3d.py la descarga +# y prepara; se empaqueta en el APK, sin versionar el binario. +/packages/tour_virtual/assets/mapa3d/*.glb diff --git a/apps/levantamiento/pubspec.lock b/apps/levantamiento/pubspec.lock index 3fadcc8..9f323c8 100644 --- a/apps/levantamiento/pubspec.lock +++ b/apps/levantamiento/pubspec.lock @@ -1,6 +1,14 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + android_intent_plus: + dependency: transitive + description: + name: android_intent_plus + sha256: "4d4bbd619d698cbee3c400ba89246ecb0f525146b0ae05389f62ede47abd5bec" + url: "https://pub.dev" + source: hosted + version: "6.1.0" args: dependency: transitive description: @@ -549,6 +557,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.18.0" + model_viewer_plus: + dependency: transitive + description: + name: model_viewer_plus + sha256: c5bfcd296a28246cceec821b0e7da268690e40baa99a3fa0f09d7a3227eb967d + url: "https://pub.dev" + source: hosted + version: "1.10.0" objective_c: dependency: transitive description: @@ -897,6 +913,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" + url: "https://pub.dev" + source: hosted + version: "6.3.30" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" uuid: dependency: transitive description: @@ -985,6 +1065,38 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.1" + webview_flutter: + dependency: transitive + description: + name: webview_flutter + sha256: c3e4fe614b1c814950ad07186007eff2f2e5dd2935eba7b9a9a1af8e5885f1ba + url: "https://pub.dev" + source: hosted + version: "4.13.0" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: ad5182eff9a550925330cb9f0cb038eddfdd5712aba8b77aa0f0400e50f6e688 + url: "https://pub.dev" + source: hosted + version: "4.12.0" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: "82648217f537573e1ca9ae9952d3eacedca6ab5aee69dc84445fc763766dcea2" + url: "https://pub.dev" + source: hosted + version: "3.25.1" win32: dependency: transitive description: diff --git a/apps/mobile/android/.gitignore b/apps/mobile/android/.gitignore index be3943c..dd5d2c9 100644 --- a/apps/mobile/android/.gitignore +++ b/apps/mobile/android/.gitignore @@ -12,3 +12,4 @@ GeneratedPluginRegistrant.java key.properties **/*.keystore **/*.jks +.kotlin/ diff --git a/apps/mobile/android/app/src/main/AndroidManifest.xml b/apps/mobile/android/app/src/main/AndroidManifest.xml index ce3e787..59f4aa3 100644 --- a/apps/mobile/android/app/src/main/AndroidManifest.xml +++ b/apps/mobile/android/app/src/main/AndroidManifest.xml @@ -16,6 +16,7 @@ android:label="@string/app_name" android:name="${applicationName}" android:icon="@mipmap/ic_launcher" + android:networkSecurityConfig="@xml/network_security_config" android:usesCleartextTraffic="false"> + + + + + 127.0.0.1 + localhost + + diff --git a/apps/mobile/integration_test/mapa_3d_test.dart b/apps/mobile/integration_test/mapa_3d_test.dart new file mode 100644 index 0000000..1b9b11f --- /dev/null +++ b/apps/mobile/integration_test/mapa_3d_test.dart @@ -0,0 +1,146 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:tour_virtual/app_tour.dart'; +import 'package:tour_virtual/configuracion_tour.dart'; +import 'package:tour_virtual/datos/preferencias.dart'; +import 'package:tour_virtual/l10n/textos.dart'; +import 'package:tour_virtual/nucleo/tema.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +void main() { + final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + testWidgets('modelo local, controles, ficha y regreso al plano', ( + tester, + ) async { + // Preferencias en memoria: esta comprobación no borra ni modifica las + // preferencias y las visitas guardadas por la persona en su teléfono. + SharedPreferences.setMockInitialValues({}); + await tester.pumpWidget(_aplicacion(1)); + await _esperar( + tester, + () => find.byIcon(Icons.map_rounded).evaluate().isNotEmpty, + ); + await tester.tap(find.byIcon(Icons.map_rounded)); + await _pausa(tester); + await binding.convertFlutterSurfaceToImage(); + await tester.pump(); + await binding.takeScreenshot('phone-mapa-2d'); + + await tester.tap(find.byTooltip('Ver mapa en 3D')); + await _esperar( + tester, + () => find.byTooltip('Girar a la derecha').evaluate().isNotEmpty, + ); + await _pausa(tester); + final web = tester + .widget(find.byType(WebViewWidget)) + .platform + .params + .controller; + expect( + await web.runJavaScriptReturningResult( + "document.querySelector('model-viewer').loaded", + ), + true, + ); + final pines = await web.runJavaScriptReturningResult( + "document.querySelectorAll('[data-tour-poi]').length", + ); + expect(_numero(pines), greaterThanOrEqualTo(5)); + await binding.takeScreenshot('phone-mapa-3d'); + + final radio = await web.runJavaScriptReturningResult( + "document.querySelector('model-viewer').getCameraOrbit().radius", + ); + await tester.tap(find.byTooltip('Acercar')); + await _pausa(tester); + final cerca = await web.runJavaScriptReturningResult( + "document.querySelector('model-viewer').getCameraOrbit().radius", + ); + expect(_numero(cerca), lessThan(_numero(radio))); + await tester.tap(find.byTooltip('Girar a la derecha')); + await _pausa(tester); + await binding.takeScreenshot('phone-mapa-3d-giro'); + + await web.runJavaScript( + "document.querySelector('[data-tour-poi=\"1\"]').click()", + ); + await _esperar( + tester, + () => find.byType(BottomSheet).evaluate().isNotEmpty, + ); + await _pausa(tester); + await binding.takeScreenshot('phone-mapa-3d-ficha'); + Navigator.of(tester.element(find.byType(BottomSheet))).pop(); + await _pausa(tester); + await tester.tap(find.byTooltip('Volver al mapa 2D')); + await _pausa(tester); + expect(find.byTooltip('Ver mapa en 3D'), findsOneWidget); + expect(find.byType(InteractiveViewer), findsOneWidget); + await binding.takeScreenshot('phone-mapa-2d-regreso'); + + await tester.tap(find.byTooltip('Ver mapa en 3D')); + await _pausa(tester); + await tester.pumpWidget(_aplicacion(2)); + await _pausa(tester); + await binding.takeScreenshot('phone-mapa-3d-texto-grande'); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pump(const Duration(seconds: 1)); + }); +} + +double _numero(Object valor) => + valor is num ? valor.toDouble() : double.parse('$valor'); + +Future _pausa(WidgetTester tester) async { + await tester.pump(const Duration(seconds: 2)); + await tester.pump(); +} + +Future _esperar(WidgetTester tester, bool Function() condicion) async { + final limite = DateTime.now().add(const Duration(seconds: 40)); + while (!condicion() && DateTime.now().isBefore(limite)) { + await tester.pump(const Duration(milliseconds: 150)); + } + expect( + condicion(), + isTrue, + reason: 'La pantalla no llegó al estado esperado', + ); +} + +Widget _aplicacion(double escala) => ProviderScope( + overrides: [ + configuracionTourProvider.overrideWithValue( + const ConfiguracionTour(fuente: ContenidoLocal(medios: 'empaquetados')), + ), + preferenciasInicialesProvider.overrideWithValue( + const Preferencias(idioma: Locale('es'), analitica: false), + ), + ], + child: _AppCaptura(escala: escala), +); + +class _AppCaptura extends StatelessWidget { + const _AppCaptura({required this.escala}); + final double escala; + + @override + Widget build(BuildContext context) => MaterialApp( + locale: const Locale('es'), + supportedLocales: Textos.supportedLocales, + localizationsDelegates: Textos.localizationsDelegates, + theme: temaUtb(altoContraste: false), + builder: (context, child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(escala)), + child: child!, + ), + home: const HomeScreen(), + ); +} diff --git a/apps/mobile/ios/Runner/Info.plist b/apps/mobile/ios/Runner/Info.plist index 5a3b47c..f562c8a 100644 --- a/apps/mobile/ios/Runner/Info.plist +++ b/apps/mobile/ios/Runner/Info.plist @@ -2,6 +2,11 @@ + NSAppTransportSecurity + + NSAllowsLocalNetworking + + NSLocationWhenInUseUsageDescription Para guiarte a pie por el campus de la UTB. Tu ubicación no sale del teléfono ni se guarda. NSCameraUsageDescription diff --git a/apps/mobile/linux/flutter/generated_plugin_registrant.cc b/apps/mobile/linux/flutter/generated_plugin_registrant.cc index e71a16d..f6f23bf 100644 --- a/apps/mobile/linux/flutter/generated_plugin_registrant.cc +++ b/apps/mobile/linux/flutter/generated_plugin_registrant.cc @@ -6,6 +6,10 @@ #include "generated_plugin_registrant.h" +#include void fl_register_plugins(FlPluginRegistry* registry) { + g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = + fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); + url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } diff --git a/apps/mobile/linux/flutter/generated_plugins.cmake b/apps/mobile/linux/flutter/generated_plugins.cmake index be1ee3e..df8d2f7 100644 --- a/apps/mobile/linux/flutter/generated_plugins.cmake +++ b/apps/mobile/linux/flutter/generated_plugins.cmake @@ -3,6 +3,7 @@ # list(APPEND FLUTTER_PLUGIN_LIST + url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/apps/mobile/macos/Flutter/GeneratedPluginRegistrant.swift b/apps/mobile/macos/Flutter/GeneratedPluginRegistrant.swift index c9f96a0..dea488b 100644 --- a/apps/mobile/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/apps/mobile/macos/Flutter/GeneratedPluginRegistrant.swift @@ -12,8 +12,10 @@ import just_audio import package_info_plus import shared_preferences_foundation import sqflite_darwin +import url_launcher_macos import video_player_avfoundation import wakelock_plus +import webview_flutter_wkwebview func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { AudioSessionPlugin.register(with: registry.registrar(forPlugin: "AudioSessionPlugin")) @@ -23,6 +25,8 @@ func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) SqflitePlugin.register(with: registry.registrar(forPlugin: "SqflitePlugin")) + UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) VideoPlayerPlugin.register(with: registry.registrar(forPlugin: "VideoPlayerPlugin")) WakelockPlusMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockPlusMacosPlugin")) + WebViewFlutterPlugin.register(with: registry.registrar(forPlugin: "WebViewFlutterPlugin")) } diff --git a/apps/mobile/pubspec.lock b/apps/mobile/pubspec.lock index 774ec74..1985344 100644 --- a/apps/mobile/pubspec.lock +++ b/apps/mobile/pubspec.lock @@ -1,6 +1,14 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + android_intent_plus: + dependency: transitive + description: + name: android_intent_plus + sha256: "4d4bbd619d698cbee3c400ba89246ecb0f525146b0ae05389f62ede47abd5bec" + url: "https://pub.dev" + source: hosted + version: "6.1.0" args: dependency: transitive description: @@ -238,6 +246,11 @@ packages: url: "https://pub.dev" source: hosted version: "0.1.1" + flutter_driver: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" flutter_lints: dependency: "direct dev" description: @@ -301,6 +314,11 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.0" + fuchsia_remote_debug_protocol: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" geoclue: dependency: transitive description: @@ -413,6 +431,11 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" + integration_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" intl: dependency: transitive description: @@ -541,6 +564,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.17.0" + model_viewer_plus: + dependency: transitive + description: + name: model_viewer_plus + sha256: c5bfcd296a28246cceec821b0e7da268690e40baa99a3fa0f09d7a3227eb967d + url: "https://pub.dev" + source: hosted + version: "1.10.0" objective_c: dependency: transitive description: @@ -669,6 +700,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" + process: + dependency: transitive + description: + name: process + sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891" + url: "https://pub.dev" + source: hosted + version: "5.0.6" pub_semver: dependency: transitive description: @@ -850,6 +889,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.1" + sync_http: + dependency: transitive + description: + name: sync_http + sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961" + url: "https://pub.dev" + source: hosted + version: "0.3.1" synchronized: dependency: transitive description: @@ -889,6 +936,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + url_launcher: + dependency: transitive + description: + name: url_launcher + sha256: e8cc955c97e06df9879140a1fe301f3d493f01b7c62dec7f46834be31d7e9fda + url: "https://pub.dev" + source: hosted + version: "6.3.3" + url_launcher_android: + dependency: transitive + description: + name: url_launcher_android + sha256: "17bc677f0b301615530dd1d67e0a9828cafa2d0b6b6eae4cd3679b7eac4a273c" + url: "https://pub.dev" + source: hosted + version: "6.3.30" + url_launcher_ios: + dependency: transitive + description: + name: url_launcher_ios + sha256: "8faa1aab294f1ab4040b43660c887b0418d5fa4f0cffef76a484e6aa1092eb4a" + url: "https://pub.dev" + source: hosted + version: "6.4.2" + url_launcher_linux: + dependency: transitive + description: + name: url_launcher_linux + sha256: "10f86fef4c2c43563fa6c211ff9cf757adf4d3ab762c56bd430664a947d70cd0" + url: "https://pub.dev" + source: hosted + version: "3.2.3" + url_launcher_macos: + dependency: transitive + description: + name: url_launcher_macos + sha256: "5e835a3b869c2d70325349c81c5a45c28e20791265b67b2669da6b08c5cd5201" + url: "https://pub.dev" + source: hosted + version: "3.2.6" + url_launcher_platform_interface: + dependency: transitive + description: + name: url_launcher_platform_interface + sha256: "552f8a1e663569be95a8190206a38187b531910283c3e982193e4f2733f01029" + url: "https://pub.dev" + source: hosted + version: "2.3.2" + url_launcher_web: + dependency: transitive + description: + name: url_launcher_web + sha256: "85c81589622fbc87c1c683aaea164d3604a7777495a79d91e39ffcdec39ddb34" + url: "https://pub.dev" + source: hosted + version: "2.4.3" + url_launcher_windows: + dependency: transitive + description: + name: url_launcher_windows + sha256: "6c5ad3f22cd4c38e089b81963b3cd7bb83b111b2df5dce008bb066162f42e429" + url: "https://pub.dev" + source: hosted + version: "3.1.6" uuid: dependency: transitive description: @@ -977,6 +1088,46 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.1" + webdriver: + dependency: transitive + description: + name: webdriver + sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e" + url: "https://pub.dev" + source: hosted + version: "3.2.0" + webview_flutter: + dependency: "direct dev" + description: + name: webview_flutter + sha256: c3e4fe614b1c814950ad07186007eff2f2e5dd2935eba7b9a9a1af8e5885f1ba + url: "https://pub.dev" + source: hosted + version: "4.13.0" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + sha256: ad5182eff9a550925330cb9f0cb038eddfdd5712aba8b77aa0f0400e50f6e688 + url: "https://pub.dev" + source: hosted + version: "4.12.0" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + sha256: "1221c1b12f5278791042f2ec2841743784cf25c5a644e23d6680e5d718824f04" + url: "https://pub.dev" + source: hosted + version: "2.15.1" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + sha256: "82648217f537573e1ca9ae9952d3eacedca6ab5aee69dc84445fc763766dcea2" + url: "https://pub.dev" + source: hosted + version: "3.25.1" win32: dependency: transitive description: diff --git a/apps/mobile/pubspec.yaml b/apps/mobile/pubspec.yaml index 5cfb436..c33747e 100644 --- a/apps/mobile/pubspec.yaml +++ b/apps/mobile/pubspec.yaml @@ -27,6 +27,9 @@ dev_dependencies: # Las pruebas manejan directamente lo que el paquete usa por dentro. flutter_riverpod: ^2.6.1 http: ^1.6.0 + integration_test: + sdk: flutter + webview_flutter: 4.13.0 flutter: uses-material-design: true diff --git a/apps/mobile/test/mapa_3d_test.dart b/apps/mobile/test/mapa_3d_test.dart new file mode 100644 index 0000000..4f59d00 --- /dev/null +++ b/apps/mobile/test/mapa_3d_test.dart @@ -0,0 +1,95 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:tour_virtual/app_tour.dart'; +import 'package:tour_virtual/datos/georreferencia_3d.dart'; +import 'package:tour_virtual/datos/preferencias.dart'; +import 'package:tour_virtual/datos/proveedores.dart'; +import 'package:tour_virtual/ui/inicio/mapa_3d.dart'; + +import 'widget_test.dart' as base; + +void main() { + setUp(() => SharedPreferences.setMockInitialValues({})); + + test('la conversión al modelo conserva las coordenadas al volver', () { + for (final punto in [ + (10.3699965, -75.4650668), + (10.37075, -75.46598), + (10.3691852, -75.4655576), + ]) { + final modelo = Georreferencia3d.aModelo(punto.$1, punto.$2); + final recuperado = Georreferencia3d.aGeografico(modelo.x, modelo.z); + expect(recuperado.lat, closeTo(punto.$1, 1e-10)); + expect(recuperado.lng, closeTo(punto.$2, 1e-10)); + } + }); + + test('la Biblioteca queda en el modelo, con norte coherente con OSM', () { + final p = Georreferencia3d.aModelo(10.3699965, -75.4650668); + expect(p.x, inInclusiveRange(0, 100)); + expect(p.z, inInclusiveRange(-230, -100)); + expect(Georreferencia3d.norteCamara, inInclusiveRange(130, 145)); + }); + + Future montar(WidgetTester tester, Future recursos) async { + base.usarTelefono(tester); + await tester.pumpWidget( + ProviderScope( + overrides: [ + preferenciasInicialesProvider.overrideWithValue(base.espanol), + repositorioContenidoProvider.overrideWithValue( + base.RepositorioFalso(pois: base.poisDePrueba), + ), + recursosMapa3dProvider.overrideWith((ref) => recursos), + ], + child: const base.AppDePrueba(hijo: HomeScreen(), sinAnimaciones: true), + ), + ); + await base.asentar(tester); + await base.abrirMapa(tester); + } + + testWidgets('si falta la maqueta conserva el plano y permite reintentar', ( + tester, + ) async { + final recurso = Completer(); + await montar(tester, recurso.future); + await tester.tap(find.byTooltip('Ver mapa en 3D')); + await tester.pump(); + expect(find.byTooltip('Volver al mapa 2D'), findsOneWidget); + recurso.completeError(StateError('Recurso ausente')); + await base.asentar(tester); + expect(find.byTooltip('Ver mapa en 3D'), findsOneWidget); + expect(find.textContaining('No se pudo abrir el mapa 3D'), findsOneWidget); + expect(find.byType(InteractiveViewer), findsOneWidget); + await tester.pumpWidget(const SizedBox.shrink()); + await base.drenarTemporizadores(tester); + }); + + testWidgets( + 'se puede cancelar el 3D mientras carga, sin perder la selección', + (tester) async { + final recurso = Completer(); + await montar(tester, recurso.future); + final paginas = tester + .widget(find.byType(PageView)) + .controller!; + paginas.jumpToPage(1); + await base.asentar(tester); + expect(paginas.page, 1); + await tester.tap(find.byTooltip('Ver mapa en 3D')); + await tester.pump(); + await tester.tap(find.byTooltip('Volver al mapa 2D')); + await base.asentar(tester); + expect(find.byTooltip('Ver mapa en 3D'), findsOneWidget); + expect(find.byType(InteractiveViewer), findsOneWidget); + expect(paginas.page, 1); + await tester.pumpWidget(const SizedBox.shrink()); + await base.drenarTemporizadores(tester); + }, + ); +} diff --git a/apps/mobile/test_driver/mapa_3d.dart b/apps/mobile/test_driver/mapa_3d.dart new file mode 100644 index 0000000..b4265e0 --- /dev/null +++ b/apps/mobile/test_driver/mapa_3d.dart @@ -0,0 +1,14 @@ +import 'dart:io'; + +import 'package:integration_test/integration_test_driver_extended.dart'; + +Future main() async { + final carpeta = Directory('../../.impeccable/review') + ..createSync(recursive: true); + await integrationDriver( + onScreenshot: (nombre, bytes, [argumentos]) async { + await File('${carpeta.path}/$nombre.png').writeAsBytes(bytes); + return bytes.length > 1000; + }, + ); +} diff --git a/apps/mobile/windows/flutter/generated_plugin_registrant.cc b/apps/mobile/windows/flutter/generated_plugin_registrant.cc index 16469c4..a30a8cb 100644 --- a/apps/mobile/windows/flutter/generated_plugin_registrant.cc +++ b/apps/mobile/windows/flutter/generated_plugin_registrant.cc @@ -9,6 +9,7 @@ #include #include #include +#include void RegisterPlugins(flutter::PluginRegistry* registry) { FlutterTtsPluginRegisterWithRegistrar( @@ -17,4 +18,6 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { registry->GetRegistrarForPlugin("GeolocatorWindows")); JustAudioWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("JustAudioWindowsPlugin")); + UrlLauncherWindowsRegisterWithRegistrar( + registry->GetRegistrarForPlugin("UrlLauncherWindows")); } diff --git a/apps/mobile/windows/flutter/generated_plugins.cmake b/apps/mobile/windows/flutter/generated_plugins.cmake index 70933a3..afce668 100644 --- a/apps/mobile/windows/flutter/generated_plugins.cmake +++ b/apps/mobile/windows/flutter/generated_plugins.cmake @@ -6,6 +6,7 @@ list(APPEND FLUTTER_PLUGIN_LIST flutter_tts geolocator_windows just_audio_windows + url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST diff --git a/docs/integracion-utb-app.md b/docs/integracion-utb-app.md index c9e0a69..b0b48c6 100644 --- a/docs/integracion-utb-app.md +++ b/docs/integracion-utb-app.md @@ -154,6 +154,10 @@ flutter test # incluye integraci ## Pendiente, del lado de la UTB +La vista 3D opcional del mapa necesita preparar la maqueta antes de compilar +y permitir el servidor local del visor en Android/iOS. Los recursos y la +configuración de loopback están descritos en [mapa-3d.md](mapa-3d.md). + | Decisión | Afecta a | |---|---| | Nube o local | La línea de `fuente`. Si es nube, quién aloja la API, la base y el almacenamiento. | diff --git a/docs/mapa-3d.md b/docs/mapa-3d.md new file mode 100644 index 0000000..d9ab865 --- /dev/null +++ b/docs/mapa-3d.md @@ -0,0 +1,84 @@ +# Maqueta 3D del campus + +El mapa del tour permite alternar entre el plano OSM y la maqueta de +[ElMapita UTB](https://github.com/ISCOUTB/AS_202620_ElMapita). El botón 3D está +en el mapa, debajo del contador de paradas. Conserva la selección del +carrusel, las fichas y el encuadre al volver al plano. + +La transición cruza el plano con una vista cenital del modelo y luego inclina +la cámara. Al volver, la cámara se endereza antes del fundido. «Quitar +animaciones» evita el movimiento espacial. Zoom, giro y encuadre también +tienen botones de 48 dp; no requieren pellizcar ni arrastrar. + +## Preparar el modelo + +Desde la raíz del repositorio, antes de compilar: + +```sh +python -I scripts/preparar_modelo3d.py +``` + +El script descarga el GLB público, comprueba su SHA-256 y excluye del dibujo +el nodo `Plano_Referencia`, usado como imagen de apoyo al modelar. Conserva +las coordenadas y la geometría del resto de la maqueta. El origen, autores, +URL y huella están en +[`origen.json`](../packages/tour_virtual/assets/mapa3d/origen.json). + +El binario institucional no se versiona. El APK incorpora tanto el GLB como +el motor del visor y funciona sin conexión. CI prepara el recurso antes de +compilar ambas apps. Si falta el modelo o falla el visor, el plano sigue +disponible y se puede reintentar. + +## Integración + +Se reutiliza el modelo, sin introducir el backend ni el estado de ElMapita. +Las fichas, el catálogo de lugares, sus permisos y el progreso siguen siendo +los del módulo. Los pines se crean solo con los POI que este ya recibió. + +La transformación OSM → modelo corresponde al ajuste provisional de +ElMapita (error medio aproximado de 9 m). `Georreferencia3d` permite también +la conversión inversa para conservar el centro del mapa. No interviene en +el cálculo de rutas ni de llegadas de AR: esos siguen usando el grafo y los +accesos medidos. La alineación se debe afinar con puntos reales del campus. + +La vista 3D usa `model_viewer_plus` en Android e iOS. Windows y web conservan +el plano. La comprobación física de esta integración se realiza en Android; +el comportamiento de iOS requiere su propia revisión en dispositivo. + +## Apps anfitrionas + +El visor sirve recursos del APK mediante un servidor en `127.0.0.1`. +En Android la anfitriona debe permitir HTTP **solo hacia loopback**, manteniendo +HTTPS para la API y los medios externos. El ejemplo está en +[`network_security_config.xml`](../apps/mobile/android/app/src/main/res/xml/network_security_config.xml) +y se referencia desde el manifest de la app de demostración. + +En iOS se configura `NSAppTransportSecurity.NSAllowsLocalNetworking`. +No se habilita HTTP general para la API. + +## Comprobaciones + +```sh +python -B -I -m unittest discover -s scripts -p 'test_*.py' -v +cd apps/mobile +flutter test test/mapa_3d_test.dart +flutter test +``` + +Las regresiones cubren la transformación geográfica inversa, el fallo de +carga, la cancelación mientras carga y la conservación del carrusel, además +de excluir la referencia del GLB sin modificar su bloque binario. + +La comprobación en un Android conectado usa una prueba dentro de Flutter, +sin inyectar toques en otras apps ni necesitar el permiso `INJECT_EVENTS`: + +```sh +cd apps/mobile +flutter drive --driver=test_driver/mapa_3d.dart --target=integration_test/mapa_3d_test.dart -d +``` + +Verifica el GLB local, los pines, zoom, giro, la apertura de una ficha y el +regreso al plano. Captura también texto al 200 %. Las imágenes quedan en +`.impeccable/review/`. Las preferencias de esa prueba viven en memoria; se +conservan los datos guardados por la persona. Después de ejecutarla se debe +reinstalar el APK normal: el comando instala una app de comprobación. diff --git a/packages/tour_virtual/assets/mapa3d/origen.json b/packages/tour_virtual/assets/mapa3d/origen.json new file mode 100644 index 0000000..805448b --- /dev/null +++ b/packages/tour_virtual/assets/mapa3d/origen.json @@ -0,0 +1,9 @@ +{ + "repositorio": "https://github.com/ISCOUTB/AS_202620_ElMapita", + "autores": ["Diego Rosales Garza", "Rodrigo Vazquez Rico", "Angel Fabian Gutierrez Gomez"], + "url": "https://smgbmfbgxfjkspvtyvfb.supabase.co/storage/v1/object/public/mapa-campus/utb_campus.glb", + "sha256": "b14fb8a0dcea7b077429167445c407f7ebead7ba5218fc7ff1487c2b88a1a61a", + "version": 1, + "preparacion": "Excluir Plano_Referencia del dibujo; conservar geometría y coordenadas originales.", + "calibracion": "Ajuste provisional de ElMapita contra OSM (~9 m); no sustituye los accesos medidos para la guía AR." +} diff --git a/packages/tour_virtual/assets/mapa3d/visor.js b/packages/tour_virtual/assets/mapa3d/visor.js new file mode 100644 index 0000000..69975d1 --- /dev/null +++ b/packages/tour_virtual/assets/mapa3d/visor.js @@ -0,0 +1,72 @@ +(function () { + 'use strict'; + const mapa = document.querySelector('model-viewer'); + let norte = 137.382; + let inclinada = false; + let quieto = false; + let ultimaCamara = 0; + function avisar(datos) { TourMapa3d.postMessage(JSON.stringify(datos)); } + function encuadrar(x, z, radio, theta, instantaneo) { + mapa.interpolationDecay = quieto || instantaneo ? 0 : 100; + mapa.cameraTarget = `${x}m 0m ${z}m`; + mapa.cameraOrbit = `${theta}rad ${inclinada ? 52 : 0.1}deg ${Math.max(70, Math.min(2600, radio))}m`; + if (quieto || instantaneo) mapa.jumpCameraToGoal(); + } + window.tour3d = { + configurar(config) { + norte = config.norte; + quieto = config.quieto; + mapa.setAttribute('alt', config.descripcion); + mapa.style.setProperty('--color-pin', config.color); + mapa.style.setProperty('--texto-pin', config.texto); + mapa.style.setProperty('--visitado', config.visitado); + mapa.style.setProperty('--tam-texto', `${14 * config.escalaTexto}px`); + mapa.querySelectorAll('[data-tour-poi]').forEach(p => p.remove()); + config.pois.forEach(p => { + const boton = document.createElement('button'); + boton.slot = `hotspot-${p.id}`; + boton.className = 'poi' + (p.numero ? ' parada' : ' lugar') + (p.visitado ? ' visitado' : ''); + boton.setAttribute('data-position', `${p.x}m 22m ${p.z}m`); + boton.setAttribute('data-normal', '0m 1m 0m'); + boton.setAttribute('aria-label', p.etiqueta); + boton.title = p.nombre; + boton.dataset.tourPoi = p.id; + boton.textContent = p.numero ? String(p.numero) : ''; + boton.addEventListener('click', e => { e.stopPropagation(); avisar({tipo: 'poi', id: p.id}); }); + mapa.appendChild(boton); + }); + window.tour3d.visibilidad(); + }, + vista(activa, x, z, radio, sinMovimiento, instantaneo) { + inclinada = activa; + quieto = sinMovimiento; + encuadrar(x, z, radio, norte * Math.PI / 180, instantaneo); + }, + centrar(x, z) { + const o = mapa.getCameraOrbit(); + encuadrar(x, z, Math.min(o.radius, 430), o.theta, false); + }, + zoom(factor) { + const o = mapa.getCameraOrbit(), c = mapa.getCameraTarget(); + encuadrar(c.x, c.z, o.radius / factor, o.theta, false); + }, + girar(grados) { + const o = mapa.getCameraOrbit(), c = mapa.getCameraTarget(); + encuadrar(c.x, c.z, o.radius, o.theta + grados * Math.PI / 180, false); + }, + todo() { encuadrar(138, -154, 1100, norte * Math.PI / 180, false); }, + visibilidad() { + const cerca = mapa.getCameraOrbit().radius < 620; + mapa.querySelectorAll('.lugar').forEach(p => { p.hidden = !cerca; }); + } + }; + mapa.addEventListener('load', () => requestAnimationFrame(() => requestAnimationFrame(() => avisar({tipo: 'listo'}))), {once: true}); + mapa.addEventListener('error', () => avisar({tipo: 'error'})); + mapa.addEventListener('camera-change', () => { + window.tour3d.visibilidad(); + if (performance.now() - ultimaCamara < 160) return; + ultimaCamara = performance.now(); + const o = mapa.getCameraOrbit(), c = mapa.getCameraTarget(); + avisar({tipo: 'camara', x: c.x, z: c.z, radio: o.radius}); + }); +})(); diff --git a/packages/tour_virtual/lib/datos/georreferencia_3d.dart b/packages/tour_virtual/lib/datos/georreferencia_3d.dart new file mode 100644 index 0000000..4b44790 --- /dev/null +++ b/packages/tour_virtual/lib/datos/georreferencia_3d.dart @@ -0,0 +1,35 @@ +import 'dart:math' as math; + +import '../navegacion/geo.dart'; + +/// Ajuste de similitud de ElMapita entre OSM y la maqueta de Ternera. +/// Fuente y autores: assets/mapa3d/origen.json. Precisión provisional ~9 m; +/// solo se usa para dibujar, nunca para calcular llegadas ni rutas AR. +abstract final class Georreferencia3d { + static const origenLat = 10.3687; + static const origenLng = -75.4645; + static const ar = 0.7037688010352227; + static const ai = 0.6475444290808399; + static const tx = 87.46136076530392; + static const tz = -304.17586844832044; + static const metrosLat = 110574.0; + static final metrosLng = 111320 * math.cos(origenLat * math.pi / 180); + static final escala = math.sqrt(ar * ar + ai * ai); + + /// La cámara mira al norte en la vista cenital, igual que el plano OSM. + static final norteCamara = math.atan2(ai, -ar) * 180 / math.pi; + + static ({double x, double z}) aModelo(double lat, double lng) { + final u = -(lng - origenLng) * metrosLng; + final v = (lat - origenLat) * metrosLat; + return (x: ar * u - ai * v + tx, z: ai * u + ar * v + tz); + } + + static PuntoGeo aGeografico(double x, double z) { + final dx = x - tx, dz = z - tz; + const norma = ar * ar + ai * ai; + final u = (ar * dx + ai * dz) / norma; + final v = (-ai * dx + ar * dz) / norma; + return PuntoGeo(origenLat + v / metrosLat, origenLng - u / metrosLng); + } +} diff --git a/packages/tour_virtual/lib/l10n/textos.dart b/packages/tour_virtual/lib/l10n/textos.dart index d68162d..2fffc1e 100644 --- a/packages/tour_virtual/lib/l10n/textos.dart +++ b/packages/tour_virtual/lib/l10n/textos.dart @@ -1205,6 +1205,42 @@ abstract class Textos { /// In es, this message translates to: /// **'Plano con la ruta hasta {lugar}'** String navPlanoSemantica(String lugar); + + /// No description provided for @verMapa3d. + /// + /// In es, this message translates to: + /// **'Ver mapa en 3D'** + String get verMapa3d; + + /// No description provided for @verMapa2d. + /// + /// In es, this message translates to: + /// **'Volver al mapa 2D'** + String get verMapa2d; + + /// No description provided for @mapa3dDescripcion. + /// + /// In es, this message translates to: + /// **'Maqueta 3D del campus. Toca una parada para ver su ficha.'** + String get mapa3dDescripcion; + + /// No description provided for @mapa3dNoDisponible. + /// + /// In es, this message translates to: + /// **'No se pudo abrir el mapa 3D. Puedes seguir en el plano o intentarlo de nuevo.'** + String get mapa3dNoDisponible; + + /// No description provided for @creditoModelo3d. + /// + /// In es, this message translates to: + /// **'Modelo 3D: ElMapita UTB'** + String get creditoModelo3d; + + /// No description provided for @mapa3dCargando. + /// + /// In es, this message translates to: + /// **'Cargando el mapa 3D'** + String get mapa3dCargando; } class _TextosDelegate extends LocalizationsDelegate { diff --git a/packages/tour_virtual/lib/l10n/textos_de.arb b/packages/tour_virtual/lib/l10n/textos_de.arb index ac72945..6430031 100644 --- a/packages/tour_virtual/lib/l10n/textos_de.arb +++ b/packages/tour_virtual/lib/l10n/textos_de.arb @@ -181,5 +181,11 @@ "navCalibrar": "Der Kompass ist ungenau: Bewege das Handy in einer Acht.", "navSinRuta": "Ich habe keinen Weg zu {lugar} gefunden.", "navAproximada": "Der Eingang dieses Ortes ist noch ungefähr.", - "navPlanoSemantica": "Karte mit der Route zu {lugar}" + "navPlanoSemantica": "Karte mit der Route zu {lugar}", + "verMapa3d": "3D-Karte anzeigen", + "verMapa2d": "Zur 2D-Karte zurückkehren", + "mapa3dDescripcion": "3D-Modell des Campus. Tippen Sie auf eine Station, um Details zu sehen.", + "mapa3dNoDisponible": "Die 3D-Karte konnte nicht geöffnet werden. Nutzen Sie die 2D-Karte oder versuchen Sie es erneut.", + "creditoModelo3d": "3D-Modell: ElMapita UTB", + "mapa3dCargando": "3D-Karte wird geladen" } diff --git a/packages/tour_virtual/lib/l10n/textos_de.dart b/packages/tour_virtual/lib/l10n/textos_de.dart index 6731737..bc93e16 100644 --- a/packages/tour_virtual/lib/l10n/textos_de.dart +++ b/packages/tour_virtual/lib/l10n/textos_de.dart @@ -681,4 +681,24 @@ class TextosDe extends Textos { String navPlanoSemantica(String lugar) { return 'Karte mit der Route zu $lugar'; } + + @override + String get verMapa3d => '3D-Karte anzeigen'; + + @override + String get verMapa2d => 'Zur 2D-Karte zurückkehren'; + + @override + String get mapa3dDescripcion => + '3D-Modell des Campus. Tippen Sie auf eine Station, um Details zu sehen.'; + + @override + String get mapa3dNoDisponible => + 'Die 3D-Karte konnte nicht geöffnet werden. Nutzen Sie die 2D-Karte oder versuchen Sie es erneut.'; + + @override + String get creditoModelo3d => '3D-Modell: ElMapita UTB'; + + @override + String get mapa3dCargando => '3D-Karte wird geladen'; } diff --git a/packages/tour_virtual/lib/l10n/textos_en.arb b/packages/tour_virtual/lib/l10n/textos_en.arb index 3b5812f..e0d99e6 100644 --- a/packages/tour_virtual/lib/l10n/textos_en.arb +++ b/packages/tour_virtual/lib/l10n/textos_en.arb @@ -181,5 +181,11 @@ "navCalibrar": "The compass is inaccurate: move your phone in a figure eight.", "navSinRuta": "I couldn’t find a way to {lugar}.", "navAproximada": "This place’s entrance is still approximate.", - "navPlanoSemantica": "Map with the route to {lugar}" + "navPlanoSemantica": "Map with the route to {lugar}", + "verMapa3d": "View 3D map", + "verMapa2d": "Return to 2D map", + "mapa3dDescripcion": "3D campus model. Tap a stop to view its details.", + "mapa3dNoDisponible": "The 3D map could not open. You can use the 2D map or try again.", + "creditoModelo3d": "3D model: ElMapita UTB", + "mapa3dCargando": "Loading the 3D map" } diff --git a/packages/tour_virtual/lib/l10n/textos_en.dart b/packages/tour_virtual/lib/l10n/textos_en.dart index 20ca0d8..de5779d 100644 --- a/packages/tour_virtual/lib/l10n/textos_en.dart +++ b/packages/tour_virtual/lib/l10n/textos_en.dart @@ -669,4 +669,24 @@ class TextosEn extends Textos { String navPlanoSemantica(String lugar) { return 'Map with the route to $lugar'; } + + @override + String get verMapa3d => 'View 3D map'; + + @override + String get verMapa2d => 'Return to 2D map'; + + @override + String get mapa3dDescripcion => + '3D campus model. Tap a stop to view its details.'; + + @override + String get mapa3dNoDisponible => + 'The 3D map could not open. You can use the 2D map or try again.'; + + @override + String get creditoModelo3d => '3D model: ElMapita UTB'; + + @override + String get mapa3dCargando => 'Loading the 3D map'; } diff --git a/packages/tour_virtual/lib/l10n/textos_es.arb b/packages/tour_virtual/lib/l10n/textos_es.arb index ceb01b9..2b6acb9 100644 --- a/packages/tour_virtual/lib/l10n/textos_es.arb +++ b/packages/tour_virtual/lib/l10n/textos_es.arb @@ -278,5 +278,11 @@ "navAproximada": "La entrada de este lugar aún es aproximada.", "@navAproximada": {"description": "La entrada no se ha medido en el campus todavía."}, "navPlanoSemantica": "Plano con la ruta hasta {lugar}", - "@navPlanoSemantica": {"description": "Etiqueta para el lector de pantalla del plano con la ruta.", "placeholders": {"lugar": {"type": "String"}}} + "@navPlanoSemantica": {"description": "Etiqueta para el lector de pantalla del plano con la ruta.", "placeholders": {"lugar": {"type": "String"}}}, + "verMapa3d": "Ver mapa en 3D", + "verMapa2d": "Volver al mapa 2D", + "mapa3dDescripcion": "Maqueta 3D del campus. Toca una parada para ver su ficha.", + "mapa3dNoDisponible": "No se pudo abrir el mapa 3D. Puedes seguir en el plano o intentarlo de nuevo.", + "creditoModelo3d": "Modelo 3D: ElMapita UTB", + "mapa3dCargando": "Cargando el mapa 3D" } diff --git a/packages/tour_virtual/lib/l10n/textos_es.dart b/packages/tour_virtual/lib/l10n/textos_es.dart index 96ec0e6..d86679b 100644 --- a/packages/tour_virtual/lib/l10n/textos_es.dart +++ b/packages/tour_virtual/lib/l10n/textos_es.dart @@ -676,4 +676,24 @@ class TextosEs extends Textos { String navPlanoSemantica(String lugar) { return 'Plano con la ruta hasta $lugar'; } + + @override + String get verMapa3d => 'Ver mapa en 3D'; + + @override + String get verMapa2d => 'Volver al mapa 2D'; + + @override + String get mapa3dDescripcion => + 'Maqueta 3D del campus. Toca una parada para ver su ficha.'; + + @override + String get mapa3dNoDisponible => + 'No se pudo abrir el mapa 3D. Puedes seguir en el plano o intentarlo de nuevo.'; + + @override + String get creditoModelo3d => 'Modelo 3D: ElMapita UTB'; + + @override + String get mapa3dCargando => 'Cargando el mapa 3D'; } diff --git a/packages/tour_virtual/lib/l10n/textos_fr.arb b/packages/tour_virtual/lib/l10n/textos_fr.arb index 9c96540..b2e0587 100644 --- a/packages/tour_virtual/lib/l10n/textos_fr.arb +++ b/packages/tour_virtual/lib/l10n/textos_fr.arb @@ -181,5 +181,11 @@ "navCalibrar": "La boussole est imprécise : bougez le téléphone en dessinant un huit.", "navSinRuta": "Je n’ai pas trouvé de chemin vers {lugar}.", "navAproximada": "L’entrée de ce lieu est encore approximative.", - "navPlanoSemantica": "Plan avec l’itinéraire vers {lugar}" + "navPlanoSemantica": "Plan avec l’itinéraire vers {lugar}", + "verMapa3d": "Voir la carte en 3D", + "verMapa2d": "Revenir à la carte 2D", + "mapa3dDescripcion": "Maquette 3D du campus. Touchez une étape pour voir sa fiche.", + "mapa3dNoDisponible": "Impossible d’ouvrir la carte 3D. Vous pouvez utiliser la carte 2D ou réessayer.", + "creditoModelo3d": "Modèle 3D : ElMapita UTB", + "mapa3dCargando": "Chargement de la carte 3D" } diff --git a/packages/tour_virtual/lib/l10n/textos_fr.dart b/packages/tour_virtual/lib/l10n/textos_fr.dart index 1f3c1cd..b65e6e1 100644 --- a/packages/tour_virtual/lib/l10n/textos_fr.dart +++ b/packages/tour_virtual/lib/l10n/textos_fr.dart @@ -682,4 +682,24 @@ class TextosFr extends Textos { String navPlanoSemantica(String lugar) { return 'Plan avec l’itinéraire vers $lugar'; } + + @override + String get verMapa3d => 'Voir la carte en 3D'; + + @override + String get verMapa2d => 'Revenir à la carte 2D'; + + @override + String get mapa3dDescripcion => + 'Maquette 3D du campus. Touchez une étape pour voir sa fiche.'; + + @override + String get mapa3dNoDisponible => + 'Impossible d’ouvrir la carte 3D. Vous pouvez utiliser la carte 2D ou réessayer.'; + + @override + String get creditoModelo3d => 'Modèle 3D : ElMapita UTB'; + + @override + String get mapa3dCargando => 'Chargement de la carte 3D'; } diff --git a/packages/tour_virtual/lib/l10n/textos_it.arb b/packages/tour_virtual/lib/l10n/textos_it.arb index 45918f4..6155721 100644 --- a/packages/tour_virtual/lib/l10n/textos_it.arb +++ b/packages/tour_virtual/lib/l10n/textos_it.arb @@ -181,5 +181,11 @@ "navCalibrar": "La bussola è imprecisa: muovi il telefono disegnando un otto.", "navSinRuta": "Non ho trovato un percorso fino a {lugar}.", "navAproximada": "L’ingresso di questo luogo è ancora approssimativo.", - "navPlanoSemantica": "Mappa con il percorso fino a {lugar}" + "navPlanoSemantica": "Mappa con il percorso fino a {lugar}", + "verMapa3d": "Visualizza mappa 3D", + "verMapa2d": "Torna alla mappa 2D", + "mapa3dDescripcion": "Modello 3D del campus. Tocca una tappa per vedere i dettagli.", + "mapa3dNoDisponible": "Impossibile aprire la mappa 3D. Puoi usare la mappa 2D o riprovare.", + "creditoModelo3d": "Modello 3D: ElMapita UTB", + "mapa3dCargando": "Caricamento della mappa 3D" } diff --git a/packages/tour_virtual/lib/l10n/textos_it.dart b/packages/tour_virtual/lib/l10n/textos_it.dart index 0b5a56e..993ac3f 100644 --- a/packages/tour_virtual/lib/l10n/textos_it.dart +++ b/packages/tour_virtual/lib/l10n/textos_it.dart @@ -679,4 +679,24 @@ class TextosIt extends Textos { String navPlanoSemantica(String lugar) { return 'Mappa con il percorso fino a $lugar'; } + + @override + String get verMapa3d => 'Visualizza mappa 3D'; + + @override + String get verMapa2d => 'Torna alla mappa 2D'; + + @override + String get mapa3dDescripcion => + 'Modello 3D del campus. Tocca una tappa per vedere i dettagli.'; + + @override + String get mapa3dNoDisponible => + 'Impossibile aprire la mappa 3D. Puoi usare la mappa 2D o riprovare.'; + + @override + String get creditoModelo3d => 'Modello 3D: ElMapita UTB'; + + @override + String get mapa3dCargando => 'Caricamento della mappa 3D'; } diff --git a/packages/tour_virtual/lib/l10n/textos_ja.arb b/packages/tour_virtual/lib/l10n/textos_ja.arb index 7edb1f3..247923f 100644 --- a/packages/tour_virtual/lib/l10n/textos_ja.arb +++ b/packages/tour_virtual/lib/l10n/textos_ja.arb @@ -181,5 +181,11 @@ "navCalibrar": "コンパスが不正確です。スマートフォンを 8 の字に動かしてください。", "navSinRuta": "{lugar}までの道が見つかりませんでした。", "navAproximada": "この場所の入口はまだおおよその位置です。", - "navPlanoSemantica": "{lugar}までのルートを示した地図" + "navPlanoSemantica": "{lugar}までのルートを示した地図", + "verMapa3d": "3Dマップを表示", + "verMapa2d": "2Dマップに戻る", + "mapa3dDescripcion": "キャンパスの3D模型です。立ち寄り地点をタップすると詳細を表示します。", + "mapa3dNoDisponible": "3Dマップを開けませんでした。2Dマップを使用するか、もう一度お試しください。", + "creditoModelo3d": "3Dモデル:ElMapita UTB", + "mapa3dCargando": "3Dマップを読み込み中" } diff --git a/packages/tour_virtual/lib/l10n/textos_ja.dart b/packages/tour_virtual/lib/l10n/textos_ja.dart index 97ffe6f..54ad8cd 100644 --- a/packages/tour_virtual/lib/l10n/textos_ja.dart +++ b/packages/tour_virtual/lib/l10n/textos_ja.dart @@ -651,4 +651,22 @@ class TextosJa extends Textos { String navPlanoSemantica(String lugar) { return '$lugarまでのルートを示した地図'; } + + @override + String get verMapa3d => '3Dマップを表示'; + + @override + String get verMapa2d => '2Dマップに戻る'; + + @override + String get mapa3dDescripcion => 'キャンパスの3D模型です。立ち寄り地点をタップすると詳細を表示します。'; + + @override + String get mapa3dNoDisponible => '3Dマップを開けませんでした。2Dマップを使用するか、もう一度お試しください。'; + + @override + String get creditoModelo3d => '3Dモデル:ElMapita UTB'; + + @override + String get mapa3dCargando => '3Dマップを読み込み中'; } diff --git a/packages/tour_virtual/lib/l10n/textos_ko.arb b/packages/tour_virtual/lib/l10n/textos_ko.arb index e0ed8be..3606c24 100644 --- a/packages/tour_virtual/lib/l10n/textos_ko.arb +++ b/packages/tour_virtual/lib/l10n/textos_ko.arb @@ -181,5 +181,11 @@ "navCalibrar": "나침반이 부정확해요. 휴대폰을 8자 모양으로 움직여 주세요.", "navSinRuta": "{lugar}까지 가는 길을 찾지 못했어요.", "navAproximada": "이 장소의 입구 위치는 아직 대략적이에요.", - "navPlanoSemantica": "{lugar}까지의 경로가 표시된 지도" + "navPlanoSemantica": "{lugar}까지의 경로가 표시된 지도", + "verMapa3d": "3D 지도 보기", + "verMapa2d": "2D 지도로 돌아가기", + "mapa3dDescripcion": "캠퍼스 3D 모형입니다. 방문 지점을 누르면 상세 정보를 볼 수 있습니다.", + "mapa3dNoDisponible": "3D 지도를 열 수 없습니다. 2D 지도를 사용하거나 다시 시도하세요.", + "creditoModelo3d": "3D 모델: ElMapita UTB", + "mapa3dCargando": "3D 지도 불러오는 중" } diff --git a/packages/tour_virtual/lib/l10n/textos_ko.dart b/packages/tour_virtual/lib/l10n/textos_ko.dart index 5dd1ef9..386deb5 100644 --- a/packages/tour_virtual/lib/l10n/textos_ko.dart +++ b/packages/tour_virtual/lib/l10n/textos_ko.dart @@ -653,4 +653,22 @@ class TextosKo extends Textos { String navPlanoSemantica(String lugar) { return '$lugar까지의 경로가 표시된 지도'; } + + @override + String get verMapa3d => '3D 지도 보기'; + + @override + String get verMapa2d => '2D 지도로 돌아가기'; + + @override + String get mapa3dDescripcion => '캠퍼스 3D 모형입니다. 방문 지점을 누르면 상세 정보를 볼 수 있습니다.'; + + @override + String get mapa3dNoDisponible => '3D 지도를 열 수 없습니다. 2D 지도를 사용하거나 다시 시도하세요.'; + + @override + String get creditoModelo3d => '3D 모델: ElMapita UTB'; + + @override + String get mapa3dCargando => '3D 지도 불러오는 중'; } diff --git a/packages/tour_virtual/lib/l10n/textos_pt.arb b/packages/tour_virtual/lib/l10n/textos_pt.arb index 0de54cd..383efea 100644 --- a/packages/tour_virtual/lib/l10n/textos_pt.arb +++ b/packages/tour_virtual/lib/l10n/textos_pt.arb @@ -181,5 +181,11 @@ "navCalibrar": "A bússola está imprecisa: mova o celular desenhando um oito.", "navSinRuta": "Não encontrei um caminho até {lugar}.", "navAproximada": "A entrada deste lugar ainda é aproximada.", - "navPlanoSemantica": "Mapa com a rota até {lugar}" + "navPlanoSemantica": "Mapa com a rota até {lugar}", + "verMapa3d": "Ver mapa em 3D", + "verMapa2d": "Voltar ao mapa 2D", + "mapa3dDescripcion": "Maquete 3D do campus. Toque em uma parada para ver os detalhes.", + "mapa3dNoDisponible": "Não foi possível abrir o mapa 3D. Você pode usar o mapa 2D ou tentar novamente.", + "creditoModelo3d": "Modelo 3D: ElMapita UTB", + "mapa3dCargando": "Carregando o mapa 3D" } diff --git a/packages/tour_virtual/lib/l10n/textos_pt.dart b/packages/tour_virtual/lib/l10n/textos_pt.dart index 3c7ec28..1160553 100644 --- a/packages/tour_virtual/lib/l10n/textos_pt.dart +++ b/packages/tour_virtual/lib/l10n/textos_pt.dart @@ -675,6 +675,26 @@ class TextosPt extends Textos { String navPlanoSemantica(String lugar) { return 'Mapa com a rota até $lugar'; } + + @override + String get verMapa3d => 'Ver mapa em 3D'; + + @override + String get verMapa2d => 'Voltar ao mapa 2D'; + + @override + String get mapa3dDescripcion => + 'Maquete 3D do campus. Toque em uma parada para ver os detalhes.'; + + @override + String get mapa3dNoDisponible => + 'Não foi possível abrir o mapa 3D. Você pode usar o mapa 2D ou tentar novamente.'; + + @override + String get creditoModelo3d => 'Modelo 3D: ElMapita UTB'; + + @override + String get mapa3dCargando => 'Carregando o mapa 3D'; } /// The translations for Portuguese, as used in Portugal (`pt_PT`). diff --git a/packages/tour_virtual/lib/l10n/textos_tr.arb b/packages/tour_virtual/lib/l10n/textos_tr.arb index 49a3cab..6b6b142 100644 --- a/packages/tour_virtual/lib/l10n/textos_tr.arb +++ b/packages/tour_virtual/lib/l10n/textos_tr.arb @@ -181,5 +181,11 @@ "navCalibrar": "Pusula hassas değil: telefonu sekiz çizerek hareket ettirin.", "navSinRuta": "{lugar} için bir yol bulamadım.", "navAproximada": "Bu yerin girişi henüz yaklaşık.", - "navPlanoSemantica": "{lugar} rotasını gösteren harita" + "navPlanoSemantica": "{lugar} rotasını gösteren harita", + "verMapa3d": "3B haritayı göster", + "verMapa2d": "2B haritaya dön", + "mapa3dDescripcion": "Kampüsün 3B modeli. Ayrıntılar için bir durağa dokunun.", + "mapa3dNoDisponible": "3B harita açılamadı. 2B haritayı kullanabilir veya tekrar deneyebilirsiniz.", + "creditoModelo3d": "3B model: ElMapita UTB", + "mapa3dCargando": "3B harita yükleniyor" } diff --git a/packages/tour_virtual/lib/l10n/textos_tr.dart b/packages/tour_virtual/lib/l10n/textos_tr.dart index 34c85f6..8c1b251 100644 --- a/packages/tour_virtual/lib/l10n/textos_tr.dart +++ b/packages/tour_virtual/lib/l10n/textos_tr.dart @@ -672,4 +672,24 @@ class TextosTr extends Textos { String navPlanoSemantica(String lugar) { return '$lugar rotasını gösteren harita'; } + + @override + String get verMapa3d => '3B haritayı göster'; + + @override + String get verMapa2d => '2B haritaya dön'; + + @override + String get mapa3dDescripcion => + 'Kampüsün 3B modeli. Ayrıntılar için bir durağa dokunun.'; + + @override + String get mapa3dNoDisponible => + '3B harita açılamadı. 2B haritayı kullanabilir veya tekrar deneyebilirsiniz.'; + + @override + String get creditoModelo3d => '3B model: ElMapita UTB'; + + @override + String get mapa3dCargando => '3B harita yükleniyor'; } diff --git a/packages/tour_virtual/lib/l10n/textos_zh.arb b/packages/tour_virtual/lib/l10n/textos_zh.arb index 9d07cd4..1c999f3 100644 --- a/packages/tour_virtual/lib/l10n/textos_zh.arb +++ b/packages/tour_virtual/lib/l10n/textos_zh.arb @@ -181,5 +181,11 @@ "navCalibrar": "指南针不准:请将手机按 8 字形移动。", "navSinRuta": "没有找到前往{lugar}的路线。", "navAproximada": "此地点的入口位置仍是大概位置。", - "navPlanoSemantica": "显示前往{lugar}路线的地图" + "navPlanoSemantica": "显示前往{lugar}路线的地图", + "verMapa3d": "查看3D地图", + "verMapa2d": "返回2D地图", + "mapa3dDescripcion": "校园3D模型。点按站点可查看详情。", + "mapa3dNoDisponible": "无法打开3D地图。您可以使用2D地图或重试。", + "creditoModelo3d": "3D模型:ElMapita UTB", + "mapa3dCargando": "正在加载3D地图" } diff --git a/packages/tour_virtual/lib/l10n/textos_zh.dart b/packages/tour_virtual/lib/l10n/textos_zh.dart index 287d170..49cfa6f 100644 --- a/packages/tour_virtual/lib/l10n/textos_zh.dart +++ b/packages/tour_virtual/lib/l10n/textos_zh.dart @@ -648,4 +648,22 @@ class TextosZh extends Textos { String navPlanoSemantica(String lugar) { return '显示前往$lugar路线的地图'; } + + @override + String get verMapa3d => '查看3D地图'; + + @override + String get verMapa2d => '返回2D地图'; + + @override + String get mapa3dDescripcion => '校园3D模型。点按站点可查看详情。'; + + @override + String get mapa3dNoDisponible => '无法打开3D地图。您可以使用2D地图或重试。'; + + @override + String get creditoModelo3d => '3D模型:ElMapita UTB'; + + @override + String get mapa3dCargando => '正在加载3D地图'; } diff --git a/packages/tour_virtual/lib/ui/inicio/mapa_3d.dart b/packages/tour_virtual/lib/ui/inicio/mapa_3d.dart new file mode 100644 index 0000000..35df726 --- /dev/null +++ b/packages/tour_virtual/lib/ui/inicio/mapa_3d.dart @@ -0,0 +1,263 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:model_viewer_plus/model_viewer_plus.dart'; +import 'package:webview_flutter/webview_flutter.dart'; + +import '../../datos/georreferencia_3d.dart'; +import '../../datos/modelos/modelos.dart'; +import '../../l10n/textos.dart'; +import '../../navegacion/geo.dart'; +import '../../nucleo/movimiento.dart'; +import '../../nucleo/tema.dart'; + +const archivoModelo3d = + 'packages/tour_virtual/assets/mapa3d/campus_elmapita.glb'; + +/// El mapa 2D se mantiene en plataformas sin WebView nativa. +bool get admiteMapa3d => + !kIsWeb && + (defaultTargetPlatform == TargetPlatform.android || + defaultTargetPlatform == TargetPlatform.iOS); + +final recursosMapa3dProvider = FutureProvider.autoDispose((ref) async { + await rootBundle.load(archivoModelo3d); + return rootBundle.loadString('packages/tour_virtual/assets/mapa3d/visor.js'); +}); + +/// Comandos explícitos: ningún dato de contenido se interpola como código. +class ControladorMapa3d { + Future Function(String)? _ejecutar; + + Future _orden(String nombre, List argumentos) async { + await _ejecutar?.call( + 'window.tour3d.$nombre(${argumentos.map(jsonEncode).join(',')});', + ); + } + + Future vista( + bool inclinada, + PuntoGeo foco, + double radio, { + required bool quieto, + bool instantaneo = false, + }) { + final p = Georreferencia3d.aModelo(foco.lat, foco.lng); + return _orden('vista', [inclinada, p.x, p.z, radio, quieto, instantaneo]); + } + + Future centrar(Poi poi) { + if (!poi.tienePosicionEnMapa) return Future.value(); + final p = Georreferencia3d.aModelo(poi.lat!, poi.lng!); + return _orden('centrar', [p.x, p.z]); + } + + void zoom(double factor) => unawaited(_orden('zoom', [factor])); + void girar(double grados) => unawaited(_orden('girar', [grados])); + void verTodo() => unawaited(_orden('todo', [])); +} + +/// Visor local: el modelo y el motor WebGL van dentro del APK. +class MapaCampus3d extends ConsumerStatefulWidget { + const MapaCampus3d({ + super.key, + required this.pois, + required this.visitados, + required this.controlador, + required this.alCargar, + required this.alFallar, + required this.alTocarPoi, + required this.alMoverCamara, + }); + + final List pois; + final Set visitados; + final ControladorMapa3d controlador; + final VoidCallback alCargar; + final VoidCallback alFallar; + final ValueChanged alTocarPoi; + final void Function(PuntoGeo, double) alMoverCamara; + + @override + ConsumerState createState() => _MapaCampus3dState(); +} + +class _MapaCampus3dState extends ConsumerState { + WebViewController? _web; + Timer? _tiempoCarga; + var _listo = false; + var _fallo = false; + String? _ultimaConfiguracion; + + @override + void initState() { + super.initState(); + _tiempoCarga = Timer(const Duration(seconds: 35), _fallar); + } + + @override + void dispose() { + _tiempoCarga?.cancel(); + widget.controlador._ejecutar = null; + super.dispose(); + } + + void _fallar() { + if (!mounted || _fallo) return; + _fallo = true; + _tiempoCarga?.cancel(); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) widget.alFallar(); + }); + } + + Future _ejecutar(String codigo) async { + if (!mounted || !_listo || _fallo) return; + try { + await _web?.runJavaScript(codigo); + } catch (error) { + debugPrint('Mapa 3D: $error'); + _fallar(); + } + } + + Future _recibir(JavaScriptMessage mensaje) async { + if (!mounted || _fallo) return; + try { + final dato = jsonDecode(mensaje.message) as Map; + switch (dato['tipo']) { + case 'listo': + _listo = true; + _tiempoCarga?.cancel(); + widget.controlador._ejecutar = _ejecutar; + await _configurar(); + if (mounted && !_fallo) widget.alCargar(); + case 'error': + _fallar(); + case 'poi': + final poi = widget.pois.where((p) => p.id == dato['id']).firstOrNull; + if (poi != null) widget.alTocarPoi(poi); + case 'camara': + final x = dato['x'], z = dato['z'], radio = dato['radio']; + if (x is num && + z is num && + radio is num && + x.isFinite && + z.isFinite && + radio.isFinite && + radio > 0) { + widget.alMoverCamara( + Georreferencia3d.aGeografico(x.toDouble(), z.toDouble()), + radio.toDouble(), + ); + } + } + } catch (error) { + debugPrint('Mensaje del mapa 3D inválido: $error'); + } + } + + String _configuracion() { + final paradas = widget.pois.where((p) => p.esParada).toList(); + final txt = Textos.of(context); + String etiqueta(Poi poi) { + final nombre = poi.esParada + ? txt.paradaSemantica(paradas.indexOf(poi) + 1, poi.nombre) + : poi.nombre; + return widget.visitados.contains(poi.id) + ? txt.yaVisitado(nombre) + : nombre; + } + + return jsonEncode({ + 'quieto': sinMovimiento(context), + 'norte': Georreferencia3d.norteCamara, + 'descripcion': Textos.of(context).mapa3dDescripcion, + 'escalaTexto': MediaQuery.textScalerOf(context).scale(14) / 14, + 'color': + '#${(ColoresUtb.azul.toARGB32() & 0xffffff).toRadixString(16).padLeft(6, '0')}', + 'texto': '#ffffff', + 'visitado': + '#${(ColoresUtb.verde.toARGB32() & 0xffffff).toRadixString(16).padLeft(6, '0')}', + 'pois': [ + for (final poi in widget.pois) + if (poi.tienePosicionEnMapa && poi.lat!.isFinite && poi.lng!.isFinite) + { + 'id': poi.id, + 'nombre': poi.nombre, + 'etiqueta': etiqueta(poi), + 'x': Georreferencia3d.aModelo(poi.lat!, poi.lng!).x, + 'z': Georreferencia3d.aModelo(poi.lat!, poi.lng!).z, + 'numero': poi.esParada ? paradas.indexOf(poi) + 1 : null, + 'visitado': widget.visitados.contains(poi.id), + }, + ], + }); + } + + Future _configurar() async { + if (!mounted || !_listo) return; + final configuracion = _configuracion(); + if (configuracion == _ultimaConfiguracion) return; + _ultimaConfiguracion = configuracion; + await _ejecutar('window.tour3d.configurar($configuracion);'); + } + + @override + Widget build(BuildContext context) { + final recursos = ref.watch(recursosMapa3dProvider); + if (recursos.hasError) { + _fallar(); + return const SizedBox.shrink(); + } + final js = recursos.valueOrNull; + if (js == null) return const SizedBox.shrink(); + if (_listo) unawaited(_configurar()); + return ModelViewer( + src: archivoModelo3d, + alt: Textos.of(context).mapa3dDescripcion, + backgroundColor: ColoresPlano.tierra, + ar: false, + autoRotate: false, + cameraControls: true, + disableTap: true, + interactionPrompt: InteractionPrompt.none, + cameraOrbit: '${Georreferencia3d.norteCamara}deg 0.1deg 1100m', + minCameraOrbit: 'auto 0.1deg 70m', + maxCameraOrbit: 'auto 80deg 2600m', + cameraTarget: '138m 0m -154m', + fieldOfView: '25deg', + minFieldOfView: '25deg', + maxFieldOfView: '25deg', + shadowIntensity: 0.35, + minHotspotOpacity: 1, + maxHotspotOpacity: 1, + exposure: 1.1, + relatedJs: js, + relatedCss: _estiloPines, + debugLogging: false, + javascriptChannels: { + JavascriptChannel('TourMapa3d', onMessageReceived: _recibir), + }, + onWebViewCreated: (web) => _web = web, + ); + } +} + +const _estiloPines = ''' +model-viewer { --poster-color: transparent; } +.poi { min-width:48px; min-height:48px; padding:8px; border:2px solid white; + border-radius:50%; background:var(--color-pin); color:var(--texto-pin); + font:700 var(--tam-texto)/1 Roboto, sans-serif; cursor:pointer; + box-shadow:0 3px 8px #0007; } +.poi:focus-visible { outline:3px solid #fff; outline-offset:4px; } +.poi.visitado { border-width:4px; background:var(--visitado); } +.poi.lugar { background:transparent; box-shadow:none; border:none; } +.poi.lugar::before { content:''; display:block; width:14px; height:14px; + margin:auto; border-radius:50%; background:var(--color-pin); border:2px solid white; } +.poi[hidden] { display:none; } +'''; diff --git a/packages/tour_virtual/lib/ui/inicio/vista_mapa.dart b/packages/tour_virtual/lib/ui/inicio/vista_mapa.dart index dc76177..b44b5e3 100644 --- a/packages/tour_virtual/lib/ui/inicio/vista_mapa.dart +++ b/packages/tour_virtual/lib/ui/inicio/vista_mapa.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:math'; import 'dart:ui' show lerpDouble; @@ -6,14 +7,17 @@ import 'package:flutter_animate/flutter_animate.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import '../../datos/modelos/modelos.dart'; +import '../../datos/georreferencia_3d.dart'; import '../../datos/plano_campus.dart'; import '../../datos/progreso.dart'; import '../../l10n/textos.dart'; import '../../nucleo/movimiento.dart'; import '../../nucleo/tema.dart'; +import '../../navegacion/geo.dart'; import '../comunes/componentes.dart'; import '../ficha_poi.dart'; import 'pintor_plano.dart'; +import 'mapa_3d.dart'; /// Plano del campus con los lugares de la UTB. /// @@ -69,6 +73,14 @@ class _VistaMapaState extends ConsumerState var _actual = 0; var _paginaProgramada = false; var _entradaIniciada = false; + final _control3d = ControladorMapa3d(); + var _crear3d = false; + var _listo3d = false; + var _desea3d = false; + var _mostrar3d = false; + Timer? _volverAlPlano; + PuntoGeo? _ultimoCentro3d; + var _ultimoRadio3d = 1100.0; List get _paradas => widget.pois.where((p) => p.esParada).toList(); @@ -95,6 +107,7 @@ class _VistaMapaState extends ConsumerState @override void dispose() { + _volverAlPlano?.cancel(); _controlador.dispose(); _camara.dispose(); _entrada.dispose(); @@ -204,6 +217,10 @@ class _VistaMapaState extends ConsumerState } void _verTodo() { + if (_mostrar3d) { + _control3d.verTodo(); + return; + } final encuadre = _encuadre; if (encuadre != null) _volarA(encuadre); } @@ -214,6 +231,10 @@ class _VistaMapaState extends ConsumerState /// puntero o el acceso con interruptores no puede hacer el gesto de dos /// dedos. void _zoom(double factor) { + if (_mostrar3d) { + _control3d.zoom(factor); + return; + } final m = _controlador.value; final s = _escalaDe(m); final x = (_ventana.width / 2 - m.storage[12]) / s; @@ -223,6 +244,7 @@ class _VistaMapaState extends ConsumerState void _seleccionar(int indice, {bool moverCarrusel = true}) { setState(() => _actual = indice); + if (_mostrar3d) unawaited(_control3d.centrar(_paradas[indice])); final punto = _enLienzo(_paradas[indice]); if (punto != null) { final escala = max(_escalaDe(_controlador.value), 2.0); @@ -244,6 +266,110 @@ class _VistaMapaState extends ConsumerState /// sin número de parada. void _abrir(Poi poi) => abrirPoi(context, ref, poi: poi, pois: _paradas); + ({PuntoGeo centro, double radio})? _camaraDelPlano() { + final p = _plano; + if (p == null || _ventana.isEmpty || _lienzo.isEmpty) return null; + final punto = _controlador.toScene(_ventana.center(Offset.zero)); + final centro = PuntoGeo( + p.norte - punto.dy / _lienzo.height * (p.norte - p.sur), + p.oeste + punto.dx / _lienzo.width * (p.este - p.oeste), + ); + final metrosPorPixel = + p.anchoMetros / (_lienzo.width * _escalaDe(_controlador.value)); + final radio = + _ventana.height * + metrosPorPixel * + Georreferencia3d.escala / + (2 * tan(25 * pi / 360)); + return (centro: centro, radio: radio.clamp(70, 2600).toDouble()); + } + + Future _entrar3d() async { + final camara = _camaraDelPlano(); + if (!_desea3d || camara == null) return; + _ultimoCentro3d = camara.centro; + _ultimoRadio3d = camara.radio; + await _control3d.vista( + false, + camara.centro, + camara.radio, + quieto: true, + instantaneo: true, + ); + if (!mounted || !_desea3d) return; + setState(() => _mostrar3d = true); + await _control3d.vista( + true, + camara.centro, + camara.radio, + quieto: sinMovimiento(context), + ); + } + + void _alternarDimension() { + _volverAlPlano?.cancel(); + if (!_desea3d) { + setState(() { + _desea3d = true; + _crear3d = true; + }); + if (_listo3d) unawaited(_entrar3d()); + return; + } + setState(() => _desea3d = false); + final centro = _ultimoCentro3d; + if (_mostrar3d && centro != null) { + unawaited( + _control3d.vista( + false, + centro, + _ultimoRadio3d, + quieto: sinMovimiento(context), + ), + ); + } + _volverAlPlano = Timer( + sinMovimiento(context) ? Duration.zero : Movimiento.largo, + () { + if (!mounted || _desea3d) return; + final plano = _plano; + if (centro != null && plano != null && !_lienzo.isEmpty) { + final n = plano.normalizar(centro.lat, centro.lng); + if (n != null) { + final s = + _ventana.height * + plano.anchoMetros * + Georreferencia3d.escala / + (2 * tan(25 * pi / 360) * _ultimoRadio3d * _lienzo.width); + _controlador.value = _matriz( + n.dx * _lienzo.width, + n.dy * _lienzo.height, + s, + ); + } + } + setState(() => _mostrar3d = false); + }, + ); + } + + void _alFallar3d() { + if (!mounted) return; + final avisar = _desea3d || _mostrar3d; + _volverAlPlano?.cancel(); + setState(() { + _desea3d = false; + _mostrar3d = false; + _crear3d = false; + _listo3d = false; + }); + if (avisar) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text(Textos.of(context).mapa3dNoDisponible)), + ); + } + } + @override Widget build(BuildContext context) { final visitados = ref.watch(progresoProvider); @@ -269,13 +395,101 @@ class _VistaMapaState extends ConsumerState child: Stack( children: [ Positioned.fill( - child: plano.when( - data: (p) => _lienzoInteractivo(p, paradas, visitados), - loading: () => const SizedBox.shrink(), - error: (_, _) => const _MapaAusente(), + key: const ValueKey('plano-campus'), + child: IgnorePointer( + ignoring: _mostrar3d, + child: ExcludeSemantics( + excluding: _mostrar3d, + child: plano.when( + data: (p) => _lienzoInteractivo(p, paradas, visitados), + loading: () => const SizedBox.shrink(), + error: (_, _) => const _MapaAusente(), + ), + ), ), ), + if (_crear3d) + Positioned.fill( + key: const ValueKey('maqueta-campus'), + child: IgnorePointer( + ignoring: !_mostrar3d, + child: ExcludeSemantics( + excluding: !_mostrar3d, + child: AnimatedOpacity( + opacity: _mostrar3d ? 1 : 0, + duration: sinMovimiento(context) + ? Duration.zero + : Movimiento.medio, + curve: Movimiento.salida, + child: MapaCampus3d( + pois: widget.pois, + visitados: visitados, + controlador: _control3d, + alCargar: () { + _listo3d = true; + unawaited(_entrar3d()); + }, + alFallar: _alFallar3d, + alMoverCamara: (centro, radio) { + if (_mostrar3d) { + _ultimoCentro3d = centro; + _ultimoRadio3d = radio; + } + }, + alTocarPoi: (poi) { + final i = _paradas.indexWhere((p) => p.id == poi.id); + if (i >= 0) _seleccionar(i); + _abrir(poi); + }, + ), + ), + ), + ), + ), + if (admiteMapa3d) + Positioned( + key: const ValueKey('dimension-campus'), + left: 12, + top: 60, + child: Tooltip( + message: _desea3d ? txt.verMapa2d : txt.verMapa3d, + child: Semantics( + button: true, + toggled: _desea3d, + label: _desea3d && !_listo3d + ? '${txt.mapa3dCargando}. ${txt.verMapa2d}' + : _desea3d + ? txt.verMapa2d + : txt.verMapa3d, + liveRegion: _desea3d && !_listo3d, + onTap: _alternarDimension, + excludeSemantics: true, + child: FilledButton.tonalIcon( + onPressed: _alternarDimension, + style: FilledButton.styleFrom( + minimumSize: const Size(80, 48), + backgroundColor: ColoresUtb.superficie, + foregroundColor: ColoresUtb.texto, + ), + icon: _desea3d && !_listo3d + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : Icon( + _desea3d + ? Icons.map_outlined + : Icons.view_in_ar_rounded, + size: 20, + ), + label: Text(_desea3d ? '2D' : '3D'), + ), + ), + ), + ), Positioned( + key: const ValueKey('leyenda-campus'), left: 12, right: 12 + MedidasUtb.toque + 8, top: 12, @@ -285,6 +499,7 @@ class _VistaMapaState extends ConsumerState ), ), Positioned( + key: const ValueKey('controles-campus'), right: 12, top: 12, child: Column( @@ -306,21 +521,37 @@ class _VistaMapaState extends ConsumerState etiqueta: txt.alejar, alTocar: () => _zoom(1 / 1.5), ), + if (_mostrar3d) ...[ + const SizedBox(height: 8), + BotonCircular( + icono: Icons.rotate_left_rounded, + etiqueta: txt.girarIzquierda, + alTocar: () => _control3d.girar(-45), + ), + const SizedBox(height: 8), + BotonCircular( + icono: Icons.rotate_right_rounded, + etiqueta: txt.girarDerecha, + alTocar: () => _control3d.girar(45), + ), + ], ], ), ), // ODbL: los datos de OSM se usan con la atribución a la vista. Positioned( + key: const ValueKey('credito-campus'), left: 12, right: 12, bottom: 12 + (paradas.isEmpty ? 0 : altoCarrusel + 8), - child: const Align( + child: Align( alignment: AlignmentDirectional.centerStart, - child: _CreditoOsm(), + child: _CreditoOsm(modelo3d: _mostrar3d), ), ), if (paradas.isNotEmpty) Positioned( + key: const ValueKey('carrusel-campus'), left: 0, right: 0, bottom: 12, @@ -561,7 +792,8 @@ class _MapaAusente extends StatelessWidget { /// «© colaboradores de OpenStreetMap», sobre el plano. class _CreditoOsm extends StatelessWidget { - const _CreditoOsm(); + const _CreditoOsm({this.modelo3d = false}); + final bool modelo3d; @override Widget build(BuildContext context) { @@ -573,7 +805,9 @@ class _CreditoOsm extends StatelessWidget { child: Padding( padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), child: Text( - Textos.of(context).creditoOsm, + modelo3d + ? '${Textos.of(context).creditoOsm}\n${Textos.of(context).creditoModelo3d}' + : Textos.of(context).creditoOsm, style: Theme.of(context).textTheme.labelSmall?.copyWith( // Gris de OSM sobre blanco: 10:1. color: const Color(0xFF333333), diff --git a/packages/tour_virtual/pubspec.yaml b/packages/tour_virtual/pubspec.yaml index 59fd5ee..48fe2bb 100644 --- a/packages/tour_virtual/pubspec.yaml +++ b/packages/tour_virtual/pubspec.yaml @@ -36,6 +36,8 @@ dependencies: dchs_motion_sensors: 2.0.2 # 1.7 conserva compatibilidad con Flutter 3.41 y el GPS del módulo. wakelock_plus: 1.7.0 + model_viewer_plus: 1.10.0 + webview_flutter: 4.13.0 dev_dependencies: flutter_test: @@ -58,6 +60,7 @@ flutter: - assets/max/ # Grafo peatonal y accesos para la navegación (scripts/grafo_campus.py). - assets/navegacion/ + - assets/mapa3d/ # Medios del APK de demostración que funciona sin red # (ContenidoLocal(medios: FuenteMedio.empaquetados)). En el repositorio van # vacías: son panorámicas y narraciones institucionales, y las llena diff --git a/scripts/preparar_modelo3d.py b/scripts/preparar_modelo3d.py new file mode 100644 index 0000000..3cc77e3 --- /dev/null +++ b/scripts/preparar_modelo3d.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Prepara la maqueta de ElMapita como recurso local y sin red para el APK.""" +import hashlib +import json +import struct +import urllib.request +from pathlib import Path + +RAIZ = Path(__file__).resolve().parent.parent +CARPETA = RAIZ / "packages" / "tour_virtual" / "assets" / "mapa3d" + + +def preparar(contenido: bytes) -> bytes: + if contenido[:4] != b"glTF" or struct.unpack_from(" None: + origen = json.loads((CARPETA / "origen.json").read_text(encoding="utf-8")) + with urllib.request.urlopen(origen["url"], timeout=60) as respuesta: + contenido = respuesta.read(20 * 1024 * 1024 + 1) + if hashlib.sha256(contenido).hexdigest() != origen["sha256"]: + raise ValueError("El modelo cambió: revisar su procedencia y calibración antes de actualizar origen.json") + destino = CARPETA / "campus_elmapita.glb" + destino.write_bytes(preparar(contenido)) + print(f"Modelo preparado: {destino} ({destino.stat().st_size / 1e6:.1f} MB)") + + +if __name__ == "__main__": + main() diff --git a/scripts/test_modelo3d.py b/scripts/test_modelo3d.py new file mode 100644 index 0000000..5220d24 --- /dev/null +++ b/scripts/test_modelo3d.py @@ -0,0 +1,28 @@ +"""Verifica la preparación del GLB sin descargar recursos externos.""" +import json +import struct +import unittest + +from preparar_modelo3d import preparar + + +class PrepararModeloTest(unittest.TestCase): + def test_excluye_la_referencia_y_conserva_la_geometria_binaria(self): + modelo = {"asset": {"version": "2.0"}, "scenes": [{"nodes": [0, 1]}], + "nodes": [{"name": "Terreno", "children": [1]}, {"name": "Plano_Referencia"}]} + bloque = json.dumps(modelo).encode() + bloque += b" " * (-len(bloque) % 4) + geometria = struct.pack("