mirror of
https://github.com/jhaizhou-ops/d2r-mobile
synced 2026-11-26 13:57:52 +08:00
v2.0: Android and HarmonyOS ports, Korean, iPhone Duo, Xbox controller layout, separate game packages, Mac icon and pointer
- Android (#113, @yyan160; graphics engine and shader-bundle packer from @biglawine's HarmonyOS port): an Android app (dm/android) with a JNI host, a touch overlay on the shared touch state machine, Vulkan presentation and AAudio sound; an NVN-to-Vulkan replay engine (dm/gfx/vulkan) behind the same backend interface as Metal; the shared host now builds for Apple and Android, and the module rewriter has an Android target (DM_TARGET=android; Apple output unchanged). Measured by the authors at a median 60 fps on a Redmi K50 Ultra. - Android install with your own game files: the release APK (dm/android/tools/shell_apk.sh) contains no game content; dm/tools/d2rm_android.py makes an import pack (rewritten program, Vulkan shader bundles, touch overlay, data tables) that the App imports from Download/S2X/D2R Mobile/android with a progress screen. The shader export step (dm/gfx/tools/dmsh_vk.py) makes the 6,927 game shader bundles byte-for-byte identical to the tested set. - Android rewriter fix (#113, @yyan160): rewrite blocks no longer stash registers below sp (Android has no red zone); equiv.py checks Android outputs, structck.py recognizes the Android block shapes. Apple output unchanged. - Android touch controls drawn as on iOS (sockets, silver skill silhouettes, joystick), no map key in game state, no virtual pad buttons over panels; dm/android/tools/art_compare.sh compares the two drawings pixel by pixel. - HarmonyOS (#114, @biglawine): a HarmonyOS NEXT app (dm/harmony, ArkTS shell + N-API library) on the same shared host and Vulkan engine as Android; shared changes are behind __OHOS__ or opt-in switches (adaptive present tier, fence waits woken on completion, OHAudio, HiTrace markers, a byte-identical BC fast path). - HarmonyOS install with your own game files (@biglawine, 0.19.4 / code122): the release HAP is unsigned and contains no game content; players re-sign it with their own debug certificate and import a pack made with dm/tools/d2rm_android.py --target ohos. The registering stand-ins read the tables only when dm_derived_reload() is called (on __OHOS__); first import creates the target folders; outside a game a map toggle request is dropped before the AutoMap exists. Run by the author on a Mate 90 Pro Max: re-sign, install, import, in game, save and exit. - Vulkan: NaN-ignoring min / max / clamp as on Maxwell (#113, @yyan160), fixing one-frame black tiles on the OnePlus 13. - Xbox controllers (from #110, @rrroy5640): recognized automatically and given the PC / Xbox layout (bottom confirms, right goes back) with the game's Xbox button icons; other controllers are unchanged. The Mac-only keyboard prompt switch became a three-way prompt style (Switch / keyboard / Xbox) on every platform. - Separate base and update packages (#106, @PowerBeef): setup.sh and extract_game.sh take both packages and read the title keys from their tickets. - Mac App (#108, #109, @PowerBeef): the project's icon by default; the pointer hides after resting 3 s. - run.sh install no longer goes through the test-device battery gate (#107, @PowerBeef). - Chinese wording (#101, @zzz6519003): 「旧接口版」 and 「默认构建」 throughout. - Dynamic 3D resolution (from #113): a run of dropped frames counts only its first 3 frames unless it lasts 1 s, so one-off stalls no longer lower the resolution. - In-game Korean (#118, @soulsakura): a 한국어 column for all our UI text, a fifth option in the language row (each checkbox now sits before its name), Korean touch wording and map name plates, Korean voice when the game files carry it; a Korean system language picks Korean on first install. - iPhone Duo: in full screen the output size follows the window when the phone is unfolded or folded, up to the size the game started with; needs Xcode 27.1 for the inner screen to be filled. Test switches DM_TEST_FOLD and DM_TEST_SCREEN simulate the two screens with the iOS package on a Mac. - README: Android and HarmonyOS sections, device table and credits in all three languages; dependency list for Android. Every change was ported into the internal tree with its authors credited. For the shared files, the code changes match the pull requests' after stripping comments. Host / graphics / iOS unit tests, the full acceptance gate and the Mac smoke test passed; the rewriter's rule sets were rebuilt and passed the equivalence regression; an iOS build of this code was played on an iPhone; the Android APK with an import pack made from our own game files was played on a vivo X200 Ultra. Exported from main 8055e5212. Co-authored-by: Yuechuan Yang <22333122+yyan160@users.noreply.github.com> Co-authored-by: biglawine <26263820+biglawine@users.noreply.github.com> Co-authored-by: rrroy <hly5640@gmail.com> Co-authored-by: Patrice Déry <109446870+PowerBeef@users.noreply.github.com> Co-authored-by: Sam Snowman(赵正中) <zhengzhongzhao@gmail.com> Co-authored-by: soulsakura <74704744+soulsakura@users.noreply.github.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
53e7c5bb9c
commit
b811b90172
347 files changed
+30412
-1440
No files matched your search
+22
@@ -3,3 +3,25 @@
|
||||
.iosdd_mac/
|
||||
.iosdd_*/
|
||||
.DS_Store
|
||||
# 安卓构建产物与本机配置 | Android build outputs and local configuration
|
||||
dm/android/local.properties
|
||||
dm/android/.gradle/
|
||||
dm/android/build/
|
||||
dm/android/app/build/
|
||||
dm/android/.kotlin/
|
||||
dm/android/app/.cxx/
|
||||
dm/android/.cxx/
|
||||
# 本地交付、游戏派生文件与签名材料不入库 | Keep local deliverables, game-derived files, and signing material out of Git.
|
||||
*.apk
|
||||
*.aab
|
||||
*.hap
|
||||
*.xgs
|
||||
*.d2s
|
||||
*.d2i
|
||||
*.keystore
|
||||
*.jks
|
||||
*.p12
|
||||
*.pfx
|
||||
/private/
|
||||
/artifacts/
|
||||
dm/android/local.env
|
||||
+96
-12
@@ -1,10 +1,10 @@
|
||||
# D2R Mobile
|
||||
|
||||
**Una capa de compatibilidad de código abierto para iOS / macOS que ejecuta Diablo II: Resurrected con la expansión Reign of the Warlock.** Lleva a iPhone, iPad y Mac, completa, la edición de Nintendo Switch que compraste, expansión incluida: el código original del juego se ejecuta de forma nativa, todos los controles se rehicieron para pantalla táctil, la tasa de fotogramas se mantiene en 60 fps y entras a una partida un segundo después del menú principal. Ahora también hay una versión nativa para macOS (primera versión): en un Mac con Apple silicon se abre con doble clic y funciona con teclado, ratón y mando. Apple TV 4K (3.ª generación, A15) cuenta con un port de la comunidad (versión preliminar para desarrolladores) que, hasta ahora, solo ha llegado a la pantalla de selección de personaje en el dispositivo de su autor; consulta la tabla de dispositivos más abajo.
|
||||
**Una capa de compatibilidad de código abierto para iOS, macOS, Android y HarmonyOS que ejecuta Diablo II: Resurrected con la expansión Reign of the Warlock.** Lleva a iPhone, iPad y Mac, completa, la edición de Nintendo Switch que compraste, expansión incluida: el código original del juego se ejecuta de forma nativa, todos los controles se rehicieron para pantalla táctil, la tasa de fotogramas se mantiene en 60 fps y entras a una partida un segundo después del menú principal. Ahora también hay una versión nativa para macOS (primera versión): en un Mac con Apple silicon se abre con doble clic y funciona con teclado, ratón y mando. **Desde la v2.0 hay una versión para Android** (port de la comunidad): el mismo programa del juego se ejecuta de forma nativa en teléfonos Android ARM64, con los gráficos reimplementados sobre Vulkan; en un teléfono con Snapdragon 8+ Gen 1, el campamento y los combates de la Guarida del Mal y del Nivel de las Vacas van a una mediana de 60 fps (consulta «Android» más abajo); sobre el mismo motor hay una versión para HarmonyOS (port de la comunidad: un shell sin firmar de la página de Releases que firmas tú, sin compilar nada; consulta «HarmonyOS»). Apple TV 4K (3.ª generación, A15) cuenta con un port de la comunidad (versión preliminar para desarrolladores) que, hasta ahora, solo ha llegado a la pantalla de selección de personaje en el dispositivo de su autor; consulta la tabla de dispositivos más abajo.
|
||||
|
||||
Esto no es una demo técnica que «más o menos funciona». Es una versión móvil pulida para jugar a diario, desde tu primer personaje hasta el contenido de fin de juego.
|
||||
|
||||
Plataformas: iPhone / iPad (iOS 26 o posterior; iOS 18 – 25 con la compilación para API antiguas) · Mac (Apple silicon, macOS 26 o posterior; macOS 15 – 25 con la compilación para API antiguas) · Apple TV 4K (3.ª generación, A15; port de la comunidad, versión preliminar para desarrolladores) · Versión del juego: edición de Switch con Reign of the Warlock, 1.0.34.0 (corresponde a la versión de PC 3.3.94012) · Español / English / 中文 / Русский · Licencia: MIT · **Aporta tus propios archivos del juego**
|
||||
Plataformas: iPhone / iPad (iOS 26 o posterior; iOS 18 – 25 con la compilación para API antiguas) · Mac (Apple silicon, macOS 26 o posterior; macOS 15 – 25 con la compilación para API antiguas) · Apple TV 4K (3.ª generación, A15; port de la comunidad, versión preliminar para desarrolladores) · Teléfonos Android (ARM64, Android 12 o posterior, Vulkan 1.1; port de la comunidad) · Teléfonos HarmonyOS (HarmonyOS NEXT; port de la comunidad, shell sin firmar de la página de Releases que firmas tú) · Versión del juego: edición de Switch con Reign of the Warlock, 1.0.34.0 (corresponde a la versión de PC 3.3.94012) · Español / English / 中文 / Русский / 한국어 · Licencia: MIT · **Aporta tus propios archivos del juego**
|
||||
|
||||
English: [README.md](README.md) · 中文: [README.zh-CN.md](README.zh-CN.md)
|
||||
|
||||
@@ -25,8 +25,8 @@ English: [README.md](README.md) · 中文: [README.zh-CN.md](README.zh-CN.md)
|
||||
**Es:**
|
||||
|
||||
- El propio programa aarch64 del juego, **ejecutándose directamente en el dispositivo**, sin CPU emulada. iPhone y Switch usan la misma clase de procesador; solo se reescriben las pocas instrucciones que no pueden ejecutarse sin cambios bajo el kernel de Apple, y todos los demás bytes del programa quedan exactamente como se publicaron. Todas las clases, todas las palabras rúnicas (Runewords), las zonas de terror (Terror Zones), los jefes, las reglas de botín y el desarrollo de las misiones son idénticos al original.
|
||||
- Los servicios de plataforma que el juego espera —llamadas al sistema, sistema de archivos, API gráfica, audio, entrada— los proporciona un pequeño anfitrión (host) escrito para las plataformas de Apple. La API gráfica está reimplementada por completo sobre Metal de Apple, sin ninguna capa de emulación en medio, y los shaders se traducen sin conexión a partir de los originales del juego.
|
||||
- Un port pensado para teléfonos y llevado hasta el final: un esquema de control táctil completo, pantalla de borde a borde en iPhone y pantalla completa real en iPad, compatibilidad con mandos, modo de ahorro de energía, sincronización de partidas guardadas, inglés y chino, y todo un conjunto de modos de fin de juego y mejoras de calidad de vida que el original nunca tuvo.
|
||||
- Los servicios de plataforma que el juego espera —llamadas al sistema, sistema de archivos, API gráfica, audio, entrada— los proporciona un pequeño anfitrión (host) escrito para las plataformas de Apple. La API gráfica está reimplementada por completo —sobre Metal en los dispositivos de Apple y sobre Vulkan en Android—, sin ninguna capa de emulación en medio, y los shaders se traducen sin conexión a partir de los originales del juego.
|
||||
- Un port pensado para teléfonos y llevado hasta el final: un esquema de control táctil completo, pantalla de borde a borde en iPhone y pantalla completa real en iPad, compatibilidad con mandos, modo de ahorro de energía, sincronización de partidas guardadas, cinco idiomas (inglés, chino, español, ruso y coreano), y todo un conjunto de modos de fin de juego y mejoras de calidad de vida que el original nunca tuvo.
|
||||
|
||||
**No es:**
|
||||
|
||||
@@ -93,7 +93,7 @@ Esto no es un mando pegado sobre la pantalla. Cada panel y cada acción se rehic
|
||||
|
||||
### Mando
|
||||
|
||||
Conecta un mando y pulsa cualquier botón: la interfaz cambia a la distribución original para mando, con indicaciones de botones en la parte inferior de cada panel. Toca la pantalla y vuelves al instante a la interfaz táctil. El inventario, el alijo (Stash), el árbol de habilidades, la Chronicle y los ajustes se pueden manejar por completo con el mando, con la misma asignación de botones que en Switch.
|
||||
Conecta un mando y pulsa cualquier botón: la interfaz cambia a la distribución original para mando, con indicaciones de botones en la parte inferior de cada panel. Toca la pantalla y vuelves al instante a la interfaz táctil. El inventario, el alijo (Stash), el árbol de habilidades, la Chronicle y los ajustes se pueden manejar por completo con el mando, con la misma asignación de botones que en Switch. Con un mando de Xbox, la asignación cambia sola a la de la versión de PC / Xbox (abajo confirma, derecha vuelve atrás) y las indicaciones muestran los iconos de botones de Xbox; no hay que activar nada.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_pad_combat.jpg" width="49%" alt="Combate con un mando conectado">
|
||||
@@ -158,9 +158,9 @@ La mayoría de las funciones se pueden activar o desactivar una por una en el ju
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_map.jpg" width="33%" alt="El mapa a pantalla completa">
|
||||
</p>
|
||||
|
||||
### Español, inglés, chino y ruso
|
||||
### Español, inglés, chino, ruso y coreano
|
||||
|
||||
Todo el juego cambia entre español, inglés, chino y ruso en Opciones → Extras; tras reiniciar, la interfaz queda en el idioma que elegiste. La primera vez que lo abres sigue el idioma de tu dispositivo (el español de España usa los textos esES del juego y el de otras regiones, los textos latinoamericanos esMX; el ruso usa los textos ruRU). En español y en ruso, los objetos, las habilidades y los monstruos usan la terminología oficial del juego, y todo lo que añadimos —Grieta superior, Crónica, la página de ajustes, las indicaciones de gestos y los rótulos del mapa— también está traducido (las notas de objetos solo existen en chino y español). El ruso es el texto ruRU del juego, sin variantes regionales. Voces: en español quedan en inglés; en ruso se usan las voces rusas originales si tus archivos del juego las incluyen (un paquete hecho con los datos completos del juego las trae) y, si no, en inglés; en chino, voces en chino.
|
||||
Todo el juego cambia entre español, inglés, chino, ruso y coreano en Opciones → Extras; tras reiniciar, la interfaz queda en el idioma que elegiste. La primera vez que lo abres sigue el idioma de tu dispositivo (el español de España usa los textos esES del juego y el de otras regiones, los textos latinoamericanos esMX; el ruso usa los textos ruRU). En español, ruso y coreano, los objetos, las habilidades y los monstruos usan la terminología oficial del juego, y todo lo que añadimos —Grieta superior, Crónica, la página de ajustes, las indicaciones de gestos y los rótulos del mapa— también está traducido (las notas de objetos solo existen en chino y español). El ruso es el texto ruRU del juego y el coreano su texto koKR, sin variantes regionales. Voces: en español quedan en inglés; en ruso y en coreano se usan las voces rusas o coreanas originales si tus archivos del juego las incluyen (un paquete hecho con los datos completos del juego las trae) y, si no, en inglés; en chino, voces en chino. El coreano lo aportó [@soulsakura](https://github.com/soulsakura) ([#118](https://github.com/jhaizhou-ops/d2r-mobile/pull/118)).
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/es_game.jpg" width="58%" alt="Partida con la interfaz en español">
|
||||
@@ -185,10 +185,36 @@ flowchart LR
|
||||
| Anfitrión (host) | `dm/host` | Carga el programa reescrito y proporciona los servicios de plataforma a los que llama |
|
||||
| Gráficos | `dm/gfx` | Implementa la API gráfica del juego sobre Metal; los shaders se traducen sin conexión a partir de los originales del juego |
|
||||
| App de iOS | `dm/ios` | El contenedor de la app, los controles táctiles y la interfaz |
|
||||
| App de Android | `dm/android` | El contenedor de Android, la capa táctil y la presentación con Vulkan |
|
||||
| App de HarmonyOS | `dm/harmony` | El contenedor de HarmonyOS (ArkTS + N-API), que comparte el anfitrión y el motor Vulkan con Android |
|
||||
| Gráficos con Vulkan | `dm/gfx/vulkan` | La misma API gráfica sobre Vulkan (lo comparten Android y HarmonyOS; el motor viene del port a HarmonyOS) |
|
||||
| Verificación | `dm/verify` | Comprueba que el código reescrito se comporta exactamente igual que el original, además de las barreras de regresión por las que pasa cada cambio |
|
||||
|
||||
**Por qué puedes confiar en él:** la estabilidad no es cuestión de suerte. Las herramientas de pruebas y verificación forman parte del proyecto: pruebas unitarias para el anfitrión y la capa gráfica, una comprobación de equivalencia para cada instrucción reescrita, regresión con recorridos automatizados por script para la interfaz táctil y pruebas de humo en dispositivos reales. Empieza por `make -C dm/host/tests run`, `make -C dm/gfx/tests run` y `dm/verify/regress.sh` (ejecútalos dentro del entorno de Python preparado en el paso 2 más abajo; `regress.sh` además necesita `brew install llvm`). Cómo contribuir se explica en [CONTRIBUTING.md](CONTRIBUTING.md) (en inglés).
|
||||
|
||||
## Android (nuevo en la v2.0)
|
||||
|
||||
Los teléfonos Android usan procesadores ARM64, igual que la Switch, así que, como en los dispositivos de Apple, el propio programa del juego se ejecuta directamente en el teléfono, sin emular la CPU. Esta versión lleva a Android todo el anfitrión —llamadas al sistema, sistema de archivos, audio, entrada, partidas guardadas— sin cambios y sustituye la capa gráfica por Vulkan: el motor de reproducción NVN→Vulkan viene del port a HarmonyOS de [@biglawine](https://github.com/biglawine), y la app de Android, los controles táctiles, la presentación con Vulkan y una ronda completa de optimización, medida paso a paso en un teléfono, son obra de [@yyan160](https://github.com/yyan160) ([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113)). Las versiones de Apple y de Android comparten el mismo código del anfitrión, así que los cambios futuros benefician a ambas.
|
||||
|
||||
Medido por los autores del port en sus teléfonos (ajustes por defecto del producto: escala de renderizado 3D limitada a 0.85 y reducida dinámicamente cuando se pierden fotogramas):
|
||||
|
||||
| Teléfono | Resultado |
|
||||
|---|---|
|
||||
| Redmi K50 Ultra (Snapdragon 8+ Gen 1, Adreno 730, Android 15) | Campamento, combate en la Guarida del Mal, combate en el Nivel de las Vacas: **mediana de 60 fps**, GPU unos 14–15 ms por fotograma |
|
||||
| OnePlus 13 (Adreno 830) | Jugable; cuando aparece cierto efecto de luz en el campamento, a veces parpadean durante un instante pequeños cuadros negros (en investigación) |
|
||||
|
||||
Requisitos mínimos: ARM64, Android 12 (API 31) o posterior y una GPU con Vulkan 1.1.
|
||||
|
||||
**Cómo usarlo hoy**: instala `D2RMobile-android.apk` desde la página de versiones (no contiene ningún contenido del juego). En un ordenador, ejecuta `python3 dm/tools/d2rm_android.py <directorio Update> <directorio de salida>` con tus propios archivos del juego para crear el paquete de importación (una carpeta `android` con el programa del juego reescrito, todos los paquetes de shaders de Vulkan, la capa táctil y algunas tablas de datos) y cópialo junto con los recursos del juego (la carpeta `data`) a `Download/S2X/D2R Mobile/` en el teléfono. La app lo importa con una pantalla de progreso al abrirla. Sin adb y sin compilar el APK tú mismo. Los pasos completos están en [docs/ANDROID.md](docs/ANDROID.md) (en inglés). Los controles táctiles se dibujan igual que en iPhone (bases de botón, siluetas plateadas de habilidades, joystick) y ya no hay botones virtuales de mando sobre los paneles abiertos. Frente a la versión de iOS faltan algunos detalles táctiles: el menú de las casillas de habilidad vacías, la superposición para repartir puntos y la imagen del objeto que sigue al dedo al arrastrar en una tienda.
|
||||
|
||||
El progreso, las mediciones de cada ronda y el trabajo pendiente están en [docs/ANDROID_COLLABORATION.md](docs/ANDROID_COLLABORATION.md) y [docs/android-notes/](docs/android-notes/) (en inglés). La versión para HarmonyOS está en la sección siguiente.
|
||||
|
||||
## HarmonyOS (nuevo en la v2.0)
|
||||
|
||||
La app para HarmonyOS NEXT (`dm/harmony`) es de [@biglawine](https://github.com/biglawine) ([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114)) y usa el mismo anfitrión y el mismo motor Vulkan que Android. Medido por el autor en un Mate 90 Pro Max (Maleoon 955): 59,7 fps manteniendo el joystick en el campamento del Acto I, intervalo de pantalla p50 16,6 / p99 18,1 ms.
|
||||
|
||||
**Cómo usarla**: la misma idea que el shell de iOS. La página de Releases tiene un **paquete de instalación sin firmar que no contiene nada del juego** (`D2RMobile-harmony-shell-unsigned.hap`). HarmonyOS NEXT solo instala apps firmadas con tu propio certificado de desarrollador, así que lo vuelves a firmar con tu certificado de depuración y lo instalas; no tienes que compilar la app. Después, en un ordenador, ejecuta `python3 dm/tools/d2rm_android.py --target ohos <carpeta Update> <carpeta de salida>` sobre tus propios archivos del juego para crear el paquete de ejecución, ponlo junto con los recursos del juego en una carpeta «D2R Mobile» del teléfono, abre la app y elige esa carpeta para importarla. Los pasos completos están en [docs/HARMONYOS.md](docs/HARMONYOS.md) (en inglés). El autor completó toda la cadena (firmar → instalar → primera importación → entrar en partida → guardar y salir) en un Mate 90 Pro Max, con tres arranques en frío seguidos sin problemas; necesitas una cuenta de desarrollador de Huawei (DevEco Studio puede generar el certificado de depuración y registrar el dispositivo por ti).
|
||||
|
||||
## Qué dispositivos son compatibles
|
||||
|
||||
Mínimo: **un chip A14 / M1 o posterior**: la capa gráfica necesita Metal 3, que Apple admite a partir de A14 / M1 (consulta [Metal support on Apple devices](https://support.apple.com/102894) y [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf) de Apple).
|
||||
@@ -196,12 +222,15 @@ Mínimo: **un chip A14 / M1 o posterior**: la capa gráfica necesita Metal 3, qu
|
||||
| Dispositivo | ¿Se puede jugar? | Cómo | Qué tan seguros estamos |
|
||||
|---|---|---|---|
|
||||
| **iPhone / iPad, A17 Pro y posteriores** (iPhone 15 Pro y posteriores, iPhone 16 y posteriores, iPad con chips de la serie M) | Sí | iOS 26 o posterior: el contenedor predeterminado / la compilación predeterminada; iOS 18 – 25: el contenedor para iOS 18 / la [compilación para API antiguas](docs/OLDER_SYSTEMS.md) (en inglés) | Dispositivos principales, jugados a diario |
|
||||
| **iPhone Duo** (plegable) | Sí; la imagen cambia de tamaño al desplegarlo o plegarlo | Los shells de la página de Releases se compilan con Xcode 27.1; si lo compilas tú con Xcode, usa la 27.1 para que la pantalla interior se llene (consulta [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md), en inglés) | Compatible desde la v2.0. Comprobado en un Mac alternando entre los tamaños de la pantalla exterior e interior que da el simulador de iPhone Duo (el simulador no puede ejecutar los gráficos del juego). Lo probaremos en un iPhone Duo real en cuanto tengamos uno; si tienes uno, cuéntanos en un Issue cómo te va |
|
||||
| **iPhone / iPad, A16 y anteriores** (todos los modelos de iPhone 14, iPhone 15 / 15 Plus, serie iPhone 13, etc.) | Sí, con un paso adicional | Crea un Legacy Device Pack (paquete para dispositivos antiguos) a partir de tus propios archivos del juego como se indica en [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md) (en inglés) e inclúyelo al crear el paquete de instalación; la división por sistema es la misma que en la fila anterior | Jugado por jugadores: iPhone 14 Pro Max (A16, 6 GB) a 60 fps; iPhone 13 Pro Max (A15, 6 GB) en el modo de 30 fps |
|
||||
| **Dispositivos con 4 GB de RAM** (como el iPad mini de 6.ª generación o el iPad Air de 4.ª generación) | Funciona, pero la memoria va muy justa (seguimos reduciendo el uso de memoria) | Igual que la fila de A16 y anteriores (con el Legacy Device Pack) | Probado por un jugador: en un iPad mini 6 (A15, 4 GB, iPadOS 27), unos minutos del Acto I funcionaron a 50–58 fps tras la reducción automática de calidad, con avisos constantes de memoria del sistema y a solo unos 560 MB por debajo del límite de memoria del sistema; las escenas cargadas, con muchos monstruos y efectos, pueden ser cerradas por el sistema. En una versión anterior, un iPad Air 4 (A14, 4 GB) fue cerrado por el sistema unos segundos después de abrirse |
|
||||
| **Chips A14 con 6 GB de RAM o más** (como el iPhone 12 Pro / 12 Pro Max) | Aún no hay reportes | Igual que la fila de A16 y anteriores | Si lo has probado, abre un Issue y cuéntanos |
|
||||
| **Chips A13 y anteriores** (como la serie iPhone 11 y el iPad Pro de 2020) | No compatible | — | El chip gráfico no admite Metal 3 (probado por un jugador en un iPad Pro con A12Z; las referencias de Apple están encima de la tabla); la app lo indica al abrirse en lugar de cerrarse inesperadamente |
|
||||
| **Mac, Apple silicon** | Sí (App nativa de macOS) | macOS 26 o posterior: la compilación predeterminada; macOS 15 – 25: la [compilación para API antiguas](docs/OLDER_SYSTEMS.md) (en inglés). Teclado, ratón y mando funcionan; lo que puede hacer cada uno está en [docs/MAC.md](docs/MAC.md) (en inglés) | Un jugador ha jugado con la compilación para API antiguas en macOS 15.7.7 |
|
||||
| **Apple TV 4K (3.ª generación, A15)** | Port de la comunidad ([@yinqingyan](https://github.com/yinqingyan), aportado bajo la licencia MIT con el consentimiento del autor), versión preliminar para desarrolladores | Compílalo como se indica en [dm/tvos/README.md](dm/tvos/README.md) (en inglés) y copia los archivos del juego y el Legacy Device Pack dentro de la app; solo en hardware real, el Simulador no puede ejecutarlo; las partidas guardadas viven en el directorio Caches, que el sistema puede vaciar | Llegó a la pantalla de selección de personaje en hardware real; entrar en la partida, la asignación completa del mando y las partidas guardadas aún no están verificados, y los mantenedores no lo han probado en hardware real |
|
||||
| **Teléfonos HarmonyOS** (HarmonyOS NEXT, API 26) | Se puede jugar (port de la comunidad) | El shell sin firmar de la página de Releases, firmado con tu certificado de depuración, más un paquete de ejecución hecho con tus archivos del juego; consulta [docs/HARMONYOS.md](docs/HARMONYOS.md) (en inglés) | Verificado por el autor en un Mate 90 Pro Max: firmar, instalar, importar, entrar en partida, guardar y salir |
|
||||
| **Teléfonos Android** (ARM64, Android 12 o posterior, Vulkan 1.1) | Se puede jugar (port de la comunidad) | El APK de la página de versiones + un paquete de importación creado con tus propios archivos del juego; consulta [docs/ANDROID.md](docs/ANDROID.md) (en inglés) | Medido por los autores del port: Redmi K50 Ultra, mediana de 60 fps; OnePlus 13 jugable, con pequeños cuadros negros que a veces parpadean un instante; probado en un vivo X200 Ultra |
|
||||
| **Mac con Intel** | No compatible | — | — |
|
||||
|
||||
**Qué significan los diálogos de la App**
|
||||
@@ -213,13 +242,23 @@ Mínimo: **un chip A14 / M1 o posterior**: la capa gráfica necesita Metal 3, qu
|
||||
|
||||
## Primeros pasos
|
||||
|
||||
Ambas rutas empiezan con **los archivos del juego que compraste**: la edición de Switch de Diablo II: Resurrected más la expansión Reign of the Warlock, actualizada a la 1.0.34.0 (la versión que muestra la consola; corresponde a la versión de PC 3.3.94012, y los nombres de directorio y las herramientas de este repositorio usan este último número). Este proyecto está hecho para la versión con esa expansión; usarlo sin la expansión no está soportado ni se ha verificado. Cómo prepararlos se explica en [docs/GAME_FILES.md](docs/GAME_FILES.md) (en inglés).
|
||||
Juegues en el dispositivo que juegues, empiezas con **los archivos del juego que compraste**: la edición de Switch de Diablo II: Resurrected más la expansión Reign of the Warlock, actualizada a la 1.0.34.0 (la versión que muestra la consola; corresponde a la versión de PC 3.3.94012, y los nombres de directorio y las herramientas de este repositorio usan este último número). Este proyecto está hecho para la versión con esa expansión; usarlo sin la expansión no está soportado ni se ha verificado. Cómo prepararlos se explica en [docs/GAME_FILES.md](docs/GAME_FILES.md) (en inglés).
|
||||
|
||||
> Este proyecto proporciona únicamente herramientas y un contenedor de instalación que no contiene ningún contenido del juego. No distribuimos ni respaldamos, y no nos hacemos responsables de, ningún tercero que distribuya recursos del juego, ejecutables del juego o paquetes de instalación que contengan contenido del juego. Usa únicamente archivos del juego que poseas legalmente.
|
||||
|
||||
Este proyecto está implementado y verificado sobre la edición de Switch 1.0.34.0 (que corresponde a la versión de PC 3.3.94012), y por defecto las herramientas solo aceptan esa versión. Usuarios de la comunidad han informado de que adaptaron otras versiones por su cuenta siguiendo la estructura de este repositorio y que las ejecutaron con éxito. Las tablas de reglas están agrupadas por versión del juego (en `dm/tools/patch_nso.py`, indexadas por el build ID del programa principal); te invitamos a contribuir con la versión que hayas adaptado.
|
||||
|
||||
**Primero revisa tu dispositivo**: la tabla «Qué dispositivos son compatibles» de arriba te indica qué compilación usar y si además necesitas un Legacy Device Pack.
|
||||
**Primero revisa tu dispositivo** y busca tu sección en la tabla de abajo; la tabla «Qué dispositivos son compatibles» de arriba te indica qué compilación usar en dispositivos de Apple y si además necesitas un Legacy Device Pack.
|
||||
|
||||
| Tu dispositivo | Cómo | Pasos |
|
||||
|---|---|---|
|
||||
| iPhone / iPad, con un Mac con Apple silicon | Una compilación completa desde el código fuente | «Con un Mac: tres pasos», más abajo |
|
||||
| iPhone / iPad, sin Mac | Descarga un contenedor sin contenido del juego y añade tu contenido en Windows / Linux | «Sin un Mac», más abajo, y [docs/NO_XCODE.md](docs/NO_XCODE.md) (en inglés) |
|
||||
| Mac (Apple silicon) | Compila una App nativa de macOS | «Jugar directamente en un Mac», más abajo, y [docs/MAC.md](docs/MAC.md) (en inglés) |
|
||||
| Teléfono Android | Instala el APK de la página de versiones y copia al teléfono un paquete de importación creado en una computadora | «Android», más abajo, y [docs/ANDROID.md](docs/ANDROID.md) (en inglés) |
|
||||
| Teléfono HarmonyOS | Firma el shell sin firmar de la página de Releases con tu certificado de depuración, crea un paquete de ejecución en un ordenador y cópialo al teléfono | «HarmonyOS», más abajo, y [docs/HARMONYOS.md](docs/HARMONYOS.md) (en inglés) |
|
||||
|
||||
Las dos rutas para iPhone / iPad, comparadas:
|
||||
|
||||
| | Con un Mac | Sin un Mac |
|
||||
|---|---|---|
|
||||
@@ -255,7 +294,7 @@ La cuenta de Apple usada para firmar: una cuenta de desarrollador de pago te da
|
||||
|
||||
La primera vez que abras la app en tu teléfono, te pedirá la «carpeta de recursos del juego» (game resource folder): los 18 archivos de recursos de tus archivos del juego. Dónde ponerlos se explica en la sección "The "game resource folder" that goes on the phone" de [docs/GAME_FILES.md](docs/GAME_FILES.md) (en inglés).
|
||||
|
||||
`./setup.sh check` es una revisión de estado: informa elemento por elemento del estado de esta computadora, las herramientas, los archivos del juego y la configuración de firma, y para todo lo que falte indica dónde conseguirlo y qué comando ejecutar a continuación; no cambia nada. Si lo que tienes es un paquete completo del juego (`.xci` / `.nsp`), `./setup.sh <game package> <prod.keys>` primero extrae los archivos del juego en su lugar y luego continúa (instala hactool antes). Vuelve a ejecutar `./setup.sh` después de cada actualización a un nuevo commit: recompila los binarios parcheados y la biblioteca de shaders para el código fuente actual (los pasos que ya están al día se omiten). También reescribe tres archivos del repositorio que cambian según las huellas de tus herramientas locales (`dm/gfx/tools/dmsh_chain.lock`, `dm/gfx/nvn/dmsh_chain.h`, `dm/gfx/nvn/c1_full.tsv`); es lo esperado, no hagas commit de ellos.
|
||||
`./setup.sh check` es una revisión de estado: informa elemento por elemento del estado de esta computadora, las herramientas, los archivos del juego y la configuración de firma, y para todo lo que falte indica dónde conseguirlo y qué comando ejecutar a continuación; no cambia nada. Si lo que tienes es un paquete completo del juego (`.xci` / `.nsp`), `./setup.sh <game package> <prod.keys>` primero extrae los archivos del juego en su lugar y luego continúa (instala hactool antes); si el juego base y la actualización son paquetes separados, pasa ambos: `./setup.sh <juego base> <actualización> <prod.keys>`. Vuelve a ejecutar `./setup.sh` después de cada actualización a un nuevo commit: recompila los binarios parcheados y la biblioteca de shaders para el código fuente actual (los pasos que ya están al día se omiten). También reescribe tres archivos del repositorio que cambian según las huellas de tus herramientas locales (`dm/gfx/tools/dmsh_chain.lock`, `dm/gfx/nvn/dmsh_chain.h`, `dm/gfx/nvn/c1_full.tsv`); es lo esperado, no hagas commit de ellos.
|
||||
|
||||
### Jugar directamente en un Mac
|
||||
|
||||
@@ -269,6 +308,38 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25: produces D2R Mobile M3.a
|
||||
|
||||
La interfaz es la interfaz para mando del original. Teclado: Espacio confirma, Esc vuelve atrás, Intro, la tecla `=` abre el menú / un personaje nuevo, W A S D mueven, y cada uno de los demás botones del mando tiene una tecla. Ratón: al hacer clic en un monstruo, un PNJ o un objeto, caminas hasta él e interactúas, y se puede hacer clic en las ranuras de habilidad, las casillas de pociones y las indicaciones de teclas de la parte inferior, en los botones y pestañas de los paneles, en las figuras de las clases al crear un personaje y en el minimapa; al hacer clic en un suelo vacío caminas hasta allí y, si mantienes pulsado, sigues caminando; al hacer clic en un monstruo lo atacas, y los objetos funcionan con doble clic y arrastre. Con teclado, las indicaciones en pantalla muestran teclas del teclado. Las partidas guardadas se quedan en este Mac (una App que compilas tú no tiene sincronización por iCloud) y se pueden importar a mano desde un iPhone / iPad. La tabla de teclas, cómo crear un personaje, qué puede hacer el ratón, los pasos de importación y las carencias conocidas están en [docs/MAC.md](docs/MAC.md) (en inglés). El teclado y un mando físico aún no los ha manejado ninguna persona; si lo pruebas, cuéntanos cómo te fue.
|
||||
|
||||
### Android
|
||||
|
||||
Sin Mac, sin adb y sin compilar el APK tú mismo; sirve cualquier computadora con Windows / Linux / Mac (por ahora se ha completado en un Mac). Los pasos completos, las herramientas necesarias y qué hacer si algo falla están en [docs/ANDROID.md](docs/ANDROID.md) (en inglés).
|
||||
|
||||
1. Prepara tus archivos del juego, igual que para los dispositivos de Apple ([docs/GAME_FILES.md](docs/GAME_FILES.md)).
|
||||
2. Crea el paquete de importación en una computadora:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py <directorio Update de tus archivos del juego> <directorio de salida>
|
||||
```
|
||||
|
||||
3. Por USB, copia la carpeta `android` que se creó y la carpeta de recursos del juego `data` a `Download/S2X/D2R Mobile/` en el teléfono.
|
||||
4. Descarga `D2RMobile-android.apk` de la [página de Releases](https://github.com/jhaizhou-ops/d2r-mobile/releases), instálalo, ábrelo y permite el «acceso a todos los archivos»; la app importa el paquete e inicia el juego.
|
||||
|
||||
El código fuente debe ser de la misma versión que el APK; con cada versión nueva cambia el APK y el paquete de importación juntos, y tus partidas se conservan. Para compilar el APK tú mismo desde el código fuente, consulta [dm/android/README.md](dm/android/README.md) (en inglés).
|
||||
|
||||
### HarmonyOS
|
||||
|
||||
No tienes que compilar la app. Necesitas una cuenta de desarrollador de Huawei y DevEco Studio (por su herramienta de firma y `hdc`; también puede generar el certificado de depuración y registrar el teléfono). Los pasos completos, los comandos y qué hacer si algo falla están en [docs/HARMONYOS.md](docs/HARMONYOS.md) (en inglés).
|
||||
|
||||
1. Prepara tus archivos del juego, igual que para los dispositivos de Apple ([docs/GAME_FILES.md](docs/GAME_FILES.md), en inglés).
|
||||
2. Descarga el shell sin firmar `D2RMobile-harmony-shell-unsigned.hap` de la [página de Releases](https://github.com/jhaizhou-ops/d2r-mobile/releases), fírmalo con tu propio certificado de depuración y tu profile (`hap-sign-tool sign-app`) e instálalo en el teléfono con `hdc install -r`.
|
||||
3. Crea el paquete de ejecución en un ordenador:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py --target ohos <carpeta Update de tus archivos del juego> <carpeta de salida>
|
||||
```
|
||||
|
||||
4. En el teléfono, crea una carpeta «D2R Mobile» con los recursos del juego en `data/` y el paquete de ejecución del paso anterior en `dm/`, abre la app, toca Importar y elige esa carpeta.
|
||||
|
||||
El código fuente debe ser de la misma versión que el shell. Para una versión nueva, firma el shell nuevo con la misma firma e instálalo encima del anterior; tus partidas guardadas se conservan. El autor completó estos pasos en un Mate 90 Pro Max.
|
||||
|
||||
### Sin un Mac: el contenedor más la herramienta de empaquetado
|
||||
|
||||
Descarga nuestro paquete «contenedor» precompilado (`D2RMobile-shell-build-input.zip`; `D2RMobile-shell-ios18-build-input.zip` para iOS 18 – 25), que no contiene ningún contenido del juego, desde la [página de Releases](https://github.com/jhaizhou-ops/d2r-mobile/releases) de este repositorio, añade tus propios archivos del juego, crea el paquete de instalación en Windows o Linux y luego fírmalo e instálalo con una herramienta de sideloading. El contenedor es material de entrada para la compilación, no una app para instalar (si lo instalas tal cual, solo muestra un diálogo y no inicia el juego); cuando pases a una nueva versión, vuelve a crear el paquete de instalación con el nuevo contenedor. Solo en esta ruta, como la computadora que crea el paquete no tiene el compilador de shaders de Apple, el **primer arranque** en el teléfono dedica unos 7 minutos a compilar shaders (una sola vez, con barra de progreso); un paquete compilado con Xcode no tiene ese paso. Los pasos, y hasta qué punto se ha verificado cada uno, están en [docs/NO_XCODE.md](docs/NO_XCODE.md) (en inglés).
|
||||
@@ -278,6 +349,7 @@ Descarga nuestro paquete «contenedor» precompilado (`D2RMobile-shell-build-inp
|
||||
| Elemento | Estado |
|
||||
|---|---|
|
||||
| Juego en línea | Fuera del alcance del proyecto; totalmente sin conexión |
|
||||
| Versión para Android | Faltan algunos detalles táctiles de iOS (menú de casillas de habilidad vacías, superposición para repartir puntos, imagen que sigue al dedo en una tienda); consulta «Android» más arriba |
|
||||
| Paquetes del juego `.nsp` / `.xci` | Las herramientas solo comprueban la versión del programa principal y no distinguen formatos de paquete; nosotros recorrimos todo el proceso con un `.xci`, y los usuarios han informado de que los paquetes `.nsp` también funcionan perfectamente |
|
||||
| Firmar e instalar con una herramienta de sideloading (Sideloadly, AltStore y similares) | No verificado; abre un issue y cuéntanos cómo te fue |
|
||||
| Crear el paquete en Linux | No verificado (verificado en Windows y Mac) |
|
||||
@@ -291,11 +363,11 @@ Descarga nuestro paquete «contenedor» precompilado (`D2RMobile-shell-build-inp
|
||||
- En los puntos marcados como no verificados, cuéntanos si funcionaron o no. Cualquiera de las dos respuestas es valiosa.
|
||||
- Para cambiar el código: primero consigue que pasen los puntos de entrada de pruebas de arriba. Cada cambio tiene que superar las barreras de regresión.
|
||||
|
||||
**Llevarlo a otras plataformas:** este enfoque no se limita a iPhone y iPad. Los Mac con Apple silicon ya tienen una versión nativa (consulta «Jugar directamente en un Mac», más arriba), compilada a partir del mismo programa del juego y el mismo anfitrión; Apple TV también tiene un port de la comunidad (versión preliminar para desarrolladores, consulta la tabla de dispositivos). Los teléfonos Android usan la misma clase de procesador, así que el programa del juego también se ejecuta allí de forma nativa, y el camino está totalmente abierto: las únicas partes que hay que sustituir son las caras del anfitrión y de la capa gráfica que dan a la plataforma. El autor no tiene ningún teléfono Android a mano, y le encantaría ver a alguien llevarlo a Android.
|
||||
**Llevarlo a otras plataformas:** este enfoque no se limita a iPhone y iPad. Los Mac con Apple silicon ya tienen una versión nativa (consulta «Jugar directamente en un Mac», más arriba), compilada a partir del mismo programa del juego y el mismo anfitrión; Apple TV también tiene un port de la comunidad (versión preliminar para desarrolladores, consulta la tabla de dispositivos). Android ya también está en marcha: desde la v2.0 hay una versión para Android portada por la comunidad (consulta «Android» más arriba), construida sobre el mismo anfitrión y con solo la capa gráfica sustituida por Vulkan; también ha llegado una versión para HarmonyOS (consulta «HarmonyOS» más arriba), que comparte el mismo motor Vulkan.
|
||||
|
||||
**Llevarlo a otros juegos:** alguien ya ha probado otros juegos de Switch sobre el mismo anfitrión. El anfitrión tiene algunos comportamientos que están activados por defecto en iOS y se escribieron para este juego en concreto; otro juego tropieza con ellos primero, así que desactívalos o sácalos antes de empezar:
|
||||
|
||||
- `dm/host/hle_oe.c`: la escala de renderizado 3D vale 0.75 por defecto en iOS, y `scale3d_tick` la reescribe en desplazamientos dentro del renderizador de este juego; con otro juego, eso es un puntero descontrolado.
|
||||
- `dm/host/hle_oe.c`: la escala de renderizado 3D vale 0.75 por defecto en los teléfonos (la app de Android la fija en 0.85), y `scale3d_tick` la reescribe en desplazamientos dentro del renderizador de este juego; con otro juego, eso es un puntero descontrolado.
|
||||
- `dm/host/hle_fs.c`: la siembra del alijo compartido en el primer arranque (`DM_STASH_SEED`) y los ajustes predeterminados de la distribución táctil (`DM_TOUCH_DEFAULTS`) están activados por defecto en iOS.
|
||||
- `dm/host/main.c`: el limitador de vaciado de partidas guardadas parchea una constante en una dirección fija del programa del juego; `argv[0]` está fijado en el código como `"D2R"`.
|
||||
- `dm/host/hle_time.c`: el interruptor de prueba de hora fija reconoce una dirección fija del programa del juego.
|
||||
@@ -321,6 +393,12 @@ Lo más limpio sería mover estos valores predeterminados a una configuración p
|
||||
| [docs/OLDER_SYSTEMS.md](docs/OLDER_SYSTEMS.md) (en inglés) | Sistemas antiguos (iOS 18 – 25, macOS 15 – 25): compilar la versión para API antiguas y combinarla con el Legacy Device Pack |
|
||||
| [docs/qa-rift-pet-life.md](docs/qa-rift-pet-life.md) (en inglés) | Lista de comprobación de regresión para la vida de los esbirros en las Greater Rifts (qué se ha ejecutado y qué no; se agradecen aportaciones) |
|
||||
| [docs/DERIVED.md](docs/DERIVED.md) (en inglés) | Material relacionado con el juego en este repositorio: qué hay, qué no hay y por qué |
|
||||
| [docs/ANDROID.md](docs/ANDROID.md) (en inglés) | Jugar en un teléfono Android: instalar el APK, crear el paquete de importación, versiones nuevas, problemas |
|
||||
| [docs/HARMONYOS.md](docs/HARMONYOS.md) (en inglés) | Jugar en un teléfono HarmonyOS: firmar el shell sin firmar, crear el paquete de ejecución, importar, solución de problemas |
|
||||
| [dm/harmony/README.md](dm/harmony/README.md) (en inglés) | HarmonyOS: estructura del código, comandos de compilación, ajustes por defecto y mediciones |
|
||||
| [dm/android/README.md](dm/android/README.md) (en inglés) | Android: estructura del código, compilación, los archivos que hay que poner en el teléfono y la lista de comprobación |
|
||||
| [dm/gfx/vulkan/INTEGRATION.md](dm/gfx/vulkan/INTEGRATION.md) (en inglés y chino) | Cómo se conecta la capa gráfica de Vulkan a la API gráfica común |
|
||||
| [docs/ANDROID_COLLABORATION.md](docs/ANDROID_COLLABORATION.md) (en inglés) | Colaboración Android / HarmonyOS: quién trabaja dónde, cómo participar, estado medido y trabajo pendiente; las notas de cada ronda están en [docs/android-notes/](docs/android-notes/) |
|
||||
|
||||
## Aviso legal
|
||||
|
||||
@@ -328,6 +406,12 @@ Lo más limpio sería mover estos valores predeterminados a una configuración p
|
||||
|
||||
## Agradecimientos
|
||||
|
||||
**La versión para Android de la v2.0 viene de tres autores de la comunidad. Gracias especiales a:**
|
||||
|
||||
- **[@yyan160](https://github.com/yyan160)** (Yuechuan Yang): el port a Android en sí ([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113)): la app de Android, el anfitrión JNI, la capa táctil, la presentación con Vulkan, una ronda completa de optimización medida paso a paso en un teléfono (el campamento en el Redmi K50 Ultra pasó de 7.7 fps a una mediana de 60 fps) y los cambios que permiten que el anfitrión común se compile y ejecute tanto en Apple como en Android. Cada punto planteado en la revisión se corrigió en la rama.
|
||||
- **[@biglawine](https://github.com/biglawine)**: el port a HarmonyOS ([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114)) y su motor de reproducción NVN→Vulkan, de donde sale la capa gráfica de Android; además montó los repositorios de colaboración de Android / HarmonyOS y generó los paquetes de shaders usados en las pruebas en dispositivo.
|
||||
- **[@vickwv](https://github.com/vickwv)**: otro port a Android, independiente ([#112](https://github.com/jhaizhou-ops/d2r-mobile/pull/112)). Sus ideas se midieron una por una en la versión para Android, y se adoptó su enfoque para aclarar la imagen 3D.
|
||||
|
||||
Este proyecto se apoya en el trabajo de código abierto que aparece a continuación. Gracias a sus autores y mantenedores.
|
||||
|
||||
- **Ryujinx** (Ryubing 1.3.2, MIT): `dm/third_party/ryujinx` incluye sin cambios su traductor de shaders (los proyectos Ryujinx.Graphics.Shader, Spv.Generator y Ryujinx.Common), que traduce los shaders del juego de Switch a SPIR-V. Durante el desarrollo también ejecutamos el juego original en un Ryujinx parcheado como referencia para comparar imágenes y estado del juego (consulta [dm/verify/README.md](dm/verify/README.md) (en inglés); los scripts que lo compilan y lo controlan no están en este repositorio).
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# D2R Mobile
|
||||
|
||||
**An open-source iOS / macOS compatibility layer for Diablo II: Resurrected with the Reign of the Warlock expansion.** It brings the Nintendo Switch release you bought, expansion included, to iPhone, iPad and Mac in full: the original game code runs natively, every control is rebuilt for touch, the frame rate holds at 60 fps, and you are in a game one second after the main menu. There is now a native macOS version as well (first version): on an Apple silicon Mac it starts on double-click and works with keyboard, mouse and gamepad. Apple TV 4K (3rd generation, A15) has a community port (developer preview) that has reached the character-selection screen only on its author's device; see the device table below.
|
||||
**An open-source compatibility layer for Diablo II: Resurrected with the Reign of the Warlock expansion, for iOS, macOS, Android and HarmonyOS.** It brings the Nintendo Switch release you bought, expansion included, to iPhone, iPad and Mac in full: the original game code runs natively, every control is rebuilt for touch, the frame rate holds at 60 fps, and you are in a game one second after the main menu. There is now a native macOS version as well (first version): on an Apple silicon Mac it starts on double-click and works with keyboard, mouse and gamepad. **Since v2.0 there is an Android version** (community port): the same game program executes natively on ARM64 Android phones, with the graphics reimplemented on Vulkan; on a Snapdragon 8+ Gen 1 phone the camp and the Den of Evil and Cow Level fights all run at a median 60 fps (see "Android" below); a HarmonyOS version runs on the same engine (community port: an unsigned shell from the Releases page that you re-sign yourself, nothing to build; see "HarmonyOS"). Apple TV 4K (3rd generation, A15) has a community port (developer preview) that has reached the character-selection screen only on its author's device; see the device table below.
|
||||
|
||||
This is not a tech demo that "sort of runs". It is a mobile version polished for daily play, from your first character all the way through the endgame.
|
||||
|
||||
Platforms: iPhone / iPad (iOS 26 and later; iOS 18 – 25 with the older-API build) · Mac (Apple silicon, macOS 26 or later; macOS 15 – 25 with the older-API build) · Apple TV 4K (3rd generation, A15; community port, developer preview) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 / Español / Русский · License: MIT · **Bring your own game files**
|
||||
Platforms: iPhone / iPad (iOS 26 and later; iOS 18 – 25 with the older-API build) · Mac (Apple silicon, macOS 26 or later; macOS 15 – 25 with the older-API build) · Apple TV 4K (3rd generation, A15; community port, developer preview) · Android phones (ARM64, Android 12 or later, Vulkan 1.1; community port) · HarmonyOS phones (HarmonyOS NEXT; community port, unsigned shell from the Releases page that you re-sign yourself) · Game version: Switch release with Reign of the Warlock, 1.0.34.0 (corresponds to PC version 3.3.94012) · English / 中文 / Español / Русский / 한국어 · License: MIT · **Bring your own game files**
|
||||
|
||||
中文: [README.zh-CN.md](README.zh-CN.md) · Español: [README.es.md](README.es.md)
|
||||
|
||||
@@ -25,8 +25,8 @@ Platforms: iPhone / iPad (iOS 26 and later; iOS 18 – 25 with the older-API bui
|
||||
**It is:**
|
||||
|
||||
- The game's own aarch64 program, **executing directly on the device**, with no emulated CPU. iPhone and Switch use the same class of processor; only the handful of instructions that cannot run unchanged under Apple's kernel are rewritten, and every other byte of the program is left exactly as shipped. Every class, every Runeword, Terror Zones, bosses, drop rules and quest flow are identical to the original.
|
||||
- The platform services the game expects — system calls, the file system, the graphics API, audio, input — provided by a small host written for Apple platforms. The graphics API is reimplemented entirely on Apple's Metal with no emulation layer in between, and the shaders are translated offline from the game's originals.
|
||||
- A port built for phones, and taken all the way: a complete touch control scheme, edge-to-edge iPhone and true full-screen iPad display, controller support, a power saver mode, save sync, English and Chinese, and a whole set of endgame modes and quality-of-life features the original never had.
|
||||
- The platform services the game expects — system calls, the file system, the graphics API, audio, input — provided by a small host written for Apple platforms. The graphics API is reimplemented entirely — on Metal on Apple devices, on Vulkan on Android — with no emulation layer in between, and the shaders are translated offline from the game's originals.
|
||||
- A port built for phones, and taken all the way: a complete touch control scheme, edge-to-edge iPhone and true full-screen iPad display, controller support, a power saver mode, save sync, five languages (English, Chinese, Spanish, Russian and Korean), and a whole set of endgame modes and quality-of-life features the original never had.
|
||||
|
||||
**It is not:**
|
||||
|
||||
@@ -93,7 +93,7 @@ This is not a gamepad pasted onto the screen. Every panel and every action was r
|
||||
|
||||
### Controller
|
||||
|
||||
Connect a controller and press any button: the interface switches to the original controller layout, with button prompts at the bottom of every panel. Touch the screen and you are back in the touch interface instantly. Inventory, stash, skill tree, Chronicle and settings are fully controller-navigable, with the same button mapping as on Switch.
|
||||
Connect a controller and press any button: the interface switches to the original controller layout, with button prompts at the bottom of every panel. Touch the screen and you are back in the touch interface instantly. Inventory, stash, skill tree, Chronicle and settings are fully controller-navigable, with the same button mapping as on Switch. With an Xbox controller the layout switches automatically to the PC / Xbox one (bottom confirms, right goes back) and the prompts show Xbox button icons; there is nothing to turn on.
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_pad_combat.jpg" width="49%" alt="Combat with a controller connected">
|
||||
@@ -158,9 +158,9 @@ Most features can be toggled one by one in game under Options → Custom.
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_map.jpg" width="33%" alt="The full-screen map">
|
||||
</p>
|
||||
|
||||
### English, Chinese, Spanish and Russian
|
||||
### English, Chinese, Spanish, Russian and Korean
|
||||
|
||||
The whole game switches between English, Chinese, Spanish and Russian under Options → Custom; after a restart, the interface is in the language you chose. On first launch it follows your device language (Spanish from Spain uses the game's esES text, other Spanish regions use the Latin American esMX text). In English, Spanish and Russian, items, skills and monsters use the original Diablo II wording, and everything we added — Greater Rift, Chronicle, the settings page, gesture prompts, map name plates — is translated too (item notes are translated for Chinese and Spanish only). Russian is the game's single ruRU text, with no regional variants. Voice acting: Chinese UI gets Chinese voices; Russian gets the original Russian voices when your game files include them (a package built from the complete game data does), otherwise English; everything else is English.
|
||||
The whole game switches between English, Chinese, Spanish, Russian and Korean under Options → Custom; after a restart, the interface is in the language you chose. On first launch it follows your device language (Spanish from Spain uses the game's esES text, other Spanish regions use the Latin American esMX text). In English, Spanish, Russian and Korean, items, skills and monsters use the original Diablo II wording, and everything we added — Greater Rift, Chronicle, the settings page, gesture prompts, map name plates — is translated too (item notes are translated for Chinese and Spanish only). Russian is the game's single ruRU text and Korean its koKR text, with no regional variants. Voice acting: Chinese UI gets Chinese voices; Russian and Korean get the original Russian or Korean voices when your game files include them (a package built from the complete game data does), otherwise English; everything else is English. Korean was contributed by [@soulsakura](https://github.com/soulsakura) ([#118](https://github.com/jhaizhou-ops/d2r-mobile/pull/118)).
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_game.jpg" width="58%" alt="Gameplay with the English interface">
|
||||
@@ -185,10 +185,36 @@ flowchart LR
|
||||
| Host | `dm/host` | Loads the rewritten program and provides the platform services it calls |
|
||||
| Graphics | `dm/gfx` | Implements the game's graphics API on Metal; shaders are translated offline from the game's originals |
|
||||
| iOS app | `dm/ios` | The app shell, touch controls and interface |
|
||||
| Android app | `dm/android` | The Android shell, touch overlay and Vulkan presentation |
|
||||
| HarmonyOS app | `dm/harmony` | The HarmonyOS shell (ArkTS + N-API), sharing the host and the Vulkan engine with Android |
|
||||
| Vulkan graphics | `dm/gfx/vulkan` | The same graphics API on Vulkan (shared by Android and HarmonyOS; the engine comes from the HarmonyOS port) |
|
||||
| Verification | `dm/verify` | Checks that the rewritten code behaves exactly like the original, plus the regression gates every change goes through |
|
||||
|
||||
**Why you can trust it:** the stability is not luck. The test and verification tooling is part of the project — unit tests for the host and graphics layers, an equivalence check for every rewritten instruction, scripted walkthrough regression for the touch interface, and on-device smoke tests. Start with `make -C dm/host/tests run`, `make -C dm/gfx/tests run` and `dm/verify/regress.sh` (run them inside the Python environment prepared in step 2 below; `regress.sh` also needs `brew install llvm`). How to contribute is in [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||
|
||||
## Android (new in v2.0)
|
||||
|
||||
Android phones use ARM64 processors just like the Switch, so, as on Apple devices, the game's own program executes directly on the phone with no CPU emulation. This release brings the whole host — system calls, file system, audio, input, saves — to Android unchanged and swaps the graphics layer for Vulkan: the NVN-to-Vulkan replay engine comes from [@biglawine](https://github.com/biglawine)'s HarmonyOS port, and the Android app, touch controls, Vulkan presentation and a full round of performance work, each step measured on a phone, are by [@yyan160](https://github.com/yyan160) ([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113)). The Apple and Android versions share the same host code, so future changes benefit both.
|
||||
|
||||
Measured by the port's authors on their phones (product defaults: 3D render scale capped at 0.85 and lowered dynamically when frames drop):
|
||||
|
||||
| Phone | Result |
|
||||
|---|---|
|
||||
| Redmi K50 Ultra (Snapdragon 8+ Gen 1, Adreno 730, Android 15) | Camp, Den of Evil fight, Cow Level fight: **median 60 fps**, GPU about 14–15 ms a frame |
|
||||
| OnePlus 13 (Adreno 830) | Playable; when one particular light effect appears in the camp, small black squares occasionally flash for an instant (under investigation) |
|
||||
|
||||
Minimum: ARM64, Android 12 (API 31) or later, and a GPU with Vulkan 1.1.
|
||||
|
||||
**How to use it today**: install `D2RMobile-android.apk` from the release page (it contains no game content). On a computer, run `python3 dm/tools/d2rm_android.py <Update directory> <output directory>` on your own game files to make the import pack (an `android` folder with the rewritten game program, every Vulkan shader bundle, the touch overlay and a few data tables), and copy it together with your game resources (the `data` folder) to `Download/S2X/D2R Mobile/` on the phone. The App imports it with a progress screen when you open it. No adb, and no need to build the APK yourself. The full steps are in [docs/ANDROID.md](docs/ANDROID.md). The touch controls are drawn the same way as on iPhone (button sockets, silver skill silhouettes, joystick), and no virtual pad buttons cover open panels. Compared with the iOS version, a few touch details are still unfinished: the empty-skill-slot menu, the stat-point overlay, and the item image that follows your finger while dragging in a shop.
|
||||
|
||||
Progress, the measurements from every round and the remaining work are in [docs/ANDROID_COLLABORATION.md](docs/ANDROID_COLLABORATION.md) and [docs/android-notes/](docs/android-notes/). The HarmonyOS version is in the next section.
|
||||
|
||||
## HarmonyOS (new in v2.0)
|
||||
|
||||
The HarmonyOS NEXT app (`dm/harmony`) is by [@biglawine](https://github.com/biglawine) ([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114)) and uses the same host and the same Vulkan engine as Android. Measured by the author on a Mate 90 Pro Max (Maleoon 955): 59.7 fps holding the joystick in the Rogue Encampment, display interval p50 16.6 / p99 18.1 ms.
|
||||
|
||||
**How to use it**: the same idea as the iOS shell. The Releases page has an **unsigned install package that contains no game content** (`D2RMobile-harmony-shell-unsigned.hap`). HarmonyOS NEXT only installs apps signed with your own developer certificate, so you re-sign it with your own debug certificate and install it; you do not build the app yourself. Then, on a computer, run `python3 dm/tools/d2rm_android.py --target ohos <Update folder> <output folder>` on your own game files to make the runtime pack, put it with the game resources in a "D2R Mobile" folder on the phone, open the app and pick that folder to import. The full steps are in [docs/HARMONYOS.md](docs/HARMONYOS.md). The author ran the whole chain (re-sign → install → first import → into a game → save and exit) on a Mate 90 Pro Max, with three cold starts in a row working; you need a Huawei developer account (DevEco Studio can generate the debug certificate and register the device for you).
|
||||
|
||||
## Which devices are supported
|
||||
|
||||
Minimum: **an A14 / M1 chip or later** — the graphics layer needs Metal 3, which Apple supports from A14 / M1 on (see Apple's [Metal support on Apple devices](https://support.apple.com/102894) and [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf)).
|
||||
@@ -196,12 +222,15 @@ Minimum: **an A14 / M1 chip or later** — the graphics layer needs Metal 3, whi
|
||||
| Device | Playable? | How | How sure we are |
|
||||
|---|---|---|---|
|
||||
| **iPhone / iPad, A17 Pro and later** (iPhone 15 Pro and later, iPhone 16 and later, iPads with M-series chips) | Yes | iOS 26 or later: the default shell / default build; iOS 18 – 25: the iOS 18 shell / [older-API build](docs/OLDER_SYSTEMS.md) | Main devices, played daily |
|
||||
| **iPhone Duo** (foldable) | Yes; the picture resizes when you unfold or fold | The shells on the Releases page are built with Xcode 27.1; when building with Xcode yourself, use 27.1 so the inner screen is filled (see [docs/DEPENDENCIES.md](docs/DEPENDENCIES.md)) | Supported since v2.0. Checked on a Mac switching between the outer and inner screen sizes taken from the iPhone Duo simulator (the simulator itself cannot run the game's graphics). We will test on a real iPhone Duo as soon as we have one; if you have the phone, please tell us how it goes in an Issue |
|
||||
| **iPhone / iPad, A16 and earlier** (all iPhone 14 models, iPhone 15 / 15 Plus, iPhone 13 series and so on) | Yes, with one extra step | Make a Legacy Device Pack from your own game files as in [docs/LEGACY_DEVICES.md](docs/LEGACY_DEVICES.md) and include it when making the install package; the system split is the same as the row above | Played by players: iPhone 14 Pro Max (A16, 6 GB) at 60 fps; iPhone 13 Pro Max (A15, 6 GB) in the 30 fps mode |
|
||||
| **Devices with 4 GB of RAM** (such as the 6th-generation iPad mini or the 4th-generation iPad Air) | Runs, but memory is very tight (we are still reducing memory use) | Same as the A16-and-earlier row (with the Legacy Device Pack) | Tested by a player: on an iPad mini 6 (A15, 4 GB, iPadOS 27) a few minutes of Act I ran at 50–58 fps after automatic quality reduction, with constant system memory warnings and only about 560 MB below the system memory limit — busy scenes with many monsters and effects may be ended by the system; on an earlier version an iPad Air 4 (A14, 4 GB) was ended by the system a few seconds after launch |
|
||||
| **A14 chips with 6 GB of RAM or more** (such as iPhone 12 Pro / 12 Pro Max) | No reports yet | Same as the A16-and-earlier row | If you have tried, please open an Issue and tell us |
|
||||
| **A13 and earlier chips** (such as the iPhone 11 series and the 2020 iPad Pro) | Not supported | — | The graphics chip does not support Metal 3 (tested by a player on an iPad Pro with A12Z; Apple's references are above the table); the app says so at launch instead of crashing |
|
||||
| **Mac, Apple silicon** | Yes (native macOS App) | macOS 26 or later: the default build; macOS 15 – 25: the [older-API build](docs/OLDER_SYSTEMS.md). Keyboard, mouse and gamepad all work; what each can do is in [docs/MAC.md](docs/MAC.md) | A player has played the older-API build on macOS 15.7.7 |
|
||||
| **Apple TV 4K (3rd generation, A15)** | Community port ([@yinqingyan](https://github.com/yinqingyan), contributed under the MIT License with the author's consent), developer preview | Build as in [dm/tvos/README.md](dm/tvos/README.md) and copy the game files and the Legacy Device Pack into the app; real hardware only, the Simulator cannot run it; saves live in the Caches directory, which the system may purge | Reached the character-selection screen on real hardware; entering the game, full controller mapping and saves are not verified yet, and the maintainers have not tested it on real hardware |
|
||||
| **HarmonyOS phones** (HarmonyOS NEXT, API 26) | Playable (community port) | The unsigned shell from the Releases page, re-signed with your own debug certificate, plus a runtime pack made from your own game files, see [docs/HARMONYOS.md](docs/HARMONYOS.md) | Verified by the author on a Mate 90 Pro Max: re-sign, install, import, into a game, save and exit |
|
||||
| **Android phones** (ARM64, Android 12 or later, Vulkan 1.1) | Playable (community port) | The release page's APK + an import pack made from your own game files, see [docs/ANDROID.md](docs/ANDROID.md) | Measured by the port's authors: Redmi K50 Ultra median 60 fps; OnePlus 13 playable, with occasional black squares flashing for an instant; played on a vivo X200 Ultra |
|
||||
| **Intel Macs** | Not supported | — | — |
|
||||
|
||||
**What the dialogs in the App mean**
|
||||
@@ -213,13 +242,23 @@ Minimum: **an A14 / M1 chip or later** — the graphics layer needs Metal 3, whi
|
||||
|
||||
## Getting started
|
||||
|
||||
Both routes start with **the files of the game you bought**: the Switch release of Diablo II: Resurrected plus the Reign of the Warlock expansion, updated to 1.0.34.0 (the version the console shows; it corresponds to PC version 3.3.94012, and the directory names and tools in this repository use the latter number). This project is built for the version with that expansion; using it without the expansion is not supported and has not been verified. How to prepare them is in [docs/GAME_FILES.md](docs/GAME_FILES.md).
|
||||
Whatever device you play on, you start with **the files of the game you bought**: the Switch release of Diablo II: Resurrected plus the Reign of the Warlock expansion, updated to 1.0.34.0 (the version the console shows; it corresponds to PC version 3.3.94012, and the directory names and tools in this repository use the latter number). This project is built for the version with that expansion; using it without the expansion is not supported and has not been verified. How to prepare them is in [docs/GAME_FILES.md](docs/GAME_FILES.md).
|
||||
|
||||
> This project provides only tools and an install shell that contains no game content. We do not distribute or endorse, and are not responsible for, any third party distributing game assets, game executables or install packages that contain game content. Please use only game files you legally own.
|
||||
|
||||
This project is implemented and verified on the Switch release 1.0.34.0 (which corresponds to PC version 3.3.94012), and by default the tools accept only that version. Community users have reported adapting other versions on their own by following the structure of this repository, and running them successfully. The rule tables are grouped by game version (in `dm/tools/patch_nso.py`, keyed by the build ID of the main program); you are welcome to contribute the version you adapted.
|
||||
|
||||
**Check your device first**: the "Which devices are supported" table above tells you which build to use and whether you also need a Legacy Device Pack.
|
||||
**Check your device first** and find your section in the table below; the "Which devices are supported" table above tells you which build to use on Apple devices and whether you also need a Legacy Device Pack.
|
||||
|
||||
| Your device | How | Steps |
|
||||
|---|---|---|
|
||||
| iPhone / iPad, with an Apple silicon Mac | A full build from source | "With a Mac: three steps" below |
|
||||
| iPhone / iPad, without a Mac | Download a shell with no game content and add your game content on Windows / Linux | "Without a Mac" below and [docs/NO_XCODE.md](docs/NO_XCODE.md) |
|
||||
| Mac (Apple silicon) | Build a native macOS App | "Playing directly on a Mac" below and [docs/MAC.md](docs/MAC.md) |
|
||||
| Android phone | Install the release page's APK and copy an import pack made on a computer to the phone | "Android" below and [docs/ANDROID.md](docs/ANDROID.md) |
|
||||
| HarmonyOS phone | Re-sign the unsigned shell from the Releases page with your own debug certificate, make a runtime pack on a computer and copy it to the phone | "HarmonyOS" below and [docs/HARMONYOS.md](docs/HARMONYOS.md) |
|
||||
|
||||
The two routes for iPhone / iPad compared:
|
||||
|
||||
| | With a Mac | Without a Mac |
|
||||
|---|---|---|
|
||||
@@ -255,7 +294,7 @@ The Apple account used for signing: a paid developer account gives you everythin
|
||||
|
||||
The first time you open the app on your phone, it asks for the "game resource folder" — the 18 resource archives from your game files. Where to put them is in the section "The "game resource folder" that goes on the phone" of [docs/GAME_FILES.md](docs/GAME_FILES.md).
|
||||
|
||||
`./setup.sh check` is a health check: it reports the state of this computer, the tools, the game files and the signing configuration item by item, and for everything missing it says where to get it and which command to run next; it changes nothing. If what you have is a whole game package (`.xci` / `.nsp`), `./setup.sh <game package> <prod.keys>` first extracts the game files into place and then carries on (install hactool first). Run `./setup.sh` again after every update to a new commit: it rebuilds the patched binaries and the shader library for the current sources (steps that are already up to date are skipped). It also rewrites three files in the repository that change with your local tool fingerprints (`dm/gfx/tools/dmsh_chain.lock`, `dm/gfx/nvn/dmsh_chain.h`, `dm/gfx/nvn/c1_full.tsv`); that is expected, do not commit them.
|
||||
`./setup.sh check` is a health check: it reports the state of this computer, the tools, the game files and the signing configuration item by item, and for everything missing it says where to get it and which command to run next; it changes nothing. If what you have is a whole game package (`.xci` / `.nsp`), `./setup.sh <game package> <prod.keys>` first extracts the game files into place and then carries on (install hactool first); if the base game and the update are separate packages, give both: `./setup.sh <base game> <update> <prod.keys>`. Run `./setup.sh` again after every update to a new commit: it rebuilds the patched binaries and the shader library for the current sources (steps that are already up to date are skipped). It also rewrites three files in the repository that change with your local tool fingerprints (`dm/gfx/tools/dmsh_chain.lock`, `dm/gfx/nvn/dmsh_chain.h`, `dm/gfx/nvn/c1_full.tsv`); that is expected, do not commit them.
|
||||
|
||||
### Playing directly on a Mac
|
||||
|
||||
@@ -269,6 +308,38 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25: produces D2R Mobile M3.a
|
||||
|
||||
The interface is the original's gamepad interface. Keyboard: Space confirms, Esc goes back, Return, the `=` key opens the menu / a new character, W A S D moves, and every other gamepad button has a key. Mouse: clicking a monster, NPC or object walks over and interacts, and the skill slots, potion cells and key hints at the bottom, buttons and tabs in panels, the class figures when creating a character and the minimap can all be clicked; clicking empty ground walks there and holding keeps walking, clicking a monster attacks it, and items take double clicks and drags. With a keyboard, the prompts on screen show keyboard keys. Saves stay on this Mac (an App you build yourself has no iCloud sync) and can be imported by hand from an iPhone / iPad. The key table, how to create a character, what the mouse can do, the import steps and the known shortcomings are in [docs/MAC.md](docs/MAC.md). Keyboard and a physical gamepad have not been operated by a person yet — if you try it, please tell us how it went.
|
||||
|
||||
### Android
|
||||
|
||||
No Mac, no adb and no building the APK yourself; any Windows / Linux / Mac computer will do (it has been run through on a Mac so far). The full steps, the tools to install and what to do when something goes wrong are in [docs/ANDROID.md](docs/ANDROID.md).
|
||||
|
||||
1. Prepare your game files, the same as for Apple devices ([docs/GAME_FILES.md](docs/GAME_FILES.md)).
|
||||
2. Make the import pack on a computer:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py <Update directory of your game files> <output directory>
|
||||
```
|
||||
|
||||
3. Over USB, copy the `android` folder it made and the game resource folder `data` to `Download/S2X/D2R Mobile/` on the phone.
|
||||
4. Download `D2RMobile-android.apk` from the [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), install it, open it and allow "All files access"; the App imports the pack and starts the game.
|
||||
|
||||
The source must be from the same release as the APK; for a new release, replace both the APK and the import pack, and your saves stay. To build the APK yourself from source, see [dm/android/README.md](dm/android/README.md).
|
||||
|
||||
### HarmonyOS
|
||||
|
||||
You do not build the app yourself. You need a Huawei developer account and DevEco Studio (for its signing tool and `hdc`; it can also generate the debug certificate and register the phone). The full steps, commands and what to do when something fails are in [docs/HARMONYOS.md](docs/HARMONYOS.md).
|
||||
|
||||
1. Prepare your game files, the same as for Apple devices ([docs/GAME_FILES.md](docs/GAME_FILES.md)).
|
||||
2. Download the unsigned shell `D2RMobile-harmony-shell-unsigned.hap` from the [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), re-sign it with your own debug certificate and profile (`hap-sign-tool sign-app`), then install it on the phone with `hdc install -r`.
|
||||
3. Make the runtime pack on a computer:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py --target ohos <Update folder of your game files> <output folder>
|
||||
```
|
||||
|
||||
4. On the phone, make a "D2R Mobile" folder with the game resources in `data/` and the runtime pack from the previous step in `dm/`, open the app, tap Import and pick that folder.
|
||||
|
||||
The source must be from the same release as the shell. For a new release, re-sign the new shell with the same signing and install it over the old one; your saves are kept. The author ran these steps on a Mate 90 Pro Max.
|
||||
|
||||
### Without a Mac: the shell plus the packaging tool
|
||||
|
||||
Download our prebuilt "shell" package (`D2RMobile-shell-build-input.zip`; `D2RMobile-shell-ios18-build-input.zip` for iOS 18 – 25), which contains no game content, from this repository's [Releases page](https://github.com/jhaizhou-ops/d2r-mobile/releases), add your own game files, make the install package on Windows or Linux, then sign and install it with a sideloading tool. The shell is build input, not an app to install (installed as is, it only shows a dialog and does not start the game); when you move to a new release, make the install package again with the new shell. On this route only, because the computer making the package has no Apple shader compiler, the **first launch** on the phone spends about 7 minutes compiling shaders (once, with a progress bar); a package built with Xcode has no such step. The steps, and how far each one has been verified, are in [docs/NO_XCODE.md](docs/NO_XCODE.md).
|
||||
@@ -278,6 +349,7 @@ Download our prebuilt "shell" package (`D2RMobile-shell-build-input.zip`; `D2RMo
|
||||
| Item | Status |
|
||||
|---|---|
|
||||
| Online play | Out of scope; fully offline |
|
||||
| Android version | A few iOS touch details (empty-skill-slot menu, stat-point overlay, the item image that follows your finger in a shop) are unfinished; see "Android" above |
|
||||
| `.nsp` / `.xci` game packages | The tools only check the version of the main program and do not distinguish package formats; we ran the whole path with an `.xci` ourselves, and users have reported that `.nsp` packages work perfectly as well |
|
||||
| Signing and installing with a sideloading tool (Sideloadly, AltStore and the like) | Not verified; open an issue and tell us how it went |
|
||||
| Making the package on Linux | Not verified (verified on Windows and Mac) |
|
||||
@@ -291,11 +363,11 @@ Download our prebuilt "shell" package (`D2RMobile-shell-build-input.zip`; `D2RMo
|
||||
- For the items marked not verified, tell us whether they worked or not. Either answer is valuable.
|
||||
- To change the code: get the test entry points above passing first. Every change has to pass the regression gates.
|
||||
|
||||
**Taking it to other platforms:** this approach is not limited to iPhone and iPad. Apple silicon Macs already have a native version (see "Playing directly on a Mac" above), built from the same game program and the same host; Apple TV also has a community port (developer preview, see the device table). Android phones use the same class of processor, so the game program executes natively there as well, and the route is fully open: the only parts to replace are the sides of the host and the graphics layer that face the platform. The author has no Android phone at hand, and would love to see someone bring it to Android.
|
||||
**Taking it to other platforms:** this approach is not limited to iPhone and iPad. Apple silicon Macs already have a native version (see "Playing directly on a Mac" above), built from the same game program and the same host; Apple TV also has a community port (developer preview, see the device table). Android has been reached too: since v2.0 there is a community-ported Android version (see "Android" above) built on the same host, with only the graphics layer swapped for Vulkan; a HarmonyOS version has arrived too (see "HarmonyOS" above), sharing the same Vulkan engine.
|
||||
|
||||
**Taking it to other games:** someone has already tried other Switch games on the same host. The host has some behaviour that is on by default on iOS and was written for this one game; another game runs into these first, so turn them off or move them out before you start:
|
||||
|
||||
- `dm/host/hle_oe.c`: the 3D render scale defaults to 0.75 on iOS, and `scale3d_tick` rewrites it at offsets inside this game's renderer — with another game that is a wild pointer.
|
||||
- `dm/host/hle_oe.c`: the 3D render scale defaults to 0.75 on phones (the Android app sets 0.85), and `scale3d_tick` rewrites it at offsets inside this game's renderer — with another game that is a wild pointer.
|
||||
- `dm/host/hle_fs.c`: seeding the shared stash on first launch (`DM_STASH_SEED`) and the touch-layout default settings (`DM_TOUCH_DEFAULTS`) are on by default on iOS.
|
||||
- `dm/host/main.c`: the save-flush throttle patches a constant at a fixed address in the game program; `argv[0]` is hard-coded to `"D2R"`.
|
||||
- `dm/host/hle_time.c`: the fixed-time test switch recognises a fixed address in the game program.
|
||||
@@ -321,6 +393,12 @@ The cleaner arrangement is to move these defaults into per-game configuration an
|
||||
| [docs/OLDER_SYSTEMS.md](docs/OLDER_SYSTEMS.md) | Older systems (iOS 18 – 25, macOS 15 – 25): building the older-API version and combining it with the Legacy Device Pack |
|
||||
| [docs/qa-rift-pet-life.md](docs/qa-rift-pet-life.md) | Regression checklist for minion life in Greater Rifts (what has been run and what has not; additions welcome) |
|
||||
| [docs/DERIVED.md](docs/DERIVED.md) | Game-related material in this repository: what is here, what is not, and why |
|
||||
| [docs/ANDROID.md](docs/ANDROID.md) | Playing on an Android phone: installing the APK, making the import pack, new releases, troubleshooting |
|
||||
| [docs/HARMONYOS.md](docs/HARMONYOS.md) | Playing on a HarmonyOS phone: re-signing the unsigned shell, making the runtime pack, importing, troubleshooting |
|
||||
| [dm/harmony/README.md](dm/harmony/README.md) | HarmonyOS: source layout, build commands, defaults and measurements |
|
||||
| [dm/android/README.md](dm/android/README.md) | Android: source layout, building, the files to put on the phone, the acceptance checklist |
|
||||
| [dm/gfx/vulkan/INTEGRATION.md](dm/gfx/vulkan/INTEGRATION.md) | How the Vulkan graphics layer plugs into the shared graphics API |
|
||||
| [docs/ANDROID_COLLABORATION.md](docs/ANDROID_COLLABORATION.md) | Android / HarmonyOS collaboration: who works where, how to take part, measured status and remaining work; the notes from every round are in [docs/android-notes/](docs/android-notes/) |
|
||||
|
||||
## Legal
|
||||
|
||||
@@ -328,6 +406,12 @@ The cleaner arrangement is to move these defaults into per-game configuration an
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
**The Android version in v2.0 comes from three community authors. Special thanks to:**
|
||||
|
||||
- **[@yyan160](https://github.com/yyan160)** (Yuechuan Yang): the Android port itself ([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113)) — the Android app, the JNI host, the touch overlay, Vulkan presentation, a full round of performance work measured step by step on a phone (the Redmi K50 Ultra camp went from 7.7 fps to a median 60 fps), and the changes that let the shared host build and run on both Apple and Android. Every point raised in review was fixed on the branch.
|
||||
- **[@biglawine](https://github.com/biglawine)**: the HarmonyOS port ([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114)) and its NVN-to-Vulkan replay engine, which is where the Android graphics layer comes from; they also set up the Android / HarmonyOS collaboration repositories and generated the shader bundles used for on-device testing.
|
||||
- **[@vickwv](https://github.com/vickwv)**: a separate, independent Android port ([#112](https://github.com/jhaizhou-ops/d2r-mobile/pull/112)). Its ideas were each measured on the Android version, and its 3D brightening approach was adopted.
|
||||
|
||||
This project stands on the open-source work below. Thank you to its authors and maintainers.
|
||||
|
||||
- **Ryujinx** (Ryubing 1.3.2, MIT): `dm/third_party/ryujinx` bundles its shader translator unchanged (the Ryujinx.Graphics.Shader, Spv.Generator and Ryujinx.Common projects), which translates the Switch game's shaders to SPIR-V. During development we also ran the original game in a patched Ryujinx as the reference for comparing pictures and game state (see [dm/verify/README.md](dm/verify/README.md); the scripts that build and drive it are not in this repository).
|
||||
|
||||
+100
-16
@@ -1,10 +1,10 @@
|
||||
# D2R Mobile
|
||||
|
||||
**开源的《暗黑破坏神 II:狱火重生》术士君临 iOS / macOS 兼容层。** 把你自己购买的 Nintendo Switch 版游戏(含「术士君临」资料片)完整带到 iPhone、iPad 和 Mac 上:原版内核原生执行,整套操作为触屏重做,稳定 60 帧,一秒进局。现在也有原生的 macOS 版(第一版):Apple 芯片的 Mac 上双击启动,键盘、鼠标、手柄都能用。Apple TV 4K(第三代 A15)有社区移植(开发者预览),只在作者的实机上到过职业选择画面,详见下面的设备表。
|
||||
**开源的《暗黑破坏神 II:狱火重生》术士君临兼容层,支持 iOS、macOS、安卓与鸿蒙。** 把你自己购买的 Nintendo Switch 版游戏(含「术士君临」资料片)完整带到 iPhone、iPad 和 Mac 上:原版内核原生执行,整套操作为触屏重做,稳定 60 帧,一秒进局。现在也有原生的 macOS 版(第一版):Apple 芯片的 Mac 上双击启动,键盘、鼠标、手柄都能用。**v2.0 起有了安卓版**(社区移植):同一份游戏程序在 ARM64 安卓手机上原生执行,图形在 Vulkan 上重新实现;骁龙 8+ 一代的手机上,营地、邪恶洞穴和奶牛关的战斗都是中位 60 帧,详见下面的「安卓版」;同一套引擎上还有鸿蒙版(社区移植,发布页下载未签名壳、自己重签即可,不用自己构建,见「鸿蒙版」)。Apple TV 4K(第三代 A15)有社区移植(开发者预览),只在作者的实机上到过职业选择画面,详见下面的设备表。
|
||||
|
||||
这不是一个「勉强能跑」的技术演示,而是一个打磨到可以天天玩、从开荒一路玩到终局的移动版。
|
||||
|
||||
平台:iPhone / iPad(iOS 26 起;iOS 18 – 25 用老接口版)· Mac(Apple 芯片,macOS 26 及以上;macOS 15 – 25 用老接口版)· Apple TV 4K(第三代 A15,社区移植,开发者预览)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English / Español / Русский · 许可证:MIT · **需要自备游戏文件**
|
||||
平台:iPhone / iPad(iOS 26 起;iOS 18 – 25 用旧接口版)· Mac(Apple 芯片,macOS 26 及以上;macOS 15 – 25 用旧接口版)· Apple TV 4K(第三代 A15,社区移植,开发者预览)· 安卓手机(ARM64,Android 12 起,Vulkan 1.1;社区移植)· 鸿蒙手机(HarmonyOS NEXT;社区移植,发布页的未签名壳 + 自己重签)· 游戏版本:Switch 版「术士君临」1.0.34.0(对应 PC 版 3.3.94012)· 中文 / English / Español / Русский / 한국어 · 许可证:MIT · **需要自备游戏文件**
|
||||
|
||||
English: [README.md](README.md) · Español: [README.es.md](README.es.md)
|
||||
|
||||
@@ -25,8 +25,8 @@ English: [README.md](README.md) · Español: [README.es.md](README.es.md)
|
||||
**是:**
|
||||
|
||||
- 游戏自己的 aarch64 程序**直接在设备上执行**,没有模拟 CPU。iPhone 和 Switch 是同一类处理器,程序里只有极少数在苹果内核下不能原样执行的指令被改写,其余逐字节保持原样。所有职业、全部符文之语、恐怖地带、首领、掉落规则、任务流程,都和原版一模一样。
|
||||
- 游戏需要的平台服务——系统调用、文件系统、图形接口、音频、输入——由一个为苹果平台写的小型宿主提供;图形接口完全在苹果的 Metal 上重新实现,中间不经过任何模拟层,着色器由游戏原版离线翻译。
|
||||
- 一次真正为手机做的移植,而且做到了底:整套触屏操作、全面屏与 iPad 真全屏、手柄支持、省电模式、存档同步、中英双语,以及一整套原版没有的终局玩法与便利功能。
|
||||
- 游戏需要的平台服务——系统调用、文件系统、图形接口、音频、输入——由一个为苹果平台写的小型宿主提供;图形接口完全重新实现——苹果上用 Metal,安卓上用 Vulkan——中间不经过任何模拟层,着色器由游戏原版离线翻译。
|
||||
- 一次真正为手机做的移植,而且做到了底:整套触屏操作、全面屏与 iPad 真全屏、手柄支持、省电模式、存档同步、中英西俄韩五种语言,以及一整套原版没有的终局玩法与便利功能。
|
||||
|
||||
**不是:**
|
||||
|
||||
@@ -93,7 +93,7 @@ iPhone 与 iPad 共用一个安装包。
|
||||
|
||||
### 手柄
|
||||
|
||||
接上手柄、按任意键,界面自动换成原版手柄布局,每个面板底部带按键提示;碰一下屏幕,立刻回到触屏界面。物品栏、储藏箱、技能树、编年史、设置页全程手柄可操作,键位与 Switch 一致。
|
||||
接上手柄、按任意键,界面自动换成原版手柄布局,每个面板底部带按键提示;碰一下屏幕,立刻回到触屏界面。物品栏、储藏箱、技能树、编年史、设置页全程手柄可操作,键位与 Switch 一致。接的是 Xbox 手柄时会自动换成 PC / Xbox 版的键位(下确认、右返回),按键提示也换成 Xbox 的图标,不用去设置里开。
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/pad_game.jpg" width="49%" alt="接手柄时的界面">
|
||||
@@ -158,9 +158,9 @@ iPhone 与 iPad 共用一个安装包。
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/map.jpg" width="33%" alt="全屏地图">
|
||||
</p>
|
||||
|
||||
### 中文、英文、西班牙语与俄语
|
||||
### 中文、英文、西班牙语、俄语与韩语
|
||||
|
||||
整个游戏可在「选项 → 自定义」里切换中文、英文、西班牙语或俄语,重启后界面就是所选语言;第一次打开时跟随设备语言(西班牙的西语用原版 esES 文字,其他地区的西语用拉美 esMX 文字;俄语用原版 ruRU 文字)。英文、西语和俄语下,物品、技能、怪物名沿用原版译名,我们新增的内容——秘境、编年史、设置页、手势提示、地图名牌——也全部配了对应语言(物品注释只有中文与西语)。语音:中文界面配中文语音;俄语界面在你的游戏文件里带俄语配音时(用完整游戏数据出的包都带)配原版俄语语音,否则配英文;其余配英文语音。
|
||||
整个游戏可在「选项 → 自定义」里切换中文、英文、西班牙语、俄语或韩语,重启后界面就是所选语言;第一次打开时跟随设备语言(西班牙的西语用原版 esES 文字,其他地区的西语用拉美 esMX 文字;俄语用原版 ruRU 文字,韩语用原版 koKR 文字)。英文、西语、俄语和韩语下,物品、技能、怪物名沿用原版译名,我们新增的内容——秘境、编年史、设置页、手势提示、地图名牌——也全部配了对应语言(物品注释只有中文与西语)。语音:中文界面配中文语音;俄语、韩语界面在你的游戏文件里带对应配音时(用完整游戏数据出的包都带)配原版俄语、韩语语音,否则配英文;其余配英文语音。韩语由 [@soulsakura](https://github.com/soulsakura) 贡献([#118](https://github.com/jhaizhou-ops/d2r-mobile/pull/118))。
|
||||
|
||||
<p align="center">
|
||||
<img src="https://github.com/jhaizhou-ops/d2r-mobile/releases/download/assets/en_game.jpg" width="58%" alt="英文界面下的游戏画面">
|
||||
@@ -185,23 +185,52 @@ flowchart LR
|
||||
| 宿主 | `dm/host` | 装载改写后的程序,提供它调用的平台服务 |
|
||||
| 图形 | `dm/gfx` | 在 Metal 上实现游戏用的图形接口;着色器由游戏原版离线翻译 |
|
||||
| iOS App | `dm/ios` | App 外壳、触摸操作与界面 |
|
||||
| 安卓 App | `dm/android` | 安卓外壳、触屏覆盖层、Vulkan 呈现 |
|
||||
| 鸿蒙 App | `dm/harmony` | 鸿蒙外壳(ArkTS + N-API),与安卓共用宿主和 Vulkan 引擎 |
|
||||
| Vulkan 图形层 | `dm/gfx/vulkan` | 在 Vulkan 上实现同一套图形接口(安卓、鸿蒙共用;引擎来自鸿蒙移植) |
|
||||
| 验证 | `dm/verify` | 核对改写后的代码与原版行为完全一致,以及每次改动都要过的回归闸门 |
|
||||
|
||||
**为什么可信:** 稳定不是靠运气。测试与验证工具是项目的一部分——宿主与图形层的单元测试、对每一处改写指令的等价核对、触摸界面的脚本化走查回归、真机冒烟。从 `make -C dm/host/tests run`、`make -C dm/gfx/tests run` 与 `dm/verify/regress.sh` 开始(都在下面第 2 步准备的 Python 环境里跑;`regress.sh` 另需 `brew install llvm`)。怎么参与见 [CONTRIBUTING.zh-CN.md](CONTRIBUTING.zh-CN.md)。
|
||||
|
||||
## 安卓版(v2.0 新增)
|
||||
|
||||
安卓手机和 Switch 一样是 ARM64 处理器,所以和苹果上一样,游戏自己的程序直接在手机上执行,没有模拟 CPU。这一版把整套宿主——系统调用、文件系统、音频、输入、存档——原样带到了安卓上,图形层换成 Vulkan:NVN→Vulkan 的回放引擎来自 [@biglawine](https://github.com/biglawine) 的鸿蒙移植,安卓 App、触屏、Vulkan 呈现和一整轮在真机上逐项测量的性能优化由 [@yyan160](https://github.com/yyan160) 完成([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113))。苹果版和安卓版用的是同一份宿主代码,以后的改动两边一起受益。
|
||||
|
||||
合作者的真机实测(产品缺省设置:3D 渲染比例上限 0.85,按掉帧动态调低):
|
||||
|
||||
| 手机 | 读数 |
|
||||
|---|---|
|
||||
| Redmi K50 Ultra(骁龙 8+ 一代,Adreno 730,Android 15) | 营地、邪恶洞穴战斗、奶牛关战斗:**中位 60 帧**,GPU 每帧约 14–15 ms |
|
||||
| OnePlus 13(Adreno 830) | 能玩;营地里有一种光效出现时,偶尔会闪过一瞬的小黑块,正在查 |
|
||||
|
||||
最低要求:ARM64,Android 12(API 31)及以上,显卡支持 Vulkan 1.1。
|
||||
|
||||
**现在怎么用**:装发布页的 `D2RMobile-android.apk`(不含任何游戏内容),在电脑上用你自己的游戏文件跑 `python3 dm/tools/d2rm_android.py <Update 目录> <输出目录>` 做出导入包(`android` 文件夹:改写后的游戏程序、全部 Vulkan 着色器包、触屏覆盖层与几张数据表),把它和游戏资源(`data` 文件夹)一起拷到手机的 `Download/S2X/D2R Mobile/`,打开 App 会带进度条自己导入。不用 adb,也不用自己编 APK。完整步骤见 [docs/ANDROID.zh-CN.md](docs/ANDROID.zh-CN.md)。触屏控件和 iPhone 版同一套画法(按钮底座、银灰技能剪影、摇杆),面板打开时不再压着虚拟手柄圆钮。和 iOS 版相比,还没做完的是几处触屏细节:空技能格菜单、加点浮层、商店拖动时跟着手指的物品图。
|
||||
|
||||
开发进度、每一轮的实测记录与待办在 [docs/ANDROID_COLLABORATION.zh-CN.md](docs/ANDROID_COLLABORATION.zh-CN.md) 和 [docs/android-notes/](docs/android-notes/)。鸿蒙版见下一节。
|
||||
|
||||
## 鸿蒙版(v2.0 新增)
|
||||
|
||||
鸿蒙 NEXT 应用(`dm/harmony`)由 [@biglawine](https://github.com/biglawine) 完成([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114)),和安卓用同一份宿主和同一套 Vulkan 引擎。作者在 Mate 90 Pro Max(马良 955)上实测:罗格营地按住摇杆 59.7 帧,上屏间隔 p50 16.6 / p99 18.1 ms。
|
||||
|
||||
**怎么用**:和 iOS 的壳一个思路。发布页有一个**不含任何游戏内容的未签名安装包**(`D2RMobile-harmony-shell-unsigned.hap`);鸿蒙 NEXT 只装用你自己的开发者证书签名的应用,所以你用自己的调试证书把它重签、装上,不用自己编应用。再在电脑上用你自己的游戏文件跑 `python3 dm/tools/d2rm_android.py --target ohos <Update 目录> <输出目录>` 做出运行包,和游戏资源一起放进手机上的「D2R Mobile」文件夹,打开应用选它导入。完整步骤见 [docs/HARMONYOS.zh-CN.md](docs/HARMONYOS.zh-CN.md)。作者在 Mate 90 Pro Max 上把「重签 → 安装 → 首次导入 → 进局 → 保存退出」整条走通,连续三次冷启动都正常;需要华为开发者账号(DevEco Studio 能自动生成调试证书与登记设备)。
|
||||
|
||||
## 支持哪些设备
|
||||
|
||||
最低要求:**A14 / M1 及以后的芯片**——本项目的图形层要用 Metal 3,苹果从 A14 / M1 起才支持(依据:苹果的[Metal 支持的设备](https://support.apple.com/102894)、[Metal 功能表](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf))。
|
||||
|
||||
| 设备 | 能不能玩 | 怎么做 | 把握程度 |
|
||||
|---|---|---|---|
|
||||
| **iPhone / iPad,A17 Pro 及以后**(iPhone 15 Pro 起、iPhone 16 起、M 系列芯片的 iPad) | 直接玩 | iOS 26 及以上用缺省的壳 / 缺省构建;iOS 18 – 25 用 iOS 18 的壳 / [老接口版](docs/OLDER_SYSTEMS.zh-CN.md) | 主力机型,日常在玩 |
|
||||
| **iPhone / iPad,A17 Pro 及以后**(iPhone 15 Pro 起、iPhone 16 起、M 系列芯片的 iPad) | 直接玩 | iOS 26 及以上用默认的壳 / 默认构建;iOS 18 – 25 用 iOS 18 的壳 / [旧接口版](docs/OLDER_SYSTEMS.zh-CN.md) | 主力机型,日常在玩 |
|
||||
| **iPhone Duo**(折叠屏) | 直接玩,展开、折叠时画面跟着换尺寸 | 发布页的壳已用 Xcode 27.1 出;自己用 Xcode 构建要用 27.1,内屏才能铺满(见 [docs/DEPENDENCIES.zh-CN.md](docs/DEPENDENCIES.zh-CN.md)) | v2.0 起支持。已在 Mac 上按 iPhone Duo 模拟器给出的内外屏尺寸来回切验过(模拟器本身跑不了游戏的图形层);拿到真机后会实测,有真机的玩家也欢迎开 Issue 告诉我们 |
|
||||
| **iPhone / iPad,A16 及更早**(iPhone 14 全系、iPhone 15 / 15 Plus、iPhone 13 系列等) | 可以玩,多一步 | 按 [docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md) 用自己的游戏文件做一份老机型补充包,做安装包时带上它;系统同上一行分 iOS 26 / iOS 18 – 25 | 已有玩家实测:iPhone 14 Pro Max(A16,6 GB)60 帧;iPhone 13 Pro Max(A15,6 GB)30 帧档 |
|
||||
| **4 GB 内存的设备**(如 iPad mini 第 6 代、iPad Air 第 4 代) | 能进游戏,内存很紧(在继续优化内存) | 同 A16 及更早那一行(带老机型补充包) | 已有玩家实测:iPad mini 6(A15,4 GB,iPadOS 27)第一幕实际玩了几分钟,画质自动降低后 50–58 帧,但一直收到系统内存告警、离系统内存上限只剩约 560 MB,怪多特效多的场景可能被系统结束;更早的版本上 iPad Air 4(A14,4 GB)启动几秒即被系统结束 |
|
||||
| **A14 芯片、6 GB 及以上内存**(如 iPhone 12 Pro / 12 Pro Max) | 尚无报告 | 同 A16 及更早那一行 | 欢迎试过的人开 Issue 告诉我们结果 |
|
||||
| **A13 及更早的芯片**(如 iPhone 11 系列、2020 年的 iPad Pro) | 不支持 | — | 图形芯片不支持 Metal 3(玩家在 iPad Pro A12Z 上实测;苹果依据见表上方);App 启动时会直接提示,不会闪退 |
|
||||
| **Mac,Apple 芯片** | 直接玩(原生 macOS App) | macOS 26 及以上用缺省出法;macOS 15 – 25 用[老接口出法](docs/OLDER_SYSTEMS.zh-CN.md)。键盘、鼠标、手柄都能玩,各自能做什么见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 已有玩家在 macOS 15.7.7 上实际玩过老接口版 |
|
||||
| **Mac,Apple 芯片** | 直接玩(原生 macOS App) | macOS 26 及以上用默认出法;macOS 15 – 25 用[旧接口出法](docs/OLDER_SYSTEMS.zh-CN.md)。键盘、鼠标、手柄都能玩,各自能做什么见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 已有玩家在 macOS 15.7.7 上实际玩过旧接口版 |
|
||||
| **Apple TV 4K(第三代 A15)** | 社区移植([@yinqingyan](https://github.com/yinqingyan),经作者同意按 MIT 许可贡献),开发者预览 | 照 [dm/tvos/README.md](dm/tvos/README.md) 构建并把游戏文件、老机型补充包拷进 App;只能在实机上跑,模拟器跑不了;存档放在系统可清理的 Caches 目录里 | 已在实机上到达职业选择画面;进游戏、手柄全键位、存档尚未验证,维护者没有实机测试过 |
|
||||
| **鸿蒙手机**(HarmonyOS NEXT,API 26) | 能玩(社区移植) | 发布页的未签名壳用自己的调试证书重签 + 用自己的游戏文件做的运行包,见 [docs/HARMONYOS.zh-CN.md](docs/HARMONYOS.zh-CN.md) | 作者实测:Mate 90 Pro Max 上重签、安装、导入、进局、保存退出走通 |
|
||||
| **安卓手机**(ARM64,Android 12 起,Vulkan 1.1) | 可以玩(社区移植) | 发布页的 APK + 用自己的游戏文件做的导入包,见 [docs/ANDROID.zh-CN.md](docs/ANDROID.zh-CN.md) | 合作者实测:Redmi K50 Ultra 中位 60 帧;OnePlus 13 能玩,偶有一瞬的小黑块;vivo X200 Ultra 上试玩过 |
|
||||
| **Intel 芯片的 Mac** | 不支持 | — | — |
|
||||
|
||||
**App 里弹的框是什么意思**
|
||||
@@ -213,13 +242,23 @@ flowchart LR
|
||||
|
||||
## 开始使用
|
||||
|
||||
两条路都要先有**你自己购买的游戏的文件**:Switch 版《暗黑破坏神 II:狱火重生》本体加「术士君临」资料片,更新到 1.0.34.0(主机上显示的版本号;它对应 PC 版的 3.3.94012,本仓库的目录名和工具里用的是后一个号)。本项目是按带这部资料片的版本做的,没有资料片的情况不支持、也没有验过。怎么准备见 [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md)。
|
||||
不管用哪种设备玩,都要先有**你自己购买的游戏的文件**:Switch 版《暗黑破坏神 II:狱火重生》本体加「术士君临」资料片,更新到 1.0.34.0(主机上显示的版本号;它对应 PC 版的 3.3.94012,本仓库的目录名和工具里用的是后一个号)。本项目是按带这部资料片的版本做的,没有资料片的情况不支持、也没有验过。怎么准备见 [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md)。
|
||||
|
||||
> 本项目只提供工具与不含任何游戏内容的安装壳。我们不提供、不认可、也不对任何第三方分发游戏资源、游戏主程序或含游戏内容的安装包的行为负责。请只使用你自己合法拥有的游戏文件。
|
||||
|
||||
本项目基于 Switch 版 1.0.34.0(对应 PC 版的 3.3.94012)实现并验证,工具默认只认这一版。已有社区用户反馈,参照仓库结构自行适配了其他版本并成功运行。规则表按游戏版本分组存放(`dm/tools/patch_nso.py` 里按主程序的构建标识分组),欢迎把你适配的版本提交回来。
|
||||
|
||||
**先对一下你的设备**:上面「支持哪些设备」那张表告诉你该用哪种构建、要不要多做一份老机型补充包。
|
||||
**先对一下你的设备**,按下表找到你该走的那一节;上面「支持哪些设备」那张表告诉你苹果设备该用哪种构建、要不要多做一份老机型补充包。
|
||||
|
||||
| 你的设备 | 怎么做 | 步骤 |
|
||||
|---|---|---|
|
||||
| iPhone / iPad,手上有 Apple 芯片的 Mac | 从源码完整构建 | 下面「有 Mac:三步」 |
|
||||
| iPhone / iPad,没有 Mac | 下载不含游戏内容的壳,在 Windows / Linux 上把游戏内容做进去 | 下面「没有 Mac:壳 + 做包工具」与 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md) |
|
||||
| Mac(Apple 芯片) | 出一个原生 macOS App | 下面「在 Mac 上直接玩」与 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) |
|
||||
| 安卓手机 | 装发布页的 APK,用电脑做一份导入包拷进手机 | 下面「安卓」与 [docs/ANDROID.zh-CN.md](docs/ANDROID.zh-CN.md) |
|
||||
| 鸿蒙手机 | 用自己的调试证书重签发布页的未签名壳,用电脑做一份运行包拷进手机 | 下面「鸿蒙」与 [docs/HARMONYOS.zh-CN.md](docs/HARMONYOS.zh-CN.md) |
|
||||
|
||||
iPhone / iPad 的两种做法对比:
|
||||
|
||||
| | 有 Mac | 没有 Mac |
|
||||
|---|---|---|
|
||||
@@ -255,7 +294,7 @@ flowchart LR
|
||||
|
||||
装到手机上第一次打开,App 会要「游戏资源文件夹」——就是游戏文件里的 18 个资源档案,怎么放见 [docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md) 的「手机上要放的那个游戏资源文件夹」一节。
|
||||
|
||||
`./setup.sh check` 是体检:逐项报告这台电脑、工具、游戏文件、签名配置的状态,缺的每一项都给出去哪拿和下一步命令,不做任何改动。手上是一整个游戏包(`.xci` / `.nsp`)时,`./setup.sh <游戏包> <prod.keys>` 会先把游戏文件取出来放到位再接着准备(要先装 hactool)。每次更新到新的提交之后都要再跑一遍 `./setup.sh`:它会按当前源码重出改写产物与着色器库(已是最新的步骤会跳过)。它还会改写仓库里三个随工具指纹变化的文件(`dm/gfx/tools/dmsh_chain.lock`、`dm/gfx/nvn/dmsh_chain.h`、`dm/gfx/nvn/c1_full.tsv`),这是预期的,不要提交它们。
|
||||
`./setup.sh check` 是体检:逐项报告这台电脑、工具、游戏文件、签名配置的状态,缺的每一项都给出去哪拿和下一步命令,不做任何改动。手上是一整个游戏包(`.xci` / `.nsp`)时,`./setup.sh <游戏包> <prod.keys>` 会先把游戏文件取出来放到位再接着准备(要先装 hactool);本体与更新是分开的两个包时两个都给:`./setup.sh <本体> <更新> <prod.keys>`。每次更新到新的提交之后都要再跑一遍 `./setup.sh`:它会按当前源码重出改写产物与着色器库(已是最新的步骤会跳过)。它还会改写仓库里三个随工具指纹变化的文件(`dm/gfx/tools/dmsh_chain.lock`、`dm/gfx/nvn/dmsh_chain.h`、`dm/gfx/nvn/c1_full.tsv`),这是预期的,不要提交它们。
|
||||
|
||||
### 在 Mac 上直接玩
|
||||
|
||||
@@ -269,6 +308,38 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
|
||||
界面用原版的手柄版界面。键盘:空格确认、Esc 返回、回车、`=` 键开菜单 / 新角色,W A S D 移动,其余手柄键各有对应。鼠标:点怪、NPC、物件会走过去交互,底部的技能格、药水格、按键提示、面板里的按钮和页签、建角时的职业、小地图都能点;点空地会走过去、按住一直走,点怪是攻击,物品的双击和拖放也认鼠标。用键盘时屏上的按键提示直接显示键盘键名。存档在这台 Mac 上(自己构建的 App 没有 iCloud 同步),可以从 iPhone / iPad 手工导入。键位表、建角怎么按、鼠标能做什么、导入步骤和已知不足,见 [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md)。键盘、实体手柄这几项还未经真人操作,你试过的话,请告诉我们结果。
|
||||
|
||||
### 安卓
|
||||
|
||||
不用 Mac、不用 adb、不用自己编 APK,Windows / Linux / Mac 电脑都行(目前在 Mac 上走通)。完整步骤、要装的工具和出错时怎么办见 [docs/ANDROID.zh-CN.md](docs/ANDROID.zh-CN.md)。
|
||||
|
||||
1. 准备游戏文件,和苹果版相同([docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md))。
|
||||
2. 在电脑上做导入包:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py <游戏文件的 Update 目录> <输出目录>
|
||||
```
|
||||
|
||||
3. 用 USB 把做出来的 `android` 文件夹和游戏资源 `data` 文件夹拷到手机的 `Download/S2X/D2R Mobile/`。
|
||||
4. 从[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载 `D2RMobile-android.apk` 装上,打开后允许「所有文件访问」,App 自己导入并进游戏。
|
||||
|
||||
源码要与 APK 同一个发布版本;换新版本时 APK 和导入包一起换,存档保留。想自己从源码编 APK 的,见 [dm/android/README.zh-CN.md](dm/android/README.zh-CN.md)。
|
||||
|
||||
### 鸿蒙
|
||||
|
||||
不用自己编应用。要有华为开发者账号和 DevEco Studio(用它带的签名工具与 `hdc`,也能自动生成调试证书、登记手机)。完整步骤、命令和出错时怎么办见 [docs/HARMONYOS.zh-CN.md](docs/HARMONYOS.zh-CN.md)。
|
||||
|
||||
1. 准备游戏文件,和苹果版相同([docs/GAME_FILES.zh-CN.md](docs/GAME_FILES.zh-CN.md))。
|
||||
2. 从[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载未签名壳 `D2RMobile-harmony-shell-unsigned.hap`,用自己的调试证书和 profile 重签(`hap-sign-tool sign-app`),再 `hdc install -r` 装到手机。
|
||||
3. 在电脑上做运行包:
|
||||
|
||||
```
|
||||
python3 dm/tools/d2rm_android.py --target ohos <游戏文件的 Update 目录> <输出目录>
|
||||
```
|
||||
|
||||
4. 在手机上建「D2R Mobile」文件夹,`data/` 放游戏资源、`dm/` 放上一步做出的运行包,打开应用点「导入」选这个文件夹。
|
||||
|
||||
源码要与壳是同一个发布版本;换新版本时用同一套签名重签新壳覆盖安装,存档保留。这几步由作者在 Mate 90 Pro Max 上走通。
|
||||
|
||||
### 没有 Mac:壳 + 做包工具
|
||||
|
||||
从本仓库的[发布页](https://github.com/jhaizhou-ops/d2r-mobile/releases)下载我们预先做好的、不含游戏内容的「壳」安装包(`D2RMobile-shell-build-input.zip`;iOS 18 – 25 用 `D2RMobile-shell-ios18-build-input.zip`),加上你自己的游戏文件,在 Windows 或 Linux 上做出安装包,再用自签工具签名装机。壳是做安装包的原料,不能直接装来玩(直接装上去只会弹框说明、不会进游戏);换新版本时要用新版的壳重新做一次安装包。只有走这条路时,因为做包的电脑上没有苹果的着色器编译器,手机**第一次启动**要花约 7 分钟把着色器编完(一次性,带进度条);用 Xcode 构建的包没有这一步。步骤与每一步的验证现状见 [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md)。
|
||||
@@ -278,10 +349,11 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
| 项 | 现状 |
|
||||
|---|---|
|
||||
| 联机 | 不在范围内,完全离线 |
|
||||
| 安卓版 | 几处 iOS 触屏细节(空技能格菜单、加点浮层、商店拖动跟手图)没做完,见上面「安卓版」 |
|
||||
| `.nsp` / `.xci` 两种游戏包 | 工具只核对主程序的版本,不区分包的格式;我们自己用 `.xci` 走过全程,有网友反馈 `.nsp` 格式的游戏包也完美兼容 |
|
||||
| 用自签工具(Sideloadly、AltStore 等)签名装机 | 没验过,欢迎开 Issue 告诉我们结果 |
|
||||
| Linux 上做包 | 没验过(Windows 与 Mac 上验过) |
|
||||
| 没升到 iOS 26 / macOS 26 的设备 | 可以玩,用老接口版(最低 iOS 18.0 / macOS 15.0):[docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md);完整的设备表见上面「支持哪些设备」 |
|
||||
| 没升到 iOS 26 / macOS 26 的设备 | 可以玩,用旧接口版(最低 iOS 18.0 / macOS 15.0):[docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md);完整的设备表见上面「支持哪些设备」 |
|
||||
| A16 及更早的机型(iPhone 14 系列、iPhone 15 / 15 Plus 等) | 可以玩,要多做一份老机型贴图包并带着它构建 App:[docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md)。App 提示「这台设备要多做一步」(旧版本显示的是「暂不支持本机型」)就是缺这一步 |
|
||||
| 物品注释里的「一句点评」与「旧译名对照」 | 两张内容表不随仓库提供,可自备,见 `dm/ios/tools/annot/README.zh-CN.md` |
|
||||
|
||||
@@ -291,11 +363,11 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
- 没验过的那几项,走通或走不通都值得告诉我们。
|
||||
- 想改代码:先跑通上面的测试入口,每次改动都要过回归闸门。
|
||||
|
||||
**往别的平台走:** 这套做法不限于 iPhone 和 iPad。Apple 芯片的 Mac 已经有了原生版本(见上面「在 Mac 上直接玩」),用的是同一份游戏程序和同一个宿主;Apple TV 也已有社区移植(开发者预览,见设备表)。安卓手机用的是同一类处理器,游戏程序同样可以原生执行,这条路完全走得通:要换的只是宿主和图形层对接的那一侧。作者手边没有安卓手机,非常期待看到有人把它带到安卓上。
|
||||
**往别的平台走:** 这套做法不限于 iPhone 和 iPad。Apple 芯片的 Mac 已经有了原生版本(见上面「在 Mac 上直接玩」),用的是同一份游戏程序和同一个宿主;Apple TV 也已有社区移植(开发者预览,见设备表)。安卓也已经走通了:v2.0 起有了社区移植的安卓版(见上面「安卓版」),用的是同一份宿主,只把图形层换成了 Vulkan;鸿蒙版也来了(见上面「鸿蒙版」),和安卓共用同一套 Vulkan 引擎。
|
||||
|
||||
**往别的游戏走:** 已经有人拿同一份宿主去试别的 Switch 游戏。宿主里有一些「iOS 上缺省就开」的行为是为这一个游戏写的,换游戏会先撞到它们,动手前先关掉或挪走:
|
||||
|
||||
- `dm/host/hle_oe.c`:三维渲染比例在 iOS 上缺省 0.75,`scale3d_tick` 按这个游戏渲染器里的偏移去改写——换一个游戏,那就是个野指针。
|
||||
- `dm/host/hle_oe.c`:三维渲染比例在手机上缺省 0.75(安卓 App 设成 0.85),`scale3d_tick` 按这个游戏渲染器里的偏移去改写——换一个游戏,那就是个野指针。
|
||||
- `dm/host/hle_fs.c`:首次启动预置共享仓库(`DM_STASH_SEED`)与触屏版缺省设置(`DM_TOUCH_DEFAULTS`),iOS 上缺省开。
|
||||
- `dm/host/main.c`:存档落盘节流改的是游戏程序里一个固定地址上的常数;`argv[0]` 写死成 `"D2R"`。
|
||||
- `dm/host/hle_time.c`:固定时刻的测试开关认的是游戏程序里的一个固定地址。
|
||||
@@ -318,9 +390,15 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
| [docs/NO_XCODE.zh-CN.md](docs/NO_XCODE.zh-CN.md) | 不用 Xcode、不用 Mac 的做法 |
|
||||
| [docs/MAC.zh-CN.md](docs/MAC.zh-CN.md) | 在 Mac 上玩:构建 macOS App、键位、已知不足 |
|
||||
| [docs/LEGACY_DEVICES.zh-CN.md](docs/LEGACY_DEVICES.zh-CN.md) | 老机型(A16 及更早):怎么做贴图包、怎么放进手机 |
|
||||
| [docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md) | 老系统(iOS 18 – 25、macOS 15 – 25):老接口版怎么出、和老机型贴图包怎么组合 |
|
||||
| [docs/OLDER_SYSTEMS.zh-CN.md](docs/OLDER_SYSTEMS.zh-CN.md) | 老系统(iOS 18 – 25、macOS 15 – 25):旧接口版怎么出、和老机型贴图包怎么组合 |
|
||||
| [docs/qa-rift-pet-life.zh-CN.md](docs/qa-rift-pet-life.zh-CN.md) | 大秘境随从生命的回归清单(哪些跑过、哪些还没人跑,欢迎补) |
|
||||
| [docs/DERIVED.zh-CN.md](docs/DERIVED.zh-CN.md) | 仓库里与游戏有关的东西:有什么、没有什么、为什么 |
|
||||
| [docs/ANDROID.zh-CN.md](docs/ANDROID.zh-CN.md) | 在安卓手机上玩:装 APK、做导入包、换新版本、出错时怎么办 |
|
||||
| [docs/HARMONYOS.zh-CN.md](docs/HARMONYOS.zh-CN.md) | 在鸿蒙手机上玩:重签未签名壳、做运行包、导入、出错时怎么办 |
|
||||
| [dm/harmony/README.zh-CN.md](dm/harmony/README.zh-CN.md) | 鸿蒙版:源码结构、构建命令、缺省设置与实测记录 |
|
||||
| [dm/android/README.zh-CN.md](dm/android/README.zh-CN.md) | 安卓版:源码结构、构建、要放进手机的文件、验收清单 |
|
||||
| [dm/gfx/vulkan/INTEGRATION.md](dm/gfx/vulkan/INTEGRATION.md) | Vulkan 图形层怎么接到共用的图形接口上 |
|
||||
| [docs/ANDROID_COLLABORATION.zh-CN.md](docs/ANDROID_COLLABORATION.zh-CN.md) | 安卓 / 鸿蒙协作:仓库分工、怎么参与、实测状态与待办;每一轮的开发笔记在 [docs/android-notes/](docs/android-notes/) |
|
||||
|
||||
## 声明
|
||||
|
||||
@@ -328,6 +406,12 @@ DM_MAC_M3=1 dm/tools/mac_app.sh # macOS 15 – 25:产出 D2R Mobile M3.ap
|
||||
|
||||
## 致谢
|
||||
|
||||
**v2.0 的安卓版来自三位社区作者,特别感谢:**
|
||||
|
||||
- **[@yyan160](https://github.com/yyan160)**(Yuechuan Yang):安卓移植本身([#113](https://github.com/jhaizhou-ops/d2r-mobile/pull/113))——安卓 App、JNI 宿主、触屏覆盖层、Vulkan 呈现、在真机上逐项测量的一整轮性能优化(Redmi K50 Ultra 的营地从 7.7 帧做到中位 60 帧),以及让共用宿主在苹果和安卓上都能编译运行的那批改动。审查里提的每个问题都在分支上逐条改好了。
|
||||
- **[@biglawine](https://github.com/biglawine)**:鸿蒙移植([#114](https://github.com/jhaizhou-ops/d2r-mobile/pull/114))和它的 NVN→Vulkan 回放引擎——安卓版的图形层就是从这里来的;还搭起了安卓 / 鸿蒙两端合作开发用的仓库,并为真机验证生成了着色器包。
|
||||
- **[@vickwv](https://github.com/vickwv)**:另一条独立的安卓移植([#112](https://github.com/jhaizhou-ops/d2r-mobile/pull/112))。它的思路在安卓版上逐项实测过,其中 3D 画面加亮的做法被采纳。
|
||||
|
||||
这个项目建立在下面这些开源工作之上,谢谢各位作者和维护者。
|
||||
|
||||
- **Ryujinx**(Ryubing 1.3.2,MIT):`dm/third_party/ryujinx` 原样内置了它的着色器翻译库(Ryujinx.Graphics.Shader、Spv.Generator、Ryujinx.Common 三个项目,未修改),用来把 Switch 原版着色器翻译成 SPIR-V。开发过程中,我们还用打了补丁的 Ryujinx 跑原版游戏,作为画面和游戏状态的对照参考(做法见 [dm/verify/README.zh-CN.md](dm/verify/README.zh-CN.md);构建和驱动它的脚本不在本仓库里)。
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
# 安卓宿主构建(NDK,arm64-v8a)。源文件清单不手抄:从 dm/host/Makefile 的 SRC / GFX / LIBDEFLATE 取(与 iOS 的 ios/tools/gen_build.py 同一思路),
|
||||
# 排除 Mac 专用(*_mac.*)、Objective-C(*.m,安卓另有实现)与 main.c(单独编:命令行 dmhost 用原名 main,App 的 libdm.so 以 -Dmain=dm_main 编)。
|
||||
# 汇编(Mach-O 写法)经 tools/asm_elf.py 转 ELF 后编;compat/ 只在安卓构建的头文件路径里,苹果构建看不到。
|
||||
#
|
||||
# 必需:-DDM_GEN_DIR=<目录>,内含由游戏文件生成的 dm_vault_tab.h / dm_hud_exp.h / dm_bright_levels.inc(生成方法同 dm/host/Makefile 对应规则,不入库)。
|
||||
# 产物:dmhost(命令行,adb shell 跑,开发验证用);libdm.so(App 的 JNI 宿主)。
|
||||
#
|
||||
# Android host build (NDK, arm64-v8a). The source list is not copied by hand: it is taken from SRC / GFX / LIBDEFLATE in dm/host/Makefile (the same idea as iOS's ios/tools/gen_build.py),
|
||||
# excluding Mac-only files (*_mac.*), Objective-C (*.m, Android has its own implementations) and main.c (built separately: the command-line dmhost keeps the name main, the App's libdm.so is built with -Dmain=dm_main).
|
||||
# Assembly (Mach-O syntax) is converted to ELF by tools/asm_elf.py before assembling; compat/ is only on the Android build's header path, invisible to Apple builds.
|
||||
#
|
||||
# Required: -DDM_GEN_DIR=<directory> containing dm_vault_tab.h / dm_hud_exp.h / dm_bright_levels.inc generated from the game files (generated as by the matching rules in dm/host/Makefile, not committed).
|
||||
# Outputs: dmhost (command line, run from adb shell, for development checks); libdm.so (the App's JNI host).
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(dm_android C CXX ASM)
|
||||
# 产物里不留本机路径(断言带的 __FILE__、调试信息里的源文件 / 生成目录 / NDK 路径都会编进 libdm.so,暴露用户名与目录结构):
|
||||
# 一律换成中性前缀。长的在前(构建目录在源码树里面)。发布包核对见 tools/shell_apk.sh。
|
||||
# No local paths in the products (__FILE__ in assertions and the source / generated / NDK paths in debug info all end up in libdm.so,
|
||||
# exposing the user name and directory layout): replace them with neutral prefixes, longer ones first (the build directory is inside
|
||||
# the source tree). The release package check is in tools/shell_apk.sh.
|
||||
get_filename_component(DM_PATH_ROOT ${CMAKE_CURRENT_SOURCE_DIR}/../.. ABSOLUTE)
|
||||
foreach(map "${CMAKE_BINARY_DIR}=build" "${DM_GEN_DIR}=gen" "${CMAKE_ANDROID_NDK}=ndk" "${DM_PATH_ROOT}=src")
|
||||
add_compile_options("-ffile-prefix-map=${map}")
|
||||
endforeach()
|
||||
add_subdirectory(../gfx/vulkan ${CMAKE_CURRENT_BINARY_DIR}/vulkan)
|
||||
|
||||
set(DM ${CMAKE_CURRENT_SOURCE_DIR}/..)
|
||||
set(HOST ${DM}/host)
|
||||
if(NOT DM_GEN_DIR OR NOT EXISTS ${DM_GEN_DIR}/dm_vault_tab.h)
|
||||
message(FATAL_ERROR "要 -DDM_GEN_DIR=<由游戏文件生成的宿主表头目录>(dm_vault_tab.h / dm_hud_exp.h / dm_bright_levels.inc,见 dm/host/Makefile)")
|
||||
endif()
|
||||
find_package(Python3 REQUIRED COMPONENTS Interpreter)
|
||||
|
||||
# App 与资源共享公开生成源码的指纹;输入清单由同一工具提供,变动会重新生成头文件。
|
||||
# The app and resources share a fingerprint of public generator inputs; one tool supplies the dependencies.
|
||||
set(DM_OVERLAY_TOOL ${DM}/ios/tools/overlay_contract.py)
|
||||
get_filename_component(DM_REPO_ROOT ${DM}/.. ABSOLUTE)
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${DM_OVERLAY_TOOL})
|
||||
execute_process(COMMAND ${Python3_EXECUTABLE} ${DM_OVERLAY_TOOL} --inputs
|
||||
OUTPUT_VARIABLE overlay_inputs RESULT_VARIABLE overlay_result OUTPUT_STRIP_TRAILING_WHITESPACE)
|
||||
if(NOT overlay_result EQUAL 0)
|
||||
message(FATAL_ERROR "Cannot read overlay contract dependencies")
|
||||
endif()
|
||||
string(REPLACE "\r\n" "\n" overlay_inputs "${overlay_inputs}")
|
||||
string(REPLACE "\n" ";" overlay_inputs "${overlay_inputs}")
|
||||
list(TRANSFORM overlay_inputs PREPEND "${DM_REPO_ROOT}/")
|
||||
set(DM_OVERLAY_HEADER ${CMAKE_CURRENT_BINARY_DIR}/dm_overlay_contract.h)
|
||||
add_custom_command(OUTPUT ${DM_OVERLAY_HEADER}
|
||||
COMMAND ${Python3_EXECUTABLE} ${DM_OVERLAY_TOOL} --repo-root ${DM_REPO_ROOT} --header ${DM_OVERLAY_HEADER}
|
||||
DEPENDS ${overlay_inputs} VERBATIM)
|
||||
|
||||
# Python 保留 Makefile 续行边界,避免 CMake 列表的反斜杠转义吞掉源码行。
|
||||
# Python preserves Makefile continuations instead of CMake list escaping joining them.
|
||||
set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${HOST}/Makefile ${CMAKE_CURRENT_SOURCE_DIR}/tools/host_sources.py)
|
||||
execute_process(COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/host_sources.py
|
||||
${HOST}/Makefile ${CMAKE_CURRENT_BINARY_DIR}/host_sources.cmake
|
||||
RESULT_VARIABLE parse_result)
|
||||
if(NOT parse_result EQUAL 0)
|
||||
message(FATAL_ERROR "Cannot parse host sources for Android")
|
||||
endif()
|
||||
include(${CMAKE_CURRENT_BINARY_DIR}/host_sources.cmake)
|
||||
file(GLOB HLE_SRCS CONFIGURE_DEPENDS ${HOST}/hle_*.c)
|
||||
file(GLOB GFX_SRCS CONFIGURE_DEPENDS ${DM}/gfx/*.c ${DM}/gfx/nvn/*.c ${DM}/gfx/tex/*.c)
|
||||
|
||||
# ---- 汇编:Mach-O → ELF | Assembly: Mach-O → ELF ----
|
||||
set(ASM_SRCS)
|
||||
foreach(s ${HOST}/entry.S ${DM}/gfx/nvn/nvn_entry.S ${DM}/gfx/nvn/nvn_thunks.S)
|
||||
get_filename_component(n ${s} NAME)
|
||||
set(out ${CMAKE_CURRENT_BINARY_DIR}/asm/${n})
|
||||
add_custom_command(OUTPUT ${out} COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/asm_elf.py ${s} ${out}
|
||||
DEPENDS ${s} ${CMAKE_CURRENT_SOURCE_DIR}/tools/asm_elf.py VERBATIM)
|
||||
list(APPEND ASM_SRCS ${out})
|
||||
endforeach()
|
||||
|
||||
set(ANDROID_SRCS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/front_android.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/touch_android.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/vulkan_present.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/compat/clonefile.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/compat/digest.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/compat/mach_thread.c
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/compat/mach_symbols.c
|
||||
${DM}/gfx/vulkan/nvn_vk.c)
|
||||
|
||||
# 技能索引由玩家资源在仓外生成;公共只读桥复用同一套身份与过期校验。
|
||||
# Generate the skill index outside the repository from the player's files; share identity and freshness checks.
|
||||
if(NOT EXISTS ${DM_GEN_DIR}/dm_touch_native_art.c)
|
||||
message(FATAL_ERROR "Generate native_art/generate.py <romfs> --output-dir <DM_GEN_DIR> first")
|
||||
endif()
|
||||
list(APPEND ANDROID_SRCS
|
||||
${DM}/ios/Sources/dm_touch_game_state.c
|
||||
${DM}/ios/Sources/dm_touch_game_identity.c
|
||||
${DM}/ios/Sources/dm_touch_game_bridge.c
|
||||
${DM_GEN_DIR}/dm_touch_native_art.c)
|
||||
|
||||
add_library(dmcore STATIC ${HOST_SRCS} ${HLE_SRCS} ${GFX_SRCS} ${LIBDEFLATE_SRCS} ${ASM_SRCS} ${ANDROID_SRCS})
|
||||
list(REMOVE_DUPLICATES HOST_SRCS)
|
||||
target_include_directories(dmcore PUBLIC ${HOST} ${DM}/gfx/nvn/include ${CMAKE_CURRENT_SOURCE_DIR}/compat/include ${DM_GEN_DIR})
|
||||
target_include_directories(dmcore PUBLIC ${DM}/ios/Sources)
|
||||
# 与 Makefile 同档优化(-O1 -g);dm_android_compat.h 强制包含;-fno-strict-aliasing 同苹果 clang 缺省行为下宿主对客体内存的读写习惯
|
||||
# Same optimization level as the Makefile (-O1 -g); dm_android_compat.h force-included; -fno-strict-aliasing matches the host's habit of reading and writing guest memory under Apple clang's default behaviour
|
||||
set(DM_CFLAGS -O1 -g -Wall -Wno-unused-function -fno-strict-aliasing -include ${CMAKE_CURRENT_SOURCE_DIR}/compat/include/dm_android_compat.h)
|
||||
target_compile_options(dmcore PUBLIC $<$<COMPILE_LANGUAGE:C>:${DM_CFLAGS} -std=gnu17>)
|
||||
target_link_libraries(dmcore PUBLIC dm_vulkan_engine aaudio android log m dl)
|
||||
|
||||
# 命令行宿主:main.c 原样 | Command-line host: main.c as is
|
||||
add_executable(dmhost ${HOST}/main.c)
|
||||
target_link_libraries(dmhost PRIVATE -Wl,--whole-archive dmcore -Wl,--no-whole-archive)
|
||||
target_link_options(dmhost PRIVATE -Wl,--no-undefined -Wl,-z,nostart-stop-gc -Wl,--export-dynamic) # 导出符号:崩溃回溯里 dladdr 能认出宿主函数 | export symbols: dladdr in crash backtraces can name host functions
|
||||
|
||||
# App 用的共享库:main.c 以 -Dmain=dm_main 编(同 iOS),JNI 入口 jni_android.c
|
||||
# Shared library for the App: main.c built with -Dmain=dm_main (as on iOS), JNI entry jni_android.c
|
||||
# 独立目标只重命名 App 入口,避免影响同目录的命令行目标。
|
||||
# Keep the renamed entry in a separate target: source properties would also
|
||||
# rename main in the command-line dmhost target in this directory.
|
||||
add_library(dm_app_main OBJECT ${HOST}/main.c)
|
||||
target_link_libraries(dm_app_main PRIVATE dmcore)
|
||||
target_compile_definitions(dm_app_main PRIVATE main=dm_main)
|
||||
add_library(dm SHARED $<TARGET_OBJECTS:dm_app_main> ${CMAKE_CURRENT_SOURCE_DIR}/jni_android.c ${CMAKE_CURRENT_SOURCE_DIR}/text_input_jni.c ${CMAKE_CURRENT_SOURCE_DIR}/touch_android_jni.c ${CMAKE_CURRENT_SOURCE_DIR}/overlay_validate.c ${DM_OVERLAY_HEADER})
|
||||
target_include_directories(dm PRIVATE ${CMAKE_CURRENT_BINARY_DIR})
|
||||
target_compile_definitions(dm PRIVATE $<$<CONFIG:Debug>:DM_ANDROID_DEBUG_ENV=1>)
|
||||
target_link_libraries(dm PRIVATE -Wl,--whole-archive dmcore -Wl,--no-whole-archive android)
|
||||
target_link_options(dm PRIVATE -Wl,--no-undefined -Wl,-z,nostart-stop-gc -Wl,-Bsymbolic) # 汇编按页寻址宿主全局(adrp + :lo12:):库内符号就地绑定,不许被抢占 | assembly addresses host globals by page (adrp + :lo12:): symbols bind locally inside the library and cannot be preempted
|
||||
@@ -0,0 +1,207 @@
|
||||
# Android port
|
||||
|
||||
中文:[README.zh-CN.md](README.zh-CN.md)
|
||||
|
||||
This is the ARM64 Android version. The APK links the shared host, the Vulkan
|
||||
replay engine, AAudio, a transparent touch overlay drawn the same way as iOS, and
|
||||
system text input. It has been played on real phones (camp, fights, panels, NPC
|
||||
dialogs); measurements are in `docs/android-notes/`. Players
|
||||
install the release APK and import their own game content: see "Installing as a
|
||||
player" below.
|
||||
|
||||
## Source layout
|
||||
|
||||
- `app/`: Java Activity, fullscreen SurfaceView, touch overlay, and Gradle app.
|
||||
- `jni_android.c`, `front_android.c`: startup, resource locations, lifecycle, and
|
||||
platform front-end interfaces.
|
||||
- `touch_android*`: bridge to the shared `dm/ios/Sources/dm_touch_controls.c` state
|
||||
machine; `text_input_jni.c` bridges synchronous guest prompts to Android dialogs.
|
||||
- `vulkan_present.*`: Android window ownership, swapchain, and presentation.
|
||||
- `../gfx/vulkan/`: NVN replay adapter and Vulkan engine.
|
||||
- `compat/`: Android implementations of the host's Apple platform interfaces.
|
||||
- `tools/`: source-list parsing, ELF assembly conversion, and localized resources.
|
||||
|
||||
## Installing as a player
|
||||
|
||||
The release page's `D2RMobile-android.apk` contains no game content (built by
|
||||
`dm/android/tools/shell_apk.sh`: the three tables generated from game files are
|
||||
replaced by stand-ins that read the imported `derived.tsv` at run time, as in the
|
||||
iOS shell). You make the game content on a computer from your own game files:
|
||||
|
||||
```sh
|
||||
python3 dm/tools/d2rm_android.py <Update directory of the Switch version 3.3.94012> <output directory>
|
||||
```
|
||||
|
||||
It rewrites the game program for Android, translates every shader into a Vulkan
|
||||
bundle, generates the touch overlay and a few data tables, and writes
|
||||
`<output directory>/android/`. The tools it needs are listed at the top of the
|
||||
script (Python packages, the .NET SDK, and `spirv-opt` / `spirv-val` / `glslc`
|
||||
from the Vulkan SDK); it reports anything missing.
|
||||
|
||||
Copy the whole `android` folder to `Download/S2X/D2R Mobile/` on the phone, and
|
||||
your game resources (the whole `RomFS/data` directory) to `data` in the same
|
||||
place. Open the App: when it finds a new import pack it copies it into the
|
||||
internal `files/dm/` (with progress; the first time takes a minute or two), then
|
||||
starts. The import pack must come from the same release as the App (the product
|
||||
code in `pack_info.txt` must equal the one built into the App); otherwise the App
|
||||
says so. After the import you can delete the `android` folder on the phone. The
|
||||
import pack contains game content; keep it to yourself.
|
||||
|
||||
## Build locally
|
||||
|
||||
The current configuration uses JDK 17 or newer, Gradle 9.8.1, Android SDK 36,
|
||||
NDK 29.0.14206865, CMake 3.31.6, and Python 3. ARM64 devices must support Android
|
||||
12/API 31 or newer and Vulkan 1.1 with the required device features. These are build/manifest requirements, not a
|
||||
claim that all matching devices have been tested. The first target is vivo X200
|
||||
Ultra (Android 16/API 36, Adreno 830).
|
||||
|
||||
Vulkan compatibility is selected from actual format features, not the Android version. Startup logs `format_feature_flags2` and `depth16_as_d24`; D16 is widened only when D16 lacks linear filtering and X8_D24 has all required uses. A Vulkan 1.1 version number alone does not establish compatibility. vivo should log `1 / 0`; the Redmi K50 Ultra (Adreno 730, Vulkan 1.1) logs `0 / 1` and runs this path.
|
||||
|
||||
Prepare your own game files according to the root setup documentation. Generate
|
||||
`dm_vault_tab.h`, `dm_hud_exp.h`, and `dm_bright_levels.inc` outside the repository
|
||||
using the rules in `dm/host/Makefile`. Set `ANDROID_HOME` and `ANDROID_SDK_ROOT` to
|
||||
the same SDK directory, and `JAVA_HOME` to the JDK. From the repository root:
|
||||
|
||||
```sh
|
||||
gradle -p dm/android :app:assembleDebug :app:lintDebug \
|
||||
-PdmGenDir=/absolute/path/to/private/generated/headers \
|
||||
-PdmPython=/absolute/path/to/python
|
||||
```
|
||||
|
||||
The APK is `dm/android/app/build/outputs/apk/debug/app-debug.apk`. Native linking
|
||||
uses `--no-undefined`. `-PdmPrebuiltJni=...` is a packaging-only fallback; it is not
|
||||
evidence that current native sources compile.
|
||||
|
||||
On Linux or WSL, `dm/android/docker/` runs the same build in a container with these
|
||||
versions pinned, so no Windows-side Python, NDK or CMake is needed:
|
||||
|
||||
```sh
|
||||
docker build -t dm-android-build:1 dm/android/docker
|
||||
DM_GEN_DIR=/absolute/path/to/private/generated/headers dm/android/docker/build.sh
|
||||
```
|
||||
|
||||
The script runs as your user and keeps the debug signing key in `~/.android-dm`; see
|
||||
its header for the mounts.
|
||||
|
||||
## Private runtime files
|
||||
|
||||
The APK and Git repository contain no game program, shaders, game art, or saves.
|
||||
The import pack provides them (see "Installing as a player"), and the App imports
|
||||
it into the internal directories below.
|
||||
|
||||
| Location | Contents |
|
||||
| --- | --- |
|
||||
| App internal `files/dm/out/` | `main` and `sdk` rewriter products generated with `DM_TARGET=android`, including patched modules, fixups, and gates |
|
||||
| App internal `files/dm/shaders/` | External `.xgs` bundles matching the game and Vulkan backend |
|
||||
| App internal `files/dm/overlay/` | Required CASC touch overlay, including `overlay.manifest`, generated from the matching source and the user's resources |
|
||||
| App internal `files/dm/overlay/touchart/`, `files/dm/overlay/hud_v4_ui/` | Skill atlases and their silver silhouettes, map icon, circle frame, bottom bar art, and the skill-button socket (the repository's `dm/ios/Sources/ControlArt/dm_mobile_socket.png`), staged by `stage_touch_assets.py`. The touch controls draw them the same way as iOS (`dm/ios/Sources/DmTouchControlArt.h`, `DmTouchOverlay.m`); the joystick is drawn in code |
|
||||
| Shared `Download/S2X/D2R Mobile/data/` | User's resource archives and `.build.config`; requires Android's all-files-access setting. When this directory does not exist but the earlier `Download/data/` does, the App keeps using `Download/data/` |
|
||||
| App internal `files/dm/derived.tsv`, `files/dm/pack_info.txt` | Data tables generated from game files (read at startup by the release APK without game content); the import pack's product code and creation time |
|
||||
| App internal `files/save/` | Saves; preserve during upgrades |
|
||||
| App internal `files/temp/`, `files/dm/boot.log` | Temporary files and appended startup logs |
|
||||
|
||||
The launcher uses external app-private `dm/` as a fallback if no internal main
|
||||
module exists. It checks required paths before startup; this check does not prove
|
||||
shader identity or resource compatibility. Use the debug application's `run-as`
|
||||
access to provision internal files, and overlay-install with the same signing
|
||||
key. Never uninstall or clear data as an upgrade step. Back up existing saves
|
||||
before device validation. Do not upload APKs or any of these private files to a PR.
|
||||
|
||||
The overlay generator `dm/ios/tools/gen_romfs_overlay.py` supports
|
||||
`DM_DESWIZZLE_LIB` for a locally compiled native texture helper. Its thin CASC
|
||||
output contains only changes and references the original archives; it must not
|
||||
replace the original resource directory.
|
||||
|
||||
### Shader bundles
|
||||
|
||||
`files/dm/shaders/` holds one `<key>.xgs` for each shader the game uses; the
|
||||
key is the first 16 hexadecimal digits of the SHA-256 of the shader's control
|
||||
section. A bundle is an XGS1 file: a header, the bindings, the vertex input
|
||||
locations, the c1 bytes, then the SPIR-V (`xbg_shader_header` in
|
||||
`dm/gfx/vulkan/engine/xbg_game.h`). The set tested so far has 6,931 bundles:
|
||||
|
||||
- **6,927 are translations of the game's own shaders.** They are derived from
|
||||
game files, so they stay out of Git, PRs and the APK. `dm/gfx/tools/dmsh_vk.py`
|
||||
makes them from start to finish: `dm/gfx/tools/dmsh_xlate` translates each
|
||||
shader to SPIR-V for Vulkan, the bindings are renumbered for the single
|
||||
descriptor set (original number × 6 + stage number), the capabilities for
|
||||
reading and writing storage images of unknown format are added, unused
|
||||
capabilities are trimmed, `<key>.vk.json` is exported, and the packing function
|
||||
of `pack_game_shaders.py` writes the bundle. The 6,927 bundles it makes are
|
||||
byte-for-byte identical to the tested ones made with biglawine's HarmonyOS
|
||||
shader pipeline (`dmsh_vk.py --compare <reference dir> <output dir>`).
|
||||
- **4 are the query kernels embedded in the main program** (`q_val0`,
|
||||
`q_val8`, `q_dlt0`, `q_dlt8`; Mac and iOS use the MSL versions in
|
||||
`dm/gfx/nvn/nvn_builtin.h`). They are hand-written, so they can be built from
|
||||
source: `python3 dm/gfx/tools/pack_builtin_queries.py --output <new
|
||||
directory>` compiles `dm/gfx/vulkan/kernels/builtin_queries.comp` with
|
||||
`glslc` (the NDK has it under `shader-tools/`) and writes the 4 files.
|
||||
|
||||
A bundle set can also carry `vk-pipeline-list.seed`. On a first launch, before
|
||||
`files/dm/vk-pipeline-list.bin` exists, the engine builds the pipelines the seed
|
||||
lists during start-up, so a first visit to the places it covers does not
|
||||
stutter while pipelines build. `dm/android/tools/merge_warm_lists.py` merges
|
||||
several devices' `files/dm/vk-pipeline-list.bin` into one seed. A seed only
|
||||
works with the bundles it was recorded with, so it ships with them. The
|
||||
measurements are in `docs/android-notes/2026-10-22-first-play-stutter.md`.
|
||||
|
||||
## Validation and remaining work
|
||||
|
||||
Run the root contribution checks, plus `:app:lintDebug`. The pure Java input
|
||||
checks can run without a device:
|
||||
|
||||
```sh
|
||||
javac -encoding UTF-8 -d /tmp/dm-input-tests \
|
||||
dm/android/app/src/main/java/com/xiaoboluo/d2r/TextInputRules.java \
|
||||
dm/android/tests/TextInputRulesTest.java
|
||||
java -cp /tmp/dm-input-tests com.xiaoboluo.d2r.TextInputRulesTest
|
||||
```
|
||||
|
||||
Device acceptance must separately record installation, genuine GPU output/FPS,
|
||||
character creation, entering a world, moving and stopping, NPC interaction,
|
||||
inventory/skills, sound, background/resume, and saving/reloading. Headless host
|
||||
FPS is not a rendering result. Metal GPU timing and scanout timestamps are not
|
||||
implemented by this backend; unavailable metrics must not be treated as zero cost.
|
||||
|
||||
The Vulkan bridge currently replays all draws and uses synchronous host
|
||||
translation (`DM_NVN_SYNC=1`); the upstream asynchronous path needs an independent
|
||||
object-lifetime audit. The presenter still waits for its queue each frame.
|
||||
Advanced iOS skill artwork, empty-slot skill menus, specialized quantity/stat
|
||||
popovers, and shop drag-follow visuals are incomplete. Generic controls and text
|
||||
input do not establish complete iOS parity. macOS/iOS regressions must be run on
|
||||
an Apple build host before upstream integration.
|
||||
|
||||
The overlay generator writes a source fingerprint and exact file hashes to `overlay.manifest`. The APK embeds the same generator-input fingerprint. Missing, incomplete, or mismatched overlays stop startup with a localized message before the host thread starts. Deploy the complete generated directory; do not copy a manifest onto old resources or generate one on the phone. Regenerate after generator/layout changes. This contract does not authenticate third-party resource downloads.
|
||||
|
||||
`gen_romfs_overlay.py` requests overlay-only assets: it skips the iOS skill atlas and its unused skill silhouettes. Full `gen_assets.ensure()` still requires them. Skill atlas validation compares dimensions and decoded RGBA pixels while retaining source sprite SHA256/MD5 checks. Generator subprocesses explicitly use UTF-8/LF and preserve an existing read-only resource adapter. Windows/Linux byte equality must still be verified with the same game input and tool versions.
|
||||
|
||||
Vulkan compatibility is selected from actual format features, not the Android version. Startup logs `format_feature_flags2` and `depth16_as_d24`; D16 is widened only when D16 lacks linear filtering and X8_D24 has all required uses. A Vulkan 1.1 version number alone does not establish compatibility. vivo should retain `1 / 0`; Redmi K50 Ultra needs separate device validation.
|
||||
# Current iOS touch controls
|
||||
|
||||
Android shares the upstream touch state machine and its read-only skill-binding observer. Generate the binding index and atlas PNGs from your own matching RomFS outside the checkout:
|
||||
|
||||
```
|
||||
python dm/ios/tools/native_art/generate.py <RomFS> --output-dir <external-native-art>
|
||||
```
|
||||
|
||||
Copy only `dm_touch_native_art.c` into the existing `DM_GEN_DIR`. CMake requires that external index alongside the existing generated host headers. After generating a fresh overlay and HUD, run:
|
||||
|
||||
```
|
||||
python dm/android/tools/stage_touch_assets.py --native-art <external-native-art>/TouchArt --hud <assets>/NativeHUD/v4/hud_v4_ui --overlay <candidate-overlay>
|
||||
```
|
||||
|
||||
Import the complete finalized candidate overlay. Skill PNGs and HUD images stay in the external resource payload; do not add them to Git or APK assets. The renderer reads them from the validated imported `files/dm/overlay` directory. `DM_NATIVE_ART_DIR=<external-native-art>` lets the native-art capture test verify the external index and pixels. The five navigation buttons remain enabled until the complete replacement inventory flow passes device validation.
|
||||
|
||||
## Debug performance controls
|
||||
|
||||
Only CMake's Debug configuration reads `<files>/dm/android-debug.env`; Release contains no reader or call. This file is separate from the game's general `env`. It accepts only `DM_3D_SCALE`, `DM_3D_SCALE_DYN` and `DM_3D_SCALE_FLOOR`, one `KEY=VALUE` per line. Blank lines, `#` comments and CRLF are accepted. Unknown or repeated keys, files over 4096 bytes, lines over 127 characters, non-finite or malformed numbers, invalid switches and a floor above the starting scale reject the whole file. Scale and floor range from 0.50 through 1.00; DYN is exactly 0 or 1. The log reports acceptance/rejection without values.
|
||||
|
||||
Defaults are a scale ceiling of 0.85 on Android (0.75 on the other phone platforms), dynamic scaling enabled, floor 0.60. For a fixed-scale A/B comparison, use:
|
||||
|
||||
```
|
||||
DM_3D_SCALE=0.75
|
||||
DM_3D_SCALE_DYN=0
|
||||
DM_3D_SCALE_FLOOR=0.60
|
||||
```
|
||||
|
||||
Synchronization stays enabled. The file cannot override synchronization, frame overlap or any other setting. The parser regression is `dm/android/tests/test_debug_env.c`; build and run it independently from the game.
|
||||
@@ -0,0 +1,128 @@
|
||||
# 安卓移植
|
||||
|
||||
English: [README.md](README.md)
|
||||
|
||||
这是 ARM64 安卓版。APK 接入了公用宿主、Vulkan 回放引擎、AAudio、与 iOS 同一套画法的透明触摸覆盖层及系统输入框,已在真机上玩过(营地、战斗、各面板、NPC 对话),实测数据在 `docs/android-notes/`。玩家装发布页的 APK、导入自己的游戏内容即可,见下面「玩家怎么装」。
|
||||
|
||||
## 源码结构
|
||||
|
||||
- `app/`:Java Activity、全屏 SurfaceView、触摸覆盖层及 Gradle 应用工程。
|
||||
- `jni_android.c`、`front_android.c`:启动、资源路径、生命周期及平台前端接口。
|
||||
- `touch_android*`:接入公用 `dm/ios/Sources/dm_touch_controls.c` 状态机;`text_input_jni.c` 将客体同步输入请求接到安卓系统对话框。
|
||||
- `vulkan_present.*`:安卓窗口引用、交换链及呈现。
|
||||
- `../gfx/vulkan/`:NVN 回放适配器和 Vulkan 引擎。
|
||||
- `compat/`:宿主 Apple 平台接口的安卓实现。
|
||||
- `tools/`:源码清单解析、ELF 汇编转换及本地化资源生成。
|
||||
|
||||
## 玩家怎么装
|
||||
|
||||
发布页的 `D2RMobile-android.apk` 不含任何游戏内容(由 `dm/android/tools/shell_apk.sh` 出:三张从游戏文件生成的表换成替身,运行时读导入的 `derived.tsv`,做法同 iOS 壳)。游戏内容用你自己的游戏文件在电脑上做:
|
||||
|
||||
```sh
|
||||
python3 dm/tools/d2rm_android.py <Switch 版 3.3.94012 的 Update 目录> <输出目录>
|
||||
```
|
||||
|
||||
它改写游戏程序(安卓目标)、把全部着色器翻成 Vulkan 包、生成触屏覆盖层与几张数据表,写出 `<输出目录>/android/`。需要的工具见脚本开头(Python 包、.NET SDK、Vulkan SDK 里的 `spirv-opt` / `spirv-val` / `glslc`),缺什么它会逐项报。
|
||||
|
||||
把这个 `android` 文件夹整个拷到手机的 `Download/S2X/D2R Mobile/` 下,游戏资源(`RomFS/data` 整个目录)拷成同一处的 `data`。打开 App:发现新的导入包就拷进内部目录 `files/dm/`(显示进度,第一次一两分钟),然后启动。导入包要与 App 同一版本(`pack_info.txt` 里的产物代号与 App 编入的相同),不同时 App 会说明。导入完,手机上的 `android` 文件夹可以删掉;导入包里有游戏内容,只给自己用。
|
||||
|
||||
## 本地构建
|
||||
|
||||
当前配置使用 JDK 17 或更新版本、Gradle 9.8.1、Android SDK 36、NDK 29.0.14206865、CMake 3.31.6 和 Python 3。ARM64 设备要求 Android 12/API 31 或更新系统及具备所需设备能力的 Vulkan 1.1。这些是构建和清单要求,不代表符合条件的机型都已验证。首台目标是 vivo X200 Ultra(Android 16/API 36、Adreno 830)。
|
||||
|
||||
按根目录准备说明提供自己的游戏文件。参考 `dm/host/Makefile` 的规则,在仓外生成 `dm_vault_tab.h`、`dm_hud_exp.h`、`dm_bright_levels.inc`。`ANDROID_HOME` 与 `ANDROID_SDK_ROOT` 必须指向同一个 SDK,`JAVA_HOME` 指向 JDK。在仓库根目录执行:
|
||||
|
||||
```sh
|
||||
gradle -p dm/android :app:assembleDebug :app:lintDebug \
|
||||
-PdmGenDir=/absolute/path/to/private/generated/headers \
|
||||
-PdmPython=/absolute/path/to/python
|
||||
```
|
||||
|
||||
APK 位于 `dm/android/app/build/outputs/apk/debug/app-debug.apk`,原生链接启用 `--no-undefined`。`-PdmPrebuiltJni=...` 只供使用已有库打包,不是当前原生源码编译通过的证据。
|
||||
|
||||
在 Linux 或 WSL 上,可用 `dm/android/docker/` 在容器里跑同一构建,上述版本均已钉死,不需要在 Windows 侧装 Python、NDK 或 CMake:
|
||||
|
||||
```sh
|
||||
docker build -t dm-android-build:1 dm/android/docker
|
||||
DM_GEN_DIR=/绝对路径/私有生成表头目录 dm/android/docker/build.sh
|
||||
```
|
||||
|
||||
脚本以当前用户身份运行,调试签名钥匙保存在 `~/.android-dm`;挂载说明见脚本开头。
|
||||
|
||||
## 仓外运行材料
|
||||
|
||||
APK 和 Git 仓库均不含游戏程序、着色器、游戏美术或存档。这些由导入包提供(见「玩家怎么装」),App 导入到下表的内部目录。
|
||||
|
||||
| 位置 | 内容 |
|
||||
| --- | --- |
|
||||
| 应用内部 `files/dm/out/` | 使用 `DM_TARGET=android` 生成的 `main`、`sdk` 改写产物,含 patched 模块、fixups 和 gates |
|
||||
| 应用内部 `files/dm/shaders/` | 与游戏及 Vulkan 后端匹配的仓外 `.xgs` 包 |
|
||||
| 应用内部 `files/dm/overlay/` | 必需 CASC 触摸覆盖层,含 `overlay.manifest`,由匹配源码及用户资源生成 |
|
||||
| 应用内部 `files/dm/overlay/touchart/`、`files/dm/overlay/hud_v4_ui/` | 由 `stage_touch_assets.py` 放入的技能图集及其银色剪影、地图图标、圆框、底栏素材,以及技能钮底座(仓库的 `dm/ios/Sources/ControlArt/dm_mobile_socket.png`)。触屏控件与 iOS 同一套画法(`dm/ios/Sources/DmTouchControlArt.h`、`DmTouchOverlay.m`),摇杆用代码画 |
|
||||
| 共享 `Download/S2X/D2R Mobile/data/` | 用户资源档案及 `.build.config`,需要安卓“所有文件访问”授权;没有这个目录、而早先的 `Download/data/` 在时,App 沿用 `Download/data/` |
|
||||
| 应用内部 `files/dm/derived.tsv`、`files/dm/pack_info.txt` | 从游戏文件生成的数据表(不含游戏内容的发布包启动时读);导入包的产物代号与生成时刻 |
|
||||
| 应用内部 `files/save/` | 存档,升级时必须保留 |
|
||||
| 应用内部 `files/temp/`、`files/dm/boot.log` | 临时文件及追加写入的启动日志 |
|
||||
|
||||
内部没有主程序时,启动器回退到应用外部私有目录下的 `dm/`。启动前会检查必要路径,但不能据此证明着色器身份及资源兼容性。调试包可使用 `run-as` 导入内部文件,升级使用相同签名覆盖安装,不以卸载或清数据作为升级步骤。真机验证前备份已有存档,不向 PR 上传 APK 或上述私人文件。
|
||||
|
||||
覆盖层生成器 `dm/ios/tools/gen_romfs_overlay.py` 支持用 `DM_DESWIZZLE_LIB` 指定本地编译的纹理处理库。生成的精简 CASC 只含变更并引用原资源,不得替换原始资源目录。
|
||||
|
||||
### 着色器包
|
||||
|
||||
`files/dm/shaders/` 里,游戏用到的每个着色器各有一个 `<键>.xgs`;键是该着色器控制段 SHA-256 的前 16 位十六进制。包是 XGS1 文件:文件头、各绑定、顶点输入位置、c1 字节,然后是 SPIR-V(`dm/gfx/vulkan/engine/xbg_game.h` 的 `xbg_shader_header`)。目前测试用的一套共 6,931 个包:
|
||||
|
||||
- **6,927 个是游戏自己着色器的翻译。** 它们出自游戏文件,所以不进 Git、PR 和 APK。`dm/gfx/tools/dmsh_vk.py` 从头做出它们:用 `dm/gfx/tools/dmsh_xlate` 翻成面向 Vulkan 的 SPIR-V,绑定号改成单描述符集的编号(原号 × 6 + 阶段号)、补上「未定格式」存储图像读写的能力、裁掉多余能力,导出 `<键>.vk.json`,再用 `pack_game_shaders.py` 的打包函数写成包。做出的 6,927 个包与 biglawine 鸿蒙着色器流程做出的测试包逐字节相同(`dmsh_vk.py --compare <参考目录> <输出目录>`)。
|
||||
- **4 个是 main 程序本体内嵌的查询核**(`q_val0`、`q_val8`、`q_dlt0`、`q_dlt8`;Mac 与 iOS 用 `dm/gfx/nvn/nvn_builtin.h` 里的 MSL 版)。它们是手写的,能从源码做:`python3 dm/gfx/tools/pack_builtin_queries.py --output <新目录>` 用 `glslc`(NDK 的 `shader-tools/` 下就有)编译 `dm/gfx/vulkan/kernels/builtin_queries.comp`,写出这 4 个文件。
|
||||
|
||||
一套包还可以附带 `vk-pipeline-list.seed`。首次启动、还没有 `files/dm/vk-pipeline-list.bin` 时,引擎在启动期间编好种子里列出的管线,种子覆盖的地方第一次去就不会因为现编管线而卡。`dm/android/tools/merge_warm_lists.py` 把几台设备的 `files/dm/vk-pipeline-list.bin` 合成一个种子。种子只能和录它时的那套包一起用,所以随包发放。实测见 `docs/android-notes/2026-10-22-first-play-stutter.zh-CN.md`。
|
||||
|
||||
## 验证与剩余工作
|
||||
|
||||
执行根目录贡献检查及 `:app:lintDebug`。纯 Java 输入测试不需要手机:
|
||||
|
||||
```sh
|
||||
javac -encoding UTF-8 -d /tmp/dm-input-tests \
|
||||
dm/android/app/src/main/java/com/xiaoboluo/d2r/TextInputRules.java \
|
||||
dm/android/tests/TextInputRulesTest.java
|
||||
java -cp /tmp/dm-input-tests com.xiaoboluo.d2r.TextInputRulesTest
|
||||
```
|
||||
|
||||
真机验收须分别记录安装、真实 GPU 出图/帧率、建角、进局、移动停止、NPC 交互、背包/技能、声音、后台恢复及保存重进。无窗口宿主帧率不等于渲染帧率。本后端尚未接入 Metal GPU 计时及实际扫描显示时间,缺失读数不能当作零耗时。
|
||||
|
||||
Vulkan 当前每次全画,并使用同步宿主翻译(`DM_NVN_SYNC=1`);上游新增异步路径需独立审计对象生命周期。呈现层仍逐帧等待队列。iOS 技能图、空技能槽菜单、专用数量/属性加点浮层及商店拖动跟随图尚未完整实现,通用控件和系统输入框不代表完整 iOS 功能对齐。提交上游集成前,还须在 Apple 构建机上验证 macOS/iOS 回归。
|
||||
|
||||
覆盖层生成器将源码指纹和逐文件哈希写入 `overlay.manifest`,APK 编入同一生成器输入指纹。缺失、不完整或不匹配时,启动界面提示并在宿主线程启动前退出启动流程。须部署完整生成目录,不可把新清单贴到旧资源上,也不可在手机启动时补清单;生成器或布局修改后应重新生成。这项校验不负责认证第三方下载来源。
|
||||
|
||||
`gen_romfs_overlay.py` 显式请求只生成 overlay 所需资产,跳过 iOS 技能图集及未使用的技能剪影;完整 `gen_assets.ensure()` 仍要求这些产物。技能图集改核尺寸和解码 RGBA 像素,保留原 sprite SHA256/MD5。生成子进程显式使用 UTF-8/LF,并保留已有只读资源适配器;Windows/Linux 的字节一致性仍须以同一游戏输入和工具版本实测。
|
||||
|
||||
Vulkan 兼容路径按实际格式能力选择,不根据 Android 版本推断。启动日志记录 `format_feature_flags2` 与 `depth16_as_d24`;仅 D16 缺线性过滤且 X8_D24 满足全部用途时拓宽深度格式。Vulkan 1.1 版本号本身不等于兼容通过;vivo 应保持 `1 / 0`,Redmi K50 Ultra 仍需单独真机验证。
|
||||
# 当期iOS触控
|
||||
|
||||
安卓复用上游触控状态机及只读技能绑定观测桥。用自己的匹配RomFS在仓外生成绑定索引和图集PNG:
|
||||
|
||||
```
|
||||
python dm/ios/tools/native_art/generate.py <RomFS> --output-dir <仓外native-art>
|
||||
```
|
||||
|
||||
只把`dm_touch_native_art.c`复制到现有`DM_GEN_DIR`。CMake要求该仓外索引与原有宿主生成头同时存在。生成新的overlay和HUD后执行:
|
||||
|
||||
```
|
||||
python dm/android/tools/stage_touch_assets.py --native-art <仓外native-art>/TouchArt --hud <assets>/NativeHUD/v4/hud_v4_ui --overlay <候选overlay>
|
||||
```
|
||||
|
||||
导入完整且已生成最终manifest的候选overlay。技能PNG和HUD图像留在外部资源载荷,不加Git或APK assets;绘制层从已校验导入的`files/dm/overlay`读取。设置`DM_NATIVE_ART_DIR=<仓外native-art>`可让素材采图测试核验仓外索引和像素。五个导航键保留,等完整替代背包流程通过真机验证后再调整。
|
||||
|
||||
## Debug性能参数
|
||||
|
||||
仅CMake的Debug配置读取`<files>/dm/android-debug.env`,Release不包含读取函数或调用。它与游戏通用`env`不同,只接受`DM_3D_SCALE`、`DM_3D_SCALE_DYN`、`DM_3D_SCALE_FLOOR`,每行一个`KEY=VALUE`。支持空行、`#`注释及CRLF;未知/重复键、文件超过4096字节、行超过127字符、非有限值/错误数字、非法开关、下限高于起点均整份拒绝。起点和下限范围为0.50至1.00,DYN只允许0或1。日志仅记录接受/拒绝,不输出数值。
|
||||
|
||||
安卓默认比例上限0.85(其他手机平台0.75)、动态比例开启、下限0.60。固定比例A/B对照示例:
|
||||
|
||||
```
|
||||
DM_3D_SCALE=0.75
|
||||
DM_3D_SCALE_DYN=0
|
||||
DM_3D_SCALE_FLOOR=0.60
|
||||
```
|
||||
|
||||
同步仍开启;此文件不能覆盖同步、帧重叠或其他设置。解析器回归位于`dm/android/tests/test_debug_env.c`,可独立于游戏构建运行。
|
||||
@@ -0,0 +1,69 @@
|
||||
// 安卓 App。原生库两种来法:
|
||||
// 缺省:externalNativeBuild 用 dm/android/CMakeLists.txt 现编(要 -PdmGenDir=<由游戏文件生成的宿主表头目录>,见该文件头);
|
||||
// -PdmPrebuiltJni=<目录>:直接打包已编好的 <目录>/arm64-v8a/libdm.so(构建机上 CMake 不可用时)。
|
||||
// -PdmAppId=<包名>:换一个包名装(与别人签名的同名包并排装来对照时用;缺省 com.xiaoboluo.d2r)。
|
||||
// Android App. Two ways to get the native library:
|
||||
// default: externalNativeBuild builds it with dm/android/CMakeLists.txt (needs -PdmGenDir=<directory of host headers generated from the game files>, see that file's header);
|
||||
// -PdmPrebuiltJni=<dir>: package the already built <dir>/arm64-v8a/libdm.so directly (when CMake is unavailable on the build machine).
|
||||
// -PdmAppId=<id>: install under another application id (to sit beside a same-name package signed by someone else; default com.xiaoboluo.d2r).
|
||||
plugins { id 'com.android.application' }
|
||||
|
||||
def prebuilt = project.findProperty('dmPrebuiltJni')
|
||||
|
||||
// 启动文案取自统一中英表,生成目录只在 build 下,不入库。
|
||||
// Startup text comes from the shared table; generated resources stay under build.
|
||||
def startupStrings = layout.buildDirectory.dir('generated/androidStrings')
|
||||
def generateStartupStrings = tasks.register('generateStartupStrings', Exec) {
|
||||
inputs.files('../tools/gen_strings.py', '../../i18n/ui_text.tsv', '../../ios/tools/dm_i18n.py')
|
||||
outputs.dir(startupStrings)
|
||||
commandLine(project.findProperty('dmPython') ?: 'python3', '../tools/gen_strings.py', '--output', startupStrings.get().asFile)
|
||||
}
|
||||
|
||||
// 复用仓库现有 iOS 图标,生成安卓资源,不重复提交图片。
|
||||
// Reuse the existing iOS icon as a generated Android resource without duplicating the image.
|
||||
def launcherIcon = layout.buildDirectory.dir('generated/launcherIcon')
|
||||
def generateLauncherIcon = tasks.register('generateLauncherIcon', Copy) {
|
||||
from('../../ios/Assets.xcassets/AppIcon.appiconset/AppIcon1024.png')
|
||||
into(launcherIcon.map { it.dir('mipmap-nodpi') })
|
||||
rename { 'ic_launcher.png' }
|
||||
}
|
||||
|
||||
android {
|
||||
namespace 'com.xiaoboluo.d2r'
|
||||
compileSdk 36
|
||||
ndkVersion '29.0.14206865'
|
||||
defaultConfig {
|
||||
applicationId project.findProperty('dmAppId') ?: 'com.xiaoboluo.d2r'
|
||||
// 产物代号(dm/PRODUCT 首行):导入包的 pack_info.txt 要与它相同(DmActivity.ensureImported)
|
||||
// Product code (first line of dm/PRODUCT): an import pack's pack_info.txt must match it (DmActivity.ensureImported)
|
||||
buildConfigField 'String', 'DM_PRODUCT', "\"${file('../../PRODUCT').readLines()[0].trim()}\""
|
||||
minSdk 31
|
||||
targetSdk 36
|
||||
// 跟发布版本走:versionName = 发布版本号,versionCode = 主 × 10000 + 次 × 100 + 修订(2.0.0 → 20000),只增不减,旧版才能被覆盖升级
|
||||
// Follows the release: versionName = release version, versionCode = major × 10000 + minor × 100 + patch (2.0.0 → 20000), only ever increasing so older installs upgrade in place
|
||||
versionCode 20000
|
||||
versionName '2.0.0'
|
||||
ndk { abiFilters 'arm64-v8a' }
|
||||
if (!prebuilt) externalNativeBuild { cmake {
|
||||
arguments "-DDM_GEN_DIR=${project.findProperty('dmGenDir') ?: ''}"
|
||||
if (project.findProperty('dmPython')) arguments "-DPython3_EXECUTABLE=${project.property('dmPython')}"
|
||||
targets 'dm'
|
||||
} }
|
||||
}
|
||||
if (!prebuilt) externalNativeBuild { cmake { path '../CMakeLists.txt'; version '3.31.6' } }
|
||||
if (prebuilt) sourceSets { main { jniLibs.srcDirs = [prebuilt] } }
|
||||
sourceSets { main { res.srcDir(startupStrings.get().asFile); res.srcDir(launcherIcon.get().asFile) } }
|
||||
packaging { jniLibs { useLegacyPackaging false; keepDebugSymbols += ['**/*.so'] } }
|
||||
buildFeatures { buildConfig true }
|
||||
// 正式版签名:钥匙不进仓库,路径与密码从环境变量来(tools/shell_apk.sh release 读本机 ~/.config/dm-android/release.env);没设就不签
|
||||
// Release signing: the key never goes into the repository; path and password come from the environment (tools/shell_apk.sh release reads the
|
||||
// local ~/.config/dm-android/release.env); unsigned when not set
|
||||
def releaseKey = System.getenv('DM_ANDROID_KEYSTORE')
|
||||
if (releaseKey) signingConfigs { release {
|
||||
storeFile file(releaseKey); storeType 'pkcs12'
|
||||
storePassword System.getenv('DM_ANDROID_KEY_PASS'); keyAlias System.getenv('DM_ANDROID_KEY_ALIAS'); keyPassword System.getenv('DM_ANDROID_KEY_PASS')
|
||||
} }
|
||||
buildTypes { release { minifyEnabled false; if (releaseKey) signingConfig signingConfigs.release } }
|
||||
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17 }
|
||||
}
|
||||
tasks.named('preBuild').configure { dependsOn(generateStartupStrings, generateLauncherIcon) }
|
||||
@@ -0,0 +1,45 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 只要一个权限:所有文件访问(读玩家放在 Download/S2X/D2R Mobile/data 的游戏资源)。不联网、不要别的权限。 -->
|
||||
<!-- Only one permission: all files access (to read the game resources the player puts in Download/S2X/D2R Mobile/data). No network, no other permissions. -->
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
|
||||
<uses-feature android:name="android.hardware.vulkan.version" android:version="0x401000" android:required="true" />
|
||||
<application
|
||||
android:label="@string/dmAndroidName"
|
||||
android:icon="@mipmap/ic_launcher"
|
||||
android:roundIcon="@mipmap/ic_launcher"
|
||||
android:hasFragileUserData="true"
|
||||
android:appCategory="game"
|
||||
android:isGame="true"
|
||||
android:allowBackup="false"
|
||||
android:theme="@android:style/Theme.DeviceDefault.NoActionBar.Fullscreen">
|
||||
<activity
|
||||
android:name=".DmActivity"
|
||||
android:exported="true"
|
||||
android:screenOrientation="sensorLandscape"
|
||||
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboard|keyboardHidden|navigation|uiMode|density"
|
||||
android:resizeableActivity="false"
|
||||
android:launchMode="singleTask">
|
||||
<intent-filter>
|
||||
<action android:name="android.intent.action.MAIN" />
|
||||
<category android:name="android.intent.category.LAUNCHER" />
|
||||
</intent-filter>
|
||||
</activity>
|
||||
<receiver android:name=".widget.HeroWidget2x2Provider"
|
||||
android:exported="false" android:label="@string/dmAndroidWidgetName2x2">
|
||||
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_2x2_info" />
|
||||
<meta-data android:name="vivo_widget" android:value="true" />
|
||||
<meta-data android:name="vivoWidgetVersion" android:value="1" />
|
||||
<meta-data android:name="vivo.widget.description" android:resource="@string/dmAndroidWidgetDescription" />
|
||||
</receiver>
|
||||
<receiver android:name=".widget.HeroWidget4x2Provider"
|
||||
android:exported="false" android:label="@string/dmAndroidWidgetName4x2">
|
||||
<intent-filter><action android:name="android.appwidget.action.APPWIDGET_UPDATE" /></intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_4x2_info" />
|
||||
<meta-data android:name="vivo_widget" android:value="true" />
|
||||
<meta-data android:name="vivoWidgetVersion" android:value="1" />
|
||||
<meta-data android:name="vivo.widget.description" android:resource="@string/dmAndroidWidgetDescription" />
|
||||
</receiver>
|
||||
</application>
|
||||
</manifest>
|
||||
@@ -0,0 +1,407 @@
|
||||
// 安卓外壳:一个全屏横屏的 SurfaceView,原生层(libdm.so,dm/android/jni_android.c)跑宿主与游戏。
|
||||
// 对应 iOS 的 main.m(启动链)与 front_ios.m(视图、触屏、生命周期);本类只做系统对接,游戏逻辑与界面都在原生层。
|
||||
// Android shell: a full-screen landscape SurfaceView; the native layer (libdm.so, dm/android/jni_android.c) runs the host and the game.
|
||||
// Counterpart of iOS's main.m (startup chain) and front_ios.m (view, touch, lifecycle); this class only does system integration, game logic and UI are all in the native layer.
|
||||
package com.xiaoboluo.d2r;
|
||||
|
||||
import android.app.Activity;
|
||||
import android.app.AlertDialog;
|
||||
import android.content.Intent;
|
||||
import android.net.Uri;
|
||||
import android.hardware.display.DisplayManager;
|
||||
import android.os.Bundle;
|
||||
import android.os.Environment;
|
||||
import android.provider.Settings;
|
||||
import android.system.ErrnoException;
|
||||
import android.system.Os;
|
||||
import android.text.Editable;
|
||||
import android.text.InputType;
|
||||
import android.text.SpanWatcher;
|
||||
import android.text.Spannable;
|
||||
import android.text.Spanned;
|
||||
import android.text.TextWatcher;
|
||||
import android.view.inputmethod.BaseInputConnection;
|
||||
import android.view.SurfaceHolder;
|
||||
import android.view.SurfaceView;
|
||||
import android.view.View;
|
||||
import android.view.WindowInsets;
|
||||
import android.view.WindowInsetsController;
|
||||
import android.view.WindowManager;
|
||||
import android.widget.TextView;
|
||||
import android.widget.EditText;
|
||||
import android.widget.FrameLayout;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.ref.WeakReference;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.Locale;
|
||||
|
||||
public class DmActivity extends Activity implements SurfaceHolder.Callback, DisplayManager.DisplayListener {
|
||||
static native int nativeStart(String filesDir, String extDir, String romfsSrc, String lang);
|
||||
static native void nativeSurface(Object surface, int w, int h);
|
||||
static native void nativeRefresh(float hz);
|
||||
static native void nativeTouch(int n, int[] ids, float[] xs, float[] ys);
|
||||
static native void nativeFocus(int ev);
|
||||
static native void nativeTextResult(long id, boolean accepted, String text);
|
||||
|
||||
private static WeakReference<DmActivity> current = new WeakReference<>(null);
|
||||
private static volatile int bootFailure;
|
||||
private AlertDialog inputDialog;
|
||||
|
||||
private SurfaceView view;
|
||||
private FrameLayout gameFrame;
|
||||
private TouchOverlay touchOverlay;
|
||||
private boolean started;
|
||||
private boolean importing;
|
||||
private boolean libraryLoaded;
|
||||
private boolean resumed;
|
||||
private DisplayManager displays;
|
||||
|
||||
@Override protected void onCreate(Bundle b) {
|
||||
super.onCreate(b);
|
||||
// 调试包:am start … --ez dmArtDump true 只把触屏控件底图写到 files/dm/artdump/ 就退出(dm/android/tools/art_compare.sh 用)
|
||||
// Debug builds: am start … --ez dmArtDump true only writes the touch control art to files/dm/artdump/ and exits (used by dm/android/tools/art_compare.sh)
|
||||
if (BuildConfig.DEBUG && getIntent().getBooleanExtra("dmArtDump", false)) {
|
||||
try { new TouchOverlay(this, null, null).dumpArt(new File(getFilesDir(), "dm/artdump")); } catch (IOException e) { android.util.Log.e("dm", "art dump: " + e); }
|
||||
finish(); return;
|
||||
}
|
||||
current = new WeakReference<>(this);
|
||||
displays = getSystemService(DisplayManager.class);
|
||||
if (displays != null) displays.registerDisplayListener(this, null);
|
||||
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
|
||||
getWindow().getAttributes().layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS;
|
||||
view = new SurfaceView(this);
|
||||
view.getHolder().addCallback(this);
|
||||
gameFrame = new FrameLayout(this);
|
||||
gameFrame.addView(view, new FrameLayout.LayoutParams(-1, -1));
|
||||
setContentView(gameFrame);
|
||||
immersive();
|
||||
}
|
||||
|
||||
private void immersive() {
|
||||
WindowInsetsController c = getWindow().getInsetsController();
|
||||
if (c != null) { c.hide(WindowInsets.Type.systemBars()); c.setSystemBarsBehavior(WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE); }
|
||||
}
|
||||
|
||||
// 资源在玩家放的位置读(缺省 Download/S2X/D2R Mobile/data),要「所有文件访问」权限;没有就引导去系统设置页,回来再启动
|
||||
// Resources are read where the player put them (default Download/S2X/D2R Mobile/data), which needs "all files access"; without it, guide the player to the system settings page and start after returning
|
||||
private boolean ensureFileAccess() {
|
||||
if (Environment.isExternalStorageManager()) return true;
|
||||
TextView t = new TextView(this);
|
||||
t.setText(R.string.dmAndroidPermission);
|
||||
t.setTextSize(20); t.setPadding(64, 64, 64, 64);
|
||||
t.setOnClickListener(v -> startActivity(new Intent(Settings.ACTION_MANAGE_APP_ALL_FILES_ACCESS_PERMISSION, Uri.parse("package:" + getPackageName()))));
|
||||
setContentView(t);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 导入包:玩家在电脑上用 dm/tools/d2rm_android.py 和自己的游戏文件做出 android 文件夹,拷到 Download/S2X/D2R Mobile/ 下;
|
||||
// 这里把它拷进内部目录 files/dm/(out、shaders、overlay、derived.tsv、pack_info.txt)。pack_info.txt 与已导入的逐字相同就不再拷。
|
||||
// 先拷到 files/dm/import.part/,齐了再逐项换上,pack_info.txt 最后放:中途被杀或空间不够,下次打开从头再导,不会用到半份。
|
||||
// 原生库加载之前做:不含游戏内容的发布包,几张表在库加载时就从 derived.tsv 读(dm/host/dm_derived_rt.h)。
|
||||
// Import pack: the player makes the android folder on a computer with dm/tools/d2rm_android.py and their own game files and copies it to
|
||||
// Download/S2X/D2R Mobile/; this copies it into the internal files/dm/ (out, shaders, overlay, derived.tsv, pack_info.txt). Nothing is copied
|
||||
// when pack_info.txt is the same as the imported one. It goes to files/dm/import.part/ first and replaces the items one by one once complete,
|
||||
// pack_info.txt last: if the app is killed or runs out of space, the next start imports again and half a copy is never used.
|
||||
// Done before the native library loads: in the release APK without game content, a few tables are read from derived.tsv at load time.
|
||||
private static final String[] IMPORT_ITEMS = {"out", "shaders", "overlay", "derived.tsv", "pack_info.txt"};
|
||||
|
||||
private static String readText(File f) {
|
||||
try { return new String(Files.readAllBytes(f.toPath()), StandardCharsets.UTF_8); } catch (IOException e) { return null; }
|
||||
}
|
||||
|
||||
private static String packProduct(String info) {
|
||||
if (info != null) for (String line : info.split("\n")) if (line.startsWith("PRODUCT=")) return line.substring(8).trim();
|
||||
return null;
|
||||
}
|
||||
|
||||
// true = 可以接着启动;false = 正在导入或已显示错误
|
||||
// true = startup can continue; false = importing, or an error is shown
|
||||
private boolean ensureImported(File source) {
|
||||
if (importing) return false;
|
||||
File runtime = new File(getFilesDir(), "dm");
|
||||
String want = readText(new File(source, "pack_info.txt")), have = readText(new File(runtime, "pack_info.txt"));
|
||||
if (want != null && !want.equals(have)) {
|
||||
String product = packProduct(want);
|
||||
if (!BuildConfig.DM_PRODUCT.equals(product)) { showStartError(getString(R.string.dmAndroidImportVersion, product)); return false; }
|
||||
importing = true;
|
||||
TextView t = new TextView(this);
|
||||
t.setTextSize(20); t.setPadding(64, 64, 64, 64); t.setText(getString(R.string.dmAndroidImporting, 0));
|
||||
setContentView(t);
|
||||
new Thread(() -> {
|
||||
String error = null;
|
||||
try { importPack(source, runtime, percent -> runOnUiThread(() -> t.setText(getString(R.string.dmAndroidImporting, percent)))); }
|
||||
catch (IOException e) { error = e.getMessage() == null ? e.toString() : e.getMessage(); }
|
||||
String failure = error;
|
||||
runOnUiThread(() -> {
|
||||
importing = false;
|
||||
if (failure != null) showStartError(getString(R.string.dmAndroidImportFailed, failure));
|
||||
else startHost();
|
||||
});
|
||||
}, "dm-import").start();
|
||||
return false;
|
||||
}
|
||||
// 已导入的是给别的版本做的(App 升级了、导入包没重做):同样要重做导入包。开发时直接推进来的没有 pack_info.txt,不核
|
||||
// The imported pack was made for another version (the app was updated, the pack was not remade): it has to be remade too.
|
||||
// Files pushed directly during development have no pack_info.txt and are not checked
|
||||
String product = packProduct(have);
|
||||
if (have != null && !BuildConfig.DM_PRODUCT.equals(product)) { showStartError(getString(R.string.dmAndroidImportVersion, product)); return false; }
|
||||
return true;
|
||||
}
|
||||
|
||||
private interface Progress { void percent(int p); }
|
||||
|
||||
private static void importPack(File source, File runtime, Progress progress) throws IOException {
|
||||
for (String item : IMPORT_ITEMS) if (!new File(source, item).exists()) throw new IOException("missing " + item);
|
||||
File part = new File(runtime, "import.part");
|
||||
deleteTree(part);
|
||||
long sum = 0;
|
||||
for (String item : IMPORT_ITEMS) sum += treeSize(new File(source, item));
|
||||
final long total = sum;
|
||||
long[] done = {0}; int[] shown = {-1};
|
||||
byte[] buffer = new byte[1 << 20];
|
||||
for (String item : IMPORT_ITEMS) copyTree(new File(source, item), new File(part, item), buffer, bytes -> {
|
||||
done[0] += bytes;
|
||||
int p = (int) (done[0] * 100 / Math.max(1, total));
|
||||
if (p != shown[0]) { shown[0] = p; progress.percent(p); }
|
||||
});
|
||||
for (String item : IMPORT_ITEMS) {
|
||||
File from = new File(part, item), to = new File(runtime, item);
|
||||
deleteTree(to);
|
||||
if (!from.renameTo(to)) throw new IOException("rename " + item);
|
||||
}
|
||||
deleteTree(part);
|
||||
}
|
||||
|
||||
private interface Copied { void bytes(long n); }
|
||||
|
||||
private static long treeSize(File f) {
|
||||
if (!f.isDirectory()) return f.length();
|
||||
long n = 0; File[] list = f.listFiles();
|
||||
if (list != null) for (File c : list) n += treeSize(c);
|
||||
return n;
|
||||
}
|
||||
|
||||
private static void copyTree(File from, File to, byte[] buffer, Copied copied) throws IOException {
|
||||
if (from.isDirectory()) {
|
||||
if (!to.isDirectory() && !to.mkdirs()) throw new IOException("mkdir " + to.getName());
|
||||
File[] list = from.listFiles();
|
||||
if (list == null) throw new IOException("list " + from.getName());
|
||||
for (File c : list) copyTree(c, new File(to, c.getName()), buffer, copied);
|
||||
return;
|
||||
}
|
||||
File parent = to.getParentFile();
|
||||
if (parent != null && !parent.isDirectory() && !parent.mkdirs()) throw new IOException("mkdir " + parent.getName());
|
||||
try (InputStream in = new FileInputStream(from); OutputStream out = new FileOutputStream(to)) {
|
||||
for (int n; (n = in.read(buffer)) > 0; ) { out.write(buffer, 0, n); copied.bytes(n); }
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteTree(File f) throws IOException {
|
||||
File[] list = f.isDirectory() ? f.listFiles() : null;
|
||||
if (list != null) for (File c : list) deleteTree(c);
|
||||
if (f.exists() && !f.delete()) throw new IOException("delete " + f.getName());
|
||||
}
|
||||
|
||||
private void startHost() {
|
||||
if (bootFailure != 0) { showBootFailure(); return; }
|
||||
if (started || importing || !resumed || !ensureFileAccess()) return;
|
||||
File downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
|
||||
if (!libraryLoaded && !ensureImported(new File(downloads, "S2X/D2R Mobile/android"))) return;
|
||||
if (gameFrame.getParent() == null) setContentView(gameFrame);
|
||||
if (!libraryLoaded) {
|
||||
// 与 jni_android.c 选运行目录同一条规则:内部目录有主程序就用内部目录,否则用外部私有目录
|
||||
// Same rule as jni_android.c's choice of runtime directory: internal storage when it has the main module, otherwise external private storage
|
||||
File ext = getExternalFilesDir(null), internal = new File(getFilesDir(), "dm");
|
||||
File runtime = new File(internal, "out/main.patched.bin").canRead() || ext == null ? internal : new File(ext, "dm");
|
||||
try { Os.setenv("DM_DERIVED", new File(runtime, "derived.tsv").getAbsolutePath(), true); } catch (ErrnoException e) { showStartError(getString(R.string.dmAndroidStorage)); return; }
|
||||
try { System.loadLibrary("dm"); libraryLoaded = true; }
|
||||
catch (UnsatisfiedLinkError error) { showStartError(getString(R.string.dmAndroidLibrary)); return; }
|
||||
}
|
||||
if (touchOverlay == null) {
|
||||
int[] gameIds = {R.string.dmAndroidAttack, R.string.dmAndroidSkill1, R.string.dmAndroidSkill2, R.string.dmAndroidSkill3, R.string.dmAndroidSkill4,
|
||||
R.string.dmAndroidPortal, R.string.dmAndroidPotion1, R.string.dmAndroidPotion2, R.string.dmAndroidPotion3, R.string.dmAndroidPotion4,
|
||||
R.string.dmAndroidMenu, R.string.dmAndroidMap, R.string.dmAndroidMove, R.string.dmAndroidSwap, R.string.dmAndroidDifficulty};
|
||||
int[] navIds = {R.string.dmConfirm, R.string.dmAndroidBack, R.string.dmAndroidAction, R.string.dmAndroidBind, R.string.dmAndroidNext};
|
||||
String[] gameLabels = new String[gameIds.length], navLabels = new String[navIds.length];
|
||||
for (int i = 0; i < gameIds.length; i++) gameLabels[i] = getString(gameIds[i]);
|
||||
for (int i = 0; i < navIds.length; i++) navLabels[i] = getString(navIds[i]);
|
||||
touchOverlay = new TouchOverlay(this, gameLabels, navLabels);
|
||||
touchOverlay.setOnApplyWindowInsetsListener((v, insets) -> {
|
||||
android.graphics.Insets safe = insets.getInsets(WindowInsets.Type.displayCutout());
|
||||
touchOverlay.setSafeInsets(safe.left, safe.right, safe.bottom);
|
||||
return insets;
|
||||
});
|
||||
gameFrame.addView(touchOverlay, new FrameLayout.LayoutParams(-1, -1));
|
||||
touchOverlay.requestApplyInsets();
|
||||
}
|
||||
if (!view.getHolder().getSurface().isValid() || view.getWidth() <= 0 || view.getHeight() <= 0) return;
|
||||
File ext = getExternalFilesDir(null);
|
||||
if (ext == null) { showStartError(getString(R.string.dmAndroidStorage)); return; }
|
||||
nativeSurface(view.getHolder().getSurface(), view.getWidth(), view.getHeight());
|
||||
updateRefresh();
|
||||
// 资源目录缺省 Download/S2X/D2R Mobile/data;没有这个目录、而早先的 Download/data 在时沿用早先的位置,已装好的手机不必搬数据。
|
||||
// 按目录判断而不按 .build.config:它也可以由导入的覆盖层提供,资源目录里就没有。
|
||||
// The resource directory defaults to Download/S2X/D2R Mobile/data; when that directory does not exist but the earlier
|
||||
// Download/data does, the earlier one is kept, so existing installs need not move their data. The test is the directory,
|
||||
// not .build.config: the imported overlay can provide that file, and then the resource directory has none.
|
||||
File data = new File(downloads, "S2X/D2R Mobile/data"), earlier = new File(downloads, "data");
|
||||
if (!data.isDirectory() && earlier.isDirectory()) data = earlier;
|
||||
String src = data.getAbsolutePath();
|
||||
int result = nativeStart(getFilesDir().getAbsolutePath(), ext.getAbsolutePath(), src, Locale.getDefault().toLanguageTag());
|
||||
if (result < 0) {
|
||||
int resource = switch (result) {
|
||||
case -2 -> R.string.dmAndroidMissingData;
|
||||
case -3 -> R.string.dmAndroidMissingModules;
|
||||
case -4 -> R.string.dmAndroidMissingShaders;
|
||||
case -5 -> R.string.dmAndroidMissingConfig;
|
||||
case -9 -> R.string.dmAndroidMissingOverlay;
|
||||
case -10 -> R.string.dmAndroidInvalidOverlay;
|
||||
default -> 0;
|
||||
};
|
||||
showStartError(resource == 0 ? getString(R.string.dmAndroidStartFailed, result) : getString(resource)); return;
|
||||
}
|
||||
started = true;
|
||||
touchOverlay.setInputEnabled(true);
|
||||
nativeFocus(3);
|
||||
}
|
||||
|
||||
private void showStartError(String message) {
|
||||
TextView t = new TextView(this);
|
||||
t.setText(message); t.setTextSize(20); t.setPadding(64, 64, 64, 64);
|
||||
setContentView(t);
|
||||
}
|
||||
|
||||
// 原生线程只投递主线程工作,不持有 Activity,也不直接操作视图。
|
||||
// Native threads only post UI work; they neither retain the Activity nor touch views.
|
||||
private static void showNativeFailure(int code) {
|
||||
bootFailure = code;
|
||||
DmActivity activity = current.get();
|
||||
if (activity != null) activity.runOnUiThread(() -> {
|
||||
if (!activity.isDestroyed()) activity.showBootFailure();
|
||||
});
|
||||
}
|
||||
|
||||
private void showBootFailure() {
|
||||
releaseTouches();
|
||||
showStartError(getString(bootFailure == -6 ? R.string.dmAndroidGraphicsFailed : R.string.dmAndroidHostStopped));
|
||||
}
|
||||
|
||||
private static void showNativeInput(long id, String title, String sub, String guide, String initial,
|
||||
int maxChars, int nameRule, int numericMax) {
|
||||
DmActivity activity = current.get();
|
||||
if (activity == null) { nativeTextResult(id, false, ""); return; }
|
||||
activity.runOnUiThread(() -> activity.openInput(id, title, sub, guide, initial, maxChars, nameRule != 0, numericMax));
|
||||
}
|
||||
|
||||
private void openInput(long id, String title, String sub, String guide, String initial,
|
||||
int maxChars, boolean nameRule, int numericMax) {
|
||||
if (!resumed || isFinishing() || isDestroyed() || inputDialog != null) { nativeTextResult(id, false, ""); return; }
|
||||
releaseTouches();
|
||||
EditText input = new EditText(this);
|
||||
input.setSingleLine(true);
|
||||
input.setInputType(numericMax >= 0 ? InputType.TYPE_CLASS_NUMBER : InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
|
||||
input.setHint(nameRule ? getString(R.string.dmNameBlankRandom) : guide);
|
||||
input.setText(TextInputRules.normalize(initial, maxChars, nameRule, numericMax));
|
||||
input.setSelection(input.length());
|
||||
String message = sub + (sub.isEmpty() || guide.isEmpty() ? "" : "\n") + guide;
|
||||
if (nameRule) message += (message.isEmpty() ? "" : "\n") + getString(R.string.dmNameRule);
|
||||
if (numericMax >= 0) message = getString(R.string.dmAndroidQuantityRange, numericMax);
|
||||
if (title.isEmpty()) title = getString(nameRule ? R.string.dmNameTitle : numericMax >= 0 ? R.string.dmQtyTitle : R.string.dmInputTitle);
|
||||
final boolean[] finished = {false};
|
||||
AlertDialog dialog = new AlertDialog.Builder(this).setTitle(title).setMessage(message).setView(input)
|
||||
.setPositiveButton(R.string.dmConfirm, null).setNegativeButton(R.string.dmCancel, (d, which) -> {})
|
||||
.create();
|
||||
inputDialog = dialog;
|
||||
dialog.setOnDismissListener(d -> {
|
||||
if (inputDialog == dialog) inputDialog = null;
|
||||
if (!finished[0]) { finished[0] = true; nativeTextResult(id, false, ""); }
|
||||
if (resumed) immersive();
|
||||
});
|
||||
dialog.setOnShowListener(d -> {
|
||||
Runnable check = () -> {
|
||||
boolean composing = BaseInputConnection.getComposingSpanStart(input.getText()) >= 0;
|
||||
int error = nameRule ? TextInputRules.nameError(input.getText().toString()) : 0;
|
||||
input.setError(composing ? getString(R.string.dmNamePickIme) : error == 1 ? getString(R.string.dmNameTooShort) : error == 2 ? getString(R.string.dmNameEdge) : null);
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(!composing && error == 0);
|
||||
};
|
||||
Runnable settle = () -> {
|
||||
Editable text = input.getText();
|
||||
if (BaseInputConnection.getComposingSpanStart(text) < 0) {
|
||||
String normalized = TextInputRules.normalize(text.toString(), maxChars, nameRule, numericMax);
|
||||
if (!normalized.contentEquals(text)) { input.setText(normalized); input.setSelection(input.length()); return; }
|
||||
}
|
||||
check.run();
|
||||
};
|
||||
// 输入法结束组字(点候选、按完成)时常常只去掉组字标记、文字不变:TextWatcher 收不到,「确定」一直灰、提示停在「先选完字」。
|
||||
// 组字状态一变就和文字变化一样处理(规整 + 重判):SpanWatcher 挂在文字上,Editable.Factory 让每次 setText 换上的新文字也挂着它。
|
||||
// When the IME finishes composing (picking a candidate, Done) it often only removes the composing span and keeps the text: TextWatcher is not
|
||||
// called, so OK stays disabled with "finish choosing characters". A change of composing state is handled like a text change (normalize + check):
|
||||
// a SpanWatcher sits on the text, and an Editable.Factory attaches it to the new text after every setText.
|
||||
SpanWatcher composingWatch = new SpanWatcher() {
|
||||
boolean composing = BaseInputConnection.getComposingSpanStart(input.getText()) >= 0;
|
||||
private void changed(Spannable text) {
|
||||
boolean now = BaseInputConnection.getComposingSpanStart(text) >= 0;
|
||||
if (now != composing) { composing = now; input.post(settle); }
|
||||
}
|
||||
public void onSpanAdded(Spannable text, Object what, int start, int end) { changed(text); }
|
||||
public void onSpanRemoved(Spannable text, Object what, int start, int end) { changed(text); }
|
||||
public void onSpanChanged(Spannable text, Object what, int ostart, int oend, int nstart, int nend) { changed(text); }
|
||||
};
|
||||
input.setEditableFactory(new Editable.Factory() {
|
||||
@Override public Editable newEditable(CharSequence source) {
|
||||
Editable e = super.newEditable(source);
|
||||
e.setSpan(composingWatch, 0, e.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
|
||||
return e;
|
||||
}
|
||||
});
|
||||
input.getText().setSpan(composingWatch, 0, input.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
|
||||
input.addTextChangedListener(new TextWatcher() {
|
||||
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
|
||||
public void onTextChanged(CharSequence s, int start, int before, int count) {}
|
||||
public void afterTextChanged(Editable text) { settle.run(); }
|
||||
});
|
||||
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
|
||||
finished[0] = true;
|
||||
nativeTextResult(id, true, input.getText().toString());
|
||||
dialog.dismiss();
|
||||
});
|
||||
check.run();
|
||||
input.requestFocus();
|
||||
if (dialog.getWindow() != null) dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
|
||||
});
|
||||
dialog.show();
|
||||
}
|
||||
|
||||
private void releaseTouches() {
|
||||
if (touchOverlay != null) touchOverlay.cancelTouches();
|
||||
if (started) nativeTouch(0, new int[0], new float[0], new float[0]);
|
||||
}
|
||||
|
||||
private void updateRefresh() {
|
||||
if (libraryLoaded) nativeRefresh(view.getDisplay() == null ? 0 : view.getDisplay().getRefreshRate());
|
||||
}
|
||||
@Override public void onDisplayAdded(int id) { updateRefresh(); }
|
||||
@Override public void onDisplayRemoved(int id) { updateRefresh(); }
|
||||
@Override public void onDisplayChanged(int id) { updateRefresh(); }
|
||||
@Override protected void onResume() { super.onResume(); resumed = true; immersive(); startHost(); updateRefresh(); if (started) { nativeFocus(3); if (touchOverlay != null && bootFailure == 0) touchOverlay.setInputEnabled(true); } }
|
||||
@Override protected void onPause() { resumed = false; if (inputDialog != null) inputDialog.dismiss(); releaseTouches(); if (touchOverlay != null) touchOverlay.setInputEnabled(false); if (started) nativeFocus(0); super.onPause(); }
|
||||
@Override protected void onStart() { super.onStart(); if (started) nativeFocus(2); }
|
||||
@Override protected void onStop() { if (started) nativeFocus(1); com.xiaoboluo.d2r.widget.HeroWidgetProvider.requestUpdate(this); super.onStop(); }
|
||||
@Override protected void onDestroy() { if (displays != null) displays.unregisterDisplayListener(this); if (inputDialog != null) inputDialog.dismiss(); if (current.get() == this) current.clear(); super.onDestroy(); }
|
||||
@Override public void onWindowFocusChanged(boolean f) { super.onWindowFocusChanged(f); if (f) immersive(); else releaseTouches(); }
|
||||
|
||||
@Override public void surfaceCreated(SurfaceHolder h) {}
|
||||
@Override public void surfaceChanged(SurfaceHolder h, int format, int w, int ht) {
|
||||
if (libraryLoaded) nativeSurface(h.getSurface(), w, ht);
|
||||
updateRefresh();
|
||||
startHost();
|
||||
}
|
||||
@Override public void surfaceDestroyed(SurfaceHolder h) { releaseTouches(); if (libraryLoaded) nativeSurface(null, 0, 0); }
|
||||
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package com.xiaoboluo.d2r;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
// 同 iOS 输入框的角色名 / 金币规则;纯 Java 部分可在主机验证。
|
||||
// Character-name and quantity rules shared with the iOS dialog; testable on the host JVM.
|
||||
final class TextInputRules {
|
||||
private TextInputRules() {}
|
||||
|
||||
static String normalize(String value, int maxChars, boolean name, int numericMax) {
|
||||
if (numericMax >= 0) {
|
||||
long number = 0; boolean any = false;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i);
|
||||
if (c >= '0' && c <= '9') { any = true; number = Math.min(numericMax, number * 10 + c - '0'); }
|
||||
}
|
||||
value = any ? Long.toString(number) : "";
|
||||
} else if (name) {
|
||||
StringBuilder filtered = new StringBuilder(); int bytes = 0; boolean dash = false;
|
||||
for (int i = 0; i < value.length(); i++) {
|
||||
char c = value.charAt(i); int n = 0;
|
||||
if (c >= 'A' && c <= 'Z' || c >= 'a' && c <= 'z') n = 1;
|
||||
else if ((c == '-' || c == '_') && !dash) { n = 1; dash = true; }
|
||||
else if (c >= 0x4e00 && c <= 0x9fff || c >= 0x3400 && c <= 0x4dbf) n = 3;
|
||||
if (n > 0 && bytes + n <= 15) { filtered.append(c); bytes += n; }
|
||||
}
|
||||
value = filtered.toString();
|
||||
}
|
||||
if (maxChars > 0 && value.length() > maxChars) {
|
||||
int end = maxChars;
|
||||
if (Character.isHighSurrogate(value.charAt(end - 1)) && Character.isLowSurrogate(value.charAt(end))) end--;
|
||||
value = value.substring(0, end);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
static int nameError(String value) {
|
||||
if (value.isEmpty()) return 0;
|
||||
if (value.getBytes(StandardCharsets.UTF_8).length < 2) return 1;
|
||||
char first = value.charAt(0), last = value.charAt(value.length() - 1);
|
||||
return first == '-' || first == '_' || last == '-' || last == '_' ? 2 : 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,467 @@
|
||||
package com.xiaoboluo.d2r;
|
||||
|
||||
import android.content.Context;
|
||||
import android.graphics.BlendMode;
|
||||
import android.graphics.Bitmap;
|
||||
import android.graphics.BlurMaskFilter;
|
||||
import android.graphics.BitmapFactory;
|
||||
import android.graphics.Canvas;
|
||||
import android.graphics.Color;
|
||||
import android.graphics.Paint;
|
||||
import android.graphics.Path;
|
||||
import android.graphics.Rect;
|
||||
import android.graphics.RectF;
|
||||
import android.graphics.LinearGradient;
|
||||
import android.graphics.RadialGradient;
|
||||
import android.graphics.Shader;
|
||||
import android.graphics.Typeface;
|
||||
import android.graphics.ColorMatrix;
|
||||
import android.graphics.ColorMatrixColorFilter;
|
||||
import android.view.Choreographer;
|
||||
import android.view.MotionEvent;
|
||||
import android.view.View;
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.Locale;
|
||||
import org.json.JSONObject;
|
||||
import org.json.JSONArray;
|
||||
|
||||
/** 透明悬浮触摸层:与游戏Surface同尺寸,不挤占游戏高度。 | Transparent overlay sharing the game Surface bounds without reducing its height. */
|
||||
public final class TouchOverlay extends View {
|
||||
private static native void nativeEvent(int phase, int slot, float x, float y);
|
||||
private static native void nativeResize(float width, float height, float left, float right, float bottom, boolean tablet);
|
||||
private static native void nativeLayout(float[] out);
|
||||
private final float density;
|
||||
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
private static final int GLYPHS=119, HUD=167, DRAW_FLOATS=185;
|
||||
private final float[] layout = new float[DRAW_FLOATS];
|
||||
// 每个刷新周期比较完整绘图快照;坐标、可见性、按下状态与技能组任一变化才重画。
|
||||
// The native layout is checked once per refresh; the view redraws only when it differs from what was last drawn
|
||||
// Coordinates, visibility, pressed state and skill set all participate in that snapshot.
|
||||
private final float[] probe = new float[DRAW_FLOATS], drawn = new float[DRAW_FLOATS];
|
||||
private boolean drawnValid;
|
||||
private final Choreographer.FrameCallback poll = new Choreographer.FrameCallback() {
|
||||
@Override public void doFrame(long frameTimeNanos) {
|
||||
if (!running) return;
|
||||
if (inputEnabled && isShown()) { nativeLayout(probe); if (!drawnValid || !Arrays.equals(probe, drawn)) invalidate(); }
|
||||
Choreographer.getInstance().postFrameCallback(this);
|
||||
}
|
||||
};
|
||||
private final int[] pointerIds = new int[16];
|
||||
private final float[] lastX = new float[16], lastY = new float[16];
|
||||
private final int[] rawIds = new int[16];
|
||||
private final float[] rawX = new float[16], rawY = new float[16];
|
||||
private final String[] gameLabels, menuLabels;
|
||||
private final File overlayRoot;
|
||||
private final HashMap<String,Bitmap> images=new HashMap<>(), art=new HashMap<>(), glyphs=new HashMap<>();
|
||||
private final HashMap<String,int[]> glowOffsets=new HashMap<>();
|
||||
private final Bitmap[] skillAtlases=new Bitmap[9], silAtlases=new Bitmap[9];
|
||||
private Bitmap mapArt, circleArt, socketArt;
|
||||
private final Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
|
||||
private final String lifeFormat, manaFormat, levelFormat, cancelLabel;
|
||||
private JSONObject hudUi;
|
||||
private float safeLeft, safeRight, safeBottom;
|
||||
private boolean running, inputEnabled;
|
||||
|
||||
/** labels为本地化表中的15项:12键、摇杆、换组、难度;menuLabels为导航态前五键。 | Pass 15 localized game labels and five navigation labels from the shared string table. */
|
||||
public TouchOverlay(Context context, String[] labels, String[] menuLabels) {
|
||||
super(context);
|
||||
density = getResources().getDisplayMetrics().density;
|
||||
Arrays.fill(pointerIds,-1);
|
||||
gameLabels = labels == null ? new String[15] : labels.clone();
|
||||
this.menuLabels = menuLabels == null ? new String[5] : menuLabels.clone();
|
||||
lifeFormat=context.getString(R.string.dmHudLife); manaFormat=context.getString(R.string.dmHudMana);
|
||||
levelFormat=context.getString(R.string.dmAndroidHudLevel); cancelLabel=context.getString(R.string.dmTcCancel);
|
||||
overlayRoot=new File(context.getFilesDir(),"dm/overlay");
|
||||
setWillNotDraw(false);
|
||||
setFocusable(false);
|
||||
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
|
||||
}
|
||||
public void setSafeInsets(int leftPx, int rightPx, int bottomPx) {
|
||||
safeLeft=leftPx/density; safeRight=rightPx/density; safeBottom=bottomPx/density;
|
||||
resizeNative();
|
||||
}
|
||||
/** 仅在libdm加载且guest启动成功后开启;暂停时先取消触点。 | Enable only after libdm loads and the guest starts; disabling cancels first. */
|
||||
public void setInputEnabled(boolean enabled) {
|
||||
if (inputEnabled==enabled) return;
|
||||
if (!enabled) cancelTouches();
|
||||
inputEnabled=enabled;
|
||||
drawnValid=false; invalidate();
|
||||
if (enabled) {
|
||||
images.clear(); art.clear(); glyphs.clear(); glowOffsets.clear();
|
||||
for(int i=0;i<skillAtlases.length;i++) {
|
||||
skillAtlases[i]=image("touchart/dm_native_skill_"+i+".png"); silAtlases[i]=image("hud_v4_ui/sil_dm_native_skill_"+i+".png");
|
||||
}
|
||||
mapArt=image("touchart/dm_native_map.png"); circleArt=image("touchart/dm_native_circle.png"); socketArt=image("touchart/dm_mobile_socket.png");
|
||||
try { hudUi=new JSONObject(new String(Files.readAllBytes(new File(overlayRoot,"hud_v4_ui/ui.json").toPath()),StandardCharsets.UTF_8)); }
|
||||
catch(Exception ignored) { hudUi=null; }
|
||||
resizeNative();
|
||||
}
|
||||
}
|
||||
private void resizeNative() {
|
||||
if (inputEnabled && getWidth()>0 && getHeight()>0) nativeResize(getWidth()/density,getHeight()/density,safeLeft,safeRight,safeBottom,
|
||||
getResources().getConfiguration().smallestScreenWidthDp>=600);
|
||||
}
|
||||
@Override protected void onSizeChanged(int w,int h,int oldw,int oldh) {
|
||||
cancelTouches(); resizeNative();
|
||||
}
|
||||
@Override protected void onAttachedToWindow() {
|
||||
super.onAttachedToWindow(); running=true; drawnValid=false; invalidate(); Choreographer.getInstance().postFrameCallback(poll);
|
||||
}
|
||||
@Override protected void onDetachedFromWindow() {
|
||||
running=false; Choreographer.getInstance().removeFrameCallback(poll); cancelTouches(); super.onDetachedFromWindow();
|
||||
}
|
||||
public void cancelTouches() {
|
||||
if (!inputEnabled) { Arrays.fill(pointerIds,-1); return; }
|
||||
for (int i=0;i<16;++i) if (pointerIds[i]>=0) {
|
||||
nativeEvent(3,i,lastX[i],lastY[i]); pointerIds[i]=-1;
|
||||
}
|
||||
publishRaw();
|
||||
}
|
||||
private void publishRaw() {
|
||||
int count=0;
|
||||
if (getWidth()>0 && getHeight()>0) for (int s=0;s<16;++s) if (pointerIds[s]>=0) {
|
||||
rawIds[count]=s; rawX[count]=lastX[s]*density/getWidth(); rawY[count]=lastY[s]*density/getHeight(); ++count;
|
||||
}
|
||||
DmActivity.nativeTouch(count,rawIds,rawX,rawY);
|
||||
}
|
||||
private int slot(int id) {
|
||||
for (int i=0;i<16;++i) if (pointerIds[i]==id) return i;
|
||||
return -1;
|
||||
}
|
||||
private void event(MotionEvent e,int index,int phase,int s) {
|
||||
lastX[s]=e.getX(index)/density; lastY[s]=e.getY(index)/density;
|
||||
nativeEvent(phase,s,lastX[s],lastY[s]);
|
||||
}
|
||||
@Override public boolean onTouchEvent(MotionEvent e) {
|
||||
if (!inputEnabled) return false;
|
||||
int action=e.getActionMasked(), index=e.getActionIndex();
|
||||
if (action==MotionEvent.ACTION_DOWN || action==MotionEvent.ACTION_POINTER_DOWN) {
|
||||
for (int s=0;s<16;++s) if (pointerIds[s]<0) {
|
||||
pointerIds[s]=e.getPointerId(index); event(e,index,0,s); break;
|
||||
}
|
||||
} else if (action==MotionEvent.ACTION_MOVE) {
|
||||
for (int i=0;i<e.getPointerCount();++i) { int s=slot(e.getPointerId(i)); if (s>=0) event(e,i,1,s); }
|
||||
} else if (action==MotionEvent.ACTION_UP || action==MotionEvent.ACTION_POINTER_UP) {
|
||||
int s=slot(e.getPointerId(index)); if (s>=0) { event(e,index,2,s); pointerIds[s]=-1; }
|
||||
if (action==MotionEvent.ACTION_UP) performClick();
|
||||
} else if (action==MotionEvent.ACTION_CANCEL) cancelTouches();
|
||||
publishRaw(); return true;
|
||||
}
|
||||
@Override public boolean performClick() { super.performClick(); return true; }
|
||||
private String label(int i,boolean navigation) {
|
||||
if (i>=15) return Integer.toString(i-14);
|
||||
String[] source=navigation && i<5?menuLabels:gameLabels;
|
||||
String text=i<source.length && source[i]!=null?source[i]:"";
|
||||
// 换组字段同时决定文字,避免快照变了却仍画相同的组别。 | The skill-set field also changes the label so a changed snapshot displays the new group.
|
||||
if(i==13) return layout[3]!=0?"Ⅱ":"Ⅰ";
|
||||
if(i==11 && layout[HUD+15]!=0) return cancelLabel;
|
||||
return text;
|
||||
}
|
||||
// 图像只从用户导入的已校验资源读取,不放进安装包。
|
||||
// Images are read only from the user's validated imported resources, never from the APK.
|
||||
private Bitmap image(String name) {
|
||||
if(images.containsKey(name)) return images.get(name);
|
||||
File file=new File(overlayRoot,name);
|
||||
Bitmap bitmap=file.isFile() && file.length()<=8*1024*1024 ? BitmapFactory.decodeFile(file.getAbsolutePath()):null;
|
||||
images.put(name,bitmap); return bitmap;
|
||||
}
|
||||
// ---- 触屏外观:逐项移植 iOS 的 dm/ios/Sources/DmTouchControlArt.h 与 DmTouchOverlay.m(参数与 iOS 逐个相同,改一边要改另一边)----
|
||||
// ---- Touch art: ported item by item from iOS dm/ios/Sources/DmTouchControlArt.h and DmTouchOverlay.m (same parameters; change both together) ----
|
||||
private static int rgba(double r,double g,double b,double a) {
|
||||
return Color.argb((int)Math.round(a*255),(int)Math.round(r*255),(int)Math.round(g*255),(int)Math.round(b*255));
|
||||
}
|
||||
private static RectF inset(float side,float d) { return new RectF(d,d,side-d,side-d); }
|
||||
private static Shader vgrad(RectF r,int... colors) { return new LinearGradient(0,r.top,0,r.bottom,colors,null,Shader.TileMode.CLAMP); }
|
||||
private static Paint stroke(int color,float width) {
|
||||
Paint p=new Paint(Paint.ANTI_ALIAS_FLAG);p.setStyle(Paint.Style.STROKE);p.setColor(color);p.setStrokeWidth(width);return p;
|
||||
}
|
||||
private interface Art { void draw(Canvas c,float side,Bitmap target,float scale); }
|
||||
// 静态底图按像素尺寸缓存(同 iOS controlArt):移动时只换摇杆头位置,不每帧建渐变。
|
||||
// Static art is cached at pixel size (as iOS controlArt): moving only changes where the thumb goes, no gradients per frame.
|
||||
private Bitmap artBitmap(String key,float side,Art a) {
|
||||
int px=Math.max(1,Math.round(side*density)); String k=key+":"+px; Bitmap b=art.get(k);
|
||||
if(b==null) {
|
||||
if(art.size()>=64) art.clear();
|
||||
b=Bitmap.createBitmap(px,px,Bitmap.Config.ARGB_8888); Canvas bc=new Canvas(b); float scale=px/side; bc.scale(scale,scale);
|
||||
a.draw(bc,side,b,scale); art.put(k,b);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
private void drawArt(Canvas c,String key,float x,float y,float side,Art a) {
|
||||
c.drawBitmap(artBitmap(key,side,a),null,new RectF(x,y,x+side,y+side),bitmapPaint);
|
||||
}
|
||||
// dm_button_draw:窄铁边、黑灰内槽;空槽淡底加细十字。 | dm_button_draw: narrow iron rim, black-grey well; empty slots get a faint base and a thin cross.
|
||||
private static void buttonArt(Canvas c,float side,boolean held,boolean empty,boolean primary) {
|
||||
RectF rim=inset(side,side*.018f), face=inset(side,side*.055f); Paint f=new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
f.setShader(vgrad(rim,rgba(.26,.28,.28,empty?.22:.9),rgba(.055,.065,.07,empty?.22:.95),rgba(.16,.11,.10,empty?.16:.7))); c.drawOval(rim,f);
|
||||
c.drawOval(rim,stroke(rgba(.008,.012,.015,empty?.38:.9),side*.025f));
|
||||
f.setShader(vgrad(face,rgba(.021,.021,.021,empty?.08:.94),rgba(.05,.05,.05,empty?.16:.94))); c.drawOval(face,f);
|
||||
int edge=empty?rgba(held?.72:.62,held?.72:.62,held?.72:.62,held?.80:.60):rgba(held?.64:.26,held?.64:.29,held?.64:.28,held?.72:.55);
|
||||
c.drawOval(face,stroke(edge,side*(held?.018f:(empty?.012f:.009f))));
|
||||
if(primary && !empty) c.drawOval(inset(side,side*.035f),stroke(rgba(.31,.23,.22,.52),side*.012f));
|
||||
if(empty) {
|
||||
float arm=side*.055f,m=side/2; Paint p=stroke(rgba(.60,.65,.64,held?.75:.25),side*.018f); p.setStrokeCap(Paint.Cap.ROUND);
|
||||
c.drawLine(m-arm,m,m+arm,m,p); c.drawLine(m,m-arm,m,m+arm,p);
|
||||
}
|
||||
}
|
||||
// CoreGraphics 的「饱和度」混合叠一层 50% 灰 = 每个像素换成它的亮度(0.3R+0.59G+0.11B),透明处按透明度混向 50% 灰(不透明)。
|
||||
// CoreGraphics "saturation" blending with 50% grey = each pixel becomes its luminosity (0.3R+0.59G+0.11B); transparent parts blend
|
||||
// towards 50% grey by their transparency (and become opaque).
|
||||
private static int neutral(int argb) {
|
||||
double a=Color.alpha(argb)/255.0, l=(.3*Color.red(argb)+.59*Color.green(argb)+.11*Color.blue(argb))/255.0;
|
||||
int v=(int)Math.round(((1-a)*.5+a*l)*255); return Color.argb(255,v,v,v);
|
||||
}
|
||||
// dm_socket_neutralize:底座图内槽(内缩 8% 的椭圆)去色;按椭圆边的覆盖率混合。
|
||||
// dm_socket_neutralize: the socket image's well (the ellipse inset by 8%) loses its colour, blended by the ellipse edge's coverage.
|
||||
private static void neutralizeWell(Bitmap b,float side,float scale) {
|
||||
int w=b.getWidth(),h=b.getHeight(); Bitmap mask=Bitmap.createBitmap(w,h,Bitmap.Config.ALPHA_8);
|
||||
Canvas mc=new Canvas(mask); mc.scale(scale,scale); Paint mp=new Paint(Paint.ANTI_ALIAS_FLAG); mc.drawOval(inset(side,side*.08f),mp);
|
||||
int[] px=new int[w*h]; b.getPixels(px,0,w,0,0,w,h); byte[] cov=new byte[w*h]; mask.copyPixelsToBuffer(java.nio.ByteBuffer.wrap(cov)); mask.recycle();
|
||||
for(int i=0;i<px.length;i++) {
|
||||
double m=(cov[i]&255)/255.0; if(m==0) continue;
|
||||
int o=px[i],n=neutral(o); double oa=Color.alpha(o)/255.0, ra=m+(1-m)*oa;
|
||||
int r=(int)Math.round((m*Color.red(n)+(1-m)*oa*Color.red(o))/ra), g=(int)Math.round((m*Color.green(n)+(1-m)*oa*Color.green(o))/ra), bl=(int)Math.round((m*Color.blue(n)+(1-m)*oa*Color.blue(o))/ra);
|
||||
px[i]=Color.argb((int)Math.round(ra*255),r,g,bl);
|
||||
}
|
||||
b.setPixels(px,0,w,0,0,w,h);
|
||||
}
|
||||
// drawButton:有底座图且不是空槽 → 底座图 + 内槽去色(按下再加银灰细环);否则 dm_button_draw。
|
||||
// drawButton: with the socket image and not empty → socket image + neutral well (plus a silver ring when held); otherwise dm_button_draw.
|
||||
private Bitmap buttonBitmap(float side,boolean held,boolean empty,boolean primary,boolean image) {
|
||||
return artBitmap("skill:"+(held?1:0)+(empty?1:0)+(primary?1:0)+(image?1:0),side,(bc,s,target,scale)->{
|
||||
if(image) {
|
||||
bc.drawBitmap(socketArt,null,new RectF(0,0,s,s),bitmapPaint); neutralizeWell(target,s,scale);
|
||||
if(held) bc.drawOval(inset(s,s*.052f),stroke(rgba(.64,.64,.64,.72),s*.015f));
|
||||
} else buttonArt(bc,s,held,empty,primary);
|
||||
});
|
||||
}
|
||||
private void button(Canvas c,float x,float y,float r,boolean held,boolean empty,boolean primary) {
|
||||
c.drawBitmap(buttonBitmap(2*r,held,empty,primary,socketArt!=null && !empty),null,new RectF(x-r,y-r,x+r,y+r),bitmapPaint);
|
||||
}
|
||||
// 调试包:各控件底图与剪影银灰化结果画成 PNG(3 倍像素),dm/android/tools/art_compare.sh 拿去和 iOS 同参数的离屏渲染逐像素比,防两边画法走开。
|
||||
// Debug builds: each control's art and the silvered silhouettes are written as PNGs (3x pixels); dm/android/tools/art_compare.sh compares them
|
||||
// pixel by pixel with an offscreen render of the iOS code with the same parameters, so the two do not drift apart.
|
||||
void dumpArt(File dir) throws java.io.IOException {
|
||||
socketArt=image("touchart/dm_mobile_socket.png"); silAtlases[0]=image("hud_v4_ui/sil_dm_native_skill_0.png");
|
||||
if(socketArt==null || silAtlases[0]==null) throw new java.io.IOException("overlay art missing");
|
||||
if(!dir.isDirectory() && !dir.mkdirs()) throw new java.io.IOException("mkdir "+dir);
|
||||
HashMap<String,Bitmap> out=new HashMap<>();
|
||||
for(int h=0;h<2;h++) for(int e=0;e<2;e++) for(int p=0;p<2;p++) out.put("button_h"+h+"e"+e+"p"+p,buttonBitmap(80,h==1,e==1,p==1,false));
|
||||
for(int h=0;h<2;h++) out.put("socket_h"+h,buttonBitmap(80,h==1,false,false,true));
|
||||
for(int a=0;a<2;a++) { boolean act=a==1;
|
||||
out.put("joybase_a"+a,artBitmap("stick:1:"+a,120,(bc,side,t,sc)->joyBaseArt(bc,side,act)));
|
||||
out.put("joythumb_a"+a,artBitmap("stick:0:"+a,46,(bc,side,t,sc)->joyThumbArt(bc,side,act))); }
|
||||
Bitmap sil=silAtlases[0]; out.put("silver0",glyph(0,0,0,sil.getWidth(),sil.getHeight()));
|
||||
for(java.util.Map.Entry<String,Bitmap> en:out.entrySet())
|
||||
try(java.io.FileOutputStream f=new java.io.FileOutputStream(new File(dir,en.getKey()+".png"))) { en.getValue().compress(Bitmap.CompressFormat.PNG,100,f); }
|
||||
}
|
||||
// dm_joystick_base_draw:向边缘渐隐的底盘、四段细弧与四个方向刻纹。 | dm_joystick_base_draw: a base fading to the edge, four thin arcs and four direction marks.
|
||||
private static void joyBaseArt(Canvas c,float side,boolean active) {
|
||||
float m=side/2; Paint f=new Paint(Paint.ANTI_ALIAS_FLAG);
|
||||
f.setShader(new RadialGradient(m,m,side*.48f,new int[]{rgba(.025,.025,.025,active?.10:.045),rgba(.025,.025,.025,active?.22:.12),rgba(.025,.025,.025,0)},
|
||||
new float[]{0,.78f,1},Shader.TileMode.CLAMP));
|
||||
c.drawCircle(m,m,side*.48f,f);
|
||||
Paint arc=stroke(rgba(.63,.63,.63,active?.12:.055),side*.004f); arc.setStrokeCap(Paint.Cap.ROUND);
|
||||
Paint mark=stroke(rgba(.68,.68,.68,active?.25:.13),side*.004f); mark.setStrokeCap(Paint.Cap.ROUND);
|
||||
float R=side*.416f; RectF ring=new RectF(m-R,m-R,m+R,m+R);
|
||||
for(int i=0;i<4;i++) {
|
||||
double angle=i*Math.PI/2;
|
||||
c.drawArc(ring,(float)Math.toDegrees(angle+.20),(float)Math.toDegrees(Math.PI/2-.40),false,arc);
|
||||
c.save(); c.translate(m,m); c.rotate(i*90f);
|
||||
float x=side*.414f,k=side*.028f; Path p=new Path();
|
||||
p.moveTo(x+k,0); p.lineTo(x-k,-k*.65f); p.lineTo(x-k*.42f,0); p.lineTo(x-k,k*.65f); p.close(); c.drawPath(p,mark);
|
||||
c.drawLine(x-k*.42f,0,x-k*2.1f,0,mark);
|
||||
c.restore();
|
||||
}
|
||||
}
|
||||
// dm_joystick_thumb_draw:低反光的黑灰摇杆头,上缘两道弧形高光。 | dm_joystick_thumb_draw: a low-sheen black-grey thumb with two arc highlights on top.
|
||||
private static void joyThumbArt(Canvas c,float side,boolean active) {
|
||||
RectF disc=inset(side,side*.055f); Paint f=new Paint(Paint.ANTI_ALIAS_FLAG); float m=side/2;
|
||||
f.setShader(vgrad(disc,rgba(.23,.23,.23,active?.78:.46),rgba(.14,.14,.14,active?.82:.49),rgba(.065,.065,.065,active?.84:.52))); c.drawOval(disc,f);
|
||||
c.drawOval(disc,stroke(rgba(.025,.025,.025,active?.65:.32),side*.035f));
|
||||
float a=side*.437f; c.drawArc(new RectF(m-a,m-a,m+a,m+a),(float)Math.toDegrees(Math.PI*1.07),(float)Math.toDegrees(Math.PI*.84),false,stroke(rgba(.64,.64,.64,active?.40:.22),side*.014f));
|
||||
float b=side*.410f; c.drawArc(new RectF(m-b,m-b,m+b,m+b),(float)Math.toDegrees(Math.PI*1.12),(float)Math.toDegrees(Math.PI*.76),false,stroke(rgba(.42,.42,.42,active?.20:.10),side*.012f));
|
||||
}
|
||||
// 圆钮上的字:同 iOS caption(Palatino 金白字、居中、文字框顶对齐);安卓用衬线体。
|
||||
// Button text: as iOS caption (Palatino in pale gold, centred, top-aligned in its box); Android uses the serif face.
|
||||
private void caption(Canvas c,String value,float cx,float top,float size,float alpha) {
|
||||
paint.setTypeface(Typeface.SERIF); paint.setTextSize(size); paint.setTextAlign(Paint.Align.CENTER); paint.setColor(rgba(.85,.79,.65,alpha));
|
||||
c.drawText(value,cx,top-paint.ascent(),paint); paint.setTypeface(null);
|
||||
}
|
||||
// skillImage:同帧位的银色剪影(无剪影图时退回原版图集、四边各裁 8%),保留明暗、统一为银灰。
|
||||
// skillImage: the silver silhouette at the same frame (without it, the original atlas trimmed 8% on each side), keeping the shading, all silver grey.
|
||||
private Bitmap glyph(int atlas,int sx,int sy,int dm,int sh) {
|
||||
Bitmap sil=silAtlases[atlas], src=sil!=null?sil:skillAtlases[atlas]; if(src==null) return null;
|
||||
int trim=sil!=null?0:Math.round(dm*.08f); sx+=trim; sy+=trim; dm-=2*trim; sh-=2*trim;
|
||||
if(dm<=0 || sh<=0 || sx<0 || sy<0 || sx+dm>src.getWidth() || sy+sh>src.getHeight()) return null;
|
||||
String key=atlas+":"+sx+":"+sy+":"+dm+":"+sh; Bitmap g=glyphs.get(key); if(g!=null) return g;
|
||||
g=Bitmap.createBitmap(src,sx,sy,dm,sh).copy(Bitmap.Config.ARGB_8888,true);
|
||||
if(sil!=null) {
|
||||
int[] px=new int[dm*sh]; g.getPixels(px,0,dm,0,0,dm,sh);
|
||||
for(int i=0;i<px.length;i++) { int n=neutral(px[i]); px[i]=(px[i]&0xff000000)|(n&0x00ffffff); } // 去色后用原图透明度恢复边缘 | restore the edges with the original alpha
|
||||
g.setPixels(px,0,dm,0,0,dm,sh);
|
||||
}
|
||||
if(glyphs.size()>=96) { glyphs.clear(); glowOffsets.clear(); } glyphs.put(key,g); return g;
|
||||
}
|
||||
// 图标外一圈淡光(iOS 用阴影:偏移 0、模糊 r×0.055,按下 r×0.10,65% 灰、32% 不透明)。
|
||||
// A faint glow around the icon (iOS uses a shadow: zero offset, blur r×0.055, r×0.10 when held, 65% grey at 32% opacity).
|
||||
private Bitmap glow(Bitmap g,RectF dst,float blur,int[] offset) {
|
||||
int w=Math.max(1,Math.round(dst.width()*density)),h=Math.max(1,Math.round(dst.height()*density));
|
||||
String key="glow:"+System.identityHashCode(g)+":"+w+":"+h+":"+Math.round(blur*density*10); Bitmap out=glyphs.get(key);
|
||||
if(out==null) {
|
||||
// CoreGraphics 的模糊值约为高斯 σ 的 2 倍;Skia 的模糊半径 r 对应 σ = 0.57735r + 0.5。 | CoreGraphics blur ≈ 2σ; Skia radius r means σ = 0.57735r + 0.5.
|
||||
Bitmap scaled=Bitmap.createScaledBitmap(g,w,h,true); Paint p=new Paint();
|
||||
float sigma=blur*density/2; p.setMaskFilter(new BlurMaskFilter(Math.max(.5f,(sigma-.5f)/.57735f),BlurMaskFilter.Blur.NORMAL));
|
||||
int[] o=new int[2]; out=scaled.extractAlpha(p,o); scaled.recycle(); glyphs.put(key,out); glowOffsets.put(key,o);
|
||||
}
|
||||
int[] o=glowOffsets.get(key); offset[0]=o[0]; offset[1]=o[1]; return out;
|
||||
}
|
||||
private void skill(Canvas c,int i,float x,float y,float r,boolean held,boolean navigation) {
|
||||
int p=GLYPHS+i*8, atlas=(int)layout[p+1], status=(int)layout[p];
|
||||
Bitmap g=status==2 && atlas>=0 && atlas<9 ? glyph(atlas,(int)layout[p+2],(int)layout[p+3],(int)layout[p+4],(int)layout[p+5]) : null;
|
||||
// 无图:主钮与「空」状态画空槽(绑定入口);未知槽画底座 + F 标签图(同 iOS lbl_*.png)。 | No icon: the main button and empty slots draw the empty
|
||||
// socket (the binding entry); an unknown slot draws the socket with its F label image (as iOS lbl_*.png).
|
||||
boolean empty=g==null && (i==0 || status==1);
|
||||
button(c,x,y,r,held,empty,i==0);
|
||||
if(empty) return;
|
||||
if(g==null) {
|
||||
Bitmap lbl=image("hud_v4_ui/"+(i==0?"lbl_main.png":"lbl_f"+(i+(layout[3]!=0?4:0))+".png"));
|
||||
if(lbl!=null) { float lh=r*(i==0?.30f:.36f),lw=lbl.getWidth()*lh/lbl.getHeight(); c.drawBitmap(lbl,null,new RectF(x-lw/2,y+r*.50f-lh/2,x+lw/2,y+r*.50f+lh/2),bitmapPaint); }
|
||||
return;
|
||||
}
|
||||
float size=2*r*.76f, fit=size/Math.max(g.getWidth(),g.getHeight());
|
||||
RectF ir=new RectF(x-g.getWidth()*fit/2,y-g.getHeight()*fit/2,x+g.getWidth()*fit/2,y+g.getHeight()*fit/2);
|
||||
boolean spent=((int)layout[p+6]&2)!=0 && layout[p+7]<=0;
|
||||
c.save(); Path clip=new Path(); clip.addCircle(x,y,r*.82f,Path.Direction.CW); c.clipPath(clip);
|
||||
Paint ip=new Paint(bitmapPaint);
|
||||
if(spent) { // 充能用完:灰底上按亮度贴图标(去色)再压一层暗 | out of charges: luminosity-blend the icon on grey, then darken
|
||||
Paint f=new Paint(Paint.ANTI_ALIAS_FLAG); f.setColor(rgba(.30,.30,.30,1)); c.drawCircle(x,y,r*.84f,f);
|
||||
ip.setBlendMode(BlendMode.LUMINOSITY); ip.setAlpha(140); c.drawBitmap(g,null,ir,ip);
|
||||
f.setColor(rgba(0,0,0,.35)); c.drawCircle(x,y,r*.88f,f);
|
||||
} else {
|
||||
int[] o=new int[2]; Bitmap gl=glow(g,ir,held?r*.10f:r*.055f,o);
|
||||
Paint gp=new Paint(Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG); gp.setColor(rgba(.65,.65,.65,.32));
|
||||
c.save(); c.translate(ir.left,ir.top); c.scale(1/density,1/density); c.drawBitmap(gl,o[0],o[1],gp); c.restore();
|
||||
ip.setAlpha(held?255:240); c.drawBitmap(g,null,ir,ip);
|
||||
}
|
||||
c.restore();
|
||||
// 副手组角标「Ⅱ」(暗底金边小圆)与充能剩余次数(腰带件数那套数字图)。 | Off-hand set badge "Ⅱ" (small dark disc with a gold ring)
|
||||
// and charges left (the belt-count digit images).
|
||||
int kind=(int)layout[p+6];
|
||||
if((kind&1)!=0) {
|
||||
float br=r*.30f,bx=x+r*.74f,by=y-r*.74f; Paint f=new Paint(Paint.ANTI_ALIAS_FLAG); f.setColor(rgba(.11,.094,.078,.95)); c.drawCircle(bx,by,br,f);
|
||||
float lw=Math.max(1,br*.14f),in=Math.max(1,br*.08f); c.drawCircle(bx,by,br-in,stroke(rgba(.63,.50,.27,1),lw));
|
||||
float ts=br*1.15f; caption(c,"Ⅱ",bx,by-ts*.62f,ts,1);
|
||||
}
|
||||
if((kind&2)!=0 && hudUi!=null) {
|
||||
float u=getHeight()/density/1320, W=getWidth()/density;
|
||||
try { JSONObject bd=hudUi.getJSONObject("badge"); hudText(c,Integer.toString(Math.max(0,(int)layout[p+7])),bd.getJSONObject("glyphs"),(x+r*.66f-W/2)/u+1434,(y+r*.42f)/u,true,u); }
|
||||
catch(Exception ignored) { }
|
||||
}
|
||||
}
|
||||
private float hudX(double x,float u) { return getWidth()/density/2+((float)x-1434)*u; }
|
||||
private void hudImage(Canvas c,String name,double x,double y,float u) {
|
||||
Bitmap b=image("hud_v4_ui/"+name); if(b==null)return;
|
||||
float left=hudX(x,u),top=(float)y*u;
|
||||
paint.setColor(Color.WHITE);c.drawBitmap(b,null,new RectF(left,top,left+b.getWidth()*u,top+b.getHeight()*u),paint);
|
||||
}
|
||||
// 字形位置、底图和数值基线来自与iOS相同的生成器,游戏层仍负责药水与球液。
|
||||
// Glyph placement, base art and baselines come from the iOS generator; the game still owns potions and orb liquid.
|
||||
private void hudText(Canvas c,String value,JSONObject glyphs,double x,double baseline,boolean right,float u) throws Exception {
|
||||
double advance=0;
|
||||
for(int i=0;i<value.length();i++) { JSONObject g=glyphs.optJSONObject(value.substring(i,i+1)); if(g!=null)advance+=g.optDouble("adv"); }
|
||||
double pen=x-(right?advance:advance/2);
|
||||
for(int i=0;i<value.length();i++) {
|
||||
JSONObject g=glyphs.optJSONObject(value.substring(i,i+1));if(g==null)continue;
|
||||
if(!g.isNull("file")) hudImage(c,g.getString("file"),pen+g.optDouble("dx"),baseline+g.optDouble("dy"),u);
|
||||
pen+=g.optDouble("adv");
|
||||
}
|
||||
}
|
||||
private void hud(Canvas c) {
|
||||
if(hudUi==null || layout[HUD]==0) return;
|
||||
float u=getHeight()/density/1320;
|
||||
try {
|
||||
JSONObject base=hudUi.getJSONObject("base");hudImage(c,"base_full.png",base.getDouble("x"),base.getDouble("y"),u);
|
||||
JSONArray slots=hudUi.getJSONArray("slots"), inner=hudUi.getJSONArray("inner"), menu=slots.getJSONArray(5);
|
||||
boolean alert=layout[HUD+12]>0 || layout[HUD+13]>0, held=layout[4+10*5+4]!=0;
|
||||
Bitmap button=image("hud_v4_ui/"+(alert?"lvl_":"lvl_d")+(held?1:0)+".png");
|
||||
if(button!=null) c.drawBitmap(button,null,new RectF(hudX(menu.getDouble(0),u),(float)menu.getDouble(1)*u,hudX(menu.getDouble(2),u),(float)menu.getDouble(3)*u),paint);
|
||||
JSONObject e=hudUi.getJSONObject("exp");
|
||||
float x=hudX(e.getDouble("x0"),u),y=(float)e.getDouble("y")*u,w=(float)(e.getDouble("x1")-e.getDouble("x0"))*u,h=(float)e.getDouble("h")*u;
|
||||
paint.setColor(0xff16120e);c.drawRect(x,y,x+w,y+h,paint);
|
||||
paint.setColor(0xffc4a046);c.drawRect(x+u,y+u,x+u+(w-2*u)*Math.max(0,Math.min(1000,layout[HUD+2]))/1000,y+h-u,paint);
|
||||
paint.setColor(0xff463a28);paint.setStyle(Paint.Style.STROKE);paint.setStrokeWidth(u);c.drawRect(x,y,x+w,y+h,paint);paint.setStyle(Paint.Style.FILL);
|
||||
paint.setColor(0xff16120e);for(int i=1;i<20;i++)c.drawRect(x+w*i/20,y+u,x+w*i/20+u,y+h-u,paint);
|
||||
JSONObject lv=hudUi.getJSONObject("lv"), vital=hudUi.getJSONObject("vital"),badge=hudUi.getJSONObject("badge");
|
||||
hudText(c,String.format(Locale.ROOT,levelFormat,(int)layout[HUD+1],(int)layout[HUD+2]/10),lv.getJSONObject("glyphs"),lv.getDouble("x"),lv.getDouble("baseline"),false,u);
|
||||
hudText(c,String.format(Locale.ROOT,lifeFormat,(int)layout[HUD+8],(int)layout[HUD+9]),vital.getJSONObject("glyphs"),vital.getDouble("left_x"),vital.getDouble("baseline"),false,u);
|
||||
hudText(c,String.format(Locale.ROOT,manaFormat,(int)layout[HUD+10],(int)layout[HUD+11]),vital.getJSONObject("glyphs"),vital.getDouble("right_x"),vital.getDouble("baseline"),false,u);
|
||||
for(int i=1;i<=4;i++) if(layout[HUD+2+i]>0) {
|
||||
JSONArray s=slots.getJSONArray(i);
|
||||
hudText(c,Integer.toString((int)layout[HUD+2+i]),badge.getJSONObject("glyphs"),s.getDouble(0)+inner.getDouble(2)+badge.getDouble("dx"),s.getDouble(1)+inner.getDouble(3)+badge.getDouble("dy"),true,u);
|
||||
}
|
||||
int players=(int)layout[HUD+7];
|
||||
if(players>=1 && players<=8) {
|
||||
JSONArray s=slots.getJSONArray(0);Bitmap b=image("hud_v4_ui/diff_"+players+".png");
|
||||
if(b!=null) hudImage(c,"diff_"+players+".png",s.getDouble(0)+(inner.getDouble(0)+inner.getDouble(2)+1-b.getWidth())/2,s.getDouble(1)+(inner.getDouble(1)+inner.getDouble(3)+1-b.getHeight())/2,u);
|
||||
}
|
||||
// 难度选择条(展开时):同 iOS drawV4,8 格 slot.png 加数字,当前档不透明、其余 82%。 | Difficulty picker (when open): as iOS drawV4,
|
||||
// 8 slot.png tiles with digits, the current one opaque and the rest at 82%.
|
||||
if(layout[4+15*5+3]!=0) {
|
||||
JSONObject pk=hudUi.getJSONObject("pick"); Bitmap tile=image("hud_v4_ui/slot.png");
|
||||
for(int i=0;i<8;i++) {
|
||||
double cx=pk.getDouble("center_x")+(i-3.5)*pk.getDouble("pitch"), cy=pk.getDouble("y"); int alpha=i+1==players?255:209;
|
||||
paint.setAlpha(alpha);
|
||||
if(tile!=null) c.drawBitmap(tile,null,new RectF(hudX(cx-tile.getWidth()/2.0,u),(float)(cy-tile.getHeight()/2.0)*u,hudX(cx+tile.getWidth()/2.0,u),(float)(cy+tile.getHeight()/2.0)*u),paint);
|
||||
Bitmap d=image("hud_v4_ui/diff_"+(i+1)+".png");
|
||||
if(d!=null) c.drawBitmap(d,null,new RectF(hudX(cx-d.getWidth()/2.0,u),(float)(cy-d.getHeight()/2.0)*u,hudX(cx+d.getWidth()/2.0,u),(float)(cy+d.getHeight()/2.0)*u),paint);
|
||||
paint.setAlpha(255);
|
||||
}
|
||||
}
|
||||
} catch(Exception ignored) { /* 缺损美术不制造HUD数据。 | Missing art never fabricates HUD values. */ }
|
||||
}
|
||||
@Override protected void onDraw(Canvas canvas) {
|
||||
super.onDraw(canvas); if (!inputEnabled) return; nativeLayout(layout); System.arraycopy(layout, 0, drawn, 0, layout.length); drawnValid=true;
|
||||
canvas.save(); canvas.scale(density,density);
|
||||
boolean navigation=layout[2]!=0;
|
||||
float k=layout[4+12*5+2]/60; // 与 iOS 同一个字号 / 粗细单位:摇杆半径 / 60 | the same size unit as iOS: joystick radius / 60
|
||||
// 同 iOS drawRect:底栏六格(腰带 / 十字)由底栏画、这里只留命中区;难度与 1–8 选择条也由底栏画(hud)。
|
||||
// As iOS drawRect: the six bar cells (belt / cross) are drawn by the bar, only their hit areas here; difficulty and the 1-8 picker too (hud).
|
||||
for (int i=0;i<14;++i) {
|
||||
int p=4+i*5; if (layout[p+3]==0 || i==12) continue;
|
||||
float x=layout[p], y=layout[p+1], r=layout[p+2];
|
||||
if (r<=0 || (i>5 && i<=10)) continue;
|
||||
boolean held=layout[p+4]!=0;
|
||||
if(!navigation && i<=5) { skill(canvas,i,x,y,r,held,navigation); continue; }
|
||||
if(!navigation && i==13) { button(canvas,x,y,r,held,false,false); float ts=12*k; caption(canvas,label(i,false),x,y-ts*.65f,ts,held?1:.86f); continue; }
|
||||
// 其余圆钮:原版圆框图(按下更实)+ 图标或字。地图钮平时画原版地图图标(36×36 一格,按住第 1 格);拖技能时变「取消」:暗红底 + 字。
|
||||
// Other buttons: the original circle image (more opaque when held) + icon or text. The map button draws the original map icon (36x36 frames,
|
||||
// frame 1 held); while a skill is dragged it becomes "Cancel": a dark red base + text.
|
||||
RectF b=new RectF(x-r,y-r,x+r,y+r);
|
||||
boolean cancel=!navigation && i==11 && layout[HUD+15]!=0;
|
||||
if(cancel) { Paint f=new Paint(); f.setColor(rgba(.55,.05,.04,.36)); canvas.drawRect(b,f); }
|
||||
if(circleArt!=null) { bitmapPaint.setAlpha(held?153:71); canvas.drawBitmap(circleArt,null,b,bitmapPaint); bitmapPaint.setAlpha(255); }
|
||||
if(!navigation && i==11 && !cancel && mapArt!=null && mapArt.getWidth()>=2*mapArt.getHeight()) {
|
||||
int f=mapArt.getHeight(),sx=held?f:0; float half=r*.62f;
|
||||
bitmapPaint.setAlpha(held?255:209); canvas.drawBitmap(mapArt,new Rect(sx,0,sx+f,f),new RectF(x-half,y-half,x+half,y+half),bitmapPaint); bitmapPaint.setAlpha(255);
|
||||
continue;
|
||||
}
|
||||
String text=navigation && i==5 ? "" : label(i,navigation); float ts=(i==0?13:10)*k;
|
||||
caption(canvas,text,x,y-ts*.6f,ts,held?1:.84f);
|
||||
}
|
||||
// 摇杆:面板开着、死亡时不画;底盘在起点,摇杆头按推量偏移(同 iOS)。 | Joystick: not drawn with a panel open or when dead; base at the origin, thumb offset by the deflection (as iOS).
|
||||
int jp=4+12*5;
|
||||
if (layout[jp+3]!=0 && !navigation && layout[HUD+14]==0 && layout[jp+2]>0) {
|
||||
float jx=layout[jp],jy=layout[jp+1],jr=layout[jp+2]; boolean active=layout[jp+4]!=0;
|
||||
drawArt(canvas,"stick:1:"+(active?1:0),jx-jr,jy-jr,2*jr,(bc,side,t,sc)->joyBaseArt(bc,side,active));
|
||||
float tx=jx+layout[HUD+16]/32767f*jr, ty=jy-layout[HUD+17]/32767f*jr, th=23*k;
|
||||
drawArt(canvas,"stick:0:"+(active?1:0),tx-th,ty-th,2*th,(bc,side,t,sc)->joyThumbArt(bc,side,active));
|
||||
}
|
||||
hud(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.xiaoboluo.d2r.widget;
|
||||
import com.xiaoboluo.d2r.R;
|
||||
/** 最近英雄的小尺寸卡片。 | Compact card for the most recent hero. */
|
||||
public final class HeroWidget2x2Provider extends HeroWidgetProvider {
|
||||
@Override protected int layoutResource() { return R.layout.widget_2x2; }
|
||||
@Override protected int maxHeroes() { return 1; }
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package com.xiaoboluo.d2r.widget;
|
||||
import com.xiaoboluo.d2r.R;
|
||||
/** 最多三个英雄的宽卡片。 | Wide card for up to three heroes. */
|
||||
public final class HeroWidget4x2Provider extends HeroWidgetProvider {
|
||||
@Override protected int layoutResource() { return R.layout.widget_4x2; }
|
||||
@Override protected int maxHeroes() { return 3; }
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
package com.xiaoboluo.d2r.widget;
|
||||
|
||||
import android.app.PendingIntent;
|
||||
import android.appwidget.AppWidgetManager;
|
||||
import android.appwidget.AppWidgetProvider;
|
||||
import android.content.ComponentName;
|
||||
import android.content.Context;
|
||||
import android.content.Intent;
|
||||
import android.view.View;
|
||||
import android.widget.RemoteViews;
|
||||
import com.xiaoboluo.d2r.DmActivity;
|
||||
import com.xiaoboluo.d2r.R;
|
||||
import java.text.NumberFormat;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
|
||||
/** 原生AppWidget与vivo元数据共用的数据层;不代表已通过平台审核。 | Shared native AppWidget data layer; metadata does not mean platform approval. */
|
||||
public abstract class HeroWidgetProvider extends AppWidgetProvider {
|
||||
private static final String ACTION_REFRESH="com.xiaoboluo.d2r.widget.REFRESH";
|
||||
private static final ExecutorService IO=Executors.newSingleThreadExecutor();
|
||||
private static final int[] NAMES={R.id.widget_name_0,R.id.widget_name_1,R.id.widget_name_2};
|
||||
private static final int[] STATS={R.id.widget_stats_0,R.id.widget_stats_1,R.id.widget_stats_2};
|
||||
private static final int[] EXP={R.id.widget_exp_0,R.id.widget_exp_1,R.id.widget_exp_2};
|
||||
private static final int[] GOLD={R.id.widget_gold_0,R.id.widget_gold_1,R.id.widget_gold_2};
|
||||
private static final int[] COLUMNS={R.id.widget_hero_0,R.id.widget_hero_1,R.id.widget_hero_2};
|
||||
private static final int[] CLASS_NAMES={R.string.dmAndroidWidgetClassAmazon,R.string.dmAndroidWidgetClassSorceress,
|
||||
R.string.dmAndroidWidgetClassNecromancer,R.string.dmAndroidWidgetClassPaladin,R.string.dmAndroidWidgetClassBarbarian,
|
||||
R.string.dmAndroidWidgetClassDruid,R.string.dmAndroidWidgetClassAssassin,R.string.dmAndroidWidgetClassWarlock};
|
||||
protected abstract int layoutResource();
|
||||
protected abstract int maxHeroes();
|
||||
|
||||
@Override public final void onUpdate(Context context,AppWidgetManager manager,int[] ids) { updateAsync(context,ids); }
|
||||
@Override public final void onReceive(Context context,Intent intent) {
|
||||
if (ACTION_REFRESH.equals(intent.getAction())) {
|
||||
int id=intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,AppWidgetManager.INVALID_APPWIDGET_ID);
|
||||
int[] own=AppWidgetManager.getInstance(context).getAppWidgetIds(new ComponentName(context,getClass()));
|
||||
for (int candidate:own) if (candidate==id) { updateAsync(context,new int[]{id}); break; }
|
||||
return;
|
||||
}
|
||||
super.onReceive(context,intent);
|
||||
}
|
||||
private void updateAsync(Context context,int[] requested) {
|
||||
final Context app=context.getApplicationContext(); final int[] ids=requested.clone();
|
||||
final android.content.BroadcastReceiver.PendingResult pending=goAsync();
|
||||
IO.execute(()->{
|
||||
try {
|
||||
/* 只读提交目录,文件I/O不在桌面广播线程执行。 | Read only the committed directory, off the launcher broadcast thread. */
|
||||
SaveSummaryReader.Result summary=SaveSummaryReader.read(app.getFilesDir().toPath().resolve("save"));
|
||||
AppWidgetManager manager=AppWidgetManager.getInstance(app);
|
||||
for (int id:ids) manager.updateAppWidget(id,render(app,id,summary));
|
||||
} finally { if (pending!=null) pending.finish(); }
|
||||
});
|
||||
}
|
||||
private RemoteViews render(Context context,int id,SaveSummaryReader.Result summary) {
|
||||
/* 每次更新新建RemoteViews,不累积跨进程操作表。 | Recreate RemoteViews for each update instead of accumulating cross-process operations. */
|
||||
RemoteViews views=new RemoteViews(context.getPackageName(),layoutResource());
|
||||
Intent open=new Intent(context,DmActivity.class).setAction(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)
|
||||
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
|
||||
views.setOnClickPendingIntent(R.id.widget_card,PendingIntent.getActivity(context,0,open,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE));
|
||||
Intent refresh=new Intent(context,getClass()).setAction(ACTION_REFRESH).putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,id);
|
||||
views.setOnClickPendingIntent(R.id.widget_refresh,PendingIntent.getBroadcast(context,id,refresh,PendingIntent.FLAG_UPDATE_CURRENT|PendingIntent.FLAG_IMMUTABLE));
|
||||
int count=Math.min(maxHeroes(),summary.heroes.size());
|
||||
views.setViewVisibility(R.id.widget_content,count==0?View.GONE:View.VISIBLE);
|
||||
views.setViewVisibility(R.id.widget_message,count==0?View.VISIBLE:View.GONE);
|
||||
if (count==0) {
|
||||
views.setTextViewText(R.id.widget_message,context.getString(summary.state==SaveSummaryReader.State.EMPTY?R.string.dmAndroidWidgetEmpty:R.string.dmAndroidWidgetError));
|
||||
views.setTextViewText(R.id.widget_footer,context.getString(summary.state==SaveSummaryReader.State.EMPTY?R.string.dmAndroidWidgetEmptyHint:R.string.dmAndroidWidgetErrorHint));
|
||||
} else {
|
||||
NumberFormat number=NumberFormat.getIntegerInstance();
|
||||
for (int i=0;i<maxHeroes();++i) {
|
||||
views.setViewVisibility(COLUMNS[i],i<count?View.VISIBLE:View.GONE);
|
||||
if (i>=count) continue;
|
||||
SaveSummaryReader.Hero hero=summary.heroes.get(i);
|
||||
views.setTextViewText(NAMES[i],hero.name);
|
||||
views.setTextViewText(STATS[i],context.getString(R.string.dmAndroidWidgetStats,hero.level,context.getString(CLASS_NAMES[hero.classIndex])));
|
||||
views.setTextViewText(EXP[i],hero.experience>=0?context.getString(R.string.dmAndroidWidgetExp,number.format(hero.experience)):context.getString(R.string.dmAndroidWidgetExpUnknown));
|
||||
views.setTextViewText(GOLD[i],hero.gold>=0?context.getString(R.string.dmAndroidWidgetGold,number.format(hero.gold)):context.getString(R.string.dmAndroidWidgetGoldUnknown));
|
||||
}
|
||||
views.setTextViewText(R.id.widget_footer,context.getString(summary.state==SaveSummaryReader.State.PARTIAL?R.string.dmAndroidWidgetPartial:R.string.dmAndroidWidgetFooter,summary.heroes.size()));
|
||||
}
|
||||
return views;
|
||||
}
|
||||
/** 主应用退到后台或确认保存后调用;不启动游戏进程。 | Call after backgrounding or a confirmed save; never starts the game process. */
|
||||
public static void requestUpdate(Context context) {
|
||||
AppWidgetManager manager=AppWidgetManager.getInstance(context);
|
||||
Class<?>[] providers={HeroWidget2x2Provider.class,HeroWidget4x2Provider.class};
|
||||
for (Class<?> provider:providers) {
|
||||
int[] ids=manager.getAppWidgetIds(new ComponentName(context,provider));
|
||||
if (ids.length==0) continue;
|
||||
Intent update=new Intent(context,provider).setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE).putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,ids);
|
||||
context.sendBroadcast(update);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package com.xiaoboluo.d2r.widget;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.CharacterCodingException;
|
||||
import java.nio.charset.CodingErrorAction;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.DirectoryStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.LinkOption;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/** 已提交目录的只读摘要;不加载游戏、不修改存档。 | Read-only summaries of the committed directory; never loads the game or modifies saves. */
|
||||
public final class SaveSummaryReader {
|
||||
private static final int MAX_SAVE_BYTES = 1024 * 1024;
|
||||
private static final int MAX_CHARACTERS = 256;
|
||||
private static final int[] WIDTH = {10,10,10,10,10,8,21,21,21,21,21,21,7,32,25,25};
|
||||
public enum State { EMPTY, READY, PARTIAL, ERROR }
|
||||
public static final class Hero {
|
||||
public final String name;
|
||||
public final int classIndex, level;
|
||||
public final long lastPlayed, experience, gold;
|
||||
private Hero(String name,int cls,int level,long time,long experience,long gold) {
|
||||
this.name=name; classIndex=cls; this.level=level; lastPlayed=time; this.experience=experience; this.gold=gold;
|
||||
}
|
||||
}
|
||||
public static final class Result {
|
||||
public final State state;
|
||||
public final List<Hero> heroes;
|
||||
public final int rejectedFiles;
|
||||
private Result(State state,List<Hero> heroes,int rejected) {
|
||||
this.state=state; this.heroes=Collections.unmodifiableList(new ArrayList<>(heroes)); rejectedFiles=rejected;
|
||||
}
|
||||
}
|
||||
private SaveSummaryReader() {}
|
||||
|
||||
/** root必须是files/save,不能是运行中的save.work。 | root must be files/save, never the active save.work directory. */
|
||||
public static Result read(Path root) {
|
||||
List<Hero> heroes=new ArrayList<>(); int rejected=0; boolean scanFailed=false;
|
||||
if (root==null || root.getFileName()==null || !root.getFileName().toString().equals("save") || Files.isSymbolicLink(root)) return new Result(State.ERROR,heroes,0);
|
||||
if (!Files.exists(root,LinkOption.NOFOLLOW_LINKS)) return new Result(State.EMPTY,heroes,0);
|
||||
if (!Files.isDirectory(root,LinkOption.NOFOLLOW_LINKS)) return new Result(State.ERROR,heroes,0);
|
||||
try (DirectoryStream<Path> directories=Files.newDirectoryStream(root)) {
|
||||
int visited=0;
|
||||
for (Path dir:directories) {
|
||||
if (++visited>MAX_CHARACTERS) { ++rejected; break; }
|
||||
if (!Files.isDirectory(dir,LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(dir)) continue;
|
||||
Path save=dir.resolve(dir.getFileName().toString()+".d2s");
|
||||
if (!Files.exists(save,LinkOption.NOFOLLOW_LINKS)) continue;
|
||||
if (!Files.isRegularFile(save,LinkOption.NOFOLLOW_LINKS) || Files.isSymbolicLink(save)) { ++rejected; continue; }
|
||||
try {
|
||||
long size=Files.size(save);
|
||||
if (size<0x15b || size>MAX_SAVE_BYTES) { ++rejected; continue; }
|
||||
/* 限长读取抵御并发增长;只读已提交版,校验和失败保留错误态。 | Bound reads even if a file grows concurrently; checksum failures remain errors. */
|
||||
byte[] bytes;
|
||||
try (java.io.InputStream in=Files.newInputStream(save); java.io.ByteArrayOutputStream out=new java.io.ByteArrayOutputStream((int)size)) {
|
||||
byte[] chunk=new byte[8192]; int n;
|
||||
while (out.size()<=MAX_SAVE_BYTES && (n=in.read(chunk,0,Math.min(chunk.length,MAX_SAVE_BYTES+1-out.size())))!=-1) out.write(chunk,0,n);
|
||||
bytes=out.toByteArray();
|
||||
}
|
||||
Hero hero=parse(bytes);
|
||||
if (hero==null) ++rejected; else heroes.add(hero);
|
||||
} catch (IOException | SecurityException ex) { ++rejected; }
|
||||
}
|
||||
} catch (IOException | SecurityException ex) { scanFailed=true; }
|
||||
heroes.sort(Comparator.comparingLong((Hero h)->h.lastPlayed).reversed().thenComparing(h->h.name));
|
||||
return new Result(heroes.isEmpty()?(rejected>0 || scanFailed?State.ERROR:State.EMPTY):(rejected>0 || scanFailed?State.PARTIAL:State.READY),heroes,rejected);
|
||||
}
|
||||
|
||||
/** 仅支持已有本仓依据的D2R版本;没有经验表就不计算百分比。 | Only accepts D2R versions evidenced in this repository; no experience table means no percentage. */
|
||||
static Hero parse(byte[] bytes) {
|
||||
if (bytes==null || bytes.length<0x15b || bytes.length>MAX_SAVE_BYTES) return null;
|
||||
ByteBuffer data=ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
||||
if (data.getInt(0)!=0xaa55aa55) return null;
|
||||
int version=data.getInt(4);
|
||||
if (version!=0x61 && version!=0x69) return null;
|
||||
if (Integer.toUnsignedLong(data.getInt(8))!=bytes.length || data.getInt(12)!=checksum(bytes)) return null;
|
||||
int cls=Byte.toUnsignedInt(bytes[0x18]), level=Byte.toUnsignedInt(bytes[0x1b]);
|
||||
if (cls>7 || level<1 || level>99) return null;
|
||||
int end=0x12b;
|
||||
while (end<0x15b && bytes[end]!=0) ++end;
|
||||
if (end==0x12b || end==0x15b) return null;
|
||||
final String name;
|
||||
try { name=StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT).onUnmappableCharacter(CodingErrorAction.REPORT).decode(ByteBuffer.wrap(bytes,0x12b,end-0x12b)).toString(); }
|
||||
catch (CharacterCodingException ex) { return null; }
|
||||
for (int i=0;i<name.length();++i) if (Character.isISOControl(name.charAt(i))) return null;
|
||||
long experience=-1, gold=-1;
|
||||
/* 复用鸿蒙gf位流语义,但不把名称内的gf当统计段;候选必须有合法终止符和一致等级。 | Reuse the Harmony gf bitstream semantics; ignore gf in the name and require termination and a matching level. */
|
||||
int limit=Math.min(bytes.length,2048);
|
||||
for (int i=0x100;i+1<limit;++i) {
|
||||
if (i>=0x12a && i<0x15b) continue;
|
||||
if (bytes[i]==0x67 && bytes[i+1]==0x66) {
|
||||
long[] stats=stats(bytes,i+2,limit);
|
||||
if (stats!=null && stats[12]==level) {
|
||||
experience=stats[13];
|
||||
if (stats[14]>=0 && stats[15]>=0) gold=stats[14]+stats[15];
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return new Hero(name,cls,level,Integer.toUnsignedLong(data.getInt(0x20)),experience,gold);
|
||||
}
|
||||
private static long[] stats(byte[] bytes,int start,int limit) {
|
||||
long[] values=new long[16]; java.util.Arrays.fill(values,-1);
|
||||
int bit=start*8, last=-1;
|
||||
for (int i=0;i<17;++i) {
|
||||
if (bit+9>limit*8) return null;
|
||||
int id=(int)readBits(bytes,bit,9); bit+=9;
|
||||
if (id==0x1ff) return values;
|
||||
if (id<=last || id>=WIDTH.length || bit+WIDTH[id]>limit*8) return null;
|
||||
values[id]=readBits(bytes,bit,WIDTH[id]); bit+=WIDTH[id]; last=id;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
private static long readBits(byte[] bytes,int offset,int length) {
|
||||
long value=0;
|
||||
for (int i=0;i<length;++i) if (((bytes[(offset+i)/8]>>>((offset+i)%8))&1)!=0) value|=1L<<i;
|
||||
return value;
|
||||
}
|
||||
private static int checksum(byte[] bytes) {
|
||||
int sum=0;
|
||||
for (int i=0;i<bytes.length;++i) sum=Integer.rotateLeft(sum,1)+(i>=12 && i<16?0:Byte.toUnsignedInt(bytes[i]));
|
||||
return sum;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 不使用游戏图片;底板随尺寸布局。 | No game image; the background follows the layout size. -->
|
||||
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
|
||||
<gradient android:angle="135" android:startColor="#2A1E14" android:endColor="#0E0B08" />
|
||||
<corners android:radius="16dp" />
|
||||
<stroke android:width="1dp" android:color="#4A3824" />
|
||||
</shape>
|
||||
@@ -0,0 +1,26 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 原子组件候选:原生RemoteViews布局,无游戏美术、无示例私人角色。 | Candidate native RemoteViews layout without game art or sample private characters. -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/widget_card" android:layout_width="match_parent" android:layout_height="match_parent"
|
||||
android:orientation="vertical" android:padding="8dp" android:background="@drawable/widget_background">
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="28dp" android:orientation="horizontal" android:gravity="center_vertical">
|
||||
<TextView android:id="@+id/widget_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"
|
||||
android:text="@string/dmAndroidWidgetTitle" android:textColor="#E8C67A" android:textSize="11sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_refresh" android:layout_width="wrap_content" android:layout_height="match_parent" android:minWidth="36dp"
|
||||
android:gravity="center" android:text="@string/dmAndroidWidgetRefresh" android:contentDescription="@string/dmAndroidWidgetRefresh"
|
||||
android:textColor="#E8C67A" android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
<LinearLayout android:id="@+id/widget_content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"
|
||||
android:orientation="horizontal" android:gravity="center_vertical" android:visibility="gone">
|
||||
<LinearLayout android:id="@+id/widget_hero_0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingEnd="4dp">
|
||||
<TextView android:id="@+id/widget_name_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#E8C67A" android:textSize="14sp" android:textStyle="bold" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_stats_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#D9C9A6" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_exp_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#BFAE8A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_gold_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#C9A85A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
<TextView android:id="@+id/widget_message" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"
|
||||
android:gravity="center_vertical" android:text="@string/dmAndroidWidgetEmpty" android:textColor="#E8C67A" android:textSize="13sp" android:maxLines="2" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_footer" android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:text="@string/dmAndroidWidgetEmptyHint" android:textColor="#A99B84" android:textSize="9sp" android:maxLines="2" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,38 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<!-- 原子组件候选:原生RemoteViews布局,无游戏美术、无示例私人角色。 | Candidate native RemoteViews layout without game art or sample private characters. -->
|
||||
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:id="@+id/widget_card" android:layout_width="match_parent" android:layout_height="match_parent"
|
||||
android:orientation="vertical" android:padding="8dp" android:background="@drawable/widget_background">
|
||||
<LinearLayout android:layout_width="match_parent" android:layout_height="28dp" android:orientation="horizontal" android:gravity="center_vertical">
|
||||
<TextView android:id="@+id/widget_title" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1"
|
||||
android:text="@string/dmAndroidWidgetTitle" android:textColor="#E8C67A" android:textSize="11sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_refresh" android:layout_width="wrap_content" android:layout_height="match_parent" android:minWidth="36dp"
|
||||
android:gravity="center" android:text="@string/dmAndroidWidgetRefresh" android:contentDescription="@string/dmAndroidWidgetRefresh"
|
||||
android:textColor="#E8C67A" android:textSize="10sp" />
|
||||
</LinearLayout>
|
||||
<LinearLayout android:id="@+id/widget_content" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"
|
||||
android:orientation="horizontal" android:gravity="center_vertical" android:visibility="gone">
|
||||
<LinearLayout android:id="@+id/widget_hero_0" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingEnd="4dp">
|
||||
<TextView android:id="@+id/widget_name_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#E8C67A" android:textSize="14sp" android:textStyle="bold" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_stats_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#D9C9A6" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_exp_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#BFAE8A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_gold_0" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#C9A85A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
<LinearLayout android:id="@+id/widget_hero_1" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingEnd="4dp">
|
||||
<TextView android:id="@+id/widget_name_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#E8C67A" android:textSize="14sp" android:textStyle="bold" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_stats_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#D9C9A6" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_exp_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#BFAE8A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_gold_1" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#C9A85A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
<LinearLayout android:id="@+id/widget_hero_2" android:layout_width="0dp" android:layout_height="match_parent" android:layout_weight="1" android:orientation="vertical" android:paddingEnd="4dp">
|
||||
<TextView android:id="@+id/widget_name_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#E8C67A" android:textSize="14sp" android:textStyle="bold" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_stats_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#D9C9A6" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_exp_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#BFAE8A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_gold_2" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#C9A85A" android:textSize="10sp" android:maxLines="1" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
</LinearLayout>
|
||||
<TextView android:id="@+id/widget_message" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"
|
||||
android:gravity="center_vertical" android:text="@string/dmAndroidWidgetEmpty" android:textColor="#E8C67A" android:textSize="13sp" android:maxLines="2" android:ellipsize="end" />
|
||||
<TextView android:id="@+id/widget_footer" android:layout_width="match_parent" android:layout_height="wrap_content"
|
||||
android:text="@string/dmAndroidWidgetEmptyHint" android:textColor="#A99B84" android:textSize="9sp" android:maxLines="2" android:ellipsize="end" />
|
||||
</LinearLayout>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:initialLayout="@layout/widget_2x2"
|
||||
android:previewLayout="@layout/widget_2x2"
|
||||
android:description="@string/dmAndroidWidgetDescription"
|
||||
android:targetCellWidth="2" android:targetCellHeight="2"
|
||||
android:minWidth="120dp" android:minHeight="120dp"
|
||||
android:resizeMode="none" android:updatePeriodMillis="43200000"
|
||||
android:widgetCategory="home_screen" />
|
||||
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
android:initialLayout="@layout/widget_4x2"
|
||||
android:previewLayout="@layout/widget_4x2"
|
||||
android:description="@string/dmAndroidWidgetDescription"
|
||||
android:targetCellWidth="4" android:targetCellHeight="2"
|
||||
android:minWidth="280dp" android:minHeight="120dp"
|
||||
android:resizeMode="none" android:updatePeriodMillis="43200000"
|
||||
android:widgetCategory="home_screen" />
|
||||
@@ -0,0 +1,88 @@
|
||||
// 安卓上的 clonefile:APFS 写时复制克隆的语义等价物——整树拷贝(目录、普通文件、user.* 扩展属性),目标不得已存在。
|
||||
// 只给存档事务用(hle_fs.c:挂载时 commit → work、提交时 work → new),存档目录只有几 MB,整拷代价可忽略。
|
||||
// 失败时删掉拷了一半的目标并返回 -1(errno 为首个失败原因),与 clonefile 一样「要么整份、要么没有」。
|
||||
// 调用方跑在客体线程的栈上(有的只有十几 KiB,见 hle_thread.c):缓冲与路径一律放堆上,栈上只留几个指针。
|
||||
// clonefile on Android: the semantic equivalent of an APFS copy-on-write clone -- a whole-tree copy (directories, regular files, user.* extended attributes); the target must not already exist.
|
||||
// Only used for save transactions (hle_fs.c: commit → work at mount, work → new at commit); a save directory is only a few MB, so the cost of a full copy is negligible.
|
||||
// On failure the half-copied target is removed and -1 is returned (errno is the first failure reason), like clonefile: "either the whole thing or nothing".
|
||||
// The caller runs on a guest thread's stack (some are only a dozen or so KiB, see hle_thread.c): buffers and paths all go on the heap, leaving only a few pointers on the stack.
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <limits.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/xattr.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int copy_xattrs(const char *src, const char *dst) {
|
||||
enum { CAP = 4096 };
|
||||
char *names = malloc(2 * CAP), *v = names + CAP; if (!names) return -1;
|
||||
ssize_t n = llistxattr(src, names, CAP); int rc = 0;
|
||||
if (n < 0) rc = errno == ENOTSUP ? 0 : -1;
|
||||
for (char *k = names; n > 0 && !rc && k < names + n; k += strlen(k) + 1) {
|
||||
if (strncmp(k, "user.", 5)) continue; // 只搬 user.*(security.* 归系统) | Only move user.* (security.* belongs to the system)
|
||||
ssize_t m = lgetxattr(src, k, v, CAP);
|
||||
if (m < 0 || lsetxattr(dst, k, v, (size_t)m, 0)) rc = -1;
|
||||
}
|
||||
{ int e = errno; free(names); errno = e; }
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int copy_file(const char *src, const char *dst, mode_t mode) {
|
||||
int in = open(src, O_RDONLY | O_CLOEXEC), out = -1, rc = -1;
|
||||
if (in < 0) return -1;
|
||||
char *buf = NULL; ssize_t k;
|
||||
if ((out = open(dst, O_WRONLY | O_CREAT | O_EXCL | O_CLOEXEC, mode & 0777)) < 0 || !(buf = malloc(1 << 16))) goto done;
|
||||
while ((k = read(in, buf, 1 << 16)) > 0)
|
||||
for (ssize_t w = 0; w < k;) { ssize_t z = write(out, buf + w, (size_t)(k - w)); if (z < 0) { if (errno == EINTR) continue; goto done; } w += z; }
|
||||
if (k < 0 || fsync(out)) goto done;
|
||||
rc = copy_xattrs(src, dst);
|
||||
done:
|
||||
{ int e = errno; free(buf); if (out >= 0) close(out); close(in); errno = e; }
|
||||
return rc;
|
||||
}
|
||||
|
||||
static int copy_tree(const char *src, const char *dst) {
|
||||
struct stat st; if (lstat(src, &st)) return -1;
|
||||
if (S_ISREG(st.st_mode)) return copy_file(src, dst, st.st_mode);
|
||||
if (!S_ISDIR(st.st_mode)) { errno = ENOTSUP; return -1; } // 存档里不该有链接 / 设备文件 | Saves should contain no links / device files
|
||||
if (mkdir(dst, st.st_mode & 0777) || copy_xattrs(src, dst)) return -1;
|
||||
DIR *d = opendir(src); if (!d) return -1;
|
||||
struct dirent *e; int rc = 0;
|
||||
char *a = malloc(2 * PATH_MAX), *b = a + PATH_MAX; if (!a) { closedir(d); return -1; }
|
||||
while (!rc && (e = readdir(d))) {
|
||||
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
|
||||
if (snprintf(a, PATH_MAX, "%s/%s", src, e->d_name) >= PATH_MAX || snprintf(b, PATH_MAX, "%s/%s", dst, e->d_name) >= PATH_MAX) { errno = ENAMETOOLONG; rc = -1; break; }
|
||||
rc = copy_tree(a, b);
|
||||
}
|
||||
{ int e2 = errno; free(a); closedir(d); errno = e2; }
|
||||
return rc;
|
||||
}
|
||||
|
||||
static void remove_tree(const char *p) {
|
||||
struct stat st; if (lstat(p, &st)) return;
|
||||
if (S_ISDIR(st.st_mode)) {
|
||||
DIR *d = opendir(p); struct dirent *e;
|
||||
if (d) {
|
||||
char *a = malloc(PATH_MAX);
|
||||
while (a && (e = readdir(d))) {
|
||||
if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue;
|
||||
if (snprintf(a, PATH_MAX, "%s/%s", p, e->d_name) < PATH_MAX) remove_tree(a);
|
||||
}
|
||||
free(a);
|
||||
closedir(d);
|
||||
}
|
||||
rmdir(p);
|
||||
} else unlink(p);
|
||||
}
|
||||
|
||||
int clonefile(const char *src, const char *dst, int flags) {
|
||||
(void)flags;
|
||||
struct stat st; if (!lstat(dst, &st)) { errno = EEXIST; return -1; }
|
||||
if (!copy_tree(src, dst)) return 0;
|
||||
int e = errno; remove_tree(dst); errno = e;
|
||||
return -1;
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
// CommonCrypto 摘要的安卓实现(按 RFC 1321 / FIPS 180-4 直写,无外部依赖)。只给宿主诊断与校验用,不作安全用途。
|
||||
// Android implementation of the CommonCrypto digests (written directly from RFC 1321 / FIPS 180-4, no external dependencies). Only for host diagnostics and checks, not for security purposes.
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <string.h>
|
||||
|
||||
#define ROL(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
|
||||
#define ROR(x, n) (((x) >> (n)) | ((x) << (32 - (n))))
|
||||
static uint32_t be32(const uint8_t *p) { return (uint32_t)p[0] << 24 | (uint32_t)p[1] << 16 | (uint32_t)p[2] << 8 | p[3]; }
|
||||
static uint32_t le32(const uint8_t *p) { return (uint32_t)p[3] << 24 | (uint32_t)p[2] << 16 | (uint32_t)p[1] << 8 | p[0]; }
|
||||
static void put_be32(uint8_t *p, uint32_t v) { p[0] = (uint8_t)(v >> 24); p[1] = (uint8_t)(v >> 16); p[2] = (uint8_t)(v >> 8); p[3] = (uint8_t)v; }
|
||||
|
||||
// ---- SHA-256 ----
|
||||
static const uint32_t K256[64] = {
|
||||
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
|
||||
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
||||
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
|
||||
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
||||
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
|
||||
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
|
||||
static void sha256_block(uint32_t *h, const uint8_t *p) {
|
||||
uint32_t w[64], a = h[0], b = h[1], c = h[2], d = h[3], e = h[4], f = h[5], g = h[6], k = h[7];
|
||||
for (int i = 0; i < 16; i++) w[i] = be32(p + 4 * i);
|
||||
for (int i = 16; i < 64; i++)
|
||||
w[i] = w[i - 16] + (ROR(w[i - 15], 7) ^ ROR(w[i - 15], 18) ^ (w[i - 15] >> 3)) + w[i - 7] + (ROR(w[i - 2], 17) ^ ROR(w[i - 2], 19) ^ (w[i - 2] >> 10));
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t t1 = k + (ROR(e, 6) ^ ROR(e, 11) ^ ROR(e, 25)) + ((e & f) ^ (~e & g)) + K256[i] + w[i];
|
||||
uint32_t t2 = (ROR(a, 2) ^ ROR(a, 13) ^ ROR(a, 22)) + ((a & b) ^ (a & c) ^ (b & c));
|
||||
k = g; g = f; f = e; e = d + t1; d = c; c = b; b = a; a = t1 + t2;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += k;
|
||||
}
|
||||
int CC_SHA256_Init(CC_SHA256_CTX *c) {
|
||||
static const uint32_t iv[8] = {0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
|
||||
memcpy(c->h, iv, sizeof iv); c->n = 0; c->used = 0; return 1;
|
||||
}
|
||||
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len) {
|
||||
const uint8_t *p = data; c->n += len;
|
||||
while (len) {
|
||||
uint32_t k = 64 - c->used; if (k > len) k = len;
|
||||
memcpy(c->buf + c->used, p, k); c->used += k; p += k; len -= k;
|
||||
if (c->used == 64) { sha256_block(c->h, c->buf); c->used = 0; }
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c) {
|
||||
uint64_t bits = c->n * 8;
|
||||
c->buf[c->used++] = 0x80;
|
||||
if (c->used > 56) { memset(c->buf + c->used, 0, 64 - c->used); sha256_block(c->h, c->buf); c->used = 0; }
|
||||
memset(c->buf + c->used, 0, 56 - c->used);
|
||||
for (int i = 0; i < 8; i++) c->buf[56 + i] = (uint8_t)(bits >> (56 - 8 * i));
|
||||
sha256_block(c->h, c->buf);
|
||||
for (int i = 0; i < 8; i++) put_be32(md + 4 * i, c->h[i]);
|
||||
return 1;
|
||||
}
|
||||
unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md) { CC_SHA256_CTX c; CC_SHA256_Init(&c); CC_SHA256_Update(&c, data, len); CC_SHA256_Final(md, &c); return md; }
|
||||
|
||||
// ---- 公共:按 64 字节块喂、补齐(SHA-1 大端长度,MD5 小端长度) | Common: feed in 64-byte blocks and pad (SHA-1 big-endian length, MD5 little-endian length) ----
|
||||
static void md_run(const uint8_t *p, uint64_t len, int big, void (*blk)(uint32_t *, const uint8_t *), uint32_t *h) {
|
||||
uint64_t n = len;
|
||||
for (; n >= 64; n -= 64, p += 64) blk(h, p);
|
||||
uint8_t tail[128] = {0}; memcpy(tail, p, (size_t)n); tail[n] = 0x80;
|
||||
size_t tl = n < 56 ? 64 : 128; uint64_t bits = len * 8;
|
||||
for (int i = 0; i < 8; i++) tail[tl - 8 + i] = (uint8_t)(big ? bits >> (56 - 8 * i) : bits >> (8 * i));
|
||||
blk(h, tail); if (tl == 128) blk(h, tail + 64);
|
||||
}
|
||||
|
||||
// ---- SHA-1 ----
|
||||
static void sha1_block(uint32_t *h, const uint8_t *p) {
|
||||
uint32_t w[80], a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
|
||||
for (int i = 0; i < 16; i++) w[i] = be32(p + 4 * i);
|
||||
for (int i = 16; i < 80; i++) w[i] = ROL(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
for (int i = 0; i < 80; i++) {
|
||||
uint32_t f, k;
|
||||
if (i < 20) { f = (b & c) | (~b & d); k = 0x5a827999; } else if (i < 40) { f = b ^ c ^ d; k = 0x6ed9eba1; }
|
||||
else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8f1bbcdc; } else { f = b ^ c ^ d; k = 0xca62c1d6; }
|
||||
uint32_t t = ROL(a, 5) + f + e + k + w[i]; e = d; d = c; c = ROL(b, 30); b = a; a = t;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e;
|
||||
}
|
||||
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md) {
|
||||
uint32_t h[5] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0};
|
||||
md_run(data, len, 1, sha1_block, h);
|
||||
for (int i = 0; i < 5; i++) put_be32(md + 4 * i, h[i]);
|
||||
return md;
|
||||
}
|
||||
|
||||
// ---- MD5 ----
|
||||
static void md5_block(uint32_t *h, const uint8_t *p) {
|
||||
static const uint32_t K[64] = {
|
||||
0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee, 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501, 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be,
|
||||
0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821, 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa, 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8,
|
||||
0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed, 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a, 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c,
|
||||
0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70, 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05, 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665,
|
||||
0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039, 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1, 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1,
|
||||
0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391};
|
||||
static const uint8_t S[64] = {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20,
|
||||
4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21};
|
||||
uint32_t m[16], a = h[0], b = h[1], c = h[2], d = h[3];
|
||||
for (int i = 0; i < 16; i++) m[i] = le32(p + 4 * i);
|
||||
for (int i = 0; i < 64; i++) {
|
||||
uint32_t f; int g;
|
||||
if (i < 16) { f = (b & c) | (~b & d); g = i; } else if (i < 32) { f = (d & b) | (~d & c); g = (5 * i + 1) & 15; }
|
||||
else if (i < 48) { f = b ^ c ^ d; g = (3 * i + 5) & 15; } else { f = c ^ (b | ~d); g = (7 * i) & 15; }
|
||||
uint32_t t = d; d = c; c = b; b = b + ROL(a + f + K[i] + m[g], S[i]); a = t;
|
||||
}
|
||||
h[0] += a; h[1] += b; h[2] += c; h[3] += d;
|
||||
}
|
||||
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md) {
|
||||
uint32_t h[4] = {0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476};
|
||||
md_run(data, len, 0, md5_block, h);
|
||||
for (int i = 0; i < 4; i++) { md[4 * i] = (uint8_t)h[i]; md[4 * i + 1] = (uint8_t)(h[i] >> 8); md[4 * i + 2] = (uint8_t)(h[i] >> 16); md[4 * i + 3] = (uint8_t)(h[i] >> 24); }
|
||||
return md;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// 安卓构建:宿主用到的 CommonCrypto 摘要(MD5 / SHA-1 / SHA-256,只用于诊断记号与校验),接口与苹果同名同参,实现在 dm/android/compat/digest.c。
|
||||
// Android build: the CommonCrypto digests the host uses (MD5 / SHA-1 / SHA-256, only for diagnostic tokens and checks), with the same names and parameters as on Apple; implemented in dm/android/compat/digest.c.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
typedef uint32_t CC_LONG;
|
||||
#define CC_MD5_DIGEST_LENGTH 16
|
||||
#define CC_SHA1_DIGEST_LENGTH 20
|
||||
#define CC_SHA256_DIGEST_LENGTH 32
|
||||
typedef struct { uint32_t h[8]; uint64_t n; uint8_t buf[64]; uint32_t used; } CC_SHA256_CTX;
|
||||
int CC_SHA256_Init(CC_SHA256_CTX *c);
|
||||
int CC_SHA256_Update(CC_SHA256_CTX *c, const void *data, CC_LONG len);
|
||||
int CC_SHA256_Final(unsigned char *md, CC_SHA256_CTX *c);
|
||||
unsigned char *CC_SHA256(const void *data, CC_LONG len, unsigned char *md);
|
||||
unsigned char *CC_SHA1(const void *data, CC_LONG len, unsigned char *md);
|
||||
unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md);
|
||||
@@ -0,0 +1,9 @@
|
||||
// 安卓构建:宿主源码按苹果目标分支的地方一律走「既非 iOS 也非 Mac」。
|
||||
// Android build: wherever the host source branches on Apple targets, always take "neither iOS nor Mac".
|
||||
#pragma once
|
||||
#define TARGET_OS_IPHONE 0
|
||||
#define TARGET_OS_IOS 0
|
||||
#define TARGET_OS_OSX 0
|
||||
#define TARGET_OS_MAC 0
|
||||
#define TARGET_OS_SIMULATOR 0
|
||||
#define TARGET_OS_MACCATALYST 0
|
||||
@@ -0,0 +1,56 @@
|
||||
// 安卓构建强制包含(CMake -include):宿主源码里零散用到的苹果 libc 扩展,在 bionic 上给出同名同语义的薄实现。
|
||||
// 只放「一行能说清、语义完全对得上」的;对不上的(Mach 线程挂起、实时调度策略、GCD、音频)在原文件按 __APPLE__ 分支各自实现,不在这里假装。
|
||||
// Force-included in the Android build (CMake -include): Apple libc extensions used here and there in the host source, given thin implementations with the same name and semantics on bionic.
|
||||
// Only things that are "explainable in one line with fully matching semantics" go here; those that do not match (Mach thread suspension, real-time scheduling policy, GCD, audio) are implemented in their own files under __APPLE__ branches, not faked here.
|
||||
#pragma once
|
||||
#if defined(__ANDROID__) || defined(__OHOS__)
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <sys/stat.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
// 苹果的 CLOCK_UPTIME_RAW(睡眠不走的单调钟)= Linux CLOCK_MONOTONIC;CLOCK_MONOTONIC_RAW 两边同名
|
||||
// Apple's CLOCK_UPTIME_RAW (a monotonic clock that stops during sleep) = Linux CLOCK_MONOTONIC; CLOCK_MONOTONIC_RAW has the same name on both
|
||||
#ifndef CLOCK_UPTIME_RAW
|
||||
#define CLOCK_UPTIME_RAW CLOCK_MONOTONIC
|
||||
#endif
|
||||
static inline uint64_t clock_gettime_nsec_np(clockid_t c) {
|
||||
struct timespec ts; if (clock_gettime(c, &ts)) return 0;
|
||||
return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
#ifndef __OHOS__ // musl 自带 | musl has its own
|
||||
static inline int getdtablesize(void) { return (int)sysconf(_SC_OPEN_MAX); }
|
||||
#endif
|
||||
static inline size_t pthread_get_stacksize_np(pthread_t t) {
|
||||
pthread_attr_t a; size_t s = 0;
|
||||
if (!pthread_getattr_np(t, &a)) { pthread_attr_getstacksize(&a, &s); pthread_attr_destroy(&a); }
|
||||
return s;
|
||||
}
|
||||
// 苹果 pthread_get_stackaddr_np 返回栈顶(最高地址);bionic 的 attr 给的是栈底 + 大小
|
||||
// Apple's pthread_get_stackaddr_np returns the stack top (highest address); bionic's attr gives the stack bottom + size
|
||||
static inline void *pthread_get_stackaddr_np(pthread_t t) {
|
||||
pthread_attr_t a; void *lo = NULL; size_t s = 0;
|
||||
if (!pthread_getattr_np(t, &a)) { pthread_attr_getstack(&a, &lo, &s); pthread_attr_destroy(&a); }
|
||||
return (char *)lo + s;
|
||||
}
|
||||
// struct stat 的纳秒时间字段:苹果叫 st_mtimespec,Linux 叫 st_mtim
|
||||
// Nanosecond time field of struct stat: called st_mtimespec on Apple, st_mtim on Linux
|
||||
#define st_mtimespec st_mtim
|
||||
#define st_atimespec st_atim
|
||||
#define st_ctimespec st_ctim
|
||||
|
||||
// 存档事务(hle_fs.c):clonefile 在安卓上是整树拷贝(含 user.* 扩展属性,存档目录只有几 MB),renamex_np(RENAME_SWAP) = renameat2(RENAME_EXCHANGE)
|
||||
// Save transactions (hle_fs.c): clonefile on Android is a whole-tree copy (including user.* extended attributes; the save directory is only a few MB), renamex_np(RENAME_SWAP) = renameat2(RENAME_EXCHANGE)
|
||||
int clonefile(const char *src, const char *dst, int flags); // dm/android/compat/clonefile.c
|
||||
#ifndef RENAME_SWAP
|
||||
#define RENAME_SWAP (1u << 1) // 与 Linux RENAME_EXCHANGE 同值 | Same value as Linux RENAME_EXCHANGE
|
||||
#endif
|
||||
static inline int renamex_np(const char *from, const char *to, unsigned flags) {
|
||||
return (int)syscall(__NR_renameat2, AT_FDCWD, from, AT_FDCWD, to, flags & RENAME_SWAP ? (1u << 1) : 0u);
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,6 @@
|
||||
// 安卓构建:改写代码后刷指令缓存。
|
||||
// Android build: flush the instruction cache after rewriting code.
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
static inline void sys_icache_invalidate(void *start, size_t len) { __builtin___clear_cache((char *)start, (char *)start + len); }
|
||||
static inline void sys_dcache_flush(void *start, size_t len) { __builtin___clear_cache((char *)start, (char *)start + len); }
|
||||
@@ -0,0 +1,86 @@
|
||||
// 安卓构建:宿主用到的几样 Mach 功能,在 Linux 上给出语义相同的实现(不是空桩)——
|
||||
// vm_read_overwrite(读可能无效的地址而不崩)= process_vm_readv 读本进程,坏地址返回失败;
|
||||
// task_info(TASK_VM_INFO).phys_footprint = /proc/self/statm 常驻页 × 页大小;
|
||||
// 线程「端口」= 内核线程号(tid):mach_thread_self / pthread_mach_thread_np / task_threads(枚举 /proc/self/task);
|
||||
// thread_suspend / thread_get_state / thread_resume(现场导出取别的线程的寄存器)= 实时信号让目标线程在信号处理里交出寄存器并原地等恢复
|
||||
// (实现 dm/android/compat/mach_thread.c;同一时刻只挂起一条,与宿主现场导出的用法一致);
|
||||
// thread_info(THREAD_BASIC_INFO) 的 CPU 时间 = /proc/self/task/<tid>/stat。
|
||||
// 其余(实时调度策略 thread_policy、vm_remap)语义对不上,在原文件按 __APPLE__ 分支处理。
|
||||
// Android build: the few Mach facilities the host uses, given implementations with the same semantics on Linux (not empty stubs) --
|
||||
// vm_read_overwrite (read a possibly invalid address without crashing) = process_vm_readv on this process, a bad address returns failure;
|
||||
// task_info(TASK_VM_INFO).phys_footprint = resident pages from /proc/self/statm × page size;
|
||||
// thread "port" = kernel thread id (tid): mach_thread_self / pthread_mach_thread_np / task_threads (enumerates /proc/self/task);
|
||||
// thread_suspend / thread_get_state / thread_resume (the state dump reads other threads' registers) = a real-time signal makes the target thread hand over its registers in the signal handler and wait in place for resume
|
||||
// (implemented in dm/android/compat/mach_thread.c; only one thread is suspended at a time, matching how the host's state dump uses it);
|
||||
// CPU time of thread_info(THREAD_BASIC_INFO) = /proc/self/task/<tid>/stat.
|
||||
// The rest (real-time scheduling policy thread_policy, vm_remap) does not match semantically and is handled in the original files under __APPLE__ branches.
|
||||
#pragma once
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <sys/uio.h>
|
||||
#include <unistd.h>
|
||||
typedef int kern_return_t;
|
||||
typedef unsigned mach_port_t;
|
||||
typedef mach_port_t thread_act_t;
|
||||
typedef thread_act_t *thread_act_array_t;
|
||||
typedef unsigned mach_msg_type_number_t;
|
||||
typedef uintptr_t vm_address_t;
|
||||
typedef size_t vm_size_t;
|
||||
typedef int *task_info_t;
|
||||
typedef int *thread_info_t;
|
||||
typedef unsigned *thread_state_t;
|
||||
#define KERN_SUCCESS 0
|
||||
#define KERN_FAILURE 5
|
||||
|
||||
static inline mach_port_t mach_task_self(void) { return 0; }
|
||||
static inline mach_port_t mach_thread_self(void) { return (mach_port_t)gettid(); }
|
||||
static inline mach_port_t pthread_mach_thread_np(pthread_t t) { return (mach_port_t)pthread_gettid_np(t); }
|
||||
static inline kern_return_t mach_port_deallocate(mach_port_t task, mach_port_t name) { (void)task; (void)name; return KERN_SUCCESS; }
|
||||
static inline kern_return_t vm_deallocate(mach_port_t task, vm_address_t a, vm_size_t n) { (void)task; (void)n; free((void *)a); return KERN_SUCCESS; }
|
||||
|
||||
static inline kern_return_t vm_read_overwrite(mach_port_t task, vm_address_t addr, vm_size_t n, vm_address_t to, vm_size_t *got) {
|
||||
(void)task;
|
||||
struct iovec l = {(void *)to, n}, r = {(void *)addr, n};
|
||||
ssize_t k = syscall(__NR_process_vm_readv, getpid(), &l, 1ul, &r, 1ul, 0ul); // 直接系统调用:bionic 只在 _GNU_SOURCE 下声明 | Direct system call: bionic declares it only under _GNU_SOURCE
|
||||
if (got) *got = k > 0 ? (vm_size_t)k : 0;
|
||||
return k == (ssize_t)n ? KERN_SUCCESS : KERN_FAILURE;
|
||||
}
|
||||
|
||||
#define TASK_VM_INFO 22
|
||||
typedef struct { uint64_t phys_footprint, resident_size, virtual_size; } task_vm_info_data_t;
|
||||
#define TASK_VM_INFO_COUNT ((mach_msg_type_number_t)(sizeof(task_vm_info_data_t) / sizeof(int)))
|
||||
static inline kern_return_t task_info(mach_port_t task, int flavor, task_info_t out, mach_msg_type_number_t *count) {
|
||||
(void)task; (void)count;
|
||||
if (flavor != TASK_VM_INFO) return KERN_FAILURE;
|
||||
task_vm_info_data_t *vi = (task_vm_info_data_t *)out;
|
||||
FILE *f = fopen("/proc/self/statm", "r"); unsigned long long vs = 0, rs = 0;
|
||||
if (!f) return KERN_FAILURE;
|
||||
int ok = fscanf(f, "%llu %llu", &vs, &rs) == 2; fclose(f);
|
||||
if (!ok) return KERN_FAILURE;
|
||||
long pg = sysconf(_SC_PAGESIZE);
|
||||
vi->virtual_size = vs * (uint64_t)pg; vi->resident_size = vi->phys_footprint = rs * (uint64_t)pg;
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
// 线程寄存器(字段名与苹果 arm_thread_state64_t 相同)
|
||||
// Thread registers (field names the same as Apple's arm_thread_state64_t)
|
||||
typedef struct { uint64_t __x[29], __fp, __lr, __sp, __pc; uint32_t __cpsr, __pad; } arm_thread_state64_t;
|
||||
#define ARM_THREAD_STATE64 6
|
||||
#define ARM_THREAD_STATE64_COUNT ((mach_msg_type_number_t)(sizeof(arm_thread_state64_t) / sizeof(uint32_t)))
|
||||
#define __darwin_arm_thread_state64_get_pc(s) ((s).__pc)
|
||||
#define __darwin_arm_thread_state64_get_lr(s) ((s).__lr)
|
||||
#define __darwin_arm_thread_state64_get_sp(s) ((s).__sp)
|
||||
#define __darwin_arm_thread_state64_get_fp(s) ((s).__fp)
|
||||
kern_return_t thread_suspend(thread_act_t t);
|
||||
kern_return_t thread_resume(thread_act_t t);
|
||||
kern_return_t thread_get_state(thread_act_t t, int flavor, thread_state_t out, mach_msg_type_number_t *count);
|
||||
kern_return_t task_threads(mach_port_t task, thread_act_array_t *out, mach_msg_type_number_t *n);
|
||||
|
||||
typedef struct { int seconds, microseconds; } time_value_t;
|
||||
typedef struct { time_value_t user_time, system_time; int cpu_usage, policy, run_state, flags, suspend_count, sleep_time; } thread_basic_info_data_t;
|
||||
#define THREAD_BASIC_INFO 3
|
||||
#define THREAD_BASIC_INFO_COUNT ((mach_msg_type_number_t)(sizeof(thread_basic_info_data_t) / sizeof(int)))
|
||||
kern_return_t thread_info(thread_act_t t, int flavor, thread_info_t out, mach_msg_type_number_t *count);
|
||||
@@ -0,0 +1,21 @@
|
||||
// 安卓构建:mach_absolute_time 时基取 1:1(纳秒,CLOCK_MONOTONIC),与宿主 now_ns 同一时钟。
|
||||
// Android build: the mach_absolute_time time base is 1:1 (nanoseconds, CLOCK_MONOTONIC), the same clock as the host's now_ns.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <time.h>
|
||||
typedef struct { uint32_t numer, denom; } mach_timebase_info_data_t;
|
||||
typedef mach_timebase_info_data_t *mach_timebase_info_t;
|
||||
static inline int mach_timebase_info(mach_timebase_info_t t) { t->numer = 1; t->denom = 1; return 0; }
|
||||
static inline uint64_t mach_absolute_time(void) {
|
||||
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
static inline uint64_t mach_continuous_time(void) {
|
||||
struct timespec ts; clock_gettime(CLOCK_BOOTTIME, &ts); return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
// 睡到绝对时刻(mach_absolute_time 时基 = 纳秒)
|
||||
// Sleep until an absolute time (mach_absolute_time time base = nanoseconds)
|
||||
static inline int mach_wait_until(uint64_t deadline) {
|
||||
struct timespec ts = {(time_t)(deadline / 1000000000ull), (long)(deadline % 1000000000ull)};
|
||||
while (clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &ts, NULL) == 4 /* EINTR */) {}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
// 安卓构建:malloc_zone_statistics(宿主只用 size_in_use 作内存读数)= bionic mallinfo 的在用字节。
|
||||
// Android build: malloc_zone_statistics (the host only uses size_in_use as a memory reading) = the in-use bytes from bionic mallinfo.
|
||||
#pragma once
|
||||
#include <malloc.h>
|
||||
#include <stddef.h>
|
||||
typedef struct { unsigned blocks_in_use; size_t size_in_use, max_size_in_use, size_allocated; } malloc_statistics_t;
|
||||
static inline void malloc_zone_statistics(void *zone, malloc_statistics_t *s) {
|
||||
(void)zone; struct mallinfo mi = mallinfo();
|
||||
s->blocks_in_use = 0; s->size_in_use = mi.uordblks; s->max_size_in_use = 0; s->size_allocated = mi.arena;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
// 安卓构建:苹果 QoS 类 → Linux nice 值(线程级 setpriority)。数值与苹果 <sys/qos.h> 相同,日志里的 QoS 读数两边可比。
|
||||
// 应用进程能否降到负 nice 由系统限额决定,失败不致命(保持原优先级);pthread_get_qos_class_np 回读本线程最后一次设的类。
|
||||
// Android build: Apple QoS classes → Linux nice values (per-thread setpriority). The values are the same as Apple's <sys/qos.h>, so QoS readings in logs are comparable on both.
|
||||
// Whether an app process can go to a negative nice is up to the system limits; failure is not fatal (the original priority is kept); pthread_get_qos_class_np reads back the class this thread last set.
|
||||
#pragma once
|
||||
#include <pthread.h>
|
||||
#include <sys/resource.h>
|
||||
#include <unistd.h>
|
||||
typedef enum {
|
||||
QOS_CLASS_USER_INTERACTIVE = 0x21, QOS_CLASS_USER_INITIATED = 0x19, QOS_CLASS_DEFAULT = 0x15,
|
||||
QOS_CLASS_UTILITY = 0x11, QOS_CLASS_BACKGROUND = 0x09, QOS_CLASS_UNSPECIFIED = 0x00,
|
||||
} qos_class_t;
|
||||
static __thread qos_class_t dm_qos_self_ = QOS_CLASS_UNSPECIFIED;
|
||||
static inline int dm_qos_nice_(qos_class_t c) {
|
||||
switch (c) {
|
||||
case QOS_CLASS_USER_INTERACTIVE: return -10; // 安卓 THREAD_PRIORITY_URGENT_DISPLAY(-8) 与 AUDIO(-16) 之间 | Between Android THREAD_PRIORITY_URGENT_DISPLAY(-8) and AUDIO(-16)
|
||||
case QOS_CLASS_USER_INITIATED: return -4; // THREAD_PRIORITY_DISPLAY
|
||||
case QOS_CLASS_UTILITY: return 5;
|
||||
case QOS_CLASS_BACKGROUND: return 10; // THREAD_PRIORITY_BACKGROUND
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
static inline int pthread_set_qos_class_self_np(qos_class_t c, int rel) {
|
||||
(void)rel; dm_qos_self_ = c;
|
||||
return setpriority(PRIO_PROCESS, (id_t)gettid(), dm_qos_nice_(c)) ? -1 : 0;
|
||||
}
|
||||
static inline int pthread_get_qos_class_np(pthread_t t, qos_class_t *c, int *rel) {
|
||||
(void)t; if (c) *c = dm_qos_self_; if (rel) *rel = 0; return 0;
|
||||
}
|
||||
static inline qos_class_t qos_class_self(void) { return dm_qos_self_; }
|
||||
@@ -0,0 +1,4 @@
|
||||
// 安卓构建:clonefile 的声明在 dm_android_compat.h(实现 dm/android/compat/clonefile.c)。
|
||||
// Android build: clonefile is declared in dm_android_compat.h (implemented in dm/android/compat/clonefile.c).
|
||||
#pragma once
|
||||
#include "dm_android_compat.h"
|
||||
@@ -0,0 +1,15 @@
|
||||
// 需要真符号(不是头文件里的内联)的两个苹果函数:汇编(nvn_entry.S 的计时入口)直接 bl _mach_absolute_time;hle_nvn.c 按 extern 声明调 thread_selfcounts。
|
||||
// 本文件不包含 compat 的 mach_time.h,免得与那里的 static inline 同名冲突。
|
||||
// Two Apple functions that need real symbols (not the inlines in headers): assembly (the timing entry in nvn_entry.S) does bl _mach_absolute_time directly; hle_nvn.c calls thread_selfcounts through an extern declaration.
|
||||
// This file does not include compat's mach_time.h, to avoid clashing with the static inline of the same name there.
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
|
||||
uint64_t mach_absolute_time(void) {
|
||||
struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint64_t)ts.tv_sec * 1000000000ull + (uint64_t)ts.tv_nsec;
|
||||
}
|
||||
// 本线程累计 {指令数, 周期数}:苹果 libSystem 私有接口。安卓应用进程不许用硬件性能计数器(perf_event_paranoid),如实返回不可用、读数 0
|
||||
// Cumulative {instructions, cycles} of this thread: a private Apple libSystem interface. Android app processes are not allowed hardware performance counters (perf_event_paranoid), so report unavailable honestly with readings of 0
|
||||
int thread_selfcounts(int type, void *buf, size_t nbytes) { (void)type; memset(buf, 0, nbytes); return -1; }
|
||||
@@ -0,0 +1,115 @@
|
||||
// Mach 线程操作的 Linux 实现(声明见 compat/include/mach/mach.h):只给宿主现场导出用(hle_thread.c svc_thread_dump)。
|
||||
// 挂起 = 给目标线程发实时信号;信号处理(备用栈上)把寄存器写进共享槽,然后原地等到 thread_resume。同一时刻只挂起一条(互斥锁串行)。
|
||||
// 目标线程 200 ms 内没进信号处理(信号被屏蔽、线程已退出)就撤销请求返回失败;晚到的信号看到请求已撤销立即返回,不会卡住。
|
||||
// Linux implementation of Mach thread operations (declared in compat/include/mach/mach.h): only for the host's state dump (hle_thread.c svc_thread_dump).
|
||||
// Suspend = send a real-time signal to the target thread; the signal handler (on the alternate stack) writes the registers into a shared slot and then waits in place until thread_resume. Only one thread is suspended at a time (serialized by a mutex).
|
||||
// If the target thread does not enter the signal handler within 200 ms (signal blocked, thread already exited), the request is withdrawn and failure is returned; a late signal sees that the request was withdrawn and returns immediately, so nothing gets stuck.
|
||||
#include <mach/mach.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <signal.h>
|
||||
#include <stdatomic.h>
|
||||
#include <string.h>
|
||||
#include <sys/resource.h>
|
||||
#include <sys/syscall.h>
|
||||
#include <time.h>
|
||||
#include <ucontext.h>
|
||||
|
||||
enum { ST_IDLE, ST_REQ, ST_HELD, ST_RESUME };
|
||||
static pthread_mutex_t g_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_once_t g_once = PTHREAD_ONCE_INIT;
|
||||
static _Atomic int g_state, g_target;
|
||||
static arm_thread_state64_t g_regs;
|
||||
|
||||
static void pause_us(long us) { struct timespec ts = {0, us * 1000}; nanosleep(&ts, NULL); }
|
||||
static void on_suspend(int sig, siginfo_t *si, void *uc_) {
|
||||
(void)sig; (void)si;
|
||||
int e = errno;
|
||||
int want = ST_REQ;
|
||||
if (atomic_load(&g_target) != gettid() || !atomic_compare_exchange_strong(&g_state, &want, ST_IDLE)) { errno = e; return; }
|
||||
const ucontext_t *uc = uc_;
|
||||
for (int i = 0; i < 29; i++) g_regs.__x[i] = uc->uc_mcontext.regs[i];
|
||||
g_regs.__fp = uc->uc_mcontext.regs[29]; g_regs.__lr = uc->uc_mcontext.regs[30];
|
||||
g_regs.__sp = uc->uc_mcontext.sp; g_regs.__pc = uc->uc_mcontext.pc; g_regs.__cpsr = (uint32_t)uc->uc_mcontext.pstate;
|
||||
atomic_store(&g_state, ST_HELD);
|
||||
while (atomic_load(&g_state) != ST_RESUME) pause_us(200);
|
||||
atomic_store(&g_state, ST_IDLE);
|
||||
errno = e;
|
||||
}
|
||||
static int suspend_sig(void) { return SIGRTMIN + 4; }
|
||||
static void install(void) {
|
||||
struct sigaction sa = {.sa_sigaction = on_suspend, .sa_flags = SA_SIGINFO | SA_ONSTACK | SA_RESTART};
|
||||
sigemptyset(&sa.sa_mask); sigaction(suspend_sig(), &sa, NULL);
|
||||
}
|
||||
|
||||
kern_return_t thread_suspend(thread_act_t t) {
|
||||
if ((pid_t)t == gettid()) return KERN_FAILURE;
|
||||
pthread_once(&g_once, install);
|
||||
pthread_mutex_lock(&g_lock);
|
||||
atomic_store(&g_target, (int)t); atomic_store(&g_state, ST_REQ);
|
||||
if (syscall(SYS_tgkill, getpid(), (pid_t)t, suspend_sig())) goto fail;
|
||||
for (int i = 0; i < 1000; i++) { if (atomic_load(&g_state) == ST_HELD) return KERN_SUCCESS; pause_us(200); }
|
||||
{ int want = ST_REQ; if (!atomic_compare_exchange_strong(&g_state, &want, ST_IDLE)) { // 恰好在撤销前进了处理:照常持有 | Entered the handler just before the withdrawal: hold as usual
|
||||
while (atomic_load(&g_state) != ST_HELD) pause_us(200);
|
||||
return KERN_SUCCESS; } }
|
||||
fail:
|
||||
atomic_store(&g_target, 0); atomic_store(&g_state, ST_IDLE);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return KERN_FAILURE;
|
||||
}
|
||||
kern_return_t thread_get_state(thread_act_t t, int flavor, thread_state_t out, mach_msg_type_number_t *count) {
|
||||
if (flavor != ARM_THREAD_STATE64 || atomic_load(&g_state) != ST_HELD || atomic_load(&g_target) != (int)t) return KERN_FAILURE;
|
||||
memcpy(out, &g_regs, sizeof g_regs); if (count) *count = ARM_THREAD_STATE64_COUNT;
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
kern_return_t thread_resume(thread_act_t t) {
|
||||
if (atomic_load(&g_state) != ST_HELD || atomic_load(&g_target) != (int)t) return KERN_FAILURE;
|
||||
atomic_store(&g_state, ST_RESUME);
|
||||
while (atomic_load(&g_state) != ST_IDLE) pause_us(50);
|
||||
atomic_store(&g_target, 0);
|
||||
pthread_mutex_unlock(&g_lock);
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
kern_return_t task_threads(mach_port_t task, thread_act_array_t *out, mach_msg_type_number_t *n) {
|
||||
(void)task;
|
||||
DIR *d = opendir("/proc/self/task"); if (!d) return KERN_FAILURE;
|
||||
unsigned cap = 64, k = 0; thread_act_t *a = malloc(cap * sizeof *a); struct dirent *e;
|
||||
while (a && (e = readdir(d))) {
|
||||
int tid = atoi(e->d_name); if (tid <= 0) continue;
|
||||
if (k == cap) { thread_act_t *b = realloc(a, (cap *= 2) * sizeof *a); if (!b) { free(a); a = NULL; break; } a = b; }
|
||||
a[k++] = (thread_act_t)tid;
|
||||
}
|
||||
closedir(d);
|
||||
if (!a) return KERN_FAILURE;
|
||||
*out = a; *n = k; return KERN_SUCCESS;
|
||||
}
|
||||
|
||||
kern_return_t thread_info(thread_act_t t, int flavor, thread_info_t out, mach_msg_type_number_t *count) {
|
||||
(void)count;
|
||||
if (flavor != THREAD_BASIC_INFO) return KERN_FAILURE;
|
||||
// 问的是调用线程自己(hle_nvn.c 的 thr_sys_ns 每次提交读两次):getrusage(RUSAGE_THREAD) 一次系统调用、微秒精度。
|
||||
// 打开 /proc 读 stat 每次要 open / read / close 加解析,约占 Redmi 营地渲染线程的 0.7%,而且只有时钟滴答(10 ms)精度
|
||||
// The calling thread itself (hle_nvn.c's thr_sys_ns reads it twice per submit): getrusage(RUSAGE_THREAD) is one system
|
||||
// call with microsecond precision. Reading /proc's stat takes an open, a read, a close and parsing each time, about 0.7% of
|
||||
// the render thread in the Redmi camp, and it only has clock-tick (10 ms) precision
|
||||
if ((pid_t)t == gettid()) {
|
||||
struct rusage ru; if (getrusage(RUSAGE_THREAD, &ru)) return KERN_FAILURE;
|
||||
thread_basic_info_data_t *bi = (thread_basic_info_data_t *)out; memset(bi, 0, sizeof *bi);
|
||||
bi->user_time.seconds = (int)ru.ru_utime.tv_sec; bi->user_time.microseconds = (int)ru.ru_utime.tv_usec;
|
||||
bi->system_time.seconds = (int)ru.ru_stime.tv_sec; bi->system_time.microseconds = (int)ru.ru_stime.tv_usec;
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
char path[64], buf[1024]; snprintf(path, sizeof path, "/proc/self/task/%u/stat", t);
|
||||
FILE *f = fopen(path, "r"); if (!f) return KERN_FAILURE;
|
||||
size_t got = fread(buf, 1, sizeof buf - 1, f); fclose(f); buf[got] = 0;
|
||||
char *p = strrchr(buf, ')'); if (!p) return KERN_FAILURE; // 线程名可含空格:从最后一个 ')' 之后数字段 | The thread name may contain spaces: count fields after the last ')'
|
||||
unsigned long ut = 0, st = 0;
|
||||
// ')' 后第 1 个字段是 state(总第 3 字段);utime / stime 是总第 14 / 15 字段 | The first field after ')' is state (field 3 overall); utime / stime are fields 14 / 15 overall
|
||||
if (sscanf(p + 2, "%*c %*d %*d %*d %*d %*d %*u %*u %*u %*u %*u %lu %lu", &ut, &st) != 2) return KERN_FAILURE;
|
||||
long hz = sysconf(_SC_CLK_TCK); if (hz <= 0) hz = 100;
|
||||
thread_basic_info_data_t *bi = (thread_basic_info_data_t *)out; memset(bi, 0, sizeof *bi);
|
||||
bi->user_time.seconds = (int)(ut / hz); bi->user_time.microseconds = (int)(ut % hz * 1000000 / hz);
|
||||
bi->system_time.seconds = (int)(st / hz); bi->system_time.microseconds = (int)(st % hz * 1000000 / hz);
|
||||
return KERN_SUCCESS;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
/* 安卓性能对照的Debug专用白名单解析;基于D2固定比例A/B要求,不读取游戏内容。
|
||||
* Debug-only Android allowlist parser for D2 fixed-scale A/B tests; reads no game content. */
|
||||
#pragma once
|
||||
#ifdef DM_ANDROID_DEBUG_ENV
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <errno.h>
|
||||
|
||||
typedef struct { unsigned present; char value[3][16]; } dm_android_debug_values;
|
||||
static const char *const dm_android_debug_keys[]={"DM_3D_SCALE","DM_3D_SCALE_DYN","DM_3D_SCALE_FLOOR"};
|
||||
|
||||
/* 完整解析后才输出;未知键、重复、超限或floor高于起点使整份失效。
|
||||
* Publish only a complete parse; unknown keys, duplicates, limits or a floor above the starting scale reject the file. */
|
||||
static int dm_android_debug_parse(const char *text,size_t bytes,dm_android_debug_values *out) {
|
||||
if(!text || !out || bytes>4096)return 0;
|
||||
dm_android_debug_values parsed={0};size_t offset=0;
|
||||
while(offset<bytes) {
|
||||
size_t start=offset;
|
||||
while(offset<bytes && text[offset]!='\n')++offset;
|
||||
size_t length=offset-start;
|
||||
if(offset<bytes)++offset;
|
||||
if(length && text[start+length-1]=='\r')--length;
|
||||
if(length>127)return 0;
|
||||
for(size_t i=0;i<length;++i)if((unsigned char)text[start+i]<32 || (unsigned char)text[start+i]>126)return 0;
|
||||
if(!length || text[start]=='#')continue;
|
||||
const char *eq=memchr(text+start,'=',length);
|
||||
if(!eq)return 0;
|
||||
size_t key_length=(size_t)(eq-(text+start)),value_length=length-key_length-1;
|
||||
if(!value_length || value_length>=sizeof parsed.value[0])return 0;
|
||||
unsigned key;
|
||||
for(key=0;key<3;++key)if(strlen(dm_android_debug_keys[key])==key_length && !memcmp(text+start,dm_android_debug_keys[key],key_length))break;
|
||||
if(key==3 || (parsed.present&(1u<<key)))return 0;
|
||||
memcpy(parsed.value[key],eq+1,value_length); parsed.value[key][value_length]=0;
|
||||
if(key==1) { if(strcmp(parsed.value[key],"0") && strcmp(parsed.value[key],"1"))return 0; }
|
||||
else {
|
||||
int dots=0,digits=0;
|
||||
for(size_t i=0;i<value_length;++i) {
|
||||
char c=parsed.value[key][i];
|
||||
if(c=='.') { if(++dots>1)return 0; }
|
||||
else if(c>='0' && c<='9')++digits;
|
||||
else return 0;
|
||||
}
|
||||
if(!digits)return 0;
|
||||
double scale=strtod(parsed.value[key],NULL);
|
||||
if(!(scale>=.50 && scale<=1.00))return 0;
|
||||
}
|
||||
parsed.present|=1u<<key;
|
||||
}
|
||||
double scale=(parsed.present&1)?strtod(parsed.value[0],NULL):.75;
|
||||
double floor=(parsed.present&4)?strtod(parsed.value[2],NULL):.60;
|
||||
if(floor>scale)return 0;
|
||||
*out=parsed;return 1;
|
||||
}
|
||||
/* 缺文件返回0,拒绝返回-1,通过返回1;无有效整份结果时不修改输出。
|
||||
* Return 0 for absent files, -1 for rejection, 1 for success; never change output without a valid complete result. */
|
||||
static int dm_android_debug_load(const char *path,dm_android_debug_values *out) {
|
||||
FILE *file=fopen(path,"rb");
|
||||
if(!file)return errno==ENOENT?0:-1;
|
||||
char bytes[4097];size_t count=fread(bytes,1,sizeof bytes,file);
|
||||
int failed=ferror(file);fclose(file);
|
||||
if(failed || count>4096 || !dm_android_debug_parse(bytes,count,out))return -1;
|
||||
return 1;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,66 @@
|
||||
# 安卓 App 的 Linux 构建环境(Gradle + NDK + CMake + JDK + Python),WSL / Linux 上不装 Windows 工具也能出 APK。
|
||||
# 版本照 dm/android/README.md 与 app/build.gradle:compileSdk 36、NDK 29.0.14206865、CMake 3.31.6、Gradle 9.8.1、JDK 17。
|
||||
# 钉死:基础镜像按摘要、apt 按 Ubuntu 快照日期、命令行工具按构建号 + Google 仓库清单里的 SHA-1、Gradle 按版本 + SHA-256;
|
||||
# SDK 各包由 sdkmanager 按仓库清单的 SHA-1 校验。用法见 build.sh。
|
||||
#
|
||||
# Linux build environment for the Android App (Gradle + NDK + CMake + JDK + Python), so WSL / Linux can produce the APK without Windows tools.
|
||||
# Versions follow dm/android/README.md and app/build.gradle: compileSdk 36, NDK 29.0.14206865, CMake 3.31.6, Gradle 9.8.1, JDK 17.
|
||||
# Pinned: base image by digest, apt by Ubuntu snapshot date, command-line tools by build number + the SHA-1 in Google's repository listing, Gradle by version + SHA-256;
|
||||
# sdkmanager checks every SDK package against the repository listing's SHA-1. Usage: see build.sh.
|
||||
|
||||
FROM ubuntu@sha256:534baea6a22c03a63003dbc8dbe78fe34bc0d7e595d9a9dc9834884ff530eb55
|
||||
|
||||
ARG APT_SNAPSHOT=20261010T000000Z
|
||||
ARG CMDLINE_TOOLS=16111833
|
||||
ARG CMDLINE_TOOLS_SHA1=e025545c62a8e64c7559119566a569fb1dec5f60
|
||||
ARG GRADLE=9.8.1
|
||||
ARG GRADLE_SHA256=dce76f55f8e251a3a1f130eb120f30b3d271de2b76c9b0729d316b5a1b6dc01f
|
||||
ARG SDK_PACKAGES="platforms;android-36 build-tools;36.0.0 ndk;29.0.14206865 cmake;3.31.6"
|
||||
|
||||
ENV DEBIAN_FRONTEND=noninteractive \
|
||||
LANG=C.UTF-8
|
||||
|
||||
# 快照服务只走 HTTPS:先从镜像自带源装 ca-certificates,其余都从快照装
|
||||
# The snapshot service is HTTPS-only: ca-certificates comes from the image's own archive first, everything else from the snapshot
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& apt-get update --snapshot "$APT_SNAPSHOT" \
|
||||
&& apt-get install -y --no-install-recommends --snapshot "$APT_SNAPSHOT" \
|
||||
openjdk-17-jdk-headless python3 curl unzip \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
ENV JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64 \
|
||||
ANDROID_HOME=/opt/android-sdk \
|
||||
ANDROID_SDK_ROOT=/opt/android-sdk
|
||||
|
||||
RUN curl -fsSL -o /tmp/clt.zip \
|
||||
"https://dl.google.com/android/repository/commandlinetools-linux-${CMDLINE_TOOLS}_latest.zip" \
|
||||
&& echo "${CMDLINE_TOOLS_SHA1} /tmp/clt.zip" | sha1sum -c - \
|
||||
&& mkdir -p "$ANDROID_HOME/cmdline-tools" \
|
||||
&& unzip -q /tmp/clt.zip -d "$ANDROID_HOME/cmdline-tools" \
|
||||
&& mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest" \
|
||||
&& rm /tmp/clt.zip
|
||||
|
||||
# 包名带精确版本,装的就是这几个。sdkmanager 解出的可执行文件是 744(只有 root 能跑),容器按宿主用户 UID 跑,所以同一层里补上 a+rX
|
||||
# Package names carry exact versions, so exactly these are installed. sdkmanager unpacks executables as 744 (root only) and the container runs as the host user's UID, so a+rX is added in the same layer
|
||||
RUN yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null \
|
||||
&& "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" $SDK_PACKAGES \
|
||||
&& chmod -R a+rX "$ANDROID_HOME" \
|
||||
&& rm -rf /root/.android /root/.cache
|
||||
|
||||
RUN curl -fsSL -o /tmp/gradle.zip \
|
||||
"https://services.gradle.org/distributions/gradle-${GRADLE}-bin.zip" \
|
||||
&& echo "${GRADLE_SHA256} /tmp/gradle.zip" | sha256sum -c - \
|
||||
&& unzip -q /tmp/gradle.zip -d /opt \
|
||||
&& ln -s "/opt/gradle-${GRADLE}/bin/gradle" /usr/local/bin/gradle \
|
||||
&& rm /tmp/gradle.zip
|
||||
|
||||
# Gradle 缓存在具名卷 /cache;调试签名钥匙在宿主目录、挂到 /android-user(见 build.sh)。都全员可写:容器按宿主用户 UID 跑
|
||||
# Gradle caches live on a named volume at /cache; the debug signing key lives in a host directory mounted at /android-user (see build.sh). Both world-writable: the container runs as the host user's UID
|
||||
RUN mkdir -m 1777 /cache /cache/home /cache/gradle /android-user
|
||||
|
||||
ENV HOME=/cache/home \
|
||||
GRADLE_USER_HOME=/cache/gradle \
|
||||
ANDROID_USER_HOME=/android-user
|
||||
|
||||
WORKDIR /src
|
||||
Executable
+51
@@ -0,0 +1,51 @@
|
||||
#!/usr/bin/env bash
|
||||
# 在容器里构建安卓 App(以宿主用户 UID 跑)。先建镜像:docker build -t dm-android-build:1 dm/android/docker
|
||||
# dm/android/docker/build.sh assembleDebug + lintDebug
|
||||
# dm/android/docker/build.sh gradle <参数...> 在 /src 里跑任意命令;build.sh bash 进 shell
|
||||
# 挂载:
|
||||
# /src 本仓库(脚本所在的工作树,或 DM_SRC)
|
||||
# /gen 由游戏文件生成的宿主表头,只读 DM_GEN_DIR(必需;生成方法见 dm/host/Makefile,不入库)
|
||||
# /android-user 调试签名钥匙(ANDROID_USER_HOME) DM_ANDROID_USER(缺省 ~/.android-dm)
|
||||
# /cache Gradle 缓存 具名卷 dm-android-build-cache
|
||||
# 钥匙要留着:已装的 App 只接受同一钥匙签的升级包,卸载会连存档一起删。第一次用时如有 Windows 版 Android Studio 的
|
||||
# %USERPROFILE%\.android\debug.keystore 就拷来,这里出的包与 Android Studio 出的包可以互相覆盖安装。
|
||||
#
|
||||
# Build the Android App in the container (runs as the host user's UID). Build the image first: docker build -t dm-android-build:1 dm/android/docker
|
||||
# dm/android/docker/build.sh assembleDebug + lintDebug
|
||||
# dm/android/docker/build.sh gradle <args...> run any command in /src; build.sh bash for a shell
|
||||
# Mounts:
|
||||
# /src this repository (the worktree the script is in, or DM_SRC)
|
||||
# /gen host headers generated from the game files, read-only DM_GEN_DIR (required; generated as in dm/host/Makefile, not committed)
|
||||
# /android-user debug signing key (ANDROID_USER_HOME) DM_ANDROID_USER (default ~/.android-dm)
|
||||
# /cache Gradle caches named volume dm-android-build-cache
|
||||
# Keep the key: an installed App only accepts upgrades signed with the same key, and uninstalling deletes the saves with it. On first use, Windows
|
||||
# Android Studio's %USERPROFILE%\.android\debug.keystore is copied when present, so packages from here and from Android Studio overlay-install each other.
|
||||
set -euo pipefail
|
||||
|
||||
image=${DM_ANDROID_BUILD_IMAGE:-dm-android-build:1}
|
||||
src=$(readlink -f "${DM_SRC:-$(dirname "$0")/../../..}") # DM_SRC:改编另一工作树(如 git worktree)| DM_SRC: build another worktree (e.g. a git worktree)
|
||||
gen=$(readlink -f "${DM_GEN_DIR:?要 DM_GEN_DIR=<宿主表头目录> | needs DM_GEN_DIR=<host header directory>}")
|
||||
user_home=${DM_ANDROID_USER:-$HOME/.android-dm}
|
||||
|
||||
for f in dm_vault_tab.h dm_hud_exp.h dm_bright_levels.inc; do
|
||||
[ -f "$gen/$f" ] || { echo "缺 $gen/$f | missing $gen/$f (dm/host/Makefile)" >&2; exit 1; }
|
||||
done
|
||||
mkdir -p "$user_home"
|
||||
if [ ! -f "$user_home/debug.keystore" ] && command -v cmd.exe > /dev/null; then
|
||||
win_key=$(wslpath "$(cmd.exe /c 'echo %USERPROFILE%' 2> /dev/null | tr -d '\r')")/.android/debug.keystore
|
||||
[ -f "$win_key" ] && cp "$win_key" "$user_home/debug.keystore" && echo "debug key ← $win_key"
|
||||
fi
|
||||
|
||||
if [ $# -eq 0 ]; then
|
||||
set -- gradle --no-daemon -p dm/android :app:assembleDebug :app:lintDebug -PdmGenDir=/gen -PdmPython=/usr/bin/python3
|
||||
fi
|
||||
|
||||
args=(--rm --user "$(id -u):$(id -g)"
|
||||
-v "$src:/src"
|
||||
-v "$gen:/gen:ro"
|
||||
-v "$user_home:/android-user"
|
||||
-v dm-android-build-cache:/cache)
|
||||
if [ -t 0 ] && [ -t 1 ]; then
|
||||
args+=(-it)
|
||||
fi
|
||||
exec docker run "${args[@]}" "$image" "$@"
|
||||
@@ -0,0 +1,69 @@
|
||||
// 安卓前端(front.h 的安卓实现,对应 Mac 的 front_mac.m、iOS 的 front_ios.m)。
|
||||
// 两种形态:
|
||||
// 命令行(adb shell 直接跑 dmhost,开发验证用):没有窗口,front_run 在当前线程直接跑客体,front_metal_layer 为 NULL(图形层走无窗口路径)。
|
||||
// App(Java 外壳经 JNI 交来 ANativeWindow,见 jni_android.c):客体在独立线程跑,front_metal_layer 返回 ANativeWindow*(图形层出图的目标面)。
|
||||
// Android front end (the Android implementation of front.h, counterpart of Mac's front_mac.m and iOS's front_ios.m).
|
||||
// Two forms:
|
||||
// Command line (dmhost run directly from adb shell, for development checks): no window, front_run runs the guest directly on the current thread, front_metal_layer is NULL (the graphics layer takes the no-window path).
|
||||
// App (the Java shell hands over an ANativeWindow through JNI, see jni_android.c): the guest runs on its own thread, front_metal_layer returns the ANativeWindow* (the surface the graphics layer presents to).
|
||||
#include "../host/dm.h"
|
||||
#include "../host/front.h"
|
||||
#include "../host/dm_input.h"
|
||||
#include "touch_android.h"
|
||||
#include "../ios/Sources/dm_touch_game_state.h"
|
||||
#include <math.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
static void *_Atomic g_window; // ANativeWindow*;命令行形态为 NULL | ANativeWindow*; NULL in the command-line form
|
||||
static _Atomic int g_screen_w, g_screen_h;
|
||||
void front_android_set_window(void *win, int w, int h) { atomic_store(&g_window, win); atomic_store(&g_screen_w, w); atomic_store(&g_screen_h, h); }
|
||||
|
||||
// UI 线程从当前 Display 读实际刷新率;0 表示未知,不冒充实测 60 Hz。
|
||||
// The UI thread reads the current Display refresh rate; 0 means unknown, not a measured 60 Hz.
|
||||
static _Atomic int g_refresh_millihz;
|
||||
void front_android_set_refresh(float hz) {
|
||||
atomic_store(&g_refresh_millihz, isfinite(hz) && hz > 0 && hz < 1000 ? (int)lroundf(hz * 1000) : 0);
|
||||
}
|
||||
double front_display_refresh(char *name, size_t n) {
|
||||
if (name && n) *name = 0;
|
||||
return atomic_load(&g_refresh_millihz) / 1000.0;
|
||||
}
|
||||
|
||||
void *front_metal_layer(void) { return atomic_load(&g_window); }
|
||||
|
||||
void front_run(void (*guest)(void)) {
|
||||
// 观测门在装载后才可订阅;这里沿用 iOS 在 front_run 接入的时机。
|
||||
// Observation gates exist only after loading; subscribe at front_run as iOS does.
|
||||
if (front_metal_layer()) {
|
||||
void uimsg_subscribe(void (*)(const char *, const char *, const char *));
|
||||
uimsg_subscribe(dm_android_touch_uimsg);
|
||||
dm_pad_hook = dm_android_touch_step;
|
||||
dm_touch_game_attach();
|
||||
dm_touch_game_live_check(1);
|
||||
}
|
||||
guest(); // 两种形态都在调用线程上跑:App 形态由 JNI 侧先起好客体线程再进 dm_main | Both forms run on the calling thread: in the App form the JNI side starts the guest thread first and then enters dm_main
|
||||
}
|
||||
|
||||
// 游戏输出分辨率:DM_GAME_RES 钉住;有屏幕尺寸时按同高度放宽到屏幕比例(与 Mac 真全屏、iOS 同一规则,宽 ≤ 4096、8 对齐),否则原版 16:9
|
||||
// Game output resolution: pinned by DM_GAME_RES; with a known screen size, widen at the same height to the screen aspect (the same rule as Mac true full screen and iOS, width ≤ 4096, aligned to 8), otherwise the original 16:9
|
||||
uint64_t front_game_res(int docked) {
|
||||
unsigned w, h; const char *e = getenv("DM_GAME_RES");
|
||||
if (e && sscanf(e, "%ux%u", &w, &h) == 2) return docked ? (uint64_t)h << 32 | w : (uint64_t)(h * 4 / 5) << 32 | (w * 4 / 5 + 3) / 4 * 4;
|
||||
int dm = atomic_load(&g_screen_w), sh = atomic_load(&g_screen_h);
|
||||
unsigned bh = docked ? 900 : 720;
|
||||
if (dm > 0 && sh > 0 && dm * 9 > sh * 16) {
|
||||
unsigned bw = (unsigned)(llround((double)bh * dm / sh / 8) * 8); if (bw > 4096) bw = 4096;
|
||||
return (uint64_t)bh << 32 | bw;
|
||||
}
|
||||
return docked ? 900ull << 32 | 1600 : 720ull << 32 | 1280;
|
||||
}
|
||||
|
||||
// 文本输入框:App 用 text_input_jni.c 的强实现弹系统输入框;命令行无窗口,返回 -1。
|
||||
// Text input: the App overrides this with text_input_jni.c; windowless command-line runs return -1.
|
||||
__attribute__((weak)) int front_android_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
|
||||
(void)title; (void)sub; (void)guide; (void)initial; (void)max_chars; (void)out; (void)out_cap; return -1;
|
||||
}
|
||||
int front_text_input(const char *title, const char *sub, const char *guide, const char *initial, int max_chars, char *out, int out_cap) {
|
||||
if (!front_metal_layer()) return -1;
|
||||
return front_android_text_input(title, sub, guide, initial, max_chars, out, out_cap);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
|
||||
android.useAndroidX=false
|
||||
@@ -0,0 +1,349 @@
|
||||
// App 形态的 JNI 入口(Java 侧 app/src/main/java/com/xiaoboluo/d2r/DmActivity.java):对应 iOS 的 main.m 启动链 + front_ios.m 的生命周期 / 触屏转发。
|
||||
// nativeStart:备好目录与环境变量(同 iOS boot_prepare:DM_ROMFS / DM_SAVE / DM_TEMP、cwd),stderr 接到日志文件 + logcat,起宿主线程跑 dm_main。
|
||||
// nativeSurface:交来 / 收回 ANativeWindow(front_android.c);nativeTouch:整组触点(front.h dm_touch_set);nativeFocus:场景生命周期(同 iOS 1 / 2 / 3 + 后台挂起)。
|
||||
// 目录约定(都不进 APK,见 dm/android/README):
|
||||
// <外部私有目录>/dm/out/ 改写产物(*.patched.bin 与各表,patch_nso.py DM_TARGET=android 出),开发时 adb push
|
||||
// 资源目录(缺省 /sdcard/Download/S2X/D2R Mobile/data) 玩家的 18 个 .data 档案 + .build.config;App 在内部目录建 romfs/data/ 逐个链接过去
|
||||
// <内部目录>/save、temp 存档与临时文件
|
||||
// JNI entry of the App form (Java side app/src/main/java/com/xiaoboluo/d2r/DmActivity.java): counterpart of iOS's main.m startup chain + front_ios.m's lifecycle / touch forwarding.
|
||||
// nativeStart: prepare directories and environment variables (as iOS boot_prepare: DM_ROMFS / DM_SAVE / DM_TEMP, cwd), connect stderr to a log file + logcat, start the host thread running dm_main.
|
||||
// nativeSurface: hand over / take back the ANativeWindow (front_android.c); nativeTouch: the whole set of touch points (front.h dm_touch_set); nativeFocus: scene lifecycle (as iOS 1 / 2 / 3 + background suspend).
|
||||
// Directory conventions (none of these go into the APK, see dm/android/README):
|
||||
// <external private dir>/dm/out/ rewriter products (*.patched.bin and tables, from patch_nso.py DM_TARGET=android), adb push during development
|
||||
// resource dir (default /sdcard/Download/S2X/D2R Mobile/data) the player's 18 .data archives + .build.config; the App creates romfs/data/ in the internal dir linking to each of them
|
||||
// <internal dir>/save, temp saves and temporary files
|
||||
#include "../host/dm.h"
|
||||
#include "../host/front.h"
|
||||
#include "../host/hle.h"
|
||||
#include <android/log.h>
|
||||
#include <android/native_window_jni.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <jni.h>
|
||||
#include "vulkan_present.h"
|
||||
#include "touch_android.h"
|
||||
#include "lifecycle_dispatch.h"
|
||||
#include "overlay_validate.h"
|
||||
#include "dm_overlay_contract.h"
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
void front_android_set_window(void *win, int w, int h);
|
||||
void front_android_set_refresh(float hz);
|
||||
int dm_main(int argc, char **argv);
|
||||
void front_android_boot_failed(int code);
|
||||
|
||||
static char g_files[1024], g_ext[1024], g_src[1024], g_runtime[1100];
|
||||
static FILE *g_logf;
|
||||
|
||||
#ifdef DM_ANDROID_DEBUG_ENV
|
||||
#include "debug_env.h"
|
||||
/* 专用调试文件只供性能A/B,不读取游戏通用env,也不开放同步等危险键。
|
||||
* This dedicated performance A/B file is separate from the game's general env and never exposes synchronization keys. */
|
||||
static void debug_environment(void) {
|
||||
char path[1200];snprintf(path,sizeof path,"%s/dm/android-debug.env",g_files);
|
||||
dm_android_debug_values values;
|
||||
int result=dm_android_debug_load(path,&values);
|
||||
if(result<0) { LOG("boot: debug environment rejected");return; }
|
||||
if(!result)return;
|
||||
for(unsigned i=0;i<3;++i)if(values.present&(1u<<i))setenv(dm_android_debug_keys[i],values.value[i],1);
|
||||
LOG("boot: debug environment allowlist applied");
|
||||
}
|
||||
#endif
|
||||
|
||||
// 挂起只能在原生pthread栈上执行;UI只登记最新状态,不能等正在等待Surface的呈现调用。
|
||||
// Suspend only on a native pthread stack; UI posts latest state without waiting for a present that needs a Surface.
|
||||
static dm_lifecycle_dispatch g_lifecycle;
|
||||
static pthread_once_t g_lifecycle_once = PTHREAD_ONCE_INIT;
|
||||
static int g_lifecycle_error;
|
||||
static void lifecycle_graphics(int on) {
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-lifecycle", "graphics suspend=%d begin", on);
|
||||
dm_gfx_suspend(on);
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-lifecycle", "graphics suspend=%d complete", on);
|
||||
}
|
||||
static void lifecycle_init(void) {
|
||||
dm_lifecycle_ops ops = {dm_focus_set, dm_audio_suspend, lifecycle_graphics};
|
||||
g_lifecycle_error = dm_lifecycle_start(&g_lifecycle, ops);
|
||||
if (!g_lifecycle_error) pthread_setname_np(g_lifecycle.thread, "dm-lifecycle");
|
||||
if (g_lifecycle_error) __android_log_print(ANDROID_LOG_ERROR, "dm-lifecycle", "worker start failed rc=%d", g_lifecycle_error);
|
||||
}
|
||||
static int lifecycle_ready(void) { pthread_once(&g_lifecycle_once, lifecycle_init); return !g_lifecycle_error; }
|
||||
|
||||
// stderr → 管道 → 本线程:逐行写日志文件(adb pull 取)并转 logcat(标签 dm)
|
||||
// stderr → pipe → this thread: write line by line to the log file (fetched with adb pull) and forward to logcat (tag dm)
|
||||
static void *log_pump(void *arg) {
|
||||
int fd = (int)(intptr_t)arg; char buf[4096]; size_t have = 0; ssize_t k;
|
||||
while ((k = read(fd, buf + have, sizeof buf - 1 - have)) > 0) {
|
||||
have += (size_t)k; buf[have] = 0; char *s = buf, *nl;
|
||||
while ((nl = strchr(s, '\n'))) { *nl = 0; __android_log_write(ANDROID_LOG_INFO, "dm", s); if (g_logf) { fputs(s, g_logf); fputc('\n', g_logf); fflush(g_logf); } s = nl + 1; }
|
||||
have = strlen(s); memmove(buf, s, have);
|
||||
if (have == sizeof buf - 1) { __android_log_write(ANDROID_LOG_INFO, "dm", buf); if (g_logf) { fputs(buf, g_logf); fflush(g_logf); } have = 0; }
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void log_init(void) {
|
||||
static int initialized; if (initialized) return; initialized = 1;
|
||||
char p[1200]; snprintf(p, sizeof p, "%s/boot.log", g_runtime); g_logf = fopen(p, "a");
|
||||
int fds[2]; if (pipe(fds)) return;
|
||||
dup2(fds[1], 2); close(fds[1]); setvbuf(stderr, NULL, _IOLBF, 0);
|
||||
pthread_t th; if (!pthread_create(&th, NULL, log_pump, (void *)(intptr_t)fds[0])) pthread_detach(th);
|
||||
}
|
||||
|
||||
static void mkdirs(const char *p) {
|
||||
char b[1100]; snprintf(b, sizeof b, "%s", p);
|
||||
for (char *s = b + 1; *s; s++) if (*s == '/') { *s = 0; mkdir(b, 0700); *s = '/'; }
|
||||
mkdir(b, 0700);
|
||||
}
|
||||
// 内部目录 romfs/data/ 下逐个链接到资源目录的文件(游戏按 rom:/data/… 读;链接让资源留在玩家放的位置,不复制 5 GB)
|
||||
// Under the internal dir romfs/data/, link each file of the resource dir (the game reads rom:/data/...; links keep the resources where the player put them instead of copying 5 GB)
|
||||
// 剔零档案的「.holes」区段表也要链过去:hle_fs.c 在档案旁边(即 romfs/data/ 下)找它;缺了就按物理偏移读剔过零的档案,第一个零段之后读到的全错位(解压失败、随后崩溃)
|
||||
// The ".holes" extent tables of zero-stripped archives are linked too: hle_fs.c looks for them next to the archive (in romfs/data/); without them a zero-stripped archive is read at physical offsets, and everything after its first stripped range comes from the wrong place (decompression failures, then a crash)
|
||||
static int link_romfs(const char *romfs) {
|
||||
char data[1100]; snprintf(data, sizeof data, "%s/data", romfs); mkdirs(data);
|
||||
DIR *d = opendir(g_src); if (!d) { LOG("【红】资源目录打不开 %s:errno %d(没给「所有文件访问」权限?)", g_src, errno); return -1; }
|
||||
struct dirent *e; int n = 0;
|
||||
while ((e = readdir(d))) {
|
||||
const char *nm = e->d_name; size_t l = strlen(nm);
|
||||
if (!(l > 5 && !strcmp(nm + l - 5, ".data")) && !(l > 11 && !strcmp(nm + l - 11, ".data.holes")) && strcmp(nm, ".build.config") && strcmp(nm, "build.config")) continue;
|
||||
char from[1100], to[1100]; snprintf(from, sizeof from, "%s/%s", g_src, nm);
|
||||
snprintf(to, sizeof to, "%s/%s", data, strcmp(nm, "build.config") ? nm : ".build.config"); // 电脑上常被存成无点名 | often saved without the leading dot on a computer
|
||||
unlink(to); if (!symlink(from, to)) n++;
|
||||
}
|
||||
closedir(d);
|
||||
return n;
|
||||
}
|
||||
|
||||
static void *host_thread(void *arg) {
|
||||
(void)arg;
|
||||
char out[1200]; snprintf(out, sizeof out, "%s/out", g_runtime);
|
||||
// 图形初始化在宿主线程进行;着色器由玩家在包外提供,失败时停止启动。
|
||||
// Initialize graphics on the host thread; shaders stay external, and failure stops startup.
|
||||
char shaders[1200], error[512] = {0};
|
||||
snprintf(shaders, sizeof shaders, "%s/shaders", g_runtime);
|
||||
int graphics_rc = dm_android_vk_initialize(shaders, error, sizeof error);
|
||||
if (graphics_rc) { LOG("boot: Vulkan initialization failed %d: %s", graphics_rc, error); front_android_boot_failed(-6); return NULL; }
|
||||
char *argv[] = {"dmhost", out, "main", "sdk", NULL};
|
||||
LOG("boot: dm_main %s", out);
|
||||
int rc = dm_main(4, argv);
|
||||
LOG("boot: dm_main 返回 %d", rc);
|
||||
front_android_boot_failed(-7);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// 测试用:files/dm/env 每行 KEY=VALUE(# 开头为注释),在下面的缺省值之前设进环境,让 run-as 能改 DM_* 开关(iOS / Mac 用启动环境变量做同样的事);没有这个文件就什么都不做
|
||||
// For testing: each KEY=VALUE line of files/dm/env (# starts a comment) is set before the defaults below, so run-as can change DM_* switches (iOS / Mac do the same with launch environment variables); without the file nothing happens
|
||||
static void load_env_file(const char *dir) {
|
||||
char path[1300]; snprintf(path, sizeof path, "%s/env", dir);
|
||||
FILE *fp = fopen(path, "r"); if (!fp) return;
|
||||
char line[512];
|
||||
while (fgets(line, sizeof line, fp)) {
|
||||
line[strcspn(line, "\r\n")] = 0;
|
||||
char *eq = strchr(line, '=');
|
||||
if (!line[0] || line[0] == '#' || !eq || eq == line) continue;
|
||||
*eq = 0; setenv(line, eq + 1, 1); LOG("boot: 环境 %s=%s(来自 %s)", line, eq + 1, path);
|
||||
}
|
||||
fclose(fp);
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeStart(JNIEnv *env, jclass cls, jstring files, jstring ext, jstring src, jstring lang) {
|
||||
(void)cls;
|
||||
static int started; if (started) return 0;
|
||||
const char *f = (*env)->GetStringUTFChars(env, files, NULL), *x = (*env)->GetStringUTFChars(env, ext, NULL), *s = (*env)->GetStringUTFChars(env, src, NULL), *lg = (*env)->GetStringUTFChars(env, lang, NULL);
|
||||
snprintf(g_files, sizeof g_files, "%s", f); snprintf(g_ext, sizeof g_ext, "%s", x); snprintf(g_src, sizeof g_src, "%s", s);
|
||||
// 启动时间线零点:Process.getStartUptimeMillis() 是 SystemClock.uptimeMillis(CLOCK_MONOTONIC),与 now_ns 同一时钟(见 main.c proc_start_mono_ns)
|
||||
// Boot timeline zero: Process.getStartUptimeMillis() is SystemClock.uptimeMillis (CLOCK_MONOTONIC), the same clock as now_ns (see main.c proc_start_mono_ns)
|
||||
jclass proc = (*env)->FindClass(env, "android/os/Process");
|
||||
g_proc_start_ns = (uint64_t)(*env)->CallStaticLongMethod(env, proc, (*env)->GetStaticMethodID(env, proc, "getStartUptimeMillis", "()J")) * 1000000ull;
|
||||
// 调试包可用 run-as 导入内部目录;有完整主程序时优先选内部目录。
|
||||
// Debug builds can import via run-as; prefer internal storage when the main module exists.
|
||||
char p[1200]; snprintf(g_runtime, sizeof g_runtime, "%s/dm", g_files);
|
||||
snprintf(p, sizeof p, "%s/out/main.patched.bin", g_runtime);
|
||||
if (access(p, R_OK)) snprintf(g_runtime, sizeof g_runtime, "%s/dm", g_ext);
|
||||
mkdirs(g_runtime);
|
||||
log_init();
|
||||
load_env_file(g_runtime);
|
||||
LOG("boot: 内部目录 %s,外部目录 %s,资源 %s,系统语言 %s", g_files, g_ext, g_src, lg);
|
||||
char romfs[1100], save[1100], temp[1100];
|
||||
snprintf(romfs, sizeof romfs, "%s/romfs", g_files); snprintf(save, sizeof save, "%s/save", g_files); snprintf(temp, sizeof temp, "%s/temp", g_files);
|
||||
mkdirs(save); mkdirs(temp);
|
||||
int n = link_romfs(romfs);
|
||||
LOG("boot: 资源链接 %d 个文件", n);
|
||||
setenv("DM_ROMFS", romfs, 0); setenv("DM_SAVE", save, 0); setenv("DM_TEMP", temp, 0);
|
||||
#ifdef DM_ANDROID_DEBUG_ENV
|
||||
debug_environment();
|
||||
#endif
|
||||
// 被更新的 GPU 结果覆盖、又只有 GPU 读的存储写回不做(引擎的 gfx-wb-skip;标记文件仍优先):营地每帧省 1.37 MB、约 1 ms 的回读。
|
||||
// Storage writebacks that a newer GPU result supersedes and only the GPU reads are dropped (the engine's gfx-wb-skip; a
|
||||
// marker file still wins): 1.37 MB and about 1 ms of readback per camp frame.
|
||||
setenv("DM_GFX_WB_SKIP", "1", 0);
|
||||
// 绘制状态与上一次绘制相同时直接沿用上一次的管线,不再序列化建管线信息去查(引擎的 gfx-pipe-memo;标记文件仍优先)。
|
||||
// A draw whose pipeline state equals the previous draw's reuses its pipeline without serializing the create info for a
|
||||
// lookup (the engine's gfx-pipe-memo; a marker file still wins).
|
||||
setenv("DM_GFX_PIPE_MEMO", "1", 0);
|
||||
// 3D 渲染比例上限 0.85(其他手机平台缺省 0.75,见 hle_oe.c;env 文件仍优先):Redmi K50 Ultra 营地和 9 分钟战斗都稳 60 帧,比 0.75
|
||||
// 多 28% 像素,打 9 分钟多热约 2 °C;重场景或机身过热掉帧时,动态比例每次退 0.05。
|
||||
// 3D render scale ceiling 0.85 (other phone platforms default to 0.75, see hle_oe.c; the env file still wins): on the Redmi K50
|
||||
// Ultra the camp and a 9-minute fight hold 60 fps with 28% more pixels than 0.75 and about 2 C more heat; when heavy scenes or
|
||||
// a hot phone drop frames, the dynamic scale steps down 0.05 at a time.
|
||||
setenv("DM_3D_SCALE", "0.85", 0);
|
||||
// Vulkan 适配器先沿用同步提交;上游新增翻译线程需独立验证对象生命周期。
|
||||
// Keep synchronous submission until the new upstream translation thread's object lifetimes are verified with Vulkan.
|
||||
setenv("DM_NVN_SYNC", "1", 0);
|
||||
// BC 贴图按原格式采样(引擎的 gfx-native-bc;设备支持时;标记文件仍优先):Redmi K50 Ultra 营地 GPU 少 0.5 ms,图像内存 827 → 320 MB。
|
||||
// BC textures sampled in their own formats where the device can (the engine's gfx-native-bc; a marker file still wins):
|
||||
// on the Redmi K50 Ultra camp GPU -0.5 ms and live image memory 827 -> 320 MB.
|
||||
setenv("DM_GFX_NATIVE_BC", "1", 0);
|
||||
// 片元着色器的四元组邻居交换改用精细导数(引擎的 gfx-quad-derivatives;标记文件仍优先):Adreno 上辅助调用在子组洗牌里取到垃圾,
|
||||
// 罪恶洞穴打斗时单位周围出现黑方块。
|
||||
// Fragment-shader quad-neighbour shuffles go through fine derivatives (the engine's gfx-quad-derivatives; a marker file
|
||||
// still wins): on Adreno helper invocations read garbage in subgroup shuffles, and black squares appeared around units in
|
||||
// the Den of Evil fight.
|
||||
setenv("DM_GFX_QUAD_DERIVATIVES", "1", 0);
|
||||
// 按 32 道线程束翻译的计算着色器,在 64 道的子组里每 32 道各当一个线程束(引擎的 gfx-warp32;标记文件仍优先):Adreno 上
|
||||
// 杂物、草地、流体与 PPR 着色器的线程束聚合追加丢了 32–63 号车道、条目互相覆盖。
|
||||
// Compute shaders translated for 32-lane warps run every 32 lanes of a 64-lane subgroup as their own warp (the engine's
|
||||
// gfx-warp32; a marker file still wins): on Adreno the clutter, grass, fluid and PPR shaders' warp-aggregated appends lost
|
||||
// lanes 32-63 and overwrote entries.
|
||||
setenv("DM_GFX_WARP32", "1", 0);
|
||||
// 翻译器输出的两项等价整理(引擎的 gfx-ldc-fold 与 gfx-forward-temps;标记文件仍优先):常量缓冲区按字寻址时可推出的分量下标
|
||||
// 换成常量,只写一次的临时变量直接转发。Redmi K50 Ultra 营地(比例 0.75)GPU 每帧 15.70 → 14.34 ms,结果不变。
|
||||
// Two exact clean-ups of the translator's output (the engine's gfx-ldc-fold and gfx-forward-temps; a marker file still
|
||||
// wins): constant-buffer component indexes that follow from known low bits become constants, and single-store temporaries
|
||||
// are forwarded. Redmi K50 Ultra camp at scale 0.75: GPU 15.70 -> 14.34 ms a frame, with the same results.
|
||||
setenv("DM_GFX_LDC_FOLD", "1", 0);
|
||||
setenv("DM_GFX_FORWARD_TEMPS", "1", 0);
|
||||
// 浮点 min / max / clamp 照 Maxwell 的规矩遇 NaN 取另一个操作数(引擎的 gfx-nan-minmax;标记文件仍优先)。不开时一加 13
|
||||
// (Adreno 830)上恰莎打铁的火花靠近画面上沿时,周围一块矩形会黑一帧。
|
||||
// Float min / max / clamp take the other operand when one is NaN, as on Maxwell (the engine's gfx-nan-minmax; a marker file
|
||||
// still wins). Without it, on the OnePlus 13 (Adreno 830) a rectangle around Charsi goes black for a frame when her hammer
|
||||
// sparks come near the top edge of the screen.
|
||||
setenv("DM_GFX_NAN_MINMAX", "1", 0);
|
||||
// 帧重叠缺省开:命令缓冲里的 SignalEvent 不提交、留到所在槽退役时再公布(引擎的 gfx-defer-events = 2;标记文件仍优先)。
|
||||
// 与呈现端的 gfx-present-overlap 一起,Redmi K50 Ultra 营地从 7.7 fps 到 19.5 fps。
|
||||
// Frame overlap on by default: command-buffer SignalEvents do not submit and are published when their slot retires (the
|
||||
// engine's gfx-defer-events = 2; a marker file still wins). With the presenter's gfx-present-overlap the Redmi K50 Ultra
|
||||
// camp went from 7.7 to 19.5 fps.
|
||||
setenv("DM_GFX_DEFER_EVENTS", "2", 0);
|
||||
// 不在每个绘制、计算和拷贝前先完成全部待写回与报告(引擎的 gfx-read-preflight;标记文件仍优先)。延后事件下几乎总有报告待写,
|
||||
// 开着就等于每个绘制前同步一次 GPU;营地与 Den of Evil 战斗里 CPU 读从未碰到待写结果(NVN PERF why=a0)。
|
||||
// CPU reads are not all resolved before every draw, dispatch and copy (the engine's gfx-read-preflight; a marker file still
|
||||
// wins). With deferred events a report is nearly always pending, so it would sync the GPU before every draw; in the camp
|
||||
// and the Den of Evil fight no CPU read ever met a pending result (NVN PERF why=a0).
|
||||
setenv("DM_GFX_READ_PREFLIGHT", "0", 0);
|
||||
// 另一个槽还在读的回读缓冲改由 GPU 在它之后写入(引擎的 gfx-xview-guard;标记文件仍优先):营地、Den of Evil、奶牛关每帧都有一次
|
||||
// 这种重用;Redmi K50 Ultra 上每帧约 6 个、1.37 MB,进程内对比测不出代价。
|
||||
// Readback buffers the other slot still reads are written by the GPU after it (the engine's gfx-xview-guard; a marker
|
||||
// file still wins): such a reuse happens once a frame in the camp, the Den of Evil and the Cow Level; on the Redmi K50
|
||||
// Ultra about 6 buffers, 1.37 MB, a frame, at no cost measurable in-process.
|
||||
setenv("DM_GFX_XVIEW_GUARD", "1", 0);
|
||||
// 本次提交还没用过的图像,整份上传排到提交之前(引擎的 gfx-upload-prologue;标记文件仍优先),不再在帧中间打断通道:Redmi K50 Ultra
|
||||
// 进营地时打断通道的上传由每次 382-558 个变为 0,第一帧 GPU 85-107 ms(8 次,均值约 96)对关时 106-115 ms(3 次,均值约 109),
|
||||
// 这一帧的上传 CPU 由约 20 ms 降到 12 ms;平常的帧没有上传,不受影响。
|
||||
// Whole uploads of images the current submission has not used yet go ahead of it (the engine's gfx-upload-prologue; a
|
||||
// marker file still wins) instead of breaking the open pass mid-frame: entering the camp on the Redmi K50 Ultra, uploads that
|
||||
// broke a pass went from 382-558 a run to 0, the first frame took 85-107 ms of GPU time (8 runs, mean about 96) against
|
||||
// 106-115 ms off (3 runs, mean about 109), and its upload CPU dropped from about 20 to 12 ms; ordinary frames upload nothing.
|
||||
setenv("DM_GFX_UPLOAD_PROLOGUE", "1", 0);
|
||||
// 着色器载入直接用预热线程改写好的 SPIR-V(引擎的 gfx-shader-reuse;标记文件仍优先):与现场改写逐字相同,每次进营地少约 100 ms 的
|
||||
// 改写 CPU(菜单、进营地、新怪物或新法术出现的帧);代价是预热留着的、这一局没用到的着色器,约 6-13 MB。
|
||||
// Shader loads take the SPIR-V the warm-up threads already rewrote (the engine's gfx-shader-reuse; a marker file still wins):
|
||||
// word for word what rewriting on the spot gives, it saves about 100 ms of rewrite CPU per camp entry (menus, entering the
|
||||
// camp, frames where a new monster or spell appears); the cost is the kept shaders a session does not load, about 6-13 MB.
|
||||
setenv("DM_GFX_SHADER_REUSE", "1", 0);
|
||||
// 顶点与索引的跨帧副本缺省开(引擎的 gfx-vcache;靠 nvn_dirty.c 的写保护脏页跟踪,标记文件仍优先):营地 CPU 少约 0.7 ms。
|
||||
// Cross-frame vertex and index copies on by default (the engine's gfx-vcache, through nvn_dirty.c's write-protect
|
||||
// tracking; a marker file still wins): about 0.7 ms less CPU per camp frame on the Redmi K50 Ultra.
|
||||
setenv("DM_GFX_VCACHE", "1", 0);
|
||||
// 贴图内容检查走同一个写保护脏页跟踪(引擎的 gfx-tex-dirty;标记文件仍优先),同 iOS nvn_mtl.m:上传后设只读,游戏写过
|
||||
// 才重新散列;原先每张贴图每 16 次提交整张重算一次(Redmi K50 Ultra 洞穴打斗渲染线程每帧约 0.27 ms)。
|
||||
// Texture content checks through the same write-protect tracking (the engine's gfx-tex-dirty; a marker file still wins),
|
||||
// as nvn_mtl.m does on iOS: write-protected after upload and re-hashed only after a guest write; before, every texture was
|
||||
// re-hashed whole on every 16th submission (~0.27 ms of the render thread per Den of Evil fight frame).
|
||||
setenv("DM_GFX_TEX_DIRTY", "1", 0);
|
||||
// 命令池在另一线程上重置(引擎的 gfx-async-pool-reset;标记文件仍优先):Redmi K50 Ultra 上 vkResetCommandPool 每帧约占渲染线程 0.4 ms。
|
||||
// Command pools reset on another thread (the engine's gfx-async-pool-reset; a marker file still wins): vkResetCommandPool
|
||||
// took about 0.4 ms of every frame on the Redmi K50 Ultra's render thread.
|
||||
setenv("DM_GFX_ASYNC_POOL_RESET", "1", 0);
|
||||
// 不对 NVN PERF 分项逐帧计时(引擎的 gfx-perf-sample;标记文件仍优先):被计时的那帧渲染线程要多花约 4 ms,在营地里每 32 帧
|
||||
// 必误一次垂直同步。测量时用标记打开。
|
||||
// No NVN PERF parts timing (the engine's gfx-perf-sample; a marker file still wins): a timed frame took ~4 ms more of the
|
||||
// render thread and missed its vsync in the camp, one hitch every 32 frames. Measurement runs turn it on with the marker.
|
||||
setenv("DM_GFX_PERF_SAMPLE", "0", 0);
|
||||
// 客体主线程的短等待先自旋至多 30 µs 再睡(HLE 的 DM_HLE_SPIN_US):D2R 主线程每帧约 45 次短暂地等工作线程持有的锁。
|
||||
// The guest main thread spins up to 30 us before a wait sleeps (the HLE's DM_HLE_SPIN_US): D2R's main thread waits ~45
|
||||
// times a frame, briefly, on locks its job workers hold.
|
||||
setenv("DM_HLE_SPIN_US", "30", 0);
|
||||
if (!getenv("DM_LANG") && *lg) setenv("DM_LANG", lg, 0); // 首次安装的语言按系统首选(同 iOS CFLocaleCopyPreferredLanguages,见 dm_i18n.c) | first-install language follows the system preference (as iOS CFLocaleCopyPreferredLanguages, see dm_i18n.c)
|
||||
if (chdir(g_files)) LOG("【红】chdir %s 失败 errno %d", g_files, errno);
|
||||
(*env)->ReleaseStringUTFChars(env, files, f); (*env)->ReleaseStringUTFChars(env, ext, x); (*env)->ReleaseStringUTFChars(env, src, s); (*env)->ReleaseStringUTFChars(env, lang, lg);
|
||||
if (n <= 0) return -2;
|
||||
char required[1300];
|
||||
const char *modules[] = {"main.patched.bin", "main.fixups.tsv", "main.gates.tsv", "sdk.patched.bin", "sdk.fixups.tsv", "sdk.gates.tsv"};
|
||||
for (unsigned i = 0; i < sizeof modules / sizeof modules[0]; i++) {
|
||||
snprintf(required, sizeof required, "%s/out/%s", g_runtime, modules[i]);
|
||||
if (access(required, R_OK)) { LOG("boot: missing %s", required); return -3; }
|
||||
}
|
||||
snprintf(required, sizeof required, "%s/data/.build.config", romfs);
|
||||
if (access(required, R_OK)) { LOG("boot: missing build configuration"); return -5; }
|
||||
snprintf(required, sizeof required, "%s/shaders", g_runtime);
|
||||
DIR *shaders = opendir(required); int have_shader = 0;
|
||||
if (shaders) { struct dirent *entry; while ((entry = readdir(shaders))) {
|
||||
size_t len = strlen(entry->d_name);
|
||||
if (len > 4 && !strcmp(entry->d_name + len - 4, ".xgs")) { have_shader = 1; break; }
|
||||
} closedir(shaders); }
|
||||
if (!have_shader) { LOG("boot: no shader bundles in %s", required); return -4; }
|
||||
snprintf(required, sizeof required, "%s/overlay", g_runtime);
|
||||
// 启动前核必需覆盖层;旧资源不能自动补指纹,也不能带着错误资源进入游戏。
|
||||
// Validate the required overlay before starting; never stamp old resources or enter with mismatched content.
|
||||
char overlay_reason[256];
|
||||
dm_overlay_result overlay = dm_overlay_validate(required, DM_OVERLAY_SOURCE_SHA256, overlay_reason, sizeof overlay_reason);
|
||||
if (overlay == DM_OVERLAY_OK) overlay = dm_overlay_require_touch_art(required, overlay_reason, sizeof overlay_reason);
|
||||
if (overlay != DM_OVERLAY_OK) {
|
||||
LOG("boot: overlay rejected (%d): %s", overlay, overlay_reason);
|
||||
return overlay == DM_OVERLAY_MISSING ? -9 : -10;
|
||||
}
|
||||
LOG("boot: overlay verified source=%s", DM_OVERLAY_SOURCE_SHA256);
|
||||
setenv("DM_ROMFS_OVERLAY", required, 1);
|
||||
if (!lifecycle_ready()) return -8;
|
||||
pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstacksize(&a, 8u << 20);
|
||||
pthread_t th; int rc = pthread_create(&th, &a, host_thread, NULL); pthread_attr_destroy(&a);
|
||||
if (!rc) { started = 1; pthread_detach(th); }
|
||||
return rc ? -1 : n;
|
||||
}
|
||||
|
||||
static ANativeWindow *g_win;
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeRefresh(JNIEnv *env, jclass cls, jfloat hz) {
|
||||
(void)env; (void)cls;
|
||||
front_android_set_refresh(hz);
|
||||
}
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeSurface(JNIEnv *env, jclass cls, jobject surface, jint w, jint h) {
|
||||
(void)cls;
|
||||
ANativeWindow *old = g_win;
|
||||
g_win = surface ? ANativeWindow_fromSurface(env, surface) : NULL;
|
||||
dm_android_vk_set_window(g_win);
|
||||
front_android_set_window(g_win, w, h);
|
||||
if (old) ANativeWindow_release(old);
|
||||
LOG("前端:画面 %s %dx%d", g_win ? "就绪" : "收回", w, h);
|
||||
}
|
||||
|
||||
// 触点:Java 按手指槽号(最小空槽,抬起前不变)交整组归一化坐标,n = 0 = 全抬起
|
||||
// Touch points: Java hands over the whole set of normalized coordinates by finger slot number (lowest free slot, unchanged until lifted), n = 0 = all lifted
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeTouch(JNIEnv *env, jclass cls, jint n, jintArray ids, jfloatArray xs, jfloatArray ys) {
|
||||
(void)cls;
|
||||
dm_touch t[16]; if (n > 16) n = 16; if (n < 0) n = 0;
|
||||
jint id[16]; jfloat x[16], y[16];
|
||||
if (n) { (*env)->GetIntArrayRegion(env, ids, 0, n, id); (*env)->GetFloatArrayRegion(env, xs, 0, n, x); (*env)->GetFloatArrayRegion(env, ys, 0, n, y); }
|
||||
for (int i = 0; i < n; i++) t[i] = (dm_touch){(uint32_t)id[i], x[i], y[i]};
|
||||
dm_touch_set(t, n);
|
||||
}
|
||||
|
||||
// UI只入队:0失焦,1后台,2前台,3激活;激活也声明前台,合并2/3时不会漏恢复。
|
||||
// UI posts only: 0 unfocused, 1 background, 2 foreground, 3 active; active also declares foreground so merging 2/3 cannot lose resume.
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeFocus(JNIEnv *env, jclass cls, jint ev) {
|
||||
(void)env; (void)cls;
|
||||
dm_android_touch_focus(ev == 2 || ev == 3);
|
||||
if (lifecycle_ready()) {
|
||||
dm_lifecycle_post(&g_lifecycle, ev);
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-lifecycle", "UI posted event=%d", ev);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
// 生命周期最新状态派发:UI不等GPU,单一宿主pthread按顺序执行挂起/恢复。
|
||||
// Latest-state lifecycle dispatch: the UI never waits for GPU; one host pthread serializes suspend/resume.
|
||||
#pragma once
|
||||
#include <pthread.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct dm_lifecycle_ops {
|
||||
void (*focus)(int);
|
||||
void (*audio)(int);
|
||||
void (*graphics)(int);
|
||||
} dm_lifecycle_ops;
|
||||
|
||||
typedef struct dm_lifecycle_dispatch {
|
||||
pthread_mutex_t mutex;
|
||||
pthread_cond_t changed;
|
||||
pthread_t thread;
|
||||
dm_lifecycle_ops ops;
|
||||
uint64_t requested, completed;
|
||||
int background, focus, stopping, started;
|
||||
} dm_lifecycle_dispatch;
|
||||
|
||||
static void *dm_lifecycle_run(void *arg) {
|
||||
dm_lifecycle_dispatch *d = arg;
|
||||
int applied_background = 0;
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&d->mutex);
|
||||
while (!d->stopping && d->requested == d->completed) pthread_cond_wait(&d->changed, &d->mutex);
|
||||
if (d->stopping) { pthread_mutex_unlock(&d->mutex); return NULL; }
|
||||
uint64_t request = d->requested;
|
||||
int background = d->background, focus = d->focus;
|
||||
pthread_mutex_unlock(&d->mutex);
|
||||
|
||||
// GPU挂起可等Surface;这个锁必须已经释放,UI才能继续提供新Surface和前台状态。
|
||||
// Graphics suspend can wait for a Surface; release this lock so UI can supply it and post foreground state.
|
||||
if (background != applied_background) {
|
||||
if (background) { d->ops.focus(3); d->ops.audio(1); d->ops.graphics(1); }
|
||||
else { d->ops.graphics(0); d->ops.audio(0); }
|
||||
applied_background = background;
|
||||
}
|
||||
pthread_mutex_lock(&d->mutex);
|
||||
int current = request == d->requested;
|
||||
pthread_mutex_unlock(&d->mutex);
|
||||
// 挂起期间已恢复时,不再发布过期焦点;下一轮先解开图形门,再恢复音频和最新焦点。
|
||||
// If state changed while suspending, skip stale focus; the next turn opens graphics, then audio and latest focus.
|
||||
if (current) d->ops.focus(focus);
|
||||
pthread_mutex_lock(&d->mutex);
|
||||
d->completed = request;
|
||||
pthread_cond_broadcast(&d->changed);
|
||||
pthread_mutex_unlock(&d->mutex);
|
||||
}
|
||||
}
|
||||
|
||||
static int dm_lifecycle_start(dm_lifecycle_dispatch *d, dm_lifecycle_ops ops) {
|
||||
memset(d, 0, sizeof *d);
|
||||
d->ops = ops; d->focus = 1;
|
||||
int rc = pthread_mutex_init(&d->mutex, NULL);
|
||||
if (rc) return rc;
|
||||
rc = pthread_cond_init(&d->changed, NULL);
|
||||
if (rc) { pthread_mutex_destroy(&d->mutex); return rc; }
|
||||
rc = pthread_create(&d->thread, NULL, dm_lifecycle_run, d);
|
||||
if (rc) { pthread_cond_destroy(&d->changed); pthread_mutex_destroy(&d->mutex); return rc; }
|
||||
d->started = 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void dm_lifecycle_post(dm_lifecycle_dispatch *d, int event) {
|
||||
if (event < 0 || event > 3) return;
|
||||
pthread_mutex_lock(&d->mutex);
|
||||
if (event == 1) d->background = 1;
|
||||
else if (event == 2 || event == 3) d->background = 0;
|
||||
d->focus = event == 1 ? 3 : event == 3 ? 1 : 2;
|
||||
++d->requested;
|
||||
pthread_cond_signal(&d->changed);
|
||||
pthread_mutex_unlock(&d->mutex);
|
||||
}
|
||||
|
||||
// 只供显式宿主关闭/CPU测试;UI生命周期回调绝不join或等待它。
|
||||
// For explicit host shutdown / CPU tests only; UI lifecycle callbacks never join or wait here.
|
||||
static void dm_lifecycle_stop(dm_lifecycle_dispatch *d) {
|
||||
if (!d->started) return;
|
||||
pthread_mutex_lock(&d->mutex); d->stopping = 1; pthread_cond_signal(&d->changed); pthread_mutex_unlock(&d->mutex);
|
||||
pthread_join(d->thread, NULL);
|
||||
pthread_cond_destroy(&d->changed); pthread_mutex_destroy(&d->mutex); d->started = 0;
|
||||
}
|
||||
@@ -0,0 +1,354 @@
|
||||
/* Read-only overlay contract validator. Hashes stream through 64 KiB; no game
|
||||
* archive is loaded as a whole. Paths are opened relative to the overlay dirfd
|
||||
* with O_NOFOLLOW at EVERY component. The manifest is never auto-generated.
|
||||
*/
|
||||
#ifndef _POSIX_C_SOURCE
|
||||
#define _POSIX_C_SOURCE 200809L
|
||||
#endif
|
||||
#include "overlay_validate.h"
|
||||
#include <CommonCrypto/CommonDigest.h>
|
||||
#include <dirent.h>
|
||||
#include <errno.h>
|
||||
#include <fcntl.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <strings.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#define OV_MANIFEST "overlay.manifest"
|
||||
#define OV_MAGIC "DM_OVERLAY_V1 "
|
||||
#define OV_PATH_MAX 1024
|
||||
#define OV_DEPTH_MAX 32
|
||||
#define OV_FILES_MAX 4096
|
||||
#define OV_NODES_MAX (OV_FILES_MAX * 2)
|
||||
#define OV_MANIFEST_MAX (4u * 1024u * 1024u)
|
||||
#define OV_FILE_MAX (UINT64_C(8) * 1024 * 1024 * 1024)
|
||||
#define OV_TOTAL_MAX (UINT64_C(16) * 1024 * 1024 * 1024)
|
||||
#define OV_LINE_MAX (OV_PATH_MAX + 66)
|
||||
|
||||
typedef struct { char *path; unsigned char hash[CC_SHA256_DIGEST_LENGTH]; } ov_entry;
|
||||
typedef struct {
|
||||
ov_entry *entries;
|
||||
size_t count, capacity;
|
||||
size_t scanned_nodes;
|
||||
uint64_t total_bytes;
|
||||
char *reason;
|
||||
size_t reason_capacity;
|
||||
} ov_check;
|
||||
|
||||
static dm_overlay_result ov_fail(ov_check *v, dm_overlay_result code, const char *fmt, ...) {
|
||||
if (v->reason && v->reason_capacity) {
|
||||
va_list args; va_start(args, fmt);
|
||||
vsnprintf(v->reason, v->reason_capacity, fmt, args);
|
||||
va_end(args);
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
static int ov_hex(const char *text, size_t length, unsigned char digest[32]) {
|
||||
if (length != 64) return 0;
|
||||
for (size_t i = 0; i < 32; ++i) {
|
||||
unsigned value = 0;
|
||||
for (size_t j = 0; j < 2; ++j) {
|
||||
unsigned char c = (unsigned char)text[2 * i + j];
|
||||
unsigned n;
|
||||
if (c >= '0' && c <= '9') n = c - '0';
|
||||
else if (c >= 'a' && c <= 'f') n = c - 'a' + 10;
|
||||
else return 0;
|
||||
value = value * 16 + n;
|
||||
}
|
||||
digest[i] = (unsigned char)value;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int ov_reserved(const char *part, size_t length) {
|
||||
size_t stem = 0;
|
||||
while (stem < length && part[stem] != '.') ++stem;
|
||||
if (stem == 3 && (!strncasecmp(part, "CON", 3) || !strncasecmp(part, "PRN", 3)
|
||||
|| !strncasecmp(part, "AUX", 3) || !strncasecmp(part, "NUL", 3))) return 1;
|
||||
return stem == 4 && part[3] >= '1' && part[3] <= '9'
|
||||
&& (!strncasecmp(part, "COM", 3) || !strncasecmp(part, "LPT", 3));
|
||||
}
|
||||
|
||||
static int ov_path(const char *path) {
|
||||
size_t length = strlen(path), start = 0, depth = 0;
|
||||
if (!length || length > OV_PATH_MAX) return 0;
|
||||
for (size_t i = 0; i <= length; ++i) {
|
||||
unsigned char c = (unsigned char)path[i];
|
||||
if (c == '/' || c == 0) {
|
||||
size_t n = i - start;
|
||||
if (!n || ++depth > OV_DEPTH_MAX || path[i - 1] == '.' || ov_reserved(path + start, n)) return 0;
|
||||
start = i + 1;
|
||||
} else if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')
|
||||
|| (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '+' || c == '.')) return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static int ov_is_data(const char *path) {
|
||||
size_t n = strlen(path);
|
||||
return n >= 10 && !strncmp(path, "data/", 5) && !strchr(path + 5, '/') && !strcmp(path + n - 5, ".data");
|
||||
}
|
||||
|
||||
static int ov_required(const char *path) {
|
||||
if (!strcmp(path, "ctrl_touch")) return 1;
|
||||
if (!strcmp(path, "touch_strings.tsv")) return 2;
|
||||
if (!strcmp(path, "data/.build.config")) return 4;
|
||||
return ov_is_data(path) ? 8 : 0;
|
||||
}
|
||||
|
||||
/* Bounded lines, strict LF+ASCII. EOF mid-line is invalid, not accepted as a
|
||||
* complete last row. A NUL cannot hide a second path from strlen/strcmp.
|
||||
*/
|
||||
static int ov_line(FILE *stream, char line[OV_LINE_MAX], size_t *total) {
|
||||
size_t used = 0;
|
||||
for (;;) {
|
||||
int c = fgetc(stream);
|
||||
if (c == EOF) return ferror(stream) || used ? -1 : 0;
|
||||
if (++*total > OV_MANIFEST_MAX) return -1;
|
||||
if (c == '\n') { line[used] = 0; return 1; }
|
||||
if (c < 32 || c > 126 || used + 1 >= OV_LINE_MAX) return -1;
|
||||
line[used++] = (char)c;
|
||||
}
|
||||
}
|
||||
|
||||
static int ov_fold_compare(const void *left, const void *right) {
|
||||
const ov_entry *const *a = left, *const *b = right;
|
||||
return strcasecmp((*a)->path, (*b)->path);
|
||||
}
|
||||
|
||||
static dm_overlay_result ov_read_manifest(ov_check *v, int fd, const char *expected) {
|
||||
struct stat info;
|
||||
if (fstat(fd, &info) || !S_ISREG(info.st_mode) || info.st_size < 0
|
||||
|| (uint64_t)info.st_size > OV_MANIFEST_MAX) {
|
||||
close(fd); return ov_fail(v, DM_OVERLAY_INVALID, "manifest: not a bounded regular file");
|
||||
}
|
||||
FILE *stream = fdopen(fd, "rb");
|
||||
if (!stream) { close(fd); return ov_fail(v, DM_OVERLAY_INVALID, "manifest: cannot read"); }
|
||||
char line[OV_LINE_MAX]; size_t total = 0; int line_number = 1, required = 0, result;
|
||||
dm_overlay_result status = DM_OVERLAY_INVALID;
|
||||
if (ov_line(stream, line, &total) != 1 || strlen(line) != strlen(OV_MAGIC) + 64
|
||||
|| strncmp(line, OV_MAGIC, strlen(OV_MAGIC)) || strcmp(line + strlen(OV_MAGIC), expected)) {
|
||||
ov_fail(v, status, "manifest: source fingerprint mismatch or malformed header"); goto done;
|
||||
}
|
||||
while ((result = ov_line(stream, line, &total)) == 1) {
|
||||
++line_number;
|
||||
unsigned char hash[32]; size_t length = strlen(line);
|
||||
if (length < 66 || line[64] != ' ' || !ov_hex(line, 64, hash) || !ov_path(line + 65)) {
|
||||
ov_fail(v, status, "manifest: malformed line %d", line_number); goto done;
|
||||
}
|
||||
const char *path = line + 65;
|
||||
if (!strcasecmp(path, OV_MANIFEST) || (v->count && strcmp(v->entries[v->count - 1].path, path) >= 0)) {
|
||||
ov_fail(v, status, "manifest: duplicate, excluded or unordered path: %s", path); goto done;
|
||||
}
|
||||
if (v->count == OV_FILES_MAX) { ov_fail(v, status, "manifest: too many files"); goto done; }
|
||||
if (v->count == v->capacity) {
|
||||
size_t cap = v->capacity ? v->capacity * 2 : 32;
|
||||
ov_entry *entries = realloc(v->entries, cap * sizeof *entries);
|
||||
if (!entries) { ov_fail(v, status, "manifest: allocation failed"); goto done; }
|
||||
v->entries = entries; v->capacity = cap;
|
||||
}
|
||||
char *copy = strdup(path);
|
||||
if (!copy) { ov_fail(v, status, "manifest: allocation failed"); goto done; }
|
||||
v->entries[v->count].path = copy;
|
||||
memcpy(v->entries[v->count].hash, hash, sizeof hash);
|
||||
++v->count; required |= ov_required(path);
|
||||
}
|
||||
if (result < 0) { ov_fail(v, status, "manifest: damaged or oversized line %d", line_number + 1); goto done; }
|
||||
if (required != 15) { ov_fail(v, status, "manifest: missing required marker, strings, config or data archive"); goto done; }
|
||||
ov_entry **folded = malloc(v->count * sizeof *folded);
|
||||
if (!folded) { ov_fail(v, status, "manifest: allocation failed"); goto done; }
|
||||
for (size_t i = 0; i < v->count; ++i) folded[i] = &v->entries[i];
|
||||
qsort(folded, v->count, sizeof *folded, ov_fold_compare);
|
||||
for (size_t i = 1; i < v->count; ++i) {
|
||||
if (!strcasecmp(folded[i - 1]->path, folded[i]->path)) {
|
||||
ov_fail(v, status, "manifest: case-ambiguous path: %s", folded[i]->path);
|
||||
free(folded); goto done;
|
||||
}
|
||||
}
|
||||
free(folded); status = DM_OVERLAY_OK;
|
||||
done:
|
||||
fclose(stream);
|
||||
return status;
|
||||
}
|
||||
|
||||
static int ov_open_file(int rootfd, const char *path) {
|
||||
char copy[OV_PATH_MAX + 1]; strcpy(copy, path);
|
||||
int directory = dup(rootfd);
|
||||
if (directory < 0) return -1;
|
||||
char *part = copy;
|
||||
for (;;) {
|
||||
char *slash = strchr(part, '/');
|
||||
if (!slash) {
|
||||
int fd = openat(directory, part, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
|
||||
close(directory); return fd;
|
||||
}
|
||||
*slash = 0;
|
||||
int next = openat(directory, part, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_DIRECTORY);
|
||||
close(directory);
|
||||
if (next < 0) return -1;
|
||||
directory = next; part = slash + 1;
|
||||
}
|
||||
}
|
||||
|
||||
static dm_overlay_result ov_hash_file(ov_check *v, int rootfd, const ov_entry *entry) {
|
||||
int fd = ov_open_file(rootfd, entry->path);
|
||||
if (fd < 0) return ov_fail(v, DM_OVERLAY_INVALID, "payload: missing, unreadable or linked: %s", entry->path);
|
||||
struct stat before, after;
|
||||
dm_overlay_result status = DM_OVERLAY_INVALID;
|
||||
if (fstat(fd, &before) || !S_ISREG(before.st_mode) || before.st_size < 0
|
||||
|| (uint64_t)before.st_size > OV_FILE_MAX
|
||||
|| (ov_required(entry->path) && !before.st_size)
|
||||
|| (uint64_t)before.st_size > OV_TOTAL_MAX - v->total_bytes) {
|
||||
ov_fail(v, status, "payload: invalid type, empty required file or byte limit: %s", entry->path); goto done;
|
||||
}
|
||||
unsigned char buffer[64 * 1024], digest[32]; CC_SHA256_CTX hash;
|
||||
uint64_t bytes = 0; ssize_t n;
|
||||
if (!CC_SHA256_Init(&hash)) { ov_fail(v, status, "payload: digest initialization failed"); goto done; }
|
||||
while ((n = read(fd, buffer, sizeof buffer)) != 0) {
|
||||
if (n < 0) { if (errno == EINTR) continue; ov_fail(v, status, "payload: read failed: %s", entry->path); goto done; }
|
||||
bytes += (uint64_t)n;
|
||||
if (bytes > (uint64_t)before.st_size || !CC_SHA256_Update(&hash, buffer, (CC_LONG)n)) {
|
||||
ov_fail(v, status, "payload: changed or digest failed: %s", entry->path); goto done;
|
||||
}
|
||||
}
|
||||
if (fstat(fd, &after) || bytes != (uint64_t)before.st_size || before.st_size != after.st_size
|
||||
|| before.st_mtim.tv_sec != after.st_mtim.tv_sec || before.st_mtim.tv_nsec != after.st_mtim.tv_nsec
|
||||
|| !CC_SHA256_Final(digest, &hash) || memcmp(digest, entry->hash, sizeof digest)) {
|
||||
ov_fail(v, status, "payload: digest mismatch or changed: %s", entry->path); goto done;
|
||||
}
|
||||
v->total_bytes += bytes; status = DM_OVERLAY_OK;
|
||||
done:
|
||||
close(fd); return status;
|
||||
}
|
||||
|
||||
static int ov_has_entry(const ov_check *v, const char *path) {
|
||||
size_t lo = 0, hi = v->count;
|
||||
while (lo < hi) {
|
||||
size_t mid = lo + (hi - lo) / 2;
|
||||
int cmp = strcmp(path, v->entries[mid].path);
|
||||
if (!cmp) return 1;
|
||||
if (cmp < 0) hi = mid; else lo = mid + 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
dm_overlay_result dm_overlay_require_touch_art(const char *directory, char *reason, size_t reason_capacity) {
|
||||
ov_check v={.reason=reason,.reason_capacity=reason_capacity};
|
||||
int rootfd=open(directory,O_RDONLY|O_CLOEXEC|O_DIRECTORY|O_NOFOLLOW);
|
||||
if (rootfd<0) return ov_fail(&v,DM_OVERLAY_INVALID,"touch art: unreadable overlay");
|
||||
/* 原版图集和HUD只接受外部导入;旧版只含CASC的overlay不能静默失去技能图标和数值。
|
||||
Native atlases and HUD are externally imported; old CASC-only overlays must not silently lose icons and numbers. */
|
||||
static const char *const names[]={
|
||||
"touchart/dm_native_skill_0.png","touchart/dm_native_skill_1.png","touchart/dm_native_skill_2.png",
|
||||
"touchart/dm_native_skill_3.png","touchart/dm_native_skill_4.png","touchart/dm_native_skill_5.png",
|
||||
"touchart/dm_native_skill_6.png","touchart/dm_native_skill_7.png","touchart/dm_native_skill_8.png",
|
||||
"touchart/dm_mobile_socket.png",
|
||||
"hud_v4_ui/sil_dm_native_skill_0.png","hud_v4_ui/sil_dm_native_skill_1.png","hud_v4_ui/sil_dm_native_skill_2.png",
|
||||
"hud_v4_ui/sil_dm_native_skill_3.png","hud_v4_ui/sil_dm_native_skill_4.png","hud_v4_ui/sil_dm_native_skill_5.png",
|
||||
"hud_v4_ui/sil_dm_native_skill_6.png","hud_v4_ui/sil_dm_native_skill_7.png","hud_v4_ui/sil_dm_native_skill_8.png",
|
||||
"hud_v4_ui/ui.json","hud_v4_ui/base_full.png","hud_v4_ui/lvl_0.png","hud_v4_ui/lvl_1.png",
|
||||
"hud_v4_ui/lvl_d0.png","hud_v4_ui/lvl_d1.png","hud_v4_ui/slot.png",
|
||||
"hud_v4_ui/diff_1.png","hud_v4_ui/diff_2.png","hud_v4_ui/diff_3.png","hud_v4_ui/diff_4.png",
|
||||
"hud_v4_ui/diff_5.png","hud_v4_ui/diff_6.png","hud_v4_ui/diff_7.png","hud_v4_ui/diff_8.png"};
|
||||
dm_overlay_result status=DM_OVERLAY_OK;
|
||||
for (size_t i=0;i<sizeof names/sizeof names[0];++i) {
|
||||
int fd=ov_open_file(rootfd,names[i]); struct stat info;
|
||||
if (fd<0 || fstat(fd,&info) || !S_ISREG(info.st_mode) || info.st_size<=0) {
|
||||
if(fd>=0)close(fd);
|
||||
status=ov_fail(&v,DM_OVERLAY_INVALID,"touch art: missing or invalid: %s",names[i]); break;
|
||||
}
|
||||
close(fd);
|
||||
}
|
||||
close(rootfd);return status;
|
||||
}
|
||||
|
||||
static dm_overlay_result ov_inventory(ov_check *v, int dirfd_value, const char *prefix, unsigned depth, size_t *seen) {
|
||||
if (depth > OV_DEPTH_MAX) return ov_fail(v, DM_OVERLAY_INVALID, "overlay: directory depth exceeded");
|
||||
int copy = dup(dirfd_value);
|
||||
if (copy < 0) return ov_fail(v, DM_OVERLAY_INVALID, "overlay: cannot duplicate directory");
|
||||
DIR *directory = fdopendir(copy);
|
||||
if (!directory) { close(copy); return ov_fail(v, DM_OVERLAY_INVALID, "overlay: cannot enumerate directory"); }
|
||||
dm_overlay_result status = DM_OVERLAY_OK;
|
||||
for (;;) {
|
||||
errno = 0;
|
||||
struct dirent *item = readdir(directory);
|
||||
if (!item) {
|
||||
if (errno) status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: directory read failed");
|
||||
break;
|
||||
}
|
||||
if (!strcmp(item->d_name, ".") || !strcmp(item->d_name, "..")) continue;
|
||||
if (++v->scanned_nodes > OV_NODES_MAX) { status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: directory entry limit exceeded"); break; }
|
||||
char relative[OV_PATH_MAX + 1];
|
||||
int length = snprintf(relative, sizeof relative, "%s%s", prefix, item->d_name);
|
||||
struct stat info;
|
||||
if (length < 0 || (size_t)length >= sizeof relative || !ov_path(relative)) {
|
||||
status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: unsafe or overlong path"); break;
|
||||
}
|
||||
if (!strcasecmp(relative, OV_MANIFEST) && strcmp(relative, OV_MANIFEST)) {
|
||||
status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: case-ambiguous manifest path"); break;
|
||||
}
|
||||
if (fstatat(dirfd_value, item->d_name, &info, AT_SYMLINK_NOFOLLOW)) {
|
||||
status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: cannot inspect: %s", relative); break;
|
||||
}
|
||||
if (S_ISDIR(info.st_mode)) {
|
||||
if ((size_t)length + 1 >= sizeof relative) { status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: path too long"); break; }
|
||||
int child = openat(dirfd_value, item->d_name, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
|
||||
if (child < 0) { status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: linked or unreadable directory: %s", relative); break; }
|
||||
relative[length] = '/'; relative[length + 1] = 0;
|
||||
status = ov_inventory(v, child, relative, depth + 1, seen);
|
||||
close(child);
|
||||
if (status != DM_OVERLAY_OK) break;
|
||||
} else if (!S_ISREG(info.st_mode)) {
|
||||
status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: link or special file: %s", relative); break;
|
||||
} else if (strcmp(relative, OV_MANIFEST)) {
|
||||
if (!ov_has_entry(v, relative) || ++*seen > OV_FILES_MAX) {
|
||||
status = ov_fail(v, DM_OVERLAY_INVALID, "overlay: unlisted file: %s", relative); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
closedir(directory); return status;
|
||||
}
|
||||
|
||||
dm_overlay_result dm_overlay_validate(const char *directory, const char *expected_source_sha256,
|
||||
char *reason, size_t reason_capacity) {
|
||||
ov_check v = {.reason = reason, .reason_capacity = reason_capacity};
|
||||
unsigned char expected[32];
|
||||
if (reason && reason_capacity) reason[0] = 0;
|
||||
if (!directory || !expected_source_sha256 || !ov_hex(expected_source_sha256, strlen(expected_source_sha256), expected))
|
||||
return ov_fail(&v, DM_OVERLAY_INVALID, "overlay: invalid validation arguments");
|
||||
struct stat root_info;
|
||||
if (lstat(directory, &root_info))
|
||||
return ov_fail(&v, errno == ENOENT || errno == ENOTDIR ? DM_OVERLAY_MISSING : DM_OVERLAY_INVALID,
|
||||
"overlay: missing or unreadable directory");
|
||||
if (S_ISLNK(root_info.st_mode)) return ov_fail(&v, DM_OVERLAY_INVALID, "overlay: linked root directory");
|
||||
int rootfd = open(directory, O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW);
|
||||
if (rootfd < 0) return ov_fail(&v, errno == ENOENT || errno == ENOTDIR ? DM_OVERLAY_MISSING : DM_OVERLAY_INVALID,
|
||||
"overlay: missing, linked or unreadable directory");
|
||||
int fd = openat(rootfd, OV_MANIFEST, O_RDONLY | O_CLOEXEC | O_NOFOLLOW | O_NONBLOCK);
|
||||
if (fd < 0) {
|
||||
dm_overlay_result missing = errno == ENOENT ? DM_OVERLAY_MISSING : DM_OVERLAY_INVALID;
|
||||
close(rootfd); return ov_fail(&v, missing, "overlay: missing, linked or unreadable manifest");
|
||||
}
|
||||
dm_overlay_result status = ov_read_manifest(&v, fd, expected_source_sha256);
|
||||
if (status == DM_OVERLAY_OK) {
|
||||
for (size_t i = 0; i < v.count; ++i) {
|
||||
status = ov_hash_file(&v, rootfd, &v.entries[i]);
|
||||
if (status != DM_OVERLAY_OK) break;
|
||||
}
|
||||
}
|
||||
if (status == DM_OVERLAY_OK) {
|
||||
size_t seen = 0;
|
||||
status = ov_inventory(&v, rootfd, "", 0, &seen);
|
||||
if (status == DM_OVERLAY_OK && seen != v.count) status = ov_fail(&v, DM_OVERLAY_INVALID, "overlay: manifest file count mismatch");
|
||||
}
|
||||
close(rootfd);
|
||||
for (size_t i = 0; i < v.count; ++i) free(v.entries[i].path);
|
||||
free(v.entries);
|
||||
return status;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Stable result values. JNI may map MISSING to -9 and INVALID to -10.
|
||||
* Missing directory/manifest is distinct from an installed but invalid overlay.
|
||||
* Validation is read-only: no repairs, process exit, save or resource writes.
|
||||
*/
|
||||
typedef enum {
|
||||
DM_OVERLAY_OK = 0,
|
||||
DM_OVERLAY_MISSING = 1,
|
||||
DM_OVERLAY_INVALID = 2
|
||||
} dm_overlay_result;
|
||||
|
||||
dm_overlay_result dm_overlay_validate(const char *directory,
|
||||
const char *expected_source_sha256,
|
||||
char *reason, size_t reason_capacity);
|
||||
/* 完整manifest验证通过后检查安卓绘制所需的固定资源;只读,不补写文件。
|
||||
* After full manifest verification, require Android's fixed drawing assets; read-only, never repairs files. */
|
||||
dm_overlay_result dm_overlay_require_touch_art(const char *directory, char *reason, size_t reason_capacity);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,136 @@
|
||||
// 安卓真机探针:宿主方案在这台机器上成不成立,一次跑完、逐项报 OK / FAIL。
|
||||
// 用法:NDK clang 编成可执行文件,adb push 到 /data/local/tmp 运行(shell 身份;应用身份的内存上限另在 App 里测)。
|
||||
// ① 页大小、CPU 特性;② bionic 键表(改写器 DM_TARGET=android 的线程槽取法)并用一段运行时生成的补丁同款代码实读;
|
||||
// ③ 匿名页写入后改只读+执行能否执行(装载器 map_image 的做法);④ x18:宿主线程里是什么、跨调度会不会被改;
|
||||
// ⑤ 新线程有没有备用信号栈(补丁块借用 SP 下方 16–24 字节,Linux 没有红区保证,信号必须走备用栈);⑥ 大块地址保留。
|
||||
// Android device probe: whether the host's approach holds on this machine, run all at once and report OK / FAIL item by item.
|
||||
// Usage: build as an executable with NDK clang, adb push to /data/local/tmp and run (shell identity; the memory limit under the app identity is measured separately in the App).
|
||||
// ① page size, CPU features; ② the bionic key table (the thread slot access of rewriter DM_TARGET=android), read for real through run-time generated code identical to the patch code;
|
||||
// ③ whether anonymous pages can execute after being written and switched to read-only+execute (what the loader's map_image does); ④ x18: what it holds in host threads and whether scheduling changes it;
|
||||
// ⑤ whether new threads have an alternate signal stack (patch blocks borrow 16–24 bytes below SP, Linux gives no red zone guarantee, so signals must use the alternate stack); ⑥ large address reservations.
|
||||
#include <pthread.h>
|
||||
#include <signal.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sched.h>
|
||||
#include <sys/auxv.h>
|
||||
#include <sys/mman.h>
|
||||
#include <unistd.h>
|
||||
|
||||
static int g_fail;
|
||||
#define OK(...) do { printf("OK " __VA_ARGS__); putchar('\n'); } while (0)
|
||||
#define FAIL(...) do { printf("FAIL " __VA_ARGS__); putchar('\n'); g_fail++; } while (0)
|
||||
#define INFO(...) do { printf("INFO " __VA_ARGS__); putchar('\n'); } while (0)
|
||||
|
||||
static uint8_t *tsd_base(void) { uint64_t tp; __asm__ volatile("mrs %0, tpidr_el0" : "=r"(tp)); return ((uint8_t **)tp)[-1]; }
|
||||
static uint64_t g_tsd_off;
|
||||
static uint64_t kidx(pthread_key_t k) { return (uint32_t)k & 0x7fffffffu; } // bionic 键号带第 31 位有效标记 | bionic key numbers carry a validity flag in bit 31
|
||||
static pthread_key_t g_k1, g_k2;
|
||||
|
||||
static void probe_tsd(void) {
|
||||
void *const m1 = (void *)0x6d4d7d5d4d3d2d1dull, *const m2 = (void *)0x1d2d3d4d5d7d4d6dull;
|
||||
// 先占掉几个键,让被测键号不是 0(装载器实际拿到的键号也不会是 0)
|
||||
// Use up a few keys first so the tested key number is not 0 (the key numbers the loader actually gets are not 0 either)
|
||||
pthread_key_t pad[5]; for (int i = 0; i < 5; i++) pthread_key_create(&pad[i], NULL);
|
||||
if (pthread_key_create(&g_k1, NULL) || pthread_key_create(&g_k2, NULL)) { FAIL("pthread_key_create"); return; }
|
||||
pthread_setspecific(g_k1, m1);
|
||||
uint8_t *b = tsd_base(); uint64_t at = 0;
|
||||
for (uint64_t o = 8; o < 0x4000 && !at; o += 8) if (*(void **)(b + o) == m1) at = o;
|
||||
if (!at) { FAIL("bionic 键表:键 %d 的值不在 bionic_tls 前 16 KB", (int)g_k1); return; }
|
||||
g_tsd_off = at - kidx(g_k1) * 16 - 8;
|
||||
pthread_setspecific(g_k2, m2);
|
||||
if (*(void **)(b + g_tsd_off + kidx(g_k2) * 16 + 8) == m2) OK("bionic 键表偏移 %#llx(键 %#x / %#x 都对得上)", (unsigned long long)g_tsd_off, (unsigned)g_k1, (unsigned)g_k2);
|
||||
else FAIL("bionic 键表:键 %d 推出的偏移 %#llx 对键 %d 不成立", (int)g_k1, (unsigned long long)g_tsd_off, (int)g_k2);
|
||||
}
|
||||
|
||||
// 运行时生成与 patch_nso.py(DM_TARGET=android)同款的取槽代码:mrs x0,tpidr_el0; ldur x0,[x0,#-8]; ldr x1,[keypage]; add x0,x0,x1; ldr x0,[x0]; ret
|
||||
// Generate at run time slot-fetch code identical to patch_nso.py (DM_TARGET=android): mrs x0,tpidr_el0; ldur x0,[x0,#-8]; ldr x1,[keypage]; add x0,x0,x1; ldr x0,[x0]; ret
|
||||
typedef uint64_t (*slotfn)(void);
|
||||
static slotfn g_slotfn;
|
||||
static void probe_exec(void) {
|
||||
long pg = sysconf(_SC_PAGESIZE);
|
||||
size_t sz = 0x8000; // 两页 16 KB:代码一页、键页一页(与装载器的 16 KB 粒度一致) | Two 16 KB pages: one code, one key page (matching the loader's 16 KB granularity)
|
||||
uint8_t *p = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
if (p == MAP_FAILED) { FAIL("mmap 匿名页"); return; }
|
||||
uint64_t *key = (uint64_t *)(p + 0x4000);
|
||||
key[0] = g_tsd_off + kidx(g_k1) * 16 + 8;
|
||||
uint32_t *c = (uint32_t *)p; int n = 0;
|
||||
c[n++] = 0xD53BD040 | 0; // mrs x0, tpidr_el0
|
||||
c[n++] = 0xF8400000 | ((-8 & 0x1FF) << 12) | 0; // ldur x0, [x0, #-8]
|
||||
{ int32_t imm = (int32_t)(0x4000 - 4 * n) >> 2; c[n++] = 0x58000000 | ((imm & 0x7FFFF) << 5) | 1; } // ldr x1, =key[0](字面量池寻址) | ldr x1, =key[0] (literal addressing)
|
||||
c[n++] = 0x8B010000; // add x0, x0, x1
|
||||
c[n++] = 0xF9400000; // ldr x0, [x0]
|
||||
c[n++] = 0xD65F03C0; // ret
|
||||
__builtin___clear_cache((char *)p, (char *)(p + 4 * n));
|
||||
if (mprotect(p, 0x4000, PROT_READ | PROT_EXEC)) { FAIL("mprotect 只读+执行被拒(页大小 %ld)", pg); return; }
|
||||
if (mprotect(p + 0x4000, 0x4000, PROT_READ)) { FAIL("mprotect 键页只读"); return; }
|
||||
g_slotfn = (slotfn)p;
|
||||
uint64_t v = g_slotfn();
|
||||
if (v == 0x6d4d7d5d4d3d2d1dull) OK("匿名页改只读+执行后可执行,补丁同款取槽代码读到键 %d 的值", (int)g_k1);
|
||||
else FAIL("补丁同款取槽代码读到 %#llx", (unsigned long long)v);
|
||||
// 写入后可执行页也可 RWX?(只记录,宿主不依赖) | Is RWX also allowed? (recorded only; the host does not depend on it)
|
||||
void *rwx = mmap(NULL, 0x4000, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANON, -1, 0);
|
||||
INFO("RWX 匿名页:%s", rwx == MAP_FAILED ? "被拒" : "允许"); if (rwx != MAP_FAILED) munmap(rwx, 0x4000);
|
||||
}
|
||||
|
||||
static uint64_t read_x18(void) { uint64_t v; __asm__ volatile("mov %0, x18" : "=r"(v)); return v; }
|
||||
|
||||
struct thr { uint64_t x18; uint64_t slot; int altstack; size_t altsize; int slot_ok; };
|
||||
static void *thr_main(void *arg) {
|
||||
struct thr *t = arg;
|
||||
t->x18 = read_x18();
|
||||
stack_t ss; t->altstack = sigaltstack(NULL, &ss) == 0 && !(ss.ss_flags & SS_DISABLE); t->altsize = ss.ss_size;
|
||||
// 新线程里经同一段生成代码取槽:设值后读,验证「每线程各自一份」 | Fetch the slot via the same generated code in a new thread: set then read, verifying "one copy per thread"
|
||||
if (g_slotfn) { pthread_setspecific(g_k1, (void *)0x5151); t->slot = g_slotfn(); t->slot_ok = t->slot == 0x5151; }
|
||||
return NULL;
|
||||
}
|
||||
|
||||
static void probe_threads(void) {
|
||||
INFO("主线程 x18 = %#llx", (unsigned long long)read_x18());
|
||||
struct thr t = {0}; pthread_t th;
|
||||
if (pthread_create(&th, NULL, thr_main, &t)) { FAIL("pthread_create"); return; }
|
||||
pthread_join(th, NULL);
|
||||
INFO("新线程 x18 = %#llx(非 0 多半是 bionic 给的影子调用栈指针:宿主代码与系统库要用 x18,客体 x18 必须走线程槽,与苹果相同)", (unsigned long long)t.x18);
|
||||
if (g_slotfn) { if (t.slot_ok) OK("新线程经生成代码取到本线程自己的槽值"); else FAIL("新线程取槽得 %#llx", (unsigned long long)t.slot); }
|
||||
if (t.altstack) OK("新线程有备用信号栈(%zu 字节):SA_ONSTACK 的信号不压当前栈", t.altsize);
|
||||
else FAIL("新线程没有备用信号栈:客体线程要自己 sigaltstack,宿主信号处理一律 SA_ONSTACK");
|
||||
// x18 跨调度是否被改:在本线程把 x18 设成记号、让出 CPU 若干次,再读回(只在不调任何库函数的汇编循环里测)
|
||||
// Whether x18 is changed across scheduling: set x18 to a marker in this thread, yield the CPU a number of times, then read back (measured only inside an asm loop that calls no library functions)
|
||||
uint64_t back = 0, changed = 0;
|
||||
for (int i = 0; i < 2000; i++) {
|
||||
__asm__ volatile(
|
||||
"mov x9, x18\n"
|
||||
"movz x18, #0x5a5a\n"
|
||||
"mov x8, #124\n" // __NR_sched_yield
|
||||
"svc #0\n"
|
||||
"mov %0, x18\n"
|
||||
"mov x18, x9\n" : "=r"(back) : : "x0", "x8", "x9", "memory");
|
||||
if (back != 0x5a5a) changed++;
|
||||
}
|
||||
if (!changed) OK("x18 跨 2000 次系统调用 / 让出调度不被内核改写");
|
||||
else FAIL("x18 跨系统调用被改 %llu / 2000 次", (unsigned long long)changed);
|
||||
}
|
||||
|
||||
static void probe_vm(void) {
|
||||
for (int gb = 8; gb <= 64; gb *= 2) {
|
||||
size_t sz = (size_t)gb << 30;
|
||||
void *p = mmap(NULL, sz, PROT_NONE, MAP_PRIVATE | MAP_ANON | MAP_NORESERVE, -1, 0);
|
||||
if (p == MAP_FAILED) { INFO("保留 %d GiB 地址:失败", gb); break; }
|
||||
INFO("保留 %d GiB 地址:%p", gb, p); munmap(p, sz);
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
INFO("页大小 %ld,CPU %ld 核", sysconf(_SC_PAGESIZE), sysconf(_SC_NPROCESSORS_CONF));
|
||||
unsigned long hw = getauxval(AT_HWCAP), hw2 = getauxval(AT_HWCAP2);
|
||||
INFO("HWCAP %#lx HWCAP2 %#lx(LSE 原子 %s)", hw, hw2, hw & (1ul << 8) ? "有" : "无");
|
||||
probe_tsd();
|
||||
probe_exec();
|
||||
probe_threads();
|
||||
probe_vm();
|
||||
printf(g_fail ? "RESULT FAIL %d\n" : "RESULT OK\n", g_fail);
|
||||
return g_fail != 0;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
pluginManagement {
|
||||
repositories { google(); mavenCentral(); gradlePluginPortal() }
|
||||
plugins { id 'com.android.application' version '9.4.1' }
|
||||
}
|
||||
dependencyResolutionManagement {
|
||||
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||
repositories { google(); mavenCentral() }
|
||||
}
|
||||
rootProject.name = 'd2r-mobile-android'
|
||||
include ':app'
|
||||
@@ -0,0 +1,82 @@
|
||||
package com.xiaoboluo.d2r.widget;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
|
||||
/** 仅生成合成存档,绝不访问玩家目录。 | Generates synthetic saves only; never reads a player's directory. */
|
||||
public final class SaveSummaryReaderTest {
|
||||
private static int checks;
|
||||
private static void check(boolean value,String label) { ++checks; if (!value) throw new AssertionError(label); }
|
||||
private static void sign(byte[] bytes) {
|
||||
ByteBuffer data=ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN); data.putInt(8,bytes.length); data.putInt(12,0);
|
||||
int sum=0; for (byte b:bytes) sum=Integer.rotateLeft(sum,1)+Byte.toUnsignedInt(b);
|
||||
data.putInt(12,sum);
|
||||
}
|
||||
private static int bits(byte[] bytes,int offset,int width,long value) {
|
||||
for (int i=0;i<width;++i) if ((value&(1L<<i))!=0) bytes[(offset+i)/8]|=(byte)(1<<((offset+i)%8));
|
||||
return offset+width;
|
||||
}
|
||||
private static byte[] save(String name,long played) {
|
||||
byte[] bytes=new byte[1024]; ByteBuffer data=ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
|
||||
data.putInt(0,0xaa55aa55); data.putInt(4,0x69); data.putInt(0x20,(int)played);
|
||||
bytes[0x18]=1; bytes[0x1b]=42;
|
||||
byte[] utf8=name.getBytes(StandardCharsets.UTF_8); System.arraycopy(utf8,0,bytes,0x12b,Math.min(47,utf8.length));
|
||||
bytes[0x180]=0x67; bytes[0x181]=0x66; int p=0x182*8;
|
||||
p=bits(bytes,p,9,12); p=bits(bytes,p,7,42);
|
||||
p=bits(bytes,p,9,13); p=bits(bytes,p,32,4_000_000_000L);
|
||||
p=bits(bytes,p,9,14); p=bits(bytes,p,25,12345);
|
||||
p=bits(bytes,p,9,15); p=bits(bytes,p,25,54321);
|
||||
bits(bytes,p,9,0x1ff); sign(bytes); return bytes;
|
||||
}
|
||||
public static void main(String[] args) throws Exception {
|
||||
byte[] valid=save("法师gf",4_100_000_000L), original=valid.clone();
|
||||
SaveSummaryReader.Hero hero=SaveSummaryReader.parse(valid);
|
||||
check(hero!=null,"valid v0x69"); check(hero.name.equals("法师gf"),"strict UTF-8 and gf inside name");
|
||||
check(hero.level==42 && hero.classIndex==1,"header fields"); check(hero.lastPlayed==4_100_000_000L,"unsigned timestamp");
|
||||
check(hero.experience==4_000_000_000L,"unsigned 32-bit experience"); check(hero.gold==66666,"carried plus bank gold");
|
||||
check(Arrays.equals(original,valid),"parser never mutates input");
|
||||
byte[] bad=valid.clone(); bad[4]=0x61; sign(bad); check(SaveSummaryReader.parse(bad)!=null,"supported v0x61");
|
||||
bad[4]=0x60; sign(bad); check(SaveSummaryReader.parse(bad)==null,"unknown version rejected");
|
||||
bad=valid.clone(); bad[100]^=1; check(SaveSummaryReader.parse(bad)==null,"checksum mismatch rejected");
|
||||
bad=valid.clone(); bad[8]=1; check(SaveSummaryReader.parse(bad)==null,"length mismatch rejected");
|
||||
check(SaveSummaryReader.parse(new byte[10])==null,"short header rejected");
|
||||
bad=valid.clone(); bad[0x12b]=(byte)0xff; sign(bad); check(SaveSummaryReader.parse(bad)==null,"malformed UTF-8 rejected");
|
||||
bad=valid.clone(); bad[0x12b]='\n'; sign(bad); check(SaveSummaryReader.parse(bad)==null,"control character rejected");
|
||||
bad=valid.clone(); bad[0x18]=8; sign(bad); check(SaveSummaryReader.parse(bad)==null,"unknown class rejected");
|
||||
bad=valid.clone(); bad[0x1b]=0; sign(bad); check(SaveSummaryReader.parse(bad)==null,"invalid level rejected");
|
||||
bad=valid.clone(); bad[0x180]=0; sign(bad); hero=SaveSummaryReader.parse(bad);
|
||||
check(hero!=null && hero.experience==-1 && hero.gold==-1,"missing stats remain unknown");
|
||||
bad=valid.clone(); bad[0x182]=(byte)0xff; bad[0x183]=(byte)0xff; sign(bad); hero=SaveSummaryReader.parse(bad);
|
||||
check(hero!=null && hero.gold==-1,"invalid stats never report invented gold");
|
||||
Path temp=Files.createTempDirectory("d2r-widget-synthetic-");
|
||||
try {
|
||||
Path root=temp.resolve("save");
|
||||
check(SaveSummaryReader.read(root).state==SaveSummaryReader.State.EMPTY,"absent directory is empty");
|
||||
Files.createDirectory(root); check(SaveSummaryReader.read(root).state==SaveSummaryReader.State.EMPTY,"empty directory");
|
||||
Path first=Files.createDirectory(root.resolve("First")); Path file=first.resolve("First.d2s"); Files.write(file,valid);
|
||||
Path second=Files.createDirectory(root.resolve("Second")); Files.write(second.resolve("Second.d2s"),save("Older",100));
|
||||
SaveSummaryReader.Result result=SaveSummaryReader.read(root);
|
||||
check(result.state==SaveSummaryReader.State.READY && result.heroes.size()==2,"two valid saves");
|
||||
check(result.heroes.get(0).name.equals("法师gf"),"newest first");
|
||||
check(Arrays.equals(Files.readAllBytes(file),valid),"reader never writes saves");
|
||||
Path broken=Files.createDirectory(root.resolve("Broken")); Files.write(broken.resolve("Broken.d2s"),new byte[400]);
|
||||
result=SaveSummaryReader.read(root); check(result.state==SaveSummaryReader.State.PARTIAL && result.rejectedFiles==1,"mixed validity reported");
|
||||
check(SaveSummaryReader.read(temp.resolve("save.work")).state==SaveSummaryReader.State.ERROR,"working directory rejected");
|
||||
Files.delete(file); Files.delete(second.resolve("Second.d2s"));
|
||||
check(SaveSummaryReader.read(root).state==SaveSummaryReader.State.ERROR,"only invalid saves is an error");
|
||||
boolean immutable=false; try { result.heroes.clear(); } catch (UnsupportedOperationException ex) { immutable=true; }
|
||||
check(immutable,"result cannot mutate cached hero list");
|
||||
} finally {
|
||||
/* 只清理由本测试创建的临时树。 | Remove only the temporary tree created by this test. */
|
||||
try (java.util.stream.Stream<Path> paths=Files.walk(temp)) {
|
||||
for (Path path:(Iterable<Path>)paths.sorted(Comparator.reverseOrder())::iterator) Files.delete(path);
|
||||
}
|
||||
}
|
||||
System.out.println("SaveSummaryReader OK ("+checks+" synthetic checks; no player data)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.xiaoboluo.d2r;
|
||||
|
||||
// 角色名的 UTF-8 字节限制、UTF-16 截断及数字溢出边界。
|
||||
// UTF-8 name limits, UTF-16 truncation, and numeric overflow boundaries.
|
||||
public class TextInputRulesTest {
|
||||
private static void equal(Object want, Object actual) {
|
||||
if (!want.equals(actual)) throw new AssertionError("want=" + want + " actual=" + actual);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
equal("你好世界中", TextInputRules.normalize("你好世界中文", 0, true, -1));
|
||||
equal("Ab-cd", TextInputRules.normalize("A1b-c_d!", 0, true, -1));
|
||||
equal("", TextInputRules.normalize("😀", 1, false, -1));
|
||||
equal("😀", TextInputRules.normalize("😀x", 2, false, -1));
|
||||
equal("2147483647", TextInputRules.normalize("99999999999999999999999999", 0, false, Integer.MAX_VALUE));
|
||||
equal("12", TextInputRules.normalize("1a2", 0, false, 100));
|
||||
equal("", TextInputRules.normalize("", 0, false, 100));
|
||||
equal(0, TextInputRules.nameError(""));
|
||||
equal(0, TextInputRules.nameError("中"));
|
||||
equal(1, TextInputRules.nameError("A"));
|
||||
equal(2, TextInputRules.nameError("Ab-"));
|
||||
equal(0, TextInputRules.nameError("Ab"));
|
||||
System.out.println("TextInputRules OK (12 cases)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// 真派发器的CPU并发回归:GPU挂起等待Surface时,UI仍能提交恢复,最终先开图形再音频/焦点。
|
||||
// CPU concurrency regression of the real dispatcher: UI can post resume while suspend waits for Surface; graphics resumes before audio/focus.
|
||||
// 用POSIX C编译器运行:cc -pthread lifecycle_dispatch_test.c -o <仓外产物>,再运行该产物。
|
||||
// Run with a POSIX C compiler: cc -pthread lifecycle_dispatch_test.c -o <external-output>; run the resulting test.
|
||||
#include "../lifecycle_dispatch.h"
|
||||
#include <assert.h>
|
||||
#include <errno.h>
|
||||
#include <time.h>
|
||||
#ifdef NDEBUG
|
||||
#error "Build this CPU regression with assertions enabled"
|
||||
#endif
|
||||
|
||||
static pthread_mutex_t mock_mutex = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t mock_changed = PTHREAD_COND_INITIALIZER;
|
||||
static int suspend_entered, surface_restored, post_finished, graphics_paused, audio_paused, final_focus;
|
||||
static int order[64], order_count;
|
||||
static dm_lifecycle_dispatch dispatcher;
|
||||
|
||||
static struct timespec deadline(void) { struct timespec t; clock_gettime(CLOCK_REALTIME, &t); t.tv_sec += 3; return t; }
|
||||
static void record(int value) { assert(order_count < 64); order[order_count++] = value; }
|
||||
static void focus(int state) { pthread_mutex_lock(&mock_mutex); final_focus = state; record(10 + state); pthread_mutex_unlock(&mock_mutex); }
|
||||
static void audio(int paused) { pthread_mutex_lock(&mock_mutex); audio_paused = paused; record(20 + paused); pthread_mutex_unlock(&mock_mutex); }
|
||||
static void graphics(int paused) {
|
||||
pthread_mutex_lock(&mock_mutex);
|
||||
if (paused) {
|
||||
suspend_entered = 1; record(31); pthread_cond_broadcast(&mock_changed);
|
||||
while (!surface_restored) pthread_cond_wait(&mock_changed, &mock_mutex);
|
||||
} else record(30);
|
||||
graphics_paused = paused;
|
||||
pthread_mutex_unlock(&mock_mutex);
|
||||
}
|
||||
static void *ui_resume(void *unused) {
|
||||
(void)unused;
|
||||
dm_lifecycle_post(&dispatcher, 2);
|
||||
dm_lifecycle_post(&dispatcher, 3);
|
||||
pthread_mutex_lock(&mock_mutex); post_finished = 1; pthread_cond_broadcast(&mock_changed); pthread_mutex_unlock(&mock_mutex);
|
||||
return NULL;
|
||||
}
|
||||
int main(void) {
|
||||
dm_lifecycle_ops ops = {focus, audio, graphics};
|
||||
assert(!dm_lifecycle_start(&dispatcher, ops));
|
||||
dm_lifecycle_post(&dispatcher, 1);
|
||||
struct timespec until = deadline();
|
||||
pthread_mutex_lock(&mock_mutex);
|
||||
while (!suspend_entered) assert(!pthread_cond_timedwait(&mock_changed, &mock_mutex, &until));
|
||||
pthread_mutex_unlock(&mock_mutex);
|
||||
pthread_t ui; assert(!pthread_create(&ui, NULL, ui_resume, NULL));
|
||||
until = deadline();
|
||||
pthread_mutex_lock(&mock_mutex);
|
||||
int timed_out = 0;
|
||||
while (!post_finished) { if (pthread_cond_timedwait(&mock_changed, &mock_mutex, &until) == ETIMEDOUT) { timed_out = 1; break; } }
|
||||
// 无论测试成败都先解除模拟GPU等待,避免失败测试自身把线程遗留阻塞。
|
||||
// Release the simulated GPU even on failure so a failed test does not leave its worker blocked.
|
||||
surface_restored = 1; pthread_cond_broadcast(&mock_changed); pthread_mutex_unlock(&mock_mutex);
|
||||
pthread_join(ui, NULL); assert(!timed_out);
|
||||
until = deadline();
|
||||
pthread_mutex_lock(&dispatcher.mutex);
|
||||
while (dispatcher.completed != dispatcher.requested) assert(!pthread_cond_timedwait(&dispatcher.changed, &dispatcher.mutex, &until));
|
||||
pthread_mutex_unlock(&dispatcher.mutex);
|
||||
dm_lifecycle_stop(&dispatcher);
|
||||
assert(!graphics_paused && !audio_paused && final_focus == 1);
|
||||
int resumed = -1;
|
||||
for (int i = 0; i < order_count; i++) if (order[i] == 30) resumed = i;
|
||||
assert(resumed >= 0 && resumed + 2 < order_count && order[resumed + 1] == 20 && order[resumed + 2] == 11);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/* 用自造字符串验证Debug性能参数,不读资源、不启动游戏。
|
||||
* Verify Debug performance parameters with synthetic strings, without resources or launching the game. */
|
||||
#define DM_ANDROID_DEBUG_ENV 1
|
||||
#include "../debug_env.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
|
||||
static void rejected(const char *value) {
|
||||
dm_android_debug_values out={.present=7};
|
||||
assert(!dm_android_debug_parse(value,strlen(value),&out));assert(out.present==7);
|
||||
}
|
||||
int main(void) {
|
||||
dm_android_debug_values out;
|
||||
const char *valid="# bounded A/B\r\nDM_3D_SCALE=0.75\r\nDM_3D_SCALE_DYN=0\r\nDM_3D_SCALE_FLOOR=0.60\r\n";
|
||||
assert(dm_android_debug_parse(valid,strlen(valid),&out));assert(out.present==7);assert(!strcmp(out.value[0],"0.75"));
|
||||
rejected("DM_NVN_SYNC=0\n");rejected("PATH=/tmp\n");rejected("DM_3D_SCALE_DYN=2\n");
|
||||
rejected("DM_3D_SCALE=nan\n");rejected("DM_3D_SCALE=1e0\n");rejected("DM_3D_SCALE=1.01\n");
|
||||
rejected("DM_3D_SCALE=Inf\n");rejected("DM_3D_SCALE=0.75garbage\n");
|
||||
rejected("DM_3D_SCALE=0.5\n");rejected("DM_3D_SCALE=0.75\nDM_3D_SCALE=0.75\n");
|
||||
rejected("DM_3D_SCALE_DYN=0 =1\n");
|
||||
char long_line[140];memset(long_line,'#',sizeof long_line);assert(!dm_android_debug_parse(long_line,sizeof long_line,&out));
|
||||
const char nul[]="DM_3D_SCALE_DYN=0\0DM_3D_SCALE_DYN=1";assert(!dm_android_debug_parse(nul,sizeof nul-1,&out));
|
||||
char too_big[4097];memset(too_big,'\n',sizeof too_big);assert(!dm_android_debug_parse(too_big,sizeof too_big,&out));
|
||||
out.present=7;assert(dm_android_debug_load("/this-path-does-not-exist-dm-debug-env",&out)==0);assert(out.present==7);
|
||||
rejected("DM_3D_SCALE=0.75\nDM_NVN_SYNC=0\n");
|
||||
puts("PASS debug_env allowlist, atomic rejection, ranges, duplicate, line limits and NUL");return 0;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
"""用自造小文件验证安卓导入资源合同,不读游戏内容。
|
||||
Validate Android imported-asset contracts with synthetic tiny files, without game content.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
TOOLS = Path(__file__).resolve().parents[1] / 'tools'
|
||||
|
||||
|
||||
def load(name):
|
||||
spec = importlib.util.spec_from_file_location(name, TOOLS / (name + '.py'))
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
stage = load('stage_touch_assets')
|
||||
strings = load('gen_strings')
|
||||
|
||||
|
||||
class AssetContract(unittest.TestCase):
|
||||
def test_complete_payload_and_tamper(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp); native = root / 'art'; hud = root / 'hud'; overlay = root / 'overlay'
|
||||
native.mkdir(); hud.mkdir(); (overlay / 'data').mkdir(parents=True)
|
||||
for name in [f'dm_native_skill_{i}.png' for i in range(9)] + ['dm_native_circle.png', 'dm_native_map.png', 'dm_native_menu.png']:
|
||||
(native / name).write_bytes(b'synthetic-art')
|
||||
for name in ['base_full.png', 'lvl_0.png', 'lvl_1.png', 'lvl_d0.png', 'lvl_d1.png', 'slot.png', 'glyph.png'] + [f'diff_{i}.png' for i in range(1, 9)]:
|
||||
(hud / name).write_bytes(b'synthetic-hud')
|
||||
ui = {key: {'glyphs': {'0': {'file': 'glyph.png'}}} for key in ('lv', 'badge', 'vital')}
|
||||
for group in ui.values():
|
||||
group['glyphs'][' '] = {'file': None, 'adv': 7}
|
||||
(hud / 'ui.json').write_text(json.dumps(ui), encoding='utf-8')
|
||||
for name in ('ctrl_touch', 'touch_strings.tsv', 'data/.build.config', 'data/test.data'):
|
||||
(overlay / name).write_bytes(b'synthetic-overlay')
|
||||
(hud / 'glyph.png').unlink()
|
||||
with self.assertRaisesRegex(ValueError, 'missing or unsafe HUD asset'):
|
||||
stage.stage(native, hud, overlay)
|
||||
self.assertFalse((overlay / 'touchart').exists())
|
||||
(hud / 'glyph.png').write_bytes(b'synthetic-hud')
|
||||
stage.stage(native, hud, overlay)
|
||||
fingerprint = stage.overlay_contract.source_fingerprint(Path(__file__).resolve().parents[3])
|
||||
entries = stage.overlay_contract.verify_manifest(overlay, fingerprint)
|
||||
self.assertIn('touchart/dm_native_skill_8.png', entries)
|
||||
self.assertIn('hud_v4_ui/glyph.png', entries)
|
||||
(overlay / 'touchart/dm_native_skill_8.png').write_bytes(b'changed')
|
||||
with self.assertRaises(stage.overlay_contract.ContractError):
|
||||
stage.overlay_contract.verify_manifest(overlay, fingerprint)
|
||||
|
||||
def test_hud_strings_available_in_both_languages(self):
|
||||
with tempfile.TemporaryDirectory() as temp:
|
||||
root = Path(temp); strings.generate(root)
|
||||
for folder in ('values', 'values-zh'):
|
||||
text = (root / folder / 'strings.xml').read_text(encoding='utf-8')
|
||||
for key in ('dmhudlife', 'dmhudmana', 'dmtccancel', 'dmandroidhudlevel'):
|
||||
self.assertIn('name="' + key + '"', text)
|
||||
self.assertIn('formatted="false"', text)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -0,0 +1,388 @@
|
||||
/* Standalone regression harness. Do not link it into the product library.
|
||||
* Includes the REAL Android bridge and shared touch state machine. No duplicate
|
||||
* implementation of layout serialization, hit testing, or key latching.
|
||||
* Compile with the repository root on -I. NDK: --target=aarch64-linux-android31 -O2 -ffunction-sections -fdata-sections
|
||||
* -I <repo> -Wl,--gc-sections -Wl,--no-undefined -lm.
|
||||
* This executable never opens saves, starts the guest, or sends Android input.
|
||||
*/
|
||||
#include <inttypes.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <math.h>
|
||||
|
||||
#include "dm/android/touch_android.c"
|
||||
#include "dm/ios/Sources/dm_touch_controls.c"
|
||||
|
||||
_Static_assert(DM_ANDROID_TOUCH_DRAW_FLOATS == 183, "Review the Java/native ABI before changing this test");
|
||||
enum { DRAW_JOY = 12, DRAW_SWAP = 13, DRAW_DIFF = 14, DRAW_PICK0 = 15 };
|
||||
static const char *case_name = "startup";
|
||||
static unsigned checks, cases;
|
||||
static uint64_t test_clock_ns = UINT64_C(100000000000), test_sample;
|
||||
static int observed_panel;
|
||||
static unsigned panel_calls;
|
||||
|
||||
#define REQUIRE(expression) do { \
|
||||
++checks; \
|
||||
if (!(expression)) { \
|
||||
fprintf(stderr, "FAIL %s:%d case=%s expression=%s\n", __FILE__, __LINE__, case_name, #expression); \
|
||||
exit(1); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
static void unexpected_host_call(const char *name) {
|
||||
fprintf(stderr, "FAIL case=%s unexpected host path=%s\n", case_name, name);
|
||||
exit(2);
|
||||
}
|
||||
|
||||
/* The Android queue test retains dm_android_touch_step(), so its host boundary
|
||||
* must link. Neutral read-only state is deliberate. Unrelated mutations fail
|
||||
* loudly rather than silently pretending to execute game behavior.
|
||||
*/
|
||||
uint64_t now_ns(void) { return test_clock_ns; }
|
||||
uint64_t dm_input_samples(void) { return test_sample; }
|
||||
void dm_cursor_clear(void) {}
|
||||
int dm_cursor_pending(void) { return 0; }
|
||||
void dm_ui_hand_idle(int idle) { (void)idle; }
|
||||
int dm_ui_panel_state(void) { return 0; }
|
||||
int dm_ui_tap_box(void) { return 0; }
|
||||
uint32_t dm_ui_cur_stack_id(void) { return 0; }
|
||||
uint32_t dm_ui_hover_unid(void) { return 0; }
|
||||
int dm_ui_targeting(void) { return 0; }
|
||||
int dm_ui_touch_active(void) { return 0; }
|
||||
int dm_ui_bind_active(void) { return 0; }
|
||||
int dm_belt_rows(int *expanded) { if (expanded) *expanded = 0; return 1; }
|
||||
void dm_hud_get(dm_hud_info *out) { memset(out, 0, sizeof *out); }
|
||||
int dm_custom_get(const char *key) { (void)key; return 0; }
|
||||
void dm_ui_safe_left(int units) { (void)units; }
|
||||
void dm_ui_safe_right(int units) { (void)units; }
|
||||
int dm_touch_game_snapshot(dm_tg_snapshot *out) { memset(out,0,sizeof *out); return 0; }
|
||||
dm_ta_glyph dm_ta_skill(uint32_t id) { (void)id; return (dm_ta_glyph){.status=DM_TA_UNKNOWN,.atlas=-1}; }
|
||||
dm_ta_glyph dm_ta_current_set(const dm_tg_snapshot *s,uint64_t key,uint64_t now,int set) { (void)s; (void)key; (void)now; (void)set; return dm_ta_skill(0); }
|
||||
int dm_ta_frame_at(int atlas,int frame,dm_ta_frame *out) { (void)atlas; (void)frame; (void)out; return 0; }
|
||||
int dm_swapskill_slot(int slot,int *charges) { (void)slot; *charges=0; return 0; }
|
||||
int dm_ui_minimap_rect(float r[4]) { (void)r; return 0; }
|
||||
int dm_ui_map_is_full(void) { return 0; }
|
||||
void dm_ui_map_full(int on) { (void)on; unexpected_host_call(__func__); }
|
||||
unsigned dm_world_tap(float x,float y) { (void)x; (void)y; unexpected_host_call(__func__); return 0; }
|
||||
int dm_world_tap_result(unsigned seq) { (void)seq; return -1; }
|
||||
uint32_t dm_ui_hit_id(void) { return 0; }
|
||||
void dm_points_get(dm_points_info *out) { memset(out,0,sizeof *out); }
|
||||
void dm_stat_add(int stat,int n) { (void)stat; (void)n; unexpected_host_call(__func__); }
|
||||
void dm_skill_add_selected(void) { unexpected_host_call(__func__); }
|
||||
|
||||
void dm_cursor_set_screen(float x, float y, float w, float h) { (void)x; (void)y; (void)w; (void)h; unexpected_host_call(__func__); }
|
||||
void dm_ui_touch(int phase, float x, float y) { (void)phase; (void)x; (void)y; unexpected_host_call(__func__); }
|
||||
int dm_ui_fe_drag_ok(void) { unexpected_host_call(__func__); return 0; }
|
||||
void dm_ui_drag_begin(int kind, float x, float y, float tolerance) { (void)kind; (void)x; (void)y; (void)tolerance; unexpected_host_call(__func__); }
|
||||
void dm_ui_drag_move(float x, float y) { (void)x; (void)y; unexpected_host_call(__func__); }
|
||||
void dm_ui_drag_end(void) { unexpected_host_call(__func__); }
|
||||
void dm_ui_drag_lift(float y) { (void)y; unexpected_host_call(__func__); }
|
||||
int dm_ui_item_at_now(float x, float y) { (void)x; (void)y; unexpected_host_call(__func__); return 0; }
|
||||
int dm_ui_drop_at_now(float x, float lifted, float finger) { (void)x; (void)lifted; (void)finger; unexpected_host_call(__func__); return 0; }
|
||||
int dm_ui_drop_bag(void) { unexpected_host_call(__func__); return 0; }
|
||||
int dm_ui_drop_point(float *x, float *y) { (void)x; (void)y; unexpected_host_call(__func__); return 0; }
|
||||
int dm_ui_origin_point(float *x, float *y) { (void)x; (void)y; unexpected_host_call(__func__); return 0; }
|
||||
int dm_ui_bind_skill_hit(float *x, float *y) { (void)x; (void)y; unexpected_host_call(__func__); return 0; }
|
||||
void dm_ui_bind_begin(uint64_t key) { (void)key; unexpected_host_call(__func__); }
|
||||
void dm_ui_world_tap(float ux, float uy, float wx, float wy) { (void)ux; (void)uy; (void)wx; (void)wy; unexpected_host_call(__func__); }
|
||||
void dm_ui_stack_take_at(float x, float y) { (void)x; (void)y; unexpected_host_call(__func__); }
|
||||
void dm_ui_stack_cube_at(float x, float y) { (void)x; (void)y; unexpected_host_call(__func__); }
|
||||
void dm_ui_shop_buy_at(float x, float y) { (void)x; (void)y; unexpected_host_call(__func__); }
|
||||
void dm_ui_tab_go(void) { unexpected_host_call(__func__); }
|
||||
void dm_ui_use_item(void) { unexpected_host_call(__func__); }
|
||||
void dm_ui_identify_hovered(void) { unexpected_host_call(__func__); }
|
||||
void dm_ui_long_press(void) { unexpected_host_call(__func__); }
|
||||
void dm_ui_item_tap(void) { unexpected_host_call(__func__); }
|
||||
void dm_stash_take(int n) { (void)n; unexpected_host_call(__func__); }
|
||||
void dm_hud_request_players(int n) { (void)n; unexpected_host_call(__func__); }
|
||||
void dm_belt_expand(int on) { (void)on; unexpected_host_call(__func__); }
|
||||
void dm_belt_use(int col, int row) { (void)col; (void)row; unexpected_host_call(__func__); }
|
||||
void dm_shop_sell_cursor(void) { unexpected_host_call(__func__); }
|
||||
void dm_tp_request(void) { unexpected_host_call(__func__); }
|
||||
|
||||
/* 观测真实桥发出的面板模式;不依赖链接器删除未用代码,不链接产品宿主。
|
||||
* Observe the real bridge's panel mode without relying on linker garbage collection or linking the product host. */
|
||||
void dm_uiscreen_set_panel(int panel) {
|
||||
REQUIRE(panel==0 || panel==1);
|
||||
observed_panel=panel; ++panel_calls;
|
||||
}
|
||||
static void fixture(int navigation) {
|
||||
memset(&tc, 0, sizeof tc);
|
||||
memset(&scene, 0, sizeof scene);
|
||||
memset(queue, 0, sizeof queue);
|
||||
head = tail = 0; ready = 0; focused = 1; cancel = resizing = ui_drag = 0;
|
||||
width = 800; height = 375; safe_left = safe_right = safe_bottom = 0; tablet_layout = swap_above = 0;
|
||||
epoch = world = 1; pulse_epoch = pulse_sample = resume_sample = 0; pulse_hold_start = 0;
|
||||
seen_world = seen_mouse = seen_tab = seen_use = seen_ident = seen_long = seen_item = seen_stack = 0;
|
||||
frontend = 0; fe_slot = -1; fe_drag = 0; fe_x0 = fe_y0 = 0;
|
||||
test_clock_ns = UINT64_C(100000000000); test_sample = 0;
|
||||
observed_panel=-1; panel_calls=0;
|
||||
dm_tc_set_safe_insets(0, 0); dm_tc_set_edge_bottom(0); dm_tc_set_safe_bottom(0); dm_tc_set_swap_above(0);
|
||||
dm_tc_set_panel_state(0); dm_tc_set_tap_box(0); dm_tc_set_cur_stack(0); dm_tc_set_hover_unid(0);
|
||||
init_locked();
|
||||
dm_tc_set_navigation_mode(&tc, navigation);
|
||||
dm_tc_enable_targets(&tc, navigation ? dm_tc_nav_mask(1) : ((1u << DM_TC_COUNT) - 1u));
|
||||
}
|
||||
|
||||
static int field(int record, int component) { return 4 + record * 5 + component; }
|
||||
static int lit(const float *s, int record) { return s[field(record, 4)] != 0; }
|
||||
static int visible(const float *s, int record) { return s[field(record, 3)] != 0; }
|
||||
|
||||
/* Read as #19 does: probe, then actual draw. Both must see the same data and
|
||||
* neither read may consume pulse/pressed state. Guard words detect ABI overrun.
|
||||
*/
|
||||
static void read_twice(float result[DM_ANDROID_TOUCH_DRAW_FLOATS]) {
|
||||
struct guarded { uint32_t left; float values[DM_ANDROID_TOUCH_DRAW_FLOATS]; uint32_t right; } a, b;
|
||||
unsigned char before[sizeof tc];
|
||||
a.left = b.left = UINT32_C(0x13579bdf); a.right = b.right = UINT32_C(0x2468ace0);
|
||||
memset(a.values, 0xa5, sizeof a.values); memset(b.values, 0x5a, sizeof b.values);
|
||||
memcpy(before, &tc, sizeof tc);
|
||||
dm_android_touch_layout(a.values);
|
||||
dm_android_touch_layout(b.values);
|
||||
REQUIRE(a.left == UINT32_C(0x13579bdf) && b.left == a.left);
|
||||
REQUIRE(a.right == UINT32_C(0x2468ace0) && b.right == a.right);
|
||||
REQUIRE(memcmp(a.values, b.values, sizeof a.values) == 0);
|
||||
REQUIRE(memcmp(before, &tc, sizeof tc) == 0);
|
||||
for (int i = 0; i < DM_ANDROID_TOUCH_DRAW_FLOATS; ++i) REQUIRE(isfinite(a.values[i]));
|
||||
memcpy(result, a.values, sizeof a.values);
|
||||
}
|
||||
|
||||
static void unchanged_geometry(const float *a, const float *b) {
|
||||
REQUIRE(a[0] == b[0] && a[1] == b[1]);
|
||||
for (int i = 0; i < 23; ++i)
|
||||
for (int c = 0; c < 3; ++c) REQUIRE(a[field(i, c)] == b[field(i, c)]);
|
||||
}
|
||||
|
||||
static void down_target(int slot, int target, double at) {
|
||||
dm_tc_target t = tc.layout.target[target];
|
||||
dm_tc_begin_at(&tc, slot, t.x, t.y, at);
|
||||
REQUIRE(tc.finger[slot].active && tc.finger[slot].target == target);
|
||||
}
|
||||
|
||||
static void test_idle_and_abi(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; read_twice(a); read_twice(b);
|
||||
REQUIRE(memcmp(a, b, sizeof a) == 0);
|
||||
REQUIRE(a[0] == 800 && a[1] == 375 && a[2] == 0 && a[3] == 0);
|
||||
REQUIRE(visible(a, DRAW_JOY) && visible(a, DRAW_SWAP) && visible(a, DRAW_DIFF));
|
||||
for (int i = 0; i < 23; ++i) REQUIRE(!lit(a, i));
|
||||
}
|
||||
|
||||
static void test_press_release_and_multitouch(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; read_twice(a);
|
||||
down_target(0, DM_TC_MAIN, 100.0); read_twice(b);
|
||||
REQUIRE(lit(b, DM_TC_MAIN)); REQUIRE(memcmp(a, b, sizeof a) != 0);
|
||||
unchanged_geometry(a, b);
|
||||
down_target(1, DM_TC_SKILL1, 100.01); read_twice(b);
|
||||
REQUIRE(lit(b, DM_TC_MAIN) && lit(b, DM_TC_SKILL1));
|
||||
dm_tc_cancel_finger(&tc, 0); read_twice(b);
|
||||
REQUIRE(!lit(b, DM_TC_MAIN) && lit(b, DM_TC_SKILL1));
|
||||
dm_tc_cancel_all(&tc); read_twice(b);
|
||||
for (int i = 0; i < 23; ++i) REQUIRE(!lit(b, i));
|
||||
down_target(0, DM_TC_MAIN, 101.0);
|
||||
dm_tc_end_at(&tc, 0, 101.1); read_twice(b);
|
||||
REQUIRE(!lit(b, DM_TC_MAIN) && tc.buttons == 0);
|
||||
}
|
||||
|
||||
static void test_slide_cancel(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS]; down_target(0, DM_TC_SKILL1, 100.0);
|
||||
dm_tc_target map = tc.layout.target[DM_TC_MAP];
|
||||
dm_tc_move_at(&tc, 0, map.x, map.y, 100.1);
|
||||
REQUIRE(tc.finger[0].active && tc.finger[0].aim_cancelled);
|
||||
REQUIRE((tc.buttons & tc.layout.target[DM_TC_SKILL1].button) == 0);
|
||||
read_twice(a); REQUIRE(!lit(a, DM_TC_SKILL1));
|
||||
dm_tc_end_at(&tc, 0, 100.11); read_twice(a);
|
||||
REQUIRE(!lit(a, DM_TC_SKILL1) && tc.pulse_button == 0);
|
||||
}
|
||||
|
||||
static void test_release_pulse(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; down_target(0, DM_TC_SKILL1, 100.0);
|
||||
dm_tc_end_at(&tc, 0, 100.01);
|
||||
REQUIRE(!tc.finger[0].active && tc.pulse_button == tc.layout.target[DM_TC_SKILL1].button);
|
||||
read_twice(a); REQUIRE(lit(a, DM_TC_SKILL1));
|
||||
REQUIRE(dm_tc_pulse_end(&tc, tc.pulse_epoch));
|
||||
read_twice(b); REQUIRE(!lit(b, DM_TC_SKILL1));
|
||||
REQUIRE(memcmp(a, b, sizeof a) != 0); unchanged_geometry(a, b);
|
||||
}
|
||||
|
||||
static void test_swap_and_delayed_pulse(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; read_twice(a);
|
||||
dm_tc_target swap = tc.layout.swap;
|
||||
dm_tc_begin_at(&tc, 0, swap.x, swap.y, 100.0); read_twice(b);
|
||||
REQUIRE(tc.finger[0].target == DM_TC_SWAP && b[3] == 0 && lit(b, DRAW_SWAP));
|
||||
REQUIRE(memcmp(a, b, sizeof a) != 0); unchanged_geometry(a, b);
|
||||
dm_tc_end_at(&tc, 0, 100.01); read_twice(b);
|
||||
REQUIRE(b[3] == 1 && !lit(b, DRAW_SWAP));
|
||||
down_target(0, DM_TC_SKILL1, 101.0); dm_tc_end_at(&tc, 0, 101.01);
|
||||
REQUIRE(!tc.finger[0].active && tc.defer_button != 0 && tc.pulse_button == 0);
|
||||
read_twice(a); REQUIRE(a[3] == 1 && !lit(a, DM_TC_SKILL1));
|
||||
dm_tc_tick(&tc, 101.0 + DM_TC_ZL_LEAD_S + 0.01); read_twice(b);
|
||||
REQUIRE(tc.defer_button == 0 && tc.pulse_button != 0 && lit(b, DM_TC_SKILL1));
|
||||
REQUIRE(memcmp(a, b, sizeof a) != 0); unchanged_geometry(a, b);
|
||||
REQUIRE(dm_tc_pulse_end(&tc, tc.pulse_epoch)); read_twice(b); REQUIRE(!lit(b, DM_TC_SKILL1));
|
||||
dm_tc_begin_at(&tc, 0, swap.x, swap.y, 102.0); dm_tc_end_at(&tc, 0, 102.01);
|
||||
read_twice(b); REQUIRE(b[3] == 0);
|
||||
}
|
||||
|
||||
static void test_difficulty_hit_and_close(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; read_twice(a);
|
||||
for (int i = 0; i < 8; ++i) REQUIRE(!visible(a, DRAW_PICK0 + i));
|
||||
dm_tc_target diff = tc.layout.diff;
|
||||
dm_tc_begin_at(&tc, 0, diff.x, diff.y, 100.0); read_twice(b);
|
||||
REQUIRE(tc.diff_open && tc.finger[0].target == DM_TC_DIFF && lit(b, DRAW_DIFF));
|
||||
for (int i = 0; i < 8; ++i) { REQUIRE(visible(b, DRAW_PICK0 + i)); REQUIRE(!lit(b, DRAW_PICK0 + i)); }
|
||||
REQUIRE(memcmp(a, b, sizeof a) != 0);
|
||||
dm_tc_cancel_finger(&tc, 0); REQUIRE(tc.diff_open);
|
||||
dm_tc_target pick = tc.layout.pick[3];
|
||||
dm_tc_begin_at(&tc, 0, pick.x, pick.y, 100.1); read_twice(b);
|
||||
REQUIRE(tc.diff_request == 4 && !tc.diff_open && tc.finger[0].target == DM_TC_DIFF);
|
||||
REQUIRE(!lit(b, DRAW_DIFF));
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
REQUIRE(!visible(b, DRAW_PICK0 + i));
|
||||
if (i != 3) REQUIRE(!lit(b, DRAW_PICK0 + i));
|
||||
}
|
||||
/* Picking immediately collapses the strip. The selected hidden cell's
|
||||
* pressed bit may be retained or gated by visibility; no rendered state is
|
||||
* asserted for an invisible cell. Incorrectly highlighting DIFF is caught.
|
||||
*/
|
||||
dm_tc_cancel_finger(&tc, 0);
|
||||
dm_tc_begin_at(&tc, 0, diff.x, diff.y, 101.0); dm_tc_end_at(&tc, 0, 101.01);
|
||||
REQUIRE(tc.diff_open);
|
||||
dm_tc_begin_at(&tc, 0, diff.x, diff.y, 101.1); read_twice(b);
|
||||
REQUIRE(!tc.diff_open && lit(b, DRAW_DIFF));
|
||||
for (int i = 0; i < 8; ++i) REQUIRE(!visible(b, DRAW_PICK0 + i));
|
||||
}
|
||||
|
||||
static void test_belt_diff_target_does_not_light_difficulty(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS]; tc.belt_rows = 2; tc.belt_open = 1;
|
||||
dm_tc_target belt = tc.layout.target[DM_TC_BELT1];
|
||||
float row_y = belt.y - 165.0f * tc.layout.height / 1320.0f;
|
||||
dm_tc_begin_at(&tc, 0, belt.x, row_y, 100.0);
|
||||
REQUIRE(tc.finger[0].active && tc.finger[0].target == DM_TC_DIFF);
|
||||
REQUIRE(tc.belt_request != 0); read_twice(a);
|
||||
REQUIRE(!lit(a, DRAW_DIFF));
|
||||
for (int i = 0; i < 8; ++i) REQUIRE(!visible(a, DRAW_PICK0 + i));
|
||||
}
|
||||
|
||||
static void test_navigation_and_resize(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS], b[DM_ANDROID_TOUCH_DRAW_FLOATS]; read_twice(a);
|
||||
dm_tc_set_navigation_mode(&tc, 1); dm_tc_enable_targets(&tc, dm_tc_nav_mask(1)); read_twice(b);
|
||||
REQUIRE(b[2] == 1 && memcmp(a, b, sizeof a) != 0);
|
||||
REQUIRE(!visible(b, DRAW_JOY) && !visible(b, DRAW_SWAP) && !visible(b, DRAW_DIFF));
|
||||
dm_tc_resize(&tc, 960, 440); read_twice(b);
|
||||
REQUIRE(b[0] == 960 && b[1] == 440 && b[2] == 1);
|
||||
}
|
||||
|
||||
static uint64_t queue_sample(void) {
|
||||
uint64_t buttons = 0; int32_t lx = 0, ly = 0, rx = 0, ry = 0;
|
||||
++test_sample;
|
||||
dm_android_touch_step(test_clock_ns, &buttons, &lx, &ly, &rx, &ry);
|
||||
return buttons;
|
||||
}
|
||||
|
||||
static void test_android_queue_ten_short_taps(void) {
|
||||
fixture(0); dm_tc_target main = tc.layout.target[DM_TC_MAIN]; unsigned observed = 0;
|
||||
for (unsigned i = 0; i < 10; ++i) {
|
||||
test_clock_ns += UINT64_C(100000000);
|
||||
dm_android_touch_event(0, 0, main.x, main.y);
|
||||
test_clock_ns += UINT64_C(5000000);
|
||||
dm_android_touch_event(2, 0, main.x, main.y);
|
||||
REQUIRE(tail - head == 2);
|
||||
uint64_t delivered = queue_sample();
|
||||
REQUIRE((delivered & DM_BTN_A) != 0);
|
||||
REQUIRE(!tc.finger[0].active && (tc.buttons & DM_BTN_A) == 0);
|
||||
++observed;
|
||||
test_clock_ns += UINT64_C(10000000);
|
||||
REQUIRE((queue_sample() & DM_BTN_A) == 0);
|
||||
}
|
||||
REQUIRE(observed == 10);
|
||||
printf("DETAIL native_queue_short_taps=%u/10 scope=bridge_samples_not_game_actions\n", observed);
|
||||
}
|
||||
|
||||
static void test_android_focus_cancel(void) {
|
||||
fixture(0); float a[DM_ANDROID_TOUCH_DRAW_FLOATS]; dm_tc_target main = tc.layout.target[DM_TC_MAIN];
|
||||
dm_android_touch_event(0, 0, main.x, main.y);
|
||||
REQUIRE((queue_sample() & DM_BTN_A) != 0); read_twice(a); REQUIRE(lit(a, DM_TC_MAIN));
|
||||
dm_android_touch_focus(0); REQUIRE(queue_sample() == 0); read_twice(a);
|
||||
REQUIRE(!lit(a, DM_TC_MAIN) && tc.buttons == 0 && head == tail);
|
||||
dm_android_touch_focus(1); REQUIRE(queue_sample() == 0); read_twice(a); REQUIRE(!lit(a, DM_TC_MAIN));
|
||||
}
|
||||
|
||||
/* 同一批内取消不能把旧按下沿带给游戏;另一手指的快按仍有效。
|
||||
Cancellation in a batch must revoke the old edge without discarding another finger's quick tap. */
|
||||
static void test_android_cancelled_latch(void) {
|
||||
fixture(0);
|
||||
dm_tc_target main=tc.layout.target[DM_TC_MAIN], map=tc.layout.target[DM_TC_MAP];
|
||||
dm_android_touch_event(0,0,main.x,main.y);
|
||||
dm_android_touch_event(1,0,map.x,map.y);
|
||||
dm_android_touch_event(2,0,map.x,map.y);
|
||||
REQUIRE((queue_sample() & DM_BTN_A)==0);
|
||||
REQUIRE(tc.buttons==0);
|
||||
fixture(0); main=tc.layout.target[DM_TC_MAIN];
|
||||
dm_android_touch_event(0,0,main.x,main.y);
|
||||
dm_android_touch_event(3,0,main.x,main.y);
|
||||
dm_android_touch_event(0,1,main.x,main.y);
|
||||
dm_android_touch_event(2,1,main.x,main.y);
|
||||
REQUIRE((queue_sample() & DM_BTN_A)!=0);
|
||||
REQUIRE((queue_sample() & DM_BTN_A)==0);
|
||||
}
|
||||
|
||||
/* 换组只在原位松手时触发;滑出去再回来的手势仍取消。
|
||||
Switching commits on release inside the original target; leaving and returning still cancels. */
|
||||
static void test_android_swap_release_cancel(void) {
|
||||
fixture(0); dm_tc_target swap=tc.layout.swap;
|
||||
dm_android_touch_event(0,0,swap.x,swap.y); queue_sample(); REQUIRE(tc.skill_set==0);
|
||||
dm_android_touch_event(2,0,swap.x,swap.y); queue_sample(); REQUIRE(tc.skill_set==1);
|
||||
dm_android_touch_event(0,0,swap.x,swap.y);
|
||||
dm_android_touch_event(1,0,swap.x-100,swap.y);
|
||||
dm_android_touch_event(2,0,swap.x,swap.y);
|
||||
queue_sample(); REQUIRE(tc.skill_set==1);
|
||||
}
|
||||
|
||||
/* 从加载进入游戏、开关背包、只开NPC对话时,宿主面板模式必须各自正确。
|
||||
* Host panel mode must distinguish entering gameplay, opening/closing inventory and an NPC-dialog-only stack. */
|
||||
static void test_android_panel_observation(void) {
|
||||
fixture(0);
|
||||
dm_android_touch_uimsg(NULL,"UnloadPanel","LoadScreenPanel");
|
||||
REQUIRE(panel_calls==0 && observed_panel==-1);
|
||||
dm_android_touch_uimsg("PanelManager","UnloadPanel","LoadScreenPanel");
|
||||
REQUIRE(scene.game==1 && tc.navigation_mode==0 && observed_panel==0 && panel_calls==1);
|
||||
dm_tc_target main=tc.layout.target[DM_TC_MAIN];
|
||||
dm_android_touch_event(0,0,main.x,main.y);
|
||||
REQUIRE((queue_sample()&DM_BTN_A)!=0);
|
||||
dm_android_touch_event(2,0,main.x,main.y);
|
||||
REQUIRE(head!=tail);
|
||||
dm_android_touch_uimsg("PanelManager","OpenPanel","PlayerInventoryExpansionLayout");
|
||||
REQUIRE(tc.navigation_mode!=0 && observed_panel==1 && panel_calls==2);
|
||||
REQUIRE(tc.buttons==0 && head==tail && !tc.finger[0].active);
|
||||
dm_android_touch_uimsg("PanelManager","UnloadPanel","PlayerInventoryExpansionLayout");
|
||||
REQUIRE(tc.navigation_mode==0 && observed_panel==0 && panel_calls==3);
|
||||
dm_android_touch_uimsg("PanelManager","OpenPanel","NpcDialogPanel");
|
||||
REQUIRE(tc.navigation_mode!=0 && dm_tc_scene_dialog_only(&scene));
|
||||
REQUIRE(observed_panel==0 && panel_calls==4);
|
||||
dm_android_touch_uimsg("PanelManager","UnloadAll","");
|
||||
REQUIRE(tc.navigation_mode==0 && observed_panel==0 && panel_calls==5);
|
||||
}
|
||||
|
||||
static void run_case(const char *name, void (*body)(void)) {
|
||||
case_name = name; body(); ++cases; printf("PASS %s\n", name);
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
puts("SCOPE native_layout_and_input_bridge; no_Java_Canvas_no_guest_no_save_access");
|
||||
run_case("idle_183_abi", test_idle_and_abi);
|
||||
run_case("press_release_multitouch", test_press_release_and_multitouch);
|
||||
run_case("slide_cancelled_finger", test_slide_cancel);
|
||||
run_case("release_pulse_highlight", test_release_pulse);
|
||||
run_case("swap_and_delayed_pulse", test_swap_and_delayed_pulse);
|
||||
run_case("difficulty_hit_and_close", test_difficulty_hit_and_close);
|
||||
run_case("belt_diff_target_no_false_highlight", test_belt_diff_target_does_not_light_difficulty);
|
||||
run_case("navigation_and_resize", test_navigation_and_resize);
|
||||
run_case("android_queue_ten_short_taps", test_android_queue_ten_short_taps);
|
||||
run_case("android_focus_cancel", test_android_focus_cancel);
|
||||
run_case("android_cancelled_latch", test_android_cancelled_latch);
|
||||
run_case("android_swap_release_cancel", test_android_swap_release_cancel);
|
||||
run_case("android_panel_observation", test_android_panel_observation);
|
||||
printf("RESULT PASS cases=%u assertions=%u; game_quick_taps_10_of_10=NOT_TESTED\n", cases, checks);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
// 系统输入框桥:JNI 只在保留原始 pthread 栈的专用线程上调用。
|
||||
// System text-input bridge: JNI runs only on a dedicated thread with its original pthread stack.
|
||||
#include "../host/dm.h"
|
||||
#include "../host/dm_actions.h"
|
||||
#include <jni.h>
|
||||
#include <android/log.h>
|
||||
#include <stdatomic.h>
|
||||
|
||||
static JavaVM *vm;
|
||||
static jclass activity_class;
|
||||
static jmethodID show_input, report_failure;
|
||||
static pthread_mutex_t input_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t input_done = PTHREAD_COND_INITIALIZER;
|
||||
static pthread_cond_t work_ready = PTHREAD_COND_INITIALIZER;
|
||||
static jlong next_request, active_request;
|
||||
static int pending, result, output_capacity, worker_state; // 0 启动中,1 就绪,-1 失败 | starting, ready, failed
|
||||
static char *output;
|
||||
typedef struct input_job {
|
||||
struct input_job *next;
|
||||
jlong id;
|
||||
char *strings[4];
|
||||
int max_chars, name_rule, numeric_max, failure_code;
|
||||
} input_job;
|
||||
static input_job *jobs_head, *jobs_tail;
|
||||
|
||||
extern int g_swkbd_name_panel, g_swkbd_numeric_max;
|
||||
extern _Atomic int g_fe_name_no_accept;
|
||||
size_t swkbd_u8_to_u16(const char *, size_t, uint16_t *, size_t);
|
||||
size_t swkbd_u16_to_u8(const uint16_t *, size_t, char *, size_t);
|
||||
|
||||
static void free_job(input_job *job) {
|
||||
for (unsigned i = 0; i < 4; i++) free(job->strings[i]);
|
||||
free(job);
|
||||
}
|
||||
|
||||
// 锁内入队;请求拥有字符串副本,不让 JNI 访问客体栈上的局部变量。
|
||||
// Enqueue under the lock; owned string copies keep JNI away from guest-stack locals.
|
||||
static void enqueue(input_job *job) {
|
||||
if (jobs_tail) jobs_tail->next = job; else jobs_head = job;
|
||||
jobs_tail = job;
|
||||
pthread_cond_signal(&work_ready);
|
||||
}
|
||||
|
||||
static void cancel_request(jlong id) {
|
||||
pthread_mutex_lock(&input_lock);
|
||||
if (active_request == id && pending) {
|
||||
result = 0; pending = 0;
|
||||
pthread_cond_signal(&input_done);
|
||||
}
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
}
|
||||
|
||||
// NewStringUTF 不是标准 UTF-8;沿用宿主转换保留中文及代理对。
|
||||
// NewStringUTF uses modified UTF-8; host conversion preserves CJK and surrogate pairs.
|
||||
static jstring utf8_string(JNIEnv *env, const char *text) {
|
||||
size_t capacity = strlen(text) + 1;
|
||||
uint16_t *wide = calloc(capacity, sizeof *wide);
|
||||
if (!wide) return NULL;
|
||||
size_t count = swkbd_u8_to_u16(text, capacity, wide, capacity);
|
||||
jstring value = (*env)->NewString(env, wide, (jsize)count);
|
||||
free(wide);
|
||||
return value;
|
||||
}
|
||||
|
||||
static void *input_worker(void *unused) {
|
||||
(void)unused;
|
||||
pthread_setname_np(pthread_self(), "dm-java-input");
|
||||
JNIEnv *env = NULL;
|
||||
int ready = (*vm)->AttachCurrentThreadAsDaemon(vm, &env, NULL) == JNI_OK;
|
||||
pthread_mutex_lock(&input_lock);
|
||||
worker_state = ready ? 1 : -1;
|
||||
pthread_cond_broadcast(&input_done);
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
__android_log_print(ready ? ANDROID_LOG_INFO : ANDROID_LOG_ERROR, "dm-input", "host worker ready=%d", ready);
|
||||
if (!ready) return NULL;
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&input_lock);
|
||||
while (!jobs_head) pthread_cond_wait(&work_ready, &input_lock);
|
||||
input_job *job = jobs_head;
|
||||
jobs_head = job->next;
|
||||
if (!jobs_head) jobs_tail = NULL;
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
// 不持锁调用 Java:无 Activity 时 Java 会同步回调取消,持锁会死锁。
|
||||
// Never call Java while locked: the no-Activity path cancels synchronously.
|
||||
if (!job->id) {
|
||||
(*env)->CallStaticVoidMethod(env, activity_class, report_failure, job->failure_code);
|
||||
} else {
|
||||
jstring strings[4] = {0};
|
||||
int valid = 1;
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
strings[i] = utf8_string(env, job->strings[i]);
|
||||
if (!strings[i] || (*env)->ExceptionCheck(env)) { valid = 0; break; }
|
||||
}
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-input", "host dispatch id=%lld valid=%d", (long long)job->id, valid);
|
||||
if (valid) (*env)->CallStaticVoidMethod(env, activity_class, show_input, job->id,
|
||||
strings[0], strings[1], strings[2], strings[3], job->max_chars, job->name_rule, job->numeric_max);
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionDescribe(env); (*env)->ExceptionClear(env); valid = 0; }
|
||||
for (unsigned i = 0; i < 4; i++) if (strings[i]) (*env)->DeleteLocalRef(env, strings[i]);
|
||||
if (!valid) cancel_request(job->id);
|
||||
}
|
||||
if ((*env)->ExceptionCheck(env)) { (*env)->ExceptionDescribe(env); (*env)->ExceptionClear(env); }
|
||||
free_job(job);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JNIEXPORT jint JNI_OnLoad(JavaVM *java_vm, void *reserved) {
|
||||
(void)reserved;
|
||||
JNIEnv *env;
|
||||
if ((*java_vm)->GetEnv(java_vm, (void **)&env, JNI_VERSION_1_6) != JNI_OK) return JNI_ERR;
|
||||
jclass local = (*env)->FindClass(env, "com/xiaoboluo/d2r/DmActivity");
|
||||
if (!local) return JNI_ERR;
|
||||
activity_class = (*env)->NewGlobalRef(env, local);
|
||||
(*env)->DeleteLocalRef(env, local);
|
||||
if (!activity_class) return JNI_ERR;
|
||||
show_input = (*env)->GetStaticMethodID(env, activity_class, "showNativeInput",
|
||||
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)V");
|
||||
report_failure = (*env)->GetStaticMethodID(env, activity_class, "showNativeFailure", "(I)V");
|
||||
if (!show_input || !report_failure) return JNI_ERR;
|
||||
vm = java_vm;
|
||||
pthread_t worker;
|
||||
if (pthread_create(&worker, NULL, input_worker, NULL)) worker_state = -1;
|
||||
else pthread_detach(worker);
|
||||
return JNI_VERSION_1_6;
|
||||
}
|
||||
|
||||
void front_android_boot_failed(int code) {
|
||||
input_job *job = calloc(1, sizeof *job);
|
||||
if (!job) return;
|
||||
job->failure_code = code;
|
||||
pthread_mutex_lock(&input_lock);
|
||||
while (!worker_state) pthread_cond_wait(&input_done, &input_lock);
|
||||
if (worker_state > 0) { enqueue(job); job = NULL; }
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
if (job) free_job(job);
|
||||
}
|
||||
|
||||
int front_android_text_input(const char *title, const char *sub, const char *guide,
|
||||
const char *initial, int max_chars, char *out, int out_cap) {
|
||||
if (!out || out_cap <= 0) return -1;
|
||||
input_job *job = calloc(1, sizeof *job);
|
||||
if (!job) return -1;
|
||||
const char *source[] = {title, sub, guide, initial};
|
||||
for (unsigned i = 0; i < 4; i++) {
|
||||
job->strings[i] = strdup(source[i] ? source[i] : "");
|
||||
if (!job->strings[i]) { free_job(job); return -1; }
|
||||
}
|
||||
job->max_chars = max_chars; job->name_rule = g_swkbd_name_panel; job->numeric_max = g_swkbd_numeric_max;
|
||||
int name_rule = job->name_rule;
|
||||
pthread_mutex_lock(&input_lock);
|
||||
while (!worker_state) pthread_cond_wait(&input_done, &input_lock);
|
||||
if (worker_state < 0 || active_request) { pthread_mutex_unlock(&input_lock); free_job(job); return -1; }
|
||||
if (next_request == INT64_MAX) next_request = 0;
|
||||
job->id = active_request = ++next_request;
|
||||
pending = 1; result = 0; output = out; output_capacity = out_cap; out[0] = 0;
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-input", "queued id=%lld max=%d capacity=%d", (long long)job->id, max_chars, out_cap);
|
||||
enqueue(job);
|
||||
while (pending) pthread_cond_wait(&input_done, &input_lock);
|
||||
int accepted = result;
|
||||
output = NULL; active_request = 0;
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
if (accepted && name_rule && !out[0]) {
|
||||
accepted = dm_name_gen(out, out_cap, dm_name_taken);
|
||||
if (accepted) atomic_store(&g_fe_name_no_accept, 1);
|
||||
}
|
||||
return accepted;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_DmActivity_nativeTextResult(
|
||||
JNIEnv *env, jclass cls, jlong id, jboolean accepted, jstring text) {
|
||||
(void)cls;
|
||||
pthread_mutex_lock(&input_lock);
|
||||
// 延迟旧回调不能写入新请求;日志只记录状态,不记录玩家文本。
|
||||
// Stale callbacks cannot write into a new request; log state, never player text.
|
||||
if (pending && active_request == id) {
|
||||
result = accepted && text;
|
||||
if (result) {
|
||||
const jchar *wide = (*env)->GetStringChars(env, text, NULL);
|
||||
if (wide) { swkbd_u16_to_u8(wide, (*env)->GetStringLength(env, text), output, output_capacity); (*env)->ReleaseStringChars(env, text, wide); }
|
||||
else result = 0;
|
||||
}
|
||||
__android_log_print(ANDROID_LOG_INFO, "dm-input", "completed id=%lld accepted=%d", (long long)id, result);
|
||||
pending = 0;
|
||||
pthread_cond_signal(&input_done);
|
||||
}
|
||||
pthread_mutex_unlock(&input_lock);
|
||||
}
|
||||
Executable
+39
@@ -0,0 +1,39 @@
|
||||
#!/bin/bash
|
||||
# 安卓触屏控件与 iOS 画法逐像素对比(防两边各改各的、画法走开):
|
||||
# iOS 一侧:art_ref.m 直接用 dm/ios/Sources/DmTouchControlArt.h 在 Mac 上离屏画参考图;
|
||||
# 安卓一侧:手机上的调试包按同样尺寸用 TouchOverlay 的 Java 画法写 PNG(DmActivity 收到 dmArtDump 只做这件事就退出)。
|
||||
# 用法:art_compare.sh <已导入的 overlay 目录(电脑上那份,d2rm_android.py 出的 android/overlay)> [包名]
|
||||
# ADB:adb 命令(缺省 adb;手机接在别的机器上就写成 "ssh 主机 adb -s 序列号");手机须 480 dpi(3 倍),装的是调试包且已导入。
|
||||
# 判据(逐张,预乘 RGBA、0–255):平均差 ≤ 2、99 分位差 ≤ 32——两套抗锯齿实现(CoreGraphics / Skia)边缘差几个级,图案或参数一走样就远超。
|
||||
# Pixel-by-pixel comparison of the Android touch controls with the iOS drawing (so the two do not drift apart when each side changes):
|
||||
# iOS side: art_ref.m uses dm/ios/Sources/DmTouchControlArt.h directly to draw the reference images offscreen on the Mac;
|
||||
# Android side: the debug build on the phone writes PNGs of the same sizes with TouchOverlay's Java drawing (DmActivity does only that and exits when it gets dmArtDump).
|
||||
# Usage: art_compare.sh <imported overlay directory (the copy on the computer, android/overlay from d2rm_android.py)> [package name]
|
||||
# ADB: the adb command (default adb; with the phone on another machine write "ssh host adb -s serial"); the phone must be 480 dpi (3x), with the debug build installed and the pack imported.
|
||||
# Criterion (per image, premultiplied RGBA, 0–255): mean difference ≤ 2 and 99th percentile ≤ 32 -- the two antialiasing implementations (CoreGraphics / Skia) differ by a few levels at edges; a wrong pattern or parameter goes far beyond that.
|
||||
set -u
|
||||
OV=${1:?用法:art_compare.sh <overlay 目录> [包名]}; PKG=${2:-com.xiaoboluo.d2r}; ADB=${ADB:-adb}
|
||||
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); O=${DM_ROOT:-$HOME/dm-work}/build/android_art; rm -rf "$O" && mkdir -p "$O/ref" "$O/dev"
|
||||
clang -fobjc-arc -O1 -o "$O/art_ref" "$HERE/art_ref.m" -framework Foundation -framework CoreGraphics -framework ImageIO -framework UniformTypeIdentifiers || exit 1
|
||||
"$O/art_ref" "$OV/touchart/dm_mobile_socket.png" "$OV/hud_v4_ui/sil_dm_native_skill_0.png" "$O/ref" || exit 1
|
||||
d=$($ADB shell wm density | awk '/Physical/{print $3}'); [ "$d" = 480 ] || { echo "🔴 手机密度 ${d},不是 480(3 倍)"; exit 1; }
|
||||
$ADB shell run-as "$PKG" rm -rf files/dm/artdump
|
||||
$ADB shell am start -W -n "$PKG/com.xiaoboluo.d2r.DmActivity" --ez dmArtDump true > /dev/null || exit 1
|
||||
for i in $(seq 1 20); do [ "$($ADB shell run-as "$PKG" ls files/dm/artdump 2> /dev/null | grep -c png)" -ge 15 ] && break; sleep 1; done
|
||||
for f in $($ADB shell run-as "$PKG" ls files/dm/artdump | tr -d '\r'); do $ADB exec-out run-as "$PKG" cat "files/dm/artdump/$f" > "$O/dev/$f"; done
|
||||
python3 - "$O/ref" "$O/dev" <<'EOF'
|
||||
import os, sys
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
ref, dev = sys.argv[1:3]; bad = 0; names = sorted(os.listdir(ref))
|
||||
def pm(p):
|
||||
a = np.asarray(Image.open(p).convert('RGBA')).astype(np.float64); a[..., :3] *= a[..., 3:4] / 255; return a
|
||||
print('%-16s %10s %8s %8s %s' % ('控件', '尺寸', '平均差', '99分位', '判'))
|
||||
for n in names:
|
||||
if not os.path.exists(os.path.join(dev, n)): print('%-16s 手机没出这张' % n); bad += 1; continue
|
||||
a, b = pm(os.path.join(ref, n)), pm(os.path.join(dev, n))
|
||||
if a.shape != b.shape: print('%-16s 尺寸不同 %s / %s' % (n, a.shape, b.shape)); bad += 1; continue
|
||||
d = np.abs(a - b); mean, p99 = d.mean(), np.percentile(d, 99); ok = mean <= 2 and p99 <= 32; bad += not ok
|
||||
print('%-16s %10s %8.2f %8.1f %s' % (n[:-4], '%dx%d' % a.shape[1::-1], mean, p99, '✓' if ok else '✗'))
|
||||
print('共 %d 张,不过 %d 张' % (len(names), bad)); sys.exit(1 if bad or not names else 0)
|
||||
EOF
|
||||
@@ -0,0 +1,68 @@
|
||||
// 触屏控件参考图:直接用 iOS 的绘制代码(dm/ios/Sources/DmTouchControlArt.h)离屏画出与安卓 TouchOverlay.dumpArt 同名、同尺寸的 PNG,
|
||||
// 给 art_compare.sh 逐像素比。几何与 iOS 的 controlArt 相同:点坐标 × 3(安卓测试机 480 dpi = 3 倍),y 轴向下(同 UIKit)。
|
||||
// 底座图 / 剪影两步照 DmTouchOverlay.m 的 drawButton / skillImage。
|
||||
// 用法:art_ref <dm_mobile_socket.png> <sil_dm_native_skill_0.png> <输出目录>
|
||||
// Touch control reference images: the iOS drawing code (dm/ios/Sources/DmTouchControlArt.h) draws offscreen PNGs with the same names and sizes as Android's TouchOverlay.dumpArt,
|
||||
// for art_compare.sh to compare pixel by pixel. Geometry as iOS controlArt: point coordinates × 3 (the Android test phone is 480 dpi = 3x), y axis pointing down (as UIKit).
|
||||
// The socket image and silhouette steps follow drawButton / skillImage in DmTouchOverlay.m.
|
||||
// Usage: art_ref <dm_mobile_socket.png> <sil_dm_native_skill_0.png> <output directory>
|
||||
#import <Foundation/Foundation.h>
|
||||
#import <ImageIO/ImageIO.h>
|
||||
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
|
||||
#include "../../ios/Sources/DmTouchControlArt.h"
|
||||
|
||||
static const CGFloat S = 3;
|
||||
static CGImageRef load(const char *path) {
|
||||
CGImageSourceRef src = CGImageSourceCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:@(path)], NULL);
|
||||
CGImageRef img = src ? CGImageSourceCreateImageAtIndex(src, 0, NULL) : NULL; if (src) CFRelease(src); return img;
|
||||
}
|
||||
static void save(CGContextRef c, NSString *dir, NSString *name) {
|
||||
CGImageRef img = CGBitmapContextCreateImage(c);
|
||||
CGImageDestinationRef d = CGImageDestinationCreateWithURL((__bridge CFURLRef)[NSURL fileURLWithPath:[dir stringByAppendingPathComponent:[name stringByAppendingString:@".png"]]],
|
||||
(__bridge CFStringRef)UTTypePNG.identifier, 1, NULL);
|
||||
CGImageDestinationAddImage(d, img, NULL); CGImageDestinationFinalize(d); CFRelease(d); CGImageRelease(img);
|
||||
}
|
||||
// 点尺寸 side 的画布:像素 = round(side × 3),坐标按点、y 向下
|
||||
// a canvas of side points: pixels = round(side × 3), coordinates in points, y pointing down
|
||||
static CGContextRef canvas(CGFloat side, CGFloat *pt) {
|
||||
size_t px = (size_t)llround(side * S); CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
|
||||
CGContextRef c = CGBitmapContextCreate(NULL, px, px, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(cs);
|
||||
CGContextTranslateCTM(c, 0, px); CGContextScaleCTM(c, px / side, -(CGFloat)px / side); *pt = side; return c;
|
||||
}
|
||||
// UIImage drawInRect 在 y 向下的画布里不翻转图像:CGContextDrawImage 前把这一块再翻回来
|
||||
// UIImage drawInRect does not flip the image on a canvas whose y axis points down: flip this area back before CGContextDrawImage
|
||||
static void draw_image(CGContextRef c, CGImageRef img, CGRect r, CGBlendMode mode) {
|
||||
CGContextSaveGState(c); CGContextTranslateCTM(c, 0, CGRectGetMaxY(r) + CGRectGetMinY(r)); CGContextScaleCTM(c, 1, -1);
|
||||
CGContextSetBlendMode(c, mode); CGContextDrawImage(c, r, img); CGContextRestoreGState(c);
|
||||
}
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
if (argc != 4) { fprintf(stderr, "用法:art_ref <dm_mobile_socket.png> <sil_dm_native_skill_0.png> <输出目录>\n"); return 2; }
|
||||
CGImageRef socket = load(argv[1]), sil = load(argv[2]); NSString *dir = @(argv[3]);
|
||||
if (!socket || !sil) { fprintf(stderr, "读不了输入图\n"); return 1; }
|
||||
[NSFileManager.defaultManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
|
||||
CGFloat side;
|
||||
for (int h = 0; h < 2; h++) for (int e = 0; e < 2; e++) for (int p = 0; p < 2; p++) {
|
||||
CGContextRef c = canvas(80, &side); dm_button_draw(c, CGRectMake(0, 0, side, side), h, e, p);
|
||||
save(c, dir, [NSString stringWithFormat:@"button_h%de%dp%d", h, e, p]); CGContextRelease(c);
|
||||
}
|
||||
for (int h = 0; h < 2; h++) { // drawButton 有底座图的分支 | the drawButton branch with the socket image
|
||||
CGContextRef c = canvas(80, &side); CGRect r = CGRectMake(0, 0, side, side);
|
||||
draw_image(c, socket, r, kCGBlendModeNormal); dm_socket_neutralize(c, r); if (h) dm_button_highlight(c, r);
|
||||
save(c, dir, [NSString stringWithFormat:@"socket_h%d", h]); CGContextRelease(c);
|
||||
}
|
||||
for (int a = 0; a < 2; a++) {
|
||||
CGContextRef c = canvas(120, &side); dm_joystick_base_draw(c, CGRectMake(0, 0, side, side), a);
|
||||
save(c, dir, [NSString stringWithFormat:@"joybase_a%d", a]); CGContextRelease(c);
|
||||
c = canvas(46, &side); dm_joystick_thumb_draw(c, CGRectMake(0, 0, side, side), a);
|
||||
save(c, dir, [NSString stringWithFormat:@"joythumb_a%d", a]); CGContextRelease(c);
|
||||
}
|
||||
{ // skillImage 的银灰化:原像素尺寸,画剪影 → 饱和度叠 50% 灰 → 用剪影透明度收边 | skillImage's silvering: at the original pixel size, draw the silhouette → saturation blend with 50% grey → trim the edges with the silhouette's alpha
|
||||
size_t w = CGImageGetWidth(sil), hh = CGImageGetHeight(sil); CGColorSpaceRef cs = CGColorSpaceCreateDeviceRGB();
|
||||
CGContextRef c = CGBitmapContextCreate(NULL, w, hh, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaPremultipliedLast); CGColorSpaceRelease(cs);
|
||||
CGRect r = CGRectMake(0, 0, w, hh);
|
||||
CGContextDrawImage(c, r, sil); dm_skill_silver(c, r); CGContextSetBlendMode(c, kCGBlendModeDestinationIn); CGContextDrawImage(c, r, sil);
|
||||
save(c, dir, @"silver0"); CGContextRelease(c);
|
||||
}
|
||||
CGImageRelease(socket); CGImageRelease(sil); return 0;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
# 苹果(Mach-O)汇编 → 安卓(ELF)汇编:宿主的 .S 只写一份苹果写法(含生成的 nvn_thunks.S),安卓构建时过一遍本脚本再汇编。
|
||||
# 用法:asm_elf.py <输入.S> <输出.S>
|
||||
# 只做语法层的一一对应,不改任何指令:
|
||||
# C 符号的下划线前缀:_name → name(Mach-O 给 C 符号加 _,ELF 不加)
|
||||
# adrp / add 的页寻址:sym@PAGE → sym,sym@PAGEOFF → :lo12:sym
|
||||
# 局部标号:本文件定义的 Lxxx → .Lxxx(ELF 的局部标号前缀)
|
||||
# .cstring → 只读字符串段;.private_extern → .hidden;文件末尾补不可执行栈声明
|
||||
# Apple (Mach-O) assembly → Android (ELF) assembly: the host's .S files are written once in Apple syntax (including the generated nvn_thunks.S), and the Android build runs them through this script before assembling.
|
||||
# Usage: asm_elf.py <input.S> <output.S>
|
||||
# Only one-to-one syntax mapping, no instruction is changed:
|
||||
# underscore prefix of C symbols: _name → name (Mach-O prefixes C symbols with _, ELF does not)
|
||||
# page addressing for adrp / add: sym@PAGE → sym, sym@PAGEOFF → :lo12:sym
|
||||
# local labels: Lxxx defined in this file → .Lxxx (the ELF local label prefix)
|
||||
# .cstring → read-only string section; .private_extern → .hidden; a non-executable stack note is appended at the end of the file
|
||||
import re, sys
|
||||
|
||||
src, dst = sys.argv[1], sys.argv[2]
|
||||
text = open(src, encoding='utf-8').read()
|
||||
locals_ = set(re.findall(r'^\s*(L\w+):', text, re.M))
|
||||
out = []
|
||||
for line in text.split('\n'):
|
||||
code, sep, comment = line.partition('//')
|
||||
code = re.sub(r'(\w+)@PAGEOFF\b', r':lo12:\1', code)
|
||||
code = re.sub(r'(\w+)@PAGE\b', r'\1', code)
|
||||
code = re.sub(r'(?<![\w.$])_(\w+)', r'\1', code)
|
||||
if locals_: code = re.sub(r'(?<![\w.])(L\w+)\b', lambda m: '.' + m.group(1) if m.group(1) in locals_ else m.group(1), code)
|
||||
code = re.sub(r'^(\s*)\.cstring\b', r'\1.section .rodata.str1.1,"aMS",@progbits,1', code)
|
||||
code = re.sub(r'^(\s*)\.private_extern\b', r'\1.hidden', code)
|
||||
out.append(code + sep + comment)
|
||||
out.append(' .section .note.GNU-stack,"",@progbits')
|
||||
open(dst, 'w', encoding='utf-8', newline='\n').write('\n'.join(out) + '\n')
|
||||
@@ -0,0 +1,36 @@
|
||||
#!/usr/bin/env python3
|
||||
"""从统一中英表生成安卓启动界面的资源;不读取游戏文件。
|
||||
Generate Android startup resources from the shared string table; no game files.
|
||||
"""
|
||||
import argparse
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
from xml.sax.saxutils import escape
|
||||
|
||||
|
||||
def generate(output):
|
||||
dm = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location("dm_i18n", dm / "ios/tools/dm_i18n.py")
|
||||
table = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(table)
|
||||
shared = {"dmInputTitle", "dmNameTitle", "dmNameRule", "dmQtyTitle", "dmNameBlankRandom",
|
||||
"dmNamePickIme", "dmNameTooShort", "dmNameEdge", "dmCancel", "dmConfirm", "dmTcCancel", "dmHudLife", "dmHudMana"}
|
||||
rows = [r for r in table.rows() if r[0].startswith("dmAndroid") or r[0] in shared]
|
||||
for folder, column in (("values", 2), ("values-zh", 1)):
|
||||
lines = ['<?xml version="1.0" encoding="utf-8"?>', '<resources>']
|
||||
for row in rows:
|
||||
value = escape(row[column]).replace("\\", "\\\\").replace("'", "\\'").replace('"', '\\"').replace("\n", "\\n")
|
||||
# 多参数C格式由Java显式格式化,避免资源编译器误判非位置参数。
|
||||
# Java formats shared multi-argument C strings explicitly; skip Android's positional-format check.
|
||||
attribute = ' formatted="false"' if row[0] in {"dmHudLife", "dmHudMana", "dmAndroidHudLevel"} else ''
|
||||
lines.append(f' <string name="{row[0]}"{attribute}>{value}</string>')
|
||||
lines.append('</resources>')
|
||||
directory = output / folder
|
||||
directory.mkdir(parents=True, exist_ok=True)
|
||||
(directory / "strings.xml").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--output", type=Path, required=True)
|
||||
generate(parser.parse_args().output)
|
||||
@@ -0,0 +1,37 @@
|
||||
#!/usr/bin/env python3
|
||||
"""读取宿主 Makefile 的源清单,输出 CMake 变量;不处理任何游戏内容。
|
||||
Read source lists from the host Makefile into CMake variables; no game content.
|
||||
"""
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
|
||||
def source_lists(makefile):
|
||||
src, libraries, in_src = [], [], False
|
||||
for line in makefile.read_text(encoding="utf-8").splitlines():
|
||||
if line.startswith("SRC="):
|
||||
in_src = True
|
||||
line = line[4:]
|
||||
if in_src:
|
||||
text = line.strip().rstrip("\\").strip()
|
||||
if re.fullmatch(r"[A-Za-z0-9_./-]+\.c", text) and text != "main.c" and not Path(text).stem.endswith("_mac"):
|
||||
src.append((makefile.parent / text).resolve())
|
||||
in_src = line.rstrip().endswith("\\")
|
||||
if line.startswith("LIBDEFLATE="):
|
||||
libraries = [(makefile.parent / s).resolve() for s in re.findall(r"[A-Za-z0-9_./-]+\.c", line)]
|
||||
if len(src) < 40 or not libraries:
|
||||
raise ValueError("Host Makefile source lists changed; update the Android parser")
|
||||
return src, libraries
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("makefile", type=Path)
|
||||
parser.add_argument("output", type=Path)
|
||||
args = parser.parse_args()
|
||||
source, libraries = source_lists(args.makefile)
|
||||
text = ""
|
||||
for name, paths in (("HOST_SRCS", source), ("LIBDEFLATE_SRCS", libraries)):
|
||||
text += "set(" + name + "\n" + "\n".join(' "' + p.as_posix() + '"' for p in paths) + "\n)\n"
|
||||
args.output.write_text(text, encoding="utf-8", newline="\n")
|
||||
@@ -0,0 +1,71 @@
|
||||
#!/usr/bin/env python3
|
||||
"""合并几台设备的管线预热列表(files/dm/vk-pipeline-list.bin),让每台都在启动时建好别的设备见过的管线。
|
||||
记录格式同引擎(xbg_game.cpp warm::start):魔数 0x57504c58、阶段数(≤5)、各阶段着色器键(长度 ≤256)、建管线信息键(≤4096 字)。
|
||||
按建管线信息键去重,保留第一份的顺序;坏记录及其后的内容同引擎一样丢掉。设备上不认得的记录在预热时建失败(warm_failed),不影响游戏。
|
||||
Merge the pipeline warm-up lists (files/dm/vk-pipeline-list.bin) of several devices, so that each builds at start-up the
|
||||
pipelines the others have seen. Records as in the engine (xbg_game.cpp warm::start): magic 0x57504c58, stage count (<= 5),
|
||||
each stage's shader key (length <= 256), the create-info key (<= 4096 words). Records are de-duplicated by the create-info
|
||||
key, keeping the first file's order; a bad record and everything after it is dropped, as the engine does. A record a
|
||||
device cannot build fails in its warm-up (warm_failed) without affecting the game.
|
||||
"""
|
||||
import argparse
|
||||
import struct
|
||||
import sys
|
||||
|
||||
MAGIC = 0x57504C58
|
||||
MAX_STAGES = 5
|
||||
MAX_KEY = 256
|
||||
MAX_WORDS = 4096
|
||||
|
||||
|
||||
def records(data):
|
||||
"""每条好记录的(建管线信息键字节, 记录字节),到第一条坏记录为止 | (create-info key bytes, record bytes) for each good record, stopping at the first bad one."""
|
||||
i, out = 0, []
|
||||
|
||||
def get():
|
||||
nonlocal i
|
||||
if i + 4 > len(data):
|
||||
return None
|
||||
v = struct.unpack_from('<I', data, i)[0]
|
||||
i += 4
|
||||
return v
|
||||
|
||||
while i < len(data):
|
||||
start = i
|
||||
magic, ns = get(), get()
|
||||
if magic != MAGIC or ns is None or ns > MAX_STAGES:
|
||||
break
|
||||
good = True
|
||||
for _ in range(ns):
|
||||
n = get()
|
||||
if n is None or n > MAX_KEY or i + n > len(data):
|
||||
good = False
|
||||
break
|
||||
i += n
|
||||
count = get() if good else None
|
||||
if count is None or count > MAX_WORDS or i + count * 4 > len(data):
|
||||
break
|
||||
key = data[i:i + count * 4]
|
||||
i += count * 4
|
||||
out.append((key, data[start:i]))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('lists', nargs='+', help='vk-pipeline-list.bin files, first one first')
|
||||
ap.add_argument('-o', '--output', required=True)
|
||||
a = ap.parse_args()
|
||||
seen, merged = set(), []
|
||||
for path in a.lists:
|
||||
recs = records(open(path, 'rb').read())
|
||||
new = [r for k, r in recs if k not in seen and not seen.add(k)]
|
||||
merged += new
|
||||
print('%s: %d records, %d new' % (path, len(recs), len(new)))
|
||||
with open(a.output, 'wb') as f:
|
||||
f.write(b''.join(merged))
|
||||
print('%s: %d records' % (a.output, len(merged)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.exit(main())
|
||||
Executable
+82
@@ -0,0 +1,82 @@
|
||||
#!/bin/bash
|
||||
# 出安卓的发布包:一个不含任何游戏内容的 APK。玩家用自己的游戏文件在电脑上做导入包(dm/tools/d2rm_android.py),拷进手机,App 打开时导入。
|
||||
# shell_apk.sh [release] [gradle 参数…] 例:shell_apk.sh -PdmAppId=org.example.test(换包名并排装)
|
||||
# 缺省出调试包(可调试,测试用:art_compare.sh 要 run-as);release = 发布用的正式包:release 构建、用正式钥匙签,钥匙与密码在本机
|
||||
# ${DM_ANDROID_SIGN:-~/.config/dm-android/release.env}(DM_ANDROID_KEYSTORE / DM_ANDROID_KEY_ALIAS / DM_ANDROID_KEY_PASS),不进仓库
|
||||
# 产物($DM_ROOT/build/android_shell/):D2RMobile-android.apk;gen/ = 编进去的替身表;ref/ = 用本机游戏文件生成的真表(只用来核对,不发布)
|
||||
# 做法同 iOS 壳(dm/ios/tools/shell_build.sh):三份「从游戏文件生成、编进代码」的文件(经验表、编年史仓库表、技能图标索引)换成替身,
|
||||
# 运行时从导入的 files/dm/derived.tsv 读(dm/host/dm_derived_rt.h);亮度表 dm_bright_levels.inc 照 iOS 壳编进去(每个关卡号一位:随不随昼夜)。
|
||||
# 游戏程序、着色器、覆盖层、界面素材本来就不进 APK(运行时在 files/dm/)。出包这台机器要有游戏文件:要用真实的生成结果定表的大小。
|
||||
# 在源码副本里构建($O/tree,只含仓库跟踪的与未被忽略的文件):工作树里平时构建留下的真表(dm/host/dm_vault_tab.h 等)会被
|
||||
# #include "…" 先于生成目录找到,副本里没有它们。
|
||||
# 环境:JAVA_HOME(JDK 17+)、ANDROID_HOME(SDK 36 + NDK 29.0.14206865 + CMake 3.31.6);缺省取 Homebrew 的 openjdk@17 与 ~/Library/Android/sdk
|
||||
# Build the Android release package: an APK with no game content. Players make the import pack on a computer from their own game files (dm/tools/d2rm_android.py), copy it to the phone, and the App imports it when opened.
|
||||
# shell_apk.sh [release] [gradle arguments...] e.g. shell_apk.sh -PdmAppId=org.example.test (another application id, to install side by side)
|
||||
# Default is a debug package (debuggable, for testing: art_compare.sh needs run-as); release = the package for publishing: a release build signed with the release key, whose key and password live on this machine in
|
||||
# ${DM_ANDROID_SIGN:-~/.config/dm-android/release.env} (DM_ANDROID_KEYSTORE / DM_ANDROID_KEY_ALIAS / DM_ANDROID_KEY_PASS), never in the repository
|
||||
# Products ($DM_ROOT/build/android_shell/): D2RMobile-android.apk; gen/ = the stand-in tables compiled in; ref/ = the real tables generated from this machine's game files (only for checking, never released)
|
||||
# Same approach as the iOS shell (dm/ios/tools/shell_build.sh): the three files "generated from game files and compiled in" (experience table, chronicle vault table, skill icon index) are replaced by stand-ins
|
||||
# that read the imported files/dm/derived.tsv at run time (dm/host/dm_derived_rt.h); the brightness table dm_bright_levels.inc is compiled in as in the iOS shell (one bit per level number: follows day and night or not).
|
||||
# The game program, shaders, overlay and UI art never go into the APK (they are in files/dm/ at run time). The building machine needs the game files: the real generated results set the table sizes.
|
||||
# Builds in a copy of the source ($O/tree, only tracked and non-ignored files): the real tables a normal build leaves in the working tree (dm/host/dm_vault_tab.h and others) would be
|
||||
# found by #include "..." before the generated directory; the copy does not have them.
|
||||
# Environment: JAVA_HOME (JDK 17+), ANDROID_HOME (SDK 36 + NDK 29.0.14206865 + CMake 3.31.6); default Homebrew's openjdk@17 and ~/Library/Android/sdk
|
||||
set -u
|
||||
KIND=debug; [ "${1:-}" = release ] && { KIND=release; shift; }
|
||||
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd); DM=$(cd "$HERE/../.." && pwd)
|
||||
ROOT=${DM_ROOT:-$HOME/dm-work}; O=$ROOT/build/android_shell; G=$O/gen
|
||||
ROMFS=${DM_ROMFS_SRC:-$ROOT/data/switch/3.3.94012/Update/RomFS}
|
||||
PY=${DM_PYTHON:-$ROOT/build/cache/dm/venv/bin/python}
|
||||
export JAVA_HOME=${JAVA_HOME:-$(brew --prefix openjdk@17 2> /dev/null)/libexec/openjdk.jdk/Contents/Home}
|
||||
export ANDROID_HOME=${ANDROID_HOME:-$HOME/Library/Android/sdk}; export ANDROID_SDK_ROOT=$ANDROID_HOME
|
||||
t() { echo "[$(date +%T)] $*"; }; die() { t "🔴 $*"; exit 1; }
|
||||
[ -f "$ROMFS/data/build_manifest.psv" ] || die "没找到游戏文件 ${ROMFS}(DM_ROMFS_SRC)"
|
||||
W=$O/tree
|
||||
rm -rf "$G" "$O/ref" "$O/D2RMobile-android.apk" && mkdir -p "$G" "$O/ref" "$W" || die "建不了 $O"
|
||||
(cd "$DM/.." && git ls-files -z -co --exclude-standard dm | rsync -a -0 --ignore-missing-args --files-from=- . "$W/") || die "拷源码副本失败"
|
||||
for f in host/dm_vault_tab.h host/dm_hud_exp.h host/dm_bright_levels.inc ios/Sources/dm_touch_native_art.c; do [ ! -e "$W/dm/$f" ] || die "副本里有生成文件 $f"; done
|
||||
t "用本机游戏文件生成真表"
|
||||
"$PY" "$DM/ios/tools/gen_vault_table.py" "$ROMFS" > "$G/dm_vault_tab.h" || die "生成 dm_vault_tab.h 失败"
|
||||
"$PY" "$DM/ios/tools/gen_hud_exp.py" "$ROMFS" > "$G/dm_hud_exp.h" || die "生成 dm_hud_exp.h 失败"
|
||||
"$PY" "$DM/tools/gen_bright_levels.py" "$ROMFS" > "$G/dm_bright_levels.inc" || die "生成 dm_bright_levels.inc 失败"
|
||||
"$PY" "$DM/ios/tools/native_art/generate.py" "$ROMFS" --output-dir "$O/ref/native_art" > /dev/null || die "生成技能图标索引失败"
|
||||
cp "$O/ref/native_art/dm_touch_native_art.c" "$G/" && cp "$G/dm_vault_tab.h" "$G/dm_hud_exp.h" "$G/dm_touch_native_art.c" "$O/ref/" || die "拷真表失败"
|
||||
"$PY" "$DM/ios/tools/shell_stubs.py" data-gen "$G" "$O/ref/derived.tsv" || die "拆表失败"
|
||||
"$PY" "$DM/ios/tools/shell_stubs.py" stubs-gen "$G" || die "写替身失败"
|
||||
t "构建 APK"
|
||||
if [ $KIND = release ]; then
|
||||
SIGN=${DM_ANDROID_SIGN:-$HOME/.config/dm-android/release.env}; [ -f "$SIGN" ] || die "没有正式钥匙配置 $SIGN"
|
||||
set -a; . "$SIGN"; set +a; [ -f "${DM_ANDROID_KEYSTORE:-}" ] && [ -n "${DM_ANDROID_KEY_PASS:-}" ] || die "钥匙配置不全:$SIGN"
|
||||
TASK=:app:assembleRelease; OUT=$W/dm/android/app/build/outputs/apk/release/app-release.apk
|
||||
else unset DM_ANDROID_KEYSTORE; TASK=:app:assembleDebug; OUT=$W/dm/android/app/build/outputs/apk/debug/app-debug.apk; fi
|
||||
rm -f "$OUT" # 增量打包会在旧 APK 上追加、留下空洞(实测 25 MB 的内容出了 46 MB),整份重写 | incremental packaging appends to the old APK and leaves holes (25 MB of content came out as 46 MB in a test); rewrite it whole
|
||||
gradle --no-daemon -q -p "$W/dm/android" $TASK -PdmGenDir="$G" -PdmPython="$PY" "$@" > "$O/build.log" 2>&1 || { grep -E "error|FAIL" "$O/build.log" | head -8; die "构建失败,日志 $O/build.log"; }
|
||||
cp "$OUT" "$O/D2RMobile-android.apk" || die "没找到构建出的 APK"
|
||||
# 核对:APK 里不许有游戏内容——真表里的字符串(编年史仓库的物品键与图标路径,只取源码里本来没有的:多语表等会带物品名)不能出现在原生库里,
|
||||
# 也不许带游戏程序 / 着色器包 / 覆盖层
|
||||
# Check: no game content in the APK -- strings from the real tables (the chronicle vault's item keys and icon paths, only those not already in the source: the string table and others carry item names) must not appear in the native library,
|
||||
# and no game program / shader bundles / overlay may be packed
|
||||
A=$O/D2RMobile-android.apk; L=$O/libdm.so; unzip -p "$A" lib/arm64-v8a/libdm.so > "$L" || die "APK 里没有 lib/arm64-v8a/libdm.so"
|
||||
n=0; hit=0
|
||||
while IFS= read -r k; do [ ${#k} -ge 6 ] || continue; git -C "$DM" grep -qF -- "$k" -- . && continue
|
||||
n=$((n + 1)); LC_ALL=C grep -qaF -- "$k" "$L" && { hit=$((hit + 1)); echo " 原生库里有:$k"; }
|
||||
done < <(awk -F'\t' '$1=="VTROW"{print $8; print $9}' "$O/ref/derived.tsv" | sort -u)
|
||||
[ "$n" -ge 100 ] || die "能核的字符串只有 $n 个,核不了"
|
||||
[ "$hit" = 0 ] || die "原生库里出现了真表里的字符串($hit 处 / 核了 $n 个):替身没生效"
|
||||
# 也不许带本机路径(用户名 / 目录结构):整个 APK 解开逐个文件查(CMakeLists.txt 用 -ffile-prefix-map 换掉了编译路径)
|
||||
X=$O/apk_x; rm -rf "$X" && mkdir -p "$X" && (cd "$X" && unzip -q "$A") || die "解不开 APK"
|
||||
leak=$(LC_ALL=C grep -raoE -- "/Users/[A-Za-z0-9._-]+|$HOME" "$X" | head -3)
|
||||
[ -z "$leak" ] || die "APK 里带着本机路径:$leak"
|
||||
# 正式包:签名必须是正式钥匙(证书指纹与钥匙库一致、主体只有项目名),且不可调试
|
||||
# Release package: the signature must be the release key (certificate fingerprint equal to the keystore's, subject only the project name), and it must not be debuggable
|
||||
if [ $KIND = release ]; then
|
||||
BT=$(ls -d "$ANDROID_HOME"/build-tools/* | tail -1)
|
||||
got=$("$BT/apksigner" verify --print-certs "$A" 2>&1 | sed -n 's/.*certificate SHA-256 digest: //p' | head -1)
|
||||
want=$("$JAVA_HOME/bin/keytool" -list -v -keystore "$DM_ANDROID_KEYSTORE" -storepass "$DM_ANDROID_KEY_PASS" 2>/dev/null | sed -n 's/^.*SHA256: //p' | head -1 | tr -d ':' | tr 'A-F' 'a-f')
|
||||
[ -n "$got" ] && [ "$got" = "$want" ] || die "签名不是正式钥匙(APK $got / 钥匙 ${want})"
|
||||
dn=$("$BT/apksigner" verify --print-certs "$A" 2>&1 | sed -n 's/.*certificate DN: //p' | head -1); [ "$dn" = "CN=D2R Mobile, O=D2R Mobile" ] || die "证书主体不对:$dn"
|
||||
"$BT/aapt2" dump xmltree --file AndroidManifest.xml "$A" | grep -q 'android:debuggable' && die "正式包是可调试的"
|
||||
fi
|
||||
bad=$(unzip -l "$A" | awk '{print $4}' | grep -E '\.(xgs|patched\.bin|data)$|^assets/|overlay|derived\.tsv' | head -3)
|
||||
[ -z "$bad" ] || die "APK 里带了不该有的文件:$bad"
|
||||
t "好了(${KIND}):${A}($(($(stat -f %z "$A") / 1048576)) MB);核了真表里 $n 个源码里没有的字符串,原生库里 0 处;APK 里没有游戏程序 / 着色器包 / 覆盖层,也没有本机路径"
|
||||
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""把仓外验证过的技能图集与HUD加入安卓overlay,不改原资源或安装包。
|
||||
Stage externally generated skill atlases and HUD into Android's overlay, leaving original resources and APKs alone.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'ios/tools'))
|
||||
import overlay_contract
|
||||
|
||||
|
||||
def stage(native_art, hud, overlay):
|
||||
"""只接收生成器的固定PNG及HUD引用,不接收源码、存档或签名文件。
|
||||
Accept generator PNGs and HUD references only, never source code, saves or signing files.
|
||||
"""
|
||||
native_art, hud, overlay = map(Path, (native_art, hud, overlay))
|
||||
required = {f'dm_native_skill_{i}.png' for i in range(9)}
|
||||
required.update(('dm_native_map.png', 'dm_native_menu.png', 'dm_native_circle.png'))
|
||||
for name in sorted(required):
|
||||
path = native_art / name
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise ValueError(f'missing or unsafe native art: {name}')
|
||||
ui = json.loads((hud / 'ui.json').read_text(encoding='utf-8'))
|
||||
files = {'ui.json', 'base_full.png', 'lvl_0.png', 'lvl_1.png', 'lvl_d0.png', 'lvl_d1.png', 'slot.png'}
|
||||
files.update(f'diff_{i}.png' for i in range(1, 9))
|
||||
# 技能钮上画的是同帧位的银色剪影(gen_hud_v4.py 出,iOS 同一套),不是原版方形图集
|
||||
# The skill buttons draw the silver silhouettes at the same frame positions (from gen_hud_v4.py, as on iOS), not the square original atlases
|
||||
files.update(f'sil_dm_native_skill_{i}.png' for i in range(9))
|
||||
for group in ('lv', 'badge', 'vital'):
|
||||
for glyph in ui[group]['glyphs'].values():
|
||||
if glyph.get('file') is None and isinstance(glyph.get('adv'), (int, float)) and glyph['adv'] >= 0:
|
||||
continue
|
||||
name = overlay_contract.valid_relative_path(glyph['file'])
|
||||
if '/' in name or not name.endswith('.png'):
|
||||
raise ValueError('HUD glyph must be a flat PNG path')
|
||||
files.add(name)
|
||||
for name in sorted(files):
|
||||
path = hud / name
|
||||
if not path.is_file() or path.is_symlink():
|
||||
raise ValueError(f'missing or unsafe HUD asset: {name}')
|
||||
# 检查完整后才复制;最终manifest涵盖全部生成图像,启动时逐字节验证。
|
||||
# Copy only after completeness checks; the final manifest covers every generated image for byte verification at startup.
|
||||
for source, subdir, names in ((native_art, 'touchart', required), (hud, 'hud_v4_ui', files)):
|
||||
target = overlay / subdir
|
||||
target.mkdir(parents=True, exist_ok=True)
|
||||
for name in sorted(names):
|
||||
shutil.copyfile(source / name, target / name)
|
||||
# 技能钮底座(仓库自带的项目美术,不是游戏资源;iOS 同一张 ControlArt/dm_mobile_socket.png)一并放进 touchart,manifest 覆盖它。
|
||||
# The skill-button socket (project art shipped in the repository, not game art; the same ControlArt/dm_mobile_socket.png as iOS) goes
|
||||
# into touchart too, so the manifest covers it.
|
||||
socket = Path(__file__).resolve().parents[3] / 'dm/ios/Sources/ControlArt/dm_mobile_socket.png'
|
||||
if not socket.is_file() or socket.is_symlink():
|
||||
raise ValueError('missing or unsafe socket art: dm_mobile_socket.png')
|
||||
shutil.copyfile(socket, overlay / 'touchart' / 'dm_mobile_socket.png')
|
||||
source_sha = overlay_contract.source_fingerprint(Path(__file__).resolve().parents[3])
|
||||
overlay_contract.write_manifest(overlay, source_sha)
|
||||
entries = overlay_contract.verify_manifest(overlay, source_sha)
|
||||
print(json.dumps({'source_sha256': source_sha, 'overlay_files': len(entries), 'native_art': len(required), 'hud': len(files)}, sort_keys=True))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--native-art', required=True, type=Path, help='Generated TouchArt directory')
|
||||
parser.add_argument('--hud', required=True, type=Path, help='Generated hud_v4_ui directory')
|
||||
parser.add_argument('--overlay', required=True, type=Path, help='New candidate overlay, never a live imported directory')
|
||||
args = parser.parse_args()
|
||||
stage(args.native_art, args.hud, args.overlay)
|
||||
@@ -0,0 +1,415 @@
|
||||
#include "touch_android.h"
|
||||
#include "../ios/Sources/dm_touch_controls.h"
|
||||
#include "../host/dm_input.h"
|
||||
#include "../host/dm_cursor.h"
|
||||
#include "../host/dm_actions.h"
|
||||
#include "../host/dm_hud.h"
|
||||
#include "../host/dm_custom.h"
|
||||
#include "../host/dm_world.h"
|
||||
#include "../ios/Sources/dm_touch_native_art.h"
|
||||
#include <pthread.h>
|
||||
#include <math.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
uint64_t now_ns(void);
|
||||
void dm_uiscreen_set_panel(int panel);
|
||||
void dm_tp_request(void);
|
||||
/* 绑定观测桥未接入时不捏造技能绑定;基础键位仍走共用状态机。 | Do not fabricate skill bindings if the observation bridge is absent; basic keys still use the shared state machine. */
|
||||
void dm_touch_game_set_scene(int game, uint64_t scene, uint64_t world) __attribute__((weak));
|
||||
|
||||
typedef struct { int phase, slot; float x, y; double time; } touch_event;
|
||||
static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static dm_tc_state tc;
|
||||
static dm_tc_scene scene;
|
||||
/* 面板栈读数(宿主 dm_cursor.c dm_hud_stack_msg,iOS / Mac 同一份):开着的非常驻面板数,只开着 NPC 对话菜单时 −1
|
||||
Panel stack reading (host dm_cursor.c dm_hud_stack_msg, shared with iOS / Mac): open non-resident panels, −1 when only the NPC dialog menu is open */
|
||||
int dm_hud_stack_msg(const char *act, const char *arg);
|
||||
static int hud_blocked;
|
||||
static touch_event queue[256];
|
||||
static unsigned head, tail;
|
||||
static int ready, focused = 1, cancel, resizing, ui_drag;
|
||||
static float width = 800, height = 375, safe_left, safe_right, safe_bottom;
|
||||
static int tablet_layout, swap_above;
|
||||
typedef struct { int kind; float x,y; double time; uint64_t key; } direct_gesture;
|
||||
static direct_gesture direct[DM_TC_MAX_TOUCH];
|
||||
static uint32_t selected_point;
|
||||
static double stat_next, skill_add_at;
|
||||
static unsigned map_world_seq;
|
||||
static int map_world_pending;
|
||||
static uint64_t epoch = 1, world = 1, pulse_epoch, pulse_sample, resume_sample;
|
||||
static double pulse_hold_start;
|
||||
static unsigned seen_world, seen_mouse, seen_tab, seen_use, seen_ident, seen_long, seen_item, seen_stack;
|
||||
/* 前端页面(主菜单 / 选角 / 建角 / 读取画面,即不在局内),同 iOS front_ios.m frontendMode:不画控件,第一根手指直接当原生点击交给游戏界面
|
||||
(dm_ui_touch → 鼠标消息,dm_cursor.c),纵向拖过 10 点改成滚动。只在装了触屏覆盖层(DM_ROMFS_OVERLAY)时这样:覆盖层把选角页换成键鼠版
|
||||
(「开始」「创建新角色」靠点);没有覆盖层时前端是原版手柄页,仍走导航键。
|
||||
Front-end pages (main menu / character select / creation / loading, i.e. not in a run), as iOS front_ios.m frontendMode: no controls are drawn, and
|
||||
the first finger goes straight to the game UI as a native click (dm_ui_touch → mouse messages, dm_cursor.c); a vertical drag past 10 points scrolls.
|
||||
Only with the touch overlay (DM_ROMFS_OVERLAY): it turns character select into the keyboard-and-mouse page ("Play", "Create New" are tapped);
|
||||
without it the front end is the original controller page and keeps the navigation keys. */
|
||||
static int frontend, fe_slot = -1, fe_drag;
|
||||
static float fe_x0, fe_y0;
|
||||
/* 面板态的五个虚拟手柄圆钮:缺省不给(同 iOS front_ios.m navigationMode:点按 / 双击 / 拖放 / 点页签 / 面板外点按已全部替代);DM_TOUCH_NAV_PAD=1 调试时叫回来
|
||||
The five virtual pad buttons in panel state: off by default (as iOS front_ios.m navigationMode: tap / double tap / drag / tab tap / tap outside
|
||||
the panel replace them all); DM_TOUCH_NAV_PAD=1 brings them back for debugging */
|
||||
static int nav_pad(void) { static int v = -1; if (v < 0) { const char *e = getenv("DM_TOUCH_NAV_PAD"); v = e && e[0] == '1'; } return v; }
|
||||
static int touch_overlay(void) { static int v = -1; if (v < 0) { const char *o = getenv("DM_ROMFS_OVERLAY"); v = o && *o; } return v; }
|
||||
static void fe_end_locked(void) {
|
||||
if (fe_slot >= 0) { if (fe_drag) dm_ui_drag_end(); else dm_ui_touch(3, 0, 0); }
|
||||
fe_slot = -1; fe_drag = 0;
|
||||
}
|
||||
static void fe_event_locked(const touch_event *e) {
|
||||
if (e->phase == 0 && fe_slot < 0) { fe_slot = e->slot; fe_x0 = e->x; fe_y0 = e->y; fe_drag = 0; }
|
||||
if (e->slot != fe_slot) return;
|
||||
float nx = e->x / width, ny = e->y / height, dy = fabsf(e->y - fe_y0);
|
||||
if (e->phase == 1 && !fe_drag && dy > 10 && dy > fabsf(e->x - fe_x0) && dm_ui_fe_drag_ok()) {
|
||||
fe_drag = 1; dm_ui_touch(3, 0, 0); dm_ui_drag_begin(1, fe_x0 / width, fe_y0 / height, 0);
|
||||
}
|
||||
if (fe_drag) { if (e->phase == 1) dm_ui_drag_move(nx, ny); else fe_end_locked(); return; }
|
||||
if (e->phase == 3) { fe_end_locked(); return; }
|
||||
dm_ui_touch(e->phase, nx, ny);
|
||||
if (e->phase == 2) fe_slot = -1;
|
||||
}
|
||||
|
||||
static void init_locked(void) {
|
||||
if (ready) return;
|
||||
dm_tc_set_tall_scale(tablet_layout);
|
||||
dm_tc_init(&tc, width, height);
|
||||
tc.mouse_click_mode = 1;
|
||||
dm_tc_set_navigation_mode(&tc, 1);
|
||||
dm_tc_enable_targets(&tc, dm_tc_nav_mask(nav_pad())); /* 开局读取期间也是面板态,同样不出圆钮 | loading at game start is panel state too, no buttons either */
|
||||
ready = 1;
|
||||
}
|
||||
static void cancel_locked(void) {
|
||||
dm_tc_cancel_all(&tc);
|
||||
if (ui_drag) dm_ui_drag_end();
|
||||
ui_drag = 0;
|
||||
fe_end_locked();
|
||||
pulse_epoch = pulse_sample = resume_sample = 0;
|
||||
pulse_hold_start = 0;
|
||||
memset(direct,0,sizeof direct); selected_point=0; stat_next=skill_add_at=0; map_world_pending=0;
|
||||
dm_cursor_clear();
|
||||
}
|
||||
void dm_android_touch_resize(float w, float h, float l, float r, float b) {
|
||||
if (!isfinite(w) || !isfinite(h) || w <= 0 || h <= 0) return;
|
||||
pthread_mutex_lock(&lock);
|
||||
width = w; height = h; safe_left = fmaxf(0,l); safe_right = fmaxf(0,r); safe_bottom = fmaxf(0,b);
|
||||
resizing = cancel = 1; head = tail = 0;
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
void dm_android_touch_tablet(int tablet) {
|
||||
pthread_mutex_lock(&lock);
|
||||
tablet_layout = !!tablet; resizing = cancel = 1;
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
void dm_android_touch_focus(int active) {
|
||||
pthread_mutex_lock(&lock);
|
||||
focused = !!active; cancel = 1; head = tail = 0;
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
void dm_android_touch_event(int phase, int slot, float x, float y) {
|
||||
if (phase < 0 || phase > 3 || slot < 0 || slot >= DM_TC_MAX_TOUCH || !isfinite(x) || !isfinite(y)) return;
|
||||
pthread_mutex_lock(&lock);
|
||||
if (focused) {
|
||||
/* 溢出只取消,绝不遗留按住的摇杆/按键。 | Overflow cancels instead of leaving a stick/key held. */
|
||||
if (tail - head == 256) { cancel = 1; head = tail = 0; }
|
||||
else { queue[tail++ % 256] = (touch_event){phase, slot, x, y, now_ns() / 1e9}; }
|
||||
}
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
void dm_android_touch_uimsg(const char *cat, const char *act, const char *arg) {
|
||||
if (!cat || !act) return;
|
||||
pthread_mutex_lock(&lock);
|
||||
init_locked();
|
||||
dm_tc_scene before = scene;
|
||||
dm_tc_set_panel_state(dm_ui_panel_state());
|
||||
if (!strcmp(cat, "PanelManager")) hud_blocked = dm_hud_stack_msg(act, arg ? arg : "");
|
||||
int nav = dm_tc_navigation(&scene, cat, act, arg ? arg : "");
|
||||
/* 同 iOS front_ios.m:局内只要面板栈里还开着非常驻面板就是面板态(不靠名单);再分出死亡弹窗(2)与只开着对话菜单(3)
|
||||
As iOS front_ios.m: in game any open non-resident panel means panel state (not a name list); then split out the death dialog (2) and dialog menu only (3) */
|
||||
if (scene.game && hud_blocked > 0) nav = 1;
|
||||
nav = dm_tc_panel_mode(nav, &scene, hud_blocked);
|
||||
if (before.game != scene.game || before.panels != scene.panels) {
|
||||
++epoch; if (before.game != scene.game) ++world;
|
||||
cancel_locked(); head = tail = 0;
|
||||
}
|
||||
int fe = !scene.game && touch_overlay();
|
||||
if (fe != frontend) { cancel_locked(); head = tail = 0; frontend = fe; }
|
||||
dm_tc_set_navigation_mode(&tc, nav);
|
||||
dm_tc_set_joy_block(&tc, !!(dm_ui_panel_state() & DM_PS_TEXT));
|
||||
/* 游戏态不要右上地图键(同 iOS front_ios.m navigationMode:点右上角小地图本身就开全屏地图,见 direct_begin)
|
||||
No top-right map key in game state (as iOS front_ios.m navigationMode: tapping the top-right minimap itself opens the full map, see direct_begin) */
|
||||
/* 3 = 只开着 NPC 对话菜单:底栏十字可点(原版 + 键此时 = 关对话并开功能页),同 iOS | 3 = only the NPC dialog menu is open: the bar's cross is tappable, as iOS */
|
||||
dm_tc_enable_targets(&tc, nav ? (dm_tc_nav_mask(nav_pad() && nav != 2 && !dm_tc_scene_dead()) | (nav == 3 ? 1u << DM_TC_MENU : 0u))
|
||||
: (((1u << DM_TC_COUNT) - 1) & ~(1u << DM_TC_MAP)));
|
||||
dm_uiscreen_set_panel(nav && !dm_tc_scene_dead() && !dm_tc_scene_dialog_only(&scene));
|
||||
if (dm_touch_game_set_scene) dm_touch_game_set_scene(!nav, epoch, world);
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
static void sync_host(void) {
|
||||
dm_tc_set_panel_state(dm_ui_panel_state());
|
||||
dm_tc_set_tap_box(dm_ui_tap_box());
|
||||
dm_tc_set_cur_stack(dm_ui_cur_stack_id());
|
||||
dm_tc_set_hover_unid(dm_ui_hover_unid());
|
||||
dm_hud_info info; dm_hud_get(&info);
|
||||
dm_tc_set_holding(&tc, info.valid && info.holding && !dm_ui_targeting());
|
||||
tc.belt_rows = dm_belt_rows(&tc.belt_open);
|
||||
}
|
||||
static void requests(void) {
|
||||
if (seen_tab != tc.tab_tap_seq) { seen_tab = tc.tab_tap_seq; dm_ui_tab_go(); }
|
||||
if (seen_use != tc.use_seq) { seen_use = tc.use_seq; dm_ui_use_item(); }
|
||||
if (seen_ident != tc.ident_seq) { seen_ident = tc.ident_seq; dm_ui_identify_hovered(); }
|
||||
if (seen_long != tc.long_press_seq) { seen_long = tc.long_press_seq; dm_ui_long_press(); }
|
||||
if (seen_item != tc.item_tap_seq) { seen_item = tc.item_tap_seq; dm_ui_item_tap(); }
|
||||
if (seen_stack != tc.stack_take_seq) { seen_stack = tc.stack_take_seq; dm_stash_take(1); }
|
||||
if (seen_world != tc.world_tap_seq) {
|
||||
seen_world = tc.world_tap_seq;
|
||||
float nx = tc.world_tap_x / width, ny = tc.world_tap_y / height;
|
||||
dm_ui_world_tap(nx, ny, nx, ny);
|
||||
}
|
||||
if (seen_mouse != tc.mouse_click_seq) {
|
||||
seen_mouse = tc.mouse_click_seq;
|
||||
float nx = tc.mouse_click_x / width, ny = tc.mouse_click_y / height;
|
||||
dm_ui_touch(0,nx,ny); dm_ui_touch(2,nx,ny);
|
||||
}
|
||||
if (tc.diff_request) { dm_hud_request_players(tc.diff_request); tc.diff_request = 0; }
|
||||
if (tc.belt_request) {
|
||||
int br = tc.belt_request; tc.belt_request = 0;
|
||||
if (br == 1 || br == 2) dm_belt_expand(br == 1);
|
||||
else dm_belt_use(br & 15, (br >> 4) & 15);
|
||||
}
|
||||
}
|
||||
static void release_pointer(dm_tc_finger *f) {
|
||||
float lift = DM_TC_POINTER_LIFT_PT * dm_tc_scale_for_size(width,height);
|
||||
int kind = dm_ui_drop_at_now(f->x/width, (f->y-lift)/height, f->y/height);
|
||||
float x,y;
|
||||
if (f->shop_drag) {
|
||||
if (kind == 11) dm_ui_stack_cube_at(f->aim_origin_x/width,f->aim_origin_y/height);
|
||||
else if (kind == 5 && dm_ui_drop_bag()) {
|
||||
if (tc.pointer_stack) dm_ui_stack_take_at(f->aim_origin_x/width,f->aim_origin_y/height);
|
||||
else dm_ui_shop_buy_at(f->aim_origin_x/width,f->aim_origin_y/height);
|
||||
}
|
||||
tc.pointer_x = f->aim_origin_x; tc.pointer_y = f->aim_origin_y;
|
||||
} else if ((kind == 5 && dm_ui_drop_point(&x,&y)) || (kind == 0 && dm_ui_origin_point(&x,&y))) dm_tc_pointer_release_at(&tc,x*width,y*height);
|
||||
else { if (kind == 7) { dm_shop_sell_cursor(); kind = 0; } dm_tc_pointer_release(&tc,kind); }
|
||||
}
|
||||
/* 空技能位和小地图先截获,不发攻击、世界点击或摇杆输入。
|
||||
Capture empty skill slots and minimap taps before emitting attack, world-tap or joystick input. */
|
||||
static int direct_begin(const touch_event *e) {
|
||||
if (tc.navigation_mode) return 0;
|
||||
int target=dm_tc_hit(&tc.layout,e->x,e->y), kind=0; uint64_t key=0;
|
||||
if (target>=DM_TC_MAIN && target<=DM_TC_SKILL4) {
|
||||
dm_tg_snapshot snapshot; dm_touch_game_snapshot(&snapshot);
|
||||
dm_ta_glyph g=dm_ta_current_set(&snapshot,tc.layout.target[target].button,now_ns(),tc.skill_set);
|
||||
if (g.status==DM_TA_EMPTY) { kind=1; key=tc.layout.target[target].button|(tc.skill_set?DM_BTN_ZL:0); }
|
||||
}
|
||||
if (!kind && target==DM_TC_MAP) kind=2;
|
||||
float r[4];
|
||||
if (!kind && target<0 && dm_ui_minimap_rect(r)) {
|
||||
float h=(r[3]-r[1])*height, band=h/4;
|
||||
if (band<30) band=fminf(30,h*.4f);
|
||||
if (e->x>=r[0]*width && e->x<=r[2]*width && e->y>=r[1]*height && e->y<=r[1]*height+band) kind=2;
|
||||
}
|
||||
if (!kind && target<0 && dm_ui_map_is_full() && !(e->x<tc.layout.joy_zone_r && e->y>=tc.layout.joy_zone_t)) kind=3;
|
||||
if (!kind) return 0;
|
||||
direct[e->slot]=(direct_gesture){kind,e->x,e->y,e->time,key}; return 1;
|
||||
}
|
||||
static int direct_event(const touch_event *e) {
|
||||
direct_gesture *g=&direct[e->slot]; if (!g->kind) return 0;
|
||||
if (hypotf(e->x-g->x,e->y-g->y)>14) g->kind=-1;
|
||||
if (e->phase==2) {
|
||||
if (!tc.navigation_mode && g->kind>0 && e->time-g->time<.6) {
|
||||
if (g->kind==1) dm_ui_bind_begin(g->key);
|
||||
else if (dm_ui_map_is_full()) dm_ui_map_full(0);
|
||||
else if (g->kind==2) { map_world_seq=dm_world_tap(e->x/width,e->y/height); map_world_pending=1; }
|
||||
}
|
||||
memset(g,0,sizeof *g);
|
||||
} else if (e->phase==3) memset(g,0,sizeof *g);
|
||||
return 1;
|
||||
}
|
||||
static void point_tick(double now) {
|
||||
if (tc.navigation_mode && !dm_ui_bind_active() && tc.pointer_slot>=0) {
|
||||
dm_tc_finger *f=&tc.finger[tc.pointer_slot]; float nx=0,ny=0;
|
||||
int hit=dm_ui_bind_skill_hit(&nx,&ny); uint32_t id=dm_ui_hit_id();
|
||||
if (f->active && !f->pointer_dragged && !f->ui_drag && now-f->start_time_s>=.5 && hypotf(f->x-f->aim_origin_x,f->y-f->aim_origin_y)<=10*dm_tc_scale_for_size(width,height)) {
|
||||
if (hit==2 && id>=1 && id<=4) {
|
||||
if (!f->pointer_long) { f->pointer_long=1; stat_next=now; selected_point=id; tc.pointer_valid=1; tc.pointer_x=nx*width; tc.pointer_y=ny*height; }
|
||||
if (now>=stat_next) { stat_next=now+.15; dm_stat_add((int)id-1,1); }
|
||||
} else if (hit==1 && !f->pointer_long) dm_tc_pointer_press(&tc,nx*width,ny*height,DM_BTN_Y);
|
||||
}
|
||||
}
|
||||
if (skill_add_at>0 && now>=skill_add_at) {
|
||||
dm_points_info points; dm_points_get(&points);
|
||||
if (points.tree_open && points.sel_skill>=0 && !dm_cursor_pending()) {
|
||||
skill_add_at=0;
|
||||
if (points.sel_block==0 || points.sel_block==5) dm_skill_add_selected();
|
||||
} else if (now>skill_add_at+1 || !points.tree_open) skill_add_at=0;
|
||||
}
|
||||
}
|
||||
void dm_android_touch_step(uint64_t guest_now, uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry) {
|
||||
(void)guest_now;
|
||||
pthread_mutex_lock(&lock);
|
||||
init_locked();
|
||||
int next_swap = dm_custom_get("touch_swap_above");
|
||||
if (next_swap != swap_above) { swap_above = next_swap; resizing = cancel = 1; }
|
||||
if (cancel) { cancel_locked(); cancel = 0; }
|
||||
if (resizing) {
|
||||
dm_tc_set_tall_scale(tablet_layout); dm_tc_set_swap_above(swap_above);
|
||||
dm_tc_set_safe_insets(safe_left,safe_right); dm_tc_set_edge_bottom(safe_bottom); dm_tc_set_safe_bottom(safe_bottom);
|
||||
dm_ui_safe_left((int)lroundf(safe_left * 2160 / height));
|
||||
dm_ui_safe_right((int)lroundf(safe_right * 2160 / height));
|
||||
dm_tc_resize(&tc,width,height); resizing = 0;
|
||||
}
|
||||
if (!focused) { pthread_mutex_unlock(&lock); return; }
|
||||
sync_host();
|
||||
if (map_world_pending) {
|
||||
int result=dm_world_tap_result(map_world_seq);
|
||||
if (result>=0) { map_world_pending=0; if (!result && !tc.navigation_mode) dm_ui_map_full(1); }
|
||||
}
|
||||
/* 本次取手柄前排队的触点整批在这里套用:按下与抬起落在同一批(点得比游戏两次取手柄的间隔还短、或游戏卡住没取输入)时,状态机算出的键在批末已经松开,
|
||||
游戏一次也看不到——iOS 由前端异步调 dm_input_set,按下沿进 hle_hid.c 的 g_press_latch 锁存,这里同样:批内任何时刻按着过的键这次一并给出,下一次照实际值。
|
||||
The touches queued before this controller read are applied here as one batch: when press and release land in the same batch (a tap shorter than the
|
||||
interval between two reads, or the game stalling its input reads), the state machine's key is already up at the end of the batch and the game never
|
||||
sees it. On iOS the front end calls dm_input_set asynchronously and the press edge is latched in hle_hid.c g_press_latch; likewise here, keys held at
|
||||
any point in the batch are delivered with this read, and the next read reports the actual state. */
|
||||
/* 批内锁存按手指归属;滑出取消只撤销该手指,保留其他手指的快按。
|
||||
Attribute batch latches to each finger; slide cancellation revokes only that finger's quick tap. */
|
||||
uint64_t latched[DM_TC_MAX_TOUCH] = {0};
|
||||
while (head != tail) {
|
||||
touch_event e = queue[head++ % 256];
|
||||
if (frontend) { fe_event_locked(&e); continue; }
|
||||
if (direct_event(&e) || (e.phase==0 && direct_begin(&e))) continue;
|
||||
dm_tc_finger *f = &tc.finger[e.slot];
|
||||
uint64_t before_buttons = tc.buttons;
|
||||
int before_target = f->target;
|
||||
int event_cancelled = 0;
|
||||
if (e.phase == 0) latched[e.slot] = 0;
|
||||
if (e.phase == 0) {
|
||||
if (dm_tc_belt_outside(&tc,e.x,e.y)) { dm_belt_expand(0); continue; }
|
||||
dm_tc_begin_at(&tc,e.slot,e.x,e.y,e.time);
|
||||
if (!tc.navigation_mode && f->target == DM_TC_PORTAL) { dm_tc_cancel_finger(&tc,e.slot); dm_tp_request(); }
|
||||
if (tc.navigation_mode && tc.pointer_slot == e.slot) dm_tc_pointer_item(&tc,dm_ui_item_at_now(e.x/width,e.y/height));
|
||||
} else if (e.phase == 1 || e.phase == 2) {
|
||||
dm_tc_move_at(&tc,e.slot,e.x,e.y,e.time);
|
||||
event_cancelled = f->aim_cancelled;
|
||||
if (tc.navigation_mode && tc.pointer_slot == e.slot && f->ui_drag) {
|
||||
if (!ui_drag) {
|
||||
ui_drag = 1; dm_ui_drag_lift(DM_TC_POINTER_LIFT_PT*dm_tc_scale_for_size(width,height)/height);
|
||||
dm_ui_drag_begin(f->ui_drag,f->aim_origin_x/width,f->aim_origin_y/height,44/height);
|
||||
}
|
||||
dm_ui_drag_move(e.x/width,e.y/height);
|
||||
}
|
||||
if (e.phase == 2) {
|
||||
tc.tap_button=0; tc.tap_move=0;
|
||||
if (tc.navigation_mode) {
|
||||
float nx,ny;
|
||||
int hit=dm_ui_bind_skill_hit(&nx,&ny);
|
||||
if (!hit) selected_point=0;
|
||||
else {
|
||||
tc.tap_x=nx*width; tc.tap_y=ny*height;
|
||||
if (hit==1 && dm_ui_bind_active()==2) tc.tap_button=DM_BTN_Y;
|
||||
else if (!dm_ui_bind_active()) tc.tap_move=1;
|
||||
}
|
||||
}
|
||||
if (tc.navigation_mode && tc.pointer_slot == e.slot && (f->pointer_dragged || f->shop_drag)) release_pointer(f);
|
||||
if (ui_drag && tc.pointer_slot == e.slot) { dm_ui_drag_end(); ui_drag = 0; }
|
||||
unsigned moved=tc.tap_move_seq;
|
||||
dm_tc_end_at(&tc,e.slot,e.time);
|
||||
if (moved!=tc.tap_move_seq) {
|
||||
uint32_t id=dm_ui_hit_id();
|
||||
if (id && id==selected_point) {
|
||||
if (id<=4) dm_stat_add((int)id-1,1);
|
||||
else skill_add_at=e.time+.3;
|
||||
} else selected_point=id;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
/* 系统取消物品拖动时回原位,不当作丢弃/购买。 | System cancellation returns dragged items; it never buys or discards. */
|
||||
if (tc.pointer_slot == e.slot && f->pointer_dragged && !f->shop_drag) {
|
||||
dm_tc_pointer_release(&tc,0); dm_tc_end_at(&tc,e.slot,e.time);
|
||||
} else dm_tc_cancel_finger(&tc,e.slot);
|
||||
if (ui_drag) { dm_ui_drag_end(); ui_drag = 0; }
|
||||
}
|
||||
int target = e.phase == 2 ? before_target : f->target;
|
||||
if (e.phase == 3 || event_cancelled || f->aim_cancelled) latched[e.slot] = 0;
|
||||
else {
|
||||
latched[e.slot] |= tc.buttons & ~before_buttons;
|
||||
if (target >= 0 && target < DM_TC_COUNT)
|
||||
latched[e.slot] |= tc.buttons & (tc.layout.target[target].button | (tc.skill_set ? DM_BTN_ZL : 0));
|
||||
}
|
||||
requests();
|
||||
}
|
||||
double now = now_ns()/1e9;
|
||||
/* 当期iOS:游戏内按住技能连续施放;换绑从技能树长按进入。
|
||||
Current iOS: holding a gameplay skill keeps casting; rebinding starts by holding an icon in the skill tree. */
|
||||
point_tick(now);
|
||||
dm_tc_tick(&tc,now); requests();
|
||||
uint64_t sample = dm_input_samples();
|
||||
if (tc.pulse_button && pulse_epoch != tc.pulse_epoch) {
|
||||
pulse_epoch = tc.pulse_epoch; pulse_sample = sample; pulse_hold_start = 0;
|
||||
}
|
||||
if (tc.pulse_button && !dm_cursor_pending()) {
|
||||
if (!pulse_hold_start) pulse_hold_start = now;
|
||||
if (sample - pulse_sample >= 4 && now - pulse_hold_start >= tc.pulse_hold_s) {
|
||||
dm_tc_pulse_end(&tc,pulse_epoch); resume_sample = sample + 2;
|
||||
}
|
||||
}
|
||||
if (!tc.pulse_button && dm_tc_pulse_pending(&tc) && resume_sample && sample >= resume_sample) { dm_tc_pulse_resume(&tc); resume_sample = 0; }
|
||||
if (tc.pointer_valid) dm_cursor_set_screen(tc.pointer_x,tc.pointer_y,width,height); else dm_cursor_clear();
|
||||
int active = 0; for (int i=0;i<DM_TC_MAX_TOUCH;++i) active |= tc.finger[i].active;
|
||||
dm_ui_hand_idle(!active && !tc.pulse_button && !dm_tc_pulse_pending(&tc) && !dm_cursor_pending() && !dm_ui_touch_active());
|
||||
*buttons |= tc.buttons;
|
||||
for (int i=0;i<DM_TC_MAX_TOUCH;++i) *buttons |= latched[i];
|
||||
if (!*lx && !*ly) { *lx = tc.lx; *ly = tc.ly; }
|
||||
if (!*rx && !*ry) { *rx = tc.rx; *ry = tc.ry; }
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
void dm_android_touch_layout(float out[DM_ANDROID_TOUCH_DRAW_FLOATS]) {
|
||||
pthread_mutex_lock(&lock); init_locked();
|
||||
memset(out,0,sizeof(float)*DM_ANDROID_TOUCH_DRAW_FLOATS);
|
||||
out[0]=tc.layout.width; out[1]=tc.layout.height; out[2]=tc.navigation_mode; out[3]=tc.skill_set;
|
||||
for (int i=0;i<23;++i) {
|
||||
float *p = out+4+i*5;
|
||||
dm_tc_target t = i<DM_TC_COUNT ? tc.layout.target[i] : i==13 ? tc.layout.swap : i>=15 ? tc.layout.pick[i-15] : tc.layout.diff;
|
||||
if (i==12) {
|
||||
p[0]=tc.joy_slot>=0?tc.joy_origin_x:tc.layout.joy_x; p[1]=tc.joy_slot>=0?tc.joy_origin_y:tc.layout.joy_y;
|
||||
p[2]=tc.layout.joy_radius; p[3]=!tc.navigation_mode; p[4]=tc.joy_slot>=0;
|
||||
} else {
|
||||
p[0]=t.x; p[1]=t.y; p[2]=t.r;
|
||||
p[3]=i<DM_TC_COUNT?!!(tc.enabled_targets&(1u<<i)):!tc.navigation_mode && (i<15 || tc.diff_open);
|
||||
/* 快照包含松手后仍在发出的脉冲;查询只读,probe和onDraw连续读取不能消费高亮。
|
||||
Include pulses that remain active after release; reads are non-consuming so probe/onDraw see the same highlight. */
|
||||
p[4]=t.button && (tc.buttons&t.button)==t.button;
|
||||
for (int j=0;j<DM_TC_MAX_TOUCH;++j) {
|
||||
const dm_tc_finger *f=&tc.finger[j];
|
||||
if (!f->active || f->aim_cancelled) continue;
|
||||
if ((i<DM_TC_COUNT && f->target==i) || (i==13 && f->target==DM_TC_SWAP)) p[4]=1;
|
||||
/* 难度格与腰带消费共用负target;还要命中当前圆,不能把所有选项一起点亮。
|
||||
Difficulty and consumed belt touches share a negative target; hit-test this circle rather than lighting every choice. */
|
||||
if (i>=14 && f->target==DM_TC_DIFF && hypotf(f->x-t.x,f->y-t.y)<=t.r) p[4]=1;
|
||||
}
|
||||
}
|
||||
if (frontend) p[3]=0; /* 前端页面不画控件(见 frontend) | No controls drawn on front-end pages (see frontend) */
|
||||
}
|
||||
dm_tg_snapshot native; dm_touch_game_snapshot(&native);
|
||||
for (int i=0;i<6;++i) {
|
||||
float *p=out+DM_ANDROID_TOUCH_GLYPHS+i*8;
|
||||
dm_ta_glyph g=i==5 ? dm_ta_skill(359) : dm_ta_current_set(&native,tc.layout.target[i].button,now_ns(),tc.skill_set);
|
||||
dm_ta_frame frame;
|
||||
p[0]=g.status; p[1]=g.atlas;
|
||||
int held=out[4+i*5+4]!=0;
|
||||
if (g.status==DM_TA_GLYPH && dm_ta_frame_at(g.atlas,held?g.pressed_frame:g.normal_frame,&frame)) {
|
||||
p[2]=frame.x; p[3]=frame.y; p[4]=frame.width; p[5]=frame.height;
|
||||
if (g.slot>=0) { int charges=0; p[6]=dm_swapskill_slot(g.slot,&charges); p[7]=charges; }
|
||||
}
|
||||
}
|
||||
dm_hud_info h; dm_hud_get(&h);
|
||||
float *hud=out+DM_ANDROID_TOUCH_HUD;
|
||||
hud[0]=!frontend && dm_hud_bar_visible(&h,tc.navigation_mode && !dm_tc_scene_dialog_only(&scene),hud_blocked>0);
|
||||
hud[1]=h.level; hud[2]=h.exp_permille;
|
||||
for (int i=0;i<4;++i) hud[3+i]=h.belt[i];
|
||||
hud[7]=h.players; hud[8]=h.hp; hud[9]=h.hp_max; hud[10]=h.mp; hud[11]=h.mp_max;
|
||||
hud[12]=h.points; hud[13]=h.quest_unread; hud[14]=h.dead; hud[15]=tc.map_cancel_active;
|
||||
hud[16]=tc.lx; hud[17]=tc.ly; /* 摇杆推量(−32767..32767),画摇杆头用,同 iOS DmTouchOverlay | stick deflection (−32767..32767) for drawing the thumb, as iOS DmTouchOverlay */
|
||||
pthread_mutex_unlock(&lock);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/* UI线程仅排队;step必须挂在dm_pad_hook游戏采样线程。 | UI only queues; step must run on the guest sampling thread through dm_pad_hook. */
|
||||
void dm_android_touch_resize(float width_dp, float height_dp, float left_dp, float right_dp, float bottom_dp);
|
||||
void dm_android_touch_tablet(int tablet);
|
||||
/* phase: 0 down, 1 move, 2 up, 3 cancel; slot: stable 0..15; coordinates in dp. | 阶段:按下/移动/抬起/取消;槽固定0..15;坐标dp。 */
|
||||
void dm_android_touch_event(int phase, int slot, float x, float y);
|
||||
void dm_android_touch_focus(int active);
|
||||
void dm_android_touch_uimsg(const char *cat, const char *act, const char *arg);
|
||||
void dm_android_touch_step(uint64_t guest_now, uint64_t *buttons, int32_t *lx, int32_t *ly, int32_t *rx, int32_t *ry);
|
||||
/* 绘图快照:header[width,height,navigation,skill_set],23个[x,y,r,enabled,pressed];12键、摇杆、换组、难度及8选择格。 | Drawing snapshot: header followed by 23 records (12 keys, stick, set switch, difficulty, 8 choices). */
|
||||
/* 后接六个技能图标记录(状态、图集、裁切矩形、副手/充能、次数)和16个HUD数值。
|
||||
Append six icon records (status, atlas, crop, secondary/charge flags, charges) and 16 HUD values. */
|
||||
enum { DM_ANDROID_TOUCH_GLYPHS = 4 + 23 * 5, DM_ANDROID_TOUCH_HUD = DM_ANDROID_TOUCH_GLYPHS + 6 * 8,
|
||||
DM_ANDROID_TOUCH_DRAW_FLOATS = DM_ANDROID_TOUCH_HUD + 18 };
|
||||
void dm_android_touch_layout(float out[DM_ANDROID_TOUCH_DRAW_FLOATS]);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
#include <jni.h>
|
||||
#include "touch_android.h"
|
||||
|
||||
/* 使用命名JNI入口,与宿主已有JNI_OnLoad兼容。 | Named JNI entry points coexist with the host's JNI_OnLoad. */
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_TouchOverlay_nativeEvent(JNIEnv *env, jclass cls, jint phase, jint slot, jfloat x, jfloat y) {
|
||||
(void)env; (void)cls;
|
||||
dm_android_touch_event(phase,slot,x,y);
|
||||
}
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_TouchOverlay_nativeResize(JNIEnv *env, jclass cls, jfloat width, jfloat height, jfloat left, jfloat right, jfloat bottom, jboolean tablet) {
|
||||
(void)env; (void)cls;
|
||||
dm_android_touch_tablet(tablet);
|
||||
dm_android_touch_resize(width,height,left,right,bottom);
|
||||
}
|
||||
JNIEXPORT void JNICALL Java_com_xiaoboluo_d2r_TouchOverlay_nativeLayout(JNIEnv *env, jclass cls, jfloatArray dst) {
|
||||
(void)cls;
|
||||
if (!dst || (*env)->GetArrayLength(env,dst)<DM_ANDROID_TOUCH_DRAW_FLOATS) return;
|
||||
float data[DM_ANDROID_TOUCH_DRAW_FLOATS];
|
||||
dm_android_touch_layout(data);
|
||||
(*env)->SetFloatArrayRegion(env,dst,0,DM_ANDROID_TOUCH_DRAW_FLOATS,data);
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
// 安卓Vulkan呈现与窗口生命周期;依据原WSI桥及PR9/10的可回退呈现/钉核实验。
|
||||
// Android Vulkan presentation and window lifetimes, based on the original WSI bridge and reversible PR9/10 overlap/affinity experiments.
|
||||
#define VK_USE_PLATFORM_ANDROID_KHR
|
||||
#include "vulkan_present.h"
|
||||
#include "../gfx/vulkan/nvn_vk.h"
|
||||
#include "../gfx/xtrace.h"
|
||||
#include <android/log.h>
|
||||
#include <android/native_window.h>
|
||||
#include <dlfcn.h>
|
||||
#include <algorithm>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <mutex>
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <cerrno>
|
||||
#include <sched.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
extern "C" double dm_present_period(void);
|
||||
// 错过上屏节拍的帧数(晚于「上次期望时刻 + 周期」2 ms 以上);自适应出图档按它降档 / 试升
|
||||
// Frames that missed their display slot (more than 2 ms later than "previous desired time + period"); the adaptive present tier steps down / probes up by it
|
||||
static std::atomic<uint64_t> dm_present_late{0};
|
||||
extern "C" uint64_t dm_present_late_count(void){return dm_present_late.load(std::memory_order_relaxed);}
|
||||
namespace {
|
||||
std::mutex window_mutex;std::condition_variable window_cv;
|
||||
// Vulkan状态仅宿主线程使用;UI锁只保护窗口快照,不跨GPU等待。
|
||||
// Serialize Vulkan callers separately; never hold the UI window lock across GPU waits.
|
||||
std::mutex render_mutex;
|
||||
ANativeWindow *desired=nullptr,*active=nullptr;uint64_t generation=0,active_generation=0;
|
||||
VkInstance instance;VkPhysicalDevice physical;VkDevice device;VkQueue queue;uint32_t family;
|
||||
VkSurfaceKHR surface;VkSwapchainKHR swapchain;VkFormat swap_format;VkExtent2D extent;
|
||||
VkSurfaceTransformFlagBitsKHR created_transform;VkExtent2D created_surface_extent;
|
||||
// 无旋转 blit 由系统合成器旋转;记录属性以免 SUBOPTIMAL 触发逐帧重建。
|
||||
// The compositor rotates our unrotated blit; cache properties to avoid rebuilding every SUBOPTIMAL frame.
|
||||
bool surface_properties_changed(){
|
||||
VkSurfaceCapabilitiesKHR c{};
|
||||
if(vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical,surface,&c)!=VK_SUCCESS)return true;
|
||||
return c.currentTransform!=created_transform || c.currentExtent.width!=created_surface_extent.width || c.currentExtent.height!=created_surface_extent.height;
|
||||
}
|
||||
std::vector<VkImage> images;VkCommandPool command_pool;VkCommandBuffer command;
|
||||
VkSemaphore acquired;std::vector<VkSemaphore> finished;VkFence fence;bool ready=false,swap_dirty=false;std::string shader_path;
|
||||
// 缺省开启(标记文件 gfx-present-overlap 为 '0' 时关):最多两次呈现 blit 在途,不在每帧后清空队列,游戏可在 GPU 收尾本帧时翻译下一帧。
|
||||
// On by default (marker file gfx-present-overlap = '0' turns it off): keep up to two present blits in flight instead of draining the queue
|
||||
// after every frame, so the game translates the next frame while the GPU finishes this one. Each in-flight frame has
|
||||
// its own pool, acquire semaphore and fence; slot 0 is the original set. Later engine barriers on the source image are
|
||||
// ALL_COMMANDS and its release retires with a later submission, which covers this blit in queue order.
|
||||
bool overlap=false;VkCommandPool overlap_pool;VkCommandBuffer overlap_command;VkSemaphore overlap_acquired;VkFence overlap_fence;
|
||||
bool in_flight[2];unsigned flight=0;
|
||||
// Diagnostic (marker gfx-present-timing; overlap mode): GPU time of each present's clear and blit, from two timestamps per
|
||||
// in-flight frame, read once that frame's fence has signalled; averaged over 300 presents.
|
||||
bool present_timing=false;VkQueryPool present_queries=VK_NULL_HANDLE;bool present_stamped[2];double present_tick_ns=1,present_gpu_ns=0;unsigned present_timed=0;
|
||||
// 游戏线程(调用呈现的线程;同步翻译时也是翻译线程)钉在最高频的核上。Redmi K50 Ultra 上调度器一直把它放在 A710
|
||||
// (cpu4–6,MIUI 封顶 2.57 GHz),从不用空着的 X2(cpu7,封顶 2.25 GHz);钉到 X2 后营地在 3D 比例 0.6 下从 40.2 升到
|
||||
// 44.3 fps(同进程 A/B,CPU 17.1 → 14.3 ms)。MIUI 会改线程的可用核掩码,所以每 120 次呈现核对一次。
|
||||
// 标记 gfx-no-pin 关闭,gfx-pin-cpu = 十六进制掩码 指定核;gfx-ab-toggle = N 加 gfx-ab-target = pin 时每 N 秒钉 / 放开交替。
|
||||
// The game thread (the caller of present, which also translates in sync mode) runs on the cores with the highest maximum
|
||||
// frequency. On the Redmi K50 Ultra the scheduler kept it on the A710 cores (cpu4-6, capped at 2.57 GHz by MIUI) and never
|
||||
// used the idle X2 (cpu7, capped at 2.25 GHz); pinned to the X2 the camp went from 40.2 to 44.3 fps at 3D scale 0.6
|
||||
// (in-process A/B, CPU 17.1 -> 14.3 ms). MIUI rewrites thread affinity masks, so the pin is checked every 120 presents.
|
||||
// Marker gfx-no-pin turns it off and gfx-pin-cpu = hex mask picks the cores; gfx-ab-toggle = N with gfx-ab-target = pin
|
||||
// alternates pinned and released every N seconds, in phase with the engine's A/B (its PERF lines carry ab=).
|
||||
unsigned pin_mask=0;int pin_ab=0;int pin_state=-1;unsigned pin_presents=0,pin_drifts=0,pin_failures=0;cpu_set_t pin_original;bool pin_have_original=false;
|
||||
unsigned fastest_cores(){
|
||||
unsigned best=0,mask=0,present=0;
|
||||
for(int c=0;c<32;c++){char path[96];snprintf(path,sizeof path,"/sys/devices/system/cpu/cpu%d/cpufreq/cpuinfo_max_freq",c);FILE *f=fopen(path,"rb");if(!f)continue;
|
||||
unsigned v=0;if(fscanf(f,"%u",&v)==1 && v){present|=1u<<c;if(v>best){best=v;mask=0;}if(v==best)mask|=1u<<c;}fclose(f);}
|
||||
return mask==present?0:mask; // one core class: nothing to pick
|
||||
}
|
||||
void pin_update(){
|
||||
if(!pin_mask)return;bool want=true;
|
||||
if(pin_ab>0){timespec ts;clock_gettime(CLOCK_MONOTONIC,&ts);want=((ts.tv_sec/pin_ab)&1)==0;}
|
||||
bool changed=int(want)!=pin_state;if(!changed && ++pin_presents%120)return;
|
||||
if(!pin_have_original){CPU_ZERO(&pin_original);if(sched_getaffinity(0,sizeof pin_original,&pin_original))for(int c=0;c<32;c++)CPU_SET(c,&pin_original);pin_have_original=true;}
|
||||
cpu_set_t set;CPU_ZERO(&set);if(want){for(int c=0;c<32;c++)if(pin_mask>>c&1)CPU_SET(c,&set);}else set=pin_original;
|
||||
if(!changed){cpu_set_t cur;CPU_ZERO(&cur);if(!sched_getaffinity(0,sizeof cur,&cur) && CPU_EQUAL(&cur,&set))return;++pin_drifts;}
|
||||
int r=sched_setaffinity(0,sizeof set,&set),err=r?errno:0;pin_state=want;if(r)++pin_failures;
|
||||
// Refused while the app's cpuset lacks the cores (Android moves the app between cpusets, at start for one): the kernel
|
||||
// keeps the request and applies it again when the cpuset allows, and the next check retries.
|
||||
if(changed || pin_drifts<=4 || (r && pin_failures<=4))__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","NVN pin tid=%d %s mask=%x result=%d errno=%d drifts=%u failures=%u",int(gettid()),want?"pinned":"released",want?pin_mask:0u,r,err,pin_drifts,pin_failures);
|
||||
}
|
||||
void log_message(void*,const char *text){__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","%s",text);}
|
||||
[[noreturn]] void fatal(void*,const char *text){__android_log_print(ANDROID_LOG_FATAL,"dm-vulkan","%s",text);abort();}
|
||||
void destroy_present_semaphores(){for(auto s:finished)if(s)vkDestroySemaphore(device,s,nullptr);finished.clear();}
|
||||
// 调用者先等队列空闲;基础WSI销毁仍沿用WaitIdle惯例,不声称提供呈现栅栏保证。
|
||||
// Call only after queue idle. Base WSI teardown follows the WaitIdle convention,
|
||||
// which is not the explicit presentation-fence guarantee of swapchain_maintenance1.
|
||||
void destroy_swap(){destroy_present_semaphores();if(swapchain)vkDestroySwapchainKHR(device,swapchain,nullptr);swapchain=VK_NULL_HANDLE;images.clear();if(surface)vkDestroySurfaceKHR(instance,surface,nullptr);surface=VK_NULL_HANDLE;if(active)ANativeWindow_release(active);active=nullptr;}
|
||||
void cleanup_initialization(){
|
||||
if(queue)vkQueueWaitIdle(queue);
|
||||
if(device){if(fence)vkDestroyFence(device,fence,nullptr);if(acquired)vkDestroySemaphore(device,acquired,nullptr);if(command_pool)vkDestroyCommandPool(device,command_pool,nullptr);}
|
||||
fence=VK_NULL_HANDLE;acquired=VK_NULL_HANDLE;command_pool=VK_NULL_HANDLE;command=VK_NULL_HANDLE;
|
||||
if(device){if(overlap_fence)vkDestroyFence(device,overlap_fence,nullptr);if(overlap_acquired)vkDestroySemaphore(device,overlap_acquired,nullptr);if(overlap_pool)vkDestroyCommandPool(device,overlap_pool,nullptr);}
|
||||
overlap_fence=VK_NULL_HANDLE;overlap_acquired=VK_NULL_HANDLE;overlap_pool=VK_NULL_HANDLE;overlap_command=VK_NULL_HANDLE;overlap=false;in_flight[0]=in_flight[1]=false;flight=0;
|
||||
destroy_swap();if(device)vkDestroyDevice(device,nullptr);device=VK_NULL_HANDLE;queue=VK_NULL_HANDLE;
|
||||
if(instance)vkDestroyInstance(instance,nullptr);instance=VK_NULL_HANDLE;physical=VK_NULL_HANDLE;
|
||||
}
|
||||
// 刷新率投票:App 不投票时,安卓(MIUI)让这个表面跑 60 Hz,尽管屏和系统设置都允许 120。投 120 Hz 不改 60 帧的出图节奏(nvn_pace_hz),
|
||||
// 但赶不上 16.7 ms 的那一帧在屏上停 25 ms 而不是 33.3 ms。标记 gfx-frame-rate = N(Hz;0 = 不投票)。
|
||||
// Frame-rate vote: without a vote from the app, Android (MIUI) runs this surface at 60 Hz although the panel and the system
|
||||
// setting allow 120. A 120 Hz vote keeps the 60 fps present pacing (nvn_pace_hz), but a frame that misses 16.7 ms stays on
|
||||
// screen for 25 ms instead of 33.3. Marker gfx-frame-rate = N (Hz; 0 = no vote).
|
||||
float frame_rate_vote=120;
|
||||
// 按游戏输出尺寸出图:窗口缓冲设成游戏输出的尺寸(2000×900),由显示硬件放大到屏幕,呈现端只做 1:1 拷贝,不再每帧清屏、
|
||||
// 用 GPU 按最近邻放大到 2712×1220。分辨率不变,最后一步放大从 GPU 移到显示控制器(滤波也更平滑)。标记 gfx-present-native = 0 关。
|
||||
// Present at the game's output size: the window's buffers take the game's output size (2000x900) and the display hardware
|
||||
// scales them to the screen, so the presenter copies 1:1 instead of clearing and nearest-scaling to 2712x1220 on the GPU
|
||||
// every frame. Same resolution; the final upscale moves from the GPU to the display controller (with smoother filtering).
|
||||
// Marker gfx-present-native = 0 turns it off.
|
||||
#ifdef __OHOS__
|
||||
bool present_native=false; // 鸿蒙:缓冲尺寸与合成缩放未在真机核过,先关;标记 gfx-present-native = 1 打开 | HarmonyOS: buffer geometry vs compositor scaling not yet checked on device; off, marker gfx-present-native = 1 enables
|
||||
#else
|
||||
bool present_native=true;
|
||||
#endif
|
||||
int native_w=0,native_h=0;
|
||||
int create_surface(){
|
||||
destroy_swap();native_w=native_h=0;
|
||||
{std::lock_guard<std::mutex> lock(window_mutex);if(!desired)return VK_NOT_READY;active=desired;ANativeWindow_acquire(active);active_generation=generation;}
|
||||
if(frame_rate_vote>0){
|
||||
// 运行时查询API,系统拒绝投票不会中止Vulkan初始化。 | Resolve the API at runtime; a refused vote does not abort Vulkan initialization.
|
||||
static auto set_rate=[]{void *lib=dlopen("libnativewindow.so",RTLD_NOW);return reinterpret_cast<int32_t(*)(ANativeWindow*,float,int8_t)>(lib?dlsym(lib,"ANativeWindow_setFrameRate"):nullptr);}();
|
||||
int fr=set_rate?set_rate(active,frame_rate_vote,ANATIVEWINDOW_FRAME_RATE_COMPATIBILITY_DEFAULT):-1;
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Frame rate vote %.0f Hz result=%d (marker gfx-frame-rate; display request, not FPS)",double(frame_rate_vote),fr);
|
||||
}
|
||||
VkAndroidSurfaceCreateInfoKHR ci{VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR};ci.window=active;
|
||||
VkResult r=vkCreateAndroidSurfaceKHR(instance,&ci,nullptr,&surface);if(r)return r;
|
||||
if(!device)return 0;VkBool32 supported=VK_FALSE;r=vkGetPhysicalDeviceSurfaceSupportKHR(physical,family,surface,&supported);if(r||!supported)return r?r:VK_ERROR_FEATURE_NOT_PRESENT;return 0;
|
||||
}
|
||||
int create_swap(){
|
||||
VkSurfaceCapabilitiesKHR cap;VkResult r=vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physical,surface,&cap);if(r)return r;
|
||||
if(!(cap.supportedUsageFlags&VK_IMAGE_USAGE_TRANSFER_DST_BIT))return VK_ERROR_FORMAT_NOT_SUPPORTED;
|
||||
if(!(cap.supportedTransforms&VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR))return VK_ERROR_FEATURE_NOT_PRESENT;
|
||||
uint32_t n=0;r=vkGetPhysicalDeviceSurfaceFormatsKHR(physical,surface,&n,nullptr);if(r||!n)return r?r:VK_ERROR_FORMAT_NOT_SUPPORTED;
|
||||
std::vector<VkSurfaceFormatKHR> formats(n);r=vkGetPhysicalDeviceSurfaceFormatsKHR(physical,surface,&n,formats.data());if(r)return r;
|
||||
VkSurfaceFormatKHR sf=formats[0];if(sf.format==VK_FORMAT_UNDEFINED)sf.format=VK_FORMAT_R8G8B8A8_UNORM;
|
||||
for(auto f:formats)if(f.format==VK_FORMAT_R8G8B8A8_UNORM||f.format==VK_FORMAT_B8G8R8A8_UNORM){sf=f;break;}
|
||||
extent=cap.currentExtent;if(extent.width==UINT32_MAX){extent.width=std::clamp(uint32_t(std::max(1,ANativeWindow_getWidth(active))),cap.minImageExtent.width,cap.maxImageExtent.width);extent.height=std::clamp(uint32_t(std::max(1,ANativeWindow_getHeight(active))),cap.minImageExtent.height,cap.maxImageExtent.height);}if(!extent.width||!extent.height)return VK_NOT_READY;
|
||||
VkSwapchainCreateInfoKHR ci{VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR};ci.surface=surface;
|
||||
#ifdef __OHOS__
|
||||
{unsigned want=4;if(const char *e=getenv("DM_SWAP_IMAGES"))want=unsigned(std::max(2,atoi(e)));ci.minImageCount=std::max(want,cap.minImageCount);} // 马良最佳实践:重负载 3–4 张;按期望上屏时刻排帧时合成器手里多压一张,取 4 张免得翻译线程等交换链、反压到游戏帧节奏 | Maleoon best practice: 3–4 under heavy load; with desired display times the compositor holds one more buffer, so take 4 to keep the translation thread from waiting on the swapchain and back-pressuring the game cadence
|
||||
#else
|
||||
ci.minImageCount=std::max(2u,cap.minImageCount);
|
||||
#endif
|
||||
if(cap.maxImageCount)ci.minImageCount=std::min(ci.minImageCount,cap.maxImageCount);ci.imageFormat=sf.format;ci.imageColorSpace=sf.colorSpace;ci.imageExtent=extent;ci.imageArrayLayers=1;ci.imageUsage=VK_IMAGE_USAGE_TRANSFER_DST_BIT;ci.imageSharingMode=VK_SHARING_MODE_EXCLUSIVE;ci.preTransform=VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;ci.compositeAlpha=VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
|
||||
if(!(cap.supportedCompositeAlpha&ci.compositeAlpha))for(uint32_t b=1;b<=8;b<<=1)if(cap.supportedCompositeAlpha&b){ci.compositeAlpha=VkCompositeAlphaFlagBitsKHR(b);break;}
|
||||
ci.presentMode=VK_PRESENT_MODE_FIFO_KHR;ci.clipped=VK_TRUE;ci.oldSwapchain=swapchain;VkSwapchainKHR replacement=VK_NULL_HANDLE;r=vkCreateSwapchainKHR(device,&ci,nullptr,&replacement);
|
||||
// 创建失败也会退休oldSwapchain;重试不得继续传入退休句柄。
|
||||
// Even failed creation retires oldSwapchain; never pass that retired handle on retry.
|
||||
destroy_present_semaphores();if(swapchain)vkDestroySwapchainKHR(device,swapchain,nullptr);swapchain=r?VK_NULL_HANDLE:replacement;images.clear();if(r)return r;swap_format=sf.format;
|
||||
created_transform=cap.currentTransform;created_surface_extent=cap.currentExtent;
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Swapchain: window=%dx%d extent=%ux%u currentTransform=%u supported=%u selected=%u",ANativeWindow_getWidth(active),ANativeWindow_getHeight(active),extent.width,extent.height,unsigned(cap.currentTransform),unsigned(cap.supportedTransforms),unsigned(ci.preTransform));
|
||||
r=vkGetSwapchainImagesKHR(device,swapchain,&n,nullptr);if(r)return r;images.resize(n);r=vkGetSwapchainImagesKHR(device,swapchain,&n,images.data());if(r)return r;images.resize(n);
|
||||
// 呈现完成信号量按交换链图像分配;重新获取该图像后才能再次发信号。
|
||||
// Index present-wait semaphores by acquired image, not by CPU frame/fence.
|
||||
finished.resize(n,VK_NULL_HANDLE);VkSemaphoreCreateInfo sc{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};
|
||||
for(auto &s:finished){r=vkCreateSemaphore(device,&sc,nullptr,&s);if(r)return r;}return VK_SUCCESS;
|
||||
}
|
||||
// 诊断(标记 gfx-membench):每种主机可见内存类型的 CPU 写、CPU 读,以及 GPU 填充后的 CPU 读速度,启动时测一次。
|
||||
// Diagnostic (marker gfx-membench): CPU write, CPU read, and CPU read after a GPU fill, for each host-visible memory type; run once at start.
|
||||
void membench(){
|
||||
VkPhysicalDeviceMemoryProperties mp;vkGetPhysicalDeviceMemoryProperties(physical,&mp);
|
||||
const VkDeviceSize n=4u<<20;std::vector<uint8_t> host(n,1),back(n);
|
||||
VkCommandPoolCreateInfo cp{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};cp.flags=VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;cp.queueFamilyIndex=family;VkCommandPool pool;if(vkCreateCommandPool(device,&cp,nullptr,&pool))return;
|
||||
VkCommandBufferAllocateInfo ca{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};ca.commandPool=pool;ca.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY;ca.commandBufferCount=1;VkCommandBuffer cmd;if(vkAllocateCommandBuffers(device,&ca,&cmd)){vkDestroyCommandPool(device,pool,nullptr);return;}
|
||||
auto now=[]{timespec ts;clock_gettime(CLOCK_MONOTONIC,&ts);return double(ts.tv_sec)*1e9+double(ts.tv_nsec);};
|
||||
for(uint32_t t=0;t<mp.memoryTypeCount;t++){
|
||||
VkMemoryPropertyFlags f=mp.memoryTypes[t].propertyFlags;if(!(f&VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT))continue;
|
||||
VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};bi.size=n;bi.usage=VK_BUFFER_USAGE_TRANSFER_DST_BIT|VK_BUFFER_USAGE_TRANSFER_SRC_BIT|VK_BUFFER_USAGE_STORAGE_BUFFER_BIT;bi.sharingMode=VK_SHARING_MODE_EXCLUSIVE;VkBuffer b;if(vkCreateBuffer(device,&bi,nullptr,&b))continue;
|
||||
VkMemoryRequirements r;vkGetBufferMemoryRequirements(device,b,&r);if(!(r.memoryTypeBits&(1u<<t))){vkDestroyBuffer(device,b,nullptr);continue;}
|
||||
VkMemoryAllocateInfo ai{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};ai.allocationSize=r.size;ai.memoryTypeIndex=t;VkDeviceMemory m;if(vkAllocateMemory(device,&ai,nullptr,&m)){vkDestroyBuffer(device,b,nullptr);continue;}
|
||||
void *p=nullptr;if(vkBindBufferMemory(device,b,m,0)||vkMapMemory(device,m,0,VK_WHOLE_SIZE,0,&p)){vkFreeMemory(device,m,nullptr);vkDestroyBuffer(device,b,nullptr);continue;}
|
||||
bool coherent=(f&VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)!=0;VkMappedMemoryRange mr{VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE};mr.memory=m;mr.size=VK_WHOLE_SIZE;
|
||||
double w=1e30,rc=1e30,rd=1e30,flush=0,inv=0;bool ok=true;
|
||||
for(int k=0;k<4;k++){double t0=now();memcpy(p,host.data(),n);double t1=now();if(!coherent)vkFlushMappedMemoryRanges(device,1,&mr);double t2=now();w=std::min(w,t1-t0);flush=std::max(flush,t2-t1);}
|
||||
for(int k=0;k<4;k++){double t0=now();memcpy(back.data(),p,n);rc=std::min(rc,now()-t0);}
|
||||
for(int k=0;k<4;k++){
|
||||
vkResetCommandBuffer(cmd,0);VkCommandBufferBeginInfo cb{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};vkBeginCommandBuffer(cmd,&cb);
|
||||
uint32_t value=0x01020304u+uint32_t(k);vkCmdFillBuffer(cmd,b,0,n,value);
|
||||
VkMemoryBarrier mb{VK_STRUCTURE_TYPE_MEMORY_BARRIER};mb.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;mb.dstAccessMask=VK_ACCESS_HOST_READ_BIT;vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&mb,0,nullptr,0,nullptr);
|
||||
vkEndCommandBuffer(cmd);VkSubmitInfo si{VK_STRUCTURE_TYPE_SUBMIT_INFO};si.commandBufferCount=1;si.pCommandBuffers=&cmd;if(vkQueueSubmit(queue,1,&si,VK_NULL_HANDLE)||vkQueueWaitIdle(queue)){ok=false;break;}
|
||||
double t0=now();if(!coherent)vkInvalidateMappedMemoryRanges(device,1,&mr);double t1=now();memcpy(back.data(),p,n);double t2=now();
|
||||
rd=std::min(rd,t2-t1);inv=std::max(inv,t1-t0);uint32_t got;memcpy(&got,back.data()+n-4,4);ok=ok&&got==value;
|
||||
}
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","NVN membench type=%u flags=%#x write=%.2f GB/s (flush %.0f us) read=%.2f GB/s read_after_gpu=%.2f GB/s (invalidate %.0f us) ok=%d",
|
||||
t,unsigned(f),double(n)/w,flush/1e3,double(n)/rc,double(n)/rd,inv/1e3,int(ok));
|
||||
vkUnmapMemory(device,m);vkFreeMemory(device,m,nullptr);vkDestroyBuffer(device,b,nullptr);
|
||||
}
|
||||
vkDestroyCommandPool(device,pool,nullptr);
|
||||
}
|
||||
int has_window(void*){std::lock_guard<std::mutex> l(window_mutex);return desired!=nullptr;}
|
||||
void wait_window(){std::unique_lock<std::mutex> lock(window_mutex);window_cv.wait(lock,[]{return desired!=nullptr;});}
|
||||
bool window_changed(){std::lock_guard<std::mutex> lock(window_mutex);return !desired||generation!=active_generation;}
|
||||
void wait_window_change(uint64_t bad){std::unique_lock<std::mutex> lock(window_mutex);window_cv.wait(lock,[bad]{return generation!=bad;});}
|
||||
void wait_resize(){std::unique_lock<std::mutex> lock(window_mutex);window_cv.wait_for(lock,std::chrono::milliseconds(16),[]{return generation!=active_generation;});}
|
||||
int present(void*,void*,VkImage source,VkFormat source_format,uint32_t width,uint32_t height,const int32_t crop[4],int32_t){
|
||||
std::lock_guard<std::mutex> render_lock(render_mutex);
|
||||
pin_update();
|
||||
VkFormatProperties sp;vkGetPhysicalDeviceFormatProperties(physical,source_format,&sp);if(!(sp.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_SRC_BIT))return VK_ERROR_FORMAT_NOT_SUPPORTED;
|
||||
int x=0,y=0,w=int(width),h=int(height);if(crop&&crop[2]>0&&crop[3]>0){x=std::clamp(crop[0],0,w);y=std::clamp(crop[1],0,h);w=std::min(crop[2],int(width)-x);h=std::min(crop[3],int(height)-y);}if(w<=0||h<=0)return VK_ERROR_INITIALIZATION_FAILED;
|
||||
for(;;){
|
||||
if(present_native && surface && active && (native_w!=w || native_h!=h)){ // the next swapchain takes this size (currentExtent follows the buffer geometry)
|
||||
int g=ANativeWindow_setBuffersGeometry(active,w,h,0);native_w=w;native_h=h;swap_dirty=true;
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Present at the game's output size %dx%d result=%d (marker gfx-present-native)",w,h,g);}
|
||||
// 后台等待释放UI锁;保留同一源帧,恢复并真正呈现后才返回成功。
|
||||
// Suspend without the UI lock; keep this source frame until it is presented.
|
||||
wait_window();
|
||||
VkResult r;
|
||||
if(!surface||window_changed()){
|
||||
if((r=vkQueueWaitIdle(queue)))return r;
|
||||
r=VkResult(create_surface());
|
||||
if(r==VK_NOT_READY)continue;
|
||||
if(r==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
if(r)return r;swap_dirty=true;
|
||||
}
|
||||
if(swap_dirty){
|
||||
if((r=vkQueueWaitIdle(queue)))return r;
|
||||
r=VkResult(create_swap());
|
||||
if(r==VK_NOT_READY||r==VK_ERROR_OUT_OF_DATE_KHR){wait_resize();continue;}
|
||||
if(r==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
if(r)return r;swap_dirty=false;
|
||||
}
|
||||
VkFormatProperties dp;vkGetPhysicalDeviceFormatProperties(physical,swap_format,&dp);if(!(dp.optimalTilingFeatures&VK_FORMAT_FEATURE_BLIT_DST_BIT))return VK_ERROR_FORMAT_NOT_SUPPORTED;
|
||||
// 有限获取超时让渲染线程重新检查Surface代数,UI从不等待驱动。
|
||||
// A bounded acquire lets rendering observe lifecycle changes; UI never waits on the driver.
|
||||
unsigned f=overlap?flight:0;VkCommandPool pool=f?overlap_pool:command_pool;VkCommandBuffer cmd=f?overlap_command:command;VkSemaphore acq=f?overlap_acquired:acquired;VkFence done=f?overlap_fence:fence;
|
||||
if(in_flight[f]){XTRACE_BEGIN("dm-present-fence");r=vkWaitForFences(device,1,&done,VK_TRUE,10000000000ull);XTRACE_END();if(r)return r;if((r=vkResetFences(device,1,&done)))return r;in_flight[f]=false;
|
||||
if(present_stamped[f]){uint64_t t[2]{};if(vkGetQueryPoolResults(device,present_queries,f*2,2,sizeof t,t,8,VK_QUERY_RESULT_64_BIT)==VK_SUCCESS && t[1]>=t[0]){present_gpu_ns+=double(t[1]-t[0])*present_tick_ns;
|
||||
if(++present_timed==300){__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","NVN PERF present_gpu_us=%.0f extent=%ux%u (marker gfx-present-timing)",present_gpu_ns/present_timed/1e3,extent.width,extent.height);present_gpu_ns=0;present_timed=0;}}present_stamped[f]=false;}}
|
||||
uint32_t index=0;XTRACE_BEGIN("dm-acquire");r=vkAcquireNextImageKHR(device,swapchain,50000000ull,acq,VK_NULL_HANDLE,&index);XTRACE_END();
|
||||
if(r==VK_TIMEOUT||r==VK_NOT_READY)continue;
|
||||
if(r==VK_ERROR_OUT_OF_DATE_KHR){swap_dirty=true;wait_resize();continue;}
|
||||
if(r==VK_ERROR_SURFACE_LOST_KHR){if((r=vkQueueWaitIdle(queue)))return r;uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
bool rebuild=r==VK_SUBOPTIMAL_KHR;if(r!=VK_SUCCESS&&!rebuild)return r;
|
||||
r=vkResetCommandPool(device,pool,0);if(r)return r;VkCommandBufferBeginInfo bi{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};bi.flags=VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;if((r=vkBeginCommandBuffer(cmd,&bi)))return r;
|
||||
bool stamp=present_timing && overlap;if(stamp && !present_queries){VkQueryPoolCreateInfo q{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};q.queryType=VK_QUERY_TYPE_TIMESTAMP;q.queryCount=4;if(vkCreateQueryPool(device,&q,nullptr,&present_queries))stamp=false;
|
||||
VkPhysicalDeviceProperties pp;vkGetPhysicalDeviceProperties(physical,&pp);present_tick_ns=pp.limits.timestampPeriod;}
|
||||
if(stamp){vkCmdResetQueryPool(cmd,present_queries,f*2,2);vkCmdWriteTimestamp(cmd,VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,present_queries,f*2);}
|
||||
VkImageMemoryBarrier barrier{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};barrier.srcQueueFamilyIndex=barrier.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED;barrier.image=images[index];barrier.subresourceRange={VK_IMAGE_ASPECT_COLOR_BIT,0,1,0,1};barrier.oldLayout=VK_IMAGE_LAYOUT_UNDEFINED;barrier.newLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;barrier.dstAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;
|
||||
// 换布局须在获取信号量的等待阶段(下面提交的 TRANSFER)之后:源阶段写 TOP_OF_PIPE 时,换布局不等信号量,可能在呈现引擎
|
||||
// 读完这张图之前就发生(验证层同步检查:SYNC-HAZARD-WRITE-AFTER-READ)。
|
||||
// The layout transition must come after the acquire semaphore's wait stage (TRANSFER, in the submit below). With
|
||||
// TOP_OF_PIPE as the source stage it does not wait for the semaphore and can happen before the presentation engine has
|
||||
// finished reading the image (synchronization validation: SYNC-HAZARD-WRITE-AFTER-READ).
|
||||
vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,nullptr,0,nullptr,1,&barrier);
|
||||
double scale=std::min(double(extent.width)/w,double(extent.height)/h);int dw=std::max(1,int(w*scale)),dh=std::max(1,int(h*scale)),dx=(int(extent.width)-dw)/2,dy=(int(extent.height)-dh)/2;
|
||||
if(dx || dy || dw!=int(extent.width) || dh!=int(extent.height)){ // letterbox bars only where the blit leaves part of the image
|
||||
VkClearColorValue black{};vkCmdClearColorImage(cmd,images[index],VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,&black,1,&barrier.subresourceRange);
|
||||
barrier.oldLayout=barrier.newLayout;barrier.srcAccessMask=barrier.dstAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_TRANSFER_BIT,0,0,nullptr,0,nullptr,1,&barrier);}
|
||||
VkImageBlit blit{};blit.srcSubresource={VK_IMAGE_ASPECT_COLOR_BIT,0,0,1};blit.dstSubresource=blit.srcSubresource;blit.srcOffsets[0]={x,y,0};blit.srcOffsets[1]={x+w,y+h,1};blit.dstOffsets[0]={dx,dy,0};blit.dstOffsets[1]={dx+dw,dy+dh,1};
|
||||
// 最近邻不要求额外线性过滤能力。鸿蒙:游戏出图比屏幕小、要放大,格式支持时用线性,不然像素发硬、斜边锯齿。
|
||||
// Nearest needs no extra linear-filter support. HarmonyOS: the game image is smaller than the screen and gets upscaled; use linear when the format supports it, otherwise pixels look blocky and diagonals jagged.
|
||||
VkFilter filter=VK_FILTER_NEAREST;
|
||||
#ifdef __OHOS__
|
||||
if(sp.optimalTilingFeatures&VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT)filter=VK_FILTER_LINEAR;
|
||||
#endif
|
||||
vkCmdBlitImage(cmd,source,VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,images[index],VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,1,&blit,filter);
|
||||
// 同队列后续写入必须等源图读取完成;即使下一次图像布局未改变也建立 WAR 执行依赖。
|
||||
// Order subsequent same-queue writes after the source read, including reuse without a layout change.
|
||||
VkMemoryBarrier source_read{VK_STRUCTURE_TYPE_MEMORY_BARRIER};source_read.srcAccessMask=VK_ACCESS_TRANSFER_READ_BIT;source_read.dstAccessMask=VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT;
|
||||
vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,0,1,&source_read,0,nullptr,0,nullptr);
|
||||
barrier.oldLayout=VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL;barrier.newLayout=VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;barrier.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;barrier.dstAccessMask=0;vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,0,0,nullptr,0,nullptr,1,&barrier);
|
||||
if(stamp){vkCmdWriteTimestamp(cmd,VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT,present_queries,f*2+1);present_stamped[f]=true;}
|
||||
if((r=vkEndCommandBuffer(cmd)))return r;VkPipelineStageFlags stage=VK_PIPELINE_STAGE_TRANSFER_BIT;VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO};submit.waitSemaphoreCount=1;submit.pWaitSemaphores=&acq;submit.pWaitDstStageMask=&stage;submit.commandBufferCount=1;submit.pCommandBuffers=&cmd;submit.signalSemaphoreCount=1;submit.pSignalSemaphores=&finished[index];
|
||||
if((r=vkQueueSubmit(queue,1,&submit,done)))return r;in_flight[f]=true;VkPresentInfoKHR pi{VK_STRUCTURE_TYPE_PRESENT_INFO_KHR};pi.waitSemaphoreCount=1;pi.pWaitSemaphores=&finished[index];pi.swapchainCount=1;pi.pSwapchains=&swapchain;pi.pImageIndices=&index;
|
||||
#ifdef __OHOS__
|
||||
// 期望上屏时刻(鸿蒙 SET_DESIRED_PRESENT_TIMESTAMP):上屏节奏 = 上次期望时刻 + 一个出图档周期;早到的帧由合成器按时放出,翻译线程不等;
|
||||
// 落后时从当前时刻重新起拍。翻译完成时刻的抖动(±5 ms)不再让一帧在屏上停 3 或 5 个刷新。DM_PRESENT_TS=0 关。
|
||||
// Desired display time (HarmonyOS SET_DESIRED_PRESENT_TIMESTAMP): cadence = previous desired time + one present-tier period; an early frame is released on time by the compositor
|
||||
// without the translation thread waiting; when late, restart the cadence from now. Jitter in translation completion (±5 ms) no longer leaves a frame on screen for 3 or 5 refreshes.
|
||||
{static int on=-1;if(on<0){const char *e=getenv("DM_PRESENT_TS");on=!(e&&*e=='0');}static int64_t tgt;double per=dm_present_period();
|
||||
if(on&&per>0&&active){timespec ts;clock_gettime(CLOCK_MONOTONIC,&ts);int64_t now=int64_t(ts.tv_sec)*1000000000+ts.tv_nsec,p=int64_t(per*1e9),next=tgt?tgt+p:now;
|
||||
if(tgt&&now>tgt+p+2000000)dm_present_late.fetch_add(1,std::memory_order_relaxed);if(next<now)next=now;if(next>now+2*p)next=now+p;tgt=next;OH_NativeWindow_NativeWindowHandleOpt(active,SET_DESIRED_PRESENT_TIMESTAMP,next);}}
|
||||
#endif
|
||||
XTRACE_BEGIN("dm-queue-present");VkResult pr=vkQueuePresentKHR(queue,&pi);XTRACE_END();
|
||||
// 呈现失败时先排空,拆除路径要求队列空闲。
|
||||
// Drain a failed present before teardown, which requires an idle queue.
|
||||
if(overlap){flight^=1;if(pr!=VK_SUCCESS && pr!=VK_SUBOPTIMAL_KHR && (r=vkQueueWaitIdle(queue)))return r;}
|
||||
else{if((r=vkWaitForFences(device,1,&done,VK_TRUE,10000000000ull)))return r;if((r=vkResetFences(device,1,&done)))return r;in_flight[0]=false;if((r=vkQueueWaitIdle(queue)))return r;}
|
||||
if(pr==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
if(pr==VK_ERROR_OUT_OF_DATE_KHR){swap_dirty=true;wait_resize();continue;}
|
||||
if(pr!=VK_SUCCESS&&pr!=VK_SUBOPTIMAL_KHR)return pr;
|
||||
// 已成功呈现的帧不因尺寸瞬变报错;下帧再重建或等待可用尺寸。
|
||||
// Defer suboptimal recreation to the next frame, which can wait for a usable extent.
|
||||
if((rebuild||pr==VK_SUBOPTIMAL_KHR)&&surface_properties_changed())swap_dirty=true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
extern "C" void dm_android_vk_set_window(ANativeWindow *window){if(window)ANativeWindow_acquire(window);{std::lock_guard<std::mutex> l(window_mutex);if(desired)ANativeWindow_release(desired);desired=window;++generation;}window_cv.notify_all();}
|
||||
extern "C" int dm_android_vk_has_window(){return has_window(nullptr);}
|
||||
extern "C" int dm_android_vk_initialize(const char *path,char *error,size_t bytes){
|
||||
if(path){std::string dir=path;size_t cut=dir.find_last_of('/');if(FILE *m=fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+"/gfx-present-native").c_str(),"rb")){present_native=fgetc(m)!='0';fclose(m);}
|
||||
if(FILE *m=fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+"/gfx-present-timing").c_str(),"rb")){present_timing=true;fclose(m);}}
|
||||
std::lock_guard<std::mutex> render_lock(render_mutex);
|
||||
auto fail=[&](const char *what,VkResult r)->int{if(error&&bytes)snprintf(error,bytes,"%s: VkResult %d",what,int(r));if(!ready)cleanup_initialization();return int(r?r:VK_ERROR_INITIALIZATION_FAILED);};
|
||||
if(ready||!path||!*path)return fail("Initialization requires an external shader directory and an uninitialized renderer",VK_ERROR_INITIALIZATION_FAILED);
|
||||
// 每次初始化从缺省的 120 Hz 重新读标记。 | Each initialization starts again from the 120 Hz default before the marker.
|
||||
frame_rate_vote=120;
|
||||
{std::string dir=path;size_t cut=dir.find_last_of('/');if(FILE *m=fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+"/gfx-frame-rate").c_str(),"rb")){float v=0;frame_rate_vote=fscanf(m,"%f",&v)==1 && v>=0 && v<=240?v:0;fclose(m);}}
|
||||
|
||||
VkApplicationInfo ai{VK_STRUCTURE_TYPE_APPLICATION_INFO};ai.pApplicationName="dm-android";ai.apiVersion=VK_API_VERSION_1_1;
|
||||
const char *ext[]={VK_KHR_SURFACE_EXTENSION_NAME,VK_KHR_ANDROID_SURFACE_EXTENSION_NAME};VkInstanceCreateInfo ic{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};ic.pApplicationInfo=&ai;ic.enabledExtensionCount=2;ic.ppEnabledExtensionNames=ext;VkResult r=vkCreateInstance(&ic,nullptr,&instance);if(r)return fail("vkCreateInstance",r);
|
||||
uint32_t n=0;vkEnumeratePhysicalDevices(instance,&n,nullptr);std::vector<VkPhysicalDevice> devices(n);vkEnumeratePhysicalDevices(instance,&n,devices.data());if(!n)return fail("No Vulkan device",VK_ERROR_INITIALIZATION_FAILED);
|
||||
physical=devices[0];
|
||||
// 启动期间也可能旋转/切后台;等待新窗口,不把瞬时撤回误报为启动失败。
|
||||
// Rotation/backgrounding can race startup too; wait for a live window instead of failing boot.
|
||||
for(;;){wait_window();r=VkResult(create_surface());if(r==VK_NOT_READY)continue;if(r==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}if(r)return fail("Android surface",r);break;}
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(physical,&n,nullptr);std::vector<VkQueueFamilyProperties> q(n);vkGetPhysicalDeviceQueueFamilyProperties(physical,&n,q.data());bool found=false;
|
||||
for(uint32_t i=0;i<n;i++){VkBool32 p=0;vkGetPhysicalDeviceSurfaceSupportKHR(physical,i,surface,&p);if(p&&(q[i].queueFlags&(VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT))==(VK_QUEUE_GRAPHICS_BIT|VK_QUEUE_COMPUTE_BIT)){family=i;found=true;break;}}if(!found)return fail("No graphics/compute/present family",VK_ERROR_FEATURE_NOT_PRESENT);
|
||||
VkPhysicalDeviceShaderDrawParametersFeatures draw{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_DRAW_PARAMETERS_FEATURES};VkPhysicalDeviceFeatures2 features{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2};features.pNext=&draw;vkGetPhysicalDeviceFeatures2(physical,&features);
|
||||
vkEnumerateDeviceExtensionProperties(physical,nullptr,&n,nullptr);std::vector<VkExtensionProperties> available(n);vkEnumerateDeviceExtensionProperties(physical,nullptr,&n,available.data());bool mirror=false;for(auto e:available)if(std::string(e.extensionName)==VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME)mirror=true;
|
||||
{std::string all;for(auto &e:available){all+=e.extensionName;all+=' ';} // 诊断:设备扩展全表(每次启动一行)| Diagnostics: the full device extension list (one line per launch)
|
||||
for(size_t at=0;at<all.size();at+=900)__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Device extensions [%zu]: %s",at/900,all.substr(at,900).c_str());
|
||||
VkPhysicalDeviceExternalMemoryHostPropertiesEXT host{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT};VkPhysicalDeviceProperties2 pr{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2};pr.pNext=&host;vkGetPhysicalDeviceProperties2(physical,&pr);
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Device %s api=%u.%u.%u driver=%#x minImportedHostPointerAlignment=%llu",pr.properties.deviceName,VK_VERSION_MAJOR(pr.properties.apiVersion),VK_VERSION_MINOR(pr.properties.apiVersion),VK_VERSION_PATCH(pr.properties.apiVersion),pr.properties.driverVersion,(unsigned long long)host.minImportedHostPointerAlignment);}
|
||||
std::vector<const char*> dext={VK_KHR_SWAPCHAIN_EXTENSION_NAME};if(mirror)dext.push_back(VK_KHR_SAMPLER_MIRROR_CLAMP_TO_EDGE_EXTENSION_NAME);
|
||||
// Diagnostic (marker gfx-pipe-stats): the driver's per-pipeline statistics (VK_KHR_pipeline_executable_properties).
|
||||
VkPhysicalDevicePipelineExecutablePropertiesFeaturesKHR pef{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PIPELINE_EXECUTABLE_PROPERTIES_FEATURES_KHR};
|
||||
if(FILE *ps=[&]{std::string dir=path;size_t cut=dir.find_last_of('/');return fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+"/gfx-pipe-stats").c_str(),"rb");}()){fclose(ps);dext.push_back(VK_KHR_PIPELINE_EXECUTABLE_PROPERTIES_EXTENSION_NAME);pef.pipelineExecutableInfo=VK_TRUE;pef.pNext=draw.pNext;draw.pNext=&pef;}
|
||||
float priority=1;VkDeviceQueueCreateInfo qc{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};qc.queueFamilyIndex=family;qc.queueCount=1;qc.pQueuePriorities=&priority;VkDeviceCreateInfo dc{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};dc.pNext=&draw;dc.pEnabledFeatures=&features.features;dc.queueCreateInfoCount=1;dc.pQueueCreateInfos=&qc;dc.enabledExtensionCount=uint32_t(dext.size());dc.ppEnabledExtensionNames=dext.data();if((r=vkCreateDevice(physical,&dc,nullptr,&device)))return fail("vkCreateDevice",r);vkGetDeviceQueue(device,family,0,&queue);
|
||||
for(;;){
|
||||
wait_window();
|
||||
if(!surface||window_changed()){
|
||||
r=VkResult(create_surface());if(r==VK_NOT_READY)continue;
|
||||
if(r==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
if(r)return fail("Android surface",r);
|
||||
}
|
||||
r=VkResult(create_swap());
|
||||
if(r==VK_NOT_READY||r==VK_ERROR_OUT_OF_DATE_KHR){wait_resize();continue;}
|
||||
if(r==VK_ERROR_SURFACE_LOST_KHR){uint64_t bad=active_generation;destroy_swap();wait_window_change(bad);continue;}
|
||||
if(r)return fail("Swapchain",r);break;
|
||||
}
|
||||
VkCommandPoolCreateInfo cp{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};cp.flags=VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;cp.queueFamilyIndex=family;if((r=vkCreateCommandPool(device,&cp,nullptr,&command_pool)))return fail("Present command pool",r);
|
||||
VkCommandBufferAllocateInfo ca{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};ca.commandPool=command_pool;ca.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY;ca.commandBufferCount=1;if((r=vkAllocateCommandBuffers(device,&ca,&command)))return fail("Present command",r);
|
||||
VkSemaphoreCreateInfo sc{VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO};if((r=vkCreateSemaphore(device,&sc,nullptr,&acquired)))return fail("Acquire semaphore",r);VkFenceCreateInfo fc{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};if((r=vkCreateFence(device,&fc,nullptr,&fence)))return fail("Present fence",r);
|
||||
{std::string dir=path;size_t cut=dir.find_last_of('/');FILE *m=fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+"/gfx-present-overlap").c_str(),"rb");overlap=true;if(m){overlap=fgetc(m)!='0';fclose(m);}
|
||||
auto open_marker=[&](const char *name){return fopen(((cut==std::string::npos?dir:dir.substr(0,cut))+name).c_str(),"rb");};
|
||||
pin_mask=fastest_cores();pin_ab=0;pin_state=-1;pin_have_original=false;pin_presents=pin_drifts=0;
|
||||
if(FILE *p=open_marker("/gfx-pin-cpu")){if(fscanf(p,"%x",&pin_mask)!=1)pin_mask=0;fclose(p);}
|
||||
if(FILE *n=open_marker("/gfx-no-pin")){pin_mask=0;fclose(n);}
|
||||
if(FILE *t=open_marker("/gfx-ab-target")){char target[16]={0};if(fscanf(t,"%15s",target)==1 && !strcmp(target,"pin"))if(FILE *a=open_marker("/gfx-ab-toggle")){if(fscanf(a,"%d",&pin_ab)!=1)pin_ab=0;fclose(a);}fclose(t);}
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","NVN pin mask=%x ab=%d (markers gfx-no-pin, gfx-pin-cpu, gfx-ab-target=pin)",pin_mask,pin_ab);
|
||||
if(FILE *b=open_marker("/gfx-membench")){fclose(b);membench();}}
|
||||
if(overlap){if((r=vkCreateCommandPool(device,&cp,nullptr,&overlap_pool)))return fail("Present command pool",r);ca.commandPool=overlap_pool;if((r=vkAllocateCommandBuffers(device,&ca,&overlap_command)))return fail("Present command",r);
|
||||
if((r=vkCreateSemaphore(device,&sc,nullptr,&overlap_acquired)))return fail("Acquire semaphore",r);if((r=vkCreateFence(device,&fc,nullptr,&overlap_fence)))return fail("Present fence",r);}
|
||||
__android_log_print(ANDROID_LOG_INFO,"dm-vulkan","Present overlap=%d (marker gfx-present-overlap)",int(overlap));
|
||||
shader_path=path;dm_vk_config config{};config.size=sizeof(config);config.game.size=sizeof(config.game);config.game.physical=physical;config.game.device=device;config.game.queue=queue;config.game.queue_family=family;config.game.enabled_core=features.features;config.game.enabled_shader_draw_parameters=draw.shaderDrawParameters;config.game.fence_timeout_ns=10000000000ull;config.game.shader_directory=shader_path.c_str();config.game.present=present;config.game.log=log_message;config.game.fatal=fatal;config.sampler_mirror_clamp_to_edge=mirror;config.has_window=has_window;config.display_hz=0; // Query actual display refresh in frontend; do not guess 60 Hz.
|
||||
int status=dm_vk_initialize(&config,error,bytes);if(!status)ready=true;else cleanup_initialization();return status;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
#include <stddef.h>
|
||||
#include <android/native_window.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/* UI线程:保留窗口;NULL暂停呈现。只更新窗口快照,不调用Vulkan或等待GPU。
|
||||
* UI thread: retains window; NULL suspends presentation. Only updates the window
|
||||
* snapshot; never calls Vulkan or waits for the GPU. */
|
||||
void dm_android_vk_set_window(ANativeWindow *window);
|
||||
/* 宿主线程:在dm_main前初始化一次;Surface暂时撤回时等待恢复。
|
||||
* Host thread: before dm_main, after set_window. Waits across surface withdrawal
|
||||
* and initializes genuine Vulkan replay once.
|
||||
* shader_directory remains external, is copied internally, and must hold .xgs. */
|
||||
int dm_android_vk_initialize(const char *shader_directory,char *error,size_t bytes);
|
||||
int dm_android_vk_has_window(void);
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,97 @@
|
||||
# Hero desktop widgets / vivo atomic-component candidate
|
||||
|
||||
The Android shell provides two read-only `RemoteViews` widgets: the latest saved hero (2×2), and up to three most recently played heroes (4×2). Both open the app when tapped and have a separate refresh action. Empty and unreadable-save states are localized. No game executable, game art, experience table, or player save is included.
|
||||
|
||||
This is implementation for platform evaluation. It has **not** received vivo platform permission, component review, or store approval. Installing an APK or setting `vivo_widget=true` does not demonstrate inclusion in the vivo atomic-component catalog or one-tap pinning support.
|
||||
|
||||
## Data and limitations
|
||||
|
||||
`SaveSummaryReader` reads only `context.getFilesDir()/save/<directory>/<directory>.d2s`, the committed `DM_SAVE` path set in `jni_android.c`. It rejects a root named `save.work`, symbolic-link entries, oversized/truncated files, invalid checksums, malformed UTF-8, unknown classes, and unsupported versions. No save is created, modified, imported, or deleted by widget code. File reads run off the broadcast thread.
|
||||
|
||||
The field layout follows the existing Harmony `SaveSummary.ts`: class at `0x18`, level at `0x1b`, unsigned last-played time at `0x20`, UTF-8 name at `0x12b`, and LSB-first `gf` stat fields. Versions `0x61` (the Harmony reader's documented format) and `0x69` (also evidenced by `dm/verify/savecmp.py`) are accepted. Other versions require independently verified layout support. The checksum and declared length must match; the bitstream must terminate with ordered known IDs and a level matching the header. If no unambiguous valid stat block is found, experience/gold remain unavailable while valid header fields can still be shown. Gold is carried plus bank gold only when both fields were read.
|
||||
|
||||
Experience percentages and progress bars are intentionally absent: no generated experience table is connected. Raw experience is displayed when verified. The original Harmony reader's embedded experience table was **not copied**. There are no extracted class portraits, last-played date labels, or gameplay actions in this first implementation. The wide layout uses three columns rather than assuming Harmony's dimension naming maps to Android.
|
||||
|
||||
## Application integration
|
||||
|
||||
These receivers are registered under the manifest's `application`. Do not add an application process or load the native game library for widget updates.
|
||||
|
||||
```xml
|
||||
<receiver android:name=".widget.HeroWidget2x2Provider"
|
||||
android:exported="false" android:label="@string/dmAndroidWidgetName2x2">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_2x2_info" />
|
||||
<meta-data android:name="vivo_widget" android:value="true" />
|
||||
<meta-data android:name="vivoWidgetVersion" android:value="1" />
|
||||
<meta-data android:name="vivo.widget.description" android:resource="@string/dmAndroidWidgetDescription" />
|
||||
</receiver>
|
||||
<receiver android:name=".widget.HeroWidget4x2Provider"
|
||||
android:exported="false" android:label="@string/dmAndroidWidgetName4x2">
|
||||
<intent-filter>
|
||||
<action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
|
||||
</intent-filter>
|
||||
<meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_4x2_info" />
|
||||
<meta-data android:name="vivo_widget" android:value="true" />
|
||||
<meta-data android:name="vivoWidgetVersion" android:value="1" />
|
||||
<meta-data android:name="vivo.widget.description" android:resource="@string/dmAndroidWidgetDescription" />
|
||||
</receiver>
|
||||
```
|
||||
|
||||
The Activity calls this from `onStop` after backgrounding:
|
||||
|
||||
```java
|
||||
com.xiaoboluo.d2r.widget.HeroWidgetProvider.requestUpdate(this);
|
||||
```
|
||||
|
||||
This sends explicit updates only to installed widget instances and never starts the game. The widget's refresh button also reads the current committed saves. There is no native save-commit callback yet; avoid describing backgrounding as proof that a save succeeded. The periodic fallback is 12 hours, matching vivo's minimum; no frequent timer or file watcher runs. No extra Gradle dependency, network permission, email, account operation, or vendor SDK was introduced.
|
||||
|
||||
The shared `dm/i18n/ui_text.tsv` keys below are integrated. The existing generator includes `dmAndroid*` and lowercases keys into `R.string` IDs.
|
||||
|
||||
| Key | 中文 | English |
|
||||
| --- | --- | --- |
|
||||
| dmAndroidWidgetTitle | 英雄 | Heroes |
|
||||
| dmAndroidWidgetRefresh | 刷新 | Refresh |
|
||||
| dmAndroidWidgetName2x2 | 最近英雄 | Latest Hero |
|
||||
| dmAndroidWidgetName4x2 | 英雄列表 | Hero List |
|
||||
| dmAndroidWidgetDescription | 查看已保存的英雄进度 | View saved hero progress |
|
||||
| dmAndroidWidgetEmpty | 还没有英雄 | No heroes yet |
|
||||
| dmAndroidWidgetEmptyHint | 点开游戏创建英雄 | Open the game to create a hero |
|
||||
| dmAndroidWidgetError | 无法读取存档摘要 | Save summary unavailable |
|
||||
| dmAndroidWidgetErrorHint | 成功保存后请刷新 | Refresh after a successful save |
|
||||
| dmAndroidWidgetStats | %1$d级 · %2$s | Lv %1$d · %2$s |
|
||||
| dmAndroidWidgetExp | 经验 %1$s | Exp %1$s |
|
||||
| dmAndroidWidgetGold | 金币 %1$s | Gold %1$s |
|
||||
| dmAndroidWidgetExpUnknown | 经验暂不可读 | Experience unavailable |
|
||||
| dmAndroidWidgetGoldUnknown | 金币暂不可读 | Gold unavailable |
|
||||
| dmAndroidWidgetFooter | %1$d位英雄 | %1$d heroes |
|
||||
| dmAndroidWidgetPartial | %1$d位英雄 · 部分存档不可读 | %1$d heroes · some saves unreadable |
|
||||
| dmAndroidWidgetClassAmazon | 亚马逊 | Amazon |
|
||||
| dmAndroidWidgetClassSorceress | 法师 | Sorceress |
|
||||
| dmAndroidWidgetClassNecromancer | 死灵法师 | Necromancer |
|
||||
| dmAndroidWidgetClassPaladin | 圣骑士 | Paladin |
|
||||
| dmAndroidWidgetClassBarbarian | 野蛮人 | Barbarian |
|
||||
| dmAndroidWidgetClassDruid | 德鲁伊 | Druid |
|
||||
| dmAndroidWidgetClassAssassin | 刺客 | Assassin |
|
||||
| dmAndroidWidgetClassWarlock | 术士 | Warlock |
|
||||
|
||||
## Validation
|
||||
|
||||
From the repository root, run with a JDK (no Android/native build needed):
|
||||
|
||||
```text
|
||||
javac -d <temporary-output> dm/android/app/src/main/java/com/xiaoboluo/d2r/widget/SaveSummaryReader.java dm/android/tests/SaveSummaryReaderTest.java
|
||||
java -cp <temporary-output> com.xiaoboluo.d2r.widget.SaveSummaryReaderTest
|
||||
```
|
||||
|
||||
The test generates synthetic bytes and its own temporary directory, then removes only that directory. It covers supported/unknown versions, checksum/length validation, unsigned fields, UTF-8, malformed stats, sort order, partial failures, working-directory rejection, and no mutation of input or save bytes. It does not establish compatibility with a real player's save, launcher rendering, platform acceptance, or refresh delivery. APK compilation and lint passed on 2026-10-16; vivo registered both providers. Launcher rendering, refresh and real-save compatibility remain unverified.
|
||||
|
||||
## Official sources and external requirements
|
||||
|
||||
- [vivo technical adaptation](https://dev.vivo.com.cn/documentCenter/doc/845): AppWidget receiver metadata, 2×2/4×2 dimensions, minimum 12-hour periodic refresh, `resizeMode=none`, no component scrolling, fresh RemoteViews per update, background-thread I/O.
|
||||
- [vivo onboarding](https://dev.vivo.com.cn/documentCenter/doc/850): the app must already be in the vivo store; the developer must apply for component-management access and submit the APK for review. No application was sent by this implementation.
|
||||
- [vivo review rules](https://dev.vivo.com.cn/documentCenter/doc/829): separate review and design requirements apply.
|
||||
- [Android AppWidget documentation](https://developer.android.com/develop/ui/views/appwidgets): standard provider/RemoteViews behavior is separate from vendor approval.
|
||||
|
||||
The vivo pages are JavaScript shells; their official public content endpoint `/webapi/doc/info?id=<id>` was read to verify these requirements. Availability in a particular OriginOS build remains untested. No one-tap pinning/catalog navigation code is included because it would require capability and approval checks.
|
||||
@@ -0,0 +1,36 @@
|
||||
# 英雄桌面卡片 / vivo 原子组件候选
|
||||
|
||||
新增两种只读 RemoteViews 卡片:2×2 显示最近保存的英雄,4×2 最多显示最近三个英雄。显示名字、等级、职业及能确认读取的经验值和金币,整卡打开游戏,刷新按钮单独更新。没有英雄或存档不可读时显示对应本地化状态。
|
||||
|
||||
代码已集成并编译通过,vivo 系统已登记两个 provider;桌面显示、刷新及真实存档兼容仍待验证,**尚未取得 vivo 原子组件后台权限、审核或商店上架资格**。普通 AppWidget 可运行或声明 `vivo_widget=true`,均不等于进入 vivo 原子组件库或获得一键加桌能力。
|
||||
|
||||
## 数据边界
|
||||
|
||||
只读 `getFilesDir()/save/<目录>/<目录>.d2s`,对应 Android `jni_android.c` 的已提交 `DM_SAVE`;不读取 `save.work`,不写入、导入、删除存档,不启动游戏运算。目录/文件符号链接、超长、截断、校验和错误、非法 UTF-8、未知职业和未知版本均拒绝。文件读取在广播线程之外执行。
|
||||
|
||||
字段位置复用本机 Claude 鸿蒙 `SaveSummary.ts` 的语义:职业 `0x18`、等级 `0x1b`、最后游玩时间 `0x20`、UTF-8 名字 `0x12b`,经验和金币来自 `gf` 位流。支持有现有源码依据的 `0x61` 和 `0x69`,不猜其他版本。统计段还要求合法终止、已知有序字段和与头部一致的等级;不能确认统计段时保留有效名字/等级,经验和金币显示不可读。只有两个金币字段均读到才相加。
|
||||
|
||||
当前不提供经验百分比或进度条:尚未接入玩家资源生成的经验表,未复制鸿蒙旧代码内的经验表进入 Git。首版也不提供游戏提取头像、上次游玩日期文案、卡片内游戏操作。4×2 用三列自适应展示,没有将鸿蒙 `2*4` 名称直接当成 Android 网格。
|
||||
|
||||
## 集成
|
||||
|
||||
已集成的 Manifest 双 receiver 配置和24项中英文案表在 [README.md](README.md)。由主负责人维护 Manifest、Activity、Gradle 和统一中英表,本任务未修改这些文件。
|
||||
|
||||
receiver 类分别为 `.widget.HeroWidget2x2Provider`、`.widget.HeroWidget4x2Provider`,元数据分别指向 `@xml/widget_2x2_info`、`@xml/widget_4x2_info`。各 receiver 包含:
|
||||
|
||||
- `android.appwidget.provider`:对应 XML。
|
||||
- `vivo_widget=true`。
|
||||
- `vivoWidgetVersion=1`。
|
||||
- `vivo.widget.description=@string/dmAndroidWidgetDescription`。
|
||||
|
||||
应用退到后台或确认存档成功后可调 `HeroWidgetProvider.requestUpdate(this)`,仅对已添加实例发显式更新广播。退后台不代表存档一定成功,原生提交完成事件尚未接入。用户也可点刷新;周期兜底为12小时。没有新增 native/JNI、第三方 SDK、网络权限、定时轮询或文件监测。
|
||||
|
||||
## 验证及未验项
|
||||
|
||||
`SaveSummaryReaderTest` 只生成合成存档和独立临时目录,覆盖校验和/长度、未知版本、无符号字段、UTF-8、异常统计段、最近游玩排序、部分失败、拒绝工作目录及读取不改写,运行命令见英文文档。
|
||||
|
||||
未进行 Android/native 构建、安装或设备操作。纯 Java 合成测试不证明真实存档版本兼容、不同字号/主题下的桌面显示、刷新投递或 vivo 平台接入已通过;这些需要主线统一验证。
|
||||
|
||||
## 官方依据
|
||||
|
||||
[技术规范](https://dev.vivo.com.cn/documentCenter/doc/845)规定原生 AppWidget 基础上的专用元数据、2×2/4×2规格、至少12小时的周期刷新、关闭拖拽缩放、禁止卡片内滑动及子线程文件读取。[接入指导](https://dev.vivo.com.cn/documentCenter/doc/850)要求应用先在商店上架,申请组件后台权限并上传 APK 审核;[审核规范](https://dev.vivo.com.cn/documentCenter/doc/829)另有产品/交互要求。官方网页为 JavaScript 壳,核查时读取了其公开官方 `/webapi/doc/info?id=<id>` 正文。本实现没有发送申请邮件或操作开发者账号。
|
||||
+242
-26
@@ -20,10 +20,13 @@
|
||||
// Environment switches: DM_NVN_FRAMES=N prints the call table per frame for the first N frames (default 3); DM_NVN_TSV=path writes the per-frame call table and timing to a TSV (DM_NVN_TSV_CALLS=0 writes timing only); DM_SLOWFRAME=1 writes only the per-frame breakdown of dropped frames to the log; DM_NVN_LOG=1 logs object creation.
|
||||
#include "../../host/hle.h"
|
||||
#include "nvn_protos.h"
|
||||
#include "nvn_pool_flags_registry.h"
|
||||
#include "nvn_count.h"
|
||||
#include "nvn_tex.h"
|
||||
#include "../xtrace.h"
|
||||
#include "nvn_mtl.h"
|
||||
#include "nvn_pace.h"
|
||||
#include "nvn_adaptive_pace.h"
|
||||
#include "../../host/front.h"
|
||||
#include "nvn_dirty.h"
|
||||
#include <mach/mach_time.h>
|
||||
@@ -37,11 +40,11 @@
|
||||
#endif
|
||||
#include <pthread/qos.h>
|
||||
#include <sys/resource.h>
|
||||
#ifdef __APPLE__
|
||||
#include <mach/thread_policy.h>
|
||||
#endif
|
||||
#include <assert.h>
|
||||
#include <stdatomic.h>
|
||||
#include <mach-o/getsect.h>
|
||||
#include <mach-o/ldsyms.h>
|
||||
|
||||
// ---------- 槽表、跳板、未实现桩 ----------
|
||||
// ---------- Slot table, thunks, unimplemented stubs ----------
|
||||
@@ -66,13 +69,13 @@ typedef struct { const char *name; void *fn; } nvn_impl;
|
||||
#define NVN(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
static const NVNT_##name chk_##name __attribute__((unused)) = h_##name; \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
DM_SECT(swnvn) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
// 无原型的新版接口:不做签名检查
|
||||
// Newer interfaces without prototypes: no signature check
|
||||
#define NVN_NOPROTO(name, ret, ...) \
|
||||
static ret h_##name(__VA_ARGS__); \
|
||||
__attribute__((used, section("__DATA,swnvn"))) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
DM_SECT(swnvn) static const nvn_impl e_##name = {#name, (void *)h_##name}; \
|
||||
static ret h_##name(__VA_ARGS__)
|
||||
|
||||
static int g_log;
|
||||
@@ -83,8 +86,8 @@ static unsigned g_nsem; // 语义实现个数(nvn_ini
|
||||
static void nvn_init_slots(void) {
|
||||
static int done; if (done) return; done = 1;
|
||||
g_log = getenv("DM_NVN_LOG") != NULL;
|
||||
unsigned long sz;
|
||||
const nvn_impl *im = (const nvn_impl *)getsectiondata(&_mh_execute_header, "__DATA", "swnvn", &sz);
|
||||
unsigned long sz; const nvn_impl *im;
|
||||
DM_SECT_GET(swnvn, const nvn_impl, im, sz);
|
||||
unsigned nim = im ? (unsigned)(sz / sizeof *im) : 0, hit = 0;
|
||||
for (unsigned i = 0; i < NVN_NFUNC; i++) nvn_slot[i].fn = (void *)nvn_unimpl_entry;
|
||||
for (unsigned k = 0; k < nim; k++) {
|
||||
@@ -174,15 +177,42 @@ NVN(nvnMemoryPoolBuilderSetDefaults, void, NVNmemoryPoolBuilder *b) { memset(b,
|
||||
NVN(nvnMemoryPoolBuilderSetDevice, void, NVNmemoryPoolBuilder *b, NVNdevice *d) { ((pool_builder_t *)b)->dev = d; }
|
||||
NVN(nvnMemoryPoolBuilderSetStorage, void, NVNmemoryPoolBuilder *b, void *m, size_t n) { ((pool_builder_t *)b)->mem = m; ((pool_builder_t *)b)->size = n; }
|
||||
NVN(nvnMemoryPoolBuilderSetFlags, void, NVNmemoryPoolBuilder *b, int f) { ((pool_builder_t *)b)->flags = f; }
|
||||
// 池标志表:图形后端可查询一段客体内存所在池的标志(Vulkan 引擎据 CPU_NO_ACCESS 省掉被更新的 GPU 结果覆盖的存储写回)。
|
||||
// 建池、销池在客体线程,查询在渲染线程;用互斥量(不在信号处理里用)。按池对象删除,重叠alias不证明CPU_NO_ACCESS。
|
||||
// 表满或非法范围后全表持续返回未知,避免未登记的可读alias被忽略。
|
||||
// Pool flags: a graphics backend may ask for the flags of the pool that holds a guest range (the Vulkan engine drops storage
|
||||
// writebacks into CPU_NO_ACCESS pools that newer GPU results supersede). Pools are created and destroyed on guest threads
|
||||
// and queried from the render thread, so use a mutex (never in signal context). Remove by pool identity; overlapping aliases cannot prove CPU_NO_ACCESS.
|
||||
// A full table or invalid range makes all later queries unknown, so an untracked CPU-readable alias cannot be ignored.
|
||||
static nvn_pool_flags_registry g_pool_flags;
|
||||
static pthread_mutex_t g_pool_flags_mu = PTHREAD_MUTEX_INITIALIZER;
|
||||
static void pool_flags_add(const void *owner,const void *mem, uint64_t size, int flags) {
|
||||
pthread_mutex_lock(&g_pool_flags_mu);
|
||||
nvn_pool_flags_registry_add(&g_pool_flags,owner,mem,size,flags);
|
||||
pthread_mutex_unlock(&g_pool_flags_mu);
|
||||
}
|
||||
static void pool_flags_del(const void *owner) {
|
||||
pthread_mutex_lock(&g_pool_flags_mu);
|
||||
nvn_pool_flags_registry_del(&g_pool_flags,owner);
|
||||
pthread_mutex_unlock(&g_pool_flags_mu);
|
||||
}
|
||||
// [addr, addr+len) 所在池的标志;不在任何登记的池里 → -1
|
||||
// Flags of the pool holding [addr, addr+len); -1 when no registered pool holds it
|
||||
int nvn_pool_flags(const void *addr, size_t len) {
|
||||
pthread_mutex_lock(&g_pool_flags_mu);
|
||||
int f=nvn_pool_flags_registry_get(&g_pool_flags,addr,len);
|
||||
pthread_mutex_unlock(&g_pool_flags_mu);
|
||||
return f;
|
||||
}
|
||||
NVN(nvnMemoryPoolInitialize, NVNboolean, NVNmemoryPool *p, const NVNmemoryPoolBuilder *b) {
|
||||
const pool_builder_t *s = (const pool_builder_t *)b; pool_t *o = (pool_t *)p;
|
||||
o->magic = MAGIC('P', 'O', 'O', 'L'); o->flags = s->flags; o->mem = s->mem; o->size = s->size;
|
||||
if (o->mem) { mtl_pool_add(o->mem, o->size); nvn_dirty_add_range(o->mem, o->size); }
|
||||
if (o->mem) { mtl_pool_add(o->mem, o->size); nvn_dirty_add_range(o->mem, o->size); pool_flags_add(p,o->mem, o->size, o->flags); }
|
||||
if (!o->mem && !(o->flags & 0x200)) LOG("【红】MemoryPoolInitialize 非虚拟池没有存储 flags=%#x size=%#llx", o->flags, o->size);
|
||||
OLOG("MemoryPool %p mem=%p size=%#llx flags=%#x", (void *)p, (void *)o->mem, o->size, o->flags);
|
||||
return 1;
|
||||
}
|
||||
NVN(nvnMemoryPoolFinalize, void, NVNmemoryPool *p) { if (((pool_t *)p)->mem) { nvn_dirty_remove_range(((pool_t *)p)->mem); mtl_pool_del(((pool_t *)p)->mem); } ((pool_t *)p)->magic = 0; }
|
||||
NVN(nvnMemoryPoolFinalize, void, NVNmemoryPool *p) { pool_flags_del(p); if (((pool_t *)p)->mem) { nvn_dirty_remove_range(((pool_t *)p)->mem); mtl_pool_del(((pool_t *)p)->mem); } ((pool_t *)p)->magic = 0; }
|
||||
NVN(nvnMemoryPoolFlushMappedRange, void, const NVNmemoryPool *p, ptrdiff_t off, size_t n) { (void)p; (void)off; (void)n; }
|
||||
NVN(nvnMemoryPoolGetBufferAddress, NVNbufferAddress, const NVNmemoryPool *p) { return (NVNbufferAddress)((const pool_t *)p)->mem; }
|
||||
|
||||
@@ -423,23 +453,62 @@ NVN(nvnSyncFinalize, void, NVNsync *s) { ((sync_t *)s)->magic = 0; }
|
||||
// Fence = "all commands previously submitted to the queue have completed": record the fence value of the most recent submit
|
||||
NVN(nvnQueueFenceSync, void, NVNqueue *q, NVNsync *s, NVNsyncCondition c, int f) { (void)q; (void)c; (void)f; ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); }
|
||||
// 没围栏过的同步对象按真机行为等到超时;已围栏的只在 GPU 真正完成到该栅栏值后放行
|
||||
// A sync object that was never fenced waits until timeout, as on a real device; a fenced one is released only after the GPU has actually completed up to that fence value
|
||||
// 诊断:游戏每帧在 SyncWait / 读事件上等了多久、等的是落后最新提交几次的栅栏(每 300 帧一行)
|
||||
// A sync object that was never fenced waits until the timeout, as on the device; a fenced one is released only once the GPU has really completed up to that fence value
|
||||
// Diagnostics: how long the game waits per frame in SyncWait / event reads, and how many submits behind the newest the waited fence is (one line per 300 frames)
|
||||
uint64_t dm_nvn_frame_count(void);
|
||||
static _Atomic uint64_t g_gw_sync_n, g_gw_sync_ns, g_gw_sync_lag, g_gw_ev_n, g_gw_ev_ns, g_gw_sync_hit, g_gw_acq_n;
|
||||
static const void *volatile g_acq_sync; // 最近一次取图带回的同步对象(诊断:游戏等的是不是它)| The sync handed back by the latest acquire (diagnostics: is this what the game waits on)
|
||||
static void gw_report(void) {
|
||||
static uint64_t last; uint64_t f = dm_nvn_frame_count(); if (f < last + 300) return; last = f;
|
||||
uint64_t sn = atomic_exchange(&g_gw_sync_n, 0), sns = atomic_exchange(&g_gw_sync_ns, 0), lag = atomic_exchange(&g_gw_sync_lag, 0), hit = atomic_exchange(&g_gw_sync_hit, 0);
|
||||
uint64_t en = atomic_exchange(&g_gw_ev_n, 0), ens = atomic_exchange(&g_gw_ev_ns, 0), an = atomic_exchange(&g_gw_acq_n, 0);
|
||||
LOG("[nvn] 游戏等 GPU(300 帧):SyncWait %.2f 次/帧(已完成 %.2f,其中取图同步 %.2f),共 %.2f ms/帧,平均落后最新提交 %.2f 次;读事件 %.2f 次/帧,共 %.2f ms/帧",
|
||||
sn / 300.0, hit / 300.0, an / 300.0, sns / 300e6, sn ? (double)lag / sn : 0, en / 300.0, ens / 300e6);
|
||||
}
|
||||
static int x_wait_sub(uint64_t sub, uint64_t timeout);
|
||||
NVN(nvnSyncWait, NVNsyncWaitResult, const NVNsync *s, uint64_t timeout) {
|
||||
const sync_t *o = (const sync_t *)s;
|
||||
if (!o->fenced) return NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
#ifdef __OHOS__ // 鸿蒙:先在翻译队列上等目标提交译完再问 GPU,并记等待统计(其他平台保持原逻辑)| HarmonyOS: wait on the translation queue for the target submit first, then ask the GPU, with wait statistics (other platforms keep the original logic)
|
||||
atomic_fetch_add(&g_gw_sync_n, 1); atomic_fetch_add(&g_gw_sync_lag, x_fence() - o->fence); if ((const void *)s == g_acq_sync) atomic_fetch_add(&g_gw_acq_n, 1); gw_report();
|
||||
if (mtl_wait(o->fence, 0)) { atomic_fetch_add(&g_gw_sync_hit, 1); return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED; }
|
||||
// 目标提交还没翻译到:先在翻译队列上睡等(不去反复抢引擎锁),再问引擎 GPU 做完没有
|
||||
// Target submit not yet translated: sleep on the translation queue first (instead of repeatedly taking the engine lock), then ask the engine whether the GPU is done
|
||||
XTRACE_BEGIN("dm-game-syncwait"); XTRACE_COUNT("dm-game-wait-target", o->fence); uint64_t t0 = now_ns(); int ok = !timeout || x_wait_sub(o->fence, timeout);
|
||||
if (ok) { uint64_t used = now_ns() - t0; ok = mtl_wait(o->fence, timeout >= 3600000000000ull ? timeout : used >= timeout ? 0 : timeout - used); }
|
||||
atomic_fetch_add(&g_gw_sync_ns, now_ns() - t0); XTRACE_END();
|
||||
return ok ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
#else
|
||||
if (mtl_wait(o->fence, 0)) return NVN_SYNC_WAIT_RESULT_ALREADY_SIGNALED;
|
||||
return mtl_wait(o->fence, timeout) ? NVN_SYNC_WAIT_RESULT_CONDITION_SATISFIED : NVN_SYNC_WAIT_RESULT_TIMEOUT_EXPIRED;
|
||||
#endif
|
||||
}
|
||||
// CPU 访问事件前解析覆盖该地址的延后 SignalEvent(安卓 Vulkan 后端 dm/gfx/vulkan/nvn_vk.c 给强定义)。这里是空的弱定义、不是弱声明:
|
||||
// 苹果的链接器要求弱引用在链接时也要有定义,否则 Mac 宿主与 iOS 链接失败(_mtl_event_read 未定义)
|
||||
// Resolves deferred SignalEvents covering the address before the CPU accesses an event (the Android Vulkan backend dm/gfx/vulkan/nvn_vk.c
|
||||
// gives the strong definition). This is an empty weak definition, not a weak declaration: Apple's linker requires even a weak reference
|
||||
// to resolve at link time, or the Mac host and the iOS app fail to link (_mtl_event_read undefined)
|
||||
__attribute__((weak)) void mtl_event_read(const volatile uint32_t *val) { (void)val; }
|
||||
NVN(nvnEventBuilderSetDefaults, void, NVNeventBuilder *b) { memset(b, 0, sizeof(ev_builder_t)); }
|
||||
NVN(nvnEventBuilderSetStorage, void, NVNeventBuilder *b, const NVNmemoryPool *p, int64_t off) { *(ev_builder_t *)b = (ev_builder_t){(const pool_t *)p, off}; }
|
||||
NVN(nvnEventInitialize, NVNboolean, NVNevent *e, const NVNeventBuilder *b) {
|
||||
const ev_builder_t *s = (const ev_builder_t *)b;
|
||||
if (!s->pool || !s->pool->mem) { LOG("【红】EventInitialize 没有存储"); return 0; }
|
||||
if (mtl_event_read) mtl_event_read((volatile uint32_t *)(s->pool->mem + s->off));
|
||||
*(ev_t *)e = (ev_t){MAGIC('E', 'V', 'N', 'T'), (volatile uint32_t *)(s->pool->mem + s->off)}; return 1;
|
||||
}
|
||||
NVN(nvnEventFinalize, void, NVNevent *e) { ((ev_t *)e)->magic = 0; }
|
||||
NVN(nvnEventGetValue, uint32_t, const NVNevent *e) { return *((const ev_t *)e)->val; }
|
||||
static void ev_signal(const ev_t *e, int mode, uint32_t v) { if (mode == NVN_EVENT_SIGNAL_MODE_ADD) *e->val += v; else *e->val = v; }
|
||||
NVN(nvnEventFinalize, void, NVNevent *e) { if (mtl_event_read) mtl_event_read(((ev_t *)e)->val); ((ev_t *)e)->magic = 0; }
|
||||
// 后端若延后发布命令缓冲里的 SignalEvent(安卓 Vulkan,gfx-defer-events),读值前先让它落地;Metal 后端没有这个钩子
|
||||
// 读事件计时只在鸿蒙做(只有鸿蒙汇报这些计数),其余平台照旧
|
||||
// If the backend defers publishing command-buffer SignalEvents (Android Vulkan, gfx-defer-events), let it land before the read; the Metal backend has no such hook
|
||||
// The event-read timing runs on HarmonyOS only (only HarmonyOS reports these counters); other platforms as before
|
||||
#ifdef __OHOS__
|
||||
NVN(nvnEventGetValue, uint32_t, const NVNevent *e) { if (mtl_event_read) { uint64_t t0 = now_ns(); mtl_event_read(((const ev_t *)e)->val); atomic_fetch_add(&g_gw_ev_ns, now_ns() - t0); atomic_fetch_add(&g_gw_ev_n, 1); } return *((const ev_t *)e)->val; }
|
||||
#else
|
||||
NVN(nvnEventGetValue, uint32_t, const NVNevent *e) { if (mtl_event_read) mtl_event_read(((const ev_t *)e)->val); return *((const ev_t *)e)->val; }
|
||||
#endif
|
||||
static void ev_signal(const ev_t *e, int mode, uint32_t v) { if (mtl_event_read) mtl_event_read(e->val); if (mode == NVN_EVENT_SIGNAL_MODE_ADD) *e->val += v; else *e->val = v; }
|
||||
NVN(nvnEventSignal, void, NVNevent *e, NVNeventSignalMode m, uint32_t v) { ev_signal((const ev_t *)e, m, v); }
|
||||
|
||||
// ---------- 队列 ----------
|
||||
@@ -841,12 +910,22 @@ enum { XJ_SUBMIT, XJ_PRESENT, XJ_FRAME };
|
||||
typedef struct { int kind, n; uint64_t *h; const tex_t *tex; double period; int crop[4]; uint64_t frame, sub, host; } xjob; // host:入队时锁存的宿主画法开关 | host: host drawing switches latched at enqueue
|
||||
#define XQ 32
|
||||
#define XTK 1024
|
||||
static xjob g_xq[XQ]; static uint64_t g_xq_in, g_xq_done; // 入队任务数 / 已执行任务数(任务号从 1 计) | Jobs enqueued / jobs executed (job numbers start at 1)
|
||||
static xjob g_xq[XQ]; static uint64_t g_xq_in, g_xq_done, g_xsub_done; // g_xsub_done:已翻译完的提交号(栅栏值) | g_xsub_done: the last submit number translated (fence value) // 入队任务数 / 已执行任务数(任务号从 1 计) | Jobs enqueued / jobs executed (job numbers start at 1)
|
||||
static struct { uint64_t job, tk; } g_xtk[XTK]; // 出图任务号 → 出图线程票号 | Present job number -> present thread ticket
|
||||
static pthread_mutex_t g_xmu = PTHREAD_MUTEX_INITIALIZER; static pthread_cond_t g_xcv = PTHREAD_COND_INITIALIZER;
|
||||
#ifdef __OHOS__
|
||||
// 只在队列锁下传递诊断帧号,不从翻译线程读取游戏线程的 g_frame。
|
||||
// Propagate the diagnostic frame epoch under the queue lock; never read the game's g_frame from translation.
|
||||
static uint64_t g_x_trace_frame;
|
||||
#endif
|
||||
static int pace_adapt_enabled(void);
|
||||
static _Atomic double g_pa_xcpu_ms = -1; // 最近60个翻译帧的真实线程CPU(不含任何等待)| Actual thread CPU per frame over the latest 60 translation frames, excluding waits
|
||||
static int g_x_sync; static pthread_t g_x_thr; static mach_port_t g_x_port; // 翻译线程(策略读数用) | Translation thread (for policy readings)
|
||||
static void x_submit(const uint64_t *h, int n, uint64_t sub, uint64_t host) {
|
||||
mtl_host_apply(host);
|
||||
#ifdef __OHOS__
|
||||
{ void front_pin_check(void); front_pin_check(); } // 系统改回可用核就再绑 | re-pin if the system changed the allowed cores
|
||||
#endif
|
||||
uint64_t t0 = now_ns(), c0 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), i0, y0, s0 = thr_sys_ns(); thr_counts(&i0, &y0);
|
||||
mtl_sub_begin();
|
||||
mtl_sub_index(h, n);
|
||||
@@ -857,24 +936,52 @@ static void x_submit(const uint64_t *h, int n, uint64_t sub, uint64_t host) {
|
||||
snap_tick(sub);
|
||||
uint64_t dw = now_ns() - t0;
|
||||
atomic_fetch_add(&g_nvn_ns, dw); atomic_fetch_add(&g_sub_wall_ns, dw);
|
||||
uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t dc = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) - c0, di = i1 - i0;
|
||||
uint64_t i1, y1; thr_counts(&i1, &y1); uint64_t c1 = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID), dc = c1 - c0, di = i1 - i0;
|
||||
XTRACE_COUNT("dm-x-submit-cpu-us", c0 && c1 >= c0 ? (int64_t)(dc / 1000) : -1);
|
||||
atomic_fetch_add(&g_cum_sub_cyc, y1 - y0); atomic_fetch_add(&g_cum_sub_sys_ns, thr_sys_ns() - s0); atomic_fetch_add(&g_cum_sub_wall_ns, dw);
|
||||
atomic_fetch_add(&g_sub_cpu_ns, dc); atomic_fetch_add(&g_cum_sub_cpu_ns, dc);
|
||||
atomic_fetch_add(&g_sub_instr, di); atomic_fetch_add(&g_cum_sub_instr, di);
|
||||
}
|
||||
static void x_run(const xjob *j, uint64_t job) {
|
||||
if (j->kind == XJ_SUBMIT) { x_submit(j->h, j->n, j->sub, j->host); free(j->h); }
|
||||
else if (j->kind == XJ_PRESENT) { uint64_t tk = mtl_present(j->tex, j->period, j->crop); pthread_mutex_lock(&g_xmu); g_xtk[job % XTK].job = job; g_xtk[job % XTK].tk = tk; pthread_mutex_unlock(&g_xmu); }
|
||||
XTRACE_COUNT("dm-x-run-job", job); XTRACE_COUNT("dm-x-run-sub", j->sub); XTRACE_COUNT("dm-x-run-frame", j->frame);
|
||||
if (j->kind == XJ_SUBMIT) { XTRACE_BEGIN("dm-x-submit"); x_submit(j->h, j->n, j->sub, j->host); free(j->h); XTRACE_END(); }
|
||||
else if (j->kind == XJ_PRESENT) {
|
||||
#ifdef __OHOS__
|
||||
{ void front_gtx_frame(void); front_gtx_frame(); }
|
||||
#endif
|
||||
XTRACE_BEGIN("dm-x-present"); uint64_t tk = mtl_present(j->tex, j->period, j->crop); XTRACE_END(); pthread_mutex_lock(&g_xmu); g_xtk[job % XTK].job = job; g_xtk[job % XTK].tk = tk; pthread_mutex_unlock(&g_xmu); }
|
||||
else {
|
||||
XTRACE_BEGIN("dm-x-frame");
|
||||
// 按同一线程的累计CPU差统计整个翻译帧(回放、出图均含);不把GPU/交换链等待当CPU负载。
|
||||
// Difference this thread's cumulative CPU across whole translation frames (replay and present); GPU/swapchain waits are not CPU load.
|
||||
if (!g_x_sync && pace_adapt_enabled()) {
|
||||
static nvn_frame_cpu_window sample; double ms;
|
||||
uint64_t cpu = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID);
|
||||
if (!cpu || cpu < sample.previous) atomic_store(&g_pa_xcpu_ms, -1); // 读钟失败/重置后不沿用旧负载 | Do not retain stale load after clock failure/reset
|
||||
if (nvn_frame_cpu_sample(&sample, cpu, &ms)) atomic_store(&g_pa_xcpu_ms, ms);
|
||||
}
|
||||
mtl_set_frame(j->frame);
|
||||
// 翻译线程与游戏主线程同级:时间约束(实时)线程,周期 = 出图周期,计算量按本线程每帧 CPU 的 p90 自动声明(同取图处的主线程;确定性时钟下不声明)
|
||||
// The translation thread has the same standing as the game main thread: a time-constraint (real-time) thread, period = present period, computation declared automatically from the p90 of this thread's per-frame CPU (same as the main thread at acquire; not declared under the deterministic clock)
|
||||
uint64_t pn = (uint64_t)(j->period * 1e9); static uint64_t rt_p;
|
||||
if (!g_x_sync && !dm_detclock_enabled()) { if (pn && rt_p != pn) { rt_p = pn; set_time_constraint(&g_rt_xlat, pn); } rt_comp_tick(&g_rt_xlat, pn); }
|
||||
XTRACE_END();
|
||||
}
|
||||
}
|
||||
static void *x_thread(void *a) {
|
||||
(void)a; pthread_setname_np("nvn-translate"); g_x_port = pthread_mach_thread_np(pthread_self());
|
||||
(void)a;
|
||||
#ifdef __APPLE__
|
||||
pthread_setname_np("nvn-translate");
|
||||
#else
|
||||
// 安卓命名接口要求线程句柄,优先级在目标线程设置。
|
||||
// Android naming takes a thread handle; apply priority on the target thread.
|
||||
pthread_setname_np(pthread_self(), "nvn-translate");
|
||||
pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
|
||||
#ifdef __OHOS__
|
||||
{ void front_pin_fast(const char *who); void front_gtx_register(int); front_pin_fast("nvn-translate"); front_gtx_register(1); } // 鸿蒙:翻译线程绑到最高频的核(调度器一直放在中核)| HarmonyOS: pin the translation thread to the fastest cores (the scheduler kept it on mid cores)
|
||||
#endif
|
||||
#endif
|
||||
g_x_port = pthread_mach_thread_np(pthread_self());
|
||||
pthread_mutex_lock(&g_xmu);
|
||||
for (;;) {
|
||||
while (g_xq_done == g_xq_in) pthread_cond_wait(&g_xcv, &g_xmu);
|
||||
@@ -882,14 +989,19 @@ static void *x_thread(void *a) {
|
||||
pthread_mutex_unlock(&g_xmu);
|
||||
x_run(&j, job);
|
||||
pthread_mutex_lock(&g_xmu);
|
||||
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
|
||||
g_xq_done = job; XTRACE_COUNT("dm-x-done-job", job);
|
||||
if (j.kind == XJ_SUBMIT) { g_xsub_done = j.sub; XTRACE_COUNT("dm-x-sub-done", g_xsub_done); } pthread_cond_broadcast(&g_xcv);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
static void x_start(void) {
|
||||
const char *e = getenv("DM_NVN_SYNC"); g_x_sync = e && atoi(e);
|
||||
if (g_x_sync) { LOG("[nvn] DM_NVN_SYNC=1:翻译在提交线程上同步做(对照档)"); return; }
|
||||
pthread_attr_t at; pthread_attr_init(&at); pthread_attr_set_qos_class_np(&at, QOS_CLASS_USER_INTERACTIVE, 0); pthread_attr_setstacksize(&at, 8 << 20);
|
||||
pthread_attr_t at; pthread_attr_init(&at);
|
||||
#ifdef __APPLE__
|
||||
pthread_attr_set_qos_class_np(&at, QOS_CLASS_USER_INTERACTIVE, 0);
|
||||
#endif
|
||||
pthread_attr_setstacksize(&at, 8 << 20);
|
||||
pthread_t t; if (pthread_create(&g_x_thr, &at, x_thread, NULL)) { LOG("【红】翻译线程起不来,改为同步翻译"); g_x_sync = 1; } else LOG("[nvn] 翻译线程已起:提交 / 出图在翻译线程上按序执行(队列 %d 项)", XQ);
|
||||
pthread_attr_destroy(&at);
|
||||
}
|
||||
@@ -899,9 +1011,14 @@ static uint64_t x_push(xjob *j) { // 返回任务号 | Returns the job number
|
||||
while (g_xq_in - g_xq_done >= XQ) pthread_cond_wait(&g_xcv, &g_xmu);
|
||||
if (j->kind == XJ_SUBMIT) j->sub = atomic_fetch_add(&g_x_subs, 1) + 1;
|
||||
uint64_t job = ++g_xq_in;
|
||||
#ifdef __OHOS__
|
||||
if (j->kind == XJ_FRAME) g_x_trace_frame = j->frame; else j->frame = g_x_trace_frame;
|
||||
#endif
|
||||
XTRACE_COUNT("dm-x-enqueue-job", job); XTRACE_COUNT("dm-x-enqueue-kind", j->kind);
|
||||
XTRACE_COUNT("dm-x-enqueue-sub", j->sub); XTRACE_COUNT("dm-x-enqueue-frame", j->frame);
|
||||
if (g_x_sync) { // 当场执行:单线程提交时与旧路径同序 | Run in place: with single-thread submission the order is the same as the old path
|
||||
pthread_mutex_unlock(&g_xmu); x_run(j, job); pthread_mutex_lock(&g_xmu);
|
||||
g_xq_done = job; pthread_cond_broadcast(&g_xcv);
|
||||
g_xq_done = job; XTRACE_COUNT("dm-x-done-job", job); pthread_cond_broadcast(&g_xcv);
|
||||
} else { g_xq[job % XQ] = *j; pthread_cond_broadcast(&g_xcv); }
|
||||
pthread_mutex_unlock(&g_xmu);
|
||||
return job;
|
||||
@@ -909,6 +1026,22 @@ static uint64_t x_push(xjob *j) { // 返回任务号 | Returns the job number
|
||||
static void x_wait(uint64_t job) { pthread_mutex_lock(&g_xmu); while (g_xq_done < job) pthread_cond_wait(&g_xcv, &g_xmu); pthread_mutex_unlock(&g_xmu); }
|
||||
static void x_drain(void) { pthread_mutex_lock(&g_xmu); uint64_t job = g_xq_in; pthread_mutex_unlock(&g_xmu); x_wait(job); }
|
||||
static uint64_t x_fence(void) { return atomic_load(&g_x_subs); }
|
||||
// 等翻译线程把第 sub 次提交翻完(栅栏值 ≤ 已翻译数才去问引擎);timeout 纳秒,超时返回 0。同步翻译模式提交当场执行,不用等
|
||||
// Wait until the translation thread has translated submit number `sub` (the engine is asked about a fence only once it has been translated); timeout in ns, returns 0 on timeout.
|
||||
// In synchronous translation mode submits execute in place, so there is nothing to wait for
|
||||
static int x_wait_sub(uint64_t sub, uint64_t timeout) {
|
||||
if (g_x_sync) return 1;
|
||||
XTRACE_BEGIN("dm-x-wait-sub"); XTRACE_COUNT("dm-x-wait-target", sub);
|
||||
pthread_mutex_lock(&g_xmu); int ok = 1;
|
||||
XTRACE_COUNT("dm-x-wait-done-in", g_xsub_done);
|
||||
if (g_xsub_done < sub) {
|
||||
if (timeout >= 3600000000000ull) while (g_xsub_done < sub) pthread_cond_wait(&g_xcv, &g_xmu);
|
||||
else { struct timespec d; clock_gettime(CLOCK_REALTIME, &d); uint64_t ns = (uint64_t)d.tv_nsec + timeout % 1000000000ull; d.tv_sec += (time_t)(timeout / 1000000000ull + ns / 1000000000ull); d.tv_nsec = (long)(ns % 1000000000ull);
|
||||
while (g_xsub_done < sub) if (pthread_cond_timedwait(&g_xcv, &g_xmu, &d)) { ok = g_xsub_done >= sub; break; } }
|
||||
}
|
||||
XTRACE_COUNT("dm-x-wait-done-out", g_xsub_done);
|
||||
pthread_mutex_unlock(&g_xmu); XTRACE_END(); return ok;
|
||||
}
|
||||
static uint64_t x_present_ticket(uint64_t job) { // 出图任务执行完后换来的出图线程票号(0 = 那次出图被丢弃,不用等) | Present thread ticket obtained after the present job runs (0 = that present was dropped, nothing to wait for)
|
||||
x_wait(job);
|
||||
pthread_mutex_lock(&g_xmu); uint64_t tk = g_xtk[job % XTK].job == job ? g_xtk[job % XTK].tk : 0; int lost = g_xtk[job % XTK].job != job; pthread_mutex_unlock(&g_xmu);
|
||||
@@ -938,7 +1071,7 @@ static const char *const g_nops[] = {
|
||||
"nvnCommandBufferWaitSync", // 每帧 1 次。GPU 侧等一个同步对象,不是 CPU 读回(CPU 等 GPU 走 nvnSyncWait,已按栅栏真等)。同步对象只有两种来源: | 1 time per frame. A GPU-side wait on a sync object, not a CPU readback (CPU waits on the GPU via nvnSyncWait, which already truly waits on the fence). Sync objects have only two sources:
|
||||
// QueueFenceSync 与 WindowAcquireTexture,栅栏值都取「记录时已提交的最大值」,含 WaitSync 的命令缓冲必在其后提交到同一条队列。
|
||||
// 翻译层只有一条 Metal 队列(游戏各帧与出图都提交到它):Metal 4 每个编码器开头都设「等队列上此前全部阶段」的屏障,
|
||||
// 老接口(iOS 18)资源都是跟踪模式、参数块引用的逐个 useResource,读写先后由 Metal 保证——两支都已按序,空跑即正确。
|
||||
// 旧接口(iOS 18)资源都是跟踪模式、参数块引用的逐个 useResource,读写先后由 Metal 保证——两支都已按序,空跑即正确。
|
||||
// 前提是只有一条队列:哪天加第二条(如异步计算),这里必须改成真等
|
||||
// For QueueFenceSync and WindowAcquireTexture, the fence value is "the max already submitted at recording time", and a command buffer containing WaitSync is always submitted after it to the same queue.
|
||||
// The translation layer has only one Metal queue (all game frames and presents are submitted to it): Metal 4 sets a barrier at the start of each encoder that "waits for all previous stages on the queue",
|
||||
@@ -1005,8 +1138,10 @@ static void sleep_until_ns(uint64_t dl);
|
||||
static uint64_t present_period(const win_t *o);
|
||||
__attribute__((weak)) void dm_main_yield_stats(uint64_t *n, uint64_t *ns) { *n = 0; *ns = 0; } // 宿主 hle_thread.c 提供真值;图形单测里为 0 | The host's hle_thread.c provides the ground truth; 0 in graphics unit tests
|
||||
__attribute__((weak)) uint32_t dm_guest_work_qos(unsigned *count) { if (count) *count = 0; return QOS_CLASS_UNSPECIFIED; }
|
||||
__attribute__((weak)) void dm_hle_wake_counts(uint64_t *wakes, uint64_t *skips) { *wakes = 0; *skips = 0; }
|
||||
extern uint32_t mtl_present_qos(void);
|
||||
static uint64_t g_frame;
|
||||
static uint64_t g_pa_wait; // 本帧取图里节拍等待(自适应出图档用) | pacing wait inside acquire this frame (for the adaptive present tier)
|
||||
static uint64_t g_acq_wait_ns, g_pq_wait_ns; // 取图里节拍等待 / 等出图队列归还的累计,出图时按帧记(一帧内可有多次取图) | Accumulated display-link wait / wait for the present queue to return inside acquire, recorded per frame at present (there can be several acquires within one frame)
|
||||
uint64_t dm_nvn_frame_count(void) { return g_frame; }
|
||||
extern uint64_t g_t0_ns; // 宿主进程起点(main.c;UIMSG 时间戳同基) | Host process start point (main.c; same base as the UIMSG timestamps)
|
||||
@@ -1029,12 +1164,12 @@ NVN(nvnWindowAcquireTexture, NVNwindowAcquireTextureResult, NVNwindow *w, NVNsyn
|
||||
if (pace < 0) { const char *e = getenv("DM_DETCLOCK_PACE"), *d = getenv("DM_DETCLOCK"); step = d ? strtoull(d, 0, 0) : 0; pace = e && atoi(e) && step; }
|
||||
if (pace) { if (last && now_ns() < last + step) sleep_until_ns(last + step); last = now_ns(); }
|
||||
}
|
||||
g_acq_wait_ns += wait; trow(g_frame, "@late_ms", wait ? (now_ns() - at) / 1e6 : 0);
|
||||
g_acq_wait_ns += wait; g_pa_wait += wait; trow(g_frame, "@late_ms", wait ? (now_ns() - at) / 1e6 : 0);
|
||||
// 该张上一次出图还没被出图线程处理完(显示跟不上、落后一整轮交换链):等它归还,再交给游戏画
|
||||
// The previous present of this texture has not yet been processed by the present thread (display cannot keep up, a whole swapchain round behind): wait for it to be returned, then hand it to the game to draw
|
||||
uint64_t tk = *idx < 4 ? o->ticket[*idx] : 0;
|
||||
if (tk) { uint64_t w0 = now_ns(), rt = x_present_ticket(tk); if (rt) mtl_present_wait(rt); g_pq_wait_ns += now_ns() - w0; } // tk 是翻译队列的出图任务号 | tk is the translation queue's present job number
|
||||
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
|
||||
if (s) { ((sync_t *)s)->fenced = 1; ((sync_t *)s)->fence = x_fence(); g_acq_sync = s; } // 交换链贴图在此前的提交完成后可用 | The swapchain texture becomes available once the commits before this point have completed
|
||||
return NVN_WINDOW_ACQUIRE_TEXTURE_RESULT_SUCCESS;
|
||||
}
|
||||
|
||||
@@ -1139,6 +1274,7 @@ static void tsummary(uint64_t frame) {
|
||||
static uint64_t pyn, pyns; uint64_t yn = 0, yns = 0; dm_main_yield_stats(&yn, &yns);
|
||||
LOG("[nvn] 翻译细项 至帧 %llu:每帧提交 周期 %.2f M(每条指令 %.2f 周期)、CPU %.3f ms 其中内核态 %.3f ms、墙钟 %.3f ms;平均主频 %.2f GHz(周期 / CPU 时间);本线程 QoS %#x;分配器池 %d 个、累计等 GPU %llu 次;实时声明计算 %.2f ms;主线程让出 每帧 %.0f 次 / %.3f ms", frame,
|
||||
cyc / 1e6 / nf, cyc / (double)(ci - pi), cpu / 1e6 / nf, (double)(ck - pk) / 1e6 / nf, (double)(cw - pw) / 1e6 / nf, cpu > 0 ? cyc / cpu : 0, (unsigned)qc, an, (unsigned long long)aw, g_rt_main.comp_ms, (double)(yn - pyn) / nf, (double)(yns - pyns) / 1e6 / nf); pyn = yn; pyns = yns; }
|
||||
#ifdef __APPLE__
|
||||
if (frame % 300 == 0) { unsigned wn = 0; uint32_t wq = dm_guest_work_qos(&wn); thread_extended_info_data_t xi; mach_msg_type_number_t xc = THREAD_EXTENDED_INFO_COUNT; int okx = thread_info(pthread_mach_thread_np(pthread_self()), THREAD_EXTENDED_INFO, (thread_info_t)&xi, &xc) == KERN_SUCCESS;
|
||||
thread_time_constraint_policy_data_t tp; mach_msg_type_number_t tc = THREAD_TIME_CONSTRAINT_POLICY_COUNT; boolean_t def = 0; int rt_live = thread_policy_get(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&tp, &tc, &def) == KERN_SUCCESS && !def; // def = 1:实时策略没在生效(没设上 / 被撤) | def = 1: the real-time policy is not in effect (never set / revoked)
|
||||
LOG("[nvn] 线程策略:主线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);工作线程 %u 条 QoS %#x;出图 QoS %#x", g_rt_main.comp_ms, g_rt_main.period_ms, rt_live ? "在生效" : "未生效", okx ? xi.pth_curpri : -1, okx ? xi.pth_priority : -1, okx ? xi.pth_policy : -1, wn, wq, mtl_present_qos());
|
||||
@@ -1148,6 +1284,7 @@ static void tsummary(uint64_t frame) {
|
||||
qos_class_t yq = QOS_CLASS_UNSPECIFIED; int yr = 0; pthread_get_qos_class_np(g_x_thr, &yq, &yr);
|
||||
LOG("[nvn] 线程策略:翻译线程 实时 计算 %.2f ms / 周期 %.2f ms,实时策略%s,当前优先级 %d(基础 %d,调度类 %d);QoS %#x", g_rt_xlat.comp_ms, g_rt_xlat.period_ms, y_live ? "在生效" : "未生效",
|
||||
oky ? yi.pth_curpri : -1, oky ? yi.pth_priority : -1, oky ? yi.pth_policy : -1, (unsigned)yq); } }
|
||||
#endif
|
||||
py = cy; pk = ck; pw = cw; }
|
||||
pi = ci; pc = cc; pd = dr_; pf = frame; }
|
||||
uint64_t up, re, fa, pr; mtl_pkg_stats(&up, &re); nvn_dirty_stats(&fa, &pr);
|
||||
@@ -1201,10 +1338,17 @@ static void slow_emit(uint64_t f) {
|
||||
static void set_time_constraint_comp(rt_decl *d, uint64_t period_ns, uint64_t comp_ns) {
|
||||
static mach_timebase_info_data_t tb; if (!tb.denom) mach_timebase_info(&tb);
|
||||
if (comp_ns < 1000000ull) comp_ns = 1000000ull; if (comp_ns > period_ns * 9 / 10) comp_ns = period_ns * 9 / 10;
|
||||
#ifdef __APPLE__
|
||||
thread_time_constraint_policy_data_t p = {
|
||||
.period = (uint32_t)(period_ns * tb.denom / tb.numer), .computation = (uint32_t)(comp_ns * tb.denom / tb.numer),
|
||||
.constraint = (uint32_t)(period_ns * tb.denom / tb.numer), .preemptible = 1};
|
||||
kern_return_t kr = thread_policy_set(pthread_mach_thread_np(pthread_self()), THREAD_TIME_CONSTRAINT_POLICY, (thread_policy_t)&p, THREAD_TIME_CONSTRAINT_POLICY_COUNT);
|
||||
#else
|
||||
// 安卓没有时间约束线程策略:同一份声明(帧期限 + 每帧工作量)交给前端走系统性能提示(APerformanceHint),未实现时视为失败
|
||||
// Android has no time-constraint thread policy: the same declaration (frame deadline + per-frame workload) is handed to the front end for the system performance hint (APerformanceHint); treated as failure when not implemented
|
||||
int front_perf_hint(uint64_t period_ns, uint64_t comp_ns) __attribute__((weak));
|
||||
kern_return_t kr = front_perf_hint && !front_perf_hint(period_ns, comp_ns) ? KERN_SUCCESS : KERN_FAILURE;
|
||||
#endif
|
||||
if (kr == KERN_SUCCESS) { d->comp_ms = comp_ns / 1e6; d->period_ms = period_ns / 1e6; }
|
||||
LOG("[nvn] %s时间约束策略(周期 %.3f ms、计算 %.3f ms)%s", d->who, period_ns / 1e6, comp_ns / 1e6, kr == KERN_SUCCESS ? "已设" : "设置失败");
|
||||
}
|
||||
@@ -1232,6 +1376,17 @@ static void sleep_until_ns(uint64_t dl) { // 单调时钟上的绝对时刻 |
|
||||
// Present is fixed at 60 Hz: the adaptive mechanism stepped down at frame 60 in 24/24 real-device logs and never came back up, so for this phase 60 fps is the hard floor.
|
||||
// DM_PRESENT_HZ=0 (uncapped frame rate) serves only as an explicit performance profiling switch: some of the game's UI logic counts frames (with the same save, uncapped gives
|
||||
// 4181 SaveIndicatorPanel entries and capped at 60 fps gives 0, which matches the ground truth), so uncapped is a semantically wrong way to run and must not be used as a criterion / cross-check / default. Unit tests set it directly with nvn_present_config
|
||||
static _Atomic int g_pa = -1; static int g_pa_k; static double g_pa_ema, g_pa_screen_hz; static unsigned g_pa_up; static uint64_t g_pa_last;
|
||||
static int pace_adapt_enabled(void) {
|
||||
if (g_pa < 0) { const char *e = getenv("DM_PACE_ADAPT"); g_pa = e && *e == '1'; }
|
||||
return g_pa;
|
||||
}
|
||||
static double present_auto_hz(double screen_hz) {
|
||||
// 自适应目标是最高60,而旧Apple策略是至少60;两者不共用取整方向。首帧/刷新率改变也受上限约束。
|
||||
// Adaptive pacing caps at 60; the legacy Apple policy has a floor of 60. Cap the first frame and refresh changes too.
|
||||
if (pace_adapt_enabled() && screen_hz > 0) return screen_hz / nvn_adaptive_divisor(screen_hz, g_pa_k, g_pa_screen_hz);
|
||||
return dm_pace_hz(screen_hz, 60);
|
||||
}
|
||||
static int g_hz = -1, g_display_mode, g_hz_auto; // g_hz_auto:有窗口、没用 DM_PRESENT_HZ 钉住——帧率跟着窗口所在屏的刷新率取整除档(每帧重读,换屏即换) | g_hz_auto: has a window and not pinned by DM_PRESENT_HZ; the frame rate takes the evenly dividing tier of the refresh rate of the screen the window is on (re-read every frame, changes with the screen)
|
||||
void nvn_present_config(int hz, int display_mode) { g_hz = hz; g_display_mode = display_mode; g_hz_auto = 0; }
|
||||
double front_display_refresh(char *name, size_t n);
|
||||
@@ -1252,14 +1407,64 @@ static void present_cfg(const win_t *o) {
|
||||
// (the save indicator is exempted as a timing race), and the timing differences of key messages are within game mode's own noise band; proof after entering a run is still missing, pending action script coverage
|
||||
const char *m = getenv("DM_PRESENT_INTERVAL"); g_display_mode = m ? !strcmp(m, "display") : scr > 0;
|
||||
char name[128]; front_display_refresh(name, sizeof name);
|
||||
if (g_hz_auto) LOG("[nvn] 出图节拍 %.2f Hz,间隔模式 %s(游戏设的出图间隔 %d;屏幕 %s,刷新率 %.2f Hz,取整除的一档)", dm_pace_hz(mtl_display_refresh(), 60), g_display_mode ? "display(每节拍一帧,剪口)" : "game(原版语义)", o->interval,
|
||||
if (g_hz_auto) LOG("[nvn] 出图节拍 %.2f Hz,间隔模式 %s(游戏设的出图间隔 %d;屏幕 %s,刷新率 %.2f Hz,取整除的一档)", present_auto_hz(mtl_display_refresh()), g_display_mode ? "display(每节拍一帧,剪口)" : "game(原版语义)", o->interval,
|
||||
*name ? name : "主屏", mtl_display_refresh());
|
||||
else LOG("[nvn] 出图节拍 %d Hz,间隔模式 %s(游戏设的出图间隔 %d;%s)", g_hz, g_display_mode ? "display(每节拍一帧,剪口)" : "game(原版语义)", o->interval,
|
||||
e ? "DM_PRESENT_HZ 钉住" : "无窗口,固定 60 Hz");
|
||||
}
|
||||
// 自适应出图档(DM_PACE_ADAPT=1;鸿蒙缺省开):跑不到 60 档时,原节拍器从不起作用,游戏帧的开始时刻跟着 GPU 栅栏忽早忽晚(实测 8 / 48 ms 交替),
|
||||
// 游戏按墙钟推进动画,屏上就是「卡一下、快进一下」。这里按屏幕刷新率的整数分之一(120 Hz:60 / 40 / 30 / 24 / 20)选当前撑得住的最高一档,
|
||||
// 让节拍器按这一档均匀放行游戏帧。撑不住的判据取整条流水线的瓶颈:max(游戏线程每帧 CPU 的均值,翻译线程真实每帧 CPU,GPU 每帧时间)。
|
||||
// 降档:瓶颈超过本档周期 3% 立即降;升档:瓶颈低于上一档周期的 88%、连续 90 帧才升,避免来回跳。
|
||||
// Adaptive present tier (DM_PACE_ADAPT=1; on by default on HarmonyOS): below the 60 tier the original pacer never engages, so game frame starts follow the GPU fences early
|
||||
// or late (measured alternating 8 / 48 ms); the game advances animation by wall clock, so the screen shows "stall, then fast-forward". This picks, among integer fractions of
|
||||
// the screen refresh (120 Hz: 60 / 40 / 30 / 24 / 20), the highest tier currently sustainable and lets the pacer release game frames evenly at it. "Sustainable" uses the
|
||||
// whole pipeline's bottleneck: max(mean game-thread CPU per frame, actual translation-thread CPU per frame, GPU time per frame).
|
||||
// Step down at once when the bottleneck exceeds this tier's period by 3%; step up only after 90 consecutive frames below 88% of the faster tier's period, to avoid flapping.
|
||||
__attribute__((weak)) uint64_t dm_present_late_count(void) { return 0; } __attribute__((weak)) double xbg_recent_gpu_ms(void) { return -1; } // 空的弱定义(不是弱声明):苹果链接器要求弱引用链接时有定义;Vulkan 后端 / 鸿蒙平台层给强定义 | empty weak definitions (not declarations): Apple's linker needs a weak reference to resolve; the Vulkan backend / HarmonyOS platform give the strong ones
|
||||
static void pace_adapt_tick(double screen_hz) {
|
||||
if (!pace_adapt_enabled() || screen_hz <= 0) return;
|
||||
// 游戏侧取本线程 CPU 时间(不含任何等待):墙钟减节拍等待会把下游等待(合成器按时放帧 → 翻译线程等交换链 → 游戏等翻译)算进去,形成越降越慢的正反馈
|
||||
// Game side uses this thread's CPU time (no waits at all): wall clock minus pacing wait would count downstream waits (compositor releasing frames on time → translation waits for
|
||||
// the swapchain → game waits for translation), a positive feedback loop that keeps lowering the tier
|
||||
uint64_t now = now_ns(), cpu = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID); static uint64_t pcpu; g_pa_wait = 0;
|
||||
if (!g_pa_last || !pcpu || !cpu || cpu < pcpu) { g_pa_last = now; pcpu = cpu; return; } // 差值前校验,避免无符号下溢 | Validate before unsigned subtraction
|
||||
double iv = (now - g_pa_last) / 1e6, busy = (cpu - pcpu) / 1e6; g_pa_last = now; pcpu = cpu;
|
||||
if (iv > 250) return; // 读取画面 / 卡住的帧不计 | loading-screen / stuck frames are not counted
|
||||
g_pa_ema += (busy - g_pa_ema) / 16;
|
||||
// 同步翻译运行在游戏线程上,其CPU已含在游戏帧CPU里,不再作为另一条流水线重复统计。
|
||||
// Synchronous translation runs on the game thread and is already included in the game's frame CPU.
|
||||
double need = g_pa_ema, gm = xbg_recent_gpu_ms ? xbg_recent_gpu_ms() : -1, cm = g_x_sync ? -1 : atomic_load(&g_pa_xcpu_ms);
|
||||
if (gm > need) need = gm; if (cm > need) need = cm;
|
||||
int kmin = nvn_adaptive_min_divisor(screen_hz), kmax = nvn_adaptive_max_divisor(screen_hz);
|
||||
g_pa_k = nvn_adaptive_divisor(screen_hz, g_pa_k, g_pa_screen_hz); // 刷新率变了(LTPO):保持周期不变 | refresh rate changed (LTPO): keep the period
|
||||
g_pa_screen_hz = screen_hz;
|
||||
double per = g_pa_k * 1000.0 / screen_hz;
|
||||
// 按「实际是否赶上上屏节拍」决定档位,不按负载时间:降到慢档后系统会降 GPU / CPU 频率,负载时间随之拉长(Mate90:GPU 15 → 28 ms),
|
||||
// 按负载判升档就永远回不去(DVFS 锁死)。降档:最近 60 帧里错过节拍 ≥ 6 帧;升档:稳定一段时间后试快一档,先放 20 帧让频率爬升,
|
||||
// 再看 60 帧,错过 ≥ 4 帧就退回且下次试升间隔翻倍(3 s 起,最多 60 s)。错过节拍由平台出图计数(dm_present_late_count),没有就按游戏帧间隔超出周期 25% 计。
|
||||
// Decide the tier by whether frames actually make their display slots, not by load times: after stepping down the system lowers GPU / CPU clocks and load times stretch
|
||||
// (Mate90: GPU 15 → 28 ms), so a load-based step-up never fires again (DVFS lock-in). Step down: >= 6 of the last 60 frames missed their slot; step up: after a stable period try
|
||||
// the faster tier, skip 20 frames while clocks ramp, then judge 60 frames; >= 4 misses reverts and doubles the next probe interval (from 3 s, at most 60 s). Misses come from the
|
||||
// platform present counter (dm_present_late_count); without it, a game frame interval 25% over the period counts as a miss.
|
||||
static unsigned wn, skip, misses_local; static int probing; static uint64_t late0, stable_since, backoff = 3000000000ull;
|
||||
uint64_t lc = dm_present_late_count ? dm_present_late_count() : 0;
|
||||
if (!dm_present_late_count && iv > per * 1.25) misses_local++;
|
||||
if (!stable_since) { stable_since = now; late0 = lc; }
|
||||
if (skip) { skip--; late0 = lc; wn = 0; misses_local = 0; return; }
|
||||
if (++wn < 60) return;
|
||||
unsigned misses = dm_present_late_count ? (unsigned)(lc - late0) : misses_local; wn = 0; late0 = lc; misses_local = 0;
|
||||
if (probing) {
|
||||
probing = 0; stable_since = now;
|
||||
if (misses >= 4 && g_pa_k < kmax) { g_pa_k++; backoff = backoff * 2 > 60000000000ull ? 60000000000ull : backoff * 2; LOG("[nvn] 出图档 试升失败,退回 %.1f FPS(60 帧错过 %u 帧;下次 %.0f s 后再试)", screen_hz / g_pa_k, misses, backoff / 1e9); }
|
||||
else { backoff = 3000000000ull; LOG("[nvn] 出图档 ↑ %.1f FPS 站稳(60 帧错过 %u 帧;游戏 %.1f / 翻译 %.1f / GPU %.1f ms)", screen_hz / g_pa_k, misses, g_pa_ema, cm, gm); }
|
||||
} else if (misses >= 6 && g_pa_k < kmax) { g_pa_k++; stable_since = now; LOG("[nvn] 出图档 ↓ %.1f FPS(60 帧错过 %u 帧;游戏 %.1f / 翻译 %.1f / GPU %.1f ms)", screen_hz / g_pa_k, misses, g_pa_ema, cm, gm); }
|
||||
else if (g_pa_k > kmin && now - stable_since > backoff) { g_pa_k--; probing = 1; skip = 20; LOG("[nvn] 出图档 试升 %.1f FPS", screen_hz / g_pa_k); }
|
||||
(void)need; (void)per;
|
||||
}
|
||||
static uint64_t present_period(const win_t *o) {
|
||||
present_cfg(o);
|
||||
int itv = g_display_mode ? 1 : o->interval > 0 ? o->interval : 1; double hz = g_hz_auto ? dm_pace_hz(mtl_display_refresh(), 60) : g_hz; // 省电模式的 30 帧由显示节拍决定,这里照旧按 60 档(60 / 120 Hz 屏与原先逐字相同) | Power saving 30 fps is determined by display pacing; here the 60 tier is used as before (identical to before on 60 / 120 Hz screens)
|
||||
int itv = g_display_mode ? 1 : o->interval > 0 ? o->interval : 1; double hz = g_hz_auto ? present_auto_hz(mtl_display_refresh()) : g_hz; // 自适应档(见 pace_adapt_tick) | adaptive tier (see pace_adapt_tick) // 省电模式的 30 帧由显示节拍决定,这里照旧按 60 档(60 / 120 Hz 屏与原先逐字相同) | Power saving 30 fps is determined by display pacing; here the 60 tier is used as before (identical to before on 60 / 120 Hz screens)
|
||||
return hz > 0 ? (uint64_t)(itv * 1e9 / hz) : 0;
|
||||
}
|
||||
int (*g_nvn_loadscreen_up)(void); // 宿主登记:读取画面此刻是否开着(diag.c 订阅界面消息时填;图形单测里为空 = 不设闸) | host registration: whether the loading screen is up right now (filled in when diag.c subscribes to UI messages; null in graphics unit tests = no gate)
|
||||
@@ -1296,7 +1501,7 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
}
|
||||
if (prev_in) {
|
||||
double fr = (t0 - prev_in) / 1e6, wk = (t0 - prev_out) / 1e6, nv = atomic_exchange(&g_nvn_ns, 0) / 1e6;
|
||||
tpush(0, fr); tpush(1, wk); tpush(2, nv);
|
||||
tpush(0, fr); tpush(1, wk); tpush(2, nv); XTRACE_COUNT("dm-game-frame", f); XTRACE_COUNT("dm-frame-ms", (int64_t)fr);
|
||||
trow(f, "@frame_ms", fr); trow(f, "@work_ms", wk); trow(f, "@nvn_ms", nv);
|
||||
// 慢帧归因(只在开 DM_NVN_TSV 时取):本帧出图线程 CPU 时间(换线程记 −1)、进程全部线程 CPU、取图等待按帧累计、出图调用时刻(与 GPU / 上屏时刻同基:进程起点 ms)
|
||||
// Slow-frame attribution (taken only when DM_NVN_TSV is on): this frame's present-thread CPU time (−1 if the thread changed), CPU of all threads in the process, acquire wait accumulated per frame, present call time (same base as the GPU / on-screen present times: ms since process start)
|
||||
@@ -1338,6 +1543,12 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
}
|
||||
plib = lib_; ppso = pso_;
|
||||
trow(f, "@t_s", (now_ns() - g_t0_ns) / 1e9);
|
||||
// 单调时钟的绝对秒数:按时间轮换的进程内对照(gfx-ab-toggle、DM_HLE_SPIN_AB)据此给每帧分相位
|
||||
// absolute monotonic seconds, so time-based in-process A/B runs (gfx-ab-toggle, DM_HLE_SPIN_AB) can split frames by phase
|
||||
{ struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); trow(f, "@mono_s", ts.tv_sec + ts.tv_nsec / 1e9); }
|
||||
// 客体线程唤醒次数,及其中目标在自旋、省掉信号的次数(hle_thread.c 的 wake)
|
||||
// Guest thread wakes, and those whose target was spinning so no signal was sent (hle_thread.c's wake)
|
||||
{ static uint64_t pw, pk; uint64_t w, k; dm_hle_wake_counts(&w, &k); trow(f, "@wakes", (double)(w - pw)); trow(f, "@wake_skips", (double)(k - pk)); pw = w; pk = k; }
|
||||
trow(f, "@drawable_ms", mtl_drawable_ns_take() / 1e6);
|
||||
trow(f, "@sub_wall_ms", atomic_exchange(&g_sub_wall_ns, 0) / 1e6); trow(f, "@sub_cpu_ms", atomic_exchange(&g_sub_cpu_ns, 0) / 1e6); trow(f, "@sub_instr", (double)atomic_exchange(&g_sub_instr, 0));
|
||||
} else atomic_store(&g_nvn_ns, 0);
|
||||
@@ -1352,6 +1563,10 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
if (on && r->f == f - 8 && f - 8 > 0 && (lf || lg)) { char b[512];
|
||||
snprintf(b, sizeof b, "帧 %llu(%.2f s)整帧 %.1f ms,提交+出图 %.1f ms,GPU %.1f ms;新建管线 %u 条 + 着色器库 %u 个共 %.1f ms;上传贴图 首传 %u 张 + 重传 %u 次 %.1f MB / %.1f ms",
|
||||
(unsigned long long)r->f, r->t_s, r->fr, r->nv, g, r->pso, r->lib, r->make_ms, r->up, r->rup, r->up_mb, r->up_ms);
|
||||
// 整帧不长、只因 GPU 才记的行标出来:没有 GPU 读数的后端(安卓原先如此)只记得到整帧长的那种,分开数才能和旧记录比
|
||||
// Lines logged only because of the GPU, for a frame that was not long, are marked: a backend without GPU readings (Android until
|
||||
// now) logged only frames that were long, so counting the two apart keeps comparisons with older logs possible
|
||||
if (!lf) strlcat(b, ";整帧不长,GPU 长", sizeof b);
|
||||
// 可见性:长帧「晚出来」的那段时间屏幕上停着的是上一帧;上一帧若是读取画面(或本帧自己就是),玩家看到的只是读取画面多停了一下,没有运动被打断
|
||||
// Visibility: during the time a long frame "comes out late", what stays on screen is the previous frame; if the previous frame was a loading screen (or this frame itself is one), all the player sees is the loading screen staying a bit longer, with no motion interrupted
|
||||
const lf_rec *pv = &g_lf[(f - 9) % LFN]; int hidden = r->ls || (f >= 9 && pv->f == f - 9 && pv->ls);
|
||||
@@ -1366,6 +1581,7 @@ NVN(nvnQueuePresentTexture, void, NVNqueue *q, NVNwindow *w, int idx) {
|
||||
{ xjob j = {XJ_FRAME}; j.frame = g_frame; j.period = present_period(o) / 1e9; x_push(&j); } // 帧号随队列生效(见翻译队列说明) | The frame number takes effect in queue order (see the translation queue notes)
|
||||
// 真机语义:出图只入队、立即返回;本帧显示时刻按节拍器排,该贴图到「显示时刻 + 一个周期」才可再获取(阻塞在 AcquireTexture)
|
||||
// Real-device semantics: present only enqueues and returns immediately; this frame's display time is scheduled by the pacer, and the texture can be acquired again only at "display time + one period" (blocking in AcquireTexture)
|
||||
if (g_hz_auto && !dm_detclock_enabled()) pace_adapt_tick(mtl_display_refresh());
|
||||
uint64_t period = present_period(o), now = dm_detclock_enabled() ? guest_ns() : now_ns();
|
||||
nvn_pacer pc = {o->pace};
|
||||
uint64_t slot = now + nvn_pace(&pc, now, period);
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
// 自适应出图的整数分档与线程CPU统计;不改变 nvn_pace.h 的 Apple「至少60」策略。
|
||||
// Integer-divisor adaptive tiers and thread-CPU sampling; leaves nvn_pace.h's Apple "at least 60" policy unchanged.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
static inline int nvn_adaptive_min_divisor(double hz) {
|
||||
double ratio = hz / 60.0;
|
||||
int k = (int)ratio;
|
||||
if (k < ratio) ++k; // ceil:90Hz最高45帧,不能取floor而升到90。| ceil: at 90 Hz cap at 45 fps, never floor to 90.
|
||||
return k > 0 ? k : 1;
|
||||
}
|
||||
static inline int nvn_adaptive_max_divisor(double hz) {
|
||||
int k = (int)(hz / 20.0 + 0.02), lo = nvn_adaptive_min_divisor(hz);
|
||||
return k < lo ? lo : k;
|
||||
}
|
||||
static inline int nvn_adaptive_divisor(double hz, int current, double old_hz) {
|
||||
int lo = nvn_adaptive_min_divisor(hz), hi = nvn_adaptive_max_divisor(hz);
|
||||
int k = current > 0 ? current : lo;
|
||||
if (current > 0 && old_hz > 0 && hz != old_hz) k = (int)(current * hz / old_hz + 0.5);
|
||||
return k < lo ? lo : k > hi ? hi : k;
|
||||
}
|
||||
|
||||
// 输入必须是同一个线程的累计CPU纳秒;60帧窗与原图形负载统计一致,等待不会推进此时钟。
|
||||
// Input is cumulative CPU nanoseconds of the same thread. The 60-frame window matches existing graphics load statistics; waits do not advance this clock.
|
||||
typedef struct { uint64_t previous, sum; unsigned count; } nvn_frame_cpu_window;
|
||||
static inline int nvn_frame_cpu_sample(nvn_frame_cpu_window *s, uint64_t cpu_ns, double *ms) {
|
||||
if (!s->previous || cpu_ns < s->previous) { s->previous = cpu_ns; s->sum = 0; s->count = 0; return 0; }
|
||||
s->sum += cpu_ns - s->previous; s->previous = cpu_ns;
|
||||
if (++s->count < 60) return 0;
|
||||
*ms = s->sum / 60000000.0; s->sum = 0; s->count = 0; return 1;
|
||||
}
|
||||
+18
-18
@@ -15,7 +15,7 @@
|
||||
#include <fcntl.h>
|
||||
#include "nvn_mtl.h"
|
||||
#include "nvn_copy_pitch.h"
|
||||
// 编译期开关 DM_NVN_M3=1:图形后端走老接口(普通命令队列 / 命令缓冲 / 渲染与计算与拷贝编码器,逐槽绑定缓冲,对参数块引用的资源逐个声明),
|
||||
// 编译期开关 DM_NVN_M3=1:图形后端走旧接口(普通命令队列 / 命令缓冲 / 渲染与计算与拷贝编码器,逐槽绑定缓冲,对参数块引用的资源逐个声明),
|
||||
// 目标 macOS 15 / iOS 18。缺省 0 = Metal 4(macOS 26 / iOS 26)。两支共用同一份回放逻辑,分叉处都在 #if DM_NVN_M3 里
|
||||
// Compile-time switch DM_NVN_M3=1: the graphics backend uses the older API (ordinary command queue / command buffers / render, compute and copy encoders, buffers bound per slot, each resource referenced by an argument block declared individually),
|
||||
// target macOS 15 / iOS 18. Default 0 = Metal 4 (macOS 26 / iOS 26). Both branches share the same replay logic, and every divergence is inside #if DM_NVN_M3
|
||||
@@ -90,14 +90,14 @@ static id<MTLCommandQueue> g_q;
|
||||
static id<MTL4CommandQueue> g_q4;
|
||||
static dispatch_queue_t g_feedback_q;
|
||||
#endif
|
||||
// 命令流队列只许一条:游戏的命令缓冲与出图都提交到它(Metal 4 = g_q4,老接口 = g_q;Metal 4 构建里的 g_q 只给 CPU 同步等完的回读 / 截图 / 收尾用)。
|
||||
// 命令流队列只许一条:游戏的命令缓冲与出图都提交到它(Metal 4 = g_q4,旧接口 = g_q;Metal 4 构建里的 g_q 只给 CPU 同步等完的回读 / 截图 / 收尾用)。
|
||||
// WaitSync 空跑即正确靠这个前提(见 hle_nvn.c g_nops 里 WaitSync 的注释):建命令流队列一律经这里,第二次建即报红中止
|
||||
// Only one command queue is allowed: the game's command buffers and presents are all submitted to it (Metal 4 = g_q4, legacy API = g_q; in Metal 4 builds g_q is only for CPU-synchronous readback / screenshots / teardown).
|
||||
// WaitSync being correct as a no-op relies on this (see the WaitSync comment in g_nops of hle_nvn.c): all command queues are created here, and a second creation reports red and aborts
|
||||
static void stream_queue_once(void) { static int n; if (++n > 1) MDIE("【红】建了第 %d 条命令流队列:WaitSync 空跑的前提是只有一条(见 hle_nvn.c g_nops 里 WaitSync 的注释),加队列先把 WaitSync 改成真等", n); }
|
||||
static _Atomic uint32_t g_present_qos;
|
||||
#define ALLOC_MAX 8
|
||||
static int g_alloc_n, g_alloc_cur; // 主提交的在途槽(Metal 4:每槽一个命令分配器;老接口:只用来限制在途提交数) | in-flight slots of the main submission (Metal 4: one command allocator per slot; older API: used only to limit the number of in-flight submissions)
|
||||
static int g_alloc_n, g_alloc_cur; // 主提交的在途槽(Metal 4:每槽一个命令分配器;旧接口:只用来限制在途提交数) | in-flight slots of the main submission (Metal 4: one command allocator per slot; older API: used only to limit the number of in-flight submissions)
|
||||
#if !DM_NVN_M3
|
||||
static id<MTL4CommandAllocator> g_alloc4[ALLOC_MAX]; // 主提交的命令分配器池:开工时挑一个 GPU 已用完的,没有就新建(到上限才等) | Command allocator pool of the main submission: at start pick one the GPU has finished with, create a new one if there is none (wait only at the cap)
|
||||
static id<MTL4CommandAllocator> g_up_alloc4[3];
|
||||
@@ -146,7 +146,7 @@ static _Atomic int g_up_pending;
|
||||
static pthread_mutex_t g_res_mu = PTHREAD_MUTEX_INITIALIZER; // 驻留集专用锁:res_add 会在持 g_mu 的路径里调用(arena_new),不能共用 g_mu | Dedicated lock for the residency set: res_add is called on paths that hold g_mu (arena_new), so it cannot share g_mu
|
||||
static NSHashTable *g_res_objects;
|
||||
#if DM_NVN_M3
|
||||
// 老接口按「缓冲对象 + 偏移」绑定,而回放层手里是显卡地址:登记过的缓冲(内存池的零拷贝缓冲、参数区块、暂存块等,几十个)按地址区间反查。
|
||||
// 旧接口按「缓冲对象 + 偏移」绑定,而回放层手里是显卡地址:登记过的缓冲(内存池的零拷贝缓冲、参数区块、暂存块等,几十个)按地址区间反查。
|
||||
// 弱引用登记(__unsafe_unretained + 撤驻留时摘掉);最近命中的那一项先试——同一通道里的绑定几乎都落在同一两个缓冲上
|
||||
// The older API binds by "buffer object + offset", while the replay layer holds GPU addresses: registered buffers (zero-copy buffers of memory pools, argument blocks, staging blocks and so on, a few dozen) are looked up by address range.
|
||||
// Registered by weak reference (__unsafe_unretained, removed when residency is withdrawn); the most recently hit entry is tried first - bindings within one pass almost always land on the same one or two buffers
|
||||
@@ -635,9 +635,9 @@ static void ser_gate(void) {
|
||||
// Metal 4 conservative barriers (first version): a consumer barrier at the start of an encoder (all prior work → this encoder) and a producer barrier at the end (this encoder and earlier → later encoders).
|
||||
// Only the one at the start is not enough: t_rt_range 'pass 1 → pass 2 → copy' read back black, and after adding the end barrier it is 19/19. Old-queue encoders (upload / diagnostics / present) do not go through these barriers.
|
||||
#if DM_NVN_M3
|
||||
static inline void m4_end(id e) { [e endEncoding]; } // 老接口没有显式屏障:依赖关系由 useResource 声明 + 系统自动跟踪 | the older API has no explicit barriers: dependencies come from useResource declarations plus the system's automatic tracking
|
||||
static inline void m4_end(id e) { [e endEncoding]; } // 旧接口没有显式屏障:依赖关系由 useResource 声明 + 系统自动跟踪 | the older API has no explicit barriers: dependencies come from useResource declarations plus the system's automatic tracking
|
||||
static inline void m3_rbuf(id<MTLRenderCommandEncoder> e, int vertex, NSUInteger i, uint64_t gpu) {
|
||||
NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; }
|
||||
NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "旧接口绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; }
|
||||
if (vertex) [e setVertexBuffer:b offset:off atIndex:i]; else [e setFragmentBuffer:b offset:off atIndex:i];
|
||||
}
|
||||
#else
|
||||
@@ -674,7 +674,7 @@ static inline void enc_r_args(RENC e, MTLRenderStages s, uint64_t gpu, NSUIntege
|
||||
static inline void enc_r_draw(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n) { [e drawPrimitives:p vertexStart:v vertexCount:n]; }
|
||||
static inline void enc_r_draw_instanced(RENC e, MTLPrimitiveType p, NSUInteger v, NSUInteger n, NSUInteger i, NSUInteger b) { [e drawPrimitives:p vertexStart:v vertexCount:n instanceCount:i baseInstance:b]; }
|
||||
#if DM_NVN_M3
|
||||
static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { (void)len; if (!n) return; NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (!b) { { static int n_; if (!n_++) MLOG("【红】" "老接口绘制:索引缓冲地址 %#llx 不在任何登记过的缓冲里", (unsigned long long)gpu); } return; } [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:b indexBufferOffset:off instanceCount:i baseVertex:bv baseInstance:bi]; }
|
||||
static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { (void)len; if (!n) return; NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (!b) { { static int n_; if (!n_++) MLOG("【红】" "旧接口绘制:索引缓冲地址 %#llx 不在任何登记过的缓冲里", (unsigned long long)gpu); } return; } [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:b indexBufferOffset:off instanceCount:i baseVertex:bv baseInstance:bi]; }
|
||||
#else
|
||||
static inline void enc_r_draw_indexed(RENC e, MTLPrimitiveType p, NSUInteger n, MTLIndexType t, uint64_t gpu, NSUInteger len, NSUInteger i, NSInteger bv, NSUInteger bi) { [e drawIndexedPrimitives:p indexCount:n indexType:t indexBuffer:gpu indexBufferLength:len instanceCount:i baseVertex:bv baseInstance:bi]; }
|
||||
#endif
|
||||
@@ -687,7 +687,7 @@ static inline id<MTLComputeCommandEncoder> enc_c_begin_concurrent(id<MTLCommandB
|
||||
static inline void enc_c_end(id e) { m4_end(e); }
|
||||
static inline void enc_c_pso(id e, id<MTLComputePipelineState> p) { [e setComputePipelineState:p]; }
|
||||
#if DM_NVN_M3
|
||||
static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "老接口计算绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; } [(id<MTLComputeCommandEncoder>)e setBuffer:b offset:off atIndex:i]; }
|
||||
static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { NSUInteger off; id<MTLBuffer> b = m3_buf(gpu, &off); if (gpu && !b) { { static int n_; if (!n_++) MLOG("【红】" "旧接口计算绑定:显卡地址 %#llx 不在任何登记过的缓冲里(槽 %lu)", (unsigned long long)gpu, (unsigned long)i); } return; } [(id<MTLComputeCommandEncoder>)e setBuffer:b offset:off atIndex:i]; }
|
||||
#else
|
||||
static inline void enc_c_args(id e, uint64_t gpu, NSUInteger i) { (void)e; [g_ct setAddress:gpu atIndex:i]; }
|
||||
#endif
|
||||
@@ -1134,7 +1134,7 @@ static void up_flush(void) {
|
||||
m4_end(g_up_ce); g_up_ce = nil;
|
||||
}
|
||||
#if DM_NVN_M3
|
||||
// 老接口:拷贝与计算是两种编码器——先一个拷贝编码器做「暂存块 → 贴图」,再一个计算编码器做无 BC 的 GPU 解压
|
||||
// 旧接口:拷贝与计算是两种编码器——先一个拷贝编码器做「暂存块 → 贴图」,再一个计算编码器做无 BC 的 GPU 解压
|
||||
// Older API: copy and compute are two kinds of encoder - first a copy encoder does "staging block -> texture", then a compute encoder does the GPU decompression for devices without BC
|
||||
BENC b = g_nup_blits ? [g_up_cb blitCommandEncoder] : nil;
|
||||
for (int i = 0; b && i < g_nup_blits; i++) {
|
||||
@@ -1678,10 +1678,10 @@ static pg_pass *pg_new(int kind, int nslot) {
|
||||
g_pg_used += nslot;
|
||||
return p;
|
||||
}
|
||||
// 开渲染通道前记通道信息(附件、尺寸、读入方式);老接口在描述符上挂阶段边界采样,Metal 4 在开编码器后 / 收编码器前写时间戳(pg_render_begin / pg_render_finish)。
|
||||
// 开渲染通道前记通道信息(附件、尺寸、读入方式);旧接口在描述符上挂阶段边界采样,Metal 4 在开编码器后 / 收编码器前写时间戳(pg_render_begin / pg_render_finish)。
|
||||
// 改到 Metal 4时描述符没了采样附件,这里整段被短路、提交时的回读调用也删了,两种接口都没再出过数,这次补齐
|
||||
// Record pass info before opening a render pass (attachments, size, load action); the legacy API attaches stage boundary sampling to the descriptor, while Metal 4 writes timestamps after opening / before ending the encoder (pg_render_begin / pg_render_finish).
|
||||
// When moving to Metal 4 the descriptor lost its sample attachments, this whole block was short-circuited and the readback call at submission was deleted, so neither API produced numbers again; this restores it
|
||||
// Record the pass info (attachments, size, load actions) before opening a render pass; the older API attaches stage-boundary sampling to the descriptor, while Metal 4 writes timestamps after opening / before ending the encoder (pg_render_begin / pg_render_finish).
|
||||
// When we moved to Metal 4 the descriptor lost its sampling attachment, this whole block was short-circuited and the readback at submit time was removed too, so neither API produced numbers any more; this restores both
|
||||
static void pg_render(RPD *pd, NSUInteger nc) {
|
||||
pg_pass *p = pg_new(0, PG_RSLOTS); if (!p) return;
|
||||
#if DM_NVN_M3
|
||||
@@ -1739,7 +1739,7 @@ static void pg_compute_end(id e) { // 收 pg_compute 开的计算编码器之
|
||||
#endif
|
||||
}
|
||||
static void pg_end_render(void) { if (g_pg_open >= 0) { g_pg_pass[g_pg_open].draws += (int)g_stat_draw; g_pg_open = -1; } }
|
||||
static void pg_commit(id fb) { // 把本次提交的通道表交给完成回调解析;fb = FB_ON(o, g_cb)(老接口是命令缓冲的完成回调,Metal 4 是提交选项的反馈回调) | Hands this submission's pass table to the completion callback for parsing; fb = FB_ON(o, g_cb) (on the legacy API the command buffer completion handler, on Metal 4 the commit options feedback handler)
|
||||
static void pg_commit(id fb) { // 把本次提交的通道表交给完成回调解析;fb = FB_ON(o, g_cb)(旧接口是命令缓冲的完成回调,Metal 4 是提交选项的反馈回调) | Hands this submission's pass table to the completion callback for parsing; fb = FB_ON(o, g_cb) (on the legacy API the command buffer completion handler, on Metal 4 the commit options feedback handler)
|
||||
if (!g_pg || !g_pg_np) return;
|
||||
int n = g_pg_np; pg_pass *ps = malloc(n * sizeof *ps); memcpy(ps, g_pg_pass, n * sizeof *ps);
|
||||
__typeof__(g_pg_buf[0]) buf = g_pg_buf[g_pg_b]; uint32_t used = g_pg_used;
|
||||
@@ -3034,7 +3034,7 @@ static uint64_t ui_mat_patch(const p_bind_buf *u, void *mb, uint64_t mo) {
|
||||
return lg;
|
||||
}
|
||||
#if DM_NVN_M3
|
||||
// 老接口的资源声明去重:同一渲染编码器内对同一资源重复 useResource 是幂等的,而每次新编参数块都会把它引用的资源全声明一遍——
|
||||
// 旧接口的资源声明去重:同一渲染编码器内对同一资源重复 useResource 是幂等的,而每次新编参数块都会把它引用的资源全声明一遍——
|
||||
// 营地实测每次绘制声明 9.7 次、其中 9.2 次是本编码器里已经声明过的,每次约 227 条指令。这里记下本通道(g_pass.serial,与渲染编码器一一对应:
|
||||
// 序号只在开渲染编码器前递增)已按哪些用法声明过哪些资源,已覆盖的跳过。表满(一个通道里超过表长个不同资源)时不记、照常声明。
|
||||
// 表项不持有资源:声明过的资源被编码器持有到提交完成,同一通道内它的地址不会被别的资源复用。只在提交线程上用
|
||||
@@ -3062,10 +3062,10 @@ static int encode_args(id<MTLCommandEncoder> en, NvShader *sh, int nvn_stage, in
|
||||
return 1;
|
||||
}
|
||||
#if DM_NVN_M3
|
||||
// 老接口:着色器经参数块间接访问的每个资源都要在本编码器上声明用途,系统才知道它和别的编码器(上传拷贝、别的通道)之间的先后依赖;
|
||||
// 旧接口:着色器经参数块间接访问的每个资源都要在本编码器上声明用途,系统才知道它和别的编码器(上传拷贝、别的通道)之间的先后依赖;
|
||||
// 不声明的话只读贴图会和写它的拷贝乱序(迁 Metal 4 前实测过)。同一编码器内重复声明是幂等的
|
||||
// Older API: every resource a shader accesses indirectly through an argument block must have its usage declared on this encoder, so that the system knows its ordering dependency against other encoders (upload copies, other passes);
|
||||
// without the declaration a read-only texture gets out of order with the copy that writes it (measured before the move to Metal 4). Repeated declarations within one encoder are idempotent
|
||||
// Older API: every resource the shaders reach indirectly through an argument buffer must have its usage declared on this encoder, so the system knows its ordering against other encoders (upload copies, other passes);
|
||||
// without the declaration a read-only texture can be reordered against the copy that writes it (measured before the move to Metal 4). Declaring it again on the same encoder is idempotent
|
||||
#define USE(r, u) do { id<MTLResource> r_ = (id<MTLResource>)(r); if (r_) { if (nvn_stage == 5) [(id<MTLComputeCommandEncoder>)en useResource:r_ usage:(u)]; else if (!m3_use_seen((__bridge void *)r_, (uint32_t)(u))) [(id<MTLRenderCommandEncoder>)en useResource:r_ usage:(u) stages:MTLRenderStageVertex | MTLRenderStageFragment]; } \
|
||||
if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0)
|
||||
#define USE_SAMP(r, u) do { (void)(u); if (__builtin_expect(g_res_check_on, 0)) res_check((r), sh->key, reg); } while (0) // 采样器不是资源,不用声明 | samplers are not resources and need no declaration
|
||||
@@ -6172,7 +6172,7 @@ static int present_now(const tex_t *t, double period, uint64_t frame, uint64_t t
|
||||
pthread_mutex_unlock(&g_pq_mu);
|
||||
}
|
||||
#if DM_NVN_M3
|
||||
CBUF cb = [g_q commandBuffer]; // 老接口:交画面记在命令缓冲上(presentDrawable),这一帧的绘制做完才上屏 | older API: presentation is recorded on the command buffer (presentDrawable), so the frame reaches the screen only after its drawing is done
|
||||
CBUF cb = [g_q commandBuffer]; // 旧接口:交画面记在命令缓冲上(presentDrawable),这一帧的绘制做完才上屏 | older API: presentation is recorded on the command buffer (presentDrawable), so the frame reaches the screen only after its drawing is done
|
||||
if (!present_encode_m4(cb, src, dr.texture, crop, alloc_i)) return 0;
|
||||
#else
|
||||
[g_present_alloc4[alloc_i] reset];
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
// PR15宿主池标志登记的有界只读查询;调用者持互斥锁,未知/重叠/溢出均不证明CPU_NO_ACCESS。
|
||||
// Bounded PR15 host pool-flags registry; callers hold a mutex, and unknown/overlapping/overflowed ranges never prove CPU_NO_ACCESS.
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
enum { NVN_POOL_FLAGS_REGISTRY_MAX=4096 };
|
||||
typedef struct { uintptr_t address; uint64_t bytes; int flags; const void *owner; } nvn_pool_flags_record;
|
||||
typedef struct { nvn_pool_flags_record entries[NVN_POOL_FLAGS_REGISTRY_MAX]; unsigned count; int incomplete; } nvn_pool_flags_registry;
|
||||
|
||||
static inline int nvn_pool_flags_range_valid(uintptr_t address,uint64_t bytes) {
|
||||
return bytes && bytes<=UINTPTR_MAX-address;
|
||||
}
|
||||
static inline void nvn_pool_flags_registry_del(nvn_pool_flags_registry *table,const void *owner) {
|
||||
for(unsigned i=0;i<table->count;) {
|
||||
if(table->entries[i].owner==owner)table->entries[i]=table->entries[--table->count];
|
||||
else ++i;
|
||||
}
|
||||
}
|
||||
static inline int nvn_pool_flags_registry_add(nvn_pool_flags_registry *table,const void *owner,const void *mem,uint64_t bytes,int flags) {
|
||||
if(!owner || !mem || !nvn_pool_flags_range_valid((uintptr_t)mem,bytes)) {table->incomplete=1;return 0;}
|
||||
nvn_pool_flags_registry_del(table,owner);
|
||||
if(table->count==NVN_POOL_FLAGS_REGISTRY_MAX) {table->incomplete=1;return 0;}
|
||||
table->entries[table->count++]=(nvn_pool_flags_record){(uintptr_t)mem,bytes,flags,owner};return 1;
|
||||
}
|
||||
static inline int nvn_pool_flags_registry_get(const nvn_pool_flags_registry *table,const void *mem,size_t bytes) {
|
||||
uintptr_t address=(uintptr_t)mem;
|
||||
if(table->incomplete || !nvn_pool_flags_range_valid(address,bytes))return -1;
|
||||
int match=-1;
|
||||
for(unsigned i=0;i<table->count;++i) {
|
||||
const nvn_pool_flags_record *record=&table->entries[i];
|
||||
if(address<record->address+record->bytes && record->address<address+bytes) {
|
||||
if(match>=0 || address<record->address || address-record->address>record->bytes || bytes>record->bytes-(address-record->address))return -1;
|
||||
match=(int)i;
|
||||
}
|
||||
}
|
||||
return match<0?-1:table->entries[match].flags;
|
||||
}
|
||||
@@ -24,7 +24,7 @@
|
||||
static id<MTLRenderPipelineState> g_rx_pso1; static MTLPixelFormat g_rx_fmt_c, g_rx_fmt_ds;
|
||||
static id<MTLDepthStencilState> g_rx_dss;
|
||||
#if DM_NVN_M3
|
||||
static int g_rx_args; // 老接口没有参数表:只当「常量缓冲建过没有」的标记 | the older API has no argument table: used only as the marker for "has the constant buffer been created"
|
||||
static int g_rx_args; // 旧接口没有参数表:只当「常量缓冲建过没有」的标记 | the older API has no argument table: used only as the marker for "has the constant buffer been created"
|
||||
#else
|
||||
static id<MTL4ArgumentTable> g_rx_args;
|
||||
#endif
|
||||
|
||||
@@ -5,6 +5,8 @@ t_deswz_gpu
|
||||
t_deswz_gpu.dSYM/
|
||||
t_builtin.dSYM/
|
||||
t_pace
|
||||
t_adaptive_pace
|
||||
t_completion_wait
|
||||
.precommit.err
|
||||
.precommit_snap/
|
||||
t_refl
|
||||
|
||||
+10
-2
@@ -26,6 +26,10 @@ t_cover: t_cover.c ../nvn/nvn_cover.h
|
||||
clang -O1 -Wall -o $@ t_cover.c
|
||||
t_pace: t_pace.c ../nvn/nvn_pace.h
|
||||
clang -O1 -Wall -o $@ t_pace.c
|
||||
t_adaptive_pace: t_adaptive_pace.c ../nvn/nvn_adaptive_pace.h ../nvn/nvn_pace.h
|
||||
clang -O1 -Wall -o $@ t_adaptive_pace.c
|
||||
t_completion_wait: t_completion_wait.cpp ../vulkan/engine/xbg_completion_wait.h
|
||||
clang++ -std=c++17 -O1 -Wall -pthread -DDM_COMPLETION_WAIT_SELFTEST -DDM_COMPLETION_WAIT_MAIN -o $@ t_completion_wait.cpp
|
||||
t_fuse_check: t_fuse_check.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
clang $(CFLAGS) -fobjc-arc -o $@ t_fuse_check.m ../../host/crash.c $(filter-out ../nvn/nvn_mtl.m ../nvn/nvn_entry.S ../nvn/nvn_thunks.S,$(GFX)) $(FW)
|
||||
t_rt_srgb_view: t_rt_srgb_view.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
@@ -59,6 +63,8 @@ t_pfv: t_pfv.m ../../host/crash.c $(GFX) $(GFX_H)
|
||||
# 依赖一行一个、按字母序(免得加一个测试就整行冲突);下面各条命令的先后不变
|
||||
# Dependencies one per line in alphabetical order (so that adding one test does not conflict on the whole line); the order of the commands below is unchanged
|
||||
run: \
|
||||
t_adaptive_pace \
|
||||
t_completion_wait \
|
||||
t_copy_pitch \
|
||||
t_builtin \
|
||||
t_cover \
|
||||
@@ -91,6 +97,8 @@ run: \
|
||||
./t_builtin
|
||||
./t_deswz_gpu
|
||||
./t_pace
|
||||
./t_adaptive_pace
|
||||
./t_completion_wait
|
||||
./t_refl
|
||||
./t_hmap
|
||||
./t_cover
|
||||
@@ -116,12 +124,12 @@ run: \
|
||||
MTL_DEBUG_LAYER=1 ./t_rt_srgb_view
|
||||
python3 test_tbdr_budget.py
|
||||
.PHONY: run
|
||||
# 老接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。
|
||||
# 旧接口版那一遍(图形后端编译期开关 DM_NVN_M3=1,目标 macOS 15.0):在旁边的 tests_m3 目录里用同一份测试源码另编另跑,不动这里的缺省产物。
|
||||
# 闸门(verify/accept.sh)两遍都跑,免得以后只测一边
|
||||
# The older-API pass (compile-time switch DM_NVN_M3=1 of the graphics backend, target macOS 15.0): built and run separately from the same test sources in the sibling tests_m3 directory, leaving the default outputs here untouched.
|
||||
# The gate (verify/accept.sh) runs both passes, so that only one side being tested cannot happen later
|
||||
run-m3:
|
||||
rm -rf ../tests_m3 && mkdir ../tests_m3 && cp Makefile *.c *.m *.py ../tests_m3/
|
||||
rm -rf ../tests_m3 && mkdir ../tests_m3 && cp Makefile *.c *.cpp *.m *.py ../tests_m3/
|
||||
$(MAKE) -C ../tests_m3 run CFLAGS="$(CFLAGS) -DDM_NVN_M3=1 -mmacosx-version-min=15.0"
|
||||
|
||||
t_copy_pitch: t_copy_pitch.c ../nvn/nvn_copy_pitch.h
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
// 自适应节拍边界测试:期望档位手算;CPU累计时钟在等待期间不动,旧墙钟输入必须被负对照识别。
|
||||
// Adaptive pacing boundary tests: hand-calculated tiers; CPU clocks stop during waits, and a wall-clock negative control must be detected.
|
||||
#include "../nvn/nvn_adaptive_pace.h"
|
||||
#include "../nvn/nvn_pace.h"
|
||||
|
||||
static const char *failure;
|
||||
#define CHECK(c, name) do { if (!(c)) { failure = name; return 1; } } while (0)
|
||||
|
||||
int adaptive_pace_test(void) {
|
||||
failure = 0;
|
||||
struct { double hz; int want; } tiers[] = {{60,1},{90,2},{120,2},{59.94,1},{119.88,2},{50,1},{144,3}};
|
||||
for (unsigned i = 0; i < sizeof(tiers)/sizeof(tiers[0]); ++i) {
|
||||
int k = nvn_adaptive_divisor(tiers[i].hz, 0, 0);
|
||||
CHECK(k == tiers[i].want, "initial tier");
|
||||
CHECK(tiers[i].hz / k <= 60, "initial 60 fps ceiling");
|
||||
}
|
||||
CHECK(nvn_adaptive_divisor(90, 1, 90) == 2, "clamp stale 90 fps tier");
|
||||
CHECK(nvn_adaptive_divisor(90, 4, 120) == 3, "120 to 90 retains 30 fps");
|
||||
CHECK(nvn_adaptive_divisor(60, 3, 90) == 2, "90 to 60 retains 30 fps");
|
||||
CHECK(nvn_adaptive_divisor(120, 2, 60) == 4, "60 to 120 retains 30 fps");
|
||||
CHECK(nvn_adaptive_divisor(90, 2, 120) == 2, "120 to 90 caps faster tier");
|
||||
CHECK(nvn_adaptive_divisor(60, 6, 120) == 3, "20 fps floor survives refresh change");
|
||||
CHECK(nvn_pace_hz(90, 60) == 90, "legacy Apple floor remains unchanged");
|
||||
CHECK(90.0 / (int)(90.0 / 60.0 + 0.02) > 60, "negative control detects old floor bug");
|
||||
|
||||
nvn_frame_cpu_window cpu = {0}, wall = {0}; double cm = -1, wm = -1;
|
||||
nvn_frame_cpu_sample(&cpu, 1000000, &cm); nvn_frame_cpu_sample(&wall, 1000000, &wm);
|
||||
for (unsigned i = 1; i <= 60; ++i) {
|
||||
// 每帧实际工作4ms、等待30ms:CPU平均必须4,墙钟负对照34,不因等待误降档。
|
||||
// Each frame does 4 ms CPU work and waits 30 ms: CPU must average 4, wall-clock control 34.
|
||||
int ready = nvn_frame_cpu_sample(&cpu, 1000000ull + i * 4000000ull, &cm);
|
||||
nvn_frame_cpu_sample(&wall, 1000000ull + i * 34000000ull, &wm);
|
||||
CHECK(ready == (i == 60), "publish only after complete 60 frame window");
|
||||
}
|
||||
CHECK(cm == 4 && wm == 34, "waits excluded from CPU; wall negative control differs");
|
||||
CHECK(cm < 1000.0/30 && wm > 1000.0/30, "wall input wrongly exceeds sustainable 30 fps budget");
|
||||
for (unsigned i = 1; i <= 60; ++i) nvn_frame_cpu_sample(&cpu, 241000000ull + i * 7000000ull, &cm);
|
||||
CHECK(cm == 7, "next window does not retain previous CPU load");
|
||||
CHECK(!nvn_frame_cpu_sample(&cpu, 1000, &cm), "counter reset starts a fresh window");
|
||||
CHECK(cpu.count == 0 && cpu.sum == 0, "counter reset clears partial load");
|
||||
return 0;
|
||||
}
|
||||
const char *adaptive_pace_failure(void) { return failure; }
|
||||
|
||||
// 桌面DLL驱动可把真实 thread_time_ns 采样送进生产统计函数;不代替鸿蒙设备验证。
|
||||
// A desktop DLL driver can feed real thread_time_ns samples into the production sampler; it does not replace HarmonyOS device verification.
|
||||
static nvn_frame_cpu_window observed;
|
||||
double adaptive_pace_observe(uint64_t cpu_ns, int reset) {
|
||||
double ms = -1;
|
||||
if (reset) { observed.previous = observed.sum = 0; observed.count = 0; }
|
||||
nvn_frame_cpu_sample(&observed, cpu_ns, &ms);
|
||||
return ms;
|
||||
}
|
||||
|
||||
#ifndef DM_PACE_TEST_DLL
|
||||
#include <stdio.h>
|
||||
#include <time.h>
|
||||
#include <errno.h>
|
||||
static uint64_t time_ns(clockid_t clock) {
|
||||
struct timespec t;
|
||||
if (clock_gettime(clock, &t)) return 0;
|
||||
return (uint64_t)t.tv_sec * 1000000000ull + (uint64_t)t.tv_nsec;
|
||||
}
|
||||
static int real_cpu_clock_test(void) {
|
||||
nvn_frame_cpu_window sample = {0}; double ms = -1;
|
||||
uint64_t wall0 = time_ns(CLOCK_MONOTONIC), cpu0 = time_ns(CLOCK_THREAD_CPUTIME_ID);
|
||||
CHECK(wall0 && cpu0, "real clocks available");
|
||||
volatile unsigned work = 1;
|
||||
while (time_ns(CLOCK_MONOTONIC) - wall0 < 20000000ull) work = work * 1664525u + 1013904223u;
|
||||
(void)work;
|
||||
struct timespec delay = {0, 150000000};
|
||||
while (nanosleep(&delay, &delay) && errno == EINTR) { }
|
||||
uint64_t cpu1 = time_ns(CLOCK_THREAD_CPUTIME_ID), wall1 = time_ns(CLOCK_MONOTONIC);
|
||||
CHECK(cpu1 >= cpu0 && wall1 > wall0, "real clocks monotonic");
|
||||
nvn_frame_cpu_sample(&sample, cpu0, &ms);
|
||||
for (unsigned i = 0; i < 60; ++i) nvn_frame_cpu_sample(&sample, cpu1, &ms);
|
||||
double wall_ms = (wall1 - wall0) / 1e6, cpu_ms = ms * 60;
|
||||
printf("real clock: wall=%.3f ms, thread CPU=%.3f ms (includes work, excludes 150 ms sleep)\n", wall_ms, cpu_ms);
|
||||
CHECK(wall_ms >= 150, "real wait occurred");
|
||||
CHECK(cpu_ms < wall_ms * 0.5, "sleep is excluded; wall-clock negative control would fail");
|
||||
return 0;
|
||||
}
|
||||
int main(void) {
|
||||
int r = adaptive_pace_test();
|
||||
if (!r) r = real_cpu_clock_test();
|
||||
printf("adaptive pace: %s%s\n", r ? "FAIL " : "PASS", r ? failure : "");
|
||||
return r;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,147 @@
|
||||
// 同一完成感知 helper 的并发测试;仅显式 debug 宏编入,启动环境开关决定是否运行。
|
||||
// Concurrent tests of the production completion helper; compiled only by an explicit debug macro and run by a startup env switch.
|
||||
#ifdef DM_COMPLETION_WAIT_SELFTEST
|
||||
#include "../vulkan/engine/xbg_completion_wait.h"
|
||||
#include <cstdio>
|
||||
#include <initializer_list>
|
||||
#include <thread>
|
||||
|
||||
namespace {
|
||||
using xbg_completion::Acquire;
|
||||
using xbg_completion::Completion;
|
||||
using xbg_completion::Deadline;
|
||||
using xbg_completion::Clock;
|
||||
unsigned assertions=0;
|
||||
std::atomic<uint64_t> max_wait_ns{0};
|
||||
bool verify(std::initializer_list<bool> checks){
|
||||
bool ok=true;for(bool check:checks){++assertions;ok=check&&ok;}return ok;
|
||||
}
|
||||
template<class BeforeSleep>
|
||||
Acquire observed_acquire(Completion &c,std::unique_lock<std::recursive_mutex> &lock,uint64_t target,const Deadline &deadline,BeforeSleep before_sleep){
|
||||
const auto begin=Clock::now();const auto result=c.acquire(lock,target,deadline,before_sleep);
|
||||
const auto ns=uint64_t(std::chrono::duration_cast<std::chrono::nanoseconds>(Clock::now()-begin).count());
|
||||
auto previous=max_wait_ns.load();while(previous<ns&&!max_wait_ns.compare_exchange_weak(previous,ns)){}
|
||||
return result;
|
||||
}
|
||||
Acquire observed_acquire(Completion &c,std::unique_lock<std::recursive_mutex> &lock,uint64_t target,const Deadline &deadline){
|
||||
return observed_acquire(c,lock,target,deadline,[]{});
|
||||
}
|
||||
struct Gate {
|
||||
std::mutex mu;std::condition_variable cv;bool set_=false;
|
||||
void set(){std::lock_guard<std::mutex> lock(mu);set_=true;cv.notify_all();}
|
||||
bool wait(){std::unique_lock<std::mutex> lock(mu);return cv.wait_for(lock,std::chrono::seconds(2),[&]{return set_;});}
|
||||
};
|
||||
|
||||
bool already_complete(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
c.publish(3);std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);
|
||||
const auto complete=observed_acquire(c,lock,3,Deadline(0));const bool complete_owned=lock.owns_lock();
|
||||
const auto expired=observed_acquire(c,lock,4,Deadline(0));
|
||||
return verify({complete==Acquire::Completed,!complete_owned,expired==Acquire::TimedOut,!lock.owns_lock()});
|
||||
}
|
||||
|
||||
bool publication_window_once(bool hold_after_completion){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
std::unique_lock<std::recursive_mutex> owner(engine);Gate checked,publishing,finished;
|
||||
int payload=0,seen=0;bool owned=true,gate_ok=true;Acquire result=Acquire::TimedOut;
|
||||
std::thread waiter([&]{
|
||||
std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);
|
||||
result=observed_acquire(c,lock,1,Deadline(1500000000),[&]{checked.set();if(!publishing.wait())gate_ok=false;});
|
||||
owned=lock.owns_lock();if(result==Acquire::Completed)seen=payload;finished.set();
|
||||
});
|
||||
const bool ready=checked.wait();publishing.set();payload=0x5a23;c.publish(1);
|
||||
const bool finished_while_locked=finished.wait();
|
||||
// 完成发布后仍持 engine 40 ms,模拟后续提交;等待者必须已经不持 engine 返回。
|
||||
// Hold engine another 40 ms after publication, modeling a later submit; the waiter must already have returned without engine.
|
||||
if(hold_after_completion)std::this_thread::sleep_for(std::chrono::milliseconds(40));owner.unlock();waiter.join();
|
||||
return verify({ready,gate_ok,finished_while_locked,result==Acquire::Completed,!owned,seen==0x5a23});
|
||||
}
|
||||
bool publication_window_and_visibility(){
|
||||
// 每轮用门闩固定复查到挂起的窗口;有限循环不依赖 sleep 命中竞态。
|
||||
// Every round gates the predicate-to-suspension window; the finite loop does not rely on sleep to hit a race.
|
||||
for(unsigned i=0;i<32;i++)if(!publication_window_once(i==0))return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool no_publisher_release(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
std::unique_lock<std::recursive_mutex> owner(engine);Gate sleeping;Acquire result=Acquire::TimedOut;bool owned=false;
|
||||
std::thread waiter([&]{std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);
|
||||
result=observed_acquire(c,lock,1,Deadline(1500000000),[&]{sleeping.set();});owned=lock.owns_lock();});
|
||||
const bool ready=sleeping.wait();owner.unlock();waiter.join();
|
||||
return verify({ready,result==Acquire::EngineLocked,owned,done.load()==0});
|
||||
}
|
||||
|
||||
bool finite_timeout(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
std::unique_lock<std::recursive_mutex> owner(engine);Gate finished;Acquire result=Acquire::Completed;bool owned=true,expired=false;
|
||||
std::thread waiter([&]{Deadline deadline(20000000);std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);
|
||||
result=observed_acquire(c,lock,1,deadline);owned=lock.owns_lock();expired=deadline.expired();finished.set();});
|
||||
const bool before_unlock=finished.wait();owner.unlock();waiter.join();
|
||||
return verify({before_unlock,result==Acquire::TimedOut,!owned,expired});
|
||||
}
|
||||
|
||||
bool shared_budget_and_large_timeout(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);Deadline budget(100000000);
|
||||
if(!verify({observed_acquire(c,lock,1,budget)==Acquire::EngineLocked}))return false;
|
||||
lock.unlock();std::this_thread::sleep_for(std::chrono::milliseconds(120));
|
||||
if(!verify({observed_acquire(c,lock,1,budget)==Acquire::TimedOut,!lock.owns_lock()}))return false;
|
||||
Deadline huge(UINT64_MAX-1),infinite(UINT64_MAX);
|
||||
return verify({huge.remaining_ns()>UINT64_MAX/2,infinite.remaining_ns()==UINT64_MAX});
|
||||
}
|
||||
|
||||
bool multiple_targets_and_delayed_writeback(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);std::recursive_mutex engine;
|
||||
std::unique_lock<std::recursive_mutex> owner(engine);Gate sleeping[4],finished[4];std::thread waiters[4];
|
||||
Acquire results[4];int payload[2]={0,0},seen[4]={};bool owned[4]={};std::atomic<unsigned> returned{0};
|
||||
for(unsigned i=0;i<4;i++)waiters[i]=std::thread([&,i]{
|
||||
std::unique_lock<std::recursive_mutex> lock(engine,std::defer_lock);
|
||||
results[i]=observed_acquire(c,lock,i<2?1:2,Deadline(1500000000),[&]{sleeping[i].set();});
|
||||
owned[i]=lock.owns_lock();if(results[i]==Acquire::Completed)seen[i]=payload[i<2?0:1];++returned;finished[i].set();
|
||||
});
|
||||
bool ready=true;for(auto &gate:sleeping)ready=gate.wait()&&ready;
|
||||
// GPU-ready 或较小目标发布不能代替尚未完成的CPU写回;真正完成后才发布对应 fence。
|
||||
// GPU readiness or a smaller target cannot replace pending CPU writeback; publish each fence only after its data is ready.
|
||||
c.publish(0);std::this_thread::sleep_for(std::chrono::milliseconds(4));const bool none_early=returned.load()==0;
|
||||
payload[0]=17;c.publish(1);const bool low_done=finished[0].wait()&&finished[1].wait();
|
||||
const bool high_pending=returned.load()==2;payload[1]=29;c.publish(2);
|
||||
bool all_done=true;for(auto &gate:finished)all_done=gate.wait()&&all_done;
|
||||
owner.unlock();for(auto &thread:waiters)thread.join();
|
||||
bool valid=true;for(unsigned i=0;i<4;i++)valid=verify({results[i]==Acquire::Completed,!owned[i],seen[i]==(i<2?17:29)})&&valid;
|
||||
return verify({ready,none_early,low_done,high_pending,all_done})&&valid;
|
||||
}
|
||||
|
||||
bool paired_statistics(){
|
||||
std::atomic<uint64_t> done{0};Completion c(done);Gate start;std::atomic<unsigned> active{4};
|
||||
std::thread producers[4];for(auto &thread:producers)thread=std::thread([&]{start.wait();for(int i=0;i<1000;i++)c.record_gpu_wait(7);--active;});
|
||||
uint64_t ns=0,calls=0;bool paired=true;start.set();
|
||||
while(active.load()){
|
||||
const auto part=c.take_gpu_waits();paired=paired && part.ns==part.calls*7;ns+=part.ns;calls+=part.calls;
|
||||
std::this_thread::sleep_for(std::chrono::microseconds(50));
|
||||
}
|
||||
for(auto &thread:producers)thread.join();const auto last=c.take_gpu_waits();ns+=last.ns;calls+=last.calls;
|
||||
const auto empty=c.take_gpu_waits();
|
||||
return verify({paired,last.ns==last.calls*7,ns==28000,calls==4000,empty.ns==0,empty.calls==0});
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" int xbg_completion_wait_selftest(char *report,size_t bytes){
|
||||
assertions=0;max_wait_ns=0;
|
||||
struct Test {const char *name;bool (*run)();};
|
||||
const Test tests[]={{"already-complete",already_complete},{"publication-window-and-writeback",publication_window_and_visibility},
|
||||
{"no-publisher-release",no_publisher_release},{"finite-timeout",finite_timeout},
|
||||
{"shared-budget-large-timeout",shared_budget_and_large_timeout},{"multiple-targets-delayed-writeback",multiple_targets_and_delayed_writeback},
|
||||
{"paired-statistics",paired_statistics}};
|
||||
const auto cases=sizeof(tests)/sizeof(tests[0]);
|
||||
for(unsigned i=0;i<cases;i++)if(!tests[i].run()){
|
||||
if(report&&bytes)snprintf(report,bytes,"NVN COMPLETION_WAIT_SELFTEST FAIL case=%s cases=%u/%zu assertions=%u max_wait_ms=%.3f",tests[i].name,i+1,cases,assertions,double(max_wait_ns.load())/1e6);return int(i)+1;
|
||||
}
|
||||
if(report&&bytes)snprintf(report,bytes,"NVN COMPLETION_WAIT_SELFTEST PASS cases=%zu assertions=%u max_wait_ms=%.3f",cases,assertions,double(max_wait_ns.load())/1e6);return 0;
|
||||
}
|
||||
// 独立运行(dm/gfx/tests/Makefile 用 -DDM_COMPLETION_WAIT_MAIN 编):打印报告,失败返回非 0
|
||||
// Standalone run (built by dm/gfx/tests/Makefile with -DDM_COMPLETION_WAIT_MAIN): prints the report, non-zero on failure
|
||||
#ifdef DM_COMPLETION_WAIT_MAIN
|
||||
int main(){char report[256];const int r=xbg_completion_wait_selftest(report,sizeof report);puts(report);return r;}
|
||||
#endif
|
||||
#endif
|
||||
@@ -4,7 +4,7 @@
|
||||
#import <Metal/Metal.h>
|
||||
#include "nvn_deswizzle.h"
|
||||
#ifndef DM_NVN_M3
|
||||
#define DM_NVN_M3 0 // 见 nvn_mtl.m:1 = 图形后端走老接口 | see nvn_mtl.m: 1 = the graphics backend uses the older API
|
||||
#define DM_NVN_M3 0 // 见 nvn_mtl.m:1 = 图形后端走旧接口 | see nvn_mtl.m: 1 = the graphics backend uses the older API
|
||||
#endif
|
||||
|
||||
int nvn_deswz_gpu_init(id<MTLDevice> dev);
|
||||
|
||||
Executable
+278
@@ -0,0 +1,278 @@
|
||||
#!/usr/bin/env python3
|
||||
# 安卓 Vulkan 着色器包:Switch 原版着色器 → SPIR-V(同 dmsh_build.py 的 dmsh_xlate,Ryujinx 翻译器,Vulkan 目标)→ 导出 <键>.vk.json + <键>.spv
|
||||
# → pack_game_shaders.py 打成 XGS1 包 <键>.xgs(Vulkan 引擎运行时从 files/dm/shaders/ 读)。iOS 那条链在同一份 SPIR-V 之后转 MSL,这里转成引擎要的包。
|
||||
# 取着色器、组作业与 dmsh_build.py 逐字相同(键 = 控制段前 0x880 字节 SHA-256 前 16 位,即 shader_map.tsv 第 4 列,引擎 xbg_shader_key.c 同一算法);
|
||||
# dmsh_build.py 本身算进 iOS 着色器链版本,不在里面加开关,这里另起一份。
|
||||
# 导出时 SPIR-V 改三处(与作者鸿蒙移植那套 6931 个包逐字节核过,见 --compare):
|
||||
# ① 绑定号:引擎每条管线只有一个描述符集,各阶段从 0 起的绑定号会撞——改成 原号 × 6 + 阶段号(顶点 0、外壳 1、域 2、几何 3、像素 4、计算 5);
|
||||
# ② 裁剪(③)之后,补「未定格式」存储图像读写的能力(Ryujinx 不声明,见 add_format_caps);
|
||||
# ③ spirv-opt --trim-capabilities:Ryujinx 无条件声明 Float64 / GroupNonUniform* / DrawParameters 等,引擎只放行白名单、见到扩展即报错。其余不优化
|
||||
# (quad / warp 改写器按 Ryujinx 原始写法匹配)。最后 spirv-val --target-env vulkan1.1。
|
||||
# 绑定来源(贴图 / 采样器 / 存储缓冲槽、c0 / c2 驱动段、c1)与 dmsh_build.py 的 reflect() / decode_tex() 同一套解码。
|
||||
# 用法:dmsh_vk.py <Switch 包目录> <输出目录> [键…] 环境:XLATE(翻译器)、MAIN(main NSO)、J(并发)、SPIRV_OPT / SPIRV_VAL
|
||||
# dmsh_vk.py --compare <参考 .xgs 目录> <本次输出目录> 逐个比字节:一致 / 不一致(不一致的再分 SPIR-V / 绑定表 / 其他)
|
||||
# Android Vulkan shader bundles: original Switch shaders → SPIR-V (the same dmsh_xlate as dmsh_build.py, the Ryujinx translator, Vulkan target) → export <key>.vk.json + <key>.spv
|
||||
# → pack_game_shaders.py packs the XGS1 bundle <key>.xgs (the Vulkan engine reads it from files/dm/shaders/ at run time). The iOS chain turns the same SPIR-V into MSL; this one into the bundles the engine needs.
|
||||
# Getting shaders and building jobs are word for word as dmsh_build.py (key = first 16 hex digits of the SHA-256 of the first 0x880 bytes of the control section, i.e. column 4 of shader_map.tsv, the same algorithm as the engine's xbg_shader_key.c);
|
||||
# dmsh_build.py itself counts towards the iOS shader chain version, so no switch is added there and this is a separate script.
|
||||
# The SPIR-V gets three changes on export (checked byte for byte against the 6931 bundles of the authors' HarmonyOS port, see --compare):
|
||||
# ① binding numbers: the engine has one descriptor set per pipeline, and each stage's bindings from 0 would collide -- they become original × 6 + stage number (vertex 0, hull 1, domain 2, geometry 3, pixel 4, compute 5);
|
||||
# ② after trimming (③), add the capabilities for reading and writing storage images of unknown format (Ryujinx does not declare them, see add_format_caps);
|
||||
# ③ spirv-opt --trim-capabilities: Ryujinx always declares Float64 / GroupNonUniform* / DrawParameters and others, while the engine allows only a whitelist and fails on any extension. No other optimization
|
||||
# (the quad / warp rewriters match Ryujinx's original form). Finally spirv-val --target-env vulkan1.1.
|
||||
# Binding sources (texture / sampler / storage buffer slots, the c0 / c2 driver banks, c1) use the same decoding as reflect() / decode_tex() in dmsh_build.py.
|
||||
# Usage: dmsh_vk.py <Switch package directory> <output directory> [keys...] environment: XLATE (translator), MAIN (main NSO), J (parallelism), SPIRV_OPT / SPIRV_VAL
|
||||
# dmsh_vk.py --compare <reference .xgs directory> <output directory> compare byte by byte: identical / different (the different ones split into SPIR-V / binding table / other)
|
||||
import os, re, sys, json, struct, hashlib, shutil, subprocess, tempfile, collections, concurrent.futures as cf
|
||||
|
||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||
DM_ROOT = os.environ.get('DM_ROOT') or os.path.expanduser('~/dm-work')
|
||||
OPT, VAL = (os.environ.get(k, d) for k, d in (('SPIRV_OPT', 'spirv-opt'), ('SPIRV_VAL', 'spirv-val')))
|
||||
STAGE_NO = {'vs': 0, 'hs': 1, 'ds': 2, 'gs': 3, 'ps': 4, 'cs': 5}
|
||||
TEX_BASE, SAMP_BASE, IMG_BASE = 0x168, 0x568, 0x120 # 同 dmsh_build.py:c[2] 贴图句柄表、采样器句柄表、图像句柄表 | as dmsh_build.py: the texture handle, sampler handle and image handle tables in c[2]
|
||||
|
||||
|
||||
def compare(ref, got):
|
||||
"""逐个比 .xgs:一致 / 不一致(SPIR-V 部分同不同、绑定表同不同)/ 参考里有本次没有 | Compare .xgs one by one: identical / different (whether the SPIR-V part and the binding table differ) / in the reference but not this time"""
|
||||
st = collections.Counter(); bad = []
|
||||
for f in sorted(os.listdir(ref)):
|
||||
if not f.endswith('.xgs'): continue
|
||||
p = os.path.join(got, f)
|
||||
if not os.path.exists(p): st['本次没有'] += 1; bad.append((f, '本次没有')); continue
|
||||
a, b = open(os.path.join(ref, f), 'rb').read(), open(p, 'rb').read()
|
||||
if a == b: st['一致'] += 1; continue
|
||||
def parts(d):
|
||||
m, v, s, nb, ni, nc, ns, _ = struct.unpack_from('<8I', d, 0); o = 32 + 32 * nb + 4 * ni + nc
|
||||
return d[:o], d[o:o + ns]
|
||||
(ha, sa), (hb, sb) = parts(a), parts(b)
|
||||
why = ('绑定表 / 头不同' if ha != hb else '') + (',' if ha != hb and sa != sb else '') + ('SPIR-V 不同' if sa != sb else '')
|
||||
st['不一致'] += 1; bad.append((f, why))
|
||||
print(f'参考 {sum(st.values())} 个:' + ','.join(f'{k} {v}' for k, v in st.items()))
|
||||
for why, n in collections.Counter(w for _, w in bad).most_common(): print(f' {why}:{n}(例:{next(f for f, w in bad if w == why)})')
|
||||
return st['一致'] == sum(st.values())
|
||||
|
||||
|
||||
if len(sys.argv) > 1 and sys.argv[1] == '--compare':
|
||||
sys.exit(0 if compare(sys.argv[2], sys.argv[3]) else 1)
|
||||
|
||||
dm_dir, out = sys.argv[1:3]; want = set(sys.argv[3:])
|
||||
sys.path.insert(0, HERE); import dmsh_facts, pack_game_shaders
|
||||
XLATE = os.environ.get('XLATE', f'{DM_ROOT}/build/gfx/dmsh_xlate/dmsh_xlate')
|
||||
MAIN = os.environ.get('MAIN', f'{DM_ROOT}/data/switch/3.3.94012/Update/ExeFS/main')
|
||||
MAP = os.path.join(HERE, '../nvn/shader_map.tsv')
|
||||
FACTS = dmsh_facts.load()
|
||||
if not FACTS: sys.exit('【红】没有作答表 nvn/shader_facts.tsv')
|
||||
|
||||
# ---- 取着色器、组作业(与 dmsh_build.py 同) ----
|
||||
# ---- Getting shaders and building jobs (as dmsh_build.py) ----
|
||||
def records(d):
|
||||
r = [m.start() for m in re.finditer(b'BTCDBTCD', d)]
|
||||
return [d[x:(r[k + 1] if k + 1 < len(r) else len(d))] for k, x in enumerate(r)]
|
||||
|
||||
loc, stage_of = {}, {}
|
||||
for ln in open(MAP):
|
||||
c = ln.rstrip('\n').split('\t')
|
||||
if len(c) > 4 and c[0].endswith('.bin'): loc.setdefault(c[3], (c[0], int(c[1])))
|
||||
if len(c) > 4 and c[0].startswith('main.rodata@'):
|
||||
loc.setdefault(c[3], (c[0], int(c[0].split('@')[1], 16))); stage_of[c[3]] = {'顶点': 'vs', '像素': 'ps'}[c[2]]
|
||||
|
||||
def main_rec(mi, o):
|
||||
g = mi.rfind(bytes.fromhex('78563412'), o - 0x1000, o)
|
||||
if g < 0 or mi[o:o + 4] != bytes.fromhex('34127698'): sys.exit(f'【红】main 映像 @{o:#x} 不是内嵌着色器控制段(MAIN={MAIN})')
|
||||
return bytes(0x38) + mi[g:o + 0x880]
|
||||
|
||||
def job_for(key, name, rec, w):
|
||||
ci = rec.find(bytes.fromhex('34127698')); code = rec[0x38:ci]; stage = stage_of.get(key, name[:2])
|
||||
c1o, c1t = struct.unpack_from('<2I', rec, ci + 0x700)
|
||||
c1 = rec[0x38 + c1o:0x38 + c1t]
|
||||
if stage != 'cs': code = code[0x30:]
|
||||
cp = os.path.join(w, key + '.bin'); open(cp, 'wb').write(code)
|
||||
j = {'key': key, 'stage': stage, 'code': cp, 'tex': {}, 'img': {}, 'attr': {}, 'fout': {}, 'c1': c1.hex(),
|
||||
'debug': os.environ.get('XLATE_DEBUG', '1') != '0', 'reduced': os.environ.get('XLATE_REDUCED', '1') == '1'}
|
||||
if key in FACTS: j.update(FACTS[key])
|
||||
return j, c1
|
||||
|
||||
# ---- SPIR-V:读写指令 ----
|
||||
# ---- SPIR-V: reading and writing instructions ----
|
||||
def insts(words):
|
||||
i = 5
|
||||
while i < len(words):
|
||||
n = words[i] >> 16
|
||||
yield i, words[i] & 0xffff, words[i + 1:i + n]
|
||||
i += n
|
||||
|
||||
def rewrite(spv, stage):
|
||||
"""绑定号 × 6 + 阶段号 | binding number × 6 + stage number"""
|
||||
w = list(struct.unpack('<%dI' % (len(spv) // 4), spv))
|
||||
for i, op, a in insts(w):
|
||||
if op == 71 and a[1] == 33: w[i + 3] = a[2] * 6 + STAGE_NO[stage] # OpDecorate … Binding
|
||||
return struct.pack('<%dI' % len(w), *w)
|
||||
|
||||
def add_format_caps(spv):
|
||||
"""Ryujinx 对「未定格式」(Format = Unknown)的存储图像读写不声明 StorageImageRead/WriteWithoutFormat,spirv-val 不放行。
|
||||
用到了就补在能力段最前面(作者那套包的写法:只补缺的,其余能力次序不动)
|
||||
'''Ryujinx does not declare StorageImageRead/WriteWithoutFormat for reads and writes of storage images with Format = Unknown, and spirv-val rejects that.
|
||||
When used, add them at the front of the capability section (as the authors' bundles do: only what is missing, the order of the rest unchanged)'''"""
|
||||
w = list(struct.unpack('<%dI' % (len(spv) // 4), spv))
|
||||
fmt, ty, have, need = {}, {}, set(), []
|
||||
for i, op, a in insts(w):
|
||||
if op == 17: have.add(a[0])
|
||||
elif op == 25: fmt[a[0]] = a[7] # OpTypeImage:结果号 → 格式 | OpTypeImage: result id → format
|
||||
elif op == 61: ty[a[1]] = a[0] # OpLoad:结果号 → 类型 | OpLoad: result id → type
|
||||
for i, op, a in insts(w):
|
||||
if op in (98, 99): # OpImageRead(结果类型、结果、图像…)/ OpImageWrite(图像…) | OpImageRead (result type, result, image...) / OpImageWrite (image...)
|
||||
img = a[2] if op == 98 else a[0]
|
||||
cap = 55 if op == 98 else 56
|
||||
if fmt.get(ty.get(img)) == 0 and cap not in have and cap not in need: need.append(cap)
|
||||
for cap in need: w[5:5] = [(2 << 16) | 17, cap]
|
||||
return struct.pack('<%dI' % len(w), *w)
|
||||
|
||||
def spirv_info(spv):
|
||||
"""能力、扩展、各变量的绑定 / 存储类 / 指向类型 / 输入位置 / 图像属性(导出 vk.json 用) | Capabilities, extensions, and each variable's binding / storage class / pointee type / input location / image properties (for exporting vk.json)"""
|
||||
w = struct.unpack('<%dI' % (len(spv) // 4), spv)
|
||||
caps, exts, deco, types, ptr, var, names, consts = [], [], collections.defaultdict(dict), {}, {}, {}, {}, {}
|
||||
for i, op, a in insts(w):
|
||||
if op == 17: caps.append(a[0])
|
||||
elif op == 43 and len(a) >= 3: consts[a[1]] = a[2] # OpConstant 结果号 → 值(数组长度用) | OpConstant result id → value (for array lengths)
|
||||
elif op == 10: exts.append(bytes(struct.pack('<%dI' % len(a), *a)).split(b'\0')[0].decode())
|
||||
elif op == 5: names[a[0]] = bytes(struct.pack('<%dI' % (len(a) - 1), *a[1:])).split(b'\0')[0].decode()
|
||||
elif op == 71: deco[a[0]][a[1]] = a[2] if len(a) > 2 else 1
|
||||
elif op in (19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30): types[a[0]] = (op, a[1:])
|
||||
elif op == 32: ptr[a[0]] = (a[1], a[2])
|
||||
elif op == 59: var[a[1]] = (a[0], a[2])
|
||||
return caps, exts, deco, types, ptr, var, names, consts
|
||||
|
||||
def image_desc(types, tid):
|
||||
op, a = types[tid]
|
||||
while op in (27, 28, 29): tid = a[0]; op, a = types[tid] # 采样图像 / 数组 → 图像 | sampled image / array → image
|
||||
st, dim, depth, arrayed, ms, sampled, fmt = a[0], a[1], a[2], a[3], a[4], a[5], a[6]
|
||||
sop, sa = types[st]
|
||||
scalar = {'kind': 'float'} if sop == 22 else {'kind': 'int', 'signed': bool(sa[1])}
|
||||
return {'format': fmt, 'dim': dim, 'arrayed': arrayed, 'multisampled': ms, 'depth': depth, 'scalar': scalar}
|
||||
|
||||
def decode_tex(slots, h, image):
|
||||
tb = (slots & 0xffff) if slots >= 0 else 2; sb = ((slots >> 16) - 1) if slots >= 0 and (slots >> 16) else tb
|
||||
o0, o1, ty = h & 0x3fff, (h >> 14) & 0x3fff, h >> 28
|
||||
def slot(word, base, cb): return (word * 4 - base) // 8 if cb == 2 and word * 4 >= base and (word * 4 - base) % 8 == 0 else None
|
||||
words = [o0] + ([o1] if ty else [])
|
||||
if image: return next((slot(x, IMG_BASE, tb) for x in words if IMG_BASE <= x * 4 < TEX_BASE and slot(x, IMG_BASE, tb) is not None), None), None, ty
|
||||
t = next((slot(x, TEX_BASE, tb) for x in words if slot(x, TEX_BASE, tb) is not None and x * 4 < SAMP_BASE), None)
|
||||
s = next((slot(x, SAMP_BASE, sb) for x in words if x * 4 >= SAMP_BASE and slot(x, SAMP_BASE, sb) is not None), None)
|
||||
return t, s, ty
|
||||
|
||||
def export(key, stage, c1, spv, res):
|
||||
"""改写后的 SPIR-V + 翻译器的 res.json → vk.json(字段见 pack_game_shaders.py) | Rewritten SPIR-V + the translator's res.json → vk.json (fields: see pack_game_shaders.py)"""
|
||||
caps, exts, deco, types, ptr, var, names, consts = spirv_info(spv)
|
||||
if exts: raise ValueError('残留扩展 ' + ','.join(exts))
|
||||
by_bind = {}
|
||||
for vid, (pt, sc) in var.items():
|
||||
if 33 in deco[vid] and sc in (0, 2, 12): by_bind[deco[vid][33]] = (vid, ptr[pt][1], sc) # UniformConstant / Uniform / StorageBuffer
|
||||
base_no = STAGE_NO[stage]; descs = []
|
||||
def vbind(b): return b * 6 + base_no
|
||||
def block_bytes(tid):
|
||||
op, a = types[tid] # 结构体首成员是 vec4 定长数组(常量缓冲)→ 长度 × 16;运行时数组(存储缓冲)→ 0 | first struct member is a fixed vec4 array (constant buffer) → length × 16; a runtime array (storage buffer) → 0
|
||||
if op == 30 and a and types[a[0]][0] == 28: return 16 * consts.get(types[a[0]][1][1], 0)
|
||||
return 0
|
||||
sb_sorted = sorted(res['sbufs'], key=lambda b: b['binding'])
|
||||
# 支持缓冲:Ryujinx 绑定 0、名字 support_buffer,声明了就列(作者那套 6927 个游戏着色器全都带,不管用没用到)
|
||||
# Support buffer: Ryujinx binding 0, named support_buffer; listed whenever declared (all 6927 game shaders in the authors' set have it, used or not)
|
||||
sup = by_bind.get(vbind(0))
|
||||
if sup and names.get(sup[0], '') == 'support_buffer':
|
||||
descs.append({'name': 'support_buffer', 'binding': vbind(0), 'type': 'uniform_buffer', 'count': 1, 'source': {'category': 'support_buffer'}})
|
||||
for b in res['cbufs']:
|
||||
vid, tid, sc = by_bind[vbind(b['binding'])]
|
||||
n = b['slot']
|
||||
nvn = {'kind': 'uniform', 'slot': n - 3} if 3 <= n <= 16 else ({'kind': 'c1', 'slot': 0} if n == 1 else {'kind': 'driver', 'bank': n, 'slot': 0})
|
||||
descs.append({'name': names.get(vid, ''), 'binding': vbind(b['binding']), 'type': 'uniform_buffer', 'count': 1,
|
||||
'source': {'category': 'nvn', 'nvn': nvn}, 'block': {'bytes': block_bytes(tid)}})
|
||||
sbase = {'vs': 0x110, 'cs': 0x310, 'ps': 0x510}.get(stage)
|
||||
for b in sb_sorted:
|
||||
vid, tid, sc = by_bind[vbind(b['binding'])]
|
||||
off = b['cb_offset'] * 4 if b['cb_slot'] == 0 else None
|
||||
if off is None: raise ValueError(f'存储缓冲不在 c0:{b}')
|
||||
if stage == 'cs' and 0x210 <= off < 0x310 and (off - 0x210) % 16 == 0: nvn = {'kind': 'uniform_pointer', 'slot': (off - 0x210) // 16}
|
||||
elif sbase is not None and 0 <= off - sbase < 0x100 and (off - sbase) % 16 == 0: nvn = {'kind': 'storage_pointer', 'slot': (off - sbase) // 16}
|
||||
else: raise ValueError(f'存储缓冲槽解不出:{stage} off={off:#x}')
|
||||
descs.append({'name': names.get(vid, ''), 'binding': vbind(b['binding']), 'type': 'storage_buffer', 'count': 1,
|
||||
'source': {'category': 'nvn', 'nvn': nvn}, 'block': {'bytes': block_bytes(tid)}})
|
||||
for kind, lst in (('texture', res['textures']), ('image', res['images'])):
|
||||
for t in lst:
|
||||
vid, tid, sc = by_bind[vbind(t['binding'])]
|
||||
img = image_desc(types, tid)
|
||||
slot, samp, ty = decode_tex(t['cbuf_slot'], t['handle'], kind == 'image')
|
||||
if slot is None: raise ValueError(f'{kind} 槽解不出:{t}')
|
||||
if kind == 'texture':
|
||||
typ = 'uniform_texel_buffer' if img['dim'] == 5 else 'combined_image_sampler'
|
||||
nvn = {'kind': 'texture', 'slot': slot, 'sampler_slot': samp if ty else None}
|
||||
else:
|
||||
typ = 'storage_texel_buffer' if img['dim'] == 5 else 'storage_image'
|
||||
nvn = {'kind': 'image', 'slot': slot}
|
||||
descs.append({'name': names.get(vid, ''), 'binding': vbind(t['binding']), 'type': typ, 'count': 1,
|
||||
'source': {'category': 'nvn', 'nvn': nvn, 'handle_decode': {'type': ty}}, 'image': img})
|
||||
descs.sort(key=lambda d: d['binding'])
|
||||
inputs = []
|
||||
if stage == 'vs':
|
||||
for vid, (pt, sc) in var.items():
|
||||
if sc == 1 and 30 in deco[vid] and 11 not in deco[vid]: inputs.append({'storage': 'input', 'location': deco[vid][30]}) # Input、Location、非 BuiltIn | Input, Location, not BuiltIn
|
||||
return {'identity': {'key': key}, 'sha256': hashlib.sha256(spv).hexdigest(), 'stage': stage, 'capabilities': sorted(set(caps)),
|
||||
'descriptors': descs, 'interfaces': inputs, 'frozen_job': {'c1': c1.hex()}}
|
||||
|
||||
# ---- 主流程 ----
|
||||
# ---- Main flow ----
|
||||
keys = sorted(want) if want else sorted(loc)
|
||||
NJ = int(os.environ.get('J', '8'))
|
||||
os.makedirs(out, exist_ok=True)
|
||||
work = tempfile.mkdtemp(prefix='dmsh_vk_', dir=os.environ.get('WORK'))
|
||||
bundle = os.path.join(work, 'bundle'); os.makedirs(bundle)
|
||||
packs, jobs, c1s = {}, {}, {}
|
||||
for key in keys:
|
||||
name, k = loc[key]
|
||||
if name.startswith('main.rodata@'):
|
||||
if 'main' not in packs:
|
||||
sys.path.insert(0, os.path.join(HERE, '../../verify')); import nsoimg
|
||||
packs['main'] = nsoimg.load(MAIN)
|
||||
rec = main_rec(packs['main'], k)
|
||||
else:
|
||||
if name not in packs: packs[name] = records(open(os.path.join(dm_dir, name), 'rb').read())
|
||||
rec = packs[name][k]
|
||||
jobs[key], c1s[key] = job_for(key, name, rec, work)
|
||||
chunks = [keys[i::NJ] for i in range(NJ)]
|
||||
def xl(ch):
|
||||
jp = os.path.join(work, f'job_{abs(hash(ch[0]))}.json'); json.dump([jobs[k] for k in ch], open(jp, 'w'))
|
||||
return subprocess.run([XLATE, jp, work], capture_output=True, text=True)
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: xr = list(ex.map(xl, [c for c in chunks if c]))
|
||||
xerr = {}
|
||||
for r in xr:
|
||||
for ln in r.stderr.splitlines():
|
||||
m = re.match(r'【红】(\w+):(.*)', ln)
|
||||
if m: xerr[m.group(1)] = m.group(2)[:160]
|
||||
|
||||
def one(key):
|
||||
if key in xerr or not os.path.exists(os.path.join(work, key + '.spv')): return key, '翻译失败', xerr.get(key, '无 spv')
|
||||
stage = jobs[key]['stage']
|
||||
spv = rewrite(open(os.path.join(work, key + '.spv'), 'rb').read(), stage)
|
||||
f1, f2 = os.path.join(work, key + '.r.spv'), os.path.join(work, key + '.t.spv')
|
||||
open(f1, 'wb').write(spv)
|
||||
r = subprocess.run([OPT, '--trim-capabilities', f1, '-o', f2], capture_output=True, text=True)
|
||||
if r.returncode: return key, 'spirv-opt 失败', r.stderr.strip()[:160]
|
||||
spv = add_format_caps(open(f2, 'rb').read()); open(f2, 'wb').write(spv)
|
||||
r = subprocess.run([VAL, '--target-env', 'vulkan1.1', f2], capture_output=True, text=True)
|
||||
if r.returncode: return key, 'spirv-val 失败', r.stderr.strip().splitlines()[0][:160] if r.stderr.strip() else '?'
|
||||
spv = open(f2, 'rb').read()
|
||||
try: vk = export(key, stage, c1s[key], spv, json.load(open(os.path.join(work, key + '.res.json'))))
|
||||
except (ValueError, KeyError) as e: return key, '导出失败', str(e)[:160]
|
||||
open(os.path.join(bundle, key + '.spv'), 'wb').write(spv)
|
||||
json.dump(vk, open(os.path.join(bundle, key + '.vk.json'), 'w'), ensure_ascii=False)
|
||||
try: k2, data = pack_game_shaders.pack(__import__('pathlib').Path(os.path.join(bundle, key + '.vk.json')))
|
||||
except (ValueError, KeyError) as e: return key, '打包失败', str(e)[:160]
|
||||
open(os.path.join(out, k2 + '.xgs'), 'wb').write(data)
|
||||
return key, 'ok', ''
|
||||
|
||||
with cf.ThreadPoolExecutor(NJ) as ex: res = list(ex.map(one, keys))
|
||||
if os.environ.get('DMSH_VK_KEEP'): print('中间产物留在', work)
|
||||
else: shutil.rmtree(work, ignore_errors=True)
|
||||
st = collections.Counter(r[1] for r in res)
|
||||
print(f'着色器 {len(res)}:成功 {st["ok"]},' + ','.join(f'{k} {v}' for k, v in st.items() if k != 'ok'))
|
||||
for lvl in [k for k in st if k != 'ok']:
|
||||
for e, n in collections.Counter(r[2] for r in res if r[1] == lvl).most_common(8): print(f' [{lvl}] {n:5d} {e}')
|
||||
sys.exit(0 if st['ok'] == len(res) else 1)
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/bin/bash
|
||||
# 把 Mac 着色器库按指定的最低系统版本重编一份:msl_retarget.sh <最低系统,如 15.0> <输出根目录> 产出 <输出根目录>/b-<翻译链版本>/
|
||||
# 为什么要有:dmsh_build.py 编库时不带最低版本参数,库里记的目标是编译这台机器的 SDK(macOS 26);老系统上加载这种库会直接失败
|
||||
# (同程序本体的最低系统版本是一回事,换了个地方)。老接口版的包(tools/mac_app.sh DM_MAC_M3=1)带的是这里重编出来的库。
|
||||
# (同程序本体的最低系统版本是一回事,换了个地方)。旧接口版的包(tools/mac_app.sh DM_MAC_M3=1)带的是这里重编出来的库。
|
||||
# 源码来源(共用缓存只读):_b 库旁边的 .metal;_bf 库(可读 tile 版本)的源码在内容寻址缓存里,按库文件内容对上。
|
||||
# 编译命令与 dmsh_build.py 相同,只多一个 -mmacosx-version-min。约 7000 个库 3 分钟。
|
||||
# Recompile the Mac shader libraries for a given minimum system version: msl_retarget.sh <minimum system, e.g. 15.0> <output root> produces <output root>/b-<translation chain version>/
|
||||
|
||||
Executable
+84
@@ -0,0 +1,84 @@
|
||||
#!/usr/bin/env python3
|
||||
# 做 Vulkan 后端要的 4 个查询核着色器包:用 glslc 把 dm/gfx/vulkan/kernels/builtin_queries.comp 按 MODE 0–3 编成 SPIR-V,
|
||||
# 再用 pack_game_shaders.py 打成 <键>.xgs。键与 MSL 版同取 dm/gfx/nvn/nvn_builtin.h 的表(main 程序本体内嵌的 4 个计算着色器)。
|
||||
# 这 4 个核是手写的,不来自游戏文件,所以能从源码重做;另外 6,927 个包是游戏着色器的翻译,不在这里做。
|
||||
# 绑定与 MSL 版一致:0 = uniform 缓冲 0(元素个数,16 字节),1 = 存储缓冲 0(计数器报告),2 = 存储缓冲 1(结果)。
|
||||
# Builds the 4 query-kernel shader bundles the Vulkan backend needs: glslc compiles dm/gfx/vulkan/kernels/builtin_queries.comp
|
||||
# into SPIR-V for MODE 0-3, and pack_game_shaders.py packs each into <key>.xgs. The keys come from the table in
|
||||
# dm/gfx/nvn/nvn_builtin.h, as for the MSL versions (the 4 compute shaders embedded in the main program itself).
|
||||
# These kernels are hand-written, not taken from the game files, so they can be rebuilt from source; the other 6,927 bundles
|
||||
# are translations of the game's shaders and are not made here.
|
||||
# Bindings as in the MSL versions: 0 = uniform buffer 0 (element count, 16 bytes), 1 = storage buffer 0 (counter reports),
|
||||
# 2 = storage buffer 1 (results).
|
||||
#
|
||||
# 用法 | Usage: pack_builtin_queries.py --output <dm/ 以外的新目录 | new directory outside dm/> [--glslc <path>]
|
||||
# glslc 缺省依次找 $GLSLC、PATH、NDK 的 shader-tools($ANDROID_NDK_HOME、$ANDROID_HOME/ndk/*)。
|
||||
# glslc defaults to $GLSLC, then PATH, then the NDK's shader-tools ($ANDROID_NDK_HOME, $ANDROID_HOME/ndk/*).
|
||||
import argparse, glob, hashlib, json, os, pathlib, re, shutil, subprocess, tempfile
|
||||
|
||||
from pack_game_shaders import pack
|
||||
|
||||
DM = pathlib.Path(__file__).resolve().parents[2]
|
||||
SOURCE = DM / 'gfx/vulkan/kernels/builtin_queries.comp'
|
||||
# builtin_queries.comp 的 MODE 0–3。
|
||||
# MODE 0-3 of builtin_queries.comp.
|
||||
MODES = ('q_val0', 'q_val8', 'q_dlt0', 'q_dlt8')
|
||||
DESCRIPTORS = [
|
||||
{'name': 'count', 'binding': 0, 'type': 'uniform_buffer', 'count': 1, 'block': {'bytes': 16},
|
||||
'source': {'category': 'nvn', 'nvn': {'kind': 'uniform', 'slot': 0}}},
|
||||
{'name': 'src', 'binding': 1, 'type': 'storage_buffer', 'count': 1,
|
||||
'source': {'category': 'nvn', 'nvn': {'kind': 'storage_pointer', 'slot': 0}}},
|
||||
{'name': 'dst', 'binding': 2, 'type': 'storage_buffer', 'count': 1,
|
||||
'source': {'category': 'nvn', 'nvn': {'kind': 'storage_pointer', 'slot': 1}}},
|
||||
]
|
||||
|
||||
|
||||
def find_glslc(given):
|
||||
found = given or os.environ.get('GLSLC') or shutil.which('glslc')
|
||||
if found:
|
||||
return found
|
||||
roots = [os.environ.get(v) for v in ('ANDROID_NDK_HOME', 'ANDROID_NDK_ROOT')]
|
||||
for sdk in (os.environ.get('ANDROID_HOME'), os.environ.get('ANDROID_SDK_ROOT')):
|
||||
if sdk:
|
||||
roots += sorted(glob.glob(os.path.join(sdk, 'ndk', '*')), reverse=True)
|
||||
for root in filter(None, roots):
|
||||
hits = glob.glob(os.path.join(root, 'shader-tools', '*', 'glslc*'))
|
||||
if hits:
|
||||
return hits[0]
|
||||
raise SystemExit('glslc not found: pass --glslc, set GLSLC, or install the Android NDK')
|
||||
|
||||
|
||||
def kernel_keys():
|
||||
text = (DM / 'gfx/nvn/nvn_builtin.h').read_text(encoding='utf-8')
|
||||
keys = {name: key for key, name in re.findall(r'\{"([0-9a-f]{16})", "(q_\w+)"\}', text)}
|
||||
missing = [name for name in MODES if name not in keys]
|
||||
if missing:
|
||||
raise SystemExit(f'nvn_builtin.h has no key for {missing}')
|
||||
return keys
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description='build the 4 query-kernel .xgs bundles from builtin_queries.comp')
|
||||
ap.add_argument('--output', type=pathlib.Path, required=True)
|
||||
ap.add_argument('--glslc')
|
||||
args = ap.parse_args()
|
||||
if args.output.resolve().is_relative_to(DM):
|
||||
raise SystemExit('output must be outside dm/')
|
||||
glslc, keys = find_glslc(args.glslc), kernel_keys()
|
||||
args.output.mkdir(parents=True, exist_ok=False)
|
||||
with tempfile.TemporaryDirectory() as work:
|
||||
for mode, name in enumerate(MODES):
|
||||
key = keys[name]
|
||||
spv = pathlib.Path(work, key + '.spv')
|
||||
subprocess.run([glslc, '-fshader-stage=comp', f'-DMODE={mode}', str(SOURCE), '-o', str(spv)], check=True)
|
||||
reflection = {'identity': {'key': key, 'name': name}, 'stage': 'cs', 'descriptors': DESCRIPTORS,
|
||||
'frozen_job': {}, 'sha256': hashlib.sha256(spv.read_bytes()).hexdigest()}
|
||||
meta = pathlib.Path(work, key + '.vk.json')
|
||||
meta.write_text(json.dumps(reflection, indent=2) + '\n', encoding='utf-8')
|
||||
key, data = pack(meta)
|
||||
(args.output / (key + '.xgs')).write_bytes(data)
|
||||
print(f'{key}.xgs {name} {len(data)} bytes sha256 {hashlib.sha256(data).hexdigest()}')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,66 @@
|
||||
# 把导出的 <键>.vk.json(反射)与同名 <键>.spv 打成 XGS1 着色器包 <键>.xgs,Vulkan 后端运行时从 files/dm/shaders/ 读。
|
||||
# 出自 biglawine 的鸿蒙移植:biglawine/d2r-mobile codex/harmony-port 544c66c 的 dm/harmony/graphics/pack_game_shaders.py。
|
||||
# 包的格式见 dm/gfx/vulkan/engine/xbg_game.h 的 xbg_shader_header:文件头、各绑定、顶点输入位置、c1 字节,然后是 SPIR-V。
|
||||
# 游戏着色器的 .vk.json 由 dmsh_vk.py 在 dmsh_xlate 翻译之后导出(它直接调这里的 pack);4 个查询核的由 pack_builtin_queries.py 现做。
|
||||
# Packs an exported <key>.vk.json (reflection) and the <key>.spv of the same name into the XGS1 shader bundle <key>.xgs,
|
||||
# which the Vulkan backend reads from files/dm/shaders/ at run time.
|
||||
# From biglawine's HarmonyOS port: dm/harmony/graphics/pack_game_shaders.py in biglawine/d2r-mobile codex/harmony-port 544c66c.
|
||||
# Bundle layout: see xbg_shader_header in dm/gfx/vulkan/engine/xbg_game.h: the header, the bindings, the vertex input
|
||||
# locations, the c1 bytes, then the SPIR-V.
|
||||
# For the game's shaders dmsh_vk.py exports the .vk.json after the dmsh_xlate translation (and calls pack here directly);
|
||||
# for the 4 query kernels pack_builtin_queries.py makes it.
|
||||
"""把校验过的 .vk.json/.spv 打成运行时 XGS1 文件(原始字节留在仓外)。 | Pack verified .vk.json/.spv into runtime XGS1 files (original bytes external). | import argparse, hashlib, json, pathlib, struct"""
|
||||
import argparse, hashlib, json, pathlib, struct
|
||||
|
||||
TYPES = {'sampler':0,'combined_image_sampler':1,'sampled_image':2,'storage_image':3,
|
||||
'uniform_texel_buffer':4,'storage_texel_buffer':5,'uniform_buffer':6,'storage_buffer':7}
|
||||
STAGES = {'vs':0,'hs':1,'ds':2,'gs':3,'ps':4,'cs':5}
|
||||
|
||||
def pack(path):
|
||||
j=json.loads(path.read_text(encoding='utf-8-sig')); key=j['identity']['key']
|
||||
spv=path.with_name(key+'.spv').read_bytes()
|
||||
if hashlib.sha256(spv).hexdigest()!=j['sha256']: raise ValueError('SPIR-V hash mismatch')
|
||||
bindings=[]
|
||||
for b in j['descriptors']:
|
||||
s=b['source']; n=s.get('nvn',{}); k=n.get('kind'); slot=n.get('slot',0)
|
||||
if s['category']=='support_buffer': source=1
|
||||
elif k in ('uniform','uniform_pointer'): source=2
|
||||
elif k=='storage_pointer': source=3
|
||||
elif k=='c1': source=4
|
||||
elif k=='driver' and n['bank'] in (0,2): source=5 if n['bank']==0 else 6
|
||||
elif k in ('texture','image') and slot is not None: source=7 if k=='texture' else 8
|
||||
else: raise ValueError(f'unmapped descriptor {b["name"]}: {s}')
|
||||
size=1392 if source==1 else b.get('block',{}).get('bytes',0)
|
||||
sampler=n.get('sampler_slot'); sampler=0xffffffff if sampler is None else sampler
|
||||
# 没给单独的采样器槽时,用 NVN 组合句柄里的采样器。
|
||||
# Without an explicit sampler slot use the sampler in the combined NVN handle.
|
||||
flags=0
|
||||
if b['type'] in ('storage_image','storage_texel_buffer') and b.get('image',{}).get('format')==0:
|
||||
if 56 in j['capabilities']: flags|=1
|
||||
if 55 in j['capabilities']: flags|=2
|
||||
if 'image' in b:
|
||||
image=b['image'];scalar=image['scalar']
|
||||
kind=0 if scalar['kind']=='float' else 2 if scalar.get('signed') else 1
|
||||
flags|=(1<<31)|(image['dim']<<8)|(image['arrayed']<<12)|(image['multisampled']<<13)|(image['depth']==1)<<14|(kind<<16)
|
||||
if source in (7,8):
|
||||
hd=s['handle_decode']
|
||||
if hd['type'] not in (0,1): raise ValueError(f'unsupported handle type {hd}')
|
||||
bindings.append(struct.pack('<8I',b['binding'],TYPES[b['type']],b['count'],size,
|
||||
source,slot or 0,sampler,flags))
|
||||
ins=sorted({x['location'] for x in j['interfaces'] if x['storage']=='input' and x['location'] is not None}) if j['stage']=='vs' else []
|
||||
c1=bytes.fromhex(j['frozen_job'].get('c1',''))
|
||||
if len(c1)%4: raise ValueError('c1 alignment')
|
||||
header=struct.pack('<8I',0x31534758,1,STAGES[j['stage']],len(bindings),len(ins),len(c1),len(spv),0)
|
||||
return key,header+b''.join(bindings)+struct.pack('<%dI'%len(ins),*ins)+c1+spv
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser(description=__doc__);ap.add_argument('--bundle',type=pathlib.Path,required=True)
|
||||
ap.add_argument('--output',type=pathlib.Path,required=True);args=ap.parse_args()
|
||||
if args.output.resolve().is_relative_to(pathlib.Path(__file__).resolve().parents[2]): raise ValueError('output must be outside repository')
|
||||
args.output.mkdir(parents=True,exist_ok=False); report=[]
|
||||
for p in sorted(args.bundle.glob('*.vk.json')):
|
||||
key,data=pack(p);(args.output/(key+'.xgs')).write_bytes(data)
|
||||
report.append({'key':key,'bytes':len(data),'sha256':hashlib.sha256(data).hexdigest()})
|
||||
(args.output/'manifest.json').write_text(json.dumps(report,indent=2)+'\n')
|
||||
print(f'packed {len(report)} genuine shaders')
|
||||
if __name__=='__main__': main()
|
||||
@@ -0,0 +1,16 @@
|
||||
cmake_minimum_required(VERSION 3.22)
|
||||
project(dm_vulkan LANGUAGES C CXX)
|
||||
set(E ${CMAKE_CURRENT_SOURCE_DIR}/engine)
|
||||
add_library(dm_vulkan_engine STATIC
|
||||
${E}/xbg_game.cpp ${E}/xbg_shader_key.c ${E}/xbg_command_clone.c
|
||||
${E}/xbg_draw_plan.c ${E}/xbg_vertex.c ${E}/xbg_quad.c ${E}/xbg_stages.cpp
|
||||
${E}/xbg_clear.cpp ${E}/xbg_blit.cpp ${E}/xbg_texture.c ${E}/xbg_depth.c
|
||||
${E}/xbg_framebuffer.c ${E}/xbg_vulkan.cpp ${E}/xbg_nvn.cpp ${E}/xbg_sampler.cpp ${E}/xbg_spirv_quad.cpp ${E}/xbg_spirv_warp.cpp ${E}/xbg_spirv_ldc.cpp ${E}/xbg_spirv_temps.cpp ${E}/xbg_spirv_raster.cpp)
|
||||
target_include_directories(dm_vulkan_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} PRIVATE ../nvn/include)
|
||||
target_compile_features(dm_vulkan_engine PUBLIC cxx_std_17)
|
||||
target_compile_options(dm_vulkan_engine PRIVATE -O2 -fno-strict-aliasing -Wall -Wextra -Wno-missing-field-initializers -Wno-format)
|
||||
set_source_files_properties(${E}/xbg_texture.c PROPERTIES COMPILE_OPTIONS -fsigned-char)
|
||||
set_target_properties(dm_vulkan_engine PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
target_link_libraries(dm_vulkan_engine PUBLIC vulkan log)
|
||||
# nvn_vk.c is compiled in dmcore (host compatibility flags); engine deliberately
|
||||
# reuses dmcore's nvn_tex.c / nvn_deswizzle.c rather than duplicate definitions.
|
||||
@@ -0,0 +1,40 @@
|
||||
> 历史检查(2026-10-15);最新集成和真机结果见 [安卓协作状态](../../../docs/ANDROID_COLLABORATION.zh-CN.md)。
|
||||
> Historical check (2026-10-15); see the [current Android status](../../../docs/ANDROID_COLLABORATION.md) for integration and device results.
|
||||
|
||||
# 安卓真实 Vulkan 后端候选(2026-10-15)
|
||||
|
||||
本轮为可编译/链接的生产路径候选,尚未接入整 App,也未真机出图。不能据此报告游戏 FPS、已运行或画面正确。
|
||||
|
||||
## 文件与接线
|
||||
|
||||
- `nvn_vk.c` 接替 CPU 空执行层,仍实现上游 `nvn_mtl.h` / `nvn_obj.h` 的 `mtl_*` ABI。
|
||||
- `engine/` 复制只读鸿蒙 gfx50-claude-perf 的真正 NVN→Vulkan 命令回放实现;原始文件 SHA-256 在 `engine/SOURCE.json`。未复制另一份 `xbg_game_nvn.c`,避免替换/重定义上游 NVN ABI。bcdec 附带原有许可证。
|
||||
- `../../android/vulkan_present.cpp/.h` 独占新增 Android 窗口/实例/设备/交换链。JNI Surface 创建/销毁分别调用 `dm_android_vk_set_window(window)` / `dm_android_vk_set_window(NULL)`;函数内部 retain/release,不在 UI 线程调用 Vulkan。调用方仍须释放自身 `ANativeWindow_fromSurface` 引用。
|
||||
- 在 `dm_main` 前且窗口有效时调用 `dm_android_vk_initialize(shader_dir,error,bytes)`。目录必须为外部匹配当前 shader control 的真实 `.xgs`,路径内部复制。失败需中止启动;不能退回无图形层伪报成功。
|
||||
- 运行前实际启用设备支持的 core features、shaderDrawParameters;BC 路径依 `enabled_core.textureCompressionBC`,无 Maleoon 特判。镜像边缘扩展仅实际启用才告知引擎。
|
||||
- 引擎所需 `nvn_new_serial`、`nvn_tex.c`、`nvn_deswizzle.c` 继续来自宿主现有目标,不能重复定义。
|
||||
|
||||
CMake可 `add_subdirectory(../gfx/vulkan ...)` 后将 `dm_vulkan_engine` 链入 dmcore;dmcore仍编 `nvn_vk.c`,新增编 `vulkan_present.cpp`。启用 CXX17;链接 vulkan/android/log/libc++;`engine/xbg_texture.c` 须 `-fsigned-char`。不让宿主强制 C compat 头污染 C++。备用源清单:engine 下全部 `.c/.cpp`(共15个)及 present.cpp;CMakeLists.txt 明列15个源。
|
||||
|
||||
## 安卓差异与同步
|
||||
|
||||
- 保留现有 Metal ABI 的 ID 全局描述符登记语义:上游 `mtl_reg_tex/mtl_reg_samp` 没有 pool 参数,引擎使用全局登记作为兼容表。没有假称解决上游多同号描述符池歧义;如游戏触发,需要另经授权修上游接口。
|
||||
- 禁异步翻译,当前游戏命令/对象指针在提交返回前解析完毕。
|
||||
- 禁 SIGSEGV/mprotect 脏页追踪及外部内存 remap 探针;不接管运行库信号链。
|
||||
- `OP_SIGNAL_EVENT` 先完成此前 GPU 工作再发布 CPU 事件值;栅栏依据真实 VkFence。有限 timeout 会返回0,不能立即标记完成。计数器和读回继续引擎既有 GPU 完成后路径。
|
||||
- present 使用真正渲染且已转 TRANSFER_SRC 的图像,离屏图→swapchain blit,FIFO/按比例居中;回调等 blit 和队列完成后成功。Surface丢失等待JNI生命周期替换,后台无窗口不跳帧计数。
|
||||
- GPU耗时/真实scanout时间尚未接入,`mtl_gpu_ms=-1`、`mtl_presented_time=0`、刷新率未知0;不得用CPU时刻冒充实际上屏时间。
|
||||
|
||||
## 本轮证据
|
||||
|
||||
命令(不访问设备/游戏资源):
|
||||
|
||||
`python dm/gfx/vulkan/check_build.py --ndk <ANDROID_SDK>/ndk/29.0.14206865 --output <PRIVATE_WORK>/vulkan-validation`
|
||||
|
||||
NDK29 clang21 arm64 Android API29:15 engine对象、adapter、present、两个现有格式/解排布依赖均编译成功;使用明确的三项宿主测试替身(log_/die/nvn_new_serial)完成 `--no-undefined` 图形链路共享库链接。完整命令/输出/源码hash在仓外 `work/vulkan-validation/validation.json`,不是整App验证。最后present生命周期修订已单对象重编并重链接。
|
||||
|
||||
产物 `libdm_vulkan_link_check.so` SHA256:`5099946a34fbf50baca3899d105acf0fa3f16b924f21f36c7231cf9da55af62c`。
|
||||
|
||||
## 尚未验证/接续
|
||||
|
||||
整App CMake/JNI接线、匹配着色器和资源导入、设备验证层、真机游戏图像/UV方向/裁剪、原生BC纹理、绘制/计算/遮挡查询、窗口切换和后台恢复、耗时与帧率。当前同步呈现和禁异步翻译是正确性基线,性能需真实热点证据再优化。进程级后端尚无退出后重新初始化接口,重启游戏需重启App进程;不能在设备/客体线程仍运行时销毁GPU对象。本轮未安装、未清数据、未改鸿蒙、未提交推送。
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Compile/link Android graphics without game resources, device access or full app."""
|
||||
import argparse, pathlib, subprocess, hashlib, json
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--ndk',type=pathlib.Path,required=True);ap.add_argument('--output',type=pathlib.Path,required=True);args=ap.parse_args()
|
||||
dm=pathlib.Path(__file__).resolve().parents[2];root=dm/'gfx/vulkan';out=args.output.resolve();out.mkdir(parents=True,exist_ok=True)
|
||||
tool=args.ndk/'toolchains/llvm/prebuilt/windows-x86_64';common=['--target=aarch64-linux-android29','--sysroot='+str(tool/'sysroot'),'-fPIC','-O1','-fsigned-char','-I'+str(dm/'gfx/nvn/include'),'-I'+str(dm/'host')]
|
||||
log=[];objects=[]
|
||||
def run(command):
|
||||
r=subprocess.run(command,capture_output=True,text=True,encoding='utf-8',errors='replace');log.append({'command':command,'exit':r.returncode,'stdout':r.stdout,'stderr':r.stderr});print(pathlib.Path(command[0]).name,'exit',r.returncode,flush=True)
|
||||
if r.returncode:
|
||||
(out/'validation.json').write_text(json.dumps(log,indent=2),encoding='utf-8');raise SystemExit(r.stderr)
|
||||
files=sorted((root/'engine').glob('*.c'))+sorted((root/'engine').glob('*.cpp'))+[root/'nvn_vk.c',dm/'android/vulkan_present.cpp',dm/'gfx/nvn/nvn_tex.c',dm/'gfx/tex/nvn_deswizzle.c']
|
||||
for p in files:
|
||||
obj=out/(p.stem+'.o');opts=['-std=c++17'] if p.suffix=='.cpp' else []
|
||||
if p.name=='nvn_vk.c':opts+=['-I'+str(dm/'android/compat/include'),'-include',str(dm/'android/compat/include/dm_android_compat.h')]
|
||||
run([str(tool/'bin/clang.exe'),*common,*opts,'-c',str(p),'-o',str(obj)]);objects.append(obj)
|
||||
# Only external host dependencies: diagnostics + hle_nvn serial generator.
|
||||
# This confirms graphics linkage, not full host linkage or execution semantics.
|
||||
stub=out/'link_host_stubs.c';stub.write_text('#include <stdint.h>\n#include <stdlib.h>\nvoid log_(const char*f,...){(void)f;}\nvoid die(const char*f,...){(void)f;abort();}\nuint64_t nvn_new_serial(void){static uint64_t n;return ++n;}\n',encoding='utf-8');obj=out/'link_host_stubs.o';run([str(tool/'bin/clang.exe'),*common,'-c',str(stub),'-o',str(obj)]);objects.append(obj)
|
||||
lib=out/'libdm_vulkan_link_check.so';run([str(tool/'bin/clang++.exe'),*common,'-shared','-Wl,--no-undefined','-o',str(lib),*[str(p) for p in objects],'-lvulkan','-landroid','-llog'])
|
||||
(out/'validation.json').write_text(json.dumps({'checks':log,'artifact':str(lib),'sha256':hashlib.sha256(lib.read_bytes()).hexdigest()},indent=2),encoding='utf-8');print('graphics-only link OK; no device validation')
|
||||
@@ -0,0 +1,141 @@
|
||||
{
|
||||
"source": "Harmony NVN-to-Vulkan implementation, imported 2026-10-15; original per-file SHA-256 values below",
|
||||
"files": [
|
||||
{
|
||||
"file": "xbg_blit.cpp",
|
||||
"source_sha256": "9c1a52d29db9c2ba8281afd7d119f0eebe7c00c5471382f9132388d98bb5b47b"
|
||||
},
|
||||
{
|
||||
"file": "xbg_blit.h",
|
||||
"source_sha256": "3c10ef623ec293800c78259ef2490e5688c1306b0cb9360759dccae7f393b3ad"
|
||||
},
|
||||
{
|
||||
"file": "xbg_clear.cpp",
|
||||
"source_sha256": "b4340b74dfedd9fe23738cea70e84574477deb70ca676b97898ab1d33fb5e941"
|
||||
},
|
||||
{
|
||||
"file": "xbg_clear.h",
|
||||
"source_sha256": "25a732b1364ae9b4a051a4a94b31619807885ec5c858b69dfa66559d8ff7642e"
|
||||
},
|
||||
{
|
||||
"file": "xbg_clear_spv.h",
|
||||
"source_sha256": "8f2901a70cc2ab1f6b4ab9c6c557a010ea94ce4989828a6250f0c06320b53c0b"
|
||||
},
|
||||
{
|
||||
"file": "xbg_command_clone.c",
|
||||
"source_sha256": "81f65b18f5699c5fe4bee5edf00df63bec1de69715eb89999af4b60967d64124"
|
||||
},
|
||||
{
|
||||
"file": "xbg_cpu_timing.h",
|
||||
"source_sha256": "d229f0985af686911d326bb17965f7fb9ddde4168c7bc141464856aba54d26b0"
|
||||
},
|
||||
{
|
||||
"file": "xbg_depth.c",
|
||||
"source_sha256": "3e88a2e1a8736a5f87c9f179edb8ef6cc511a178dc276800706936b3743b7dad"
|
||||
},
|
||||
{
|
||||
"file": "xbg_depth.h",
|
||||
"source_sha256": "93c9f396d0f17ad0dedc12276be873ebf44540509da36e8ac028eab93cda31fd"
|
||||
},
|
||||
{
|
||||
"file": "xbg_descriptor_timing.h",
|
||||
"source_sha256": "a130ceef7b4a4a90ff59efdc406b751c3996664a04d47236d255337afc1d843c"
|
||||
},
|
||||
{
|
||||
"file": "xbg_draw_plan.c",
|
||||
"source_sha256": "622062219b778258a9a557ff2ad0f9411d718022649e38fa235cc620cff38d6e"
|
||||
},
|
||||
{
|
||||
"file": "xbg_draw_plan.h",
|
||||
"source_sha256": "64ba70e73626bd558501d04be559479c5e9415f0dd7ae085ffc0e48f4bb00f66"
|
||||
},
|
||||
{
|
||||
"file": "xbg_draw_timing.h",
|
||||
"source_sha256": "07b98bce77dded45dd1a1d3ac328a6b8dfa599f5374fb3a153f36ccdf3ff9569"
|
||||
},
|
||||
{
|
||||
"file": "xbg_framebuffer.c",
|
||||
"source_sha256": "43d0d9e3894cfea321bc1c32a333ff15c79bfaf874f199b370a18f1e17931fe7"
|
||||
},
|
||||
{
|
||||
"file": "xbg_framebuffer.h",
|
||||
"source_sha256": "703a13437ffcd19acecd88a897a0458dde89fc32af3cf4c15de4b9c91c95be2e"
|
||||
},
|
||||
{
|
||||
"file": "xbg_game.cpp",
|
||||
"source_sha256": "da1222b52b67dae0ad6cc28713bb236c27a7ac250f8bfdceb71c9cd64d348555"
|
||||
},
|
||||
{
|
||||
"file": "xbg_game.h",
|
||||
"source_sha256": "f350b239253b5cd23d346d352c705a45d8c53081d58987642720106423e5b174"
|
||||
},
|
||||
{
|
||||
"file": "xbg_game_internal.h",
|
||||
"source_sha256": "22675923f18cdbad15ae4c39992c822f8e0f715bd6ca63f58276c78fe44d3011"
|
||||
},
|
||||
{
|
||||
"file": "xbg_nvn.cpp",
|
||||
"source_sha256": "8afe6c4abeabf8c299836fbbd0a06ac77db584f7bdde16f4b56bee0fccab0475"
|
||||
},
|
||||
{
|
||||
"file": "xbg_pipeline_key.h",
|
||||
"source_sha256": "1bf85b7dd11bf589946766119a75be07bc7b29422a1d422c34f4f33f0b44cf7b"
|
||||
},
|
||||
{
|
||||
"file": "xbg_provenance.h",
|
||||
"source_sha256": "a44404dceb348bf0da6c1c5754382b031d0835af32506180da347950f1c9b41a"
|
||||
},
|
||||
{
|
||||
"file": "xbg_quad.c",
|
||||
"source_sha256": "19c22404c5657abe62acca86cce7afe388616aeea6f5677d44db8f87cb22e047"
|
||||
},
|
||||
{
|
||||
"file": "xbg_quad.h",
|
||||
"source_sha256": "f34dbf2c9c1550e045e528cb4e0c7bbbbc990d362529de85eba9b26fb83c0d43"
|
||||
},
|
||||
{
|
||||
"file": "xbg_sampler.cpp",
|
||||
"source_sha256": "7b75ff1b55ab2129e5711ddfbd13d7ee7253d84a9ba30cc6285488af47db0ca9"
|
||||
},
|
||||
{
|
||||
"file": "xbg_sampler.h",
|
||||
"source_sha256": "d61447f049da230e05e21ecc976947c3e7f3f90d3def6879fe29a00faf486677"
|
||||
},
|
||||
{
|
||||
"file": "xbg_shader_key.c",
|
||||
"source_sha256": "8f396ca34711713963cc4c78c6b3d43dfe7febb6393b4dc664dd3dbd0e80bf4b"
|
||||
},
|
||||
{
|
||||
"file": "xbg_stages.cpp",
|
||||
"source_sha256": "b7e5c5603d997ab0d87b08b880646f9e7e99f6f10880585d58df2366b7aa9f3c"
|
||||
},
|
||||
{
|
||||
"file": "xbg_stages.h",
|
||||
"source_sha256": "3fc5edbab8640796b10377cb1fe178c9f6734a9375911d0a47b3fe67d94c2a6e"
|
||||
},
|
||||
{
|
||||
"file": "xbg_texture.c",
|
||||
"source_sha256": "f1732756c97b2c4254b845bedaa8b005564aa0639a3262136992d84e7e7fd379"
|
||||
},
|
||||
{
|
||||
"file": "xbg_texture.h",
|
||||
"source_sha256": "d4438006218222d3771dc8638202cdb1010e959985ab1fbc78aa451f1409f4da"
|
||||
},
|
||||
{
|
||||
"file": "xbg_vertex.c",
|
||||
"source_sha256": "e34d470579a4b7d22d9229fc81420ca6c96039c639a87d255cf485331a561154"
|
||||
},
|
||||
{
|
||||
"file": "xbg_vertex.h",
|
||||
"source_sha256": "1d20c65e27c2d379edb0e79281f49ff00130e3045c36355f67b4f42271f5c94e"
|
||||
},
|
||||
{
|
||||
"file": "xbg_vulkan.cpp",
|
||||
"source_sha256": "e44726c2fe7c8afeceebf325146d553a084e6254df79fc19cca07a3a06b6fd46"
|
||||
},
|
||||
{
|
||||
"file": "xbg_vulkan.h",
|
||||
"source_sha256": "c714270e7492950b3c055fe36d5108d97d738a543ca50a7eb8b31ea7ab4cad7d"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
# 验证 Vulkan 分层拷贝规划及填充保护,依据 U3 字节图距契约。
|
||||
# Validate Vulkan slice-copy planning and padding preservation against U3 byte image strides.
|
||||
from pathlib import Path
|
||||
import random
|
||||
from math import lcm
|
||||
|
||||
source = (Path(__file__).resolve().parent.parent / "xbg_game.cpp").read_text(encoding="utf-8")
|
||||
assert "case OP_COPY_IMAGE_STRIDE:" in source
|
||||
assert "size_t(k)*staging_image" in source
|
||||
assert "state.copy_image_stride=image" in source
|
||||
assert "row,image,region" in source and "source_bytes,row,image,decoded" in source
|
||||
rng = random.Random(20261019)
|
||||
for case in range(1000):
|
||||
w,h,d,bpp = rng.randint(1,21),rng.randint(1,13),rng.randint(1,5),rng.choice([1,2,3,4,6,8,12,16])
|
||||
row=w*bpp+rng.randint(0,13)
|
||||
staging_row=w*bpp
|
||||
image=row*h+rng.randint(0,11)
|
||||
alignment=lcm(4,bpp)
|
||||
staging_image=((staging_row*h+alignment-1)//alignment)*alignment
|
||||
guest=bytearray(rng.randbytes(image*d))
|
||||
original=bytes(guest)
|
||||
staging=bytearray(staging_image*d)
|
||||
for z in range(d):
|
||||
assert (z*staging_image)%4 == 0 and (z*staging_image)%bpp == 0
|
||||
for y in range(h):
|
||||
a=z*image+y*row;b=z*staging_image+y*staging_row
|
||||
staging[b:b+w*bpp]=guest[a:a+w*bpp]
|
||||
for z in range(d):
|
||||
for y in range(h):
|
||||
a=z*image+y*row;b=z*staging_image+y*staging_row
|
||||
guest[a:a+w*bpp]=staging[b:b+w*bpp]
|
||||
assert bytes(guest)==original
|
||||
print("PASS: 1000 seeded slice/array padding and aligned staging model cases; source wiring guards passed (no driver execution)")
|
||||
@@ -0,0 +1,36 @@
|
||||
# 延后事件与报告边界的顺序模型和源码门,依据 PR9 及 code9 的完成契约。
|
||||
# Ordering model and source gates for deferred events/report boundaries, based on PR9 and code9 completion contracts.
|
||||
# linux-build keeps only the event-guard gates of main's 07ea121 (its report batching and default-off marker differ).
|
||||
from pathlib import Path
|
||||
from texture_cache_regression import balanced
|
||||
root=Path(__file__).resolve().parent.parent
|
||||
s=(root/'xbg_game.cpp').read_text(encoding='utf-8')
|
||||
h=(root/'../../nvn/hle_nvn.c').resolve().read_text(encoding='utf-8')
|
||||
for name in ['nvnEventInitialize','nvnEventFinalize','nvnEventGetValue']:
|
||||
assert 'mtl_event_read' in balanced(h,h.index('NVN('+name+','))
|
||||
assert 'mtl_event_read' in balanced(h,h.index('static void ev_signal('))
|
||||
read=balanced(s,s.index('extern "C" void xbg_game_event_read('))
|
||||
assert read.index('gfx_drain()')<read.index('lock(mutex)')<read.index('complete_all()')
|
||||
wait=balanced(s,s.index('case OP_COUNT_+4:'))
|
||||
assert wait.index('complete_all()')<wait.index('__atomic_load_n')
|
||||
|
||||
class Events:
|
||||
def __init__(self): self.values={}; self.pending=[]
|
||||
def signal_gpu(self,a,m,v): self.pending.append((a,m,v))
|
||||
def drain(self):
|
||||
for a,m,v in self.pending:
|
||||
self.values[a]=(self.values.get(a,0)+v if m=='add' else v)&0xffffffff
|
||||
self.pending=[]
|
||||
def cpu(self,a,m,v):
|
||||
self.drain();self.values[a]=(self.values.get(a,0)+v if m=='add' else v)&0xffffffff
|
||||
def read(self,a): self.drain();return self.values.get(a,0)
|
||||
for first in ['write','add']:
|
||||
for second in ['write','add']:
|
||||
e=Events();e.values[1]=7;e.signal_gpu(1,first,11);e.cpu(1,second,3)
|
||||
expect=11 if first=='write' else 18
|
||||
expect=3 if second=='write' else expect+3
|
||||
assert e.read(1)==expect
|
||||
e.signal_gpu(1,'add',5);e.drain() # Finalize/reinitialize storage boundary.
|
||||
e.values[1]=0;e.signal_gpu(1,'write',9);assert e.read(1)==9
|
||||
e.signal_gpu(1,'write',0xffffffff);e.cpu(1,'add',2);assert e.read(1)==1
|
||||
print('PASS: event WRITE/ADD, CPU overwrite, wrap and reused storage model; host hook and command-wait source gates (guest direct reads checked separately by gfx-event-guard)')
|
||||
@@ -0,0 +1,93 @@
|
||||
// 直接调用生产的单写临时变量转发并检查合成 SPIR-V:该删的删、该留的留、引用全部有定义,输出跑出与原来相同的值。
|
||||
// Call the production single-store temporary forwarding on synthetic SPIR-V: what may go goes, what must stay stays, every
|
||||
// referenced id is defined, and the output computes the same values as the input.
|
||||
#include "../xbg_spirv_temps.h"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <set>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using Module=std::vector<uint32_t>;
|
||||
void require(bool ok,const char *why){if(!ok)throw std::runtime_error(why);}
|
||||
void op(Module &m,uint32_t opcode,std::initializer_list<uint32_t> args){m.push_back((uint32_t(args.size()+1)<<16)|opcode);m.insert(m.end(),args);}
|
||||
enum : uint32_t {tVoid=1,tFn=2,tInt=4,tPtrIn=5,tPtrOut=6,tPtrFn=7,tBool=8,
|
||||
c1=10,c2=11,c7=12,inX=30,outA=31,outB=32,outC=33,outD=34,outE=35,outF=36,outG=37,fMain=20,lEntry=21,lNext=22,
|
||||
vFwd=40,vChain=41,vTwice=42,vInit=43,vOther=44,vNamed=45,vDead=46,vNever=47,vArr=48};
|
||||
// One function, two blocks. Forwardable: vFwd, vChain (stores vFwd's load), vDead (stored, never loaded). Must stay: vOther
|
||||
// (loaded in the next block), vTwice (stored twice), vInit (initializer), vNamed (OpName), vNever (loaded, never stored),
|
||||
// vArr (written by an OpCopyMemory, which the pass does not follow).
|
||||
Module module(){
|
||||
Module m{0x07230203,0x00010300,0,100,0};
|
||||
op(m,17,{1});op(m,14,{0,1});
|
||||
op(m,15,{0,fMain,0x6e69616d,0,inX,outA,outB,outC,outD,outE,outF,outG});
|
||||
op(m,5,{vNamed,0x00706d74}); // OpName vNamed "tmp"
|
||||
for(uint32_t v:{inX})op(m,71,{v,30,0});
|
||||
{uint32_t l=0;for(uint32_t v:{outA,outB,outC,outD,outE,outF,outG})op(m,71,{v,30,l++});}
|
||||
op(m,19,{tVoid});op(m,33,{tFn,tVoid});op(m,21,{tInt,32,1});op(m,20,{tBool});
|
||||
op(m,32,{tPtrIn,1,tInt});op(m,32,{tPtrOut,3,tInt});op(m,32,{tPtrFn,7,tInt});
|
||||
op(m,43,{tInt,c1,1});op(m,43,{tInt,c2,2});op(m,43,{tInt,c7,7});
|
||||
op(m,59,{tPtrIn,inX,1});for(uint32_t v:{outA,outB,outC,outD,outE,outF,outG})op(m,59,{tPtrOut,v,3});
|
||||
op(m,54,{tVoid,fMain,0,tFn});op(m,248,{lEntry});
|
||||
for(uint32_t v:{vFwd,vChain,vTwice,vOther,vNamed,vDead,vNever,vArr})op(m,59,{tPtrFn,v,7});
|
||||
op(m,59,{tPtrFn,vInit,7,c7});
|
||||
op(m,61,{tInt,50,inX});op(m,128,{tInt,51,50,c1});
|
||||
op(m,62,{vFwd,51});op(m,61,{tInt,52,vFwd});op(m,61,{tInt,53,vFwd});op(m,128,{tInt,54,52,53});op(m,62,{outA,54});
|
||||
op(m,62,{vChain,52});op(m,61,{tInt,55,vChain});op(m,62,{outB,55});
|
||||
op(m,62,{vTwice,51});op(m,61,{tInt,56,vTwice});op(m,62,{vTwice,c2});op(m,61,{tInt,57,vTwice});op(m,128,{tInt,58,56,57});op(m,62,{outC,58});
|
||||
op(m,61,{tInt,59,vInit});op(m,62,{vInit,51});op(m,61,{tInt,60,vInit});op(m,128,{tInt,61,59,60});op(m,62,{outD,61});
|
||||
op(m,62,{vOther,51});op(m,62,{vNamed,51});op(m,61,{tInt,62,vNamed});op(m,62,{outE,62});
|
||||
op(m,62,{vDead,51});op(m,61,{tInt,63,vNever});op(m,62,{vArr,51});op(m,63,{vArr,vTwice});
|
||||
op(m,249,{lNext});op(m,248,{lNext});
|
||||
op(m,61,{tInt,64,vOther});op(m,62,{outF,64});op(m,61,{tInt,65,vArr});op(m,62,{outG,65});
|
||||
op(m,253,{});op(m,56,{});
|
||||
return m;
|
||||
}
|
||||
std::set<uint32_t> defined(const Module &m){
|
||||
std::set<uint32_t> d;
|
||||
for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16,o=m[i]&0xffff;
|
||||
if(o==19||o==20||o==21||o==32||o==33||o==248)d.insert(m[i+1]);
|
||||
else if(o==43||o==59||o==61||o==128||o==54)d.insert(m[i+2]);
|
||||
i+=wc;}
|
||||
return d;
|
||||
}
|
||||
size_t count(const Module &m,uint32_t opcode,uint32_t word1){size_t c=0;for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16;if((m[i]&0xffff)==opcode && m[i+1]==word1)c++;i+=wc;}return c;}
|
||||
// The value written to each output, by running the two straight-line blocks (OpCopyMemory copies the source variable).
|
||||
std::map<uint32_t,uint32_t> run(const Module &m,uint32_t x){
|
||||
std::map<uint32_t,uint32_t> val,mem;
|
||||
for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16,o=m[i]&0xffff;const uint32_t *a=&m[i+1];
|
||||
auto g=[&](uint32_t id){return val.count(id)?val[id]:0u;};
|
||||
if(o==43)val[a[1]]=a[2];
|
||||
else if(o==59 && a[2]==7 && wc>=5)mem[a[1]]=g(a[3]);
|
||||
else if(o==61)mem.count(a[2]) || a[2]==inX?void(val[a[1]]=a[2]==inX?x:mem[a[2]]):void(val[a[1]]=0);
|
||||
else if(o==62)mem[a[0]]=g(a[1]);
|
||||
else if(o==63)mem[a[0]]=mem[a[1]];
|
||||
else if(o==128)val[a[1]]=g(a[2])+g(a[3]);
|
||||
i+=wc;}
|
||||
std::map<uint32_t,uint32_t> r;for(uint32_t v:{outA,outB,outC,outD,outE,outF,outG})r[v]=mem[v];return r;
|
||||
}
|
||||
void reject(const Module &in,const char *why){Module out{99};require(xbg_spirv_forward_temps(in.data(),in.size(),out)==0 && out.empty(),why);}
|
||||
}
|
||||
int main(){try{
|
||||
Module in=module(),out;
|
||||
size_t k=xbg_spirv_forward_temps(in.data(),in.size(),out);
|
||||
require(k==3,"expected vFwd, vChain and vDead to go");
|
||||
for(uint32_t v:{vFwd,vChain,vDead})require(!count(out,62,v) && !defined(out).count(v),"a forwarded variable or its store is left");
|
||||
for(uint32_t v:{vTwice,vInit,vOther,vNamed,vNever,vArr})require(defined(out).count(v),"a variable that must stay was removed");
|
||||
require(count(out,62,outB)==1,"the chained store must remain");
|
||||
auto d=defined(out);
|
||||
for(size_t i=5;i<out.size();){uint32_t wc=out[i]>>16,o=out[i]&0xffff;
|
||||
if(o==62||o==128||o==61||o==63)for(uint32_t w=(o==128||o==61)?3:1;w<wc && w<=4;w++)require(d.count(out[i+w]),"an operand refers to a removed id");
|
||||
i+=wc;}
|
||||
std::mt19937 rng(11);
|
||||
for(int t=0;t<2000;t++){uint32_t x=rng();require(run(in,x)==run(out,x),"the forwarded module writes different outputs");}
|
||||
reject(Module{},"empty input");reject(Module{0x07230203},"short input");
|
||||
Module bad=module();bad[0]=0;reject(bad,"bad magic");bad=module();bad[5]=0;reject(bad,"zero word count");
|
||||
bad=module();bad[5]=0xffff0011;reject(bad,"word count past the end");
|
||||
Module none{0x07230203,0x00010300,0,8,0};op(none,17,{1});op(none,14,{0,1});reject(none,"no function");
|
||||
Module o2{99};require(!xbg_spirv_forward_temps(nullptr,5,o2) && o2.empty(),"null input");
|
||||
std::cout<<"PASS forward temps: 3 of 9 variables removed (forwarded, chained, dead), 6 kept (other block, stored twice, initializer, named, never stored, copied); outputs equal over 2000 inputs; rejects\n";return 0;
|
||||
}catch(const std::exception &e){std::cerr<<"FAIL "<<e.what()<<'\n';return 1;}}
|
||||
@@ -0,0 +1,90 @@
|
||||
// 直接调用生产的分量下标折叠并解释合成 SPIR-V:翻译器的 LDC 字寻址经只写一次的临时变量,折叠结果须与原值一致。
|
||||
// Call the production component-index fold on synthetic SPIR-V in the translator's LDC word-addressing form, through
|
||||
// single-store temporaries, and check every folded value against the original computation.
|
||||
#include "../xbg_spirv_ldc.h"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using Module=std::vector<uint32_t>;
|
||||
void require(bool ok,const char *why){if(!ok)throw std::runtime_error(why);}
|
||||
void op(Module &m,uint32_t opcode,std::initializer_list<uint32_t> args){m.push_back((uint32_t(args.size()+1)<<16)|opcode);m.insert(m.end(),args);}
|
||||
enum : uint32_t {tVoid=1,tFn=2,tInt=4,tUint=5,tPtrInUint=6,tPtrFnInt=7,tPtrFnUint=8,
|
||||
c48=10,c32=11,c2=12,c3=13,c1=14,c20=15,c4=16,inBone=30,fMain=20,lEntry=21,
|
||||
vT1=40,vT2=41,vT3=42,vT4=43,vT5=44,vMulti=45,vT6=46,vT7=47,vT8=48,vT9=49,vInit=39};
|
||||
// The skinning form: word = (bone * 48 + 32) >> 2, component = word & 3 (= 0) and (word + 1) & 3 (= 1); a multiplier of 20
|
||||
// (low bits not enough), a variable stored twice, one with an initializer, and a mask of 4 (needs three known bits).
|
||||
Module module(){
|
||||
Module m{0x07230203,0x00010300,0,100,0};
|
||||
op(m,17,{1});op(m,14,{0,1});op(m,15,{0,fMain,0x6e69616d,0,inBone});
|
||||
op(m,71,{inBone,30,0});
|
||||
op(m,19,{tVoid});op(m,33,{tFn,tVoid});op(m,21,{tInt,32,1});op(m,21,{tUint,32,0});
|
||||
op(m,32,{tPtrInUint,1,tUint});op(m,32,{tPtrFnInt,7,tInt});op(m,32,{tPtrFnUint,7,tUint});
|
||||
op(m,43,{tInt,c48,48});op(m,43,{tInt,c32,32});op(m,43,{tUint,c2,2});op(m,43,{tInt,c3,3});op(m,43,{tInt,c1,1});op(m,43,{tInt,c20,20});op(m,43,{tInt,c4,4});
|
||||
op(m,59,{tPtrInUint,inBone,1});
|
||||
op(m,54,{tVoid,fMain,0,tFn});op(m,248,{lEntry});
|
||||
for(uint32_t v:{vT1,vT2,vT4,vT5,vMulti,vT6,vT7,vT8,vT9})op(m,59,{tPtrFnInt,v,7});
|
||||
op(m,59,{tPtrFnUint,vT3,7});op(m,59,{tPtrFnInt,vInit,7,c1});
|
||||
op(m,61,{tUint,50,inBone});op(m,124,{tInt,51,50});op(m,132,{tInt,52,51,c48});
|
||||
op(m,62,{vT1,52});op(m,61,{tInt,53,vT1});op(m,128,{tInt,54,53,c32});
|
||||
op(m,62,{vT2,54});op(m,61,{tInt,55,vT2});op(m,194,{tInt,56,55,c2});op(m,124,{tUint,57,56});
|
||||
op(m,62,{vT3,57});op(m,61,{tUint,58,vT3});op(m,124,{tInt,59,58});
|
||||
op(m,199,{tInt,60,59,c3});op(m,62,{vT4,60}); // folds to 0
|
||||
op(m,128,{tInt,61,59,c1});op(m,199,{tInt,62,c3,61});op(m,62,{vT5,62}); // folds to 1 (mask on the left)
|
||||
op(m,132,{tInt,63,51,c20});op(m,194,{tInt,64,63,c2});op(m,199,{tInt,65,64,c3});op(m,62,{vT6,65}); // unknown
|
||||
op(m,62,{vMulti,52});op(m,62,{vMulti,54});op(m,61,{tInt,66,vMulti});op(m,194,{tInt,67,66,c2});op(m,199,{tInt,68,67,c3});op(m,62,{vT7,68}); // stored twice
|
||||
op(m,62,{vInit,54});op(m,61,{tInt,69,vInit});op(m,194,{tInt,70,69,c2});op(m,199,{tInt,71,70,c3});op(m,62,{vT8,71}); // initializer
|
||||
op(m,199,{tInt,72,59,c4});op(m,62,{vT9,72}); // (word & 4): needs three bits, only two known
|
||||
op(m,253,{});op(m,56,{});
|
||||
return m;
|
||||
}
|
||||
// The value stored to each Function variable, for one input, by running the straight-line body.
|
||||
std::map<uint32_t,uint32_t> run(const Module &m,uint32_t bone){
|
||||
std::map<uint32_t,uint32_t> val,mem,last;
|
||||
for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16,o=m[i]&0xffff;const uint32_t *a=&m[i+1];
|
||||
auto g=[&](uint32_t id){return val.count(id)?val[id]:0u;};
|
||||
if(o==43)val[a[1]]=a[2];
|
||||
else if(o==59 && a[2]==7 && wc>=5)mem[a[1]]=g(a[3]);
|
||||
else if(o==61)val[a[1]]=a[2]==inBone?bone:mem[a[2]];
|
||||
else if(o==62){mem[a[0]]=g(a[1]);last[a[0]]=g(a[1]);}
|
||||
else if(o==124)val[a[1]]=g(a[2]);
|
||||
else if(o==128)val[a[1]]=g(a[2])+g(a[3]);
|
||||
else if(o==132)val[a[1]]=g(a[2])*g(a[3]);
|
||||
else if(o==194)val[a[1]]=g(a[2])>>(g(a[3])&31);
|
||||
else if(o==199)val[a[1]]=g(a[2])&g(a[3]);
|
||||
i+=wc;}
|
||||
return last;
|
||||
}
|
||||
uint32_t stored_operand(const Module &m,uint32_t var){
|
||||
uint32_t r=0;for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16;if((m[i]&0xffff)==62 && m[i+1]==var)r=m[i+2];i+=wc;}return r;
|
||||
}
|
||||
uint32_t constant_value(const Module &m,uint32_t id){
|
||||
for(size_t i=5;i<m.size();){uint32_t wc=m[i]>>16;if((m[i]&0xffff)==43 && m[i+2]==id)return m[i+3];i+=wc;}
|
||||
throw std::runtime_error("not a constant");
|
||||
}
|
||||
void reject(const Module &in,const char *why){Module out{99};require(xbg_spirv_ldc_fold(in.data(),in.size(),out)==0 && out.empty(),why);}
|
||||
}
|
||||
int main(){try{
|
||||
Module in=module(),out;
|
||||
size_t k=xbg_spirv_ldc_fold(in.data(),in.size(),out);
|
||||
require(k==2,"expected exactly the two skinning components to fold");
|
||||
require(out.size()==in.size()+4 && out[3]==in[3]+1,"one new constant (0) and the bound raised by one");
|
||||
require(stored_operand(out,vT4)!=60 && constant_value(out,stored_operand(out,vT4))==0,"word & 3 must become the constant 0");
|
||||
require(stored_operand(out,vT5)==c1,"(word + 1) & 3 must reuse the existing constant 1");
|
||||
require(stored_operand(out,vT6)==65 && stored_operand(out,vT7)==68 && stored_operand(out,vT8)==71 && stored_operand(out,vT9)==72,"unprovable values stay");
|
||||
std::mt19937 rng(7);
|
||||
for(int t=0;t<20000;t++){uint32_t bone=rng();if(t<64)bone=uint32_t(t);
|
||||
auto a=run(in,bone),b=run(out,bone);
|
||||
for(uint32_t v:{vT4,vT5,vT6,vT7,vT8,vT9})require(a[v]==b[v],"a folded module stores a different value");}
|
||||
reject(Module{},"empty input");reject(Module{0x07230203},"short input");
|
||||
Module bad=module();bad[0]=0;reject(bad,"bad magic");
|
||||
bad=module();bad[5]=0;reject(bad,"zero word count");
|
||||
bad=module();bad[5]=0xffff0011;reject(bad,"word count past the end");
|
||||
Module none{0x07230203,0x00010300,0,8,0};op(none,17,{1});op(none,14,{0,1});reject(none,"nothing to fold");
|
||||
Module o2{99};require(!xbg_spirv_ldc_fold(nullptr,5,o2) && o2.empty(),"null input");
|
||||
std::cout<<"PASS ldc fold: 2 of 6 components folded (0 new, 1 reused), 4 kept (low bits short, stored twice, initializer, wide mask); 20000 inputs equal; rejects\n";return 0;
|
||||
}catch(const std::exception &e){std::cerr<<"FAIL "<<e.what()<<'\n';return 1;}}
|
||||
@@ -0,0 +1,97 @@
|
||||
// 调用真实生产策略、块间距复制和blit规划;不声称执行Vulkan/GPU。
|
||||
// Exercise actual production policy, block-pitch copying and blit planning; this does not execute Vulkan/GPU work.
|
||||
#include "../xbg_bc_policy.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#define CHECK(expression) do { if(!(expression)){printf("FAIL line %d: %s\n",__LINE__,#expression);return 1;} } while(0)
|
||||
int main(){
|
||||
CHECK(!xbg_native_bc_option(false,0,nullptr));
|
||||
CHECK(xbg_native_bc_option(false,0,"1"));
|
||||
const char *invalid_options[]={"0","","2","-1","1x","01"};
|
||||
for(const char *v:invalid_options)CHECK(!xbg_native_bc_option(false,0,v));
|
||||
CHECK(xbg_native_bc_option(true,'1',"0"));
|
||||
const int invalid_markers[]={'0','2','\n',EOF};
|
||||
for(int marker:invalid_markers)CHECK(!xbg_native_bc_option(true,marker,"1"));
|
||||
|
||||
CHECK(xbg_bc_native_format(0x40)==VK_FORMAT_UNDEFINED);
|
||||
CHECK(xbg_bc_native_format(0x51)==VK_FORMAT_UNDEFINED);
|
||||
CHECK(xbg_bc_native_format(0x41)==VK_FORMAT_BC1_RGB_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x42)==VK_FORMAT_BC1_RGBA_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x43)==VK_FORMAT_BC2_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x45)==VK_FORMAT_BC1_RGB_SRGB_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x46)==VK_FORMAT_BC1_RGBA_SRGB_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x47)==VK_FORMAT_BC2_SRGB_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x44)==VK_FORMAT_BC3_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x48)==VK_FORMAT_BC3_SRGB_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x49)==VK_FORMAT_BC4_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4a)==VK_FORMAT_BC4_SNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4b)==VK_FORMAT_BC5_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4c)==VK_FORMAT_BC5_SNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4d)==VK_FORMAT_BC7_UNORM_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4e)==VK_FORMAT_BC7_SRGB_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x4f)==VK_FORMAT_BC6H_SFLOAT_BLOCK);
|
||||
CHECK(xbg_bc_native_format(0x50)==VK_FORMAT_BC6H_UFLOAT_BLOCK);
|
||||
const VkFormatFeatureFlags features=VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT|VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT|VK_FORMAT_FEATURE_TRANSFER_SRC_BIT|VK_FORMAT_FEATURE_TRANSFER_DST_BIT;
|
||||
for(uint32_t f=0x41;f<=0x50;f++){
|
||||
bool rgba=(f<=0x48 || f==0x4d || f==0x4e);
|
||||
CHECK(xbg_bc_astc_destination(f)==rgba);
|
||||
CHECK(xbg_native_bc_eligible(f,true,true,features,1,4,0)==!rgba);
|
||||
}
|
||||
CHECK(!xbg_native_bc_eligible(0x49,false,true,features,1,1,0));
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,false,features,1,1,0));
|
||||
const VkFormatFeatureFlags required_bits[]={VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT,VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT,VK_FORMAT_FEATURE_TRANSFER_SRC_BIT,VK_FORMAT_FEATURE_TRANSFER_DST_BIT};
|
||||
for(VkFormatFeatureFlags bit:required_bits)
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,true,features&~bit,1,1,0));
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,true,features,4,1,0));
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,true,features,1,2,0));
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,true,features,1,1,0x4));
|
||||
CHECK(!xbg_native_bc_eligible(0x49,true,true,features,1,1,0x10));
|
||||
VkImageFormatProperties limits{};limits.maxExtent={64,32,1};limits.maxMipLevels=7;limits.maxArrayLayers=12;limits.sampleCounts=VK_SAMPLE_COUNT_1_BIT;
|
||||
CHECK(xbg_native_bc_extent_fits(limits,64,32,7,12));
|
||||
CHECK(!xbg_native_bc_extent_fits(limits,65,32,7,12));
|
||||
CHECK(!xbg_native_bc_extent_fits(limits,64,33,7,12));
|
||||
CHECK(!xbg_native_bc_extent_fits(limits,64,32,8,12));
|
||||
CHECK(!xbg_native_bc_extent_fits(limits,64,32,7,13));
|
||||
limits.sampleCounts=VK_SAMPLE_COUNT_4_BIT;CHECK(!xbg_native_bc_extent_fits(limits,64,32,7,12));
|
||||
|
||||
XbgBlitRegion src{8,8,3,3,1,1,0,0,1,4,4,1},dst{8,8,4,3,1,2,0,0,1,4,4,1};
|
||||
VkImageBlit blit{};VkFilter filter=VK_FILTER_LINEAR;
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)==0);
|
||||
CHECK(filter==VK_FILTER_NEAREST && blit.srcSubresource.mipLevel==1 && blit.srcSubresource.baseArrayLayer==2 && blit.dstSubresource.baseArrayLayer==3);
|
||||
CHECK(blit.srcSubresource.layerCount==1 && blit.dstOffsets[1].x==4 && blit.dstOffsets[1].y==4);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_SRGB_BLOCK,VK_FORMAT_R8G8B8A8_SRGB,src,dst,1,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)==0 && filter==VK_FILTER_NEAREST);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_SRGB_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)!=0);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_5x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)!=0);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,4,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)!=0);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,0,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)!=0);
|
||||
CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,VK_FORMAT_FEATURE_BLIT_SRC_BIT,0,&blit,&filter)!=0);
|
||||
dst.z=2;CHECK(xbg_astc_bc_plan(VK_FORMAT_ASTC_4x4_UNORM_BLOCK,VK_FORMAT_R8G8B8A8_UNORM,src,dst,0,VK_FORMAT_FEATURE_BLIT_SRC_BIT,VK_FORMAT_FEATURE_BLIT_DST_BIT,&blit,&filter)!=0);dst.z=1;
|
||||
CHECK(!xbg_copy_is_full(dst));
|
||||
CHECK(!xbg_copy_is_full({8,8,4,1,0,0,0,0,0,8,8,1}));
|
||||
CHECK(xbg_copy_is_full({8,8,4,1,0,0,0,0,0,8,8,4}));
|
||||
|
||||
XbgBcCopyRows p{};CHECK(xbg_bc_copy_rows(5,7,2,16,48,160,&p)==0);
|
||||
CHECK(p.tight==32 && p.rows==2 && p.row==48 && p.image==160 && p.guest_bytes==320 && p.packed_bytes==128);
|
||||
unsigned char guest[320],packed[128],restored[320];
|
||||
for(size_t i=0;i<sizeof guest;i++)guest[i]=static_cast<unsigned char>(i*17+13);
|
||||
memset(restored,0xcd,sizeof restored);
|
||||
CHECK(xbg_bc_copy_transfer(packed,sizeof packed,guest,sizeof guest,p,false)==0);
|
||||
CHECK(xbg_bc_copy_transfer(restored,sizeof restored,packed,sizeof packed,p,true)==0);
|
||||
for(size_t i=0;i<sizeof restored;i++){
|
||||
bool block_byte=(i%160)<32 || ((i%160)>=48 && (i%160)<80);
|
||||
CHECK(restored[i]==(block_byte?guest[i]:0xcd));
|
||||
}
|
||||
CHECK(xbg_bc_copy_transfer(restored,sizeof restored-1,packed,sizeof packed,p,true)!=0);
|
||||
CHECK(xbg_bc_copy_transfer(packed,sizeof packed,guest,sizeof guest-1,p,false)!=0);
|
||||
CHECK(xbg_bc_copy_rows(5,7,2,16,31,160,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(5,7,2,16,48,95,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(5,7,2,16,-1,0,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(5,7,0,16,0,0,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(0,7,2,16,0,0,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(5,7,2,16,INT64_MAX,0,&p)!=0);
|
||||
CHECK(xbg_bc_copy_rows(1,1,1,8,0,0,&p)==0 && p.packed_bytes==8);
|
||||
CHECK(xbg_bc_copy_rows(1,1,1,16,0,0,&p)==0 && p.packed_bytes==16);
|
||||
puts("PASS production native-BC policy, ASTC blit planner, mip/layer preservation decisions and block copy pitches; GPU NOT RUN");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Execute production query helpers in a mock command stream (CPU/WASM only).
|
||||
|
||||
Extracts the production begin/end helpers and checks their integration sites.
|
||||
The mock supplies sample values, pool allocation and report-prefix bookkeeping;
|
||||
it does not execute Vulkan, shaders, the full draw function or a driver.
|
||||
"""
|
||||
import argparse
|
||||
import pathlib
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from texture_cache_regression import balanced
|
||||
|
||||
|
||||
def main():
|
||||
ap = argparse.ArgumentParser(description=__doc__)
|
||||
ap.add_argument('--compiler', required=True)
|
||||
ap.add_argument('--node', default='node')
|
||||
args = ap.parse_args()
|
||||
source = (pathlib.Path(__file__).resolve().parent.parent / 'xbg_game.cpp').read_text(encoding='utf-8')
|
||||
declaration_start = source.index('struct OpenOcclusion ')
|
||||
declaration = source[declaration_start:source.index('open_occlusion;', declaration_start) + len('open_occlusion;')]
|
||||
end = balanced(source, source.index('void end_occlusion_query('))
|
||||
begin = balanced(source, source.index('void begin_occlusion_query('))
|
||||
endpass = balanced(source, source.index('void end_open_pass('))
|
||||
assert endpass.index('end_occlusion_query(') < endpass.index('vkCmdEndRenderPass(')
|
||||
reset = balanced(source, source.index('case OP_RESET_COUNTER:'))
|
||||
assert reset.index('end_occlusion_query(') < reset.index('++counter_epoch')
|
||||
report = balanced(source, source.index('case OP_REPORT_COUNTER:'))
|
||||
# 样本报告在任何后续 draw 之前用非 draw 的 Commands 结束计数段;时间戳报告不结束 pass,以免切开 tiling pass。
|
||||
# A samples report ends the open run with a non-draw Commands before any later draw; a timestamp report keeps the pass,
|
||||
# so that it does not split a tiling pass.
|
||||
assert 'else{Commands c;' in report and report.index('epochs[counter_epoch].size()') < report.index('else{Commands c;')
|
||||
commands = balanced(source, source.index('struct Commands '))
|
||||
assert 'end_open_pass()' in commands
|
||||
clear = balanced(source, source.index('void clear_attachment('))
|
||||
assert clear.index('end_occlusion_query(') < clear.index('masked.encode(')
|
||||
draw = balanced(source, source.index('void draw(int prim'))
|
||||
assert 'occlusion_batch_enabled' in draw
|
||||
assert 'begin_occlusion_query(' in draw and 'end_occlusion_query(' in draw
|
||||
assert 'vkCmdBeginQuery(' not in draw and 'vkCmdEndQuery(' not in draw
|
||||
prefix = r'''
|
||||
typedef __UINT32_TYPE__ uint32_t;typedef __UINT64_TYPE__ uint64_t;
|
||||
typedef unsigned VkCommandBuffer;typedef unsigned VkQueryPool;
|
||||
constexpr unsigned VK_NULL_HANDLE=0,VK_QUERY_CONTROL_PRECISE_BIT=1;
|
||||
int failure=0;void need(bool ok,const char*){if(!ok)failure=1;}
|
||||
struct Record{unsigned epoch=0;uint64_t value=0;bool allocated=false,ended=false;};
|
||||
Record records[8192];unsigned current_epoch=0,current_id=0,active_id=0,active_cmd=0;
|
||||
unsigned begins=0,ends=0,pass_cmd=0,pass_id=0,used[2]={},growth=0;
|
||||
uint64_t occlusion_queries_started=0;
|
||||
uint64_t expected[4]={};
|
||||
void vkCmdBeginQuery(unsigned cmd,unsigned pool,unsigned index,unsigned flags){
|
||||
if(active_id || !cmd || pass_cmd!=cmd || flags!=1)failure=2;
|
||||
unsigned id=pool*256+index;if(id>=8192 || !records[id].allocated || records[id].ended)failure=3;
|
||||
active_id=id;active_cmd=cmd;++begins;
|
||||
}
|
||||
void vkCmdEndQuery(unsigned cmd,unsigned pool,unsigned index){
|
||||
unsigned id=pool*256+index;if(active_id!=id || active_cmd!=cmd || pass_cmd!=cmd)failure=4;
|
||||
records[id].ended=true;active_id=active_cmd=0;++ends;
|
||||
}
|
||||
struct OpenPass{unsigned cmd=0;bool depth_attached=false,depth_used=false;} open_pass;
|
||||
void pass_prof_end(unsigned){}
|
||||
// end_open_pass's per-op pass-end and idle-depth counters (diagnostics only).
|
||||
uint64_t depth_idle_passes=0,pass_end_by[64]={};unsigned cur_op=0;void pass_prof_depth_idle(unsigned){}
|
||||
void vkCmdEndRenderPass(unsigned cmd){if(active_id || pass_cmd!=cmd)failure=7;}
|
||||
'''
|
||||
model = r'''
|
||||
void close_pass(){end_open_pass();if(active_id)failure=5;pass_cmd=pass_id=0;}
|
||||
void ensure_pass(unsigned cmd,unsigned pass){if(pass_cmd!=cmd || pass_id!=pass){close_pass();pass_cmd=cmd;pass_id=pass;open_pass.cmd=cmd;}}
|
||||
void draw(unsigned slot,unsigned pass,unsigned samples,bool batch){
|
||||
unsigned cmd=slot+1;
|
||||
if(pass_cmd!=cmd || pass_id!=pass)close_pass();
|
||||
unsigned pool=0,index=0;
|
||||
if(!open_occlusion.cmd){
|
||||
unsigned n=used[slot]++;index=n%256;pool=1+slot*12+n/256;
|
||||
if(index==0){close_pass();++growth;} // production pool growth resets outside the pass
|
||||
current_id=pool*256+index;records[current_id].allocated=true;records[current_id].epoch=current_epoch;
|
||||
}
|
||||
ensure_pass(cmd,pass);
|
||||
if(!open_occlusion.cmd)begin_occlusion_query(cmd,pool,index);
|
||||
if(!active_id)failure=6;else records[active_id].value+=samples;
|
||||
expected[current_epoch]+=samples;
|
||||
if(!batch)end_occlusion_query();
|
||||
}
|
||||
void clear(unsigned synthetic_samples,int control){
|
||||
if(control!=1)end_occlusion_query();
|
||||
// A backend masked-clear triangle must never contribute to guest counters.
|
||||
if(active_id)records[active_id].value+=synthetic_samples;
|
||||
}
|
||||
void reset(int control){if(control!=2)end_occlusion_query();++current_epoch;}
|
||||
bool report(){close_pass();uint64_t sum[4]={};
|
||||
for(unsigned i=0;i<8192;i++)if(records[i].allocated){if(!records[i].ended)return false;sum[records[i].epoch]+=records[i].value;}
|
||||
for(unsigned e=0;e<=current_epoch;e++)if(sum[e]!=expected[e])return false;
|
||||
return !failure;
|
||||
}
|
||||
int scenario(bool batch,int control){
|
||||
failure=0;current_epoch=current_id=active_id=active_cmd=begins=ends=pass_cmd=pass_id=growth=0;
|
||||
used[0]=used[1]=0;open_occlusion={};
|
||||
for(auto &r:records)r=Record{};for(auto &v:expected)v=0;
|
||||
if(!report())return 10; // zero-draw timestamp/counter report
|
||||
for(unsigned i=0;i<813;i++)draw(0,1,1+i%7,batch);
|
||||
unsigned ui_segments=begins;if(ui_segments!=(batch?1u:813u))return 11;
|
||||
if(!report())return 12; // first prefix excludes all subsequent draws
|
||||
draw(0,1,13,batch);draw(0,1,17,batch);
|
||||
clear(999,control);draw(0,1,19,batch);
|
||||
if(!report())return 13;
|
||||
draw(0,2,23,batch);reset(control);draw(0,2,29,batch);
|
||||
if(!report())return 14; // reset inside same renderpass keeps old epoch separate
|
||||
reset(control);if(!report())return 15; // empty epoch and repeated report
|
||||
// Pool growth at 256, renderpass switches and both slots, including reuse.
|
||||
for(unsigned i=0;i<600;i++){draw(i&1,10+i,1+i%11,batch);if(i%31==0 && !report())return 16;}
|
||||
if(!report())return 17;
|
||||
if(begins!=ends || active_id || open_occlusion.cmd)return 18;
|
||||
if(growth<4 || used[0]<256 || used[1]<256)return 19;
|
||||
return 0;
|
||||
}
|
||||
extern "C" int run_tests(int control){
|
||||
if(control)return scenario(true,control);
|
||||
int a=scenario(true,0);if(a)return a;
|
||||
int b=scenario(false,0);return b?100+b:0;
|
||||
}
|
||||
'''
|
||||
with tempfile.TemporaryDirectory(prefix='xbg-occlusion-batch-') as temp:
|
||||
cpp, wasm = pathlib.Path(temp) / 'test.cpp', pathlib.Path(temp) / 'test.wasm'
|
||||
cpp.write_text(prefix + declaration + '\n' + end + '\n' + begin + '\n' + endpass + model, encoding='utf-8')
|
||||
subprocess.run([args.compiler, '--target=wasm32', '-std=c++17', '-ffreestanding',
|
||||
'-fno-exceptions', '-fno-rtti', '-nostdlib', '-Wl,--no-entry',
|
||||
'-Wl,--export=run_tests', str(cpp), '-o', str(wasm)], check=True)
|
||||
js = ('const fs=require("fs");WebAssembly.instantiate(fs.readFileSync(process.argv[1]))'
|
||||
'.then(({instance})=>{for(const [mode,want] of [[0,0],[1,13],[2,14]]){'
|
||||
'let got=instance.exports.run_tests(mode);if(got!==want)'
|
||||
'throw Error(`mode ${mode}: got ${got}, expected ${want}`);'
|
||||
'console.log(`mode ${mode}: ${got} (expected ${want})`);}});')
|
||||
subprocess.run([args.node, '-e', js, str(wasm)], check=True)
|
||||
print('PASS: production begin/end helpers; batched and per-draw prefixes/epochs, clear exclusion, pool256 and slots; negative controls caught. CPU mocks only, no Vulkan/device.')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,165 @@
|
||||
// 独立真机正确性小样:无 Surface/游戏资源/文件操作,不测游戏性能。
|
||||
// Standalone device correctness probe: no Surface, game assets, files or FPS claims.
|
||||
// Build separately with Vulkan headers/loader; never link into the game library.
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
#include "../xbg_clear_spv.h"
|
||||
|
||||
namespace {
|
||||
constexpr uint32_t count=11,side=32;
|
||||
void check(VkResult result,const char *call){if(result!=VK_SUCCESS){
|
||||
std::fprintf(stderr,"FAIL %s VkResult=%d\n",call,int(result));throw std::runtime_error(call);}}
|
||||
#define VK(call) check((call),#call)
|
||||
struct Probe {
|
||||
VkInstance instance{};VkPhysicalDevice physical{};VkDevice device{};VkQueue queue{};
|
||||
uint32_t family=0;VkPhysicalDeviceMemoryProperties memories{};
|
||||
VkImage image{};VkDeviceMemory image_memory{};VkImageView view{};
|
||||
VkRenderPass pass{};VkFramebuffer framebuffer{};VkShaderModule vs{},fs{};
|
||||
VkPipelineLayout layout{};VkPipeline pipeline{};VkCommandPool commands{};
|
||||
VkCommandBuffer cmd{};VkQueryPool queries{};VkBuffer buffer{};VkDeviceMemory memory{};
|
||||
VkFence fence{};void *mapped=nullptr;bool coherent=false;
|
||||
~Probe(){
|
||||
if(device){vkDeviceWaitIdle(device);if(mapped)vkUnmapMemory(device,memory);
|
||||
if(fence)vkDestroyFence(device,fence,nullptr);
|
||||
if(commands)vkDestroyCommandPool(device,commands,nullptr);
|
||||
if(queries)vkDestroyQueryPool(device,queries,nullptr);
|
||||
if(buffer)vkDestroyBuffer(device,buffer,nullptr);if(memory)vkFreeMemory(device,memory,nullptr);
|
||||
if(pipeline)vkDestroyPipeline(device,pipeline,nullptr);
|
||||
if(layout)vkDestroyPipelineLayout(device,layout,nullptr);
|
||||
if(vs)vkDestroyShaderModule(device,vs,nullptr);if(fs)vkDestroyShaderModule(device,fs,nullptr);
|
||||
if(framebuffer)vkDestroyFramebuffer(device,framebuffer,nullptr);
|
||||
if(pass)vkDestroyRenderPass(device,pass,nullptr);if(view)vkDestroyImageView(device,view,nullptr);
|
||||
if(image)vkDestroyImage(device,image,nullptr);if(image_memory)vkFreeMemory(device,image_memory,nullptr);
|
||||
vkDestroyDevice(device,nullptr);}
|
||||
if(instance)vkDestroyInstance(instance,nullptr);
|
||||
}
|
||||
uint32_t memory_type(uint32_t bits,VkMemoryPropertyFlags required,VkMemoryPropertyFlags preferred=0){
|
||||
for(unsigned preference=0;preference<2;++preference)for(uint32_t i=0;i<memories.memoryTypeCount;++i)
|
||||
if((bits&(1u<<i)) && (memories.memoryTypes[i].propertyFlags&required)==required &&
|
||||
(preference || (memories.memoryTypes[i].propertyFlags&preferred)==preferred))return i;
|
||||
throw std::runtime_error("No compatible memory type");
|
||||
}
|
||||
void initialize(){
|
||||
VkApplicationInfo app{VK_STRUCTURE_TYPE_APPLICATION_INFO};app.pApplicationName="occlusion-device-probe";app.apiVersion=VK_API_VERSION_1_1;
|
||||
VkInstanceCreateInfo ic{VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO};ic.pApplicationInfo=&app;VK(vkCreateInstance(&ic,nullptr,&instance));
|
||||
uint32_t n=0;VK(vkEnumeratePhysicalDevices(instance,&n,nullptr));std::vector<VkPhysicalDevice> devices(n);
|
||||
VK(vkEnumeratePhysicalDevices(instance,&n,devices.data()));
|
||||
for(auto candidate:devices){VkPhysicalDeviceProperties p;vkGetPhysicalDeviceProperties(candidate,&p);
|
||||
VkPhysicalDeviceFeatures f;vkGetPhysicalDeviceFeatures(candidate,&f);
|
||||
if(p.apiVersion<VK_API_VERSION_1_1 || !f.occlusionQueryPrecise)continue;
|
||||
uint32_t qn=0;vkGetPhysicalDeviceQueueFamilyProperties(candidate,&qn,nullptr);std::vector<VkQueueFamilyProperties> qs(qn);
|
||||
vkGetPhysicalDeviceQueueFamilyProperties(candidate,&qn,qs.data());
|
||||
for(uint32_t q=0;q<qn;++q)if(qs[q].queueCount && (qs[q].queueFlags&VK_QUEUE_GRAPHICS_BIT)){physical=candidate;family=q;break;}
|
||||
if(physical)break;
|
||||
}
|
||||
if(!physical)throw std::runtime_error("Vulkan1.1 graphics device with PRECISE queries required");
|
||||
VkPhysicalDeviceProperties p;vkGetPhysicalDeviceProperties(physical,&p);
|
||||
std::printf("GPU=%s API=%u.%u.%u driver=%u vendor=%#x device=%#x\n",p.deviceName,
|
||||
VK_VERSION_MAJOR(p.apiVersion),VK_VERSION_MINOR(p.apiVersion),VK_VERSION_PATCH(p.apiVersion),p.driverVersion,p.vendorID,p.deviceID);
|
||||
float priority=1;VkDeviceQueueCreateInfo qc{VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO};qc.queueFamilyIndex=family;qc.queueCount=1;qc.pQueuePriorities=&priority;
|
||||
VkPhysicalDeviceFeatures features{};features.occlusionQueryPrecise=VK_TRUE;
|
||||
VkDeviceCreateInfo dc{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO};dc.queueCreateInfoCount=1;dc.pQueueCreateInfos=&qc;dc.pEnabledFeatures=&features;
|
||||
VK(vkCreateDevice(physical,&dc,nullptr,&device));vkGetDeviceQueue(device,family,0,&queue);vkGetPhysicalDeviceMemoryProperties(physical,&memories);
|
||||
VkImageCreateInfo ii{VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO};ii.imageType=VK_IMAGE_TYPE_2D;ii.format=VK_FORMAT_R8G8B8A8_UNORM;ii.extent={side,side,1};
|
||||
ii.mipLevels=ii.arrayLayers=1;ii.samples=VK_SAMPLE_COUNT_1_BIT;ii.tiling=VK_IMAGE_TILING_OPTIMAL;ii.usage=VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;ii.sharingMode=VK_SHARING_MODE_EXCLUSIVE;
|
||||
VK(vkCreateImage(device,&ii,nullptr,&image));VkMemoryRequirements req;vkGetImageMemoryRequirements(device,image,&req);
|
||||
VkMemoryAllocateInfo ma{VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO};ma.allocationSize=req.size;ma.memoryTypeIndex=memory_type(req.memoryTypeBits,0,VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT);
|
||||
VK(vkAllocateMemory(device,&ma,nullptr,&image_memory));VK(vkBindImageMemory(device,image,image_memory,0));
|
||||
VkImageViewCreateInfo vi{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO};vi.image=image;vi.viewType=VK_IMAGE_VIEW_TYPE_2D;vi.format=ii.format;vi.subresourceRange={VK_IMAGE_ASPECT_COLOR_BIT,0,1,0,1};
|
||||
VK(vkCreateImageView(device,&vi,nullptr,&view));
|
||||
VkAttachmentDescription a{};a.format=ii.format;a.samples=ii.samples;a.loadOp=VK_ATTACHMENT_LOAD_OP_CLEAR;a.storeOp=VK_ATTACHMENT_STORE_OP_STORE;
|
||||
a.stencilLoadOp=VK_ATTACHMENT_LOAD_OP_DONT_CARE;a.stencilStoreOp=VK_ATTACHMENT_STORE_OP_DONT_CARE;a.initialLayout=a.finalLayout=VK_IMAGE_LAYOUT_GENERAL;
|
||||
VkAttachmentReference color{0,VK_IMAGE_LAYOUT_GENERAL};VkSubpassDescription sub{};sub.pipelineBindPoint=VK_PIPELINE_BIND_POINT_GRAPHICS;sub.colorAttachmentCount=1;sub.pColorAttachments=&color;
|
||||
VkSubpassDependency dep[2]={{VK_SUBPASS_EXTERNAL,0,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,
|
||||
VK_ACCESS_MEMORY_WRITE_BIT,VK_ACCESS_COLOR_ATTACHMENT_READ_BIT|VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,0},
|
||||
{0,VK_SUBPASS_EXTERNAL,VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,VK_PIPELINE_STAGE_ALL_COMMANDS_BIT,
|
||||
VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT,VK_ACCESS_MEMORY_READ_BIT|VK_ACCESS_MEMORY_WRITE_BIT,0}};
|
||||
VkRenderPassCreateInfo rp{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO};rp.attachmentCount=1;rp.pAttachments=&a;rp.subpassCount=1;rp.pSubpasses=⊂rp.dependencyCount=2;rp.pDependencies=dep;
|
||||
VK(vkCreateRenderPass(device,&rp,nullptr,&pass));VkFramebufferCreateInfo fb{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO};fb.renderPass=pass;fb.attachmentCount=1;fb.pAttachments=&view;fb.width=fb.height=side;fb.layers=1;
|
||||
VK(vkCreateFramebuffer(device,&fb,nullptr,&framebuffer));
|
||||
VkShaderModuleCreateInfo sm{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO};sm.codeSize=sizeof(xbg_clear_vs);sm.pCode=xbg_clear_vs;VK(vkCreateShaderModule(device,&sm,nullptr,&vs));
|
||||
sm.codeSize=sizeof(xbg_clear_fs_float);sm.pCode=xbg_clear_fs_float;VK(vkCreateShaderModule(device,&sm,nullptr,&fs));
|
||||
VkPushConstantRange push{VK_SHADER_STAGE_FRAGMENT_BIT,0,16};VkPipelineLayoutCreateInfo pl{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO};pl.pushConstantRangeCount=1;pl.pPushConstantRanges=&push;
|
||||
VK(vkCreatePipelineLayout(device,&pl,nullptr,&layout));
|
||||
VkPipelineShaderStageCreateInfo stages[2]={{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,nullptr,0,VK_SHADER_STAGE_VERTEX_BIT,vs,"main",nullptr},
|
||||
{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO,nullptr,0,VK_SHADER_STAGE_FRAGMENT_BIT,fs,"main",nullptr}};
|
||||
VkPipelineVertexInputStateCreateInfo vertex{VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO};
|
||||
VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO};assembly.topology=VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
|
||||
VkPipelineViewportStateCreateInfo vp{VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO};vp.viewportCount=vp.scissorCount=1;
|
||||
VkPipelineRasterizationStateCreateInfo raster{VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO};raster.polygonMode=VK_POLYGON_MODE_FILL;raster.cullMode=VK_CULL_MODE_NONE;raster.lineWidth=1;
|
||||
VkPipelineMultisampleStateCreateInfo ms{VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO};ms.rasterizationSamples=VK_SAMPLE_COUNT_1_BIT;
|
||||
VkPipelineDepthStencilStateCreateInfo depth{VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO};
|
||||
VkPipelineColorBlendAttachmentState ba{};ba.colorWriteMask=15;VkPipelineColorBlendStateCreateInfo blend{VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO};blend.attachmentCount=1;blend.pAttachments=&ba;
|
||||
VkDynamicState dyn[]={VK_DYNAMIC_STATE_VIEWPORT,VK_DYNAMIC_STATE_SCISSOR};VkPipelineDynamicStateCreateInfo dynamic{VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO};dynamic.dynamicStateCount=2;dynamic.pDynamicStates=dyn;
|
||||
VkGraphicsPipelineCreateInfo pc{VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO};pc.stageCount=2;pc.pStages=stages;pc.pVertexInputState=&vertex;pc.pInputAssemblyState=&assembly;pc.pViewportState=&vp;
|
||||
pc.pRasterizationState=&raster;pc.pMultisampleState=&ms;pc.pDepthStencilState=&depth;pc.pColorBlendState=&blend;pc.pDynamicState=&dynamic;pc.layout=layout;pc.renderPass=pass;
|
||||
VK(vkCreateGraphicsPipelines(device,VK_NULL_HANDLE,1,&pc,nullptr,&pipeline));
|
||||
VkQueryPoolCreateInfo qp{VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO};qp.queryType=VK_QUERY_TYPE_OCCLUSION;qp.queryCount=count;VK(vkCreateQueryPool(device,&qp,nullptr,&queries));
|
||||
VkBufferCreateInfo bi{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO};bi.size=count*sizeof(uint64_t);bi.usage=VK_BUFFER_USAGE_TRANSFER_DST_BIT;bi.sharingMode=VK_SHARING_MODE_EXCLUSIVE;VK(vkCreateBuffer(device,&bi,nullptr,&buffer));
|
||||
vkGetBufferMemoryRequirements(device,buffer,&req);ma.allocationSize=req.size;ma.memoryTypeIndex=memory_type(req.memoryTypeBits,VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT,VK_MEMORY_PROPERTY_HOST_COHERENT_BIT);
|
||||
coherent=(memories.memoryTypes[ma.memoryTypeIndex].propertyFlags&VK_MEMORY_PROPERTY_HOST_COHERENT_BIT)!=0;
|
||||
VK(vkAllocateMemory(device,&ma,nullptr,&memory));VK(vkBindBufferMemory(device,buffer,memory,0));VK(vkMapMemory(device,memory,0,VK_WHOLE_SIZE,0,&mapped));
|
||||
std::memset(mapped,0xff,count*sizeof(uint64_t));if(!coherent){VkMappedMemoryRange range{VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE};range.memory=memory;range.size=VK_WHOLE_SIZE;VK(vkFlushMappedMemoryRanges(device,1,&range));}
|
||||
VkCommandPoolCreateInfo cp{VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO};cp.queueFamilyIndex=family;VK(vkCreateCommandPool(device,&cp,nullptr,&commands));
|
||||
VkCommandBufferAllocateInfo ca{VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO};ca.commandPool=commands;ca.level=VK_COMMAND_BUFFER_LEVEL_PRIMARY;ca.commandBufferCount=1;VK(vkAllocateCommandBuffers(device,&ca,&cmd));
|
||||
VkFenceCreateInfo fc{VK_STRUCTURE_TYPE_FENCE_CREATE_INFO};VK(vkCreateFence(device,&fc,nullptr,&fence));
|
||||
}
|
||||
void begin_pass(){VkClearValue zero{};VkRenderPassBeginInfo b{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO};b.renderPass=pass;b.framebuffer=framebuffer;b.renderArea.extent={side,side};b.clearValueCount=1;b.pClearValues=&zero;
|
||||
vkCmdBeginRenderPass(cmd,&b,VK_SUBPASS_CONTENTS_INLINE);vkCmdBindPipeline(cmd,VK_PIPELINE_BIND_POINT_GRAPHICS,pipeline);
|
||||
VkViewport v{0,0,float(side),float(side),0,1};vkCmdSetViewport(cmd,0,1,&v);float rgba[4]={1,0,0,1};vkCmdPushConstants(cmd,layout,VK_SHADER_STAGE_FRAGMENT_BIT,0,16,rgba);}
|
||||
void draw(uint32_t size){VkRect2D sc{{0,0},{size,size}};vkCmdSetScissor(cmd,0,1,&sc);vkCmdDraw(cmd,3,1,0,0);}
|
||||
void start(unsigned q){vkCmdBeginQuery(cmd,queries,q,VK_QUERY_CONTROL_PRECISE_BIT);}
|
||||
void end(unsigned q){vkCmdEndQuery(cmd,queries,q);}
|
||||
bool run(){
|
||||
VkCommandBufferBeginInfo cb{VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO};cb.flags=VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;VK(vkBeginCommandBuffer(cmd,&cb));
|
||||
vkCmdResetQueryPool(cmd,queries,0,count);
|
||||
VkImageMemoryBarrier im{VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER};im.oldLayout=VK_IMAGE_LAYOUT_UNDEFINED;im.newLayout=VK_IMAGE_LAYOUT_GENERAL;im.image=image;
|
||||
im.srcQueueFamilyIndex=im.dstQueueFamilyIndex=VK_QUEUE_FAMILY_IGNORED;im.subresourceRange={VK_IMAGE_ASPECT_COLOR_BIT,0,1,0,1};im.dstAccessMask=VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
|
||||
vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT,VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT,0,0,nullptr,0,nullptr,1,&im);
|
||||
begin_pass();
|
||||
// 同一组3 draw:1024+256+64=1344,逐draw与聚合应相等。
|
||||
// Three draws: 1024+256+64=1344, separate and grouped queries must agree.
|
||||
const uint32_t sizes[3]={32,16,8};for(unsigned i=0;i<3;++i){start(i);draw(sizes[i]);end(i);}
|
||||
start(3);for(auto size:sizes)draw(size);end(3);
|
||||
// clear前后分段;排除真正ClearAttachments及模拟masked-clear的合成draw。
|
||||
// Split around both ClearAttachments and a synthetic masked-clear draw.
|
||||
start(4);draw(32);end(4);
|
||||
VkClearAttachment clear{};clear.aspectMask=VK_IMAGE_ASPECT_COLOR_BIT;clear.colorAttachment=0;
|
||||
VkClearRect rect{{{0,0},{32,32}},0,1};vkCmdClearAttachments(cmd,1,&clear,1,&rect);draw(32);
|
||||
start(5);draw(16);end(5);
|
||||
// 两epoch,epoch0的report前缀1024、末尾1280;epoch1为64+256=320。
|
||||
// Two epochs: epoch0 report prefix 1024, final 1280; epoch1 total 320.
|
||||
start(6);draw(32);end(6); // report boundary, no query may straddle it
|
||||
start(7);draw(16);end(7); // reset boundary before starting epoch1
|
||||
start(8);draw(8);draw(16);end(8);
|
||||
// 同一逻辑counter跨两个renderpass,必须拆query:1280+64=1344。
|
||||
// One logical counter across two renderpasses: split queries, 1280+64=1344.
|
||||
start(9);draw(32);draw(16);end(9);vkCmdEndRenderPass(cmd);
|
||||
begin_pass();start(10);draw(8);end(10);vkCmdEndRenderPass(cmd);
|
||||
// 有意与生产相同:64_BIT且不加WAIT;哨兵能检出未写回的结果。
|
||||
// Deliberately match production: 64_BIT without WAIT; detect unwritten results.
|
||||
vkCmdCopyQueryPoolResults(cmd,queries,0,count,buffer,0,sizeof(uint64_t),VK_QUERY_RESULT_64_BIT);
|
||||
VkMemoryBarrier host{VK_STRUCTURE_TYPE_MEMORY_BARRIER};host.srcAccessMask=VK_ACCESS_TRANSFER_WRITE_BIT;host.dstAccessMask=VK_ACCESS_HOST_READ_BIT;
|
||||
vkCmdPipelineBarrier(cmd,VK_PIPELINE_STAGE_TRANSFER_BIT,VK_PIPELINE_STAGE_HOST_BIT,0,1,&host,0,nullptr,0,nullptr);
|
||||
VK(vkEndCommandBuffer(cmd));VkSubmitInfo submit{VK_STRUCTURE_TYPE_SUBMIT_INFO};submit.commandBufferCount=1;submit.pCommandBuffers=&cmd;VK(vkQueueSubmit(queue,1,&submit,fence));
|
||||
VK(vkWaitForFences(device,1,&fence,VK_TRUE,10000000000ull));
|
||||
if(!coherent){VkMappedMemoryRange range{VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE};range.memory=memory;range.size=VK_WHOLE_SIZE;VK(vkInvalidateMappedMemoryRanges(device,1,&range));}
|
||||
uint64_t copied[count],direct[count]{};std::memcpy(copied,mapped,sizeof copied);
|
||||
VK(vkGetQueryPoolResults(device,queries,0,count,sizeof direct,direct,sizeof(uint64_t),VK_QUERY_RESULT_64_BIT));
|
||||
const uint64_t expected[count]={1024,256,64,1344,1024,256,1024,256,320,1280,64};bool good=true;
|
||||
for(unsigned i=0;i<count;++i){std::printf("query=%u get=%llu copy=%llu expected=%llu\n",i,(unsigned long long)direct[i],(unsigned long long)copied[i],(unsigned long long)expected[i]);
|
||||
good&=direct[i]==expected[i] && copied[i]==direct[i];}
|
||||
std::printf("separate_sum=%llu batched=%llu clear_excluded=%llu epoch0_prefix=%llu epoch0_total=%llu epoch1_total=%llu two_pass_sum=%llu\n",
|
||||
(unsigned long long)(direct[0]+direct[1]+direct[2]),(unsigned long long)direct[3],(unsigned long long)(direct[4]+direct[5]),
|
||||
(unsigned long long)direct[6],(unsigned long long)(direct[6]+direct[7]),(unsigned long long)direct[8],(unsigned long long)(direct[9]+direct[10]));
|
||||
good&=direct[0]+direct[1]+direct[2]==direct[3] && direct[4]+direct[5]==1280 && direct[6]+direct[7]==1280 && direct[9]+direct[10]==1344;
|
||||
std::printf("%s queries=%u (device correctness only; not game FPS)\n",good?"PASS":"FAIL",count);return good;
|
||||
}
|
||||
};
|
||||
}
|
||||
int main(){try{Probe probe;probe.initialize();return probe.run()?0:1;}
|
||||
catch(const std::exception &e){std::fprintf(stderr,"FAIL %s\n",e.what());return 2;}}
|
||||
@@ -0,0 +1,50 @@
|
||||
# 核对生产State完整字段清单及上一draw管线memo的失效接线;补足ABI padding内新增字段无法靠sizeof发现的情况。
|
||||
# Check the full production State inventory and the previous-draw pipeline memo's invalidation wiring, including new fields
|
||||
# hidden inside ABI padding.
|
||||
# memo键按指针记着色器、布局定义和pass定义(xbg_game.cpp PipeMemoKey);这些对象只在关闭时释放,且先于释放清掉memo。
|
||||
# The memo key holds shader, layout-definition and pass-definition pointers (xbg_game.cpp PipeMemoKey); those objects are freed
|
||||
# only at shutdown, after the clear_* calls that drop the memo.
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
from texture_cache_regression import balanced
|
||||
|
||||
root = Path(__file__).resolve().parent.parent
|
||||
source = (root / 'xbg_game.cpp').read_text(encoding='utf-8')
|
||||
start = source.index('struct State {')
|
||||
body = source[source.index('{', start) + 1:source.index('\n} state;', start)]
|
||||
while '{' in body:
|
||||
next_body = re.sub(r'\{[^{}]*\}', '', body)
|
||||
assert next_body != body, 'Cannot parse State initializer; audit the inventory checker'
|
||||
body = next_body
|
||||
body = re.sub(r'\[[^]]*\]|=[^,;]+', '', body)
|
||||
names = [re.findall(r'[A-Za-z_]\w*', part)[-1]
|
||||
for declaration in body.split(';') if declaration.strip()
|
||||
for part in declaration.split(',')]
|
||||
expected = ['rt', 'shader', 'ub', 'sb', 'vb', 'tex', 'samp', 'img', 'texture_pool', 'sampler_pool',
|
||||
'attrib', 'stream', 'blend', 'color', 'mask', 'ms', 'poly', 'ds', 'viewport', 'scissor',
|
||||
'blend_color', 'bias', 'stencil_compare', 'stencil_write', 'stencil_ref', 'copy_stride',
|
||||
'copy_image_stride', 'patch_size', 'bounds', 'count_samples', 'samples_passed']
|
||||
assert names == expected, ('New or reordered State fields require explicit pipeline/dynamic/resource policy', names)
|
||||
key = balanced(source, source.index('struct PipeMemoKey{'))
|
||||
for part in ['offsetof(State,viewport)-offsetof(State,attrib)', 'offsetof(State,copy_stride)-offsetof(State,blend_color)',
|
||||
'offsetof(State,count_samples)-offsetof(State,patch_size)']:
|
||||
assert part in key, part
|
||||
for signature, first_destroy in [('void clear_pipeline_objects(){', None),
|
||||
('void clear_descriptor_caches(){', 'vkDestroyDescriptorUpdateTemplate'),
|
||||
('void clear_render_pass_cache(){', None)]:
|
||||
block = balanced(source, source.index(signature))
|
||||
assert 'pipe_memo_valid=false' in block, signature
|
||||
if first_destroy:
|
||||
assert block.index('pipe_memo_valid=false') < block.index(first_destroy), signature
|
||||
lookup = balanced(source, source.index('void pipeline_lookup('))
|
||||
assert lookup.index('pipe_memo_valid=false') < lookup.index('pipeline_objects.erase(oldest)')
|
||||
shutdown = balanced(source, source.index('extern "C" int xbg_game_shutdown(){'))
|
||||
for call in ['clear_pipeline_objects()', 'clear_descriptor_caches()', 'clear_render_pass_cache()']:
|
||||
assert shutdown.index(call) < shutdown.index('shaders.clear()'), call
|
||||
assert 'shaders.erase' not in source and source.count('shaders.clear()') == 1
|
||||
assert 'render_pass_cache.erase' not in source and 'layout_cache.erase' not in source
|
||||
assert '!ab_off("pipememo")' in source and '"/gfx-pipe-memo"' in source and 'pipe_memo_valid=false;if(m)' in source
|
||||
print('PASS: 31 actual State fields, memo key slices, clear/evict/shutdown invalidation and opt-in/A-B source wiring; not a native or GPU test')
|
||||
@@ -0,0 +1,64 @@
|
||||
// 直接测试生产memo helper和生产State模板;依据PR16的ABA、生命周期与固定输入契约。
|
||||
// Test the production memo helper and State template against PR16 ABA, lifetime and fixed-input contracts.
|
||||
#include "../xbg_pipeline_memo.h"
|
||||
#include <iostream>
|
||||
#include <new>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace {
|
||||
void require(bool ok,const char *message){if(!ok)throw std::runtime_error(message);}
|
||||
struct Shader{XbgPipelineGeneration lifetime;};
|
||||
using State=XbgPipelineDrawState<Shader>;
|
||||
using Key=XbgPipelineMemoKey<State>;
|
||||
using Memo=XbgPreviousPipelineMemo<Key,uint64_t>;
|
||||
Key fill(const State &state,const XbgPipelineGeneration &layout,const XbgPipelineGeneration &definition,const XbgPipelineGeneration &pass,int prim=4,uint32_t colors=1,VkSampleCountFlagBits samples=VK_SAMPLE_COUNT_1_BIT){
|
||||
Key key;xbg_fill_pipeline_memo_key(key,state,&layout,layout.value,definition.value,&pass,pass.value,VK_NULL_HANDLE,VK_NULL_HANDLE,prim,samples,colors);return key;
|
||||
}
|
||||
bool same(const Key &a,const Key &b){return std::memcmp(&a,&b,sizeof a)==0;}
|
||||
template<class F>void changed(const State &base,const Key &key,const XbgPipelineGeneration &layout,const XbgPipelineGeneration &definition,const XbgPipelineGeneration &pass,F mutation,const char *name){
|
||||
State state=base;mutation(state);require(!same(key,fill(state,layout,definition,pass)),name);
|
||||
}
|
||||
}
|
||||
int main(){try{
|
||||
alignas(Shader) unsigned char storage[sizeof(Shader)];Shader *shader=new(storage)Shader;
|
||||
State state;state.shader[0]=shader;state.rt.n=1;
|
||||
XbgPipelineGeneration layout,definition,pass;Key key=fill(state,layout,definition,pass);Memo memo;
|
||||
require(!memo.find(key),"empty memo hit");memo.store(key,17);require(memo.find(key) && *memo.find(key)==17,"equal production key missed");
|
||||
uint64_t old=shader->lifetime.value;shader->~Shader();shader=new(storage)Shader;require(shader->lifetime.value!=old,"shader address reuse copied generation");
|
||||
require(!memo.find(fill(state,layout,definition,pass)),"shader ABA hit");
|
||||
key=fill(state,layout,definition,pass);memo.store(key,18);
|
||||
old=layout.value;layout.~XbgPipelineGeneration();new(&layout)XbgPipelineGeneration;require(layout.value!=old && !memo.find(fill(state,layout,definition,pass)),"layout ABA hit");
|
||||
key=fill(state,layout,definition,pass);memo.store(key,19);
|
||||
old=pass.value;pass.~XbgPipelineGeneration();new(&pass)XbgPipelineGeneration;require(pass.value!=old && !memo.find(fill(state,layout,definition,pass)),"render definition ABA hit");
|
||||
key=fill(state,layout,definition,pass);memo.store(key,20);definition.refresh();require(!memo.find(fill(state,layout,definition,pass)),"layout definition mutation hit");
|
||||
XbgPipelineGeneration copied=layout,moved=std::move(copied);require(layout.value!=copied.value && moved.value!=copied.value,"generation copied on copy/move construction");
|
||||
old=moved.value;moved=layout;require(moved.value!=old && moved.value!=layout.value,"generation copied on assignment");
|
||||
key=fill(state,layout,definition,pass);memo.store(key,21);memo.invalidate();require(!memo.find(key) && memo.payload==0,"destroy/evict/clear retained payload");
|
||||
memo.store(key,22);memo.invalidate();memo.store(key,23);require(memo.find(key) && *memo.find(key)==23,"cache failed after invalidation and refill");
|
||||
// 修改真实State的各切片字段;测试直接调用生产fill,未重写一份key算法。
|
||||
// Mutate each actual State slice field, calling production fill instead of mirroring its key algorithm.
|
||||
#define CHECK(field) changed(state,key,layout,definition,pass,[](State &s){reinterpret_cast<unsigned char*>(&s.field)[0]^=1;},"missing field " #field)
|
||||
CHECK(attrib);CHECK(stream);CHECK(blend);CHECK(color);CHECK(mask);CHECK(ms);CHECK(poly);CHECK(ds);
|
||||
CHECK(blend_color);CHECK(bias);CHECK(stencil_compare);CHECK(stencil_write);CHECK(stencil_ref);CHECK(patch_size);CHECK(bounds);
|
||||
#undef CHECK
|
||||
changed(state,key,layout,definition,pass,[](State &s){s.rt.n=2;},"target count missing");
|
||||
tex_t depth{};depth.d.format=0x32;state.rt.depth=&depth;Key depth_key=fill(state,layout,definition,pass);
|
||||
require(!same(key,depth_key),"depth attachment presence missing");depth.d.format=0x34;require(!same(depth_key,fill(state,layout,definition,pass)),"depth format missing");state.rt.depth=nullptr;
|
||||
require(!same(key,fill(state,layout,definition,pass,5)),"primitive missing");
|
||||
require(!same(key,fill(state,layout,definition,pass,4,3)),"active colors missing");
|
||||
require(!same(key,fill(state,layout,definition,pass,4,1,VK_SAMPLE_COUNT_4_BIT)),"sample count missing");
|
||||
State dynamic=state;dynamic.viewport.width=99;dynamic.scissor.extent.width=11;dynamic.copy_stride=1024;dynamic.copy_image_stride=4096;dynamic.samples_passed=17;dynamic.count_samples=true;
|
||||
require(same(key,fill(dynamic,layout,definition,pass)),"non-pipeline dynamic/copy/query inputs incorrectly changed the key");
|
||||
dynamic.ub[0][0].address=123;dynamic.vb[0].address=456;dynamic.tex[0][0]=7;dynamic.samp[0][0]=9;dynamic.img[0][0]=11;
|
||||
require(same(key,fill(dynamic,layout,definition,pass)),"resource addresses incorrectly changed the pipeline key");
|
||||
shader->~Shader();
|
||||
std::cout<<"PASS production memo: same-address shader/layout/definition generations, mutation/copy/move, invalidation/refill, 15 State slice fields, targets/format/primitive/colors/samples, dynamic/resource exclusions; CPU only\n";return 0;
|
||||
}catch(const std::exception &e){std::cerr<<"FAIL "<<e.what()<<'\n';return 1;}}
|
||||
|
||||
#ifdef XBG_PIPELINE_MEMO_NEGATIVE_STATE
|
||||
// 编译负控制:新增未分类尾字段必须触发布局契约失败,root应确认该构建失败。
|
||||
// Negative compile control: an unclassified new tail field must fail the layout contract; root should require compilation to fail.
|
||||
struct MissingPolicyState:State{uint32_t unclassified_pipeline_field;};
|
||||
XbgPipelineStateBytes<MissingPolicyState> must_fail_layout_contract;
|
||||
#endif
|
||||
@@ -0,0 +1,41 @@
|
||||
// 直接测试生产C池表:容量、owner删除、alias、未知及地址溢出;不访问伪造地址。
|
||||
// Test the production C pool registry directly: capacity, owner deletion, aliases, unknowns and overflow; never dereference synthetic addresses.
|
||||
#ifdef NDEBUG
|
||||
#error Build this regression with assertions enabled (-UNDEBUG).
|
||||
#endif
|
||||
#include "../../../nvn/nvn_pool_flags_registry.h"
|
||||
#include <assert.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
static unsigned checks;
|
||||
#define CHECK(x) do {++checks;assert(x);} while(0)
|
||||
static const void *ptr(uintptr_t value) {return (const void*)value;}
|
||||
int main(void) {
|
||||
nvn_pool_flags_registry *table=calloc(1,sizeof *table);CHECK(table!=NULL);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),16)==-1);
|
||||
CHECK(nvn_pool_flags_registry_add(table,ptr(1),ptr(0x1000),64,1));
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),64)==1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x103f),1)==1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1040),1)==-1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x103f),2)==-1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),0)==-1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(UINTPTR_MAX),1)==-1);
|
||||
CHECK(nvn_pool_flags_registry_add(table,ptr(2),ptr(0x1010),16,4));
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1010),1)==-1);
|
||||
nvn_pool_flags_registry_del(table,ptr(2));CHECK(nvn_pool_flags_registry_get(table,ptr(0x1010),16)==1);
|
||||
CHECK(nvn_pool_flags_registry_add(table,ptr(2),ptr(0x1000),64,4));
|
||||
nvn_pool_flags_registry_del(table,ptr(2));CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),16)==1);
|
||||
CHECK(nvn_pool_flags_registry_add(table,ptr(1),ptr(0x2000),64,4));CHECK(table->count==1);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),1)==-1);CHECK(nvn_pool_flags_registry_get(table,ptr(0x2000),1)==4);
|
||||
memset(table,0,sizeof *table);
|
||||
for(unsigned i=0;i<NVN_POOL_FLAGS_REGISTRY_MAX;++i)CHECK(nvn_pool_flags_registry_add(table,ptr(i+1),ptr(0x1000+(uintptr_t)i*0x1000),128,1));
|
||||
CHECK(table->count==NVN_POOL_FLAGS_REGISTRY_MAX && !table->incomplete);
|
||||
CHECK(nvn_pool_flags_registry_get(table,ptr(0x1000),128)==1);
|
||||
CHECK(!nvn_pool_flags_registry_add(table,ptr(99999),ptr(0x1000),128,4));
|
||||
CHECK(table->incomplete && nvn_pool_flags_registry_get(table,ptr(0x1000),128)==-1);
|
||||
nvn_pool_flags_registry_del(table,ptr(1));CHECK(nvn_pool_flags_registry_get(table,ptr(0x2000),1)==-1);
|
||||
memset(table,0,sizeof *table);
|
||||
CHECK(!nvn_pool_flags_registry_add(table,ptr(1),ptr(UINTPTR_MAX-2),8,1));CHECK(table->incomplete);
|
||||
free(table);printf("PASS pool_flags_registry production_C checks=%u; host_mutex_and_GPU=NOT_TESTED\n",checks);return 0;
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
// 直接调用生产的光栅事实检测,喂合成 SPIR-V:翻译器的写法(先写常量、再逐分量抄输入)认得出,任何一处不是原样抄就不认。
|
||||
// Call the production raster-facts detection on synthetic SPIR-V: the translator's pattern (constants first, then each
|
||||
// component copied from an input) is recognized, and anything that is not a plain copy is not.
|
||||
#include "../xbg_spirv_raster.h"
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace {
|
||||
using Module=std::vector<uint32_t>;
|
||||
void require(bool ok,const char *why){if(!ok)throw std::runtime_error(why);}
|
||||
void op(Module &m,uint32_t opcode,std::initializer_list<uint32_t> args){m.push_back((uint32_t(args.size()+1)<<16)|opcode);m.insert(m.end(),args);}
|
||||
enum : uint32_t {tVoid=1,tFn=2,tFloat=3,tVec4=4,tInt=5,tBlock=6,tPtrInV4=7,tPtrOutF=8,tPtrOutBlock=9,tPtrOutV4=10,tPtrInF=11,
|
||||
i0=20,i1=21,i2=22,i3=23,f0=24,f1=25,inA=30,inB=31,outPV=32,outC0=33,outC2=34,outMask=35,fMain=40,lEntry=41,lNext=42};
|
||||
enum Variant {Plain,WFromInput,Swizzled,ClipWritten,TwoBlocks,WholeVector,OtherInput};
|
||||
// Vertex module: gl_PerVertex {vec4 Position; float PointSize; float ClipDistance}, inputs at locations 0 (inA) and 3 (inB).
|
||||
Module vertex(Variant v){
|
||||
Module m{0x07230203,0x00010300,0,100,0};
|
||||
op(m,17,{1});op(m,14,{0,1});
|
||||
op(m,15,{0,fMain,0x6e69616d,0,inA,inB,outPV});
|
||||
op(m,71,{inA,30,0});op(m,71,{inB,30,3});
|
||||
op(m,71,{tBlock,2});op(m,72,{tBlock,0,11,0});op(m,72,{tBlock,1,11,1});op(m,72,{tBlock,2,11,3});
|
||||
op(m,19,{tVoid});op(m,33,{tFn,tVoid});op(m,22,{tFloat,32});op(m,23,{tVec4,tFloat,4});op(m,21,{tInt,32,1});
|
||||
op(m,30,{tBlock,tVec4,tFloat,tFloat});
|
||||
op(m,32,{tPtrInV4,1,tVec4});op(m,32,{tPtrOutF,3,tFloat});op(m,32,{tPtrOutBlock,3,tBlock});op(m,32,{tPtrOutV4,3,tVec4});op(m,32,{tPtrInF,1,tFloat});
|
||||
op(m,43,{tInt,i0,0});op(m,43,{tInt,i1,1});op(m,43,{tInt,i2,2});op(m,43,{tInt,i3,3});op(m,43,{tFloat,f0,0});op(m,43,{tFloat,f1,0x3f800000});
|
||||
op(m,59,{tPtrInV4,inA,1});op(m,59,{tPtrInV4,inB,1});op(m,59,{tPtrOutBlock,outPV,3});
|
||||
op(m,54,{tVoid,fMain,0,tFn});op(m,248,{lEntry});
|
||||
uint32_t id=50;
|
||||
auto store_pos=[&](uint32_t comp,uint32_t value){uint32_t p=id++;op(m,65,{tPtrOutF,p,outPV,i0,comp});op(m,62,{p,value});};
|
||||
auto load_in=[&](uint32_t var,uint32_t comp){uint32_t p=id++,r=id++;op(m,65,{tPtrInF,p,var,comp});op(m,61,{tFloat,r,p});return r;};
|
||||
// the translator's start: (0, 0, 0, 1)
|
||||
store_pos(i0,f0);store_pos(i1,f0);store_pos(i2,f0);store_pos(i3,f1);
|
||||
if(v==WholeVector){uint32_t r=id++;op(m,61,{tVec4,r,inA});uint32_t p=id++;op(m,65,{tPtrOutV4,p,outPV,i0});op(m,62,{p,r});}
|
||||
else{
|
||||
uint32_t x=load_in(inA,i0),y=load_in(inA,i1),z=load_in(v==Swizzled?inA:v==OtherInput?inB:inA,v==Swizzled?i3:i2);
|
||||
uint32_t cx=id++;op(m,83,{tFloat,cx,x});
|
||||
store_pos(i0,cx);store_pos(i1,y);store_pos(i2,z);
|
||||
if(v==WFromInput)store_pos(i3,load_in(inA,i3));
|
||||
if(v==ClipWritten){uint32_t p=id++;op(m,65,{tPtrOutF,p,outPV,i2});op(m,62,{p,f0});}
|
||||
}
|
||||
if(v==TwoBlocks){op(m,249,{lNext});op(m,248,{lNext});}
|
||||
op(m,253,{});op(m,56,{});
|
||||
m[3]=id;return m;
|
||||
}
|
||||
Module fragment(){
|
||||
Module m{0x07230203,0x00010300,0,100,0};
|
||||
op(m,17,{1});op(m,14,{0,1});
|
||||
op(m,15,{4,fMain,0x6e69616d,0,outC0,outC2,outMask});
|
||||
op(m,71,{outC0,30,0});op(m,71,{outC2,30,2});op(m,71,{outMask,11,20});
|
||||
op(m,19,{tVoid});op(m,33,{tFn,tVoid});op(m,22,{tFloat,32});op(m,23,{tVec4,tFloat,4});op(m,21,{tInt,32,1});
|
||||
op(m,32,{tPtrOutV4,3,tVec4});op(m,32,{tPtrOutF,3,tInt});
|
||||
op(m,59,{tPtrOutV4,outC0,3});op(m,59,{tPtrOutV4,outC2,3});op(m,59,{tPtrOutF,outMask,3});
|
||||
op(m,54,{tVoid,fMain,0,tFn});op(m,248,{lEntry});op(m,253,{});op(m,56,{});
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
int main(){
|
||||
try{
|
||||
auto facts=[](Variant v){Module m=vertex(v);return xbg_spirv_raster_facts(m.data(),m.size(),0);};
|
||||
XbgRasterFacts a=facts(Plain);require(a.pos_input==0 && a.pos_w1,"plain copy of input 0 with w = 1");
|
||||
XbgRasterFacts b=facts(WFromInput);require(b.pos_input==0 && !b.pos_w1,"w copied from the same input");
|
||||
require(facts(Swizzled).pos_input==-1,"z taken from component 3");
|
||||
require(facts(OtherInput).pos_input==-1,"z taken from another input");
|
||||
require(facts(ClipWritten).pos_input==-1,"ClipDistance written");
|
||||
require(facts(TwoBlocks).pos_input==-1,"more than one block");
|
||||
XbgRasterFacts w=facts(WholeVector);require(w.pos_input==0 && !w.pos_w1,"whole input vector stored, w from the input");
|
||||
{Module m=vertex(Plain);require(xbg_spirv_raster_facts(m.data(),m.size(),4).pos_input==-1,"vertex module read as fragment");}
|
||||
{Module m=fragment();XbgRasterFacts f=xbg_spirv_raster_facts(m.data(),m.size(),4);require(f.outputs==0x5u && f.sample_mask,"fragment outputs 0 and 2, SampleMask");}
|
||||
{Module m=vertex(Plain);m[0]=0;require(xbg_spirv_raster_facts(m.data(),m.size(),0).pos_input==-1,"bad magic");}
|
||||
}catch(const std::exception &e){std::cerr<<"FAIL "<<e.what()<<"\n";return 1;}
|
||||
std::cout<<"PASS raster facts\n";return 0;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# 驻留 texel 淘汰、代际及槽生命周期模型,依据 PR10b 的独立驻留设计。
|
||||
# Resident texel eviction, generation and slot-lifetime model based on the PR10b resident design.
|
||||
from pathlib import Path
|
||||
from texture_cache_regression import balanced
|
||||
s=(Path(__file__).resolve().parent.parent/'xbg_game.cpp').read_text(encoding='utf-8')
|
||||
a=balanced(s,s.index('TexelResident *texel_acquire('))
|
||||
assert a.index('for(auto &w:pending_writebacks)if(xbg_wb_overlaps(base,bytes,w.addr,w.bytes))')<a.index('it->second.checked==slot_serial')
|
||||
assert 'slots[si].recording && !slots[si].pending' in a
|
||||
assert 'texel_live_bytes[si]+texel_hole_bytes[si]+bytes>64ull*1024*1024' in a
|
||||
assert 'if(r.used==slot_serial)' in a
|
||||
assert 'r.gen=++texel_gen' in a
|
||||
v=balanced(s,s.index('void texel_evict(unsigned si,bool all){'))
|
||||
assert v.index('!slots[si].pending')<v.index('vkDestroyBufferView')
|
||||
assert v.index('vkDestroyBufferView')<v.index('texel_arena[si].release()')
|
||||
assert 'r->gen!=tr.gen' in s and 'desc_memo_texel_fail' in s
|
||||
class Slot:
|
||||
def __init__(self): self.pending=False;self.map={};self.gen=0;self.holes=0;self.released=0
|
||||
def acquire(self,key,serial,content):
|
||||
assert not self.pending
|
||||
old=self.map.get(key)
|
||||
if old and old[2]!=content and old[1]==serial: return None
|
||||
if not old: self.gen+=1
|
||||
gen=old[0] if old else self.gen
|
||||
self.map[key]=(gen,serial,content)
|
||||
return gen
|
||||
def evict(self,serial,all=False):
|
||||
assert not self.pending
|
||||
for key,(gen,used,content) in list(self.map.items()):
|
||||
if all or used+128<serial: del self.map[key];self.holes+=key[1]
|
||||
if all or self.holes>8*1024*1024:self.map.clear();self.holes=0;self.released+=1
|
||||
slots=[Slot(),Slot()]
|
||||
for n in range(1,1025):
|
||||
slot=slots[n%2];slot.pending=False;slot.evict(n)
|
||||
key=(n%67,256*1024)
|
||||
gen=slot.acquire(key,n,n)
|
||||
assert slot.acquire(key,n,n)==gen
|
||||
assert slot.acquire(key,n,n+1) is None
|
||||
slot.pending=True
|
||||
try:slot.evict(n,True)
|
||||
except AssertionError:pass
|
||||
else:raise AssertionError('in-flight eviction accepted')
|
||||
for slot in slots:
|
||||
slot.pending=False;old=slot.gen;slot.evict(2048,True)
|
||||
assert not slot.map and slot.holes==0
|
||||
assert slot.acquire((1,4096),2049,7)>old
|
||||
assert slot.released>1
|
||||
print('PASS: 1024 two-slot retire/reuse/eviction/arena-release model cycles and source guards; Vulkan driver not executed')
|
||||
@@ -0,0 +1,14 @@
|
||||
# C/C++ 分隔符门:捕获手工三方合并的结构截断,不替代编译器。
|
||||
# C/C++ delimiter gate: catch structural truncation during manual three-way merges; not a compiler replacement.
|
||||
from pathlib import Path
|
||||
import re
|
||||
root=Path(__file__).resolve().parents[4]
|
||||
for name in ['gfx/vulkan/engine/xbg_game.cpp','gfx/nvn/hle_nvn.c','android/vulkan_present.cpp']:
|
||||
s=(root/name).read_text(encoding='utf-8')
|
||||
s=re.sub(r"""/\*.*?\*/|//[^\n]*|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'""", "", s,flags=re.S)
|
||||
stack=[]
|
||||
for ch in s:
|
||||
if ch in '({[':stack.append(ch)
|
||||
elif ch in ')}]':assert stack and stack.pop()=={')':'(',']':'[','}':'{'}[ch],name
|
||||
assert not stack,name
|
||||
print('PASS: C/C++ balanced delimiters for engine, NVN and Android presenter (not a compile)')
|
||||
@@ -0,0 +1,296 @@
|
||||
// 真C++改写器回归与仓外XGS审计入口:合成SPIR-V,不链接Vulkan、不启动游戏。
|
||||
// Real C++ rewriter regression and external XGS audit entry: synthetic SPIR-V, no Vulkan linkage or game launch.
|
||||
#include "../xbg_spirv_quad.h"
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#ifdef NDEBUG
|
||||
#error "Quad regression tests require active assertions; compile with -UNDEBUG."
|
||||
#endif
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <map>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
|
||||
namespace fs=std::filesystem;
|
||||
using Words=std::vector<uint32_t>;
|
||||
using Quad=std::array<float,4>;
|
||||
enum class Mode { numeric,source_bits,source_bits_copy,result_bits,result_bits_copy,integer_use,memory_use,branch,scope,xor4,index,existing_coord,source_bits_use,source_integer_use,source_memory_use };
|
||||
static void add(Words &v,uint32_t op,std::initializer_list<uint32_t> args) {
|
||||
v.push_back((uint32_t(args.size()+1)<<16)|op);v.insert(v.end(),args.begin(),args.end());
|
||||
}
|
||||
static Words fixture(unsigned mask,Mode mode=Mode::numeric) {
|
||||
Words w={0x07230203,0x00010300,0,400,0};
|
||||
add(w,17,{1});add(w,17,{61});add(w,17,{65});add(w,14,{0,1});
|
||||
if(mode==Mode::existing_coord)add(w,15,{4,100,0x6e69616d,0,10,11,12,19});
|
||||
else if(mode==Mode::source_bits || mode==Mode::source_bits_copy)add(w,15,{4,100,0x6e69616d,0,10,11,12,19});
|
||||
else add(w,15,{4,100,0x6e69616d,0,10,11,12});
|
||||
add(w,16,{100,7});add(w,71,{10,11,41});add(w,71,{10,14});add(w,71,{11,30,0});add(w,71,{12,30,0});
|
||||
if(mode==Mode::existing_coord)add(w,71,{19,11,15});
|
||||
if(mode==Mode::source_bits || mode==Mode::source_bits_copy) {add(w,71,{19,30,1});add(w,71,{19,14});}
|
||||
add(w,19,{1});add(w,21,{2,32,0});add(w,22,{3,32});add(w,23,{4,3,4});add(w,20,{5});
|
||||
add(w,32,{6,1,2});add(w,32,{7,1,3});add(w,32,{8,3,3});add(w,33,{9,1});
|
||||
if(mode==Mode::existing_coord)add(w,32,{16,1,4});
|
||||
if((mode==Mode::memory_use || mode==Mode::source_memory_use))add(w,32,{16,7,3});
|
||||
add(w,59,{6,10,1});add(w,59,{7,11,1});add(w,59,{8,12,3});
|
||||
if(mode==Mode::existing_coord)add(w,59,{16,19,1});
|
||||
if(mode==Mode::source_bits || mode==Mode::source_bits_copy)add(w,59,{6,19,1});
|
||||
add(w,43,{2,13,mode==Mode::scope?2u:3u});add(w,43,{2,14,mode==Mode::xor4?4u:mask});add(w,41,{5,20});
|
||||
add(w,54,{1,100,0,9});add(w,248,{101});
|
||||
if((mode==Mode::memory_use || mode==Mode::source_memory_use))add(w,59,{16,19,7});
|
||||
add(w,61,{2,102,10});add(w,198,{2,103,102,14});
|
||||
if(mode==Mode::source_bits || mode==Mode::source_bits_copy) {
|
||||
add(w,61,{2,116,19});add(w,124,{3,mode==Mode::source_bits?104u:117u,116});
|
||||
if(mode==Mode::source_bits_copy)add(w,83,{3,104,117});
|
||||
} else add(w,61,{3,104,11});
|
||||
if(mode==Mode::branch) {add(w,247,{111,0});add(w,250,{20,112,113});add(w,248,{112});}
|
||||
add(w,345,{3,105,13,104,mode==Mode::index?102u:103u});
|
||||
add(w,62,{12,105});
|
||||
if(mode==Mode::source_bits_use)add(w,124,{2,118,104});
|
||||
if(mode==Mode::source_integer_use)add(w,109,{2,118,104});
|
||||
if(mode==Mode::result_bits)add(w,124,{2,118,105});
|
||||
if(mode==Mode::result_bits_copy) {add(w,83,{3,117,105});add(w,124,{2,118,117});}
|
||||
if(mode==Mode::integer_use)add(w,109,{2,118,105});
|
||||
if((mode==Mode::memory_use || mode==Mode::source_memory_use))add(w,62,{19,mode==Mode::source_memory_use?104u:105u});
|
||||
if(mode==Mode::branch) {add(w,249,{111});add(w,248,{113});add(w,249,{111});add(w,248,{111});}
|
||||
add(w,253,{});add(w,56,{});return w;
|
||||
}
|
||||
|
||||
// 在四个活跃lane上执行真实输出指令,检查对角项和非有限回退,不模拟GPU辅助调用。
|
||||
// Execute the actual emitted instructions over four active lanes to check diagonals and nonfinite fallback, without pretending to simulate GPU helpers.
|
||||
static Quad evaluate(const Words &w,const Quad &input) {
|
||||
std::map<uint32_t,Quad> f;
|
||||
std::map<uint32_t,std::array<uint32_t,4>> u;
|
||||
std::map<uint32_t,std::array<bool,4>> b;
|
||||
std::map<uint32_t,std::array<Quad,4>> vectors;
|
||||
Quad result={};
|
||||
for(size_t at=5;at<w.size();) {
|
||||
auto *p=w.data()+at;unsigned wc=p[0]>>16,op=p[0]&65535;
|
||||
if(op==43 && p[1]==2)u[p[2]].fill(p[3]);
|
||||
if(op==61) {
|
||||
if(p[1]==2)u[p[2]]={0,1,2,3};
|
||||
else if(p[1]==3)f[p[2]]=input;
|
||||
else for(unsigned lane=0;lane<4;++lane)vectors[p[2]][lane]={float(lane&1)+.5f,float(lane>>1)+.5f,0,1};
|
||||
}
|
||||
if(op==198 || op==199)for(unsigned lane=0;lane<4;++lane)u[p[2]][lane]=op==198?(u[p[3]][lane]^u[p[4]][lane]):(u[p[3]][lane]&u[p[4]][lane]);
|
||||
if(op==171)for(unsigned lane=0;lane<4;++lane)b[p[2]][lane]=u[p[3]][lane]!=u[p[4]][lane];
|
||||
if(op==345)for(unsigned lane=0;lane<4;++lane)f[p[2]][lane]=f[p[4]][u[p[5]][lane]&3];
|
||||
if(op==81)for(unsigned lane=0;lane<4;++lane)f[p[2]][lane]=vectors[p[3]][lane][p[4]];
|
||||
if(op==109)for(unsigned lane=0;lane<4;++lane)u[p[2]][lane]=uint32_t(f[p[3]][lane]);
|
||||
if(op==210) {auto q=f[p[3]];f[p[2]]={q[1]-q[0],q[1]-q[0],q[3]-q[2],q[3]-q[2]};}
|
||||
if(op==211) {auto q=f[p[3]];f[p[2]]={q[2]-q[0],q[3]-q[1],q[2]-q[0],q[3]-q[1]};}
|
||||
if(op==127)for(unsigned lane=0;lane<4;++lane)f[p[2]][lane]=-f[p[3]][lane];
|
||||
if(op==129)for(unsigned lane=0;lane<4;++lane)f[p[2]][lane]=f[p[3]][lane]+f[p[4]][lane];
|
||||
if(op==156 || op==157)for(unsigned lane=0;lane<4;++lane)b[p[2]][lane]=op==156?std::isnan(f[p[3]][lane]):std::isinf(f[p[3]][lane]);
|
||||
if(op==166)for(unsigned lane=0;lane<4;++lane)b[p[2]][lane]=b[p[3]][lane]||b[p[4]][lane];
|
||||
if(op==169)for(unsigned lane=0;lane<4;++lane)f[p[2]][lane]=b[p[3]][lane]?f[p[4]][lane]:f[p[5]][lane];
|
||||
if(op==62 && p[1]==12)result=f[p[2]];
|
||||
at+=wc;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
// 辅助函数调用形式的合成模块:Ryujinx ShuffleXor 辅助函数(同 D2R 着色器库),值以整数位经 Function 变量传入,结果按位还原。
|
||||
// A synthetic module of the helper-call form: the translator's ShuffleXor helper (as in D2R's library), the value passed as
|
||||
// integer bits through Function variables, the result cast back.
|
||||
enum class Call { plain,uniform,divergent,kill,integer_source,integer_use };
|
||||
static Words call_fixture(uint32_t xor_value,uint32_t mask,Call mode=Call::plain) {
|
||||
Words w={0x07230203,0x00010300,0,300,0};
|
||||
add(w,17,{1});add(w,17,{61});add(w,17,{65});add(w,14,{0,1});add(w,15,{4,100,0x6e69616d,0,10,11,12});add(w,16,{100,7});
|
||||
add(w,71,{10,11,41});add(w,71,{10,14});add(w,71,{11,30,0});add(w,71,{12,30,0});
|
||||
add(w,71,{34,2});add(w,72,{34,0,35,0});add(w,71,{37,34,0});add(w,71,{37,33,0});
|
||||
add(w,19,{1});add(w,21,{2,32,0});add(w,22,{3,32});add(w,23,{4,3,4});add(w,20,{5});
|
||||
add(w,32,{6,1,2});add(w,32,{7,1,3});add(w,32,{8,3,3});add(w,33,{9,1});
|
||||
add(w,21,{30,32,1});add(w,32,{31,7,30});add(w,33,{32,30,31,31,31,31});add(w,32,{33,7,5});
|
||||
add(w,30,{34,3});add(w,32,{35,2,34});add(w,32,{36,2,3});
|
||||
add(w,59,{6,10,1});add(w,59,{7,11,1});add(w,59,{8,12,3});add(w,59,{35,37,2});
|
||||
add(w,43,{2,13,3});add(w,43,{30,40,31});add(w,43,{30,41,8});add(w,43,{30,42,0xffffffffu});add(w,43,{30,43,0});
|
||||
add(w,43,{30,44,xor_value});add(w,43,{30,45,mask});add(w,43,{3,46,0x3f000000u});add(w,43,{3,48,0});
|
||||
add(w,54,{1,100,0,9});add(w,248,{101});
|
||||
for(uint32_t v:{50u,51u,52u,53u,54u})add(w,59,{31,v,7});
|
||||
add(w,59,{33,55,7});
|
||||
add(w,61,{3,60,11});add(w,mode==Call::integer_source?110u:124u,{30,61,60});
|
||||
add(w,62,{50,61});add(w,62,{51,44});add(w,62,{52,45});
|
||||
auto call=[&]{add(w,57,{30,70,200,50,51,52,53});add(w,62,{54,70});add(w,61,{30,71,54});add(w,mode==Call::integer_use?111u:124u,{3,72,71});add(w,62,{12,72});};
|
||||
if(mode==Call::uniform || mode==Call::divergent) {
|
||||
if(mode==Call::uniform) {add(w,65,{36,80,37,43});add(w,61,{3,81,80});add(w,186,{5,82,81,48});}
|
||||
else add(w,186,{5,82,60,48});
|
||||
add(w,247,{91,0});add(w,250,{82,90,91});add(w,248,{90});call();add(w,249,{91});add(w,248,{91});
|
||||
} else if(mode==Call::kill) {
|
||||
add(w,184,{5,83,60,46});add(w,62,{55,83});add(w,61,{5,84,55});add(w,247,{93,0});add(w,250,{84,92,93});add(w,248,{92});add(w,252,{});
|
||||
add(w,248,{93});add(w,61,{5,85,55});add(w,247,{95,0});add(w,250,{85,94,95});add(w,248,{94});add(w,249,{95});add(w,248,{95});call();
|
||||
} else call();
|
||||
add(w,253,{});add(w,56,{});
|
||||
add(w,54,{30,200,0,32});for(uint32_t v:{201u,202u,203u,204u})add(w,55,{31,v});add(w,248,{205});
|
||||
add(w,61,{30,210,203});add(w,199,{30,211,210,40});add(w,194,{30,212,210,41});add(w,199,{30,213,212,40});
|
||||
add(w,61,{2,214,10});add(w,124,{30,215,214});add(w,199,{30,216,215,213});add(w,200,{30,217,213});
|
||||
add(w,199,{30,218,211,217});add(w,197,{30,219,218,216});add(w,61,{30,220,202});add(w,198,{30,221,215,220});
|
||||
add(w,124,{2,222,221});add(w,124,{2,223,219});add(w,178,{5,224,222,223});add(w,169,{30,225,224,42,43});add(w,62,{204,225});
|
||||
add(w,61,{30,226,201});add(w,124,{3,227,226});add(w,345,{3,228,13,227,222});add(w,124,{30,229,228});add(w,169,{30,230,224,229,226});
|
||||
add(w,254,{230});add(w,56,{});
|
||||
return w;
|
||||
}
|
||||
// 在一个四元组上执行改写后的主函数:原调用按 32 道线程束的语义取 lane^x 的位,导数与非有限回退照输出指令计算。
|
||||
// Run the rewritten entry function over one quad: the original call takes lane^x's bits (its 32-lane meaning), and the
|
||||
// derivatives and the nonfinite fallback follow the emitted instructions.
|
||||
static Quad evaluate_call(const Words &w,const Quad &input,uint32_t xor_value) {
|
||||
std::map<uint32_t,std::array<uint32_t,4>> u,memory;std::map<uint32_t,std::array<bool,4>> b;std::map<uint32_t,std::array<Quad,4>> vectors;
|
||||
auto f=[](uint32_t x){float r;std::memcpy(&r,&x,4);return r;};auto bits=[](float x){uint32_t r;std::memcpy(&r,&x,4);return r;};
|
||||
Quad result={};bool in_main=false;
|
||||
for(size_t at=5;at<w.size();) {
|
||||
auto *p=w.data()+at;unsigned wc=p[0]>>16,op=p[0]&65535;at+=wc;
|
||||
if(op==54)in_main=p[2]==100;
|
||||
if(op==43)u[p[2]].fill(p[3]);
|
||||
if(!in_main)continue;
|
||||
if(op==61) {
|
||||
if(p[3]==11)for(unsigned l=0;l<4;++l)u[p[2]][l]=bits(input[l]);
|
||||
else if(p[3]==10)u[p[2]]={0,1,2,3};
|
||||
else if(p[1]==4)for(unsigned l=0;l<4;++l)vectors[p[2]][l]={float(l&1)+.5f,float(l>>1)+.5f,0,1};
|
||||
else u[p[2]]=memory[p[3]];
|
||||
}
|
||||
if(op==62) {if(p[1]==12)for(unsigned l=0;l<4;++l)result[l]=f(u[p[2]][l]);else memory[p[1]]=u[p[2]];}
|
||||
if(op==124)u[p[2]]=u[p[3]];
|
||||
if(op==57)for(unsigned l=0;l<4;++l)u[p[2]][l]=memory[p[4]][l^xor_value];
|
||||
if(op==81)for(unsigned l=0;l<4;++l)u[p[2]][l]=bits(vectors[p[3]][l][p[4]]);
|
||||
if(op==109)for(unsigned l=0;l<4;++l)u[p[2]][l]=uint32_t(f(u[p[3]][l]));
|
||||
if(op==199)for(unsigned l=0;l<4;++l)u[p[2]][l]=u[p[3]][l]&u[p[4]][l];
|
||||
if(op==171)for(unsigned l=0;l<4;++l)b[p[2]][l]=u[p[3]][l]!=u[p[4]][l];
|
||||
if(op==210 || op==211) {Quad q;for(unsigned l=0;l<4;++l)q[l]=f(u[p[3]][l]);
|
||||
Quad d=op==210?Quad{q[1]-q[0],q[1]-q[0],q[3]-q[2],q[3]-q[2]}:Quad{q[2]-q[0],q[3]-q[1],q[2]-q[0],q[3]-q[1]};
|
||||
for(unsigned l=0;l<4;++l)u[p[2]][l]=bits(d[l]);}
|
||||
if(op==127)for(unsigned l=0;l<4;++l)u[p[2]][l]=bits(-f(u[p[3]][l]));
|
||||
if(op==129)for(unsigned l=0;l<4;++l)u[p[2]][l]=bits(f(u[p[3]][l])+f(u[p[4]][l]));
|
||||
if(op==156 || op==157)for(unsigned l=0;l<4;++l)b[p[2]][l]=op==156?std::isnan(f(u[p[3]][l])):std::isinf(f(u[p[3]][l]));
|
||||
if(op==166)for(unsigned l=0;l<4;++l)b[p[2]][l]=b[p[3]][l]||b[p[4]][l];
|
||||
if(op==169)for(unsigned l=0;l<4;++l)u[p[2]][l]=b[p[3]][l]?u[p[4]][l]:u[p[5]][l];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
static void save(const fs::path &path,const Words &words) {
|
||||
std::ofstream file(path,std::ios::binary);file.write(reinterpret_cast<const char *>(words.data()),std::streamsize(words.size()*4));
|
||||
if(!file)throw std::runtime_error("cannot write synthetic SPIR-V");
|
||||
}
|
||||
static void run_tests(const fs::path &output={}) {
|
||||
unsigned cases=0;
|
||||
if(!output.empty())fs::create_directories(output);
|
||||
for(unsigned mask=1;mask<=3;++mask) {
|
||||
auto original=fixture(mask);Words rewritten;xbg_spirv_quad_stats stats;
|
||||
assert(xbg_spirv_quad_derivatives(original.data(),original.size(),rewritten,&stats)==1);
|
||||
assert(stats.candidates==1 && stats.rewritten==1 && stats.guarded_nonfinite==1);
|
||||
Quad values={1,4,7,20};auto actual=evaluate(rewritten,values);
|
||||
for(unsigned lane=0;lane<4;++lane)assert(actual[lane]==values[lane^mask]);
|
||||
if(mask==3) {
|
||||
size_t horizontal=0,vertical=0;uint32_t dy_source=0;
|
||||
for(size_t at=5;at<rewritten.size();at+=rewritten[at]>>16) {
|
||||
unsigned op=rewritten[at]&65535;
|
||||
if(op==210)horizontal=at;if(op==211) {vertical=at;dy_source=rewritten[at+3];}
|
||||
}
|
||||
assert(horizontal && vertical>horizontal && dy_source!=104);
|
||||
}
|
||||
Quad exceptional={INFINITY,2,NAN,-INFINITY};auto fallback=evaluate(rewritten,exceptional);
|
||||
for(unsigned lane=0;lane<4;++lane)assert(std::isnan(exceptional[lane^mask])?std::isnan(fallback[lane]):fallback[lane]==exceptional[lane^mask]);
|
||||
if(!output.empty()) {save(output/(("xor"+std::to_string(mask))+"-before.spv"),original);save(output/(("xor"+std::to_string(mask))+"-after.spv"),rewritten);}
|
||||
++cases;
|
||||
}
|
||||
struct Rejection {Mode mode;xbg_quad_skip reason;const char *name;};
|
||||
for(auto test:{Rejection{Mode::source_bits,xbg_quad_skip::bit_pattern,"source_bits"},
|
||||
{Mode::source_bits_copy,xbg_quad_skip::bit_pattern,"transitive_source_bits"},
|
||||
{Mode::result_bits,xbg_quad_skip::bit_pattern,"result_bits"},
|
||||
{Mode::result_bits_copy,xbg_quad_skip::bit_pattern,"transitive_result_bits"},
|
||||
{Mode::integer_use,xbg_quad_skip::integer_flow,"integer_use"},
|
||||
{Mode::memory_use,xbg_quad_skip::memory_flow,"private_memory"},
|
||||
{Mode::source_bits_use,xbg_quad_skip::bit_pattern,"source_downstream_bits"},
|
||||
{Mode::source_integer_use,xbg_quad_skip::integer_flow,"source_downstream_integer"},
|
||||
{Mode::source_memory_use,xbg_quad_skip::memory_flow,"source_downstream_private_memory"},
|
||||
{Mode::branch,xbg_quad_skip::control_flow,"conditional_branch"},
|
||||
{Mode::scope,xbg_quad_skip::lane_index,"wrong_scope"},
|
||||
{Mode::xor4,xbg_quad_skip::lane_index,"cross_quad"},
|
||||
{Mode::index,xbg_quad_skip::lane_index,"unproven_index"}}) {
|
||||
auto original=fixture(3,test.mode);Words rewritten={1,2,3};xbg_spirv_quad_stats stats;
|
||||
assert(!xbg_spirv_quad_derivatives(original.data(),original.size(),rewritten,&stats));
|
||||
assert(rewritten.empty() && stats.candidates==1 && stats.skipped[size_t(test.reason)]==1);
|
||||
if(!output.empty())save(output/(std::string(test.name)+"-unchanged.spv"),original);
|
||||
++cases;
|
||||
}
|
||||
// 辅助函数调用形式:直线、统一分支、kill 之后均改写;分叉、整数来源或用途、跨四元组、clamp 不全都保留原样。
|
||||
// Helper-call form: rewritten in straight-line code, under a uniform branch and after a kill; left alone under a divergent
|
||||
// branch, for integer sources or uses, across quads, and with a clamp that does not cover the quad.
|
||||
for(uint32_t x=1;x<=3;++x)for(Call mode:{Call::plain,Call::uniform,Call::kill}) {
|
||||
auto original=call_fixture(x,0x1c03,mode);Words rewritten;xbg_spirv_quad_stats stats;
|
||||
assert(xbg_spirv_quad_derivatives(original.data(),original.size(),rewritten,&stats)==1);
|
||||
assert(stats.calls==1 && stats.calls_rewritten==1 && stats.rewritten==0 && stats.skipped[size_t(xbg_quad_skip::control_flow)]==1);
|
||||
for(size_t at=5;at<rewritten.size();at+=rewritten[at]>>16)assert((rewritten[at]&65535)!=57 || rewritten[at+3]!=200);
|
||||
if(mode==Call::plain) {
|
||||
Quad values={1,4,7,20};auto actual=evaluate_call(rewritten,values,x);
|
||||
for(unsigned lane=0;lane<4;++lane)assert(actual[lane]==values[lane^x]);
|
||||
// 无 shuffle 回退:自身有限的 lane 照取邻居,含非有限邻居(对角分两步,还要水平与竖直邻居有限);否则得 NaN。
|
||||
// No shuffle fallback: a lane whose own value is finite gets its neighbour's value, nonfinite ones included (the
|
||||
// diagonal takes two steps, so its horizontal and vertical neighbours must be finite too); any other lane gets NaN.
|
||||
for(Quad exceptional:{Quad{INFINITY,2,NAN,-INFINITY},Quad{3,INFINITY,5,NAN},Quad{-INFINITY,INFINITY,6,7}}) {
|
||||
auto actual=evaluate_call(rewritten,exceptional,x);
|
||||
for(unsigned lane=0;lane<4;++lane) {
|
||||
bool exact=std::isfinite(exceptional[lane]) && (x!=3 || (std::isfinite(exceptional[lane^1]) && std::isfinite(exceptional[lane^2])));
|
||||
if(!exact)assert(std::isnan(actual[lane]));
|
||||
else assert(std::isnan(exceptional[lane^x])?std::isnan(actual[lane]):actual[lane]==exceptional[lane^x]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!output.empty()) {std::string name="call-xor"+std::to_string(x)+(mode==Call::plain?"":mode==Call::uniform?"-uniform":"-kill");
|
||||
save(output/(name+"-before.spv"),original);save(output/(name+"-after.spv"),rewritten);}
|
||||
++cases;
|
||||
}
|
||||
struct CallRejection {uint32_t x,mask;Call mode;xbg_quad_call_skip reason;const char *name;};
|
||||
for(auto test:{CallRejection{1,0x1c03,Call::divergent,xbg_quad_call_skip::control_flow,"call_divergent"},
|
||||
{1,0x1c03,Call::integer_source,xbg_quad_call_skip::source,"call_integer_source"},
|
||||
{1,0x1c03,Call::integer_use,xbg_quad_call_skip::use,"call_integer_use"},
|
||||
{4,0x1c03,Call::plain,xbg_quad_call_skip::helper,"call_cross_quad"},
|
||||
{1,0x1c02,Call::plain,xbg_quad_call_skip::helper,"call_partial_clamp"}}) {
|
||||
auto original=call_fixture(test.x,test.mask,test.mode);Words rewritten={1,2,3};xbg_spirv_quad_stats stats;
|
||||
assert(!xbg_spirv_quad_derivatives(original.data(),original.size(),rewritten,&stats));
|
||||
assert(rewritten.empty() && stats.calls==1 && stats.call_skipped[size_t(test.reason)]==1);
|
||||
if(!output.empty())save(output/(std::string(test.name)+"-unchanged.spv"),original);
|
||||
++cases;
|
||||
}
|
||||
auto existing=fixture(3,Mode::existing_coord);Words out;xbg_spirv_quad_stats stats;
|
||||
assert(xbg_spirv_quad_derivatives(existing.data(),existing.size(),out,&stats)==1);++cases;
|
||||
auto invalid=fixture(3);invalid[5]=0;assert(!xbg_spirv_quad_derivatives(invalid.data(),invalid.size(),out,&stats));assert(out.empty());++cases;
|
||||
assert(!xbg_spirv_quad_derivatives(nullptr,0,out,&stats));assert(stats.skipped[size_t(xbg_quad_skip::malformed)]==1);++cases;
|
||||
auto ordinary=fixture(1);assert(xbg_spirv_quad_derivatives(ordinary.data(),ordinary.size(),out)==1);++cases;
|
||||
auto rounded=evaluate(out,{1e20f,1,1e20f,1});
|
||||
assert(rounded[0]!=1);++cases;
|
||||
std::cout<<"PASS quad_rewriter cases="<<cases<<"; active-lane arithmetic only; finite_rounding_limit_confirmed=1; device_helpers=NOT_TESTED\n";
|
||||
}
|
||||
static void audit(const fs::path &directory,const fs::path &output={}) {
|
||||
size_t modules=0,total=0;std::vector<fs::path> files;
|
||||
for(const auto &entry:fs::directory_iterator(directory))if(entry.path().extension()==".xgs")files.push_back(entry.path());
|
||||
std::sort(files.begin(),files.end());if(!output.empty())fs::create_directories(output);
|
||||
for(const auto &path:files) {
|
||||
std::ifstream file(path,std::ios::binary);std::vector<char> raw((std::istreambuf_iterator<char>(file)),{});
|
||||
if(raw.size()<32)throw std::runtime_error("short XGS");
|
||||
uint32_t h[8];std::memcpy(h,raw.data(),32);size_t offset=32+size_t(h[3])*32+size_t(h[4])*4+h[5];
|
||||
if(h[0]!=0x31534758 || h[1]!=1 || h[6]%4 || offset>raw.size() || h[6]!=raw.size()-offset)throw std::runtime_error("invalid XGS extent");
|
||||
Words before(h[6]/4),after;std::memcpy(before.data(),raw.data()+offset,h[6]);xbg_spirv_quad_stats stats;
|
||||
total+=xbg_spirv_quad_derivatives(before.data(),before.size(),after,&stats);++modules;
|
||||
std::cout<<"{\"shader\":\""<<path.filename().string()<<"\",\"stage\":"<<h[2]<<",\"candidates\":"<<stats.candidates<<",\"rewritten\":"<<stats.rewritten<<",\"skipped\":{";
|
||||
bool first=true;
|
||||
for(size_t i=0;i<size_t(xbg_quad_skip::count);++i)if(stats.skipped[i]) {if(!first)std::cout<<',';first=false;std::cout<<'"'<<xbg_spirv_quad_skip_name(xbg_quad_skip(i))<<"\":"<<stats.skipped[i];}
|
||||
std::cout<<"},\"calls\":"<<stats.calls<<",\"calls_rewritten\":"<<stats.calls_rewritten<<",\"call_skipped\":{";
|
||||
first=true;
|
||||
for(size_t i=0;i<size_t(xbg_quad_call_skip::count);++i)if(stats.call_skipped[i]) {if(!first)std::cout<<',';first=false;std::cout<<'"'<<xbg_spirv_quad_call_skip_name(xbg_quad_call_skip(i))<<"\":"<<stats.call_skipped[i];}
|
||||
std::cout<<"}}\n";
|
||||
if(!output.empty() && stats.candidates)save(output/(path.stem().string()+".spv"),after.empty()?before:after);
|
||||
}
|
||||
std::cerr<<"AUDIT modules="<<modules<<" rewritten="<<total<<"\n";
|
||||
}
|
||||
int main(int argc,char **argv) {
|
||||
try {
|
||||
if(argc>=3 && std::string(argv[1])=="--audit")audit(argv[2],argc>=4?fs::path(argv[3]):fs::path{});
|
||||
else if(argc==3 && std::string(argv[1])=="--emit-fixtures")run_tests(argv[2]);
|
||||
else if(argc==1)run_tests();
|
||||
else {std::cerr<<"usage: quad_test [--emit-fixtures dir | --audit xgs-dir [spv-dir]]\n";return 2;}
|
||||
return 0;
|
||||
} catch(const std::exception &error) {std::cerr<<error.what()<<'\n';return 1;}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
"""生产入口顺序门与负控制;不模拟 Vulkan。 / Production source guard, not a Vulkan simulation."""
|
||||
import pathlib
|
||||
import re
|
||||
import unittest
|
||||
|
||||
SOURCE = pathlib.Path(__file__).resolve().parents[1] / "xbg_game.cpp"
|
||||
ENTRIES = (
|
||||
"draw", "dispatch", "clear_attachment", "copy_texture_buffer",
|
||||
"copy_texture", "clear_texture", "resolve_texture", "execute_indirect",
|
||||
"xbg_present_texture_now", "xbg_legacy_read_texels", "gpu_buffer_copy",
|
||||
)
|
||||
|
||||
|
||||
def entry_prefix(source, name):
|
||||
match = re.search(r"(?:static )?(?:void|bool) " + name + r"\([^\n]*?\)\{", source)
|
||||
if not match:
|
||||
raise AssertionError("missing production entry: " + name)
|
||||
return match.end(), source[match.end():]
|
||||
|
||||
|
||||
# 预检可由宿主关闭(gfx-read-preflight / DM_GFX_READ_PREFLIGHT,Android 关闭),默认开启。
|
||||
# The preflight can be turned off by the host (gfx-read-preflight / DM_GFX_READ_PREFLIGHT; Android does), and is on by default.
|
||||
PREFLIGHT = "void preflight_cpu_reads(){if(read_preflight)resolve_pending();}"
|
||||
DEFAULT_ON = "bool read_preflight=true;"
|
||||
INVARIANT = 'need(!read_preflight || (pending_writebacks.empty() && pending_reports.empty()),"Unresolved CPU reads at descriptor entry");'
|
||||
|
||||
|
||||
def check(source):
|
||||
# 直接核生产函数,不复制同步/绘制实现。 / Inspect production functions without copying their implementations.
|
||||
if PREFLIGHT not in source or DEFAULT_ON not in source:
|
||||
raise AssertionError("preflight must resolve actual pending results")
|
||||
for name in ENTRIES:
|
||||
_, tail = entry_prefix(source, name)
|
||||
if name in ("xbg_present_texture_now", "xbg_legacy_read_texels"):
|
||||
lock = ("gfx_drain();" if name == "xbg_legacy_read_texels" else "") + "std::lock_guard<std::recursive_mutex> lock(mutex);"
|
||||
if not tail.startswith(lock):
|
||||
raise AssertionError("present preflight requires engine lock")
|
||||
tail = tail[len(lock):]
|
||||
if not tail.startswith("preflight_cpu_reads();"):
|
||||
raise AssertionError(name + ": preflight must precede all acquired references")
|
||||
_, tail = entry_prefix(source, "descriptors")
|
||||
if not tail.lstrip().startswith(INVARIANT):
|
||||
raise AssertionError("descriptor entry must reject unresolved results")
|
||||
if "s.recording=false;s.pending=true;" not in source or "release_descriptors(s);" not in source:
|
||||
raise AssertionError("retirement contract changed: re-audit required")
|
||||
|
||||
|
||||
class ReadPreflightOrder(unittest.TestCase):
|
||||
def test_production(self):
|
||||
check(SOURCE.read_text(encoding="utf-8"))
|
||||
|
||||
def test_missing_and_late_negative_controls(self):
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
for name in ENTRIES:
|
||||
offset, tail = entry_prefix(source, name)
|
||||
at = offset + tail.index("preflight_cpu_reads();")
|
||||
end = at + len("preflight_cpu_reads();")
|
||||
for replacement in ("", "Commands stale;preflight_cpu_reads();"):
|
||||
with self.subTest(entry=name, mutation=replacement):
|
||||
with self.assertRaises(AssertionError):
|
||||
check(source[:at] + replacement + source[end:])
|
||||
|
||||
def test_noop_and_missing_invariant_negative_controls(self):
|
||||
source = SOURCE.read_text(encoding="utf-8")
|
||||
for mutated in (
|
||||
source.replace(PREFLIGHT, "void preflight_cpu_reads(){}"),
|
||||
source.replace(DEFAULT_ON, "bool read_preflight=false;"),
|
||||
source.replace(INVARIANT, ""),
|
||||
):
|
||||
with self.assertRaises(AssertionError):
|
||||
check(mutated)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Loaded 100 of 347 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user