unity error
This commit is contained in:
@@ -96,10 +96,14 @@ public class Ball : NetworkBehaviour
|
||||
|
||||
if(collision.collider.CompareTag("wall")){
|
||||
AudioManager.instance.PlayWallHit(vol);
|
||||
if (isServer)
|
||||
ReplayRecorder.RecordHit("ball_wall", vol, this);
|
||||
RpcWallHitAudio(vol);
|
||||
}
|
||||
else if(collision.collider.CompareTag("Puck")){
|
||||
AudioManager.instance.PlayBallHit(vol);
|
||||
if (isServer)
|
||||
ReplayRecorder.RecordHit("ball_puck", vol, this);
|
||||
RpcBallHitAudio(vol);
|
||||
}
|
||||
|
||||
|
||||
@@ -161,6 +161,7 @@ public class GameManager : NetworkBehaviour
|
||||
bool _dedicatedReportedRedJoin;
|
||||
bool _dedicatedReportedBlueJoin;
|
||||
bool _dedicatedReportedGameOver;
|
||||
bool _replayRecordingStarted;
|
||||
|
||||
public static Action<Team> OnTeamChanged;
|
||||
public static bool isMoving{
|
||||
@@ -575,6 +576,14 @@ public class GameManager : NetworkBehaviour
|
||||
Logger.Log("Game started On Server");
|
||||
}
|
||||
}
|
||||
|
||||
// Host practice (tutorial) and dedicated matches both record once NetworkServer is ready.
|
||||
// Retry until StartRecording succeeds — StartHost can lag one frame behind gameStarted.
|
||||
if (gameStarted && !_replayRecordingStarted && NetworkServer.active)
|
||||
{
|
||||
if (ReplayRecorder.StartRecording(DedicatedMatchId, this))
|
||||
_replayRecordingStarted = true;
|
||||
}
|
||||
}
|
||||
|
||||
UpdateLocalTurnTimerBeep();
|
||||
@@ -736,6 +745,7 @@ public class GameManager : NetworkBehaviour
|
||||
if(hitCounter == 1){
|
||||
//kickoff goal
|
||||
Logger.Log("Kickoff goal");
|
||||
ReplayRecorder.RecordGoal(concedingTeam, redScore, blueScore, kickoff: true);
|
||||
SetKickoffTeam(concedingTeam);
|
||||
StartCoroutine(CoroutineOnGoal(team,true));//true = Kickoff goal, reset only the ball
|
||||
hitCounter = 0;
|
||||
@@ -754,16 +764,19 @@ public class GameManager : NetworkBehaviour
|
||||
Logger.Log($"Red goal scored, red score is now {redScore}");
|
||||
}
|
||||
|
||||
ReplayRecorder.RecordGoal(concedingTeam, redScore, blueScore, kickoff: false);
|
||||
SetKickoffTeam(concedingTeam);
|
||||
|
||||
|
||||
if(blueScore >= 3){
|
||||
isGameEnded = true;
|
||||
ReplayRecorder.StopAndFlush();
|
||||
ReportDedicatedMatchGameOver(Team.Blue);
|
||||
RpcGameOver(Team.Blue);
|
||||
gameOver(Team.Blue);
|
||||
}else if(redScore >= 3){
|
||||
isGameEnded = true;
|
||||
ReplayRecorder.StopAndFlush();
|
||||
ReportDedicatedMatchGameOver(Team.Red);
|
||||
RpcGameOver(Team.Red);
|
||||
gameOver(Team.Red);
|
||||
@@ -963,6 +976,7 @@ public class GameManager : NetworkBehaviour
|
||||
}
|
||||
|
||||
IEnumerator CoroutineReset(bool kickoff = false){
|
||||
ReplayRecorder.RecordReset(kickoff);
|
||||
float resetDuration = 0.5f;
|
||||
if(!kickoff){
|
||||
foreach(Puck puck in pucks){
|
||||
|
||||
@@ -25,6 +25,8 @@ public class MainMenuManager : MonoBehaviour
|
||||
public GameObject gameModesScreen;
|
||||
public GameObject dummyBuyScreen;
|
||||
public GameObject withdrawalScreen;
|
||||
public GameObject settingsScreen;
|
||||
|
||||
[Header("Play")]
|
||||
public Button btnPlay;
|
||||
public Button btnTutorial;
|
||||
@@ -338,6 +340,7 @@ public class MainMenuManager : MonoBehaviour
|
||||
gameModesScreen.SetActive(false);
|
||||
dummyBuyScreen.SetActive(false);
|
||||
withdrawalScreen.SetActive(false);
|
||||
settingsScreen.SetActive(false);
|
||||
}
|
||||
|
||||
public void ShowGameModesScreen(){
|
||||
@@ -346,6 +349,7 @@ public class MainMenuManager : MonoBehaviour
|
||||
gameModesScreen.SetActive(true);
|
||||
dummyBuyScreen.SetActive(false);
|
||||
withdrawalScreen.SetActive(false);
|
||||
settingsScreen.SetActive(false);
|
||||
}
|
||||
|
||||
public void ShowDummyBuyScreen(){
|
||||
@@ -354,6 +358,7 @@ public class MainMenuManager : MonoBehaviour
|
||||
gameModesScreen.SetActive(false);
|
||||
dummyBuyScreen.SetActive(true);
|
||||
withdrawalScreen.SetActive(false);
|
||||
settingsScreen.SetActive(false);
|
||||
}
|
||||
|
||||
public void ShowWithdrawalScreen(){
|
||||
@@ -362,7 +367,17 @@ public class MainMenuManager : MonoBehaviour
|
||||
gameModesScreen.SetActive(false);
|
||||
dummyBuyScreen.SetActive(false);
|
||||
withdrawalScreen.SetActive(true);
|
||||
settingsScreen.SetActive(false);
|
||||
UpdateWithdrawalStatus();
|
||||
}
|
||||
|
||||
public void ShowSettingsScreen(){
|
||||
statsPanel.SetActive(false);
|
||||
mainMenuScreen.SetActive(false);
|
||||
gameModesScreen.SetActive(false);
|
||||
dummyBuyScreen.SetActive(false);
|
||||
withdrawalScreen.SetActive(false);
|
||||
settingsScreen.SetActive(true);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ public class NetManager : NetworkManager
|
||||
{
|
||||
Application.logMessageReceived -= ForwardMirrorServerLogToLogger;
|
||||
|
||||
ReplayRecorder.StopAndFlush();
|
||||
GameManager.ReportDedicatedMatchRoomClosed();
|
||||
base.OnStopServer();
|
||||
}
|
||||
|
||||
@@ -135,6 +135,7 @@ public class Puck : NetworkBehaviour
|
||||
if (AudioManager.instance != null){
|
||||
AudioManager.instance.PlayPuckHit(vol);
|
||||
if(isServer){
|
||||
ReplayRecorder.RecordHit("puck_puck", vol, this);
|
||||
RpcPuckHitAudio(vol);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 9cff4a867ddc05341bf42777b654509a
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,291 @@
|
||||
# Match Replay JSON Format
|
||||
|
||||
Guide for implementing the admin-panel replay viewer. Files are written by the Unity dedicated server (and practice host) to disk only.
|
||||
|
||||
## Where files live
|
||||
|
||||
Written next to the match log with the **same basename**, only the extension differs:
|
||||
|
||||
```
|
||||
{ApplicationDirectory}/Logs/{matchId}.txt ← match log
|
||||
{ApplicationDirectory}/Logs/{matchId}.json ← replay
|
||||
```
|
||||
|
||||
| Match type | `matchId` | Example pair |
|
||||
|------------|-----------|--------------|
|
||||
| Ranked / dedicated | Positive matchmaker id | `Logs/228.txt` + `Logs/228.json` |
|
||||
| Practice / tutorial | Negative unix timestamp | `Logs/-1769539200.txt` + `Logs/-1769539200.json` |
|
||||
|
||||
Admin panel: given a log at `Logs/{id}.txt`, load `Logs/{id}.json` beside it.
|
||||
|
||||
## Top-level object
|
||||
|
||||
```json
|
||||
{
|
||||
"version": 1,
|
||||
"matchId": 228,
|
||||
"isPractice": false,
|
||||
"fixedDeltaTime": 0.02,
|
||||
"duration": 184.32,
|
||||
"entities": [ /* ... */ ],
|
||||
"frames": [ /* ... */ ],
|
||||
"events": [ /* ... */ ]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `version` | int | Schema version. Currently `1`. |
|
||||
| `matchId` | int | Match id (positive = ranked, negative = practice). |
|
||||
| `isPractice` | bool | `true` for localhost practice / tutorial host. |
|
||||
| `fixedDeltaTime` | float | Physics step used while recording (typically `0.02` → ~50 Hz). |
|
||||
| `duration` | float | Length of the recording in seconds (`t` of last sample / end). |
|
||||
| `entities` | array | Ball + pucks. Order defines pose array indices in every frame. |
|
||||
| `frames` | array | Time-ordered pose samples (~every FixedUpdate). |
|
||||
| `events` | array | Time-ordered discrete events (hits, goals, resets). |
|
||||
|
||||
Time `t` everywhere is **seconds since recording start** (match start), not wall-clock UTC.
|
||||
|
||||
---
|
||||
|
||||
## Entities
|
||||
|
||||
```json
|
||||
{ "id": 0, "type": "ball", "team": "" }
|
||||
{ "id": 1, "type": "puck", "team": "Red" }
|
||||
{ "id": 2, "type": "puck", "team": "Blue" }
|
||||
```
|
||||
|
||||
| Field | Type | Values |
|
||||
|-------|------|--------|
|
||||
| `id` | int | Stable index `0 .. N-1`. Matches array index in each frame’s `x`/`y`/`vx`/`vy`. |
|
||||
| `type` | string | `"ball"` or `"puck"` |
|
||||
| `team` | string | `"Red"`, `"Blue"`, or `""` for ball |
|
||||
|
||||
Entity list is fixed for the whole file. **Index `i` in a frame’s pose arrays always refers to `entities[i]`.**
|
||||
|
||||
Typical order: ball first, then pucks sorted by team then spawn position.
|
||||
|
||||
---
|
||||
|
||||
## Frames (motion samples)
|
||||
|
||||
```json
|
||||
{
|
||||
"t": 12.40,
|
||||
"x": [0.0, 1.2, -0.5],
|
||||
"y": [0.1, -0.3, 2.0],
|
||||
"vx": [0.0, 3.1, -1.0],
|
||||
"vy": [0.2, 0.0, 0.5]
|
||||
}
|
||||
```
|
||||
|
||||
| Field | Type | Description |
|
||||
|-------|------|-------------|
|
||||
| `t` | float | Sample time in seconds (monotonic, increasing). |
|
||||
| `x`, `y` | float[] | World position per entity (Unity 2D world units). |
|
||||
| `vx`, `vy` | float[] | Linear velocity per entity at that sample (world units / second). |
|
||||
|
||||
- Array length always equals `entities.length`.
|
||||
- Samples are dense (~`1 / fixedDeltaTime` Hz). Do **not** treat them as render frames.
|
||||
|
||||
### Coordinate system
|
||||
|
||||
Unity 2D world space:
|
||||
|
||||
- Origin at field center
|
||||
- `+X` right, `+Y` up (as in Unity)
|
||||
- Scale matches the in-game pitch (see game `fieldSize` / art for admin canvas mapping)
|
||||
|
||||
---
|
||||
|
||||
## Events
|
||||
|
||||
```json
|
||||
{ "t": 12.4, "type": "hit", "kind": "ball_wall", "vol": 0.6, "id": 0, "team": "", "redScore": 0, "blueScore": 0, "kickoff": false }
|
||||
{ "t": 30.1, "type": "goal", "kind": "", "vol": 0, "id": -1, "team": "Blue", "redScore": 1, "blueScore": 0, "kickoff": false }
|
||||
{ "t": 32.2, "type": "reset", "kind": "", "vol": 0, "id": -1, "team": "", "redScore": 0, "blueScore": 0, "kickoff": false }
|
||||
```
|
||||
|
||||
All event objects share the same fields (Unity `JsonUtility` shape). Unused fields are empty / zero / `-1`.
|
||||
|
||||
| Field | Used by | Description |
|
||||
|-------|---------|-------------|
|
||||
| `t` | all | Event time in seconds. |
|
||||
| `type` | all | `"hit"` \| `"goal"` \| `"reset"` |
|
||||
| `kind` | `hit` | `"puck_puck"` \| `"ball_puck"` \| `"ball_wall"` |
|
||||
| `vol` | `hit` | SFX volume `0..1` (from relative impact speed). |
|
||||
| `id` | `hit` | Entity id involved (spatial cue). `-1` if unknown. |
|
||||
| `team` | `goal` | **Conceding** side / goal owner (`"Red"` or `"Blue"`). The other team scored. |
|
||||
| `redScore` | `goal` | Score after this goal. |
|
||||
| `blueScore` | `goal` | Score after this goal. |
|
||||
| `kickoff` | `goal`, `reset` | Kickoff-goal / kickoff-style reset when `true`. |
|
||||
|
||||
### Event semantics
|
||||
|
||||
| `type` | Meaning for the viewer |
|
||||
|--------|-------------------------|
|
||||
| `hit` | Play collision SFX at `vol`. Optional: flash near entity `id`. |
|
||||
| `goal` | Goal scored against `team`. Update scoreboard to `redScore`/`blueScore`. Play goal SFX. **Discontinuity** — do not interpolate motion across this time. |
|
||||
| `reset` | Pieces are lerping / teleporting back. **Discontinuity** — snap poses; do not blend across. |
|
||||
|
||||
First-to-3 wins; a completed match usually ends shortly after a goal that makes a score `3`.
|
||||
|
||||
---
|
||||
|
||||
## Playback contract (required for smooth motion)
|
||||
|
||||
Recording is FixedUpdate (~50 Hz). Snapping happens if the viewer steps sample-by-sample without blending. Follow this:
|
||||
|
||||
### 1. Drive time with wall clock
|
||||
|
||||
```text
|
||||
playbackTime += (deltaMs / 1000) * playbackSpeed
|
||||
playbackTime = clamp(playbackTime, 0, duration)
|
||||
```
|
||||
|
||||
Use `requestAnimationFrame` (or equivalent). Do **not** advance one JSON frame per rAF tick.
|
||||
|
||||
### 2. Interpolate poses between samples
|
||||
|
||||
Binary-search `frames` for neighbors where:
|
||||
|
||||
```text
|
||||
frames[i].t <= playbackTime < frames[i+1].t
|
||||
```
|
||||
|
||||
Then for each entity index `e`:
|
||||
|
||||
**Minimum (good):** linear lerp of `x`/`y`:
|
||||
|
||||
```text
|
||||
u = (playbackTime - t0) / (t1 - t0)
|
||||
x = lerp(x0[e], x1[e], u)
|
||||
y = lerp(y0[e], y1[e], u)
|
||||
```
|
||||
|
||||
**Recommended (smooth under acceleration):** cubic Hermite using velocities:
|
||||
|
||||
```text
|
||||
dt = t1 - t0
|
||||
u = (playbackTime - t0) / dt
|
||||
u2 = u*u
|
||||
u3 = u2*u
|
||||
|
||||
h00 = 2*u3 - 3*u2 + 1
|
||||
h10 = u3 - 2*u2 + u
|
||||
h01 = -2*u3 + 3*u2
|
||||
h11 = u3 - u2
|
||||
|
||||
x = h00*x0 + h10*dt*vx0 + h01*x1 + h11*dt*vx1
|
||||
y = h00*y0 + h10*dt*vy0 + h01*y1 + h11*dt*vy1
|
||||
```
|
||||
|
||||
(Same for each entity index.)
|
||||
|
||||
### 3. Snap across discontinuities
|
||||
|
||||
Treat every `goal` and `reset` event as a cut:
|
||||
|
||||
- When `playbackTime` crosses that event’s `t`, **do not** interpolate from the previous sample across the cut.
|
||||
- Seek to the frame at or immediately after `t` and snap positions.
|
||||
|
||||
Practical approach: build a sorted list of discontinuity times from events where `type === "goal" || type === "reset"`. If `t0` and `t1` straddle a discontinuity, snap to the post-cut sample instead of lerping.
|
||||
|
||||
### 4. Fire events once when crossed
|
||||
|
||||
Keep `lastEventIndex` (or last fired `t`). When `playbackTime` advances past an event’s `t`, fire it once:
|
||||
|
||||
- `hit` → SFX by `kind` / `vol`
|
||||
- `goal` → score UI + goal audio
|
||||
- `reset` → optional reset cue (usually silent)
|
||||
|
||||
On seek / scrub: reset event cursor; either skip SFX or replay only from the new time forward.
|
||||
|
||||
---
|
||||
|
||||
## Suggested viewer pipeline
|
||||
|
||||
```text
|
||||
Load JSON
|
||||
→ map entities to sprites (ball / red pucks / blue pucks)
|
||||
→ sort events by t (already ordered, but verify)
|
||||
→ each animation frame:
|
||||
advance playbackTime
|
||||
resolve poses (Hermite + discontinuity snaps)
|
||||
draw entities
|
||||
dispatch newly crossed events
|
||||
```
|
||||
|
||||
### Seeking / scrubbing
|
||||
|
||||
1. Set `playbackTime` to the scrub value.
|
||||
2. Find the nearest frame (or interpolate as above).
|
||||
3. Recompute score from the last `goal` event with `t <= playbackTime` (else `0–0`).
|
||||
4. Reset the event-fire cursor to that time so SFX don’t spam.
|
||||
|
||||
### Scoreboard without scrubbing
|
||||
|
||||
Start at `0–0`. On each `goal` event, set scores from that event’s `redScore` / `blueScore`.
|
||||
|
||||
---
|
||||
|
||||
## Minimal TypeScript types
|
||||
|
||||
```ts
|
||||
export interface ReplayFile {
|
||||
version: number;
|
||||
matchId: number;
|
||||
isPractice: boolean;
|
||||
fixedDeltaTime: number;
|
||||
duration: number;
|
||||
entities: ReplayEntity[];
|
||||
frames: ReplayFrame[];
|
||||
events: ReplayEvent[];
|
||||
}
|
||||
|
||||
export interface ReplayEntity {
|
||||
id: number;
|
||||
type: "ball" | "puck" | string;
|
||||
team: "Red" | "Blue" | "" | string;
|
||||
}
|
||||
|
||||
export interface ReplayFrame {
|
||||
t: number;
|
||||
x: number[];
|
||||
y: number[];
|
||||
vx: number[];
|
||||
vy: number[];
|
||||
}
|
||||
|
||||
export interface ReplayEvent {
|
||||
t: number;
|
||||
type: "hit" | "goal" | "reset" | string;
|
||||
kind: "puck_puck" | "ball_puck" | "ball_wall" | "" | string;
|
||||
vol: number;
|
||||
id: number; // entity id, or -1
|
||||
team: "Red" | "Blue" | "" | string; // conceding team on goal
|
||||
redScore: number;
|
||||
blueScore: number;
|
||||
kickoff: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Checklist for a correct viewer
|
||||
|
||||
- [ ] Time driven by real elapsed time × speed, not frame index
|
||||
- [ ] Poses interpolated between samples (Hermite preferred)
|
||||
- [ ] No interpolation across `goal` / `reset`
|
||||
- [ ] Entity index `i` always matches `entities[i]`
|
||||
- [ ] Hit SFX use `kind` + `vol`
|
||||
- [ ] Goal `team` means **conceding** side
|
||||
- [ ] Practice files filtered via `isPractice` or negative `matchId`
|
||||
|
||||
## Out of scope (not in the JSON)
|
||||
|
||||
- Player names / user ids (use matchmaker / match API by `matchId` for ranked games)
|
||||
- Camera / UI layout
|
||||
- Launch aim lines / turn timer
|
||||
- Network latency or client prediction
|
||||
@@ -0,0 +1,7 @@
|
||||
fileFormatVersion: 2
|
||||
guid: 8cced32e9b154814b99db72a5ae58c70
|
||||
TextScriptImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,8 @@
|
||||
fileFormatVersion: 2
|
||||
guid: a1b2c3d4e5f60718293a4b5c6d7e8f90
|
||||
folderAsset: yes
|
||||
DefaultImporter:
|
||||
externalObjects: {}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,61 @@
|
||||
using System;
|
||||
|
||||
/// <summary>
|
||||
/// Replay JSON DTOs for admin-panel playback.
|
||||
/// Playback contract:
|
||||
/// 1. Advance playbackTime with real time (scaled).
|
||||
/// 2. Binary-search frames by t; Hermite-interpolate x/y using vx/vy between neighbors.
|
||||
/// 3. On reset/goal events (discontinuities): snap to the sample at/after t — do not blend across.
|
||||
/// 4. Fire SFX on hit/goal when playbackTime crosses event t.
|
||||
/// </summary>
|
||||
[Serializable]
|
||||
public class ReplayFile
|
||||
{
|
||||
public int version = 1;
|
||||
public int matchId;
|
||||
/// <summary>True for localhost practice / tutorial host matches (no dedicated matchmaker id).</summary>
|
||||
public bool isPractice;
|
||||
public float fixedDeltaTime;
|
||||
public float duration;
|
||||
public ReplayEntity[] entities;
|
||||
public ReplayFrame[] frames;
|
||||
public ReplayEvent[] events;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class ReplayEntity
|
||||
{
|
||||
public int id;
|
||||
/// <summary>"ball" or "puck"</summary>
|
||||
public string type;
|
||||
/// <summary>"Red", "Blue", or empty for ball</summary>
|
||||
public string team;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class ReplayFrame
|
||||
{
|
||||
public float t;
|
||||
public float[] x;
|
||||
public float[] y;
|
||||
public float[] vx;
|
||||
public float[] vy;
|
||||
}
|
||||
|
||||
[Serializable]
|
||||
public class ReplayEvent
|
||||
{
|
||||
public float t;
|
||||
/// <summary>"hit", "goal", or "reset"</summary>
|
||||
public string type;
|
||||
/// <summary>For hits: "puck_puck", "ball_puck", or "ball_wall"</summary>
|
||||
public string kind;
|
||||
public float vol;
|
||||
/// <summary>Entity id for spatial cueing; -1 when N/A</summary>
|
||||
public int id = -1;
|
||||
/// <summary>For goals: conceding team ("Red"/"Blue")</summary>
|
||||
public string team;
|
||||
public int redScore;
|
||||
public int blueScore;
|
||||
public bool kickoff;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: b2c3d4e5f60718293a4b5c6d7e8f901a
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -0,0 +1,301 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using Mirror;
|
||||
using UnityEngine;
|
||||
|
||||
/// <summary>
|
||||
/// Server-only match recorder. Samples poses every FixedUpdate; flushes JSON to disk on stop.
|
||||
/// Admin playback must interpolate by time (Hermite using velocity) — never snap one FixedUpdate sample per render frame.
|
||||
/// </summary>
|
||||
public class ReplayRecorder : MonoBehaviour
|
||||
{
|
||||
public static ReplayRecorder Instance { get; private set; }
|
||||
|
||||
public static bool IsRecording => Instance != null && Instance._recording && !Instance._flushed;
|
||||
|
||||
bool _recording;
|
||||
bool _flushed;
|
||||
int _matchId;
|
||||
bool _isPractice;
|
||||
float _startFixedTime;
|
||||
float _duration;
|
||||
|
||||
readonly List<ReplayEntity> _entities = new List<ReplayEntity>();
|
||||
readonly List<Rigidbody2D> _bodies = new List<Rigidbody2D>();
|
||||
readonly Dictionary<int, int> _instanceIdToEntityId = new Dictionary<int, int>();
|
||||
readonly List<ReplayFrame> _frames = new List<ReplayFrame>();
|
||||
readonly List<ReplayEvent> _events = new List<ReplayEvent>();
|
||||
|
||||
/// <returns>True if recording started (or already recording this session).</returns>
|
||||
public static bool StartRecording(int matchId, GameManager gm)
|
||||
{
|
||||
if (!NetworkServer.active || gm == null)
|
||||
return false;
|
||||
|
||||
if (Instance == null)
|
||||
{
|
||||
var go = new GameObject("ReplayRecorder");
|
||||
DontDestroyOnLoad(go);
|
||||
Instance = go.AddComponent<ReplayRecorder>();
|
||||
}
|
||||
|
||||
Instance.Begin(matchId, gm);
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void StopAndFlush()
|
||||
{
|
||||
if (Instance != null)
|
||||
Instance.Flush();
|
||||
}
|
||||
|
||||
public static void RecordHit(string kind, float vol, Component source)
|
||||
{
|
||||
if (!IsRecording)
|
||||
return;
|
||||
Instance.AddHit(kind, vol, source);
|
||||
}
|
||||
|
||||
public static void RecordGoal(Team concedingTeam, int redScore, int blueScore, bool kickoff)
|
||||
{
|
||||
if (!IsRecording)
|
||||
return;
|
||||
Instance.AddEvent(new ReplayEvent
|
||||
{
|
||||
t = Instance.CurrentT(),
|
||||
type = "goal",
|
||||
kind = "",
|
||||
vol = 0f,
|
||||
id = -1,
|
||||
team = concedingTeam.ToString(),
|
||||
redScore = redScore,
|
||||
blueScore = blueScore,
|
||||
kickoff = kickoff
|
||||
});
|
||||
}
|
||||
|
||||
public static void RecordReset(bool kickoff)
|
||||
{
|
||||
if (!IsRecording)
|
||||
return;
|
||||
Instance.AddEvent(new ReplayEvent
|
||||
{
|
||||
t = Instance.CurrentT(),
|
||||
type = "reset",
|
||||
kind = "",
|
||||
vol = 0f,
|
||||
id = -1,
|
||||
team = "",
|
||||
redScore = 0,
|
||||
blueScore = 0,
|
||||
kickoff = kickoff
|
||||
});
|
||||
}
|
||||
|
||||
public static bool TryGetEntityId(Component source, out int entityId)
|
||||
{
|
||||
entityId = -1;
|
||||
if (Instance == null || source == null)
|
||||
return false;
|
||||
return Instance._instanceIdToEntityId.TryGetValue(source.gameObject.GetInstanceID(), out entityId);
|
||||
}
|
||||
|
||||
void Begin(int matchId, GameManager gm)
|
||||
{
|
||||
if (_recording && !_flushed)
|
||||
Flush();
|
||||
|
||||
// Practice / tutorial host uses DedicatedMatchId 0 — mint a unique id so files don't overwrite.
|
||||
_isPractice = matchId <= 0 || GameTutorialManager.tutorialModeEnabled;
|
||||
if (matchId <= 0)
|
||||
matchId = GeneratePracticeMatchId();
|
||||
|
||||
_matchId = matchId;
|
||||
_recording = true;
|
||||
_flushed = false;
|
||||
_startFixedTime = Time.fixedTime;
|
||||
_duration = 0f;
|
||||
_entities.Clear();
|
||||
_bodies.Clear();
|
||||
_instanceIdToEntityId.Clear();
|
||||
_frames.Clear();
|
||||
_events.Clear();
|
||||
|
||||
// Keep log + replay siblings: Logs/{matchId}.txt and Logs/{matchId}.json
|
||||
if (_isPractice)
|
||||
Logger.SetFileName(_matchId.ToString());
|
||||
|
||||
BuildEntities(gm);
|
||||
string mode = _isPractice ? "practice" : "match";
|
||||
Logger.Log($"ReplayRecorder started ({mode}) id {_matchId} with {_entities.Count} entities");
|
||||
}
|
||||
|
||||
/// <summary>Negative unix timestamp so practice ids never collide with positive matchmaker ids.</summary>
|
||||
static int GeneratePracticeMatchId()
|
||||
{
|
||||
long unix = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
if (unix > int.MaxValue)
|
||||
unix %= int.MaxValue;
|
||||
int id = -(int)unix;
|
||||
return id == 0 ? -1 : id;
|
||||
}
|
||||
|
||||
void BuildEntities(GameManager gm)
|
||||
{
|
||||
if (gm.ball != null)
|
||||
{
|
||||
RegisterEntity(gm.ball.gameObject, gm.ball, "ball", "");
|
||||
}
|
||||
|
||||
var sorted = new List<Puck>(gm.pucks);
|
||||
sorted.Sort((a, b) =>
|
||||
{
|
||||
int teamCmp = a.team.CompareTo(b.team);
|
||||
if (teamCmp != 0)
|
||||
return teamCmp;
|
||||
int xCmp = a.transform.position.x.CompareTo(b.transform.position.x);
|
||||
if (xCmp != 0)
|
||||
return xCmp;
|
||||
return a.transform.position.y.CompareTo(b.transform.position.y);
|
||||
});
|
||||
|
||||
foreach (Puck puck in sorted)
|
||||
{
|
||||
if (puck == null || puck.rb == null)
|
||||
continue;
|
||||
RegisterEntity(puck.gameObject, puck.rb, "puck", puck.team.ToString());
|
||||
}
|
||||
}
|
||||
|
||||
void RegisterEntity(GameObject go, Rigidbody2D rb, string type, string team)
|
||||
{
|
||||
int id = _entities.Count;
|
||||
_entities.Add(new ReplayEntity { id = id, type = type, team = team ?? "" });
|
||||
_bodies.Add(rb);
|
||||
_instanceIdToEntityId[go.GetInstanceID()] = id;
|
||||
}
|
||||
|
||||
float CurrentT() => Time.fixedTime - _startFixedTime;
|
||||
|
||||
void FixedUpdate()
|
||||
{
|
||||
if (!_recording || _flushed || !NetworkServer.active)
|
||||
return;
|
||||
|
||||
int n = _bodies.Count;
|
||||
if (n == 0)
|
||||
return;
|
||||
|
||||
var frame = new ReplayFrame
|
||||
{
|
||||
t = CurrentT(),
|
||||
x = new float[n],
|
||||
y = new float[n],
|
||||
vx = new float[n],
|
||||
vy = new float[n]
|
||||
};
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
{
|
||||
Rigidbody2D rb = _bodies[i];
|
||||
if (rb == null)
|
||||
continue;
|
||||
Vector2 pos = rb.position;
|
||||
Vector2 vel = rb.linearVelocity;
|
||||
frame.x[i] = pos.x;
|
||||
frame.y[i] = pos.y;
|
||||
frame.vx[i] = vel.x;
|
||||
frame.vy[i] = vel.y;
|
||||
}
|
||||
|
||||
_duration = frame.t;
|
||||
_frames.Add(frame);
|
||||
}
|
||||
|
||||
void AddHit(string kind, float vol, Component source)
|
||||
{
|
||||
int entityId = -1;
|
||||
if (source != null)
|
||||
_instanceIdToEntityId.TryGetValue(source.gameObject.GetInstanceID(), out entityId);
|
||||
|
||||
AddEvent(new ReplayEvent
|
||||
{
|
||||
t = CurrentT(),
|
||||
type = "hit",
|
||||
kind = kind ?? "",
|
||||
vol = vol,
|
||||
id = entityId,
|
||||
team = "",
|
||||
redScore = 0,
|
||||
blueScore = 0,
|
||||
kickoff = false
|
||||
});
|
||||
}
|
||||
|
||||
void AddEvent(ReplayEvent ev)
|
||||
{
|
||||
_events.Add(ev);
|
||||
}
|
||||
|
||||
void Flush()
|
||||
{
|
||||
if (!_recording || _flushed)
|
||||
return;
|
||||
|
||||
_flushed = true;
|
||||
_recording = false;
|
||||
_duration = Mathf.Max(_duration, CurrentT());
|
||||
|
||||
var file = new ReplayFile
|
||||
{
|
||||
version = 1,
|
||||
matchId = _matchId,
|
||||
isPractice = _isPractice,
|
||||
fixedDeltaTime = Time.fixedDeltaTime,
|
||||
duration = _duration,
|
||||
entities = _entities.ToArray(),
|
||||
frames = _frames.ToArray(),
|
||||
events = _events.ToArray()
|
||||
};
|
||||
|
||||
try
|
||||
{
|
||||
string path = ResolveReplayFilePath();
|
||||
string json = JsonUtility.ToJson(file);
|
||||
File.WriteAllText(path, json);
|
||||
Logger.Log($"ReplayRecorder wrote {path} ({_frames.Count} frames, {_events.Count} events, duration {_duration:F2}s)");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Logger.Log("ReplayRecorder flush failed: " + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Same directory and basename as the match log, extension <c>.json</c>
|
||||
/// (e.g. <c>Logs/228.txt</c> → <c>Logs/228.json</c>).
|
||||
/// </summary>
|
||||
string ResolveReplayFilePath()
|
||||
{
|
||||
string expectedName = _matchId.ToString();
|
||||
string logPath = Logger.instance != null ? Logger.instance.LogFilePath : null;
|
||||
if (!string.IsNullOrEmpty(logPath))
|
||||
{
|
||||
string logBase = Path.GetFileNameWithoutExtension(logPath);
|
||||
if (logBase == expectedName)
|
||||
return Path.ChangeExtension(logPath, ".json");
|
||||
}
|
||||
|
||||
return Path.Combine(Logger.GetLogsDirectory(), expectedName + ".json");
|
||||
}
|
||||
|
||||
void OnDestroy()
|
||||
{
|
||||
if (Instance == this)
|
||||
{
|
||||
Flush();
|
||||
Instance = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
fileFormatVersion: 2
|
||||
guid: c3d4e5f60718293a4b5c6d7e8f901a2b
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
||||
@@ -19,6 +19,7 @@ public class FrameAnimator : MonoBehaviour
|
||||
bool m_previewPlaying = false;
|
||||
#if UNITY_EDITOR
|
||||
double m_lastEditorTime = 0d;
|
||||
bool m_editorHooked;
|
||||
#endif
|
||||
Image m_img;
|
||||
Image img {
|
||||
@@ -42,19 +43,19 @@ public class FrameAnimator : MonoBehaviour
|
||||
void OnEnable()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
if (!Application.isPlaying)
|
||||
{
|
||||
m_lastEditorTime = EditorApplication.timeSinceStartup;
|
||||
EditorApplication.update -= OnEditorUpdate;
|
||||
EditorApplication.update += OnEditorUpdate;
|
||||
}
|
||||
// Never hook editor updates during play-mode enter/exit — QueuePlayerLoopUpdate
|
||||
// + isPlaying serialized true can infinite-reload Temp/__Backupscenes.
|
||||
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
|
||||
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
|
||||
TryHookEditorUpdate();
|
||||
#endif
|
||||
}
|
||||
|
||||
void OnDisable()
|
||||
{
|
||||
#if UNITY_EDITOR
|
||||
EditorApplication.update -= OnEditorUpdate;
|
||||
UnhookEditorUpdate();
|
||||
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
|
||||
#endif
|
||||
}
|
||||
void Start()
|
||||
@@ -80,24 +81,72 @@ public class FrameAnimator : MonoBehaviour
|
||||
}
|
||||
|
||||
#if UNITY_EDITOR
|
||||
void OnEditorUpdate()
|
||||
void OnPlayModeStateChanged(PlayModeStateChange state)
|
||||
{
|
||||
if (Application.isPlaying || this == null || !isActiveAndEnabled)
|
||||
if (state == PlayModeStateChange.ExitingEditMode ||
|
||||
state == PlayModeStateChange.EnteredPlayMode ||
|
||||
state == PlayModeStateChange.ExitingPlayMode)
|
||||
{
|
||||
m_previewPlaying = false;
|
||||
UnhookEditorUpdate();
|
||||
}
|
||||
else if (state == PlayModeStateChange.EnteredEditMode)
|
||||
{
|
||||
TryHookEditorUpdate();
|
||||
}
|
||||
}
|
||||
|
||||
void TryHookEditorUpdate()
|
||||
{
|
||||
if (Application.isPlaying || EditorApplication.isPlayingOrWillChangePlaymode)
|
||||
{
|
||||
UnhookEditorUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_editorHooked)
|
||||
return;
|
||||
|
||||
m_lastEditorTime = EditorApplication.timeSinceStartup;
|
||||
EditorApplication.update += OnEditorUpdate;
|
||||
m_editorHooked = true;
|
||||
}
|
||||
|
||||
void UnhookEditorUpdate()
|
||||
{
|
||||
if (!m_editorHooked)
|
||||
return;
|
||||
EditorApplication.update -= OnEditorUpdate;
|
||||
m_editorHooked = false;
|
||||
}
|
||||
|
||||
void OnEditorUpdate()
|
||||
{
|
||||
if (Application.isPlaying ||
|
||||
EditorApplication.isPlayingOrWillChangePlaymode ||
|
||||
this == null ||
|
||||
!isActiveAndEnabled)
|
||||
{
|
||||
UnhookEditorUpdate();
|
||||
return;
|
||||
}
|
||||
|
||||
// Edit-mode animation is preview-only. Ignoring serialized isPlaying prevents
|
||||
// permanent editor loops when isPlaying was left true in the scene.
|
||||
if (!m_previewPlaying)
|
||||
return;
|
||||
|
||||
double now = EditorApplication.timeSinceStartup;
|
||||
float dt = (float)(now - m_lastEditorTime);
|
||||
m_lastEditorTime = now;
|
||||
|
||||
if (dt <= 0f)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
int frameBefore = currentFrame;
|
||||
TickAnimation(dt);
|
||||
EditorApplication.QueuePlayerLoopUpdate();
|
||||
if (currentFrame != frameBefore || m_previewPlaying)
|
||||
EditorApplication.QueuePlayerLoopUpdate();
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -108,7 +157,9 @@ public class FrameAnimator : MonoBehaviour
|
||||
return;
|
||||
}
|
||||
|
||||
bool shouldAnimate = m_previewPlaying || isPlaying;
|
||||
bool shouldAnimate = Application.isPlaying
|
||||
? (m_previewPlaying || isPlaying)
|
||||
: m_previewPlaying;
|
||||
if (!shouldAnimate)
|
||||
{
|
||||
return;
|
||||
|
||||
Reference in New Issue
Block a user