DetPhysDocs日本語

Engine layer names

Unity (package 1.0.0, DetPhys namespace)

  • World (detphys.h): DetPhysWorld, DetPhysWorldSettings, DetPhysHashChain, DetPhysHash
  • Body readback (detphys_body.h): DetPhysWorldView (ReadBodies, GetShapes, ReadMesh), DetPhysBodyView
  • Turn-based (detphys_turn.h): DetPhysTurnSession, DetPhysTurnSettings, DetPhysStackRules (ToParams), DetPhysStack (RuleId), DetPhysTurnSession.Create, DetPhysTurnRule (rules in C#), DetPhysTurnContext, DetPhysRuleWorld
  • Real time (detphys_rt.h): DetPhysRtSession, DetPhysRtSettings, DetPhysRtDriver, DetPhysRtRule (rules in C#)
  • Built-in push (detphys_rt.h version 5): DetPhysRtSession.CreatePush, DetPhysPushSettings, DetPhysPushField, DetPhysPush (QuantizeMove, GetLayout), DetPhysPushLayout
  • Moving concave shapes (detphys_kinematic.h): DetPhysKinematic, DetPhysMotion, IDetPhysMotionFunction
  • Peers whose config check does not match (detphys_turn.h version 9, detphys_rt.h version 7): DetPhysRtSession.TryGetTagInfo, DetPhysTurnSession.TryGetTagInfo (false with an older core), DetPhysTagInfo (Active, RemoteKnown, PeerKnows, DiffParts, DiffText() and more; integers only), DetPhysTag (PartName, PartNames, RtSupported / TurnSupported, constants Part* / Info*), DetPhysRtFrameFlags.TagMismatch (0x200) and DetPhysRtFrame.TagMismatch
  • Transports (detphys_udp.h and others): DetPhysUdpLink, DetPhysLoopback, DetPhysFaultyLink
  • Connection interface, room codes (detphys_link.h), own relay (detphys_relay.h): DetPhysLink (CreateRelay, CreateHub, CreateUdp, CreateLoopback, Host, Join, Poll, Info, Endpoint, Close, TryParseHostPort), DetPhysLinkInfo (State, Role, Path, Reason, RoomCode, RttMs, PathText ...), DetPhysLinkHub (test lobby, DetPhysLinkHubSettings), DetPhysRoomCode (Make, Parse), DetPhysRoomOpener (make / enter a room and wait until the role is known; a guest that comes first enters again), DetPhysLinkResult, DetPhysLinkState, DetPhysLinkPath, DetPhysLinkReason
  • EOS P2P transport (detphys_eos.h version 2; a separate library, detphys_eos): DetPhysEos (CreateLink, IsAvailable, UnavailableReason, SdkVersion, LastError, PrepareAndroid, Shutdown), DetPhysEosSettings (the portal values, Relay, Load / TryLoad [the ini's [eos]], Find, Missing), DetPhysEosRelay, DetPhysLink.CreateEos. The Editor script DetPhysEosAndroidGradle adds the Android Gradle settings (see the EOS section of "8. Transports and room codes")
  • 3D world (detphys3d.h version 2): DetPhysWorld3D (Step, Hash, EngineHash, AddHull, AddBody, AddShape, ApplyForce and more, WriteSnapshot / RestoreSnapshot, WriteTransfer / RestoreTransfer), DetPhysWorld3DSettings, DetPhysWorld3DView (read only: ReadBodies, ReadTransforms, GetShapes, ReadHull, Stats), DetPhysRuleWorld3D (the world inside a rule), DetPhysBody3DDesc, DetPhysShape3DDesc (Box, Sphere, Capsule, Hull, At), DetPhysBody3DView (Position, Rotation), DetPhysHull3DInfo, DetPhysHull3DMesh (ToUnityMesh), DetPhysQuat (One = 2^30, From, FromFloats), DetPhysShape3DKind, DetPhysBody3DFlags
  • 3D sessions (detphys_rt.h version 6, detphys_turn.h version 8): DetPhysRtSession.Create3D, DetPhysRtSettings.Default3D (full snapshots in the ring), DetPhysRtRule3D (rules in C#), DetPhysRtContext3D, World3D, ResyncInfo (DetPhysRtResyncInfo); DetPhysTurnSession.Create3D, DetPhysTurnRule3D, DetPhysTurnContext3D, DetPhysTurnTick, DetPhysTurnEndReason, SetCheckpointKind, World3D. Both have Is3D and Rule3D
  • 3D moving concave shapes (detphys3d_kinematic.h version 1): DetPhysKinematic3D (Add, Bind, Step, Check, TryPoseAt, Stats), DetPhysMotion3D (Spin, PingPong, Orbit, Points), IDetPhysMotion3DFunction, DetPhysMotion3DPoint, DetPhysKinematic3DPose. With UsesKinematic => true in the rule the session owns the table (DetPhysRtContext3D.Kinematic, DetPhysTurnContext3D.Kinematic, DetPhysRtSession.Kinematic3D); splitting is set with the same DetPhysKinematicSettings as 2D
  • Desync debugger (detphys_debug.h version 3, 2D and 3D): Sessions: SetDebug (DetPhysDebugSettings.On), DebugReportCount, TryGetDebugReport (DetPhysDesyncReport: first tick, body, field, both values, ULP, cause), DebugBundle (DNDB), DebugStats (real time and turn-based, 2D and 3D). Your own ring: DetPhysDebugRecorder (Record, Record3D, Export), DetPhysDebug (Compare, TryGetFileInfo, WriteFile, FieldName, CauseName), DetPhysDesyncStatus, DetPhysDesyncCause
  • Match components (MonoBehaviour): DetPhysRtMatch (2D real time), DetPhysRtMatch3D (3D real time), DetPhysTurnMatch (2D turn based, the built-in stacking rule or your DetPhysTurnRule) and DetPhysTurnMatch3D (3D turn based, your DetPhysTurnRule3D). Add one to a GameObject and set it in the Inspector: it starts in Start and steps in Update
    • Connecting (all of them): connection (DetPhysMatchConnection: kind = Local [two players on this device], Udp (peer, listen, address, port), Relay (relay, host, roomCode, bucket, joinRetrySeconds), Eos (eosConfig, eosRelay) or Manual [from code]; simulated delay and loss for testing simulate*), startAutomatically, stepInUpdate, StartMatch, StartWithLink, StartWithEndpoint, StartRoom, Stop, Step / StepAt, Clock, IsRunning, InLobby, IsPeerConnected, LocalPeer, RoomCode, LinkInfo, Error. UnityEvents: onConnected, onPeerLost, onError, onRoomCode, onRoomReady, onSettingsMismatch (what differs, e.g. rule)
    • Real time: rule (DetPhysRuleSource.BuiltIn = the built-in push / CSharp = Rule or RuleFactory), push (DetPhysPushSettings in 2D, DetPhysPush3DSettings in 3D), shapes (2D shapes), sessionId, inputDelay, maxPrediction, automaticInputDelay, desyncDebugger, workers, kinematic, maxTicksPerFrame, endAtTick, InputSource ((peer, tick) → input integers) or LocalInput, AdjustSettings, Session, ConfirmedTick, RolledBack, StateReplaced. UnityEvents: onTickConfirmed (tick, hash, flags; the same on both peers), onDesync, onResynced, onRejoined, onInputDelayChanged, onDesyncReport (the desync debugger's report as text), onMatchEnded
    • Turn based: rule (2D; DetPhysRuleSource.BuiltIn = the built-in stacking / CSharp = Rule or RuleFactory), rules, shapes (2D), Rule / RuleFactory, world (3D), firstMover, maxTicksPerTurn, peerTimeoutMs, ticksPerFrame, playbackSpeed, desyncDebugger, InputSource ((peer, turn) → the move; null asks again next frame) or Submit, State, IsLocalTurn, Results. UnityEvents: onLocalTurn, onTurnFinished (turn, hash, flags), onMatchOver, onDesync, onDesyncReport, onStateChanged
    • Drawing: views (DetPhysViewSettings: syncTransforms [copy to Transforms every frame], bodies [Transforms by body id], createViews [simple views — boxes, spheres, hulls and so on — for bodies without a Transform], material [empty = the default material, for the built-in pipeline, URP and HDRP], colorByShape [color the default material by body type and shape], skipStatic), ViewOf, ViewCount. 2D worlds use the XY plane (rotation about z); 3D worlds use Unity's axes
  • Built-in 3D push (detphys_rt.h version 8): DetPhysRtSession.CreatePush3D, IsBuiltInPush3D, Push3DSettings, DetPhysPush3DSettings (seed, turntable, tableSpinMradS, boxCount / sphereCount / hullCount, predictButtonsReleased), DetPhysPush3D (Input, QuantizeAxis, Params, Fingerprint, GetLayout, AutoInputs, IsAvailable), DetPhysPush3DLayout
  • Shape Baker (detphys_bake.h version 1; Editor only, DetPhys.Editor): the window Window > DetPhys > Shape Baker (DetPhysShapeBakerWindow), DetPhysShapeBaker (Bake [a Texture2D, a Sprite or either], BakePng, BakeAlpha, Save [a .dnshape.bytes asset], DefaultAssetPath), DetPhysBakeSettings (pixelsPerMeter, useSpritePixelsPerUnit, alphaThreshold, simplifyPixels, method, maxVertices and more), DetPhysBakeMethod (Steiner, HertelMehlhorn), DetPhysBakeResult (Succeeded, Error, Data, Shape, Stats, Outline). At run time: DetPhysShapeFile (Parse, TryParse, PieceCount, PiecesMeters, BoundsMeters) reads a .dnshape
  • Random numbers: DetPhysRandom (splitmix64)
  • Raw C ABI: DetPhys.Native.DetPhysNative (push: DetPhysNativePush, 3D: DetPhysNative3D.cs, desync debugger: DetPhysNativeDebug.cs)
  • 2D turn-based rules can be written in C# too. Subclass DetPhysTurnRule, set InputWords, StateWords, RuleId, Params (part of the settings check, so put every setting of the rule here) and UsesKinematic, and write BeginMatch (the start of a match: the world is empty and the shapes are registered) and ApplyInput (put the mover's input into the world), plus only what you need of CheckInput (HasCheckInput), AfterTick (HasAfterTick; returns a DetPhysTurnTick; by default the turn ends when everything sleeps) and EndTurn (HasEndTurn; returns the next mover and ends the match with matchOver; by default the movers alternate). Pass it to DetPhysTurnSession.Create(settings, rule, meshes, localPeer, endpoint, kinematic = null); everything else is the same as the built-in stacking rule (Poll, Submit, TryGetResult, World). The callbacks get a DetPhysTurnContext with World (DetPhysRuleWorld: AddBody, AddShape, ApplyImpulse, TryGetBody, TryGetMeshInfo, MeshCount, BodyCount and so on), GetState / SetState, Mover, Turn, Match, MatchTurn, Tick, Settled and Kinematic (the session's DetPhysKinematic when UsesKinematic => true; moving platforms never sleep, so end turns in AfterTick by the tick count). The session's Rule and Kinematic return them. With the match components, use DetPhysTurnMatch with rule = CSharp and Rule / RuleFactory. Assets/Samples/DetPhys/1.0.0/DetPhys Samples/StackVersus/Runtime/CSharpStackRule.cs in the "Stack Versus" sample is the built-in stacking rule written in C#: it returns DetPhysStackRules.ToParams() as Params and DetPhysStack.RuleId as RuleId and computes with the same formulas in the same order, so it connects to peers using the built-in rule and to peers with the same rule written in Godot or Unreal, with the same hash on every turn.
  • 3D rules can be written in C# (DetPhysRtRule3D, DetPhysTurnRule3D; the same rules as the 2D DetPhysRtRule: integers only, state in the state words, hulls registered in Begin in the same order on both peers). The rule of the "3D push" sample (Assets/Samples/DetPhys/1.0.0/DetPhys Samples/Push3D/Runtime/Shared/Push3DRule.cs) has the same params and rule id (with or without the turntable) as the core's built-in 3D push (detphys_rt_create_push3d, version 8), so it connects to peers using the core rule (such as the Godot sample). Use the core rule with DetPhysRtSession.CreatePush3D (DetPhysPush3DSettings) or DetPhysRtMatch3D with rule = BuiltIn.
  • Drawing: Box3D and Unity both have y up, so DetPhysBody3DView.Position and Rotation can be used as they are (Box3D is right-handed and Unity left-handed, so the picture is a mirror image of the right-handed world; everything is mirrored the same way; DetPhysHull3DMesh.ToUnityMesh turns the hull triangles the way Unity expects).
  • The samples compare their confirmed hashes with the reference hashes stored in each sample's Resources folder when they run with automatic inputs, so you can check on any device that 2D and 3D worlds, sessions and moving concave shapes give the same hashes.
  • A transport written in C# (an implementation table given to detphys_link_create) is not wrapped yet; use the transports of the C ABI for now.

Godot (add-on addons/detphys, layer version 7)

  • World: GDScript: DetPhysWorld, DetPhysWorldSettings, DetPhys (hash hex, chains). C#: DetPhysWorld, DetPhysWorldSettings, DetPhysHash
  • Body readback: GDScript: DetPhysWorldReader (read_bodies, read_body_info, get_body_shapes, get_mesh_polygons; sessions inherit it). C#: Same declarations as Unity
  • Turn-based: GDScript: DetPhysTurnSession (create_stack), DetPhysTurnSettings, DetPhysStackRules, node DetPhysStackMatch. C#: DetPhysTurnSession
  • Real time, built-in push: GDScript: DetPhysRtSession (create_push, get_layout, kinematic_check), DetPhysRtSettings, DetPhysPushRules (moving field too), node DetPhysRtMatch. C#: DetPhysRtSession.CreatePush, DetPhysPush
  • Peers whose config check does not match: GDScript: DetPhysRtSession.get_tag_info(), DetPhysTurnSession.get_tag_info() (a Dictionary of integers: flags, diff_parts and more; local_parts / remote_parts are PackedInt64Arrays of 8), static tag_part_name(part), tag_part_names(parts, separator), constants DETPHYS_TAG_PART_*, DETPHYS_TAG_INFO_*, DETPHYS_RT_FRAME_TAG_MISMATCH (and DETPHYS_RT_FRAME_DEBUG), node signal tag_mismatch(info) (DetPhysRtMatch, DetPhysStackMatch; info adds known_after_ms and parts_text; call check_tag() when you drive advance_once yourself). C#: TryGetTagInfo (real time, turn-based; DetPhysTagInfoNative), DetPhysTag (PartName, PartNames)
  • Transports: GDScript: DetPhysLink (udp_listen, udp_connect, set_faults), DetPhysLoopback. C#: DetPhysUdpLink, DetPhysLoopback
  • Connection interface, room codes, own relay (detphys_link.h, detphys_relay.h): GDScript: DetPhysLink (static relay(host, port, local_port), host_room(bucket, code, entropy, timeout_ms), join_room(code, bucket, timeout_ms), poll, get_state, get_role, get_path, get_room_code, get_info [Dictionary with names], get_link_error, close, static room_code_make, room_code_parse, room_code_check, state_name, reason_name, path_name, constants DETPHYS_LINK_*, DETPHYS_RELAY_*; set_faults works too), DetPhysLinkHub (create, create_link, pump). The nodes DetPhysRtMatch and DetPhysStackMatch call link.poll() every frame. C#: DetPhysLink (CreateRelay, Host, Join, Poll, Info, Transport), DetPhysLinkHub, DetPhysRoomCode, DetPhysRoomOpener (the same as in Unity: make / enter a room and wait until the role is known; a guest that comes first enters again; FailResult is a DetPhysNative.LinkError* number)
  • EOS P2P transport (detphys_eos.h version 2): GDScript has DetPhysLink (static eos(settings), eos_available(), eos_sdk_version(), eos_error(); detphys_eos is loaded when first used) and the helper script addons/detphys/eos/detphys_eos.gd (load_ini, find_ini, create_link, prepare_android, available, error). For Android exports the editor plugin "DetPhys" adds the EOS SDK's aar and the Gradle settings. C# has the same API as Unity: DetPhysEos (CreateLink, IsAvailable, UnavailableReason, SdkVersion, LastError, PrepareAndroid, AndroidExternalFilesDir, Shutdown), DetPhysEosSettings (Load / TryLoad [res:// and user:// work too], Find, Missing), DetPhysEosRelay; declarations in DetPhysNativeEos.cs (GDScript and C# use the same detphys_eos)
  • 3D, built-in 3D push (detphys_rt.h version 8, detphys3d.h, detphys3d_kinematic.h; layer version 3): GDScript: DetPhysRtSession.create_push3d(settings, rules, local_peer, link, world = null), DetPhysRtSettings.default_3d() (FULL snapshots), DetPhysPush3DRules (Resource, one to one with the desc: box_count, sphere_count, hull_count, spawn_max, field [FIELD_NONE / FIELD_TURNTABLE], seed, table_spin_mrad_s and more; to_params, fingerprint, get_layout, static auto_inputs(seed, peer, ticks), constants BUTTON_*, TAG_*, INPUT_WORDS), DetPhysWorld3DSettings (tick_hz, substeps, gravity xyz, worker_count). Input: 3 words every tick [move x, move z, buttons]. Readback (for drawing): is_3d, get_world3d_tick / _hash, get_body3d_count, get_world3d_stats, read_transforms3d(first) (7 floats: position in m, quaternion x, y, z, w), read_bodies3d() (8 ints: id, type, flags, tag, shape count, first shape, hull), get_body3d(id), get_body3d_shapes(id) (Vector3 / Quaternion), get_hull3d_count, get_hull3d(hull), get_hull3d_arrays(hull) (ready for ArrayMesh.add_surface_from_arrays). The turntable's table: has_kinematic, get_kinematic_stats, kinematic_check (the same names as 2D). C#: DetPhysRtSession.CreatePush3D (Is3D, World3D, ReadTransforms3D, ResyncInfo, KinematicCheck), DetPhysPush3D (Desc, Params, Fingerprint, Layout, AutoInputs); declarations in DetPhysNativePush3D.cs
  • State sent on a resync, desync debugger (detphys_debug.h version 3; 2D and 3D sessions): GDScript: DetPhysRtSession.get_resync_info() (registry_rebuilds, hull_replacements, last_bytes and more; 3D also sends the shape registry and the hull table), set_debug(enabled, ticks_before = 30, max_reports = 4, timeout_ms = 10000), get_debug_count, get_debug_report(index) (status, first_tick, body, field_name, ulp, cause_name, text [the same line as Unity's DetPhysDesyncReport] and more), get_debug_bundle(index) (DNDB, open it with tools/desync), get_debug_stats, static debug_field_name, debug_cause_name, rt_abi_version, world3d_abi_version, debug_abi_version. C#: ResyncInfo, the same desync debugger as Unity (SetDebug [DetPhysDebugSettings.On], DebugReportCount, TryGetDebugReport [DetPhysDesyncReport], DebugBundle, DebugStats; real-time and turn-based sessions), DetPhysDebugRecorder (Record3D, Export), DetPhysDebug (Compare, FieldName, CauseName) and DebugNudgeAt for tests
  • 3D, rules you write (C#; detphys_rt.h version 6, detphys_turn.h version 8, detphys3d.h, detphys3d_kinematic.h): the same names and design as Unity. Derive from DetPhysRtRule3D (real time) or DetPhysTurnRule3D (turn based) and pass it to DetPhysRtSession.Create3D(rule, localPeer, transport, owner, world = null, sessionId = 0x36, inputDelay = 0, maxPrediction = 10, snapshot = Full, recordAllHashes = true, kinematic = null) or DetPhysTurnSession.Create3D(rule, localPeer, transport, owner, world = null, sessionId = 0x36, maxTicksPerTurn = 600, peerTimeoutMs = -1, firstMover = 0, kinematic = null) (transport is DetPhysUdpLink.Transport, DetPhysLink.Transport or DetPhysLoopback.Side(n); owner is the object that holds it). The callbacks get a DetPhysRtContext3D / DetPhysTurnContext3D with World (DetPhysRuleWorld3D: AddHull, AddBody, AddShape, ApplyForce, ApplyImpulse, TryGetBody and more), GetState / SetState, Tick and Kinematic (when the rule returns UsesKinematic => true, the DetPhysKinematic3D the session owns; add moving concave shapes in Begin: Add, DetPhysMotion3D.Spin / PingPong / Orbit / Points, IDetPhysMotion3DFunction). Turn speeds into integers with DetPhysFixed.FloorMilli. Session readback: Is3D, Rule3D, World3D (DetPhysWorld3DView: ReadBodies, ReadTransforms, GetShapes, ReadHull, Stats, Hash), ReadTransforms3D, Kinematic3D, and SetCheckpointKind for turn-based sessions. To step a world directly: DetPhysWorld3D (Edit gives the same calls as a rule; WriteSnapshot / RestoreSnapshot, WriteTransfer / RestoreTransfer) and DetPhysKinematic3D (Step, Check). For drawing: DetPhysBody3DView.Position, Rotation (Godot Vector3, Quaternion), DetPhysHull3DMesh.ToArrayMesh() (an ArrayMesh with Godot's front-face order) and DetPhysQuat.From(Quaternion) (to quantize inputs). Declarations are the same files as Unity: DetPhysNative3D.cs, DetPhysNativeKinematic.cs, DetPhysNativeDebug.cs
    • The rules of a rule are the same as in Unity: results may depend only on the inputs, the context, the world and Params, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Register hulls in Begin (BeginMatch), in the same order on every peer. Change the kinematic table only in Begin too
    • Sample rules (samples/rules3d/DetPhysSampleRules3D.cs, namespace DetPhys.Samples): DetPhysSamplePush3DRule (the 3D push written in C#; it has the same params and rule id as the built-in rule, so it plays peers that use the built-in rule [GDScript create_push3d, Unity, Unreal]), DetPhysSampleStack3DRule (3D stacking, turn based) and DetPhysSampleSpinTableRule (a turning octagonal table, a concave shape moved by the kinematic table). With the launch option rule=cs, the "3D push" sample plays an automatic match with this rule (without drawing)
  • 3D, rules you write (GDScript; layer version 4): rules with the same design as in C# can be written in GDScript alone. extends DetPhysRtRule3D (real time) or DetPhysTurnRule3D (turn based), set input_words, state_words, rule_id, params (a PackedInt32Array that is part of the config check, so put every value of the rule in it) and uses_kinematic in _init, and pass the rule to DetPhysRtSession.create3d(settings, rule, local_peer, link, world = null) or DetPhysTurnSession.create3d(settings, rule, local_peer, link, world = null) (settings is DetPhysRtSettings.default_3d() / DetPhysTurnSettings, world is a DetPhysWorld3DSettings [null = defaults]; on failure they return null and print the reason as a Godot error).
    • Real-time callbacks: _begin(ctx) (tick 0; create hulls, bodies and kinematic bodies), _apply_inputs(ctx, inputs) (every tick; inputs holds both peers in one PackedInt32Array, word w of peer p is inputs[p * input_words + w]), _after_tick(ctx) (optional) and _predict(peer, tick, known_tick, known) (optional; return the peer's input that has not arrived yet as a PackedInt32Array of input_words words; without it the last received input is repeated).
    • Turn-based callbacks: _begin_match(ctx) (every match; the world starts empty), _apply_input(ctx, input) (place the mover's move), _check_input(ctx, input) (optional; return a bool, false rejects the move), _after_tick(ctx) (optional; return TICK_CONTINUE, TICK_END_TURN or TICK_END_MATCH) and _end_turn(ctx, reason) (optional; return the next mover 0 / 1, plus MATCH_OVER to end the match; reason is REASON_END_TURN, REASON_END_MATCH or REASON_CAPPED).
    • Contexts: DetPhysRtContext3D (tick, resimulating, local_peer, world, get_state(i) / set_state(i, v), fail(why), add_kinematic(body, motion), kinematic_check()) and DetPhysTurnContext3D (turn, match, match_turn, mover, tick, settled, plus the same world, get_state / set_state, fail, add_kinematic, kinematic_check). They are valid only inside a callback.
    • World (DetPhysRuleWorld3D, all values are integers): add_hull(xyz, units_per_meter = 1000, max_vertices = 0) (points in x, y, z order; returns the hull index), add_body(desc), add_shape(body, shape), remove_body, set_transform, set_velocity, apply_force (mN), apply_torque, apply_impulse (mN·s), apply_angular_impulse, get_body(id) (x_mm, vx_mm_s, wx_mrad_s, qx–qw [times DETPHYS3D_QUAT_ONE], type, removed, awake and more), get_hull_info(hull), get_tick, get_hash, get_body_count. desc, shape and motion are Dictionaries whose keys are the field names of the C structs (x_mm, radius_mm, half_x_mm, density_milli, friction_milli, flags, shape and so on). Missing keys take the defaults; unknown keys and float values are rejected as typos (the rule stops and get_rule_error() tells why). Constants: DetPhysRuleWorld3D.DETPHYS3D_SHAPE_*, DETPHYS3D_BODY_*, DETPHYS3D_BODY_FLAG_*, DETPHYS3D_PATH_*, DETPHYS_EASE_*.
    • Moving concave shapes: a rule with uses_kinematic = true adds them inside _begin (_begin_match) with ctx.add_kinematic({"shape": {...}}, {"path": DetPhysRuleWorld3D.DETPHYS3D_PATH_FIXED, "spin_mrad_s": 1200, ...}). In real time, kinematic_max_subticks and the other kinematic_* values of DetPhysRtSettings set how finely the table is stepped.
    • Reading the session: the same is_3d, get_world3d_hash, read_transforms3d, read_bodies3d, get_body3d, get_hull3d / get_hull3d_arrays, has_kinematic and kinematic_check as the 3D push work on both real-time and turn-based sessions, plus get_rule() and get_rule_error().
    • The same rules as in C# apply: results may depend only on the inputs, the context, the world and params, computed with integers (do not let float, randi(), Time or Dictionary iteration order reach the result; use a DetPhysRandom made from a seed). Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Register hulls inside _begin in the same order on every peer.
    • Sample rules (samples/rules3d): push3d_rule.gd (the 3D push; it has the same params, rule id and results as the built-in rule and C#'s DetPhysSamplePush3DRule, so it plays create_push3d and C# peers), stack3d_rule.gd (3D stacking, turn based) and spin_table_rule.gd (the spinning octagonal table). See 3. Concepts for an example.
  • 2D, rules you write (GDScript and C#; detphys_rt.h, detphys_turn.h, detphys_body.h, detphys_kinematic.h; layer version 5, match nodes and C# rules for them 6): rules for the 2D world (Box2D) with the same design as 3D. Shapes (.dnshape) are passed when the session is created and registered from index 0.
    • GDScript: extends DetPhysRtRule2D (real time) or DetPhysTurnRule2D (turn based), set input_words, state_words, rule_id, params and uses_kinematic in _init, and pass the rule to DetPhysRtSession.create2d(settings, rule, local_peer, link, meshes = []) or DetPhysTurnSession.create2d(settings, rule, local_peer, link, meshes = []) (meshes is an Array of .dnshape PackedByteArrays; on failure they return null and print the reason as a Godot error). The callbacks and their return values are the same as in 3D (_begin, _apply_inputs, _after_tick, _predict / _begin_match, _apply_input, _check_input, _after_tick, _end_turn). params returns a copy, so build the PackedInt32Array first and assign it once.
    • Contexts: DetPhysRtContext2D and DetPhysTurnContext2D (the same names as 3D: tick, world, get_state / set_state, fail, add_kinematic, kinematic_check; turn based also has turn, match_turn, mover, settled and get_match()).
    • World (DetPhysRuleWorld2D): add_body(desc), add_shape(body, shape), remove_body, set_transform(body, x_mm, y_mm, angle_mrad), set_velocity(body, vx_mm_s, vy_mm_s, w_mrad_s), apply_force(body, fx_mN, fy_mN), apply_impulse(body, ix_mNs, iy_mNs), get_body(id), get_body_count, get_awake_count, get_mesh_count, get_mesh_info(mesh) (radius_mm and more), get_tick, get_hash. desc, shape and motion are Dictionaries whose keys are the field names of the C structs (type, x_mm, angle_mrad, tag, and in shape: kind, mesh, size_x_mm, offset_x_mm, density_milli, friction_milli and more). get_body returns integers (x_mm, y_mm, angle_mrad, vx_mm_s, w_mrad_s, type, shape_kind, mesh, removed and more) and floats for drawing (x, y, angle, vx, vy, w). Do not compute with the floats; use them only to compare a position with a limit. Constants: DetPhysRuleWorld2D.DETPHYS_BODY_*, DETPHYS_SHAPE_*, DETPHYS_PATH_*, DETPHYS_EASE_*.
    • Moving concave shapes: a rule with uses_kinematic = true adds them inside _begin (_begin_match) with ctx.add_kinematic({"shape": {"kind": DetPhysRuleWorld2D.DETPHYS_SHAPE_MESH, "mesh": 3}}, {"path": DetPhysRuleWorld2D.DETPHYS_PATH_FIXED, "x_mm": -5500, "y_mm": 4000, "spin_mrad_s": -1200}). The points of a POINTS path are 4 words per point: x_mm, y_mm, angle_mrad, ticks.
    • C#: inherit DetPhysRtRule (real time, the same name as in Unity) or DetPhysTurnRule (turn based, the same design as 3D), and pass the rule to DetPhysRtSession.Create(rule, localPeer, meshes, transport, owner, sessionId = 0x16, inputDelay = 0, maxPrediction = 10, recordAllHashes = true, kinematic = null) or DetPhysTurnSession.Create(rule, localPeer, meshes, transport, owner, sessionId = 0x7E57, maxTicksPerTurn = 0, peerTimeoutMs = -1, firstMover = 0) (meshes is a byte[][] of .dnshape files). The callbacks get a DetPhysRtContext / DetPhysTurnContext and use World (DetPhysRuleWorld: AddBody, AddShape, ApplyForce, ApplyImpulse, TryGetBody, TryGetMeshInfo, MeshCount and more), GetState / SetState and Kinematic (DetPhysKinematic: Add, DetPhysMotion.Spin / PingPong / Orbit / Points, IDetPhysMotionFunction). Sessions have Rule, Kinematic and, turn based, World2D.
    • The same rules as in 3D apply: results may depend only on the inputs, the context, the world and params, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep the match state in the world and the state words. Change the kinematic table only inside _begin (_begin_match).
    • Peers with the same rule connect and confirm the same tick hashes whether the rule is written in GDScript, C#, Unreal C++ or is the core's built-in rule (they are matched by params and rule_id). Check that your values match the built-in rules with DetPhysPushRules.to_params(), RULE_ID, DetPhysStackRules.to_params() and RULE_ID.
    • Sample rules (samples/rules2d): push_rule.gd / DetPhysSamplePushRule (the push, with or without the moving stage) and stack_rule.gd / DetPhysSampleStackRule (stacking, turn based; the next shape decided by a seed or chosen by the input). They have the same params, rule id and results as the built-in rules (create_push, create_stack).
    • Match nodes (layer version 6): put a rule in rule of DetPhysRtMatch or DetPhysStackMatch before start, and the node plays that rule with the same links (UDP, relay rooms, EOS rooms), signals and drawing readback as the built-in rules (an empty rule plays the built-in push / stacking). It takes a GDScript rule (DetPhysRtRule2D / DetPhysTurnRule2D) or a C# rule wrapped in DetPhysRuleRef (new DetPhysRuleRef(new MyRule()), for both DetPhysRtRule and DetPhysTurnRule). Use one rule instance per node. The input (input_source, submit) is the rule's input_words integers. Give clock (func() -> int, µs) your own clock to step with it (for tests). DetPhysRtSession.create2d and DetPhysTurnSession.create2d also take a DetPhysRuleRef (the core calls the C# callbacks directly).
  • 3D match nodes (C#): DetPhysRtMatch3D (Rule [empty = the built-in 3D push with Seed, Turntable, PredictButtonsReleased], World, Kinematic, InputSource [tick → input words], Start(localPeer, transport, owner), Stop, StepFrame / StepAt(nowUs), Session, RolledBack, Replaced, IsPeerConnected, QuantizeAxis; signals Connected, TickConfirmed(tick, hash, flags), DesyncFound, Resynced, Rejoined, PeerLost, Failed) and DetPhysTurnMatch3D (Rule [required], InputSource [turn number → move; null = ask again next frame], MaxTicksPerTurn, MaxTicksPerFrame, Results; signals Connected, TurnFinished(turn, hash, flags), MatchOver, StateChanged, Failed). Both are [GlobalClass], so they appear in the editor's "Add Node". With AutoProcess on (the default) they advance in _Process; give Clock your own clock (µs) to advance ticks by it (for tests)
  • Random numbers: GDScript: DetPhysRandom. C#: DetPhysRandom
  • 3D coordinates: Box3D and Godot are both y up, right-handed, in meters, so the positions and quaternions of read_transforms3d go straight into Transform3D(Basis(Quaternion(qx, qy, qz, qw)), Vector3(x, y, z)) (unlike Unity, the picture is not mirrored). Box3D's hull triangles are counter-clockwise seen from outside and Godot's front faces are clockwise, so get_hull3d / get_hull3d_arrays reorder them (get_hull3d_arrays gives per-face vertices and outward normals).
  • The "3D push" sample (samples/push3d, GDScript only) plays Unity's "3D push" sample, with the same confirmed hashes.
  • Even when the core turns a HELLO with a different config hash into ERROR, DetPhysStackMatch keeps polling until the peer's parts arrive and it knows what differs (waiting up to 300 ms), and emits failed after tag_mismatch.
  • In the Godot layer, matches use the built-in rules (stacking, push, 3D push). 2D and 3D rules (real time and turn based) and kinematic tables can be written in GDScript and C#. The desync debugger works on real-time sessions (2D and 3D) from GDScript, and on real-time and turn-based sessions from C#.
  • The steps "make / enter a room, wait until the role is known (a guest that comes first enters again)" are written in GDScript in the sample's samples/common/detphys_sample_room.gd (copy it).

Unreal (plugin DetPhys 0.1.0)

  • World (detphys.h): UDetPhysWorld (Blueprint: CreateDetPhysWorld, Step, StepTicks, GetTick, GetStateHash; C++: GetNative()), FDetPhysWorldSettings, UDetPhysLibrary
  • Body readback (detphys_body.h): ReadBodies, GetBody, GetBodyShapes, GetMeshPolygons (on UDetPhysWorld and on the sessions), FDetPhysBody, FDetPhysBodyShape, FDetPhysPolygon
  • Turn-based, built-in stacking (detphys_turn.h): UDetPhysTurnSession::CreateStack (Poll / PollAt, Submit, NextResult, UpcomingShape, ShapeAt, GetLinkStats, GetWorldSerial), FDetPhysTurnSettings, FDetPhysStackRules, FDetPhysTurnResult (AgreedHash), FDetPhysTurnLinkStats
  • Real time, built-in push (detphys_rt.h): UDetPhysRtSession::CreatePush (Poll, DueTicks, GetNextInputTick, Advance, DrainConfirmed, GetStats, ReadState, moving field HasMovingField, CheckMovingField, GetMovingFieldStats), FDetPhysRtSettings, FDetPhysPushRules (moving field Field), FDetPhysRtFrame, FDetPhysConfirmedTick, FDetPhysRtStats
  • 2D, your own rules (detphys_rt.h, detphys_turn.h, detphys_body.h, detphys_kinematic.h): subclass UDetPhysRtRule (real time) or UDetPhysTurnRule (turn based) in C++ and pass it to UDetPhysRtSession::Create(Outer, Settings, Rule, Shapes, LocalPeer, Link) or UDetPhysTurnSession::Create(Outer, Settings, Rule, Shapes, LocalPeer, Link). The shapes (Shapes) are registered as mesh 0, 1, ... before the rule's Begin (BeginMatch). The virtual functions are the same as Unity's DetPhysRtRule and follow the 3D rules (real time: GetInputWords, GetStateWords, GetRuleId, GetParams, UsesKinematic, HasAfterTick, HasPredict, Begin, ApplyInputs, AfterTick, Predict, GetPlayerBody; turn based: GetInputWords, GetStateWords, GetRuleId, GetParams, UsesKinematic, GetKinematicMaxSubticks, GetKinematicSubtickMoveMm, BeginMatch, HasCheckInput / CheckInput, ApplyInput, HasAfterTick / AfterTick [EDetPhysTurnTick], HasEndTurn / EndTurn [EDetPhysTurnEndReason], ShapeAt). The callbacks get FDetPhysRtContext / FDetPhysTurnContext (GetWorld() = detphys_world*, GetTick, GetState / SetState, GetMeshCount, GetKinematic() = detphys_kinematic*, Fail; turn based also GetMover, GetTurn, GetMatch, GetMatchTurn, IsSettled). Build and move the world with the C ABI (detphys_body.h, detphys_kinematic.h) directly. The session's GetRule() returns the rule, and GetPlayerBody, UpcomingShape and ShapeAt return what the rule's GetPlayerBody and ShapeAt answer. With UsesKinematic true the session owns a kinematic table (real time: split by the Kinematic* values in Settings; read it with GetKinematic())
    • A rule with the same rule id and params as a built-in rule connects to peers running the built-in rule (CreatePush, CreateStack, Unity, Godot, detphys_rt_create_push in the C ABI, and so on), with the same confirmed-tick and turn hashes
    • Sample rules (DetPhysSampleRules2D.h in DetPhysSample): UDetPhysSamplePushRule (the push game, with or without the moving field; values in FDetPhysPushRules) and UDetPhysSampleStackRule (stacking, turn based; values in FDetPhysStackRules). Both use the same formulas and params as the built-in rules. The DetPhysVersus commandlet runs matches with them when given rule=cpp
  • 3D, built-in 3D push (detphys_rt.h version 8, detphys3d.h, detphys3d_kinematic.h): UDetPhysRtSession::CreatePush3D(Outer, Settings, Rules, LocalPeer, Link, World) (Poll, DueTicks, Advance [3 input words per tick: [move x, move z, buttons]], DrainConfirmed and the desync debugger work as in 2D; the turntable through HasMovingField, CheckMovingField, GetMovingFieldStats; players through GetPlayerBody), FDetPhysPush3DRules (one to one with the desc: BoxCount, SphereCount, HullCount, SpawnMax, Seed, Field [EDetPhysPush3DField::None / Turntable], TableSpinMradS, TableXMm, TableZMm and more), FDetPhysWorld3DSettings (tick rate, substeps, gravity xyz, worker threads), UDetPhys3DLibrary (DefaultRtSettings3D [FULL snapshots], AutoPush3DInputs, MakePush3DInput, GetPush3DLayout, Push3DParams, Push3DFingerprint, coordinate conversion CoreToUnrealLocation, CoreMmToUnreal, UnrealToCoreMm, CoreToUnrealRotation, CoreToUnrealDirection). Readback for drawing: Is3D, GetPush3DLayout, ReadTransforms3D (an array of FTransform; index = body id), ReadBodies3D, GetBody3D (FDetPhysBody3D), GetBodyShapes3D (FDetPhysShape3D), GetHull3DCount, GetHull3DMesh (FDetPhysHull3DMesh: vertices, triangles and outward normals ready for UProceduralMeshComponent::CreateMeshSection), GetWorld3DTick, GetWorld3DHash, GetWorld3DStats, GetResyncInfo (FDetPhysResyncInfo, also for 2D). C++: GetDetPhysWorld3D() returns the detphys3d_world*
    • Coordinates: the core is right-handed with y up and metres; Unreal is left-handed with z up and centimetres. Values returned as FVector, FQuat and FTransform are converted to Unreal coordinates by the layer (position (x, y, z) m → (x, z, y) × 100 cm, quaternion (qx, qy, qz, qw) → FQuat(-qx, -qz, -qy, qw), hull triangles in Unreal's front-face order). Swapping y and z keeps the look of the scene (nothing is mirrored). Integer values (*Mm, settings, input) stay in core coordinates
  • 3D, your own rules (detphys_rt.h, detphys_turn.h, detphys3d.h, detphys3d_kinematic.h): subclass UDetPhysRtRule3D (real time) or UDetPhysTurnRule3D (turn based) in C++ and pass it to UDetPhysRtSession::Create3D(Outer, Settings, World, Rule, LocalPeer, Link) or UDetPhysTurnSession::Create3D(Outer, Settings, World, Rule, LocalPeer, Link). The virtual functions are the same as Unity's DetPhysRtRule3D / DetPhysTurnRule3D (real time: GetInputWords, GetStateWords, GetRuleId, GetParams, UsesKinematic, Begin, ApplyInputs, AfterTick, Predict; turn based: BeginMatch, CheckInput, ApplyInput, AfterTick [EDetPhysTurnTick], EndTurn). The FDetPhysRtContext3D / FDetPhysTurnContext3D a callback gets gives GetWorld() (the detphys3d_world*: create bodies and hulls, apply forces and read with the core's C ABI), GetState / SetState, GetTick, GetKinematic() (with UsesKinematic, the kinematic table detphys3d_kinematic* the session owns: add moving concave bodies in Begin) and Fail. Turn speeds into integers with FDetPhysRule3DMath::FloorMilli. 3D readback of a turn-based session: Is3D, ReadTransforms3D, ReadBodies3D, GetBody3D, GetBodyShapes3D, GetHull3DCount, GetHull3DMesh, GetWorld3DStats, GetWorldHash, ReadState, CheckMovingField. C++: GetDetPhysWorld3D(), GetKinematic3D()
    • Rules for rules: results may depend only on the inputs, the context, the world and GetParams, computed with integers. Real-time callbacks run again for the same tick on every rollback, so keep match state in the world and in the state words (members of the rule object are not rolled back). Register hulls in Begin (BeginMatch) in the same order on every peer. Change the kinematic table only in Begin
    • Sample rules (DetPhysSampleRules3D.h in DetPhysSample): UDetPhysSamplePush3DRule (the 3D push written in C++; its params and rule id equal the built-in rule's, so it also connects to built-in peers), UDetPhysSampleStack3DRule (3D stacking, turn based), UDetPhysSampleSpinTableRule (a spinning octagonal table, a concave body moved by the kinematic table)
  • Desync debugger (session interface): SetDebug, GetDesyncReportCount, GetDesyncReport, DebugNudgeAt (tests), FDetPhysDebugSettings, FDetPhysDesyncReport
  • Peers whose config check does not match: UDetPhysTurnSession::GetTagInfo, UDetPhysRtSession::GetTagInfo (false with an older core), FDetPhysTagInfo (integers only; C++ has IsActive() and the like), UDetPhysLibrary::TagPartName, TagPartNames, 512 in FDetPhysRtFrame.Flags (DETPHYS_RT_FRAME_TAG_MISMATCH)
  • Transports (detphys_udp.h, loopback): UDetPhysLink (UdpListen, UdpConnect, SetFaults [tests], GetLocalPort), UDetPhysLoopback (CreateLoopback, GetSide, Pump)
  • Pluggable transport, room codes (detphys_link.h), own relay (detphys_relay.h): UDetPhysLink (static CreateRelay(Host, Port, LocalPort), HostRoom(Bucket, Code, Entropy, TimeoutMs), JoinRoom(Code, Bucket, TimeoutMs), Poll, GetState, GetRole [0 / 1, -1 before], GetPath, GetRoomCode, GetInfo, GetInfoText, GetLinkError, Close [leaves the room], IsRoomLink, static RoomCodeMake, RoomCodeParse, RoomCodeCheck, StateName, ReasonName, PathName, SplitHostPort, IsRoomApiAvailable; SetFaults works as before), FDetPhysLinkInfo, EDetPhysLinkState, EDetPhysLinkPath, EDetPhysLinkReason, UDetPhysLinkHub (test lobby: CreateHub, CreateLink, Pump, GetRoomCount), UDetPhysRoomOpener (OpenRelayRoom, OpenHubRoom, C++ Open: make / enter a room and wait for the role, a guest that comes first enters again; Poll, GetRole, GetLink, GetAttempts, GetFailResult, GetFailReason)
  • EOS P2P transport (detphys_eos.h version 2; a separate library, detphys_eos; Windows x64): UDetPhysEos (IsEosAvailable, GetEosError, GetEosSdkVersion, GetEosLocation, LoadEosSettings, FindEosSettingsFile, CreateEosLink(Outer, Settings), OpenEosRoom(Outer, Settings, bHost, Code, Bucket, Entropy, RetryForMs, RetryEveryMs, TimeoutMs), DescribeEosSettings, ParseEosRelay, ShutdownEos), FDetPhysEosSettings (ProductId, SandboxId, DeploymentId, ClientId, ClientSecret [Transient], ProductName, ProductVersion, DisplayName, CacheDir, Relay [EDetPhysEosRelay: Allow / Force / Never], LoginTimeoutMs, LogLevel, bNewDeviceId [tests only]). The link is a UDetPhysLink (GetKind() is "eos") and Close frees it at once. detphys_eos.dll is loaded when it is first used, so the plugin works without it. This is not Unreal's Online Subsystem EOS
  • Match ActorComponents and Delegates (Godot's DetPhysRtMatch / DetPhysStackMatch): UDetPhysRtMatchComponent (Settings, Rules, LocalInput [C++: InputSource], StepFrame / StepFrameAt, GetSession, WasRolledBack, WasReplaced; Delegates OnTickConfirmed, OnDesync, OnResynced, OnRejoined, OnInputDelayChanged), UDetPhysStackMatchComponent (Settings, Rules, TicksPerFrame, Speed, Submit, StepTicks; Delegates OnLocalTurn, OnTurnFinished, OnMatchFinished, OnWorldReplaced). Both have StartWithLink(LocalPeer, Link), HostRelayRoom / JoinRelayRoom, StartRoom(UDetPhysRoomOpener), Stop, Shapes / ShapeFiles, RoomBucket, bAutoStep, and the shared Delegates OnConnected, OnPeerLost, OnFailed, OnTagMismatch, OnLinkStateChanged, OnRoomReady
    • Your own 2D rules: CustomRule on UDetPhysRtMatchComponent and UDetPhysStackMatchComponent (your UDetPhysRtRule / UDetPhysTurnRule; empty = the built-in rule with the values in Rules). With your own rule, OnLocalTurn's Shape is what the rule's ShapeAt answers and OnMatchFinished's Winner is -1 (the rule decides the winner in the result's State words)
    • 3D: UDetPhysRtMatch3DComponent (World, Rule [your UDetPhysRtRule3D; empty = the built-in 3D push with the values in Rules3D]; Settings start with FULL snapshots) and UDetPhysTurnMatch3DComponent (World, Rule [your UDetPhysTurnRule3D, required]). Stepping, input, Delegates and the ways to connect are the same as the 2D components (OnLocalTurn's Shape and OnMatchFinished's Winner are -1; the rule's state words in the result tell who won). Draw with the *3D functions of GetSession()
  • Shapes, input quantization: UDetPhysLibrary (LoadShapeFile / LoadShapeFiles, ShapesFingerprint, QuantizeMove, QuantizeMm, QuantizeMrad, MakePushInput, automatic moves AutoStackInput / AutoPushInputs, NowUs), FDetPhysShapeData
  • Everything else: Call the C ABI of the DetPhysCore module directly from C++ (header copies in Source/ThirdParty/DetPhysCore/include)
  • Everything above can be called from Blueprint (settings and results are integer-only USTRUCTs). When you use the sessions directly, your code drives Poll / Advance every frame. Add a match component to an Actor instead and it steps in Tick and reports what happened through Delegates (Blueprint "bind event").
  • Call Poll on a room link (relay, hub) every frame (the relay's ping and time-outs run there); the components do it themselves. Anything sent before the role (GetRole) is known is dropped (the session sends it again).
  • After OnTagMismatch, a UDetPhysRtMatchComponent session keeps waiting (the game decides whether to stop; the sample shows it and calls Stop). For UDetPhysStackMatchComponent the core turns a peer with a different config hash into ERROR, so OnFailed follows right after OnTagMismatch.
  • With the same settings, a 3D push session connects to Unity and Godot 3D push peers with the same settings, with the same confirmed tick hashes. A wrapper for your own transport written in C++ / Blueprint (a vtable given to detphys_link_create) is (planned). C++ can use all of them through the core's C ABI today.

DetPhys is not affiliated with Box2D or Box3D and is not endorsed or recommended by Box2D, Box3D or their author. It uses Box2D v3 and Box3D, both under the MIT license, as its physics.

LicensesMatches the current versions (2026-11)

© 2026 PetafProductsContactPrivacy

This site uses no analytics or tracking.

↑↓ to choose, Enter to open, Esc to close