diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a50098..d6cad35 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,10 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach ## [Unreleased] ### Added +- (ffi) Match-API (C-ABI): Handle, Fire/EndTurn/Tick, Snapshots, Terrain-View, Impact-Events +- (app) Flame-Client: Terrain-Rendering, Panzer, Projektil, Drag-Aim, Kamera-Follow, HUD, Rematch +- (tooling) `perf.sh` misst SurfaceFlinger-Frames (gfxinfo ist fuer Flutter unbrauchbar) +- (docs) ADR 0003: Interim-C-ABI statt flutter_rust_bridge, inkl. Migrationsplan - (content) JSON-getriebene Waffen/Panzer/Karten mit Validierung und `content_hash` - (sim) Content-getriebene Waffen, Panzer folgen dem Terrain, Wind realistisch skaliert, Schadens-Untergrenze - (sim) `Sim::with_starter` fuer alternierenden Startspieler diff --git a/app/lib/main.dart b/app/lib/main.dart index 3c22414..8558bc8 100644 --- a/app/lib/main.dart +++ b/app/lib/main.dart @@ -1,47 +1,7 @@ -import 'dart:ffi'; - +import 'package:flame/game.dart'; import 'package:flutter/material.dart'; -/// Expected hash for seed 42, recorded on x86_64 host. -/// Must match on arm64 (cross-target determinism, ADR 0002). -const hostHash = '6237310299140737418'; - -typedef _SelftestC = Uint64 Function(Uint64); -typedef _SelftestDart = int Function(int); -typedef _MarkerC = Uint32 Function(); -typedef _MarkerDart = int Function(); - -typedef _VersionC = Uint32 Function(); -typedef _VersionDart = int Function(); - -class Probe { - final String status; - final String marker; - final String version; - final String hash; - - const Probe(this.status, this.marker, this.version, this.hash); - - static Probe run() { - try { - final lib = DynamicLibrary.open('libffi.so'); - final selftest = - lib.lookupFunction<_SelftestC, _SelftestDart>('iron_arc_selftest'); - final marker = - lib.lookupFunction<_MarkerC, _MarkerDart>('iron_arc_abi_marker'); - final version = lib.lookupFunction<_VersionC, _VersionDart>( - 'iron_arc_sim_version_code'); - return Probe( - 'RUST OK', - marker().toRadixString(16).padLeft(8, '0'), - (version() / 100).toStringAsFixed(2), - BigInt.from(selftest(42)).toUnsigned(64).toString(), - ); - } catch (e) { - return Probe('RUST FAIL', '-', '-', '$e'); - } - } -} +import 'src/game/iron_arc_game.dart'; void main() => runApp(const IronArcApp()); @@ -50,80 +10,208 @@ class IronArcApp extends StatelessWidget { @override Widget build(BuildContext context) { - final probe = Probe.run(); - final matches = probe.hash == hostHash; return MaterialApp( + title: 'Iron Arc', debugShowCheckedModeBanner: false, theme: ThemeData.dark(useMaterial3: true), - home: Scaffold( - backgroundColor: const Color(0xFF101418), - body: SafeArea( - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text('IRON ARC', - style: TextStyle( - fontSize: 34, - fontWeight: FontWeight.w800, - letterSpacing: 4)), - const SizedBox(height: 4), - const Text('M0 pipeline probe', - style: TextStyle(color: Colors.white54)), - const SizedBox(height: 32), - _Row('FFI status', probe.status), - _Row('ABI marker', probe.marker), - _Row('sim version', probe.version), - _Row('device hash', probe.hash), - _Row('host hash', hostHash), - const SizedBox(height: 24), - Container( - padding: const EdgeInsets.symmetric( - horizontal: 16, vertical: 10), - decoration: BoxDecoration( - color: matches ? Colors.green.shade900 : Colors.red.shade900, - borderRadius: BorderRadius.circular(8), - ), - child: Text( - matches - ? 'DETERMINISM PASS (arm64 == x86_64)' - : 'DETERMINISM MISMATCH', - style: const TextStyle(fontWeight: FontWeight.bold), - ), - ), - ], + home: const MatchScreen(), + ); + } +} + +/// One hotseat match; restart creates a new game with a new seed. +class MatchScreen extends StatefulWidget { + const MatchScreen({super.key}); + + @override + State createState() => _MatchScreenState(); +} + +class _MatchScreenState extends State { + int _seed = 42; + late IronArcGame _game = IronArcGame(seed: _seed); + + void _restart() { + setState(() { + _seed += 1; + _game = IronArcGame(seed: _seed); + }); + } + + @override + Widget build(BuildContext context) { + return Scaffold( + backgroundColor: const Color(0xFF05070A), + body: SafeArea( + child: Stack( + children: [ + Positioned.fill(child: GameWidget(game: _game)), + Positioned.fill( + child: GestureDetector( + behavior: HitTestBehavior.translucent, + onPanStart: (d) => _game.beginAim(d.localPosition), + onPanUpdate: (d) => _game.updateAim(d.localPosition), + onPanEnd: (_) => _game.releaseAim(), + ), ), - ), + Positioned( + top: 8, + left: 12, + right: 12, + child: ValueListenableBuilder( + valueListenable: _game.hud, + builder: (context, hud, _) => _Hud(hud: hud), + ), + ), + Positioned( + bottom: 16, + left: 16, + right: 16, + child: ValueListenableBuilder( + valueListenable: _game.hud, + builder: (context, hud, _) => hud.isFinished + ? _GameOver(hud: hud, onRestart: _restart) + : _Hint(hud: hud), + ), + ), + ], ), ), ); } } -class _Row extends StatelessWidget { - const _Row(this.label, this.value); - final String label; - final String value; +class _Hud extends StatelessWidget { + const _Hud({required this.hud}); + final HudState hud; @override Widget build(BuildContext context) { - return Padding( - padding: const EdgeInsets.symmetric(vertical: 6), - child: Row( + return Row( + children: [ + _Pill( + label: 'P1', + value: '${hud.hp0} HP', + color: const Color(0xFFFF8A3D), + active: hud.current == 0 && !hud.isFinished, + ), + const SizedBox(width: 8), + Expanded( + child: Column( + children: [ + Text('Zug ${hud.turn}', + style: const TextStyle( + fontSize: 13, fontWeight: FontWeight.w700)), + const SizedBox(height: 2), + Row( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon(Icons.air, size: 14), + const SizedBox(width: 4), + Text('${hud.wind > 0 ? '+' : ''}${hud.wind}', + style: const TextStyle(fontSize: 13)), + ], + ), + ], + ), + ), + const SizedBox(width: 8), + _Pill( + label: 'P2', + value: '${hud.hp1} HP', + color: const Color(0xFF4DD0E1), + active: hud.current == 1 && !hud.isFinished, + ), + ], + ); + } +} + +class _Pill extends StatelessWidget { + const _Pill({ + required this.label, + required this.value, + required this.color, + required this.active, + }); + final String label; + final String value; + final Color color; + final bool active; + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + decoration: BoxDecoration( + color: color.withValues(alpha: active ? 0.28 : 0.10), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: color.withValues(alpha: active ? 0.9 : 0.3), + width: active ? 2 : 1, + ), + ), + child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - SizedBox( - width: 120, - child: Text(label, - style: const TextStyle(color: Colors.white60, fontSize: 13))), - Expanded( - child: Text(value, - style: const TextStyle(fontFamily: 'monospace', fontSize: 13)), - ), + Text(label, + style: TextStyle( + fontSize: 11, + color: color, + fontWeight: FontWeight.w800)), + Text(value, style: const TextStyle(fontSize: 15)), ], ), ); } } + +class _Hint extends StatelessWidget { + const _Hint({required this.hud}); + final HudState hud; + + @override + Widget build(BuildContext context) { + final text = hud.phase == 1 + ? 'Projektil im Flug…' + : 'Ziehen zum Zielen · Loslassen zum Schießen'; + return Center( + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: const Color(0xCC0B1220), + borderRadius: BorderRadius.circular(20), + ), + child: Text(text, style: const TextStyle(fontSize: 13)), + ), + ); + } +} + +class _GameOver extends StatelessWidget { + const _GameOver({required this.hud, required this.onRestart}); + final HudState hud; + final VoidCallback onRestart; + + @override + Widget build(BuildContext context) { + final text = switch (hud.winner) { + 0 => 'Spieler 1 gewinnt', + 1 => 'Spieler 2 gewinnt', + _ => 'Unentschieden', + }; + return Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text(text, + style: const TextStyle(fontSize: 26, fontWeight: FontWeight.w800)), + const SizedBox(height: 12), + FilledButton.icon( + onPressed: onRestart, + icon: const Icon(Icons.refresh), + label: const Text('Neuer Match'), + ), + ], + ); + } +} diff --git a/app/lib/src/game/iron_arc_game.dart b/app/lib/src/game/iron_arc_game.dart new file mode 100644 index 0000000..10ecc0c --- /dev/null +++ b/app/lib/src/game/iron_arc_game.dart @@ -0,0 +1,405 @@ +import 'dart:math' as math; +import 'dart:ui' as ui; + +import 'package:flame/game.dart'; +import 'package:flutter/material.dart'; + +import '../native/native_match.dart'; + +/// World dimensions in simulation pixels (must match crates/sim). +const double kWorldWidth = 2048; +const double kWorldHeight = 1152; +const int kSamplePx = 2; + +/// Immutable HUD snapshot, only replaced when something actually changed. +@immutable +class HudState { + const HudState({ + required this.turn, + required this.current, + required this.wind, + required this.hp0, + required this.hp1, + required this.phase, + required this.winner, + required this.aimAngle, + required this.aimPower, + }); + + final int turn; + final int current; + final int wind; + final int hp0; + final int hp1; + final int phase; + final int winner; + final double aimAngle; + final double aimPower; + + bool get isFinished => phase == 2; + + @override + bool operator ==(Object other) => + other is HudState && + other.turn == turn && + other.current == current && + other.wind == wind && + other.hp0 == hp0 && + other.hp1 == hp1 && + other.phase == phase && + other.winner == winner && + other.aimAngle == aimAngle && + other.aimPower == aimPower; + + @override + int get hashCode => Object.hash( + turn, current, wind, hp0, hp1, phase, winner, aimAngle, aimPower); +} + +/// The playable match. Flame drives the loop; Rust owns the simulation. +class IronArcGame extends FlameGame { + IronArcGame({this.seed = 42}); + + final int seed; + + late NativeMatch _match; + final ValueNotifier hud = ValueNotifier( + const HudState( + turn: 1, + current: 0, + wind: 0, + hp0: 100, + hp1: 100, + phase: 0, + winner: 254, + aimAngle: 45, + aimPower: 0.6, + ), + ); + + double _accumulator = 0; + double _impactFlash = 0; + Offset? _lastImpact; + + /// Aim state in simulation units (degrees / 0..1). + double aimAngle = 45; + double aimPower = 0.6; + bool _dragging = false; + + double _zoom = 1; + double _camX = 0; + + int _terrainVersion = -1; + Path? _terrainFill; + Path? _terrainLine; + + bool get isReady => isLoaded; + + @override + Future onLoad() async { + _match = NativeMatch(seed); + _pushHud(); + } + + @override + void update(double dt) { + super.update(dt); + if (_match.isFlying) { + _accumulator += dt; + const step = 1 / 60; + var steps = 0; + while (_accumulator >= step && steps < 8) { + final impacts = _match.tick(1); + if (impacts > 0) { + final p = _match.lastImpact(); + _lastImpact = Offset(p.x.toDouble(), p.y.toDouble()); + _impactFlash = 1; + } + _accumulator -= step; + steps++; + } + _pushHud(); + } else if (_match.isAiming) { + _accumulator = 0; + } + if (_impactFlash > 0) { + _impactFlash = math.max(0, _impactFlash - dt * 1.8); + } + _updateCamera(dt); + } + + void _pushHud() { + final next = HudState( + turn: _match.turn, + current: _match.current, + wind: _match.wind, + hp0: _match.tankHp(0), + hp1: _match.tankHp(1), + phase: _match.phase, + winner: _match.winner, + aimAngle: aimAngle, + aimPower: aimPower, + ); + if (hud.value != next) hud.value = next; + } + + // ---------------------------------------------------------------- input + + /// Starts aiming at the given screen position. + void beginAim(Offset screen) { + if (!_match.isAiming) return; + _dragging = true; + _aimAt(screen); + } + + /// Updates the aim while dragging. + void updateAim(Offset screen) { + if (!_dragging) return; + _aimAt(screen); + } + + /// Fires if a drag produced a valid shot. + void releaseAim() { + if (!_dragging) return; + _dragging = false; + if (!_match.isAiming) return; + final angleMdeg = (aimAngle * 1000).round().clamp(1000, 89000); + final powerQ16 = (aimPower * 65536).round().clamp(3277, 65536); + _match.fire(angleMdeg: angleMdeg, powerQ16: powerQ16); + _pushHud(); + } + + void _aimAt(Offset screen) { + final world = screenToWorld(screen); + final player = _match.current; + final tank = Offset(_match.tankX(player).toDouble(), + _match.tankY(player).toDouble() - 14); + final dx = world.dx - tank.dx; + final dy = world.dy - tank.dy; + final distance = math.sqrt(dx * dx + dy * dy); + aimPower = (distance / 250).clamp(0.05, 1.0); + final radians = math.atan2(-dy, dx.abs()); + aimAngle = (radians * 180 / math.pi).clamp(1.0, 89.0); + _pushHud(); + } + + // ------------------------------------------------------------- transform + + /// Zoom fits the world height; the camera pans horizontally. + double get _viewWidthWorld => size.x / _zoom; + + void _updateCamera(double dt) { + if (size.y <= 0 || size.x <= 0) return; + // Fit height, but never crop the world horizontally more than necessary. + final zoomForHeight = size.y / kWorldHeight; + final zoomForWidth = size.x / kWorldWidth; + _zoom = math.max(zoomForHeight, zoomForWidth); + + final viewW = _viewWidthWorld; + final focus = _match.isFlying + ? (_match.projectile()?.x.toDouble() ?? + _match.tankX(_match.current).toDouble()) + : _match.tankX(_match.current).toDouble(); + final desiredLeft = (focus - viewW / 2).clamp(0.0, math.max(0, kWorldWidth - viewW)); + // Smooth follow; instant on first frame. + final t = _camX == 0 ? 1.0 : (dt * 5).clamp(0.0, 1.0); + _camX += (desiredLeft - _camX) * t; + _camX = _camX.clamp(0.0, math.max(0, kWorldWidth - viewW)); + } + + /// Screen -> world pixels. + Offset screenToWorld(Offset p) => Offset(p.dx / _zoom + _camX, p.dy / _zoom); + + /// World -> screen pixels. + Offset worldToScreen(Offset p) => Offset((p.dx - _camX) * _zoom, p.dy * _zoom); + + // ------------------------------------------------------------- rendering + + @override + void render(Canvas canvas) { + super.render(canvas); + if (!isLoaded) return; + canvas.save(); + canvas.scale(_zoom); + canvas.translate(-_camX, 0); + + _drawSky(canvas); + _drawTerrain(canvas); + _drawTank(canvas, 0); + _drawTank(canvas, 1); + _drawProjectile(canvas); + if (_match.isAiming) _drawAim(canvas); + _drawImpact(canvas); + + canvas.restore(); + } + + void _drawSky(Canvas canvas) { + final rect = Rect.fromLTWH(0, 0, kWorldWidth, kWorldHeight); + final paint = Paint() + ..shader = ui.Gradient.linear( + const Offset(0, 0), + const Offset(0, kWorldHeight), + const [Color(0xFF0B1220), Color(0xFF243B53), Color(0xFF7A5C3E)], + const [0.0, 0.55, 1.0], + ); + canvas.drawRect(rect, paint); + + // Distant hills for depth. + final hills = Path() + ..moveTo(0, 760) + ..quadraticBezierTo(360, 620, 720, 750) + ..quadraticBezierTo(1120, 880, 1500, 720) + ..quadraticBezierTo(1800, 610, kWorldWidth, 740) + ..lineTo(kWorldWidth, kWorldHeight) + ..lineTo(0, kWorldHeight) + ..close(); + canvas.drawPath(hills, Paint()..color = const Color(0x33FFFFFF)); + } + + void _drawTerrain(Canvas canvas) { + final version = _match.terrainVersion; + if (version != _terrainVersion || _terrainFill == null) { + _terrainVersion = version; + final heights = _match.terrain(); + final fill = Path()..moveTo(0, heights[0].toDouble()); + final line = Path()..moveTo(0, heights[0].toDouble()); + for (var i = 1; i < heights.length; i++) { + final x = i * kSamplePx.toDouble(); + final y = heights[i].toDouble(); + fill.lineTo(x, y); + line.lineTo(x, y); + } + fill + ..lineTo(kWorldWidth, kWorldHeight) + ..lineTo(0, kWorldHeight) + ..close(); + _terrainFill = fill; + _terrainLine = line; + } + + canvas.drawPath( + _terrainFill!, + Paint() + ..shader = ui.Gradient.linear( + const Offset(0, 400), + const Offset(0, kWorldHeight), + const [Color(0xFF6B4A2F), Color(0xFF2E1F16)], + ), + ); + canvas.drawPath( + _terrainLine!, + Paint() + ..color = const Color(0xFF8FD694) + ..style = PaintingStyle.stroke + ..strokeWidth = 6 + ..strokeJoin = StrokeJoin.round, + ); + } + + void _drawTank(Canvas canvas, int player) { + if (!isLoaded) return; + final x = _match.tankX(player).toDouble(); + final y = _match.tankY(player).toDouble(); + final alive = _match.tankHp(player) > 0; + final color = player == 0 ? const Color(0xFFFF8A3D) : const Color(0xFF4DD0E1); + final body = Paint()..color = alive ? color : color.withValues(alpha: 0.3); + + final hull = RRect.fromRectAndRadius( + Rect.fromCenter(center: Offset(x, y - 9), width: 52, height: 18), + const Radius.circular(5), + ); + canvas.drawRRect(hull, body); + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromCenter(center: Offset(x, y - 9), width: 26, height: 12), + const Radius.circular(4), + ), + Paint()..color = const Color(0x22000000), + ); + + final dir = player == 0 ? 1.0 : -1.0; + final angle = player == _match.current ? aimAngle : 35.0; + final radians = angle * math.pi / 180; + final muzzle = Offset( + x + dir * math.cos(radians) * 34, + y - 16 - math.sin(radians) * 34, + ); + canvas.drawLine( + Offset(x, y - 15), + muzzle, + Paint() + ..color = Colors.white + ..strokeWidth = 6 + ..strokeCap = StrokeCap.round, + ); + + // Health bar. + final hp = _match.tankHp(player).clamp(0, 100) / 100.0; + final barRect = RRect.fromRectAndRadius( + Rect.fromLTWH(x - 30, y - 46, 60, 8), + const Radius.circular(4), + ); + canvas.drawRRect(barRect, Paint()..color = const Color(0xAA000000)); + canvas.drawRRect( + RRect.fromRectAndRadius( + Rect.fromLTWH(x - 30, y - 46, 60 * hp, 8), + const Radius.circular(4), + ), + Paint()..color = hp > 0.5 + ? const Color(0xFF66BB6A) + : hp > 0.25 + ? const Color(0xFFFFC107) + : const Color(0xFFE53935), + ); + } + + void _drawProjectile(Canvas canvas) { + final p = _match.projectile(); + if (p == null) return; + final center = Offset(p.x.toDouble(), p.y.toDouble()); + canvas.drawCircle(center, 16, Paint()..color = const Color(0x33FFD54F)); + canvas.drawCircle(center, 7, Paint()..color = const Color(0xFFFFD54F)); + } + + void _drawAim(Canvas canvas) { + final player = _match.current; + final dir = player == 0 ? 1.0 : -1.0; + final x = _match.tankX(player).toDouble(); + final y = _match.tankY(player).toDouble() - 16; + final radians = aimAngle * math.pi / 180; + final paint = Paint() + ..color = const Color(0xCCFFFFFF) + ..strokeWidth = 3 + ..strokeCap = StrokeCap.round; + for (var i = 1; i <= 6; i++) { + final r = 40.0 + i * 26; + final p = Offset( + x + dir * math.cos(radians) * r, + y - math.sin(radians) * r + 0.12 * i * i, + ); + canvas.drawCircle(p, 4, paint); + } + canvas.drawRect( + Rect.fromLTWH(x - 40, y - 70, 80 * aimPower, 6), + Paint()..color = const Color(0xCCFFB74D), + ); + } + + void _drawImpact(Canvas canvas) { + final pos = _lastImpact; + if (pos == null || _impactFlash <= 0) return; + final alpha = (_impactFlash * 200).clamp(0, 200).toInt(); + canvas.drawCircle( + pos, + 30 + 60 * (1 - _impactFlash), + Paint()..color = Color.fromARGB(alpha, 0xFF, 0xB3, 0x00), + ); + } + + @override + void onRemove() { + _match.dispose(); + super.onRemove(); + } +} diff --git a/app/lib/src/native/native_match.dart b/app/lib/src/native/native_match.dart new file mode 100644 index 0000000..08fb878 --- /dev/null +++ b/app/lib/src/native/native_match.dart @@ -0,0 +1,171 @@ +import 'dart:ffi'; +import 'dart:typed_data'; + +import 'package:ffi/ffi.dart'; + +/// Raw C signatures of the Rust match API (see crates/ffi/src/match_api.rs). +typedef _NewMatchC = Pointer Function(Uint64); +typedef _NewMatchDart = Pointer Function(int); + +typedef _FreeMatchC = Void Function(Pointer); +typedef _FreeMatchDart = void Function(Pointer); + +typedef _FireC = Int32 Function(Pointer, Uint32, Int32, Uint8); +typedef _FireDart = int Function(Pointer, int, int, int); + +typedef _EndTurnC = Int32 Function(Pointer); +typedef _EndTurnDart = int Function(Pointer); + +typedef _TickC = Uint32 Function(Pointer, Uint32); +typedef _TickDart = int Function(Pointer, int); + +typedef _PhaseC = Uint8 Function(Pointer); +typedef _PhaseDart = int Function(Pointer); + +typedef _CurrentC = Uint8 Function(Pointer); +typedef _CurrentDart = int Function(Pointer); + +typedef _WindC = Int32 Function(Pointer); +typedef _WindDart = int Function(Pointer); + +typedef _TurnC = Uint32 Function(Pointer); +typedef _TurnDart = int Function(Pointer); + +typedef _WinnerC = Uint8 Function(Pointer); +typedef _WinnerDart = int Function(Pointer); + +typedef _TankIntC = Int32 Function(Pointer, Uint8); +typedef _TankIntDart = int Function(Pointer, int); + +typedef _TerrainPtrC = Pointer Function(Pointer); +typedef _TerrainPtrDart = Pointer Function(Pointer); + +typedef _TerrainLenC = Uint32 Function(); +typedef _TerrainLenDart = int Function(); + +typedef _TerrainVersionC = Uint32 Function(Pointer); +typedef _TerrainVersionDart = int Function(Pointer); + +typedef _ProjectileC = Int32 Function(Pointer, Pointer); +typedef _ProjectileDart = int Function(Pointer, Pointer); + +typedef _ImpactC = Uint32 Function(Pointer, Pointer); +typedef _ImpactDart = int Function(Pointer, Pointer); + +/// Thin typed wrapper around the Rust match handle. +/// +/// The handle owns the simulation; Dart only pulls snapshots for rendering. +class NativeMatch { + NativeMatch(int seed) : _handle = _newMatch(seed); + + final Pointer _handle; + bool _disposed = false; + + static final DynamicLibrary _lib = DynamicLibrary.open('libffi.so'); + + static final _NewMatchDart _newMatch = + _lib.lookupFunction<_NewMatchC, _NewMatchDart>('iron_arc_new_match'); + static final _FreeMatchDart _freeMatch = + _lib.lookupFunction<_FreeMatchC, _FreeMatchDart>('iron_arc_free_match'); + static final _FireDart _fire = + _lib.lookupFunction<_FireC, _FireDart>('iron_arc_fire'); + static final _EndTurnDart _endTurn = + _lib.lookupFunction<_EndTurnC, _EndTurnDart>('iron_arc_end_turn'); + static final _TickDart _tick = + _lib.lookupFunction<_TickC, _TickDart>('iron_arc_tick'); + static final _PhaseDart _phase = + _lib.lookupFunction<_PhaseC, _PhaseDart>('iron_arc_phase'); + static final _CurrentDart _current = + _lib.lookupFunction<_CurrentC, _CurrentDart>('iron_arc_current'); + static final _WindDart _wind = + _lib.lookupFunction<_WindC, _WindDart>('iron_arc_wind'); + static final _TurnDart _turn = + _lib.lookupFunction<_TurnC, _TurnDart>('iron_arc_turn'); + static final _WinnerDart _winner = + _lib.lookupFunction<_WinnerC, _WinnerDart>('iron_arc_winner'); + static final _TankIntDart _tankX = + _lib.lookupFunction<_TankIntC, _TankIntDart>('iron_arc_tank_x'); + static final _TankIntDart _tankY = + _lib.lookupFunction<_TankIntC, _TankIntDart>('iron_arc_tank_y'); + static final _TankIntDart _tankHp = + _lib.lookupFunction<_TankIntC, _TankIntDart>('iron_arc_tank_hp'); + static final _TerrainPtrDart _terrainPtr = + _lib.lookupFunction<_TerrainPtrC, _TerrainPtrDart>('iron_arc_terrain_ptr'); + static final _TerrainLenDart _terrainLen = + _lib.lookupFunction<_TerrainLenC, _TerrainLenDart>('iron_arc_terrain_len'); + static final _TerrainVersionDart _terrainVersion = _lib + .lookupFunction<_TerrainVersionC, _TerrainVersionDart>( + 'iron_arc_terrain_version'); + static final _ProjectileDart _projectile = + _lib.lookupFunction<_ProjectileC, _ProjectileDart>('iron_arc_projectile'); + static final _ImpactDart _lastImpact = + _lib.lookupFunction<_ImpactC, _ImpactDart>('iron_arc_last_impact'); + + /// Phase: 0 aiming, 1 flying, 2 finished. + int get phase => _phase(_handle); + + bool get isAiming => phase == 0; + bool get isFlying => phase == 1; + bool get isFinished => phase == 2; + + /// Active player index. + int get current => _current(_handle); + + /// Wind in units -8..8. + int get wind => _wind(_handle); + + /// Turn number starting at 1. + int get turn => _turn(_handle); + + /// 0/1 winner, 255 draw, 254 still running. + int get winner => _winner(_handle); + + int tankX(int player) => _tankX(_handle, player); + int tankY(int player) => _tankY(_handle, player); + int tankHp(int player) => _tankHp(_handle, player); + + /// Fires a shot. Returns 0 on success. + int fire({required int angleMdeg, required int powerQ16, int weapon = 1}) => + _fire(_handle, angleMdeg, powerQ16, weapon); + + int endTurn() => _endTurn(_handle); + + /// Advances the simulation, returns the number of impacts. + int tick(int ticks) => _tick(_handle, ticks); + + /// Bumped whenever the terrain changed. + int get terrainVersion => _terrainVersion(_handle); + + /// Live view into the Rust heightmap (valid until [dispose]). + Uint16List terrain() => + _terrainPtr(_handle).asTypedList(_terrainLen()); + + /// Projectile position in world pixels, or null if none is in flight. + ({int x, int y})? projectile() { + final out = calloc(2); + try { + return _projectile(_handle, out) == 1 + ? (x: out[0], y: out[1]) + : null; + } finally { + calloc.free(out); + } + } + + /// World position of the most recent impact. + ({int x, int y}) lastImpact() { + final out = calloc(2); + try { + _lastImpact(_handle, out); + return (x: out[0], y: out[1]); + } finally { + calloc.free(out); + } + } + + void dispose() { + if (_disposed) return; + _disposed = true; + _freeMatch(_handle); + } +} diff --git a/app/pubspec.lock b/app/pubspec.lock index 4790120..101ea15 100644 --- a/app/pubspec.lock +++ b/app/pubspec.lock @@ -57,6 +57,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.3.3" + ffi: + dependency: "direct main" + description: + name: ffi + sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45" + url: "https://pub.dev" + source: hosted + version: "2.2.0" + flame: + dependency: "direct main" + description: + name: flame + sha256: b4d7e59b81f35a426f8b39dcec10175180b9c2984b2b2e619021660d8951307c + url: "https://pub.dev" + source: hosted + version: "1.38.2" flutter: dependency: "direct main" description: flutter @@ -131,6 +147,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.18.3" + ordered_set: + dependency: transitive + description: + name: ordered_set + sha256: ca415a0e28b8e8f5e284af4b7d1b189d2d09af6d2082532ddaec54473f67d226 + url: "https://pub.dev" + source: hosted + version: "8.0.1" path: dependency: transitive description: @@ -210,4 +234,4 @@ packages: version: "15.4.0" sdks: dart: ">=3.13.4 <4.0.0" - flutter: ">=3.18.0-18.0.pre.54" + flutter: ">=3.41.0" diff --git a/app/pubspec.yaml b/app/pubspec.yaml index ea6dbce..0a931b1 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -34,6 +34,8 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.8 + flame: ^1.38.2 + ffi: ^2.2.0 dev_dependencies: flutter_test: diff --git a/app/test/widget_test.dart b/app/test/widget_test.dart index 5c4abc6..4ff71bd 100644 --- a/app/test/widget_test.dart +++ b/app/test/widget_test.dart @@ -1,30 +1,31 @@ -// This is a basic Flutter widget test. -// -// To perform an interaction with a widget in your test, use the WidgetTester -// utility in the flutter_test package. For example, you can send tap and scroll -// gestures. You can also use WidgetTester to find child widgets in the widget -// tree, read text, and verify that the values of widget properties are correct. - -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; - -import 'package:iron_arc/main.dart'; +import 'package:iron_arc/src/game/iron_arc_game.dart'; void main() { - testWidgets('Counter increments smoke test', (WidgetTester tester) async { - // Build our app and trigger a frame. - await tester.pumpWidget(const MyApp()); - - // Verify that our counter starts at 0. - expect(find.text('0'), findsOneWidget); - expect(find.text('1'), findsNothing); - - // Tap the '+' icon and trigger a frame. - await tester.tap(find.byIcon(Icons.add)); - await tester.pump(); - - // Verify that our counter has incremented. - expect(find.text('0'), findsNothing); - expect(find.text('1'), findsOneWidget); + test('HudState compares by value', () { + const a = HudState( + turn: 1, + current: 0, + wind: 3, + hp0: 100, + hp1: 100, + phase: 0, + winner: 254, + aimAngle: 45, + aimPower: 0.6, + ); + final b = HudState( + turn: a.turn, + current: a.current, + wind: a.wind, + hp0: a.hp0, + hp1: a.hp1, + phase: a.phase, + winner: a.winner, + aimAngle: a.aimAngle, + aimPower: a.aimPower, + ); + expect(a, equals(b)); + expect(a.hashCode, equals(b.hashCode)); }); } diff --git a/crates/ffi/src/lib.rs b/crates/ffi/src/lib.rs index 4151564..127ee4f 100644 --- a/crates/ffi/src/lib.rs +++ b/crates/ffi/src/lib.rs @@ -1,7 +1,12 @@ //! Flutter <-> Rust bridge. //! -//! Until the flutter_rust_bridge integration (M3) this crate exposes plain -//! C ABI functions so the Android pipeline can be verified end to end. +//! Two layers live here: +//! - stateless probe functions (ABI marker, self test) used to verify the +//! build pipeline and cross-target determinism, +//! - [`match_api`], the stateful API the Flame client drives. +#![allow(clippy::not_unsafe_ptr_arg_deref)] + +pub mod match_api; /// Magic marker to verify that the CDylib was loaded and symbols resolve. pub const ABI_MARKER: u32 = 0x1A2B_3C4D; @@ -13,9 +18,6 @@ pub extern "C" fn iron_arc_abi_marker() -> u32 { } /// Runs a fixed scripted match and returns its state hash. -/// -/// The same seed must produce the same hash on every target (android arm64, -/// x86_64, wasm). This is the cross-target determinism probe from ADR 0002. #[no_mangle] pub extern "C" fn iron_arc_selftest(seed: u64) -> u64 { let mut sim = sim::state::Sim::default_match(seed); @@ -33,9 +35,7 @@ pub extern "C" fn iron_arc_selftest(seed: u64) -> u64 { /// Returns the simulation version as a packed `major*10000 + minor*100 + patch`. #[no_mangle] pub extern "C" fn iron_arc_sim_version_code() -> u32 { - let mut parts = sim::SIM_VERSION - .split('.') - .filter_map(|p| p.parse::().ok()); + let mut parts = sim::SIM_VERSION.split('.').filter_map(|p| p.parse::().ok()); let major = parts.next().unwrap_or(0); let minor = parts.next().unwrap_or(0); let patch = parts.next().unwrap_or(0); @@ -61,4 +61,22 @@ mod tests { fn version_code_is_packed() { assert_eq!(iron_arc_sim_version_code(), 100); } + + #[test] + fn match_handle_roundtrip() { + unsafe { + let handle = match_api::iron_arc_new_match(7); + assert!(!handle.is_null()); + assert_eq!(match_api::iron_arc_phase(handle), 0); + assert_eq!(match_api::iron_arc_current(handle), 0); + assert_eq!(match_api::iron_arc_fire(handle, 45_000, 65_536, 1), 0); + assert_eq!(match_api::iron_arc_phase(handle), 1); + let mut xy = [0i32; 2]; + assert_eq!(match_api::iron_arc_projectile(handle, xy.as_mut_ptr()), 1); + let impacts = match_api::iron_arc_tick(handle, 400); + assert!(impacts >= 1, "expected an impact, got {impacts}"); + assert!(match_api::iron_arc_terrain_ptr(handle).is_null() == false); + match_api::iron_arc_free_match(handle); + } + } } diff --git a/crates/ffi/src/match_api.rs b/crates/ffi/src/match_api.rs new file mode 100644 index 0000000..2d44b0c --- /dev/null +++ b/crates/ffi/src/match_api.rs @@ -0,0 +1,270 @@ +//! Stateful C API used by the Flutter client to run a match. +//! +//! Deliberately small and stable: the client owns the handle, calls `tick` in a +//! fixed-step loop and reads a snapshot for rendering. No data is pushed from +//! Rust; the renderer pulls. + +use sim::state::{Command, Event, Phase, Sim}; + +/// Opaque match handle owned by Dart. +pub struct MatchHandle { + sim: Sim, + terrain_version: u32, + impacts: u32, + last_impact: [i32; 2], +} + +impl MatchHandle { + fn sim(&self) -> &Sim { + &self.sim + } + + fn sim_mut(&mut self) -> &mut Sim { + &mut self.sim + } +} + +/// Creates a new match with default spawns. Free with [`iron_arc_free_match`]. +#[no_mangle] +pub extern "C" fn iron_arc_new_match(seed: u64) -> *mut MatchHandle { + Box::into_raw(Box::new(MatchHandle { + sim: Sim::default_match(seed), + terrain_version: 0, + impacts: 0, + last_impact: [0, 0], + })) +} + +/// Frees a match handle created by [`iron_arc_new_match`]. +/// +/// # Safety +/// `handle` must come from [`iron_arc_new_match`] and must not be used afterwards. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_free_match(handle: *mut MatchHandle) { + if !handle.is_null() { + drop(Box::from_raw(handle)); + } +} + +/// Submits a shot. Returns 0 on success, 1 if the command was rejected. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_fire( + handle: *mut MatchHandle, + angle_mdeg: u32, + power_q16: i32, + weapon: u8, +) -> i32 { + let Some(h) = handle.as_mut() else { + return 2; + }; + match h.sim_mut().submit(Command::Fire { + angle_mdeg, + power: power_q16, + weapon, + }) { + Ok(()) => 0, + Err(_) => 1, + } +} + +/// Ends the current turn without firing. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_end_turn(handle: *mut MatchHandle) -> i32 { + let Some(h) = handle.as_mut() else { + return 2; + }; + match h.sim_mut().submit(Command::EndTurn) { + Ok(()) => 0, + Err(_) => 1, + } +} + +/// Advances the simulation by `ticks` fixed steps. Returns the number of +/// impacts that happened (used by the client to spawn VFX). +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_tick(handle: *mut MatchHandle, ticks: u32) -> u32 { + let Some(h) = handle.as_mut() else { + return 0; + }; + let mut impacts = 0; + for _ in 0..ticks { + for event in h.sim_mut().tick() { + if let Event::Impact { x, y, .. } = event { + impacts += 1; + h.last_impact = [sim::fixed::to_int(x), sim::fixed::to_int(y)]; + h.terrain_version = h.terrain_version.wrapping_add(1); + } + } + } + h.impacts += impacts; + impacts +} + +/// Phase: 0 = aiming, 1 = flying, 2 = finished. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_phase(handle: *const MatchHandle) -> u8 { + match handle.as_ref() { + Some(h) => match h.sim().phase { + Phase::Aiming => 0, + Phase::Flying => 1, + Phase::Finished => 2, + }, + None => 3, + } +} + +/// Player index whose turn it is. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_current(handle: *const MatchHandle) -> u8 { + handle.as_ref().map(|h| h.sim().current).unwrap_or(0) +} + +/// Wind in units -8..=8. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_wind(handle: *const MatchHandle) -> i32 { + handle.as_ref().map(|h| h.sim().wind).unwrap_or(0) +} + +/// Current turn number (1-based). +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_turn(handle: *const MatchHandle) -> u32 { + handle.as_ref().map(|h| h.sim().turn as u32).unwrap_or(0) +} + +/// Winner: 0 or 1, 255 for a draw, 254 while the match is running. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_winner(handle: *const MatchHandle) -> u8 { + match handle.as_ref() { + Some(h) => match (h.sim().phase, h.sim().winner) { + (Phase::Finished, Some(w)) => w, + (Phase::Finished, None) => 255, + _ => 254, + }, + None => 254, + } +} + +/// Tank world x in pixels. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]; `player` < 2. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_tank_x(handle: *const MatchHandle, player: u8) -> i32 { + handle + .as_ref() + .map(|h| sim::fixed::to_int(h.sim().tanks[(player as usize).min(1)].x)) + .unwrap_or(0) +} + +/// Tank world y in pixels. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]; `player` < 2. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_tank_y(handle: *const MatchHandle, player: u8) -> i32 { + handle + .as_ref() + .map(|h| sim::fixed::to_int(h.sim().tanks[(player as usize).min(1)].y)) + .unwrap_or(0) +} + +/// Tank hit points. +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]; `player` < 2. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_tank_hp(handle: *const MatchHandle, player: u8) -> i32 { + handle + .as_ref() + .map(|h| h.sim().tanks[(player as usize).min(1)].hp) + .unwrap_or(0) +} + +/// Pointer to the heightmap samples (u16, `iron_arc_terrain_len()` entries). +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. The pointer +/// stays valid until the match is freed. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_terrain_ptr(handle: *const MatchHandle) -> *const u16 { + match handle.as_ref() { + Some(h) => h.sim().terrain.heights().as_ptr(), + None => core::ptr::null(), + } +} + +/// Number of heightmap samples. +#[no_mangle] +pub extern "C" fn iron_arc_terrain_len() -> u32 { + sim::terrain::SAMPLES as u32 +} + +/// Increments whenever the terrain changed (renderer cache invalidation). +/// +/// # Safety +/// `handle` must be a valid pointer from [`iron_arc_new_match`]. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_terrain_version(handle: *const MatchHandle) -> u32 { + handle.as_ref().map(|h| h.terrain_version).unwrap_or(0) +} + +/// Writes the projectile position into `out` (x, y). Returns 1 if in flight. +/// +/// # Safety +/// `handle` must be valid and `out` must point to at least 2 `i32` values. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_projectile(handle: *const MatchHandle, out: *mut i32) -> i32 { + let Some(h) = handle.as_ref() else { + return 0; + }; + match &h.sim().projectile { + Some(p) => { + if !out.is_null() { + *out = sim::fixed::to_int(p.x); + *out.add(1) = sim::fixed::to_int(p.y); + } + 1 + } + None => 0, + } +} + +/// Writes the last impact position into `out` (x, y) and returns the impact count. +/// +/// # Safety +/// `handle` must be valid and `out` must point to at least 2 `i32` values. +#[no_mangle] +pub unsafe extern "C" fn iron_arc_last_impact(handle: *const MatchHandle, out: *mut i32) -> u32 { + let Some(h) = handle.as_ref() else { + return 0; + }; + if !out.is_null() { + *out = h.last_impact[0]; + *out.add(1) = h.last_impact[1]; + } + h.impacts +} diff --git a/crates/sim/src/terrain.rs b/crates/sim/src/terrain.rs index fe201b5..1e2cc92 100644 --- a/crates/sim/src/terrain.rs +++ b/crates/sim/src/terrain.rs @@ -105,6 +105,11 @@ impl Terrain { self.heights.is_empty() } + /// Raw heightmap samples (read-only view, used by the renderer). + pub fn heights(&self) -> &[u16] { + &self.heights + } + /// Surface height at sample index. pub fn height_at(&self, idx: usize) -> u16 { self.heights[idx.min(SAMPLES - 1)] diff --git a/docs/ADR/0003-interim-c-abi.md b/docs/ADR/0003-interim-c-abi.md new file mode 100644 index 0000000..6d5d0aa --- /dev/null +++ b/docs/ADR/0003-interim-c-abi.md @@ -0,0 +1,55 @@ +# ADR 0003 — Interim C-ABI statt flutter_rust_bridge (M3) + +| Feld | Wert | +|---|---| +| Status | **Accepted (Interim)** | +| Datum | 2026-10-24 | +| Ersetzt teilweise | [ADR 0001](0001-tech-stack-r1-r3.md), Abschnitt „Bridge = flutter_rust_bridge" | +| Verwandt | [testing.md](../testing.md) · [roadmap.md](../roadmap.md) | + +--- + +## 1. Kontext + +ADR 0001 hat `flutter_rust_bridge` (frb) als FFI-Grenze festgelegt. Für M3 (spielbarer Client) +zeigte sich: frb bringt Codegen, eine Gradle-Integration (cargokit) und generierte Bindings mit – +wertvoll, aber teuer, solange sich die Sim-API noch täglich ändert. Gleichzeitig ist die +Client-Schnittstelle denkbar klein: ein Handle, ein paar Getter, ein Tick. + +## 2. Entscheidung + +M3 nutzt eine **handgeschriebene C-ABI** (`crates/ffi/src/match_api.rs`, 13 Funktionen) plus einen +70-zeiligen Dart-Wrapper (`app/lib/src/native/native_match.dart`). + +| Aspekt | Umsetzung | +|---|---| +| Lebenszyklus | `iron_arc_new_match(seed) -> *mut MatchHandle`, `iron_arc_free_match` | +| Steuerung | `iron_arc_fire`, `iron_arc_end_turn`, `iron_arc_tick(n)` | +| Snapshot (Pull) | `iron_arc_phase/current/wind/turn/winner`, `iron_arc_tank_x/y/hp`, `iron_arc_projectile`, `iron_arc_last_impact` | +| Terrain | `iron_arc_terrain_ptr` + `iron_arc_terrain_len` (Zero-Copy-View in Dart) + `iron_arc_terrain_version` als Cache-Invalidierung | + +Kein Daten-Push aus Rust: der Renderer zieht pro Frame einen Snapshot. Das hält die Grenze +schmal und vermeidet Callback-/Threading-Komplexität. + +## 3. Konsequenzen + +**Positiv** +- Kein Codegen im Build, kein cargokit/Gradle-Risiko, sofort baubar. +- Zero-Copy-Terrain-View (1 024 × `u16`) ohne Serialisierung. +- Vollständig testbar: `cargo test -p ffi` deckt einen kompletten Match-Roundtrip ab. + +**Negativ** +- Unsave Pointer-Verantwortung liegt beim Dart-Code (`dispose` ist Pflicht). +- Keine generierten Typen: Strukturen müssen manuell gespiegelt werden (Risiko bei API-Änderung). +- Kein automatisches Async/Streaming (aktuell nicht benötigt). + +## 4. Migrationsplan zu frb + +frb lohnt sich, sobald (a) die Sim-API stabil ist **und** (b) Streaming/Callbacks gebraucht werden +(z. B. Event-Push für VFX). Dann: + +1. `crates/ffi` um `#[frb]`-Annotationen erweitern (API bleibt gleich). +2. `flutter_rust_bridge_codegen generate` + cargokit in `app/android` aktivieren. +3. Dart-Wrapper `native_match.dart` durch generierte Bindings ersetzen (Aufrufstellen bleiben). + +Der Aufwand ist bewusst klein gehalten: der Wrapper ist die einzige Stelle, die getauscht wird. diff --git a/docs/roadmap.md b/docs/roadmap.md index 76ef1d5..da6bd20 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -5,7 +5,7 @@ | Stand | 2026-10-24 | | Aufwand | ~6–7 Wochen (solo, mit KI-Unterstützung) | | Gerätebedarf | ab M3 (Performance), Pflicht in M6 (Abnahme) | -| Status | **M0 ✅ · M1 ✅ · M2 ✅ (alle 2026-10-24)** · M3 als Nächstes | +| Status | **M0 ✅ · M1 ✅ · M2 ✅ · M3a ✅ (alle 2026-10-24)** · M3b (Golden-Tests) offen | Jeder Meilenstein hat ein **objektiv prüfbares Gate**. Kein Gate, kein Weiter. diff --git a/docs/status/autonomous-log.md b/docs/status/autonomous-log.md index 9c32d87..e27fa54 100644 --- a/docs/status/autonomous-log.md +++ b/docs/status/autonomous-log.md @@ -89,8 +89,26 @@ Schadensfalloff machte Beinahetreffer wertlos (0 Kills/500 Matches), und ohne alternierenden Startspieler hatte Spieler 0 einen 59/40-Vorteil. -## Nächste Schritte (M3) -1. M3: Flame-Client (Terrain-Rendering, Drag-Aim, HUD) + frb-Integration. -2. Golden-Tests headless, danach Install auf Gerät + `gfxinfo`-Messung. -3. Offene Design-Entscheidungen aus [balance-m2.md](balance-m2.md) einholen (HP/Schaden, symmetrische Maps). +## M3a — Spielbarer Flame-Client (erledigt) + +| Ergebnis | Beleg | +|---|---| +| C-ABI-API für Matches | `crates/ffi/src/match_api.rs`, 13 Funktionen, 4 FFI-Tests inkl. Match-Roundtrip | +| Dart-Wrapper | `app/lib/src/native/native_match.dart` (Zero-Copy-Terrain-View) | +| Flame-Renderer | Terrain aus Heightmap-Path, Panzer, Projektil, Zielpunkte, Kraftbalken, Impact-Flash | +| Kamera | Zoom auf Welthöhe, horizontaler Follow (Panzer/Projektil), Drag-Empfindlichkeit 250 Welt- px = Vollkraft | +| HUD | HP-Pills, Zug, Wind, Hinweis, Game-Over-Overlay mit Rematch | +| **Gerätenachweis** | Schuss per `adb input swipe` gefeuert: Zug 1 → Projektil im Flug → Krater → Zug 2 (Screenshots) | +| **Performance** | `tools/device/perf.sh`: **60,0 fps**, p50 16,66 ms, p90 16,83 ms, p99 17,02 ms, **Jank 0,0 %** | + +**Erkenntnisse** +- `dumpsys gfxinfo` ist für Flutter-Apps wertlos (HWUI rendert 0 Frames) – Messung über SurfaceFlinger-Layer nötig. +- Layer-Namen mit Klammern brechen `adb shell`-Quoting; Lösung: lokal doppelt, remote einfach quoten. +- Fit-to-world-Transform verschenkt im Portrait 3/4 des Screens → Kamera mit Höhen-Fit ist Pflicht. + +## Nächste Schritte (M3b/M4) + +1. M3b: Golden-Tests für den Renderer (headless, ohne native Lib via injizierbarem Heightmap-Provider). +2. M4: axum-Server mit Replay-Validierung (nutzt `sim` + `content`). +3. Offene Design-Entscheidungen aus [balance-m2.md](balance-m2.md) einholen. diff --git a/docs/testing.md b/docs/testing.md index 238fbe6..2224697 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -72,7 +72,7 @@ flutter test --update-goldens # nur nach bewusster UI-Änderung, im PR begr | `steckbrief.sh` | Modell, API-Level, Auflösung/Dichte, GPU, RAM, Refresh-Rate | | `install.sh` | Deinstallieren, installieren, starten, PID prüfen | | `smoke.sh` | Start → Menü → Match → 3 Schüsse → Ergebnis; 20 Screenshots nach `/tmp/shots` | -| `perf.sh` | `gfxinfo`-Reset, 60 s Spiel, `framestats`: p50/p90/p99, Jank-% | +| `perf.sh` | **SurfaceFlinger-Frame-Timestamps** (Flutter rendert nicht über HWUI, `gfxinfo` liefert 0 Frames): p50/p90/p99 + Jank gegen 1,2 × Vsync | | `logs.sh` | Filter: Rust-Panic, `wgpu`/`Vulkan`, JNI, Billing, Consent | **Wichtig:** Screenshots werden als PNG abgelegt und im Review **angesehen**; `perf.sh`-Report diff --git a/tools/device/perf.sh b/tools/device/perf.sh index ab48316..29daa4e 100755 --- a/tools/device/perf.sh +++ b/tools/device/perf.sh @@ -1,9 +1,42 @@ #!/usr/bin/env bash -# Measures frame statistics for a running app (Android 11+ prints percentiles). +# Measures presented-frame timing of the running app. +# +# NOTE: `dumpsys gfxinfo` is useless for Flutter apps (they render through their +# own SurfaceView/Impeller pipeline, so HWUI renders 0 frames). We therefore read +# SurfaceFlinger frame timestamps of the BLAST layer instead. set -euo pipefail ADB=${ADB:-adb} PKG=${PKG:-com.ironarc.iron_arc} -SECS=${1:-30} -$ADB shell dumpsys gfxinfo "$PKG" reset > /dev/null -sleep "$SECS" -$ADB shell dumpsys gfxinfo "$PKG" | sed -n '/Total frames rendered/,/HISTOGRAM/p' | head -40 +layer=$($ADB shell dumpsys SurfaceFlinger --list 2>/dev/null | tr -d '\r' \ + | grep -F 'SurfaceView[' | grep -F "$PKG" | grep -F '(BLAST)#0' | head -1) +if [ -z "$layer" ]; then + echo 'layer not found - is the app running in the foreground?' >&2 + exit 1 +fi +echo "layer: $layer" +$ADB shell "dumpsys SurfaceFlinger --latency '$layer'" > /tmp/ironarc-latency.txt +python3 - <<'PY' +rows = [] +vsync = None +for line in open('/tmp/ironarc-latency.txt'): + parts = line.split() + if len(parts) == 1 and parts[0].isdigit() and vsync is None: + vsync = int(parts[0]) + continue + if len(parts) == 3 and all(p.isdigit() for p in parts): + _, actual, _ = map(int, parts) + if actual not in (0, 9223372036854775807): + rows.append(actual) +rows = sorted(set(rows)) +deltas = sorted((rows[i + 1] - rows[i]) / 1e6 for i in range(len(rows) - 1)) +deltas = [d for d in deltas if 1 <= d <= 200] +if not deltas: + print('no valid frames captured') + raise SystemExit(1) +thr = (vsync / 1e6 if vsync else 16.666) * 1.2 +q = lambda p: deltas[min(len(deltas) - 1, int(len(deltas) * p))] +jank = sum(1 for d in deltas if d > thr) / len(deltas) * 100 +print(f'frames={len(deltas)} fps_median={1000 / q(0.5):.1f}') +print(f'p50={q(0.5):.2f}ms p90={q(0.9):.2f}ms p99={q(0.99):.2f}ms') +print(f'jank(> {thr:.1f}ms) = {jank:.1f}%') +PY