Writing C#

A game's code can be C#. In a Unity project with Tide's package, the structs and static methods you mark become Tide: Unity compiles your C# as usual, and Tide turns the marked parts into its own code, which runs as every Tide game does, as native code, the same on every machine of a match, predicted and rolled back. Everything else in the project stays ordinary C#: your MonoBehaviours, editor scripts and UI read the same structs.

A game can be all C#, all .tide, graphs, or any mix: each uses what the others declare.

tide
using UnityEngine;

namespace Balls
{
    using Tide;
    using static Tide.Match;

    public struct Body : IComponent
    {
        [Position] public Vector2 position;
        public Vector2 velocity;
        [Default(20f)] public float radius;
    }

    public struct Ball : IComponent { }

    public struct Main : IScene { }

    public static class Game
    {
        [On, With(typeof(Main))]
        static void Setup(Spawned spawned) =>
            Spawn(new Body { velocity = new Vector2(160, 120) }, new Ball());

        [System]
        static void Move(ref Body body, in Time time) =>
            body.position += body.velocity * time.dt;

        [System, With(typeof(Ball))]
        static void Bounce(ref Body body)
        {
            if (Mathf.Abs(body.position.x) > 160) body.velocity.x = -body.velocity.x;
            if (Mathf.Abs(body.position.y) > 160) body.velocity.y = -body.velocity.y;
        }

        [View, With(typeof(Ball))]
        static void DrawBalls(in Body body) =>
            Draw.Circle(body.position, body.radius, Color.red);
    }
}

using Tide; goes inside the game's namespace. C# reads a using there before the file's own, so the names Tide and Unity both have (Time, Debug, Random, Screen, GUI...) are Tide's in game code, with nothing more to write, while Vector2, Color and Mathf still come from Unity. Unity's one of those is still there by its full name: UnityEngine.Debug.Log(...).

What C# is for Tide

Data is structs, marked by what they are:

C# What it is
struct Body : IComponent a component
struct Score : ISingleton a singleton
struct Hit : IEvent an event
struct Controls : IInput the input, with Sample(in Devices devices)
struct Main : IScene a scene
struct FighterRow : IRow a query's row
any other struct, enum or const a struct, an enum or a constant, when Tide code uses it
[Local] on a struct or a field this machine's own: never sent, rolled back or hashed. A component is this machine's by being on a local entity (Local.Spawn(new Spark { ... })), so [Local] goes on a singleton, an event or a scene, or on a field

A field's default is [Default(20f)], so new Body() and default(Body) have it, as in Tide. (With C# 10 or newer turned on, public float radius = 20; with a public Body() { } works too.)

Code is static methods, marked by what they are: [System], [On] (an event's handler), [View], [Command], and [Vert], [Frag] and [Compute] for the GPU. What they take says what they read and change: ref Body body changes it, in Body body (or a plain Body body) reads it. [With(typeof(Ball))] and [Without(typeof(Ball))] choose entities without reading their data. An Entity entity parameter is the entity the code runs for. Methods they call become Tide too, with no attribute.

Tide C#
query (Body body, with Fighter) fighters [With(typeof(Fighter))] struct FighterRow : IRow { public Entity entity; public Body body; }, taken as Query<FighterRow> fighters
parallel (var f in fighters) { ... } Parallel.ForEach(fighters, f => { ... })
mut World world, world.Edit<Health>(e, health) { ... } ref World world, world.Edit(e, (ref Health health) => { ... })
command(string name) Rename(mut Name mine, PlayerID sender) [Command] static void Rename(string name, ref Name mine, [Sender] PlayerID sender), called as Rename("Ada") or entity.Rename("Ada") with using static TideCommands;
int Parse(string s) fails ParseError static Result<int, ParseError> Parse(string s), return Fail(error);, and at the call .Or(0), .TryGet(out var v), .Try()
async event(...), await Wait.Seconds(1) [On] static async TideTask ..., await Wait.Seconds(1)
GUILayout.Area(Anchor.UpperLeft) { ... } using (GUILayout.Area(Anchor.UpperLeft)) { ... }
parallel (var at in grid.cells) { ... } foreach (var at in grid.cells.Parallel()) { ... }
frag Glow(Corner c, out Color color) reading this.world [Frag] static void Glow(in Corner c, out Color color, in Pixel pixel) reading pixel.world
Draw.Mesh(ribbon.vertices, ribbon.indices, Wave, Stripes) Draw.Mesh(ribbon.vertices, ribbon.indices, TideShaders.Wave, TideShaders.Stripes)
input.jump.down input.jump.Down()
[Stage(Stages.Physics)], [After(Move)] [Stage(Stages.Physics)], [After(nameof(Move))]

Vector2, Vector3, Quaternion, Color, Mathf and Unity.Mathematics' math work as in Unity, computed with Tide's math, which gives the same bits on every machine.

An animated model's clips and bones are named by a contract, as C# can't read the model's file to find them: a struct of the Animation and Bone fields the code uses ([Name("Right Hand")] for a name C# can't spell), given as the model's second type.

tide
public struct HeroParts
{
    public Animation idle;
    public Animation run;
    [Name("Head")] public Bone head;
}

[Asset("art/hero.glb")] public static readonly SkinnedMesh<Corner, HeroParts> hero;

Then hero.animations.run.Sample(seconds, Playback.Loop) and pose[hero.skeleton.bones.head].rotation = ... read as in Tide, and the build checks the file has them. Tide's own verts and frags, such as baked poses' BakedSkin, are TideShaders.BakedSkin (Tide.TideShaders.BakedSkin in a namespace that declares shaders of its own).

Your scripts, .tide files and packages

The game's C# can be anywhere in Assets: every script references Tide's C# API by itself, so no assembly definition is needed (one references Tide.Api by name). Your MonoBehaviours read the same structs and call the same commands. The package's own C# is in Tide.Unity:

tide
using UnityEngine;

namespace Balls
{
    using Tide;
    using Tide.Unity;

    public class BallLook : MonoBehaviour
    {
        void Update()
        {
            var entity = GetComponent<TideEntity>();
            transform.position = entity.Get<Body>().position;
            if (UnityEngine.Input.GetKeyDown(KeyCode.Space)) entity.AsEntity().Push(Vector2.up);
        }
    }
}

runner.Get<Score>() reads a singleton as views see it this frame, and runner.On<Hit>(hit => ...) hears an event as the game's local handlers do; runner.On<Hit>((hit, heard) => ...) also has its tick, whether it's verified and the GameObject it was sent to. Reading a struct every frame makes nothing new for the garbage collector: its lists are the ones the last read filled, so copy what should outlast the frame. Add Component > Tide offers a component for each of your component structs, as for a .tide file's, to put on a prefab or in a scene and set in the inspector.

A script writes this machine's state through the same structs. entity.Set(value) writes the [Local] fields of the entity's component, and runner.Set(value) a [Local] singleton whole, or a match singleton's [Local] fields:

tide
var ball = entity.Get<Ball>();
ball.shade = 0.5f;                       // [Local] public float shade;
entity.Set(ball);
runner.Set(new Skin { face = myTexture2D }); // [Local] public struct Skin : ISingleton { public Texture face; }

An entity of this machine's local world, made with Local.Spawn(...), shows through a GameObject too: a view rule of the runner's that names one of its components (Balls.Ember), or the prefab it's the root of, shows it as it shows a match entity, and entity.Local says it's one. A Unity prefab or a scene's contents loaded by local code shows through its own GameObjects, as the match's do. All of it is this machine's, so entity.Set(value) writes its component whole, and the textures and other Unity objects its components have in the inspector are handed to it. A LocalEntity field finds the GameObject showing it, runner.GameObjectOf(runner.Get<Hearth>().ember), and entity.AsLocalEntity() gives it back. A command goes to the match or to a match entity, never to a local one: a local entity's AsEntity() is none, and a command called on none is refused, saying so in the Console.

Each [Local] singleton also has a component, which a designer adds to any GameObject of a scene (Add Component > Tide) and sets with no code. Its values are the singleton's from the game's start, and again as a scene holding one loads; in Play it shows the singleton's values, and an edit in the Inspector writes them again:

tide
[Local]
public struct Settings : ISingleton
{
    [Default(1f)] public float volume;
    public Texture logo;
}
// In the first scene: a GameObject with Tide.Authoring.Settings, volume 0.5 and a logo set in the Inspector

A field Unity can't author, and a Texture or GameObject left empty, stays as the singleton has it. With two of them, the active scene's is written, and the Console names the other.

The match is everyone's, so its fields change through a command alone: a value one of whose match fields isn't what the match has is refused whole, its local fields too, and Set returns false. The Console says which field and to write a [Command] instead, once a field each time you press Play, so a script that repeats it every frame doesn't fill the Console (every refused call still returns false). Read the value with Get, change its local fields and Set it, and its match fields are the match's. What you write is seen by Tide's views from the next frame, as this frame's views ran before your Update, and by Get at once. A local singleton is yours in a match or not: runner.Get and runner.Set take it before a match starts and after one ends.

A Texture field is what you give it: one of Unity's textures, which Tide's views draw as any texture and which reads back as it ((UnityEngine.Texture)skin.face), or none (default), which clears the field. A field holding one of Tide's own images (a render target's, say) reads as a value that keeps it, so Get, change another field, Set leaves it as it was. Your struct's fields hold what Tide's do: numbers, vectors, entities, enums, text, List<T>, Dictionary<K, V>, HashSet<T>, your structs holding any of those, Unity's Mesh, Material and AudioClip ([Local] fields), and Texture. Reading and writing them every frame makes nothing new for the garbage collector once their lists are there. A .tide file's structs write grids and T? too, and an enum stored as a byte (enum Voxel : byte) is a byte in C# as well, so a Grid2<Voxel> reads and writes.

What a .tide file or a package declares is a struct of Tide.Game in C#, with Tide's fields: ref Tide.Game.Glow glow in a system, Spawn(new Tide.Game.Box3D.Body { position = new float3(0, 10, 0) }, new Tide.Game.Box3D.Sphere()), and entity.Get<Tide.Game.Box3D.Body>() in a script. using Box3D = Tide.Game.Box3D; makes it Box3D.Body, as Tide writes it. A script reads its local fields, its grids' cells and a local singleton the same way. Unity's own side of each type (the component Add Component offers, and the classes runner.Send takes) is in Tide.Authoring.

A package's functions are statics of a class named like its namespace: with using Tide.Game.Particles;, which is Tide's using Particles;, Particles.Burst(ref emitter, 70, Spark) calls the package's Particles.Burst, and Emitter, Particle and the package's other types are named alone. Where a function takes a function that changes its arguments (Tide's Func<mut Particle, mut Random, void>), C# has a delegate for it, and a method or a lambda with ref parameters fits it: (ref Particle particle, ref Random random) => SparkAt(ref particle, ref random, position).

A shader of a package's that takes functions, such as Render3D's Lit frag, is a value you configure: a struct of its name whose fields are those functions, material.shader = new Render3D.Lit { surface = Striped };.

What's different

Tide's rules keep a match the same on every machine and let it run its systems at once, so some C# isn't Tide. Each of these is an error that says what to write instead, with a quick fix in Rider and Visual Studio where one can be written for you:

  • No classes for data, no statics that change. Match state lives in components and singletons, which snapshots and rollback see.
  • Lists, maps and sets are values. var items = bag.items; items.Add(1); changes bag.items, as in C#. But a.items = b.items;, which makes two places share one list in C#, is an error: copy it, new List<int>(b.items).
  • No exceptions, null or ?.. A function that can fail returns a Result; a value that may be missing is a T?.
  • Only Tide's, Unity's math and your own code. .NET's APIs and Unity's Time.deltaTime in a system aren't the match's: use the tick's in Time time.
  • A lambda can't use a ref or in parameter (C#'s own rule). Read a parameter taken plainly instead, and write a GUI container as using (...) { }.
  • Some names are both Tide's and Unity's (Time, Debug, Random, Screen, Cursor, GUI, Animation, Pose...). With using Tide; inside the namespace, as above, they're Tide's. With both usings at the top of a file, C# can't tell which is meant: the quick fix moves using Tide; into the namespace (or, in a file with none, writes using Time = Tide.Time;).
  • Random.Range(...), Random.value, Random.onUnitSphere and Random.rotation are rolls, the same on every machine; a sequence of the game's own is a value, new Random(seed), with NextInt, NextFloat and the rest.