Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 6 additions & 7 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,13 @@ existing libs stand ([COMPLIANCE.md](COMPLIANCE.md)).
camera out of the state, versioned structs, shared units, snapshot,
event ids, move lockstep code out to inklib-net, measure tick step and
input delay.
3. libray3: apply COMPLIANCE.md: DetMath for the 13 platform-maths sites
3. libray3: apply COMPLIANCE.md: DetMathF (copy TEMPLATE/src/Tpl.Core/DetMathF.cs)
for the 13 platform-maths sites, touch tolerance, hooks in ray3_hooks.h,
(float32 stays), TickSeconds 0.016, 1-tick input delay, world API,
snapshot, events, macOS CI, inklib-replay format.
4. Template: a float32 DetMath variant for float32 libs (spec allows it,
template only has double).
5. Template: an example of a lib-owned store (SPEC.md section 6, "Lib-owned
4. Template: an example of a lib-owned store (SPEC.md section 6, "Lib-owned
world state") once the Splatoon lib starts.
6. inklib-net and inklib-arena: spec only; start code when two libs comply.
7. Template: implement the host hooks (SPEC.md section 14) and loadout
5. inklib-net and inklib-arena: spec only; start code when two libs comply.
6. Template: implement the host hooks (SPEC.md section 14) and loadout
(section 12) as a reference, with snapshot tests. Spec only so far.
8. COMPLIANCE.md: add an sp2 (Splatoon 2) table once its repo can be read.
7. COMPLIANCE.md: add an sp2 (Splatoon 2) table once its repo can be read.
2 changes: 2 additions & 0 deletions COMPLIANCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ C API v7 only. Every ❔ needs a look in the repo.
| 6 State hash | 🟡 A hash exists for the lockstep check (what it covers ❔). | Expose it as `fc_state_hash` = FNV-1a 64 over the snapshot bytes. The hash changes, so old lockstep peers do not match new ones (API v8 anyway). |
| 6 Event ids | ❔ | `id` (same on resimulation) and `tick` on every event. |
| 6 Input quantisation | ✅ The game reads PS1 pad bytes. | Make the stick handling depend only on `round(stick * 127)` (map it onto the pad byte), so inklib-net can send 4 stick bytes. |
| 4 Touch tolerance | unknown | Add `FC_TOUCH_TOLERANCE`; check that `segment` callers slide along touching walls. |
| 12 Loadout | 🟡 Weapons per slot exist (15 VS weapons, 3 slots, `rearm`). List/equip shape unknown. | `fc_loadout_list`, `fc_equip`, `fc_equipped` in the weapons module; equipped weapons in the snapshot. |
| 14 Host hooks | unknown | Teleport, impulse, hurt (with `invulnerable_ticks`, HURT event), mount/unmount (libfc's pilot/park may map onto it), action enum, aim offset, in `fc_hooks.h`. |
| 13 Netcode out of the lib | ❔ The lockstep 1v1 code: inside libfc or in the host? | If it is inside libfc, move it out: it becomes the first piece of inklib-net (lockstep = the zero-rollback case). libfc keeps only snapshot, hash, events and replays. |
Expand Down Expand Up @@ -79,6 +80,7 @@ Read from OctoAlgo/libray3 at commit `484385e` (2026-10-31).
| 6 Event ids | ❌ No events yet. | Add events with `id` and `tick` from the start. |
| 6 Input quantisation | ❌ Stick floats are used as given. | Quantise to `round(stick * 127) / 127` in `ray3_char_input`. |
| 13 Netcode out of the lib | ✅ None. | None. |
| 4 Touch tolerance | ❌ `ICollisionWorld` says a cast that starts overlapping returns a hit at distance 0, so a PhysX host blocks sliding along touching floors and walls. | Add `RAY3_TOUCH_TOLERANCE` and the section 4 rule to the contract and to its test geometry, with slide tests. |
| 12 Loadout | unknown (power-ups exist in the game: copter, big fist, ...). | `ray3_loadout_list` / `ray3_equip` / `ray3_equipped` for the power-ups. |
| 14 Host hooks | 🟡 Built for InkArena as C API 21-26: teleport + add impulse (21) and hurt (22) merged; mount (23), HURT event (24), action (25), aim offset (26) pending merge (libray3 #34-#37). | Check the names and return values against section 14 (hurt: 1 / 0 / -1), add `invulnerable_ticks` to the state, HURT = event type 5, action values from the common core, move the hooks into `ray3_hooks.h` + `ray3_get_hooks_api()`, and put their state in the snapshot. |
| 7 Camera | ❌ Out of scope in PLAN.md. MEASURE M6 notes that turning is done by the camera's script. | Ship Rayman 3's third-person camera (`THIRD_PERSON`): research, look input, `ray3_char_camera`. This is the largest piece of new work. |
Expand Down
21 changes: 19 additions & 2 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,22 @@ material bits). The host sets what it knows; zero is plain solid ground.

The character never reports itself: the host leaves the character's own body out of every answer.

### Touch tolerance

PhysX and most engines report a shape that starts touching the probe as a start overlap. Taken
literally ("starts inside = hit at t 0"), a character could never slide along a floor or a wall it
touches. So every lib states a touch tolerance, `<P>_TOUCH_TOLERANCE` (native length units, in its
header), and the contract for `sweep` and `segment` is:

- A shape that starts within the tolerance of a surface (just apart, or overlapping by less than the
tolerance) is **touching**, not blocked.
- A touching surface blocks only when the move goes into it: `dot(move, normal) < 0`. Then the hit is
at `t` = 0 with that surface's normal. Moving along it or away from it is free.
- A shape that starts deeper than the tolerance is a real start overlap: hit at `t` = 0.
- Otherwise the first contact along the move is the hit, as usual.

The template's test collision world follows this rule and tests it (`CollisionTests`).

## 5. Determinism

**Closeness to the original is the top priority of every inklib.** The rules below serve it.
Expand Down Expand Up @@ -223,8 +239,9 @@ A lib meets this one of two ways.
variable or cast it (`(float)`), so no runtime keeps extra precision. RyuJIT computes `float` in
single precision; check other runtimes before relying on them.
- Only `+ - * /`, comparisons, `Math.Abs/Min/Max/Floor/Ceiling/Round/Truncate/Sign/Clamp` and the
lib's own `DetMath` (template: `DetMath.cs`, double; a float32 lib keeps a float32 `DetMath`, or
computes in double and rounds once to float, which is also deterministic). IEEE 754 makes
lib's own `DetMath` (template: `DetMath.cs` for double and `DetMathF.cs` for float32, same functions, both checked
bit for bit on three platforms; a float32 lib may also compute in double and round once to
float, which is deterministic too). IEEE 754 makes
these the same everywhere.
`DetMath.Sqrt` is `Math.Sqrt`, which IEEE 754 requires to be correctly rounded.
- No `Math.Sin/Cos/Tan/Asin/Acos/Atan/Atan2/Pow/Exp/Log/Cbrt`, no `MathF`: they come from the
Expand Down
1 change: 1 addition & 0 deletions TEMPLATE/native/include/tpl.h
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ extern "C" {
#define TPL_TICK_RATE 60 /* ticks per real second the host calls (pacing) */
#define TPL_TICK_SECONDS 0.016666666666666666 /* game time one tick simulates, exact */
#define TPL_INPUT_DELAY_TICKS 1 /* ticks before the game reads a new pad */
#define TPL_TOUCH_TOLERANCE 0.5 /* native length units: closer than this counts as touching (SPEC.md section 4) */
#define TPL_SIM_BITS 64 /* the simulation's reals: 32 = float32, 64 = double, 0 = integer/fixed */

enum {
Expand Down
10 changes: 10 additions & 0 deletions TEMPLATE/src/Tpl.Core/Collision.cs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,16 @@ public enum SurfaceFlags : uint
CameraPass = 1u << 9,
}

/// <summary>Collision rules shared with the host (SPEC.md section 4).</summary>
public static class CollisionRules
{
/// <summary>
/// Native length units (cm). A shape closer to a surface than this, or overlapping it by less,
/// is touching: it blocks only a move into the surface. Same as TPL_TOUCH_TOLERANCE.
/// </summary>
public const double TouchTolerance = 0.5;
}

/// <summary>Flags for <see cref="ICollisionWorld.Segment"/>. Values match TPL_SEGMENT_*.</summary>
[Flags]
public enum SegmentFlags : uint
Expand Down
81 changes: 81 additions & 0 deletions TEMPLATE/src/Tpl.Core/DetMathF.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System;

namespace Tpl
{
/// <summary>
/// <see cref="DetMath"/> for float32 simulations (TPL_SIM_BITS = 32): the same functions, computed
/// in float only, so they give the same bits on every machine. Every intermediate is a float
/// variable; constants are float literals. A float32 lib copies this file and deletes DetMath.cs.
/// Accuracy is about 1 float ulp (1e-7). Our own code (series expansions); no source copied.
/// </summary>
public static class DetMathF
{
public const float Pi = 3.14159265f;
public const float HalfPi = 1.57079633f;
public const float TwoPi = 6.28318531f;

/// <summary>IEEE 754 requires float sqrt to be correctly rounded too: same bits everywhere.</summary>
public static float Sqrt(float x) => MathF.Sqrt(x);

/// <summary>Sine of an angle in radians.</summary>
public static float Sin(float x)
{
float k = MathF.Round(x / TwoPi);
x = x - TwoPi * k; // -pi..pi
if (x > HalfPi) x = Pi - x; // -pi/2..pi/2, same sine
else if (x < -HalfPi) x = -Pi - x;
float x2 = x * x;
// Taylor series to x^13; the next term is below 1e-9 on this range.
float p = 1f / 6227020800f; // 1/13!
p = p * -x2 + 1f / 39916800f; // 1/11!
p = p * -x2 + 1f / 362880f; // 1/9!
p = p * -x2 + 1f / 5040f; // 1/7!
p = p * -x2 + 1f / 120f; // 1/5!
p = p * -x2 + 1f / 6f; // 1/3!
p = p * -x2 + 1f;
float r = x * p;
return r;
}

/// <summary>Cosine of an angle in radians.</summary>
public static float Cos(float x)
{
float y = x + HalfPi;
return Sin(y);
}

/// <summary>Arc tangent, -pi/2..pi/2.</summary>
public static float Atan(float x)
{
if (float.IsNaN(x)) return x;
bool negative = x < 0;
if (negative) x = -x;
bool inverted = x > 1;
if (inverted) x = 1f / x;
// atan(x) = 2 atan(x / (1 + sqrt(1 + x^2))), twice: x drops below tan(pi/16) = 0.199.
float s = Sqrt(1f + x * x);
x = x / (1f + s);
s = Sqrt(1f + x * x);
x = x / (1f + s);
float x2 = x * x, p = 0f;
for (int k = 13; k >= 1; k -= 2) p = 1f / k - x2 * p; // 1 - x^2/3 + ... to x^12/13
float r = 4f * x * p;
if (inverted) r = HalfPi - r;
return negative ? -r : r;
}

/// <summary>Angle of the vector (x, y) in radians, -pi..pi, like MathF.Atan2.</summary>
public static float Atan2(float y, float x)
{
if (x > 0) return Atan(y / x);
if (x < 0)
{
float a = Atan(y / x);
return y >= 0 ? a + Pi : a - Pi;
}
if (y > 0) return HalfPi;
if (y < 0) return -HalfPi;
return 0f;
}
}
}
69 changes: 69 additions & 0 deletions TEMPLATE/tests/Tpl.Core.Tests/CollisionTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using Xunit;

namespace Tpl.Tests
{
/// <summary>The touch tolerance rule of SPEC.md section 4, on the test world's box sweep.</summary>
public class CollisionTests
{
static readonly Vec3 Half = new Vec3(40, 90, 40);
const double Tol = CollisionRules.TouchTolerance;

// A wall block from x = 400 (the "step" world's 100 cm wall starts there, the 20 cm step before it).
static TestWorld World() => TestWorld.Make("step");

[Theory]
[InlineData(0.0)] // exactly on the floor
[InlineData(0.3)] // just above, within the tolerance
[InlineData(-0.3)] // sunk in by less than the tolerance
public void SlidesAlongTheFloorItTouches(double gap)
{
Assert.False(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(150, 0, 0), out _));
Assert.False(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(0, 10, 0), out _), "moving away is free");
}

[Theory]
[InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)]
public void IsBlockedMovingIntoTheFloor(double gap)
{
Assert.True(World().SweepBox(new Vec3(0, 90 + gap, 0), Half, new Vec3(10, -5, 0), out Hit h));
Assert.Equal(0, h.T);
Assert.Equal(new Vec3(0, 1, 0), h.Normal);
}

[Theory]
[InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)]
public void SlidesAlongAWallItTouches(double gap)
{
// Standing on the 20 cm step, touching the wall face at x = 400.
var c = new Vec3(400 - 40 - gap, 20 + 90 + 1, 0);
Assert.False(World().SweepBox(c, Half, new Vec3(0, 0, 200), out _));
Assert.False(World().SweepBox(c, Half, new Vec3(-50, 0, 0), out _), "moving away is free");
}

[Theory]
[InlineData(0.0)] [InlineData(0.3)] [InlineData(-0.3)]
public void IsBlockedMovingIntoTheWall(double gap)
{
var c = new Vec3(400 - 40 - gap, 20 + 90 + 1, 0);
Assert.True(World().SweepBox(c, Half, new Vec3(10, 0, 50), out Hit h));
Assert.Equal(0, h.T);
Assert.Equal(new Vec3(-1, 0, 0), h.Normal);
}

[Fact]
public void DeepStartOverlapIsAHit()
{
Assert.True(World().SweepBox(new Vec3(0, 90 - 2 * Tol, 0), Half, new Vec3(10, 0, 0), out Hit h));
Assert.Equal(0, h.T);
}

[Fact]
public void ApartHitsAtFirstContact()
{
Assert.True(World().SweepBox(new Vec3(400 - 40 - 100, 20 + 90 + 1, 0), Half, new Vec3(200, 0, 0), out Hit h));
Assert.Equal(0.5, h.T, 12);
Assert.Equal(new Vec3(-1, 0, 0), h.Normal);
Assert.False(World().SweepBox(new Vec3(400 - 40 - 100, 20 + 90 + 1, 0), Half, new Vec3(50, 0, 0), out _));
}
}
}
30 changes: 29 additions & 1 deletion TEMPLATE/tests/Tpl.Core.Tests/DeterminismTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,34 @@ public void DetMathGoldenBits()

const string Golden = "0x40698e7e61f762cf";

[Theory]
[InlineData(0f)] [InlineData(0.5f)] [InlineData(-1.2f)] [InlineData(3f)] [InlineData(100.25f)] [InlineData(-1000f)]
public void DetMathFIsCloseToMath(float x)
{
double tol = 2e-6 + System.Math.Abs(x) * 4e-8; // float 2*pi is off by ~2e-7, so big angles drift a little
Assert.True(System.Math.Abs(DetMathF.Sin(x) - System.Math.Sin(x)) < tol, "sin");
Assert.True(System.Math.Abs(DetMathF.Cos(x) - System.Math.Cos(x)) < tol, "cos");
Assert.True(System.Math.Abs(DetMathF.Atan(x) - System.Math.Atan(x)) < 1e-6, "atan");
Assert.True(System.Math.Abs(DetMathF.Atan2(x, 0.7f) - System.Math.Atan2(x, 0.7f)) < 1e-6, "atan2");
Assert.True(System.Math.Abs(DetMathF.Atan2(0.3f, -x) - System.Math.Atan2(0.3f, -x)) < 1e-6, "atan2 left");
}

/// <summary>Golden bits for the float32 version: must be the same on every machine.</summary>
[Fact]
public void DetMathFGoldenBits()
{
float sum = 0;
for (int i = -500; i <= 500; i++)
{
float x = i * 0.0173f;
float term = DetMathF.Sin(x) + DetMathF.Cos(x) * 0.5f + DetMathF.Atan2(x, 1.5f - x) * 0.25f;
sum = sum + term;
}
Assert.Equal(GoldenF, "0x" + System.BitConverter.SingleToInt32Bits(sum).ToString("x8"));
}

const string GoldenF = "0x434c73eb";

/// <summary>Platform maths and other sources of difference must not appear in Core (outside DetMath.cs).</summary>
[Fact]
public void CoreUsesNoPlatformMaths()
Expand All @@ -46,7 +74,7 @@ public void CoreUsesNoPlatformMaths()
string dir = Path.Combine(Repo.Root(), "src", "Tpl.Core");
foreach (string file in Directory.GetFiles(dir, "*.cs"))
{
if (Path.GetFileName(file) == "DetMath.cs") continue;
if (Path.GetFileName(file) == "DetMath.cs" || Path.GetFileName(file) == "DetMathF.cs") continue;
string[] lines = File.ReadAllLines(file);
for (int i = 0; i < lines.Length; i++)
{
Expand Down
1 change: 1 addition & 0 deletions TEMPLATE/tests/Tpl.Core.Tests/HeaderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public void NativeUnitsMatchCore()
Assert.Equal(new Tuning().TickSeconds, double.Parse(Macro("TPL_TICK_SECONDS"), CultureInfo.InvariantCulture));
Assert.Equal(new Tuning().InputDelayTicks, int.Parse(Macro("TPL_INPUT_DELAY_TICKS")));
Assert.Equal(Units.SimBits, int.Parse(Macro("TPL_SIM_BITS")));
Assert.Equal(CollisionRules.TouchTolerance, double.Parse(Macro("TPL_TOUCH_TOLERANCE"), CultureInfo.InvariantCulture));
}

[Fact]
Expand Down
Loading
Loading