feat(m5): client-server sync, offline queue and replay playback
This commit is contained in:
@@ -7,6 +7,10 @@ Alle nennenswerten Änderungen an diesem Projekt. Format nach
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- (ffi) Replay-Export (`iron_arc_replay_json`), Playback-Handle, `iron_arc_state_hash`
|
||||
- (app) HTTP-Client, Offline-Queue, MatchSession mit Desync-Erkennung und Replay-Playback
|
||||
- (app) Layout mit getrenntem Spielfeld und Bedienleiste
|
||||
- (protocol) Hashes als Hex-Strings (Praezision ab 2^53)
|
||||
- (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)
|
||||
|
||||
Generated
+1
@@ -258,6 +258,7 @@ name = "ffi"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"content",
|
||||
"serde_json",
|
||||
"sim",
|
||||
]
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
|
||||
xmlns:tools="http://schemas.android.com/tools">
|
||||
<!-- The INTERNET permission is required for development. Specifically,
|
||||
the Flutter tool needs it to communicate with the running application
|
||||
to allow setting breakpoints, to provide hot reload, etc.
|
||||
-->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<!-- Debug builds may talk plain HTTP to the local referee (adb reverse).
|
||||
Release builds keep cleartext disabled. -->
|
||||
<application android:usesCleartextTraffic="true" tools:targetApi="28" />
|
||||
</manifest>
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||
<!-- Needed to reach the replay referee. -->
|
||||
<uses-permission android:name="android.permission.INTERNET"/>
|
||||
<application
|
||||
android:label="iron_arc"
|
||||
android:name="${applicationName}"
|
||||
|
||||
+149
-162
@@ -1,7 +1,13 @@
|
||||
import 'package:flame/game.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'src/game/iron_arc_game.dart';
|
||||
import 'src/native/native_match.dart';
|
||||
import 'src/net/api_client.dart';
|
||||
import 'src/net/match_session.dart';
|
||||
import 'src/net/offline_queue.dart';
|
||||
import 'src/ui/widgets.dart';
|
||||
|
||||
void main() => runApp(const IronArcApp());
|
||||
|
||||
@@ -19,7 +25,7 @@ class IronArcApp extends StatelessWidget {
|
||||
}
|
||||
}
|
||||
|
||||
/// One hotseat match; restart creates a new game with a new seed.
|
||||
/// Hotseat match with optional server sync (`adb reverse tcp:8080 tcp:8080`).
|
||||
class MatchScreen extends StatefulWidget {
|
||||
const MatchScreen({super.key});
|
||||
|
||||
@@ -28,50 +34,166 @@ class MatchScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _MatchScreenState extends State<MatchScreen> {
|
||||
static const _baseUrl = 'http://127.0.0.1:8080';
|
||||
|
||||
int _seed = 42;
|
||||
late IronArcGame _game = IronArcGame(seed: _seed);
|
||||
late final ApiClient _api = ApiClient(baseUrl: _baseUrl);
|
||||
late final OfflineQueue _queue = OfflineQueue();
|
||||
late final MatchSession _session =
|
||||
MatchSession(client: _api, queue: _queue, deviceId: 'pending');
|
||||
late IronArcGame _game = _buildGame();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initSession();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_api.close();
|
||||
_session.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
/// Loads or creates a stable device id, then refreshes the offline queue.
|
||||
Future<void> _initSession() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
var id = prefs.getString('iron_arc.device_id');
|
||||
if (id == null || id.length < 4) {
|
||||
id = 'dev-${DateTime.now().microsecondsSinceEpoch.toRadixString(16)}';
|
||||
await prefs.setString('iron_arc.device_id', id);
|
||||
}
|
||||
_session.deviceId = id;
|
||||
await _session.refreshQueueSize();
|
||||
}
|
||||
|
||||
IronArcGame _buildGame({int? seed, String? replayJson}) {
|
||||
final game = replayJson != null
|
||||
? IronArcGame(matchFactory: () => NativeMatch.playback(replayJson))
|
||||
: IronArcGame(seed: seed ?? _seed);
|
||||
game.onShotResolved = (expect, command, localHashAfter) {
|
||||
if (game.isPlayback) return;
|
||||
if (_session.status == SyncStatus.online) {
|
||||
_session.submitShot(
|
||||
expectHash: expect,
|
||||
command: command,
|
||||
localHashAfter: localHashAfter,
|
||||
replayJson: game.replayJson(),
|
||||
);
|
||||
} else if (game.hud.value.isFinished) {
|
||||
_session.enqueueReplay(game.replayJson());
|
||||
}
|
||||
};
|
||||
return game;
|
||||
}
|
||||
|
||||
Future<void> _startOnline() async {
|
||||
final seed = await _session.startOnlineMatch();
|
||||
if (!mounted || seed == null) {
|
||||
_toast('Server nicht erreichbar');
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_seed = seed;
|
||||
_game = _buildGame(seed: seed);
|
||||
});
|
||||
_toast('Online-Match ${_session.matchId}');
|
||||
}
|
||||
|
||||
void _playReplay() {
|
||||
final json = _game.replayJson();
|
||||
debugPrint('iron_arc: replay tapped, ${json.length} bytes');
|
||||
if (json.isEmpty) {
|
||||
_toast('Kein Replay vorhanden');
|
||||
return;
|
||||
}
|
||||
setState(() => _game = _buildGame(replayJson: json));
|
||||
_toast('Replay läuft');
|
||||
}
|
||||
|
||||
Future<void> _flushQueue() async {
|
||||
final validated = await _session.flushQueue();
|
||||
if (mounted) _toast('$validated Replay(s) validiert');
|
||||
}
|
||||
|
||||
void _restart() {
|
||||
setState(() {
|
||||
_seed += 1;
|
||||
_game = IronArcGame(seed: _seed);
|
||||
_game = _buildGame(seed: _seed);
|
||||
});
|
||||
}
|
||||
|
||||
void _toast(String message) {
|
||||
ScaffoldMessenger.of(context)
|
||||
..clearSnackBars()
|
||||
..showSnackBar(SnackBar(
|
||||
content: Text(message),
|
||||
duration: const Duration(seconds: 2),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFF05070A),
|
||||
body: SafeArea(
|
||||
child: Stack(
|
||||
child: Column(
|
||||
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(),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 0),
|
||||
child: Column(
|
||||
children: [
|
||||
ValueListenableBuilder<HudState>(
|
||||
valueListenable: _game.hud,
|
||||
builder: (context, hud, _) => Hud(hud: hud),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
AnimatedBuilder(
|
||||
animation: _session,
|
||||
builder: (context, _) => StatusBar(session: _session),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
top: 8,
|
||||
left: 12,
|
||||
right: 12,
|
||||
child: ValueListenableBuilder<HudState>(
|
||||
valueListenable: _game.hud,
|
||||
builder: (context, hud, _) => _Hud(hud: hud),
|
||||
// Play area: gestures only affect the game, never the controls.
|
||||
Expanded(
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned.fill(child: GameWidget(key: ValueKey(_game), game: _game)),
|
||||
Positioned.fill(
|
||||
child: GestureDetector(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanStart: (d) => _game.beginAim(d.localPosition),
|
||||
onPanUpdate: (d) => _game.updateAim(d.localPosition),
|
||||
onPanEnd: (_) => _game.releaseAim(),
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
left: 16,
|
||||
right: 16,
|
||||
bottom: 8,
|
||||
child: ValueListenableBuilder<HudState>(
|
||||
valueListenable: _game.hud,
|
||||
builder: (context, hud, _) => hud.isFinished
|
||||
? GameOver(hud: hud, onRestart: _restart)
|
||||
: HintBubble(hud: hud),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Positioned(
|
||||
bottom: 16,
|
||||
left: 16,
|
||||
right: 16,
|
||||
child: ValueListenableBuilder<HudState>(
|
||||
valueListenable: _game.hud,
|
||||
builder: (context, hud, _) => hud.isFinished
|
||||
? _GameOver(hud: hud, onRestart: _restart)
|
||||
: _Hint(hud: hud),
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
|
||||
child: AnimatedBuilder(
|
||||
animation: _session,
|
||||
builder: (context, _) => Controls(
|
||||
session: _session,
|
||||
onOnline: _startOnline,
|
||||
onReplay: _playReplay,
|
||||
onFlush: _flushQueue,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
@@ -80,138 +202,3 @@ class _MatchScreenState extends State<MatchScreen> {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Hud extends StatelessWidget {
|
||||
const _Hud({required this.hud});
|
||||
final HudState hud;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
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: [
|
||||
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'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,6 +66,14 @@ class IronArcGame extends FlameGame {
|
||||
/// Optional override, used by golden tests to run without the native library.
|
||||
final MatchSource Function()? matchFactory;
|
||||
|
||||
/// Called once a shot has been resolved locally.
|
||||
void Function(int expectHash, Map<String, Object?> command,
|
||||
int localHashAfter)? onShotResolved;
|
||||
|
||||
int? _shotExpectHash;
|
||||
Map<String, Object?>? _shotCommand;
|
||||
bool _wasFlying = false;
|
||||
|
||||
late final MatchSource _match;
|
||||
final ValueNotifier<HudState> hud = ValueNotifier<HudState>(
|
||||
const HudState(
|
||||
@@ -108,7 +116,9 @@ class IronArcGame extends FlameGame {
|
||||
@override
|
||||
void update(double dt) {
|
||||
super.update(dt);
|
||||
if (_match.isFlying) {
|
||||
// A playback handle must keep ticking even while aiming, otherwise the
|
||||
// recorded commands (which are bound to ticks) never become due.
|
||||
if (_match.isFlying || _match.isPlayback) {
|
||||
_accumulator += dt;
|
||||
const step = 1 / 60;
|
||||
var steps = 0;
|
||||
@@ -129,6 +139,19 @@ class IronArcGame extends FlameGame {
|
||||
if (_impactFlash > 0) {
|
||||
_impactFlash = math.max(0, _impactFlash - dt * 1.8);
|
||||
}
|
||||
|
||||
// Shot resolved: hand the command and both hashes to the sync layer.
|
||||
final flying = _match.isFlying;
|
||||
if (_wasFlying && !flying) {
|
||||
final expect = _shotExpectHash;
|
||||
final command = _shotCommand;
|
||||
if (expect != null && command != null) {
|
||||
onShotResolved?.call(expect, command, _match.stateHash());
|
||||
_shotExpectHash = null;
|
||||
_shotCommand = null;
|
||||
}
|
||||
}
|
||||
_wasFlying = flying;
|
||||
_updateCamera(dt);
|
||||
}
|
||||
|
||||
@@ -169,7 +192,16 @@ class IronArcGame extends FlameGame {
|
||||
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);
|
||||
final before = _match.stateHash();
|
||||
if (_match.fire(angleMdeg: angleMdeg, powerQ16: powerQ16) == 0) {
|
||||
_shotExpectHash = before;
|
||||
_shotCommand = {
|
||||
'kind': 'fire',
|
||||
'angle': angleMdeg,
|
||||
'power': powerQ16,
|
||||
'w': 1,
|
||||
};
|
||||
}
|
||||
_pushHud();
|
||||
}
|
||||
|
||||
@@ -410,6 +442,14 @@ class IronArcGame extends FlameGame {
|
||||
);
|
||||
}
|
||||
|
||||
/// Replay JSON of everything played so far.
|
||||
String replayJson() => _match.replayJson();
|
||||
|
||||
/// Local state hash (compare with the server).
|
||||
int stateHash() => _match.stateHash();
|
||||
|
||||
bool get isPlayback => _match.isPlayback;
|
||||
|
||||
@override
|
||||
void onRemove() {
|
||||
_match.dispose();
|
||||
|
||||
@@ -44,5 +44,15 @@ abstract class MatchSource {
|
||||
int fire({required int angleMdeg, required int powerQ16, int weapon});
|
||||
int endTurn();
|
||||
int tick(int ticks);
|
||||
|
||||
/// Current state hash (FNV chain over the whole state).
|
||||
int stateHash();
|
||||
|
||||
/// Replay JSON (ReplayV1) of the match played so far.
|
||||
String replayJson();
|
||||
|
||||
/// True when the handle plays back a recording.
|
||||
bool get isPlayback;
|
||||
|
||||
void dispose();
|
||||
}
|
||||
|
||||
@@ -54,12 +54,44 @@ typedef _ProjectileDart = int Function(Pointer<Void>, Pointer<Int32>);
|
||||
typedef _ImpactC = Uint32 Function(Pointer<Void>, Pointer<Int32>);
|
||||
typedef _ImpactDart = int Function(Pointer<Void>, Pointer<Int32>);
|
||||
|
||||
typedef _StateHashC = Uint64 Function(Pointer<Void>);
|
||||
typedef _StateHashDart = int Function(Pointer<Void>);
|
||||
|
||||
typedef _ReplayJsonC = Pointer<Utf8> Function(Pointer<Void>);
|
||||
typedef _ReplayJsonDart = Pointer<Utf8> Function(Pointer<Void>);
|
||||
|
||||
typedef _StringFreeC = Void Function(Pointer<Utf8>);
|
||||
typedef _StringFreeDart = void Function(Pointer<Utf8>);
|
||||
|
||||
typedef _PlaybackC = Pointer<Void> Function(Pointer<Utf8>);
|
||||
typedef _PlaybackDart = Pointer<Void> Function(Pointer<Utf8>);
|
||||
|
||||
typedef _IsPlaybackC = Int32 Function(Pointer<Void>);
|
||||
typedef _IsPlaybackDart = int Function(Pointer<Void>);
|
||||
|
||||
/// Thin typed wrapper around the Rust match handle.
|
||||
///
|
||||
/// The handle owns the simulation; Dart only pulls snapshots for rendering.
|
||||
class NativeMatch extends MatchSource {
|
||||
NativeMatch(int seed) : _handle = _newMatch(seed);
|
||||
|
||||
/// Creates a handle that replays a recorded match (see [replayJson]).
|
||||
NativeMatch.playback(String replayJson)
|
||||
: _handle = _createPlayback(replayJson) {
|
||||
if (_handle.address == 0) {
|
||||
throw StateError('replay rejected (content or sim version mismatch)');
|
||||
}
|
||||
}
|
||||
|
||||
static Pointer<Void> _createPlayback(String json) {
|
||||
final encoded = json.toNativeUtf8();
|
||||
try {
|
||||
return _newPlayback(encoded);
|
||||
} finally {
|
||||
calloc.free(encoded);
|
||||
}
|
||||
}
|
||||
|
||||
final Pointer<Void> _handle;
|
||||
bool _disposed = false;
|
||||
|
||||
@@ -102,6 +134,16 @@ class NativeMatch extends MatchSource {
|
||||
_lib.lookupFunction<_ProjectileC, _ProjectileDart>('iron_arc_projectile');
|
||||
static final _ImpactDart _lastImpact =
|
||||
_lib.lookupFunction<_ImpactC, _ImpactDart>('iron_arc_last_impact');
|
||||
static final _StateHashDart _stateHash =
|
||||
_lib.lookupFunction<_StateHashC, _StateHashDart>('iron_arc_state_hash');
|
||||
static final _ReplayJsonDart _replayJson =
|
||||
_lib.lookupFunction<_ReplayJsonC, _ReplayJsonDart>('iron_arc_replay_json');
|
||||
static final _StringFreeDart _stringFree =
|
||||
_lib.lookupFunction<_StringFreeC, _StringFreeDart>('iron_arc_string_free');
|
||||
static final _PlaybackDart _newPlayback = _lib
|
||||
.lookupFunction<_PlaybackC, _PlaybackDart>('iron_arc_new_match_playback');
|
||||
static final _IsPlaybackDart _isPlayback =
|
||||
_lib.lookupFunction<_IsPlaybackC, _IsPlaybackDart>('iron_arc_is_playback');
|
||||
|
||||
/// Phase: 0 aiming, 1 flying, 2 finished.
|
||||
@override
|
||||
@@ -176,6 +218,26 @@ class NativeMatch extends MatchSource {
|
||||
}
|
||||
}
|
||||
|
||||
/// Current state hash (desync detection against the server).
|
||||
@override
|
||||
int stateHash() => BigInt.from(_stateHash(_handle)).toSigned(64).toInt();
|
||||
|
||||
/// Serialised replay (ReplayV1 JSON) of everything played so far.
|
||||
@override
|
||||
String replayJson() {
|
||||
final ptr = _replayJson(_handle);
|
||||
if (ptr.address == 0) return '';
|
||||
try {
|
||||
return ptr.toDartString();
|
||||
} finally {
|
||||
_stringFree(ptr);
|
||||
}
|
||||
}
|
||||
|
||||
/// True when this handle plays back a recorded match.
|
||||
@override
|
||||
bool get isPlayback => _isPlayback(_handle) == 1;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_disposed) return;
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
/// Error returned by the referee service.
|
||||
class ApiException implements Exception {
|
||||
ApiException(this.statusCode, this.code, this.message);
|
||||
|
||||
final int statusCode;
|
||||
final String code;
|
||||
final String message;
|
||||
|
||||
@override
|
||||
String toString() => 'ApiException($statusCode, $code): $message';
|
||||
}
|
||||
|
||||
/// Result of `POST /v1/matches`.
|
||||
class MatchInfo {
|
||||
const MatchInfo({
|
||||
required this.matchId,
|
||||
required this.seed,
|
||||
required this.turn,
|
||||
required this.stateHash,
|
||||
});
|
||||
|
||||
final String matchId;
|
||||
final int seed;
|
||||
final int turn;
|
||||
final int stateHash;
|
||||
}
|
||||
|
||||
/// Result of `POST /v1/matches/{id}/turn`.
|
||||
class TurnResult {
|
||||
const TurnResult({
|
||||
required this.turn,
|
||||
required this.current,
|
||||
required this.stateHash,
|
||||
required this.impacts,
|
||||
});
|
||||
|
||||
final int turn;
|
||||
final int current;
|
||||
final int stateHash;
|
||||
final int impacts;
|
||||
}
|
||||
|
||||
/// Result of `POST /v1/matches/{id}/validate`.
|
||||
class ValidateResult {
|
||||
const ValidateResult({
|
||||
required this.finalHash,
|
||||
required this.scrap,
|
||||
required this.xp,
|
||||
});
|
||||
|
||||
final int finalHash;
|
||||
final int scrap;
|
||||
final int xp;
|
||||
}
|
||||
|
||||
/// Thin client for the replay referee (`crates/server`).
|
||||
class ApiClient {
|
||||
ApiClient({required this.baseUrl, http.Client? client})
|
||||
: _http = client ?? http.Client();
|
||||
|
||||
final String baseUrl;
|
||||
final http.Client _http;
|
||||
|
||||
Uri _uri(String path) => Uri.parse('$baseUrl$path');
|
||||
|
||||
Future<Map<String, dynamic>> _decode(http.Response response) async {
|
||||
final body = response.body.isEmpty
|
||||
? <String, dynamic>{}
|
||||
: jsonDecode(response.body) as Map<String, dynamic>;
|
||||
if (response.statusCode >= 400) {
|
||||
final error = (body['error'] as Map<String, dynamic>?) ?? const {};
|
||||
throw ApiException(
|
||||
response.statusCode,
|
||||
error['code'] as String? ?? 'unknown',
|
||||
error['message'] as String? ?? response.body,
|
||||
);
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
/// Public health probe.
|
||||
Future<Map<String, dynamic>> health() async {
|
||||
final response = await _http.get(_uri('/v1/health'));
|
||||
return _decode(response);
|
||||
}
|
||||
|
||||
/// Exchanges a device id for a bearer token.
|
||||
Future<String> authenticate(String deviceId) async {
|
||||
final response = await _http.post(
|
||||
_uri('/v1/auth/device'),
|
||||
headers: const {'content-type': 'application/json'},
|
||||
body: jsonEncode({'device_id': deviceId}),
|
||||
);
|
||||
final body = await _decode(response);
|
||||
return body['token'] as String;
|
||||
}
|
||||
|
||||
/// Creates a server-authoritative match.
|
||||
Future<MatchInfo> createMatch({
|
||||
required String token,
|
||||
required String mode,
|
||||
required String contentHash,
|
||||
required String simVersion,
|
||||
required List<List<int>> loadouts,
|
||||
}) async {
|
||||
final response = await _http.post(
|
||||
_uri('/v1/matches'),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'authorization': 'Bearer $token',
|
||||
},
|
||||
body: jsonEncode({
|
||||
'mode': mode,
|
||||
'content_hash': contentHash,
|
||||
'sim_version': simVersion,
|
||||
'players': [
|
||||
{'tank': 'vanguard', 'loadout': loadouts[0]},
|
||||
{'tank': 'longshot', 'loadout': loadouts[1]},
|
||||
],
|
||||
}),
|
||||
);
|
||||
final body = await _decode(response);
|
||||
return MatchInfo(
|
||||
matchId: body['match_id'] as String,
|
||||
seed: (body['seed'] as num).toInt(),
|
||||
turn: (body['turn'] as num).toInt(),
|
||||
stateHash: _u64(body['state_hash']),
|
||||
);
|
||||
}
|
||||
|
||||
/// Submits one shot and lets the server resolve it.
|
||||
Future<TurnResult> submitTurn({
|
||||
required String token,
|
||||
required String matchId,
|
||||
required int expectHash,
|
||||
required Map<String, Object?> command,
|
||||
}) async {
|
||||
final response = await _http.post(
|
||||
_uri('/v1/matches/$matchId/turn'),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'authorization': 'Bearer $token',
|
||||
},
|
||||
body: jsonEncode({'expect_hash': _hex64(expectHash), 'command': command}),
|
||||
);
|
||||
final body = await _decode(response);
|
||||
return TurnResult(
|
||||
turn: (body['turn'] as num).toInt(),
|
||||
current: (body['current'] as num).toInt(),
|
||||
stateHash: _u64(body['state_hash']),
|
||||
impacts: (body['impacts'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
/// Submits a replay for validation (offline play, anti-cheat).
|
||||
Future<ValidateResult> validate({
|
||||
required String token,
|
||||
required String replayJson,
|
||||
String? matchId,
|
||||
}) async {
|
||||
final response = await _http.post(
|
||||
_uri('/v1/matches/${matchId ?? 'offline'}/validate'),
|
||||
headers: {
|
||||
'content-type': 'application/json',
|
||||
'authorization': 'Bearer $token',
|
||||
},
|
||||
body: jsonEncode({'match_id': matchId, 'replay': jsonDecode(replayJson)}),
|
||||
);
|
||||
final body = await _decode(response);
|
||||
final rewards = (body['rewards'] as Map<String, dynamic>?) ?? const {};
|
||||
return ValidateResult(
|
||||
finalHash: _u64(body['final_hash']),
|
||||
scrap: (rewards['scrap'] as num?)?.toInt() ?? 0,
|
||||
xp: (rewards['xp'] as num?)?.toInt() ?? 0,
|
||||
);
|
||||
}
|
||||
|
||||
void close() => _http.close();
|
||||
}
|
||||
|
||||
/// Hashes travel as fixed-width hex strings: JSON numbers lose precision above
|
||||
/// 2^53, and u64 hashes routinely exceed that.
|
||||
int _u64(Object? value) {
|
||||
if (value is String) return BigInt.parse(value, radix: 16).toSigned(64).toInt();
|
||||
if (value is int) return value.toUnsigned(64);
|
||||
if (value is num) return value.toInt().toUnsigned(64);
|
||||
return 0;
|
||||
}
|
||||
|
||||
String _hex64(int value) =>
|
||||
BigInt.from(value).toUnsigned(64).toRadixString(16).padLeft(16, '0');
|
||||
@@ -0,0 +1,141 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
import 'offline_queue.dart';
|
||||
|
||||
/// Connection state shown in the HUD.
|
||||
enum SyncStatus { offline, connecting, online, desync, error }
|
||||
|
||||
/// Keeps a match in sync with the referee service.
|
||||
///
|
||||
/// Online: every shot is submitted with the pre-shot state hash; the server
|
||||
/// resolves it and returns its own hash. A mismatch means the client and server
|
||||
/// disagree (desync) and ranked play stops immediately.
|
||||
/// Offline: replays are queued and validated later, rewards only after a
|
||||
/// `valid: true` verdict.
|
||||
class MatchSession extends ChangeNotifier {
|
||||
MatchSession({
|
||||
required this.client,
|
||||
required this.queue,
|
||||
required this.deviceId,
|
||||
});
|
||||
|
||||
final ApiClient client;
|
||||
final OfflineQueue queue;
|
||||
String deviceId;
|
||||
|
||||
SyncStatus status = SyncStatus.offline;
|
||||
String? matchId;
|
||||
int? seed;
|
||||
String? lastError;
|
||||
int queued = 0;
|
||||
|
||||
String? _token;
|
||||
|
||||
String get statusLabel => switch (status) {
|
||||
SyncStatus.offline => 'Offline',
|
||||
SyncStatus.connecting => 'Verbinde…',
|
||||
SyncStatus.online => 'Online · ${matchId ?? '-'}',
|
||||
SyncStatus.desync => 'DESYNC – Ranked gestoppt',
|
||||
SyncStatus.error => 'Fehler: ${lastError ?? '?'}',
|
||||
};
|
||||
|
||||
Future<void> _ensureToken() async {
|
||||
_token ??= await client.authenticate(deviceId);
|
||||
}
|
||||
|
||||
/// Creates a server-authoritative match and returns its seed.
|
||||
Future<int?> startOnlineMatch() async {
|
||||
status = SyncStatus.connecting;
|
||||
notifyListeners();
|
||||
try {
|
||||
await _ensureToken();
|
||||
final health = await client.health();
|
||||
final info = await client.createMatch(
|
||||
token: _token!,
|
||||
mode: 'ranked',
|
||||
contentHash: health['content_hash'] as String,
|
||||
simVersion: health['sim_version'] as String,
|
||||
loadouts: const [
|
||||
[1, 2, 5],
|
||||
[1, 3, 4],
|
||||
],
|
||||
);
|
||||
matchId = info.matchId;
|
||||
seed = info.seed;
|
||||
status = SyncStatus.online;
|
||||
lastError = null;
|
||||
notifyListeners();
|
||||
return info.seed;
|
||||
} catch (e) {
|
||||
status = SyncStatus.error;
|
||||
lastError = e.toString();
|
||||
debugPrint('iron_arc: online start failed: $e');
|
||||
notifyListeners();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Submits one shot. Falls back to the offline queue on transport errors.
|
||||
Future<void> submitShot({
|
||||
required int expectHash,
|
||||
required Map<String, Object?> command,
|
||||
required int localHashAfter,
|
||||
required String replayJson,
|
||||
}) async {
|
||||
if (status != SyncStatus.online || matchId == null) {
|
||||
await queue.add(replayJson);
|
||||
queued = await queue.size();
|
||||
notifyListeners();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
final result = await client.submitTurn(
|
||||
token: _token!,
|
||||
matchId: matchId!,
|
||||
expectHash: expectHash,
|
||||
command: command,
|
||||
);
|
||||
if (result.stateHash != localHashAfter) {
|
||||
status = SyncStatus.desync;
|
||||
lastError = 'server ${result.stateHash} != local $localHashAfter';
|
||||
notifyListeners();
|
||||
}
|
||||
} on ApiException catch (e) {
|
||||
if (e.statusCode == 409 && e.code == 'state_conflict') {
|
||||
status = SyncStatus.desync;
|
||||
lastError = e.message;
|
||||
} else {
|
||||
await queue.add(replayJson);
|
||||
queued = await queue.size();
|
||||
}
|
||||
notifyListeners();
|
||||
} catch (e) {
|
||||
await queue.add(replayJson);
|
||||
queued = await queue.size();
|
||||
lastError = e.toString();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates everything that was played offline.
|
||||
/// Queues a finished offline match for later validation.
|
||||
Future<void> enqueueReplay(String replayJson) async {
|
||||
await queue.add(replayJson);
|
||||
queued = await queue.size();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<int> flushQueue() async {
|
||||
await _ensureToken();
|
||||
final validated = await queue.flush(client, _token!);
|
||||
queued = await queue.size();
|
||||
notifyListeners();
|
||||
return validated;
|
||||
}
|
||||
|
||||
Future<void> refreshQueueSize() async {
|
||||
queued = await queue.size();
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
import 'api_client.dart';
|
||||
|
||||
/// Durable queue of replays that still need server validation.
|
||||
///
|
||||
/// Rewards are only granted after `valid: true`, so offline matches are played
|
||||
/// locally and submitted later ("pending" in the UI).
|
||||
class OfflineQueue {
|
||||
static const _key = 'iron_arc.pending_replays';
|
||||
|
||||
Future<List<String>> pending() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getStringList(_key) ?? const [];
|
||||
}
|
||||
|
||||
Future<int> size() async => (await pending()).length;
|
||||
|
||||
Future<void> add(String replayJson) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final items = prefs.getStringList(_key) ?? <String>[];
|
||||
items.add(replayJson);
|
||||
await prefs.setStringList(_key, items);
|
||||
}
|
||||
|
||||
/// Tries to validate every queued replay.
|
||||
///
|
||||
/// Rejected replays are dropped (no rewards), transport failures are kept.
|
||||
Future<int> flush(ApiClient client, String token) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final items = prefs.getStringList(_key) ?? <String>[];
|
||||
if (items.isEmpty) return 0;
|
||||
|
||||
final remaining = <String>[];
|
||||
var validated = 0;
|
||||
for (final replay in items) {
|
||||
try {
|
||||
await client.validate(token: token, replayJson: replay);
|
||||
validated++;
|
||||
} on ApiException catch (e) {
|
||||
if (e.statusCode >= 400 && e.statusCode < 500) continue;
|
||||
remaining.add(replay);
|
||||
} catch (_) {
|
||||
remaining.add(replay);
|
||||
}
|
||||
}
|
||||
await prefs.setStringList(_key, remaining);
|
||||
return validated;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../game/iron_arc_game.dart';
|
||||
import '../net/match_session.dart';
|
||||
|
||||
/// Score pills, turn counter and wind indicator.
|
||||
class Hud extends StatelessWidget {
|
||||
const Hud({super.key, required this.hud});
|
||||
|
||||
final HudState hud;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
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,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Connection state and pending-replay counter.
|
||||
class StatusBar extends StatelessWidget {
|
||||
const StatusBar({super.key, required this.session});
|
||||
|
||||
final MatchSession session;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final (color, icon) = switch (session.status) {
|
||||
SyncStatus.online => (const Color(0xFF66BB6A), Icons.cloud_done),
|
||||
SyncStatus.connecting => (const Color(0xFFFFC107), Icons.cloud_sync),
|
||||
SyncStatus.desync => (const Color(0xFFE53935), Icons.warning_amber),
|
||||
SyncStatus.error => (const Color(0xFFE53935), Icons.cloud_off),
|
||||
SyncStatus.offline => (const Color(0xFF90A4AE), Icons.cloud_off),
|
||||
};
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(icon, size: 14, color: color),
|
||||
const SizedBox(width: 6),
|
||||
Flexible(
|
||||
child: Text(
|
||||
session.statusLabel,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(fontSize: 11, color: color),
|
||||
),
|
||||
),
|
||||
if (session.queued > 0) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text('· ${session.queued} pending',
|
||||
style: const TextStyle(fontSize: 11, color: Color(0xFFFFC107))),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Online / Replay / Upload actions.
|
||||
class Controls extends StatelessWidget {
|
||||
const Controls({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.onOnline,
|
||||
required this.onReplay,
|
||||
required this.onFlush,
|
||||
});
|
||||
|
||||
final MatchSession session;
|
||||
final VoidCallback onOnline;
|
||||
final VoidCallback onReplay;
|
||||
final VoidCallback onFlush;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: [
|
||||
_Action(icon: Icons.wifi_tethering, label: 'Online', onTap: onOnline),
|
||||
_Action(icon: Icons.replay, label: 'Replay', onTap: onReplay),
|
||||
_Action(
|
||||
icon: Icons.cloud_upload,
|
||||
label: session.queued > 0 ? 'Senden (${session.queued})' : 'Senden',
|
||||
onTap: onFlush,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Action extends StatelessWidget {
|
||||
const _Action({required this.icon, required this.label, required this.onTap});
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Material(
|
||||
color: const Color(0xCC0B1220),
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
child: InkWell(
|
||||
borderRadius: BorderRadius.circular(18),
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 12),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 18),
|
||||
const SizedBox(width: 6),
|
||||
Text(label, style: const TextStyle(fontSize: 13)),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
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: [
|
||||
Text(label,
|
||||
style: TextStyle(
|
||||
fontSize: 11, color: color, fontWeight: FontWeight.w800)),
|
||||
Text(value, style: const TextStyle(fontSize: 15)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Short instruction or flight indicator.
|
||||
class HintBubble extends StatelessWidget {
|
||||
const HintBubble({super.key, 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)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Winner banner plus rematch button.
|
||||
class GameOver extends StatelessWidget {
|
||||
const GameOver({super.key, 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'),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
Generated
+182
-1
@@ -1,6 +1,14 @@
|
||||
# Generated by pub
|
||||
# See https://dart.dev/tools/pub/glossary#lockfile
|
||||
packages:
|
||||
args:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: args
|
||||
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
async:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -65,6 +73,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
flame:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -91,6 +107,43 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_web_plugins:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
http:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: http
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
http_parser:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http_parser
|
||||
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.1.2"
|
||||
jni:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: jni
|
||||
sha256: "6b9ca0602fef0230e83149afbe3f9f8227e94f2bbe84a1da4f14d699742f402d"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
jni_util:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: jni_util
|
||||
sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.0.0"
|
||||
leak_tracker:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -155,6 +208,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "8.0.1"
|
||||
package_config:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: package_config
|
||||
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.0"
|
||||
path:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -163,6 +224,102 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.9.1"
|
||||
path_provider_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_linux
|
||||
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.2"
|
||||
path_provider_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_platform_interface
|
||||
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.3"
|
||||
path_provider_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: path_provider_windows
|
||||
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.3.0"
|
||||
platform:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: platform
|
||||
sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.0"
|
||||
plugin_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: plugin_platform_interface
|
||||
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.8"
|
||||
shared_preferences:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: shared_preferences
|
||||
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.6"
|
||||
shared_preferences_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_android
|
||||
sha256: "593034a16e82953ca31145db6c85174286262715f9c5e6a9d8c65ffd9fcdce09"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.3"
|
||||
shared_preferences_foundation:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_foundation
|
||||
sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.5.7"
|
||||
shared_preferences_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_linux
|
||||
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.1"
|
||||
shared_preferences_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_platform_interface
|
||||
sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.2"
|
||||
shared_preferences_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_web
|
||||
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.3"
|
||||
shared_preferences_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: shared_preferences_windows
|
||||
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.1"
|
||||
sky_engine:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
@@ -216,6 +373,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.7.12"
|
||||
typed_data:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: typed_data
|
||||
sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.4.0"
|
||||
vector_math:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -232,6 +397,22 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "15.4.0"
|
||||
web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: web
|
||||
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.2"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: xdg_directories
|
||||
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
sdks:
|
||||
dart: ">=3.13.4 <4.0.0"
|
||||
flutter: ">=3.41.0"
|
||||
flutter: ">=3.44.0"
|
||||
|
||||
@@ -36,6 +36,8 @@ dependencies:
|
||||
cupertino_icons: ^1.0.8
|
||||
flame: ^1.38.2
|
||||
ffi: ^2.2.0
|
||||
http: ^1.6.0
|
||||
shared_preferences: ^2.5.6
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:http/testing.dart';
|
||||
import 'package:iron_arc/src/net/api_client.dart';
|
||||
|
||||
void main() {
|
||||
test('authenticate posts the device id and returns the token', () async {
|
||||
final api = ApiClient(
|
||||
baseUrl: 'http://test',
|
||||
client: MockClient((request) async {
|
||||
expect(request.url.path, '/v1/auth/device');
|
||||
expect(jsonDecode(request.body)['device_id'], 'dev-1');
|
||||
return http.Response(
|
||||
jsonEncode({'token': 'dev-1.sig', 'expires_in_s': 60}),
|
||||
200,
|
||||
);
|
||||
}),
|
||||
);
|
||||
expect(await api.authenticate('dev-1'), 'dev-1.sig');
|
||||
});
|
||||
|
||||
test('createMatch sends pinning fields and parses the response', () async {
|
||||
final api = ApiClient(
|
||||
baseUrl: 'http://test',
|
||||
client: MockClient((request) async {
|
||||
expect(request.url.path, '/v1/matches');
|
||||
expect(request.headers['authorization'], 'Bearer tok');
|
||||
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||
expect(body['content_hash'], 'fnv1a:abc');
|
||||
expect(body['sim_version'], '0.1.0');
|
||||
expect((body['players'] as List).length, 2);
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'match_id': 'm_1',
|
||||
'seed': 42,
|
||||
'turn': 1,
|
||||
'state_hash': 'ffffffffffffffff',
|
||||
}),
|
||||
201,
|
||||
);
|
||||
}),
|
||||
);
|
||||
final info = await api.createMatch(
|
||||
token: 'tok',
|
||||
mode: 'ranked',
|
||||
contentHash: 'fnv1a:abc',
|
||||
simVersion: '0.1.0',
|
||||
loadouts: const [
|
||||
[1, 2, 5],
|
||||
[1, 3, 4],
|
||||
],
|
||||
);
|
||||
expect(info.matchId, 'm_1');
|
||||
expect(info.seed, 42);
|
||||
// u64 max wraps to the signed representation, which is exactly what the
|
||||
// local state hash also returns.
|
||||
expect(info.stateHash, -1);
|
||||
});
|
||||
|
||||
test('submitTurn sends expect_hash and parses the new hash', () async {
|
||||
final api = ApiClient(
|
||||
baseUrl: 'http://test',
|
||||
client: MockClient((request) async {
|
||||
expect(request.url.path, '/v1/matches/m_1/turn');
|
||||
final body = jsonDecode(request.body) as Map<String, dynamic>;
|
||||
expect(body['expect_hash'], '0000000000000007');
|
||||
expect((body['command'] as Map)['kind'], 'fire');
|
||||
return http.Response(
|
||||
jsonEncode({
|
||||
'accepted': true,
|
||||
'turn': 2,
|
||||
'current': 1,
|
||||
'state_hash': '0000000000000063',
|
||||
'impacts': 1,
|
||||
}),
|
||||
200,
|
||||
);
|
||||
}),
|
||||
);
|
||||
final result = await api.submitTurn(
|
||||
token: 'tok',
|
||||
matchId: 'm_1',
|
||||
expectHash: 7,
|
||||
command: const {'kind': 'fire', 'angle': 45000, 'power': 65536, 'w': 1},
|
||||
);
|
||||
expect(result.turn, 2);
|
||||
expect(result.stateHash, 99);
|
||||
expect(result.impacts, 1);
|
||||
});
|
||||
|
||||
test('error responses raise ApiException with the server code', () async {
|
||||
final api = ApiClient(
|
||||
baseUrl: 'http://test',
|
||||
client: MockClient((_) async => http.Response(
|
||||
jsonEncode({
|
||||
'error': {'code': 'rate_limited', 'message': 'too many'}
|
||||
}),
|
||||
429,
|
||||
)),
|
||||
);
|
||||
await expectLater(
|
||||
api.health(),
|
||||
throwsA(isA<ApiException>()
|
||||
.having((e) => e.statusCode, 'status', 429)
|
||||
.having((e) => e.code, 'code', 'rate_limited')),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -120,6 +120,20 @@ class FakeMatch extends MatchSource {
|
||||
@override
|
||||
int tick(int ticks) => 0;
|
||||
|
||||
@override
|
||||
int stateHash() => _hash;
|
||||
|
||||
final int _hash = 1;
|
||||
|
||||
@override
|
||||
String replayJson() =>
|
||||
'{"v":1,"sim_version":"0.1.0","content_hash":"fnv1a:test","seed":1,'
|
||||
'"mode":"hotseat","players":[],"commands":[],"final_hash":1,'
|
||||
'"duration_ticks":0}';
|
||||
|
||||
@override
|
||||
bool get isPlayback => false;
|
||||
|
||||
@override
|
||||
void dispose() {}
|
||||
}
|
||||
|
||||
@@ -10,5 +10,6 @@ description = "CDylib bridge between Flutter and the deterministic simulation"
|
||||
crate-type = ["cdylib", "staticlib"]
|
||||
|
||||
[dependencies]
|
||||
sim.workspace = true
|
||||
sim = { workspace = true, features = ["serde"] }
|
||||
content.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -64,6 +64,50 @@ mod tests {
|
||||
assert_eq!(iron_arc_sim_version_code(), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replay_export_reproduces_state() {
|
||||
unsafe {
|
||||
let handle = match_api::iron_arc_new_match(77);
|
||||
assert_eq!(match_api::iron_arc_fire(handle, 45_000, 65_536, 1), 0);
|
||||
match_api::iron_arc_tick(handle, 400);
|
||||
let hash = match_api::iron_arc_state_hash(handle);
|
||||
|
||||
let json_ptr = match_api::iron_arc_replay_json(handle);
|
||||
assert!(!json_ptr.is_null(), "replay json must be produced");
|
||||
let json = std::ffi::CStr::from_ptr(json_ptr)
|
||||
.to_str()
|
||||
.expect("utf8")
|
||||
.to_string();
|
||||
match_api::iron_arc_string_free(json_ptr);
|
||||
assert!(json.contains(r#""commands""#));
|
||||
|
||||
let c_json = std::ffi::CString::new(json).expect("no nul bytes");
|
||||
let playback = match_api::iron_arc_new_match_playback(c_json.as_ptr());
|
||||
assert!(!playback.is_null(), "playback handle must be created");
|
||||
assert_eq!(match_api::iron_arc_is_playback(playback), 1);
|
||||
|
||||
match_api::iron_arc_tick(playback, 400);
|
||||
assert_eq!(
|
||||
match_api::iron_arc_state_hash(playback),
|
||||
hash,
|
||||
"playback must reproduce the identical state"
|
||||
);
|
||||
|
||||
match_api::iron_arc_free_match(playback);
|
||||
match_api::iron_arc_free_match(handle);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn playback_rejects_foreign_content() {
|
||||
unsafe {
|
||||
let json = r#"{"v":1,"sim_version":"0.1.0","content_hash":"fnv1a:0000000000000000","seed":1,"mode":"hotseat","players":[{"tank":"a","loadout":[1,2,5]},{"tank":"b","loadout":[1,3,4]}],"commands":[],"final_hash":0,"duration_ticks":0}"#;
|
||||
let c_json = std::ffi::CString::new(json).unwrap();
|
||||
let handle = match_api::iron_arc_new_match_playback(c_json.as_ptr());
|
||||
assert!(handle.is_null(), "content mismatch must be rejected");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn match_handle_roundtrip() {
|
||||
unsafe {
|
||||
|
||||
+121
-1
@@ -4,7 +4,12 @@
|
||||
//! 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};
|
||||
use std::ffi::{CStr, CString};
|
||||
use std::os::raw::c_char;
|
||||
|
||||
use sim::replay::{CommandRecord, ReplayV1};
|
||||
use sim::state::{Command, Event, Phase, Sim, TankSpec};
|
||||
use sim::terrain::WORLD_W;
|
||||
|
||||
/// Opaque match handle owned by Dart.
|
||||
pub struct MatchHandle {
|
||||
@@ -12,6 +17,8 @@ pub struct MatchHandle {
|
||||
terrain_version: u32,
|
||||
impacts: u32,
|
||||
last_impact: [i32; 2],
|
||||
/// When set, due commands are applied automatically while ticking.
|
||||
playback: Option<(Vec<CommandRecord>, usize)>,
|
||||
}
|
||||
|
||||
impl MatchHandle {
|
||||
@@ -32,6 +39,7 @@ pub extern "C" fn iron_arc_new_match(seed: u64) -> *mut MatchHandle {
|
||||
terrain_version: 0,
|
||||
impacts: 0,
|
||||
last_impact: [0, 0],
|
||||
playback: None,
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -97,6 +105,20 @@ pub unsafe extern "C" fn iron_arc_tick(handle: *mut MatchHandle, ticks: u32) ->
|
||||
};
|
||||
let mut impacts = 0;
|
||||
for _ in 0..ticks {
|
||||
// In playback mode, apply every command that is due at this tick.
|
||||
if h.playback.is_some() {
|
||||
let tick = h.sim.tick;
|
||||
let mut pending: Vec<Command> = Vec::new();
|
||||
if let Some((records, index)) = h.playback.as_mut() {
|
||||
while *index < records.len() && records[*index].t <= tick {
|
||||
pending.push(records[*index].c.to_command());
|
||||
*index += 1;
|
||||
}
|
||||
}
|
||||
for command in pending {
|
||||
let _ = h.sim_mut().submit(command);
|
||||
}
|
||||
}
|
||||
for event in h.sim_mut().tick() {
|
||||
if let Event::Impact { x, y, .. } = event {
|
||||
impacts += 1;
|
||||
@@ -268,3 +290,101 @@ pub unsafe extern "C" fn iron_arc_last_impact(handle: *const MatchHandle, out: *
|
||||
}
|
||||
h.impacts
|
||||
}
|
||||
|
||||
/// Serialises the recorded match as replay JSON (`ReplayV1`).
|
||||
///
|
||||
/// The returned string must be released with [`iron_arc_string_free`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `handle` must be a valid pointer from [`iron_arc_new_match`].
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn iron_arc_replay_json(handle: *const MatchHandle) -> *mut c_char {
|
||||
let Some(h) = handle.as_ref() else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let replay = ReplayV1::capture(&h.sim, "hotseat", h.sim.tick);
|
||||
match serde_json::to_string(&replay) {
|
||||
Ok(json) => match CString::new(json) {
|
||||
Ok(value) => value.into_raw(),
|
||||
Err(_) => std::ptr::null_mut(),
|
||||
},
|
||||
Err(_) => std::ptr::null_mut(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Frees a string returned by [`iron_arc_replay_json`].
|
||||
///
|
||||
/// # Safety
|
||||
/// `value` must come from this library and must not be used afterwards.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn iron_arc_string_free(value: *mut c_char) {
|
||||
if !value.is_null() {
|
||||
drop(CString::from_raw(value));
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a handle that replays the given replay JSON automatically.
|
||||
///
|
||||
/// Returns null when the JSON is invalid, the simulation version differs or the
|
||||
/// content hash does not match the build.
|
||||
///
|
||||
/// # Safety
|
||||
/// `json` must be a valid, null-terminated UTF-8 string.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn iron_arc_new_match_playback(json: *const c_char) -> *mut MatchHandle {
|
||||
if json.is_null() {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let Ok(text) = CStr::from_ptr(json).to_str() else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
let Ok(replay) = serde_json::from_str::<ReplayV1>(text) else {
|
||||
return std::ptr::null_mut();
|
||||
};
|
||||
if replay.players.len() != 2 {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let specs = [
|
||||
TankSpec {
|
||||
x: 220,
|
||||
loadout: replay.players[0].loadout,
|
||||
},
|
||||
TankSpec {
|
||||
x: WORLD_W - 220,
|
||||
loadout: replay.players[1].loadout,
|
||||
},
|
||||
];
|
||||
let content = content::Content::builtin();
|
||||
if content.hash() != replay.content_hash {
|
||||
return std::ptr::null_mut();
|
||||
}
|
||||
let sim = Sim::new(replay.seed, specs, content);
|
||||
Box::into_raw(Box::new(MatchHandle {
|
||||
sim,
|
||||
terrain_version: 0,
|
||||
impacts: 0,
|
||||
last_impact: [0, 0],
|
||||
playback: Some((replay.commands.clone(), 0)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// True (1) when this handle replays a recorded match.
|
||||
///
|
||||
/// # Safety
|
||||
/// `handle` must be a valid pointer from this library.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn iron_arc_is_playback(handle: *const MatchHandle) -> i32 {
|
||||
match handle.as_ref() {
|
||||
Some(h) => i32::from(h.playback.is_some()),
|
||||
None => 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Current state hash (used by the client to detect desync with the server).
|
||||
///
|
||||
/// # Safety
|
||||
/// `handle` must be a valid pointer from this library.
|
||||
#[no_mangle]
|
||||
pub unsafe extern "C" fn iron_arc_state_hash(handle: *const MatchHandle) -> u64 {
|
||||
handle.as_ref().map(|h| h.sim.state_hash()).unwrap_or(0)
|
||||
}
|
||||
|
||||
+21
-11
@@ -106,6 +106,16 @@ impl AppState {
|
||||
}
|
||||
}
|
||||
|
||||
/// Encodes a 64 bit hash as fixed-width hex (JSON numbers lose precision above 2^53).
|
||||
fn hex64(value: u64) -> String {
|
||||
format!("{value:016x}")
|
||||
}
|
||||
|
||||
fn parse_hash(value: &str) -> Result<u64, ApiError> {
|
||||
u64::from_str_radix(value, 16)
|
||||
.map_err(|_| ApiError::bad_request("bad_hash", "expected 16 hex chars"))
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
@@ -288,7 +298,7 @@ struct CreateMatchResponse {
|
||||
match_id: String,
|
||||
seed: u64,
|
||||
turn: u32,
|
||||
state_hash: u64,
|
||||
state_hash: String,
|
||||
}
|
||||
|
||||
async fn create_match(
|
||||
@@ -359,7 +369,7 @@ async fn create_match(
|
||||
match_id: id,
|
||||
seed,
|
||||
turn: 1,
|
||||
state_hash,
|
||||
state_hash: hex64(state_hash),
|
||||
}),
|
||||
))
|
||||
}
|
||||
@@ -371,7 +381,7 @@ struct MatchStateBody {
|
||||
current: u8,
|
||||
phase: u8,
|
||||
hp: [i32; 2],
|
||||
state_hash: u64,
|
||||
state_hash: String,
|
||||
}
|
||||
|
||||
async fn get_match(
|
||||
@@ -392,7 +402,7 @@ async fn get_match(
|
||||
Phase::Finished => 2,
|
||||
},
|
||||
hp: [sim.tanks[0].hp, sim.tanks[1].hp],
|
||||
state_hash: sim.state_hash(),
|
||||
state_hash: hex64(sim.state_hash()),
|
||||
})
|
||||
};
|
||||
if let Some(body) = live_body {
|
||||
@@ -413,13 +423,13 @@ async fn get_match(
|
||||
current: 0,
|
||||
phase: 0,
|
||||
hp: [0, 0],
|
||||
state_hash: row.state_hash,
|
||||
state_hash: hex64(row.state_hash),
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TurnRequest {
|
||||
expect_hash: u64,
|
||||
expect_hash: String,
|
||||
command: sim::replay::CommandDto,
|
||||
}
|
||||
|
||||
@@ -428,7 +438,7 @@ struct TurnResponse {
|
||||
accepted: bool,
|
||||
turn: u32,
|
||||
current: u8,
|
||||
state_hash: u64,
|
||||
state_hash: String,
|
||||
impacts: u32,
|
||||
}
|
||||
|
||||
@@ -447,7 +457,7 @@ async fn submit_turn(
|
||||
if sim.phase != Phase::Aiming {
|
||||
return Err(ApiError::conflict("state_conflict", "no turn is open"));
|
||||
}
|
||||
if sim.state_hash() != body.expect_hash {
|
||||
if sim.state_hash() != parse_hash(&body.expect_hash)? {
|
||||
return Err(ApiError::conflict(
|
||||
"state_conflict",
|
||||
"expect_hash does not match",
|
||||
@@ -483,7 +493,7 @@ async fn submit_turn(
|
||||
accepted: true,
|
||||
turn,
|
||||
current,
|
||||
state_hash,
|
||||
state_hash: hex64(state_hash),
|
||||
impacts,
|
||||
}))
|
||||
}
|
||||
@@ -503,7 +513,7 @@ struct Rewards {
|
||||
#[derive(Serialize)]
|
||||
struct ValidateResponse {
|
||||
valid: bool,
|
||||
final_hash: u64,
|
||||
final_hash: String,
|
||||
rewards: Rewards,
|
||||
}
|
||||
|
||||
@@ -531,7 +541,7 @@ async fn validate_replay(
|
||||
})?;
|
||||
Ok(Json(ValidateResponse {
|
||||
valid: true,
|
||||
final_hash: hash,
|
||||
final_hash: hex64(hash),
|
||||
rewards: Rewards { scrap: 120, xp: 35 },
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -99,12 +99,12 @@ async fn create_match_and_play_a_turn() {
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::CREATED, "body: {body}");
|
||||
let match_id = body["match_id"].as_str().unwrap().to_string();
|
||||
let state_hash = body["state_hash"].as_u64().unwrap();
|
||||
let state_hash = body["state_hash"].as_str().unwrap().to_string();
|
||||
assert!(state.has_live_match(&match_id));
|
||||
|
||||
// Wrong expect_hash must be rejected.
|
||||
let turn = json!({
|
||||
"expect_hash": state_hash ^ 0xFF,
|
||||
"expect_hash": "ffffffffffffffff",
|
||||
"command": {"kind": "fire", "angle": 45000, "power": 65536, "w": 1}
|
||||
});
|
||||
let req = Request::builder()
|
||||
@@ -134,7 +134,7 @@ async fn create_match_and_play_a_turn() {
|
||||
assert_eq!(status, StatusCode::OK, "body: {body}");
|
||||
assert_eq!(body["accepted"], true);
|
||||
assert_eq!(body["turn"], 2);
|
||||
assert!(body["state_hash"].as_u64().unwrap() != state_hash);
|
||||
assert_ne!(body["state_hash"].as_str().unwrap(), state_hash);
|
||||
}
|
||||
|
||||
fn build_replay(seed: u64) -> ReplayV1 {
|
||||
@@ -175,7 +175,10 @@ async fn valid_replay_is_accepted() {
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {body}");
|
||||
assert_eq!(body["valid"], true);
|
||||
assert_eq!(body["final_hash"].as_u64().unwrap(), replay.final_hash);
|
||||
assert_eq!(
|
||||
body["final_hash"].as_str().unwrap(),
|
||||
format!("{:016x}", replay.final_hash)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
+11
-1
@@ -51,7 +51,7 @@ Alle Zeitangaben sind **Ticks** (60 Hz), keine Millisekunden — Zeit muss deter
|
||||
| `mode` | Enum | `ranked` \| `async` \| `daily` \| `hotseat` \| `campaign` |
|
||||
| `players[]` | Array | `tank` (ID), `loadout` (max. 3 Waffen-IDs) |
|
||||
| `commands[]` | Array | geordnet, aufsteigend in `t` |
|
||||
| `final_hash` | u64 | FNV-1a-Kette über alle Ticks (ADR 0002) |
|
||||
| `final_hash` | u64 | FNV-1a-Kette über alle Ticks (ADR 0002) – **im HTTP-Protokoll als 16-stelliger Hex-String** |
|
||||
| `duration_ticks` | u32 | Match-Länge; Cap 18000 (= 5 Minuten) |
|
||||
|
||||
**Größenbudget:** typisch 2–5 KB, hartes Limit 256 KB (Server lehnt sonst mit `too_long` ab).
|
||||
@@ -131,6 +131,16 @@ POST /v1/matches/m_8f3a…/validate
|
||||
| `422` | `{ "valid": false, "reason": "illegal_command", "at": 12 }` | Command außerhalb der Regeln |
|
||||
| `413` | `{ "valid": false, "reason": "too_long" }` | > 256 KB oder > 18000 Ticks |
|
||||
|
||||
## 4.4 Hash-Kodierung im HTTP-Protokoll
|
||||
|
||||
Alle 64-Bit-Hashes (`state_hash`, `expect_hash`, `final_hash`) werden als **16-stellige
|
||||
Hex-Strings** übertragen, z. B. `"0000000000000063"`.
|
||||
|
||||
**Grund:** JSON-Zahlen sind in JavaScript/Dart auf 2^53 exakt; u64-Hashes überschreiten das
|
||||
regelmäßig. Als Zahl übertragen würde stillschweigend Präzision verloren gehen und jeder
|
||||
Vergleich fehlschlagen. Rust parst mit `u64::from_str_radix(s, 16)`, Dart mit
|
||||
`BigInt.parse(s, radix: 16).toSigned(64)`.
|
||||
|
||||
## 5. Fehlerformat
|
||||
|
||||
```json
|
||||
|
||||
Reference in New Issue
Block a user