Implement source-backed Scooter vehicle in tutorial and outside

This commit is contained in:
UnixNight committed 2026-11-04 18:06:09 -05:00
1 parent 8df5e81070
commit 62c07a3d59
44 files changed
+3135 -174

No files matched your search

+23 -3
View File
@@ -37,7 +37,8 @@ public sealed class ActorPatrol
public float WaitRemaining { get; private set; }
public string? CurrentWaypoint => waypoint?.Tag;
public string? PreviousWaypoint => previousWaypoint?.Tag;
public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6;
public bool FollowPlayer {get;set;}
public bool SupportedState => actor.AIstate is 1 or 3 or 7 or 9 || actor.Kind == "3CAR" && actor.AIstate == 6 || FollowPlayer&&actor.Kind=="3DOG"&&actor.AIstate==4;
public ActorPatrol(DirectorActor actor, Func<string, DirectorActor?> findActor,
Func<PatrolBodyState, float, PatrolBodyState> integrateBody,
@@ -86,7 +87,7 @@ public sealed class ActorPatrol
if (!float.IsFinite(dt) || dt < 0 || dt > 1) throw new ArgumentOutOfRangeException(nameof(dt));
SynchronizeAuthoredState();
if (!SupportedState) return false;
if (!actor.Active) return true;
if (!actor.Active||!actor.MovementEnabled) return true;
if (!float.IsFinite(actor.Speed)) throw new InvalidOperationException("Nonfinite Goddard speed");
// EXE408023->40E050: the body consumes the *previous* velocity first.
@@ -104,6 +105,7 @@ public sealed class ActorPatrol
{
case 1: Velocity = Vector3.Zero; break; // EXE40835D, after body integration.
case 3: StepPatrol(); break;
case 4: StepFollow(); break;
case 7: StepWait(dt); break;
// State9 jumps directly to the common finisher408911. State6 calls
// sensing409CC0 first; source player-contact dispatch is implemented
@@ -112,12 +114,30 @@ public sealed class ActorPatrol
}
// States1/6/7 return before selecting a destination angle (409186..19B).
// Retain the old destination on a waypoint change, as the source does.
if (actor.AIstate == 3 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0)
if (actor.AIstate is 3 or 4 && DestinationDelta.X * DestinationDelta.X + DestinationDelta.Z * DestinationDelta.Z > 0)
desiredYaw = MathF.Atan2(-DestinationDelta.X, DestinationDelta.Z) * (180 / MathF.PI);
Publish();
return true;
}
private void StepFollow()
{
var target=findActor("JIM1");if(target==null||!target.Active)return;
DestinationDelta=target.Position-actor.Position;DestinationDistance=DestinationDelta.Length();
var length=magnitude(DestinationDelta);
float multiplier=DestinationDistance>=2000?3:DestinationDistance>=1000?1.7f:1;
Velocity=Arrived||length==0?Vector3.Zero:DestinationDelta/length*(actor.Speed*multiplier);
if(DestinationDistance<ArrivalDistance)Arrived=true;
else if(DestinationDistance>ArrivalDistance*1.5f)Arrived=false;
actor.Speed=DestinationDistance>440?600:450;
if(DestinationDistance>1500)
{
actor.Position=target.Position+RocketOrientation.Rotate(new(0,0,-800),target.Rotation);
Velocity=Vector3.Zero;
}
actor.Animation=magnitude(Velocity)>20?"RUN":"WAG";
}
private void StepPatrol()
{
waypoint ??= findActor(actor.Patrol ?? "none");
+15 -1
View File
@@ -238,7 +238,7 @@ public sealed class LabSimulation
return ((float)Math.Sin(radians), (float)Math.Cos(radians));
}
public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null, Action? afterPhysics = null)
public void Step(PlayerInput input, bool controlled = true, bool? anyControlled = null, Action? afterPhysics = null,Func<bool>? controlledAfterPhysics=null)
{
if (Noclip)
{
@@ -251,6 +251,7 @@ public sealed class LabSimulation
// scene registry, original cadence or original collision response.
StepPhysics();
afterPhysics?.Invoke();
if(controlledAfterPhysics!=null)controlled=controlledAfterPhysics();
if (controlled && !InputAfterPlayerUpdate) StepInput(input);
//42469F..4246DC runs independently of raw ownership.
if (Grounded)
@@ -288,6 +289,19 @@ public sealed class LabSimulation
forceFall=true;CameraEye=sharedEye;
}
public void EnterScooter()
{
CancelPoweredFlight(); //425120 only cancels mode1 jump/effect.
TracksBubbleOrientation=true;
}
public void ApplyScooterTransform(Vector3 root,Vector3 rotation)
{ApplyAuthoredTransform(root,rotation.Y);Pitch=rotation.X;Roll=rotation.Z;targetPitch=Pitch;targetRoll=Roll;targetYaw=Yaw;}
public void LeaveScooter(Vector3 root,Vector3 rotation,Vector3 eye)
{
ApplyScooterTransform(root+Vector3.UnitY*40,rotation);
Velocity=Vector3.Zero;extraAirAcceleration=0;CameraEye=eye;
}
public void RocketImpact()
{
AdjustEnergy(-1);ScoreChanged?.Invoke(-1);CancelPoweredFlight();
+7 -1
View File
@@ -50,7 +50,8 @@ public sealed class OriginalBodyPhysics
public OrdinaryBodyStep Step(OrdinaryBodyState body, float seconds,
float radius = OriginalBodySupport.JimmyRadius, float factor = OriginalBodySupport.JimmyFactor,
float friction = .8f, float suppressionScale = .5f, bool geometryEnabled = true,
BodyResponseProfile profile = BodyResponseProfile.Jimmy)
BodyResponseProfile profile = BodyResponseProfile.Jimmy,
Func<OrdinaryBodyState,CameraRayPolygon,OrdinaryBodyState>? wallContact = null)
{
Finite(body.Position); Finite(body.Velocity); Finite(body.Acceleration); Finite(body.Impulse);
Finite(body.AngularVelocity); Finite(body.Rotation);
@@ -111,6 +112,11 @@ public sealed class OriginalBodyPhysics
}
}
var position = move.Position;
if(wallContact!=null&&move.CallbackPolygon is{StoredNormal.Y:>-.7f}terminal)
{
body=wallContact(body with{Position=position,Velocity=velocity,Acceleration=acceleration,Impulse=impulse},terminal);
position=body.Position;velocity=body.Velocity;acceleration=body.Acceleration;impulse=body.Impulse;
}
if (horizontalFirst) position.Y += delta.Y;
position.Y = MathF.Max(position.Y, -25000);
body = body with { Position = position, Velocity = velocity, Acceleration = acceleration, Impulse = impulse };
+1 -1
View File
@@ -69,7 +69,7 @@ public sealed class OriginalCameraRay
public static OriginalCameraRay FromRouteScene(Mesh mesh, string levelCode)
{
ArgumentNullException.ThrowIfNull(mesh);
if (levelCode is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR07" or "VR08" or "LEV1"))
if (levelCode is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1"))
throw new NotSupportedException("Static camera game-filter recovery covers only selected route/tutorial scenes");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Original camera query requires source polygon metadata");
+1 -1
View File
@@ -61,7 +61,7 @@ public sealed class OriginalStaticCollision
public static OriginalStaticCollision FromRouteScene(Mesh mesh, string level)
{
ArgumentNullException.ThrowIfNull(mesh);
if (level is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR07" or "VR08" or "LEV1"))
if (level is not ("LV1B" or "VR01" or "VR02" or "VR04" or "VR05" or "VR07" or "VR08" or "LEV1"))
throw new NotSupportedException("Original static game-filter recovery covers the route and VR01");
if (mesh.Indices.Length % 3 != 0 || mesh.CollisionPolygons.Length != mesh.Indices.Length / 3)
throw new InvalidDataException("Source static collision requires original polygon metadata");
+53 -10
View File
@@ -10,16 +10,18 @@ public sealed class PlayerSceneBinding : IDisposable
private readonly LabSimulation player;
private readonly SceneInventory inventory;
private readonly string tag;
public Scooter? Scooter {get;}
public Rocketship? Rocketship { get; }
public bool InventoryControlled=>director.InventoryEnabled&&(director.Controlled||
Rocketship is{Mounted:true} rocket&&director.ControlledTag==rocket.Actor.Tag);
Rocketship is{Mounted:true} rocket&&director.ControlledTag==rocket.Actor.Tag||
Scooter is{Mounted:true} scooter&&director.ControlledTag==scooter.Actor.Tag);
public int UnsupportedGadgetCleanups { get; private set; }
public PlayerSceneBinding(SceneDirector director, LabSimulation player, SceneInventory inventory, string tag,
Rocketship? rocketship=null)
Rocketship? rocketship=null,Scooter? scooter=null)
{
this.director = director; this.player = player; this.inventory = inventory; this.tag = tag;
Rocketship=rocketship;
Rocketship=rocketship;Scooter=scooter;
if(rocketship!=null)rocketship.RiderHit+=player.RocketImpact;
director.ActorPreparing += Prepare;
director.AuthoredTransformChanged += Transform;
@@ -34,12 +36,31 @@ public sealed class PlayerSceneBinding : IDisposable
public bool Step(PlayerInput input)
{
if(player.Noclip&&Rocketship?.Mounted==true)inventory.SelectGadget(-1);
if(player.Noclip&&(Rocketship?.Mounted==true||Scooter?.Spawned==true))inventory.SelectGadget(-1);
bool VehicleControl()=>Rocketship is{Mounted:true} r&&(director.AuthoredControlledTag==r.Actor.Tag||director.DebugForceControl);
var acceptsInput = director.Controlled || player.Noclip || VehicleControl();
bool ScooterControl()=>Scooter is{Mounted:true}s&&(director.AuthoredControlledTag==s.Actor.Tag||director.DebugForceControl);
var acceptsInput = director.Controlled || player.Noclip || VehicleControl()||ScooterControl();
Scooter?.StepBody(FixedStepClock.Step,input);
Rocketship?.StepBody(FixedStepClock.Step);
player.Step(input,(director.Controlled&&Rocketship?.Mounted!=true)||player.Noclip,director.ControlledTag!=null,
()=>{if(!player.InputAfterPlayerUpdate&&VehicleControl())Rocketship!.StepInput(input,FixedStepClock.Step);});
bool JimmyControl()=>(director.Controlled&&Rocketship?.Mounted!=true&&Scooter?.Mounted!=true)||player.Noclip;
player.Step(input,JimmyControl(),director.ControlledTag!=null,()=>
{
if(Scooter is{Spawned:true,Mounted:false}s&&!player.Noclip&&s.TryMount(player.ActorRoot,player.InteractionRadius))
{player.EnterScooter();director.TransferControl(s.Actor);}
if(!player.InputAfterPlayerUpdate)
{
if(VehicleControl())Rocketship!.StepInput(input,FixedStepClock.Step);
if(ScooterControl())Scooter!.StepInput(input,FixedStepClock.Step);
}
},JimmyControl);
Scooter?.StepFrame(input,FixedStepClock.Step);
if(Scooter is{Mounted:true}scooter)
{
player.ApplyScooterTransform(scooter.Root,scooter.Rotation);
director.TransferControl(scooter.Actor);
if(player.InputAfterPlayerUpdate&&ScooterControl())scooter.StepInput(input,FixedStepClock.Step);
}
Scooter?.StepWheels();
Rocketship?.StepFrame(input,FixedStepClock.Step);
if(Rocketship is{Mounted:true} rocket)
{
@@ -69,13 +90,25 @@ public sealed class PlayerSceneBinding : IDisposable
if (!string.Equals(actor.Tag, tag, StringComparison.OrdinalIgnoreCase)) return;
//427FF0 switches raw mode, not display selection. A rejected Invisible
//equip can leave display2 with raw mode-1; cleanup does not equip it.
if (player.GadgetMode is 0 or 1 or 2 or 6 or 7 || inventory.SelectedGadget is -1 or 3)
if (player.GadgetMode is 0 or 1 or 2 or 4 or 6 or 7 || inventory.SelectedGadget is -1 or 3)
{ inventory.SelectGadget(-1); player.GadgetMode = -1; }
else if (player.GadgetMode != -1) UnsupportedGadgetCleanups++;
}
private void Selected(int item)
{
if(Scooter is{Spawned:true}scooter)
{
bool mounted=scooter.Mounted;
if(director.FindActor("C3DGODDARD") is{} dog)
{dog.Position=scooter.Root;dog.Rotation=scooter.Rotation;dog.Visible=dog.BodyEnabled=dog.MovementEnabled=true;}
scooter.Release();
if(mounted)
{
player.LeaveScooter(scooter.Root,scooter.Rotation,scooter.CameraEye);
if(director.FindActor(tag) is{} rider){rider.Animation="RUN";director.TransferControl(rider);}
}
}
if(Rocketship?.Mounted==true)
{
Rocketship.Release();
@@ -85,7 +118,16 @@ public sealed class PlayerSceneBinding : IDisposable
if (item==0 && director.FindActor(tag) is{} actor) player.SeedBubbleTilt(actor.Rotation);
//The display tile remains available for Practice outside the bounded
//live scene; unsupported selection must not invent a Jimmy flight mode.
player.GadgetMode=item==1&&Rocketship==null?-1:GadgetScreen.EquippedMode(item);
player.GadgetMode=item==1&&Rocketship==null||item==4&&Scooter==null?-1:GadgetScreen.EquippedMode(item);
if(item==4&&Scooter!=null)
{
if(director.FindActor("C3DGODDARD") is{} dog&&dog.BodyEnabled)
{
Scooter.Summon(dog.Position,dog.Rotation,player.CameraEye);
dog.Visible=dog.BodyEnabled=dog.MovementEnabled=false;
}
else player.GadgetMode=-1;
}
if(item==1&&Rocketship!=null)
{
var rider=director.FindActor(tag)!;
@@ -97,8 +139,9 @@ public sealed class PlayerSceneBinding : IDisposable
public void ResetVehicle()
{
if(Rocketship?.Mounted==true)inventory.SelectGadget(-1);
if(Rocketship?.Mounted==true||Scooter?.Spawned==true)inventory.SelectGadget(-1);
Rocketship?.Reset();
Scooter?.Reset();
}
private void DefaultGadget() => inventory.SelectGadget(-1);
+12
View File
@@ -183,6 +183,18 @@ public sealed class SceneDirector
public DirectorActor? FindActor(string tag) => actors.GetValueOrDefault(tag);
internal DirectorActor AddOwnedActor(string tag,string kind,Vector3 root)
{
if(actors.TryGetValue(tag,out var existing))return existing;
var actor=new DirectorActor(null,tag,kind,root);Actors.Add(actor);actors.Add(tag,actor);return actor;
}
public DirectorActor EnsureCompanion(Vector3 root,Vector3 rotation)
{
var actor=AddOwnedActor("C3DGODDARD","3DOG",root);
actor.Position=root;actor.Rotation=rotation;actor.AIstate=4;actor.Speed=450;return actor;
}
internal void TransferControl(DirectorActor actor)
{
if(!Actors.Contains(actor))throw new ArgumentException("Control requires a registered actor",nameof(actor));
+3 -3
View File
@@ -81,7 +81,7 @@ public sealed class SceneInteractions
{
if (!float.IsFinite(activePlayerRoot.X + activePlayerRoot.Y + activePlayerRoot.Z)
|| !float.IsFinite(playerRadius) || playerRadius < 0) throw new ArgumentOutOfRangeException(nameof(activePlayerRoot));
bool VehicleControlled()=>vehicle is{Kind:"3ROC"}&&director.AuthoredControlledTag==vehicle.Tag;
bool VehicleControlled()=>vehicle is{Kind:"3ROC" or "3JEE"}&&director.AuthoredControlledTag==vehicle.Tag;
bool Controlled()=>director.Controlled||VehicleControlled();
if (!Controlled()) return;
HideCollected();
@@ -97,9 +97,9 @@ public sealed class SceneInteractions
if (!director.Controlled) break;
}
// Carl InitObject413E2F..45 sets radius100 and support factor0.75.
//435D08 pickups require the raw controlled ship.457EE6 LOAD requires
//435D08 pickups require the raw controlled actor.457EE6 LOAD requires
//the real Jimmy passenger; the coincident actors keep distinct radii.
var contactRadius=source.Kind=="3PIC"&&VehicleControlled()?50:playerRadius;
var contactRadius=source.Kind=="3PIC"&&VehicleControlled()?(vehicle!.Kind=="3JEE"?150:50):playerRadius;
var radius = contactRadius + (source.Kind == "3TRO" ? 20 : source.Kind == "3CAR" ? 100 : source.Number("Radius"));
var overlaps = actor.Active && (source.Kind!="3TRO" || actor.BodyEnabled)
&& OriginalBodySupport.QuickMagnitude(activePlayerRoot - actor.Position) < radius;
+155
View File
@@ -0,0 +1,155 @@
using System.Numerics;
using GamePort.Assets;
namespace GamePort.Game;
/// <summary>Jimmy's owned C3DJEEP, summoned at Goddard and mounted by contact.
/// Ordinary source vehicle/wheel profile is admitted in VR05 and outsideLEV1.</summary>
public sealed class Scooter : IDisposable
{
private readonly OriginalStaticCollision world;
private readonly OriginalBodyPhysics physics;
private readonly Dictionary<(int,int),Vector3> normals;
private readonly ScooterWheels wheels=new();
private OrdinaryBodyState body;
private Vector3 destination;
private float poseClock,faceRate=5,impactTime;
private bool jumpLatch;
private Vector3? supportNormal;
public DirectorActor Actor{get;}
public bool Spawned{get;private set;}
public bool Mounted{get;private set;}
public bool ImpactActive{get;private set;}
public bool RiderStopped{get;private set;}
public bool EnginePlaying{get;private set;}
public Vector3 Root=>body.Position;
public Vector3 Rotation{get;private set;}
public Vector3 RiderRotation{get;private set;}
public Vector3 Velocity=>body.Velocity;
public Vector3 PendingImpulse=>body.Impulse;
public bool Supported=>body.Supported;
public ScooterSteering Steering{get;private set;}
public IReadOnlyList<Vector3> WheelRoots=>wheels.Roots;
public IReadOnlyList<Vector3> WheelRotations=>wheels.Rotations;
public int FrontSupports=>wheels.Front;
public int RearSupports=>wheels.Rear;
public int BodySteps{get;private set;}
public int InputSteps{get;private set;}
public int FrameSteps{get;private set;}
public int Contacts{get;private set;}
public int Jumps{get;private set;}
public Vector3 CameraEye{get;private set;}
public Vector3 CameraTarget{get;private set;}
public Func<Vector3,Vector3,float,Vector3>? DynamicRootResolver{get;set;}
public event Action? EngineStarted;
public event Action? EngineStopped;
public event Action<float>? EngineSpeedChanged;
public event Action? MountedChanged;
public Scooter(DirectorActor actor,Mesh mesh,string level)
{
if(level is not("VR05" or "LEV1"))throw new NotSupportedException("Scooter body profile covers VR05 and outsideLEV1");
Actor=actor;world=OriginalStaticCollision.FromRouteScene(mesh,level);
//421910 ordinary callback is independent of Jimmy's special materials.
physics=new(world,allowSpecialMaterials:true);
normals=mesh.CollisionPolygons.ToDictionary(p=>(p.ShapeId,p.PolygonIndex),p=>p.Normal);
Reset();
}
public void Reset()
{
Release();body=default;Steering=default;RiderRotation=Rotation=destination=Vector3.Zero;
faceRate=5;poseClock=impactTime=0;ImpactActive=jumpLatch=RiderStopped=false;wheels.Reset();
BodySteps=InputSteps=FrameSteps=Contacts=Jumps=0;
}
public void Summon(Vector3 root,Vector3 rotation,Vector3 eye)
{
body=body with{Position=root};RiderRotation=Rotation=destination=rotation;CameraEye=eye;CameraTarget=eye+Vector3.UnitZ*200;
Spawned=true;Actor.Visible=Actor.BodyEnabled=Actor.MovementEnabled=true;Sync();
}
public bool TryMount(Vector3 jimmyRoot,float radius)
{
if(!Spawned||Mounted||OriginalBodySupport.QuickMagnitude(Root-jimmyRoot)>=150+radius)return false;
Mounted=true;RiderStopped=false;poseClock=0;MountedChanged?.Invoke();return true;
}
public void Release()
{
Spawned=Mounted=false;Actor.Visible=Actor.BodyEnabled=Actor.MovementEnabled=false;
if(EnginePlaying){EnginePlaying=false;EngineStopped?.Invoke();}
}
public void StepBody(float dt,PlayerInput input)
{
if(!Spawned)return;
var result=physics.Step(body,dt,150,.2f,friction:.9f,suppressionScale:1,wallContact:(current,wall)=>
{body=current;Contact(wall.StoredNormal,input,dt);return body with{PublishedSpeed=Steering.Speed};});
body=result.Body;BodySteps++;
if(DynamicRootResolver!=null)body=body with{Position=DynamicRootResolver(result.PreviousPosition,Root,150)};
if(result.SupportHit is{} hit&&normals.TryGetValue((hit.ShapeId,hit.PolygonId),out var normal))
supportNormal=normal;
Sync();
}
public void StepInput(PlayerInput input,float dt)
{
if(!Mounted)return;InputSteps++;
var next=ScooterMotion.Input(Steering,input,RearSupports,dt);
Steering=ImpactActive?Steering with{Angle=next.Angle,KeyboardTurn=next.KeyboardTurn}:next;
var camera=ScooterCamera.Follow(Root,Rotation,CameraEye,dt,(start,end)=>
{
var context=physics.LastStaticContext??new(64.9519043f);
context.Nearest=context.Nearest with{FaceDistance=130000};
//413870 pushes false: camera reclip tests faces, not wheel/body edges.
return world.Move(start,end-start,64.9519043f,context,edges:false).Position;
},impact:ImpactActive);
CameraEye=camera.Eye;CameraTarget=camera.Target;
}
public void StepFrame(PlayerInput input,float dt)
{
if(!Spawned)return;
Rotation=ScooterWheels.Face(Rotation,destination,faceRate,dt);
if(ImpactActive)
{
var impact=ScooterMotion.Impact(Velocity,body.AngularVelocity,impactTime,dt);
impactTime=impact.Time;ImpactActive=impact.Active;
body=body with{Velocity=impact.Velocity,AngularVelocity=impact.AngularVelocity};
if(!ImpactActive)Steering=Steering with{Speed=0};
}
else
{
var drive=ScooterMotion.Apply(Steering,Velocity,Rotation,Supported,FrontSupports,RearSupports,dt,.9f);
Steering=drive.Steering;Rotation=drive.Rotation;body=body with{Velocity=drive.Velocity};
}
FrameSteps++;
if(Mounted)
{
if(!input.Jump)jumpLatch=false;
else if(!jumpLatch&&Supported){body=body with{Impulse=new(0,700,0)};jumpLatch=true;Jumps++;}
poseClock+=dt;
if((double)poseClock>.3){RiderStopped=Steering.Speed<10;poseClock=0;}
}
else {Steering=Steering with{Speed=0};faceRate=10;}
body=body with{PublishedSpeed=Steering.Speed};
//Jimmy copies the parent's Euler before the later wheel/lean phase.
RiderRotation=Rotation;
if(!EnginePlaying){EnginePlaying=true;EngineStarted?.Invoke();}
else EngineSpeedChanged?.Invoke(Steering.Speed);
Sync();
}
public void StepWheels()
{
if(!Spawned)return;
Rotation=Rotation with{Z=Steering.Angle*-.5f};
//Counts used by465220 are from the preceding wheel pass.
var oldFront=FrontSupports;var oldRear=RearSupports;
wheels.Update(Root,Rotation,Steering.Angle,Steering.Speed,Steering.Braking,ImpactActive,world);
if(oldFront+oldRear==0){destination=new(340,Rotation.Y,0);faceRate=2;}
else if(supportNormal is{} normal)destination=ScooterWheels.TerrainTarget(normal,Rotation.Y);
Sync();
}
private void Contact(Vector3 normal,PlayerInput input,float dt)
{
Contacts++;
var result=ScooterMotion.Contact(Steering.Speed,Velocity,Rotation,normal,body.Acceleration,ImpactActive,input.Forward||input.Fire,dt);
if(!ImpactActive&&result.Impact)impactTime=0;
ImpactActive=result.Impact;Steering=Steering with{Speed=result.Speed};body=body with{Acceleration=result.Acceleration};
}
private void Sync(){Actor.Position=Root;Actor.Rotation=Rotation;Actor.Speed=Steering.Speed;}
public void Dispose()=>Release();
}
+25
View File
@@ -0,0 +1,25 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct ScooterCameraResult(Vector3 Eye,Vector3 Target,Vector3 DesiredEye,Vector3 Look,float Gain);
/// <summary>4130A0 default mode1. Clipping follows smoothing and uses a sphere,
/// then look minus NEW eye determines source signed14-bit aim.</summary>
public static class ScooterCamera
{
public static ScooterCameraResult Follow(Vector3 root,Vector3 rotation,Vector3 oldEye,float dt,Func<Vector3,Vector3,Vector3>? clip=null,bool impact=false)
{
var desired=root+RocketOrientation.Rotate(new(-30,0,-200),rotation)+Vector3.UnitY*50;
var delta=desired-oldEye;var distance=OriginalBodySupport.QuickMagnitude(delta);
float gain=distance>400?2.8f:distance>200?1.7f:1;
var eye=oldEye+delta*dt*gain;
if(impact)
{
//413157..4131C0: approach root X/Z at .3; leave eye Y unchanged.
desired=new(root.X,oldEye.Y,root.Z);gain=.3f;eye=oldEye+(desired-oldEye)*dt*gain;
}
if(clip!=null)eye=clip(root,eye);
var look=impact?root:root+RocketOrientation.Rotate(new(0,50,100),rotation);
var(p,y)=OriginalHeading.Angles(look-eye);
var direction=RocketOrientation.Rotate(Vector3.UnitZ,new(p*.02197265625f,y*.02197265625f,0));
return new(eye,eye+direction*200,desired,look,gain);
}
}
+102
View File
@@ -0,0 +1,102 @@
using System.Numerics;
namespace GamePort.Game;
public readonly record struct ScooterSteering(float Speed=0,float Angle=0,bool KeyboardTurn=false,bool Reverse=false,
bool Braking=false,bool Throttle=false,float BrakeTime=0,float YawRate=0,float Blend=0);
public readonly record struct ScooterDrive(ScooterSteering Steering,Vector3 Velocity,Vector3 Rotation);
public readonly record struct ScooterContact(float Speed,Vector3 Acceleration,bool Impact);
public readonly record struct ScooterImpact(Vector3 Velocity,Vector3 AngularVelocity,float Time,bool Active);
/// <summary>465830 keyboard prefix and465220 ordinary non-AI/non-sprint drive.
/// Wheel/body support is observed independently; never fabricated here.</summary>
public static class ScooterMotion
{
public const float Maximum=1485;
/// <summary>421910 with the constructor's disabled bounce flag.</summary>
public static ScooterContact Contact(float speed,Vector3 velocity,Vector3 rotation,Vector3 normal,
Vector3 acceleration,bool impact,bool throttle,float dt)
{
float length=OriginalBodySupport.QuickMagnitude(velocity with{Y=0});
var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation);
if(!impact&&length>20&&MathF.Abs(Vector3.Dot(forward,normal))>=.9f)
return new(0,Vector3.Zero,true);
if(impact||speed<=0||length==0)return new(speed,acceleration,impact);
float dot=Vector3.Dot(velocity/OriginalBodySupport.QuickMagnitude(velocity),normal);
dot*=dot<-.85f?3.5f:1.5f;
if(dot<0&&throttle)speed=MathF.Max(230,speed-MathF.Abs(dot)*1200*dt);
return new(speed,acceleration,impact);
}
/// <summary>4669F0 ordinary enabled-body impact suffix.</summary>
public static ScooterImpact Impact(Vector3 velocity,Vector3 angular,float time,float dt)
{
time+=dt;
return time>=4?new(Vector3.Zero,Vector3.Zero,time,false):
new(velocity+new Vector3(-velocity.X*dt,0,-velocity.Z*dt),angular-angular*dt,time,true);
}
public static ScooterSteering Input(ScooterSteering state,PlayerInput input,int rear,float dt)
{
var angle=state.Angle;var keyboard=state.KeyboardTurn;
if(input.Left){angle+=200*dt;keyboard=true;}
else if(input.Right){angle-=200*dt;keyboard=true;}
else if(keyboard)angle=angle>0?MathF.Max(0,angle-200*dt):MathF.Min(0,angle+200*dt);
angle=Math.Clamp(angle,-45,45);float speed=state.Speed;bool reverse=state.Reverse,brake=state.Braking;
bool throttle=rear>0&&(input.Forward||input.Fire);
if(throttle){if(speed<Maximum)speed=MathF.Min(Maximum,speed+700*dt);reverse=false;}
if(rear>0&&input.Backward)
{
if(!reverse)
{
reverse=true;
if(speed>0){speed=MathF.Max(0,speed-1200*dt);brake=true;}
else if(speed<0){speed=MathF.Min(0,speed+1200*dt);brake=true;}
}
else speed=MathF.Max(-Maximum*.4f,speed-1200*dt);
}
else {brake=false;reverse=false;}
return state with{Speed=speed,Angle=angle,KeyboardTurn=keyboard,Reverse=reverse,Braking=brake,Throttle=throttle};
}
public static ScooterDrive Apply(ScooterSteering state,Vector3 velocity,Vector3 rotation,bool supported,int front,int rear,float dt,float friction=.9f)
{
float speed=state.Speed,rate=state.YawRate,blend=state.Blend,timer=state.BrakeTime;
var horizontal=velocity with{Y=0};var magnitude=OriginalBodySupport.QuickMagnitude(horizontal);
if(magnitude>0)
{
if(front>0)
{
rate=front*state.Angle*MathF.Min(magnitude*.005f,1);
var direction=horizontal/magnitude;var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation);
var delta=rate*dt*(Vector3.Dot(direction,forward)<0?-1:1);
rotation=RocketOrientation.Add(rotation,new(0,delta,0));
}
if(front+rear!=0)
{
if(!state.Throttle&&!state.Reverse)
{speed=(float)(speed-speed*.5f*dt);if(speed>=-1&&speed<=1)speed=0;}
if(!state.Braking)speed=(float)(speed-Math.Abs(state.Angle)*(1.0/45)*(speed*.8f)*dt);
speed=(float)(speed-Math.Sin(rotation.X*.01745329238474369f)*500*dt);
}
}
if(supported&&front+rear>=2)
{
var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation);var direction=forward;
var liveMagnitude=OriginalBodySupport.QuickMagnitude(velocity);
if(speed>0&&liveMagnitude!=0)
{
direction=velocity/liveMagnitude;
if(Vector3.Dot(direction,forward)<0)direction=forward;
if(!state.Braking)
{
var factor=(float)(2250*.6600000262260437f*.20000000298023224f/speed);
blend=MathF.Min(friction,friction*factor);
direction=new(direction.X+forward.X*blend,forward.Y,direction.Z+forward.Z*blend);
}
timer=0;
}
else if(state.Braking){timer+=dt;if(timer<1)speed=0;}
var next=direction*speed;
if(velocity.Y<0)next.Y+=velocity.Y;
velocity=next;
}
return new(state with{Speed=speed,YawRate=rate,Blend=blend,BrakeTime=timer},velocity,rotation);
}
}
+65
View File
@@ -0,0 +1,65 @@
using System.Numerics;
namespace GamePort.Game;
/// <summary>412A90 four-child setup and467080 post-normal wheel positioning.
/// Child support is queried manually; children have no independent integrator.</summary>
public sealed class ScooterWheels
{
public const float Radius=23.769514083862305f;
public static readonly Vector3[] Offsets=[new(-3,1,73),new(3,1,73),new(-3,1,-30),new(3,1,-30)];
private readonly Vector3[] roots=new Vector3[4],angles=new Vector3[4];
private readonly float[] spins=new float[4];
private readonly bool[] supported=new bool[4];
public IReadOnlyList<Vector3> Roots=>roots;
public IReadOnlyList<Vector3> Rotations=>angles;
public int Front=>supported.Take(2).Count(v=>v);
public int Rear=>supported.Skip(2).Count(v=>v);
public void Reset(){Array.Clear(roots);Array.Clear(angles);Array.Clear(spins);Array.Clear(supported);}
public void Update(Vector3 root,Vector3 rotation,float steering,float speed,bool braking,bool crash,OriginalStaticCollision world)
{
var forward=RocketOrientation.Rotate(Vector3.UnitZ,rotation);
for(int i=0;i<4;i++)
{
var before=roots[i];var local=Offsets[i];var desired=root+RocketOrientation.Rotate(local,rotation);
if(!crash)
{
var result=OriginalBodySupport.Resolve(new(desired,before,Vector3.Zero,Vector3.Zero,Radius,1,PreventLowering:false),
supported[i],(a,b,s)=>world.TraceSupport(a,b,s));
supported[i]=result.Supported;
var anchor=result.Supported?result.SupportAnchor.Y:-25000;
local.Y=Math.Clamp(local.Y+anchor-desired.Y,Offsets[i].Y-15,Offsets[i].Y+15);
}
roots[i]=root+RocketOrientation.Rotate(local,rotation);
var delta=(roots[i]-before) with{Y=0};var distance=OriginalBodySupport.QuickMagnitude(delta);
if(distance!=0&&(speed<0||!braking))
spins[i]=RocketOrientation.AddAxis(spins[i],(float)(distance/Radius*57.295776f)*(Vector3.Dot(delta,forward)>0?1:-1));
angles[i]=i%2==0
?new(rotation.Z,RocketOrientation.AddAxis(rotation.Y,90),RocketOrientation.AddAxis(rotation.X,-spins[i]))
:new(RocketOrientation.AddAxis(0,-rotation.Z),RocketOrientation.AddAxis(rotation.Y,-90),RocketOrientation.AddAxis(rotation.X,spins[i]));
if(i<2)angles[i]=RocketOrientation.Add(angles[i],RocketOrientation.Rotate(new(0,steering,0),rotation));
}
}
public static Vector3 TerrainTarget(Vector3 normal,float yaw)
{
var(_,x)=OriginalHeading.Angles(new(normal.X,0,normal.Y));
var(_,z)=OriginalHeading.Angles(new(normal.Z,0,normal.Y));
var index=(int)((double)yaw*45.511112213134766)&16383;
var(sine,cosine)=RocketOrientation.Units(index);
//Source table cardinal endpoints are exact, rather than Math.Cos(pi/2)'s residue.
if((index&4095)==0){sine=index switch{4096=>1,12288=>-1,_=>0};cosine=index switch{0=>1,8192=>-1,_=>0};}
var components=new Vector3((float)(-x*(double)cosine-z*(double)sine),0,
(float)(-z*(double)cosine+x*(double)sine))*.02197265625f;
return new(RocketOrientation.AddAxis(0,-components.Z),yaw,RocketOrientation.AddAxis(0,components.X));
}
public static Vector3 Face(Vector3 rotation,Vector3 target,float rate,float dt)
{
float Axis(float current,float desired)
{
float delta=desired-current;
if(delta>=180)delta-=360;else if(delta< -180)delta+=360;
float gain=dt*rate;float step=delta*gain;
return MathF.Abs(step)<gain?desired:current+step;
}
return new(Axis(rotation.X,target.X),Axis(rotation.Y,target.Y),Axis(rotation.Z,target.Z));
}
}