Compare commits
6 Commits
964b46e1c5
...
0905876b99
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0905876b99 | ||
|
|
55a178e8c5 | ||
|
|
f0f89ff947 | ||
|
|
4912d0ae1a | ||
|
|
4899a38265 | ||
|
|
629ae6715c |
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"Longitudinal": {
|
||||
"B": 18,
|
||||
"C": 1.5,
|
||||
"D": 1.5,
|
||||
"E": 0.3
|
||||
},
|
||||
"Lateral": {
|
||||
"B": 12,
|
||||
"C": 1.3,
|
||||
"D": 1.8,
|
||||
"E": -1.8
|
||||
},
|
||||
"Aligning": {
|
||||
"B": 2.8,
|
||||
"C": 2.1,
|
||||
"D": 0.1,
|
||||
"E": -2.5
|
||||
},
|
||||
"__references": [],
|
||||
"__version": 0
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
{
|
||||
"Longitudinal": {
|
||||
"B": 0,
|
||||
"C": 1,
|
||||
"D": 1,
|
||||
"E": 0.3
|
||||
},
|
||||
"Lateral": {
|
||||
"B": 1,
|
||||
"C": 1,
|
||||
"D": 1,
|
||||
"E": 0.3
|
||||
},
|
||||
"Aligning": {
|
||||
"B": 2.8,
|
||||
"C": 2.1,
|
||||
"D": 0.1,
|
||||
"E": -2.5
|
||||
},
|
||||
"__references": [],
|
||||
"__version": 0
|
||||
}
|
||||
20
Assets/frictions/default.tire
Normal file
20
Assets/frictions/default.tire
Normal file
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"Pacejka": {
|
||||
"Lateral": {
|
||||
"B": 12,
|
||||
"C": 1.3,
|
||||
"D": 1.8,
|
||||
"E": -1.8
|
||||
},
|
||||
"Longitudinal": {
|
||||
"B": 10.86,
|
||||
"C": 2.15,
|
||||
"D": 2,
|
||||
"E": 0.992
|
||||
}
|
||||
},
|
||||
"RollResistanceLin": 0.001,
|
||||
"RollResistanceQuad": 1E-06,
|
||||
"__references": [],
|
||||
"__version": 0
|
||||
}
|
||||
@@ -3,7 +3,7 @@ using System;
|
||||
|
||||
namespace VeloX.Powertrain;
|
||||
|
||||
[Category( "VeloX/Powertrain/Gearbox" )]
|
||||
[Category( "VeloX/Powertrain/Differential" )]
|
||||
public abstract class BaseDifferential : PowertrainComponent
|
||||
{
|
||||
[Property] public float FinalDrive { get; set; } = 3.392f;
|
||||
|
||||
@@ -8,8 +8,6 @@ public class Engine : PowertrainComponent
|
||||
[Property, Group( "Settings" )] public float IdleRPM { get; set; } = 900f;
|
||||
[Property, Group( "Settings" )] public float MaxRPM { get; set; } = 7000f;
|
||||
[Property, Group( "Settings" )] public override float Inertia { get; set; } = 0.151f;
|
||||
[Property, Group( "Settings" )] public float StartFriction { get; set; } = 50f;
|
||||
[Property, Group( "Settings" )] public float FrictionCoeff { get; set; } = 0.02f;
|
||||
[Property, Group( "Settings" )] public float LimiterDuration { get; set; } = 0.05f;
|
||||
[Property, Group( "Settings" )] public Curve TorqueMap { get; set; }
|
||||
[Property, Group( "Settings" )] public EngineStream Stream { get; set; }
|
||||
@@ -24,6 +22,7 @@ public class Engine : PowertrainComponent
|
||||
private float finalTorque;
|
||||
|
||||
private EngineStreamPlayer StreamPlayer;
|
||||
public float[] friction = [15.438f, 2.387f, 0.7958f];
|
||||
|
||||
protected override void OnStart()
|
||||
{
|
||||
@@ -32,11 +31,19 @@ public class Engine : PowertrainComponent
|
||||
StreamPlayer = new( Stream );
|
||||
}
|
||||
|
||||
public float GetFrictionTorque( float throttle, float rpm )
|
||||
{
|
||||
float s = rpm < 0 ? -1f : 1f;
|
||||
float r = s * rpm * 0.001f;
|
||||
float f = friction[0] + friction[1] * r + friction[2] * r * r;
|
||||
return -s * f * (1 - throttle);
|
||||
}
|
||||
private float GenerateTorque()
|
||||
{
|
||||
float throttle = Throttle;
|
||||
float rpm = RPM;
|
||||
float friction = StartFriction - rpm * FrictionCoeff;
|
||||
float friction = GetFrictionTorque( throttle, rpm );
|
||||
|
||||
float maxInitialTorque = TorqueMap.Evaluate( RPMPercent ) - friction;
|
||||
float idleFadeStart = Math.Clamp( MathX.Remap( rpm, IdleRPM - 300, IdleRPM, 1, 0 ), 0, 1 );
|
||||
float idleFadeEnd = Math.Clamp( MathX.Remap( rpm, IdleRPM, IdleRPM + 600, 1, 0 ), 0, 1 );
|
||||
@@ -70,6 +77,7 @@ public class Engine : PowertrainComponent
|
||||
float outputInertia = Output.QueryInertia();
|
||||
float inertiaSum = Inertia + outputInertia;
|
||||
float outputW = Output.QueryAngularVelocity( angularVelocity );
|
||||
|
||||
float targetW = Inertia / inertiaSum * angularVelocity + outputInertia / inertiaSum * outputW;
|
||||
float generatedTorque = GenerateTorque();
|
||||
float reactTorque = (targetW - angularVelocity) * Inertia / Time.Delta;
|
||||
|
||||
@@ -7,7 +7,11 @@ public class PowerWheel : PowertrainComponent
|
||||
{
|
||||
[Property] public VeloXWheel Wheel { get; set; }
|
||||
|
||||
public override float QueryInertia() => Wheel.Inertia;
|
||||
public override float QueryInertia()
|
||||
{
|
||||
float dtScale = Math.Clamp( Time.Delta, 0.01f, 0.05f ) / 0.005f;
|
||||
return Wheel.BaseInertia * dtScale;
|
||||
}
|
||||
|
||||
public override float QueryAngularVelocity( float angularVelocity )
|
||||
{
|
||||
@@ -19,7 +23,8 @@ public class PowerWheel : PowertrainComponent
|
||||
Wheel.AutoPhysics = false;
|
||||
Wheel.Torque = torque;
|
||||
Wheel.Brake = Vehicle.Brake;
|
||||
|
||||
Inertia = Wheel.BaseInertia + inertia;
|
||||
Wheel.Inertia = inertia;
|
||||
Wheel.DoPhysics( Vehicle );
|
||||
|
||||
angularVelocity = Wheel.AngularVelocity;
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
namespace VeloX;
|
||||
using Sandbox;
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
public abstract partial class VeloXBase
|
||||
{
|
||||
@@ -19,6 +22,20 @@ public abstract partial class VeloXBase
|
||||
foreach ( var v in Wheels )
|
||||
if ( v.AutoPhysics ) v.DoPhysics( this );
|
||||
|
||||
var totalSpeed = TotalSpeed + Math.Abs( Body.AngularVelocity.z );
|
||||
|
||||
var factor = 1 - Math.Clamp( totalSpeed / 30, 0, 1 );
|
||||
|
||||
if ( factor > 0.1f )
|
||||
{
|
||||
var vel = Body.Velocity;
|
||||
|
||||
var rt = WorldRotation.Right;
|
||||
|
||||
var force = rt.Dot( vel ) / Time.Delta * mass * factor * rt;
|
||||
Body.ApplyForce( -force );
|
||||
}
|
||||
|
||||
Body.ApplyTorque( angForce );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ public abstract partial class VeloXBase : Component
|
||||
[Property, Group( "Components" )] public Rigidbody Body { get; protected set; }
|
||||
[Property, Group( "Components" )] public Collider Collider { get; protected set; }
|
||||
|
||||
[Sync] public Angles SteerAngle { get; set; }
|
||||
[Sync( SyncFlags.Interpolate )] public Angles SteerAngle { get; set; }
|
||||
|
||||
public Vector3 LocalVelocity;
|
||||
public float ForwardSpeed;
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
public class FrictionPreset
|
||||
{
|
||||
public float B { get; set; } = 10.86f;
|
||||
public float C { get; set; } = 2.15f;
|
||||
public float D { get; set; } = 0.933f;
|
||||
public float E { get; set; } = 0.992f;
|
||||
public float Evaluate( float slip )
|
||||
{
|
||||
var t = Math.Abs( slip );
|
||||
|
||||
return D * MathF.Sin( C * MathF.Atan( B * t - E * (B * t - MathF.Atan( B * t )) ) );
|
||||
}
|
||||
}
|
||||
43
Code/Base/Wheel/Pacejka.cs
Normal file
43
Code/Base/Wheel/Pacejka.cs
Normal file
@@ -0,0 +1,43 @@
|
||||
using Sandbox;
|
||||
using Sandbox.Services;
|
||||
using System;
|
||||
using System.Threading;
|
||||
|
||||
namespace VeloX;
|
||||
public class Pacejka
|
||||
{
|
||||
public class PacejkaPreset
|
||||
{
|
||||
[KeyProperty] public float B { get; set; } = 10.86f;
|
||||
[KeyProperty] public float C { get; set; } = 2.15f;
|
||||
[KeyProperty] public float D { get; set; } = 0.933f;
|
||||
[KeyProperty] public float E { get; set; } = 0.992f;
|
||||
|
||||
public float Evaluate( float slip ) => D * MathF.Sin( C * MathF.Atan( B * slip - E * (B * slip - MathF.Atan( B * slip )) ) );
|
||||
|
||||
public float GetPeakSlip()
|
||||
{
|
||||
float peakSlip = -1;
|
||||
float yMax = 0;
|
||||
|
||||
for ( float i = 0; i < 1f; i += 0.01f )
|
||||
{
|
||||
float y = Evaluate( i );
|
||||
if ( y > yMax )
|
||||
{
|
||||
yMax = y;
|
||||
peakSlip = i;
|
||||
}
|
||||
}
|
||||
|
||||
return peakSlip;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public PacejkaPreset Lateral { get; set; } = new();
|
||||
public PacejkaPreset Longitudinal { get; set; } = new();
|
||||
|
||||
public float PacejkaFx( float slip ) => Longitudinal.Evaluate( slip );
|
||||
public float PacejkaFy( float slip ) => Lateral.Evaluate( slip );
|
||||
}
|
||||
18
Code/Base/Wheel/Suspension/BasicSuspension.cs
Normal file
18
Code/Base/Wheel/Suspension/BasicSuspension.cs
Normal file
@@ -0,0 +1,18 @@
|
||||
namespace VeloX;
|
||||
|
||||
public class BasicSuspension
|
||||
{
|
||||
private readonly Hinge Hinge;
|
||||
|
||||
public BasicSuspension( Vector3 wheel, Vector3 hingeBody, Vector3 hingeWheel )
|
||||
{
|
||||
Vector3 hingePoint = wheel - (hingeWheel - hingeBody);
|
||||
Hinge = new Hinge( hingePoint, hingeWheel - hingeBody );
|
||||
}
|
||||
|
||||
public virtual void GetWheelTransform( float travel, out Rotation rotation, out Vector3 position )
|
||||
{
|
||||
rotation = Rotation.Identity;
|
||||
position = Hinge.Rotate( travel );
|
||||
}
|
||||
}
|
||||
26
Code/Base/Wheel/Suspension/Hinge.cs
Normal file
26
Code/Base/Wheel/Suspension/Hinge.cs
Normal file
@@ -0,0 +1,26 @@
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
internal readonly struct Hinge( Vector3 hinge_anchor, Vector3 hinge_arm )
|
||||
{
|
||||
[Description( "the point that the wheels are rotated around as the suspension compresses" )]
|
||||
public readonly Vector3 Anchor = hinge_anchor;
|
||||
|
||||
[Description( "anchor to wheel vector" )]
|
||||
public readonly Vector3 Arm = hinge_arm;
|
||||
|
||||
[Description( "arm length squared" )]
|
||||
public readonly float LengthSquared = hinge_arm.Dot( hinge_arm );
|
||||
|
||||
[Description( "1 / arm length in hinge axis normal plane" )]
|
||||
public readonly float NormXY = 1 / MathF.Sqrt( hinge_arm.x * hinge_arm.x + hinge_arm.y * hinge_arm.y );
|
||||
|
||||
public readonly Vector3 Rotate( float travel )
|
||||
{
|
||||
float z = Arm.z + travel;
|
||||
float lengthSq = MathF.Max( LengthSquared - z * z, 0.0f );
|
||||
float nxy = NormXY * MathF.Sqrt( lengthSq );
|
||||
return Anchor + new Vector3( Arm.x * nxy, Arm.y * nxy, z );
|
||||
}
|
||||
}
|
||||
32
Code/Base/Wheel/Suspension/MacPhersonSuspension.cs
Normal file
32
Code/Base/Wheel/Suspension/MacPhersonSuspension.cs
Normal file
@@ -0,0 +1,32 @@
|
||||
using Sandbox;
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
public class MacPhersonSuspension
|
||||
{
|
||||
public readonly Vector3 WheelOffset;
|
||||
public readonly Vector3 UprightTop;
|
||||
public readonly Vector3 UprightAxis;
|
||||
private readonly Hinge Hinge;
|
||||
|
||||
public MacPhersonSuspension( Vector3 wheel, Vector3 strutBody, Vector3 strutWheel, Vector3 hingeBody )
|
||||
{
|
||||
WheelOffset = wheel - strutWheel;
|
||||
UprightTop = strutBody;
|
||||
UprightAxis = (strutBody - strutWheel).Normal;
|
||||
Hinge = new( hingeBody, strutWheel - hingeBody );
|
||||
}
|
||||
|
||||
public void GetWheelTransform( float travel, out Rotation rotation, out Vector3 position )
|
||||
{
|
||||
Vector3 hingeEnd = Hinge.Rotate( travel );
|
||||
Vector3 uprightAxisNew = (UprightTop - hingeEnd).Normal;
|
||||
|
||||
rotation = Rotation.FromAxis(
|
||||
Vector3.Cross( UprightAxis, uprightAxisNew ),
|
||||
MathF.Acos( Vector3.Dot( UprightAxis, uprightAxisNew ) ).RadianToDegree()
|
||||
);
|
||||
|
||||
position = hingeEnd + WheelOffset.Transform( rotation );
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,60 @@
|
||||
using Sandbox;
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
|
||||
[GameResource( "Wheel Friction", "whfric", "Wheel Friction", Category = "VeloX", Icon = "radio_button_checked" )]
|
||||
[GameResource( "Wheel Friction", "tire", "Wheel Friction", Category = "VeloX", Icon = "radio_button_checked" )]
|
||||
public class TirePreset : GameResource
|
||||
{
|
||||
public FrictionPreset Longitudinal { get; set; }
|
||||
public FrictionPreset Lateral { get; set; }
|
||||
public FrictionPreset Aligning { get; set; }
|
||||
|
||||
[Property] public Pacejka Pacejka { get; set; }
|
||||
|
||||
public float RollResistanceLin { get; set; } = 1E-3f;
|
||||
public float RollResistanceQuad { get; set; } = 1E-6f;
|
||||
|
||||
public float GetRollingResistance( float velocity, float resistance_factor )
|
||||
{ // surface influence on rolling resistance
|
||||
float resistance = resistance_factor * RollResistanceLin;
|
||||
|
||||
// heat due to tire deformation increases rolling resistance
|
||||
// approximate by quadratic function
|
||||
resistance += velocity * velocity * RollResistanceQuad;
|
||||
|
||||
return resistance;
|
||||
}
|
||||
|
||||
public static void ComputeSlip( float lon_velocity, float lat_velocity, float rot_velocity, float wheel_radius, out float slip_ratio, out float slip_angle )
|
||||
{
|
||||
var abs_lon = Math.Max( MathF.Abs( lon_velocity ), 1e-3f );
|
||||
|
||||
slip_ratio = lon_velocity - rot_velocity * wheel_radius;
|
||||
|
||||
if ( abs_lon >= 0.005f )
|
||||
slip_ratio /= abs_lon;
|
||||
else
|
||||
slip_ratio *= abs_lon;
|
||||
|
||||
if ( abs_lon >= 0.5f )
|
||||
slip_angle = MathF.Atan2( -lat_velocity, abs_lon ).RadianToDegree() / 50f;
|
||||
else
|
||||
slip_angle = -lat_velocity * (0.01f / Time.Delta);
|
||||
|
||||
slip_ratio = Math.Clamp( slip_ratio, -1, 1 );
|
||||
slip_angle = Math.Clamp( slip_angle, -1, 1 );
|
||||
|
||||
}
|
||||
|
||||
/// approximate asin(x) = x + x^3/6 for +-18 deg range
|
||||
public static float ComputeCamberAngle( float sin_camber )
|
||||
{
|
||||
float sc = Math.Clamp( sin_camber, -0.3f, 0.3f );
|
||||
return ((1 / 6.0f) * (sc * sc) + 1) * sc;
|
||||
}
|
||||
|
||||
public static float ComputeCamberVelocity( float sa, float vx )
|
||||
{
|
||||
float tansa = (1 / 3.0f * (sa * sa) + 1) * sa;
|
||||
return tansa * vx;
|
||||
}
|
||||
}
|
||||
|
||||
28
Code/Base/Wheel/VeloXWheel.Sound.cs
Normal file
28
Code/Base/Wheel/VeloXWheel.Sound.cs
Normal file
@@ -0,0 +1,28 @@
|
||||
using Sandbox;
|
||||
using System;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
|
||||
public partial class VeloXWheel : Component
|
||||
{
|
||||
private RealTimeUntil expandSoundCD;
|
||||
private RealTimeUntil contractSoundCD;
|
||||
private void DoSuspensionSounds( VeloXBase vehicle, float change )
|
||||
{
|
||||
if ( change > 0.1f && expandSoundCD )
|
||||
{
|
||||
expandSoundCD = 0.3f;
|
||||
var sound = Sound.Play( vehicle.SuspensionUpSound, WorldPosition );
|
||||
sound.Volume = Math.Clamp( Math.Abs( change ) * 5f, 0, 0.5f );
|
||||
}
|
||||
|
||||
if ( change < -0.1f && contractSoundCD )
|
||||
{
|
||||
contractSoundCD = 0.3f;
|
||||
change = MathF.Abs( change );
|
||||
var sound = Sound.Play( change > 0.3f ? vehicle.SuspensionHeavySound : vehicle.SuspensionDownSound, WorldPosition );
|
||||
sound.Volume = Math.Clamp( change * 5f, 0, 1 );
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,16 @@
|
||||
using Sandbox;
|
||||
using Sandbox.Rendering;
|
||||
using Sandbox.Services;
|
||||
using Sandbox.UI;
|
||||
using System;
|
||||
using System.Collections.Specialized;
|
||||
using System.Diagnostics.Metrics;
|
||||
using System.Numerics;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using static Sandbox.CameraComponent;
|
||||
using static Sandbox.Package;
|
||||
using static Sandbox.SkinnedModelRenderer;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
@@ -13,15 +23,10 @@ public partial class VeloXWheel : Component
|
||||
[Property] public float Mass { get; set; } = 20;
|
||||
[Property] public float RollingResistance { get; set; } = 20;
|
||||
[Property] public float SlipCircleShape { get; set; } = 1.05f;
|
||||
|
||||
public FrictionPreset LongitudinalFrictionPreset => WheelFriction.Longitudinal;
|
||||
public FrictionPreset LateralFrictionPreset => WheelFriction.Lateral;
|
||||
public FrictionPreset AligningFrictionPreset => WheelFriction.Aligning;
|
||||
|
||||
[Property] public TirePreset WheelFriction { get; set; }
|
||||
[Property] public TirePreset TirePreset { get; set; }
|
||||
[Property] public float Width { get; set; } = 6;
|
||||
[Sync] public float SideSlip { get; private set; }
|
||||
[Sync] public float ForwardSlip { get; private set; }
|
||||
public float SideSlip { get; private set; }
|
||||
public float ForwardSlip { get; private set; }
|
||||
[Sync] public float Torque { get; set; }
|
||||
[Sync, Range( 0, 1 )] public float Brake { get; set; }
|
||||
[Property] float BrakePowerMax { get; set; } = 3000;
|
||||
@@ -30,6 +35,7 @@ public partial class VeloXWheel : Component
|
||||
[Property] public float CasterAngle { get; set; } = 7; // todo
|
||||
[Property] public float CamberAngle { get; set; } = -3;
|
||||
[Property] public float ToeAngle { get; set; } = 0.5f;
|
||||
[Property] public float Ackermann { get; set; } = 0;
|
||||
|
||||
[Property, Group( "Suspension" )] float SuspensionLength { get; set; } = 10;
|
||||
[Property, Group( "Suspension" )] float SpringStrength { get; set; } = 800;
|
||||
@@ -39,8 +45,8 @@ public partial class VeloXWheel : Component
|
||||
|
||||
public float Spin { get; private set; }
|
||||
|
||||
public float RPM { get => angularVelocity * 60f / MathF.Tau; set => angularVelocity = value / (60 / MathF.Tau); }
|
||||
public float AngularVelocity => angularVelocity;
|
||||
public float RPM { get => angularVelocity * 30f / MathF.PI; set => angularVelocity = value / (30f / MathF.PI); }
|
||||
public float AngularVelocity { get => angularVelocity; set => angularVelocity = value; }
|
||||
|
||||
internal float DistributionFactor { get; set; }
|
||||
|
||||
@@ -54,21 +60,23 @@ public partial class VeloXWheel : Component
|
||||
private float angularVelocity;
|
||||
private float load;
|
||||
private float lastFraction;
|
||||
private RealTimeUntil expandSoundCD;
|
||||
private RealTimeUntil contractSoundCD;
|
||||
|
||||
private Vector3 contactPos;
|
||||
private Vector3 forward;
|
||||
private Vector3 right;
|
||||
private Vector3 up;
|
||||
|
||||
private Friction forwardFriction;
|
||||
private Friction sideFriction;
|
||||
private float forwardFriction;
|
||||
private float sideFriction;
|
||||
private Vector3 force;
|
||||
public float CounterTorque { get; private set; }
|
||||
|
||||
private float BaseInertia => 0.5f * Mass * MathF.Pow( Radius.InchToMeter(), 2 );
|
||||
public float Inertia => BaseInertia;
|
||||
internal float BaseInertia => 0.5f * Mass * MathF.Pow( Radius.InchToMeter(), 2 );
|
||||
public float Inertia
|
||||
{
|
||||
get => BaseInertia + inertia;
|
||||
set => inertia = value;
|
||||
}
|
||||
|
||||
|
||||
protected override void OnAwake()
|
||||
@@ -78,24 +86,6 @@ public partial class VeloXWheel : Component
|
||||
StartPos = LocalPosition;
|
||||
}
|
||||
|
||||
private void DoSuspensionSounds( VeloXBase vehicle, float change )
|
||||
{
|
||||
if ( change > 0.1f && expandSoundCD )
|
||||
{
|
||||
expandSoundCD = 0.3f;
|
||||
var sound = Sound.Play( vehicle.SuspensionUpSound, WorldPosition );
|
||||
sound.Volume = Math.Clamp( Math.Abs( change ) * 5f, 0, 0.5f );
|
||||
}
|
||||
|
||||
if ( change < -0.1f && contractSoundCD )
|
||||
{
|
||||
contractSoundCD = 0.3f;
|
||||
change = MathF.Abs( change );
|
||||
var sound = Sound.Play( change > 0.3f ? vehicle.SuspensionHeavySound : vehicle.SuspensionDownSound, WorldPosition );
|
||||
sound.Volume = Math.Clamp( change * 5f, 0, 1 );
|
||||
}
|
||||
}
|
||||
|
||||
internal void Update( VeloXBase vehicle, in float dt )
|
||||
{
|
||||
UpdateVisuals( vehicle, dt );
|
||||
@@ -103,94 +93,102 @@ public partial class VeloXWheel : Component
|
||||
|
||||
private void UpdateVisuals( VeloXBase vehicle, in float dt )
|
||||
{
|
||||
var entityAngles = vehicle.WorldRotation;
|
||||
|
||||
Spin -= angularVelocity.MeterToInch() * dt;
|
||||
|
||||
|
||||
var steerRotated = entityAngles.RotateAroundAxis( Vector3.Up, vehicle.SteerAngle.yaw * SteerMultiplier + ToeAngle );
|
||||
var camberRotated = steerRotated.RotateAroundAxis( Vector3.Forward, -CamberAngle );
|
||||
var angularVelocityRotated = camberRotated.RotateAroundAxis( Vector3.Right, Spin );
|
||||
|
||||
WorldRotation = angularVelocityRotated;
|
||||
|
||||
Spin -= angularVelocity.RadianToDegree() * dt;
|
||||
WorldRotation = vehicle.WorldTransform.RotationToWorld( GetSteer( vehicle.SteerAngle.yaw ) ) * Rotation.FromAxis( Vector3.Right, Spin );
|
||||
}
|
||||
|
||||
private (float, float, float, float) StepLongitudinal( float Vx, float Lc, float kFx, float kSx)
|
||||
private Rotation GetSteer( float steer )
|
||||
{
|
||||
float Tm = Torque;
|
||||
float Tb = Brake * BrakePowerMax + RollingResistance;
|
||||
float R = Radius.InchToMeter();
|
||||
float I = Inertia;
|
||||
|
||||
float Winit = angularVelocity;
|
||||
float W = angularVelocity;
|
||||
float angle = (-steer * SteerMultiplier).DegreeToRadian();
|
||||
|
||||
float VxAbs = MathF.Abs( Vx );
|
||||
float t = MathF.Tan( (MathF.PI / 2) - angle ) - Ackermann;
|
||||
float steering_angle = MathF.CopySign( float.Pi / 2, t ) - MathF.Atan( t );
|
||||
var steering_axis = Vector3.Up * MathF.Cos( -CasterAngle.DegreeToRadian() ) +
|
||||
Vector3.Right * MathF.Sin( -CasterAngle.DegreeToRadian() );
|
||||
|
||||
return Rotation.FromAxis( Vector3.Forward, -CamberAngle ) * Rotation.FromAxis( steering_axis, steering_angle.RadianToDegree() );
|
||||
}
|
||||
|
||||
|
||||
private static float GetLongitudinalLoadCoefficient( float load ) => 11000 * (1 - MathF.Exp( -0.00014f * load ));
|
||||
private static float GetLateralLoadCoefficient( float load ) => 18000 * (1 - MathF.Exp( -0.0001f * load ));
|
||||
private float inertia;
|
||||
|
||||
|
||||
private (float, float, float, float) StepLongitudinal( float Tm, float Tb, float Vx, float W, float Lc, float R, float I )
|
||||
{
|
||||
float wInit = W;
|
||||
float vxAbs = Math.Abs( Vx );
|
||||
float Sx;
|
||||
if ( VxAbs >= 0.1f )
|
||||
Sx = (Vx - W * R) / VxAbs;
|
||||
|
||||
if ( Lc < 0.01f )
|
||||
{
|
||||
Sx = 0;
|
||||
}
|
||||
else if ( vxAbs >= 0.01f )
|
||||
{
|
||||
Sx = (W * R - Vx) / vxAbs;
|
||||
}
|
||||
else
|
||||
Sx = (Vx - W * R) * 0.6f;
|
||||
{
|
||||
Sx = (W * R - Vx) * 0.6f;
|
||||
}
|
||||
|
||||
Sx = Math.Clamp( Sx * kSx, -1, 1 );
|
||||
Sx = Math.Clamp( Sx, -1, 1 );
|
||||
|
||||
W += Tm / I * Time.Delta;
|
||||
|
||||
Tb *= W > 0 ? -1 : 1;
|
||||
|
||||
float TbCap = MathF.Abs( W ) * I / Time.Delta;
|
||||
float Tbr = MathF.Abs( Tb ) - MathF.Abs( TbCap );
|
||||
Tbr = MathF.Max( Tbr, 0 );
|
||||
Tb = Math.Clamp( Tb, -TbCap, TbCap );
|
||||
float tbCap = Math.Abs( W ) * I / Time.Delta;
|
||||
float tbr = Math.Abs( Tb ) - Math.Abs( tbCap );
|
||||
tbr = Math.Max( tbr, 0 );
|
||||
|
||||
Tb = Math.Clamp( Tb, -tbCap, tbCap );
|
||||
|
||||
W += Tb / I * Time.Delta;
|
||||
|
||||
float maxTorque = LongitudinalFrictionPreset.Evaluate( Sx ) * Lc * kFx;
|
||||
float maxTorque = TirePreset.Pacejka.PacejkaFx( Math.Abs( Sx ) ) * Lc * R;
|
||||
|
||||
float errorTorque = (W - Vx / R) * I / Time.Delta;
|
||||
|
||||
float surfaceTorque = MathX.Clamp( errorTorque, -maxTorque, maxTorque );
|
||||
float surfaceTorque = Math.Clamp( errorTorque, -maxTorque, maxTorque );
|
||||
|
||||
W -= surfaceTorque / I * Time.Delta;
|
||||
|
||||
float Fx = surfaceTorque / R;
|
||||
|
||||
|
||||
Tbr *= W > 0 ? -1 : 1;
|
||||
float TbCap2 = MathF.Abs( W ) * I / Time.Delta;
|
||||
|
||||
float Tb2 = Math.Clamp( Tbr, -TbCap2, TbCap2 );
|
||||
|
||||
tbr *= (W > 0 ? -1 : 1);
|
||||
float TbCap2 = Math.Abs( W ) * I / Time.Delta;
|
||||
float Tb2 = Math.Clamp( tbr, -TbCap2, TbCap2 );
|
||||
W += Tb2 / I * Time.Delta;
|
||||
|
||||
float deltaOmegaTorque = (W - Winit) * I / Time.Delta;
|
||||
|
||||
float deltaOmegaTorque = (W - wInit) * I / Time.Delta;
|
||||
float Tcnt = -surfaceTorque + Tb + Tb2 - deltaOmegaTorque;
|
||||
if ( Lc < 0.001f )
|
||||
Sx = 0;
|
||||
|
||||
return (W, Sx, Fx, Tcnt);
|
||||
}
|
||||
|
||||
private (float, float) StepLateral( float Vx, float Vy, float Lc, float kFy, float kSy)
|
||||
private void StepLateral( float Vx, float Vy, float Lc, out float Sy, out float Fy )
|
||||
{
|
||||
float VxAbs = MathF.Abs( Vx );
|
||||
float Sy;
|
||||
float VxAbs = Math.Abs( Vx );
|
||||
|
||||
if ( VxAbs > 0.1f )
|
||||
Sy = MathF.Atan( Vy / VxAbs ).RadianToDegree() * 0.01111f;
|
||||
else
|
||||
Sy = Vy * (0.003f / Time.Delta);
|
||||
|
||||
|
||||
Sy *= kSy * 0.95f;
|
||||
Sy = Math.Clamp( Sy * kSy, -1, 1 );
|
||||
float Fy = -MathF.Sign( Sy ) * LateralFrictionPreset.Evaluate( Sy ) * Lc * kFy;
|
||||
if ( Lc < 0.0001f )
|
||||
if ( Lc < 0.01f )
|
||||
{
|
||||
Sy = 0;
|
||||
}
|
||||
else if ( VxAbs > 0.1f )
|
||||
{
|
||||
|
||||
return (Sy, Fy);
|
||||
Sy = MathX.RadianToDegree( MathF.Atan( Vy / VxAbs ) ) / 50;
|
||||
}
|
||||
else
|
||||
{
|
||||
|
||||
Sy = Vy * (0.003f / Time.Delta);
|
||||
}
|
||||
|
||||
Sy = Math.Clamp( Sy, -1, 1 );
|
||||
float slipSign = Sy < 0 ? -1 : 1;
|
||||
Fy = -slipSign * TirePreset.Pacejka.PacejkaFy( Math.Abs( Sy ) ) * Lc;
|
||||
}
|
||||
|
||||
private void SlipCircle( float Sx, float Sy, float Fx, ref float Fy )
|
||||
@@ -198,39 +196,23 @@ public partial class VeloXWheel : Component
|
||||
float SxAbs = Math.Abs( Sx );
|
||||
if ( SxAbs > 0.01f )
|
||||
{
|
||||
|
||||
float SxClamped = Math.Clamp( Sx, -1, 1 );
|
||||
|
||||
float SyClamped = Math.Clamp( Sy, -1, 1 );
|
||||
|
||||
Vector2 combinedSlip = new(
|
||||
SxClamped * SlipCircleShape,
|
||||
SyClamped
|
||||
);
|
||||
|
||||
Vector2 combinedSlip = new( SxClamped * 1.05f, SyClamped );
|
||||
Vector2 slipDir = combinedSlip.Normal;
|
||||
|
||||
float F = MathF.Sqrt( Fx * Fx + Fy * Fy );
|
||||
float absSlipDirY = Math.Abs( slipDir.y );
|
||||
|
||||
float absSlipDirY = MathF.Abs( slipDir.y );
|
||||
|
||||
Fy = F * absSlipDirY * MathF.Sign( Fy );
|
||||
Fy = F * absSlipDirY * (Fy < 0 ? -1 : 1);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private static float GetLongitudinalLoadCoefficient( float load ) => 11000 * (1 - MathF.Exp( -0.00014f * load ));
|
||||
private static float GetLateralLoadCoefficient( float load ) => 18000 * (1 - MathF.Exp( -0.0001f * load ));
|
||||
|
||||
public void DoPhysics( VeloXBase vehicle )
|
||||
{
|
||||
var pos = vehicle.WorldTransform.PointToWorld( StartPos );
|
||||
|
||||
var ang = vehicle.WorldTransform.RotationToWorld( vehicle.SteerAngle * SteerMultiplier );
|
||||
|
||||
forward = ang.Forward;
|
||||
right = ang.Right;
|
||||
up = ang.Up;
|
||||
var ang = vehicle.WorldTransform.RotationToWorld( GetSteer( vehicle.SteerAngle.yaw ) );
|
||||
|
||||
var maxLen = SuspensionLength;
|
||||
|
||||
@@ -240,112 +222,95 @@ public partial class VeloXWheel : Component
|
||||
.Cylinder( Width, Radius, pos, endPos )
|
||||
.Rotated( vehicle.WorldTransform.Rotation * CylinderOffset )
|
||||
.UseRenderMeshes( false )
|
||||
.UseHitPosition( false )
|
||||
.UseHitPosition( true )
|
||||
.WithoutTags( vehicle.WheelIgnoredTags )
|
||||
.Run();
|
||||
|
||||
forward = Vector3.VectorPlaneProject( ang.Forward, Trace.Normal );
|
||||
right = Vector3.VectorPlaneProject( ang.Right, Trace.Normal );
|
||||
|
||||
var fraction = Trace.Fraction;
|
||||
|
||||
contactPos = pos - maxLen * fraction * up;
|
||||
contactPos = pos - maxLen * fraction * ang.Up;
|
||||
|
||||
LocalPosition = vehicle.WorldTransform.PointToLocal( contactPos );
|
||||
|
||||
DoSuspensionSounds( vehicle, fraction - lastFraction );
|
||||
lastFraction = fraction;
|
||||
|
||||
var normal = Trace.Normal;
|
||||
|
||||
var vel = vehicle.Body.GetVelocityAtPoint( pos );
|
||||
|
||||
vel.x = vel.x.InchToMeter();
|
||||
vel.y = vel.y.InchToMeter();
|
||||
vel.z = vel.z.InchToMeter();
|
||||
|
||||
if ( !IsOnGround )
|
||||
{
|
||||
SideSlip = 0;
|
||||
ForwardSlip = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
var vel = vehicle.Body.GetVelocityAtPoint( contactPos );
|
||||
|
||||
var offset = maxLen - (fraction * maxLen);
|
||||
var springForce = (offset * SpringStrength);
|
||||
var springForce = offset * SpringStrength;
|
||||
var damperForce = (lastSpringOffset - offset) * SpringDamper;
|
||||
|
||||
lastSpringOffset = offset;
|
||||
force = (springForce - damperForce) * MathF.Max( 0, up.Dot( normal ) ) * normal / Time.Delta;
|
||||
|
||||
// Vector3.CalculateVelocityOffset is broken (need fix)
|
||||
//var velU = normal.Dot( vel ).MeterToInch();
|
||||
//if ( velU < 0 && offset + Math.Abs( velU * dt ) > SuspensionLength )
|
||||
//{
|
||||
// var (linearVel, angularVel) = vehicle.Body.PhysicsBody.CalculateVelocityOffset( (-velU.InchToMeter() / dt) * normal, pos );
|
||||
// vehicle.Body.Velocity += linearVel;
|
||||
// vehicle.Body.AngularVelocity += angularVel;
|
||||
//}
|
||||
|
||||
|
||||
load = springForce - damperForce;
|
||||
load = Math.Max( load, 0 );
|
||||
var velU = Trace.Normal.Dot( vel );
|
||||
|
||||
var longitudinalLoadCoefficient = GetLongitudinalLoadCoefficient( load );
|
||||
var lateralLoadCoefficient = GetLateralLoadCoefficient( load );
|
||||
|
||||
float forwardSpeed = 0;
|
||||
float sideSpeed = 0;
|
||||
|
||||
|
||||
if ( IsOnGround )
|
||||
if ( velU < 0 && offset + Math.Abs( velU * Time.Delta ) > SuspensionLength )
|
||||
{
|
||||
forwardSpeed = vel.Dot( forward );
|
||||
sideSpeed = vel.Dot( right );
|
||||
vehicle.Body.CalculateVelocityOffset( -velU / Time.Delta * Trace.Normal, pos, out var linearImp, out var angularImp );
|
||||
|
||||
vehicle.Body.Velocity += linearImp;
|
||||
vehicle.Body.AngularVelocity += angularImp;
|
||||
vehicle.Body.CalculateVelocityOffset( Trace.HitPosition - (contactPos + Trace.Normal * velU * Time.Delta), pos, out var lin, out _ );
|
||||
|
||||
vehicle.WorldPosition += lin / Time.Delta;
|
||||
damperForce = 0;
|
||||
|
||||
}
|
||||
(float W, float Sx, float Fx, float Tcnt) = StepLongitudinal(
|
||||
forwardSpeed,
|
||||
longitudinalLoadCoefficient,
|
||||
0.95f,
|
||||
0.9f
|
||||
|
||||
force = (springForce - damperForce) * Trace.Normal;
|
||||
|
||||
load = Math.Max( springForce - damperForce, 0 );
|
||||
float R = Radius.InchToMeter();
|
||||
|
||||
float forwardSpeed = vel.Dot( forward ).InchToMeter();
|
||||
float sideSpeed = vel.Dot( right ).InchToMeter();
|
||||
|
||||
float longitudinalLoadCoefficient = GetLongitudinalLoadCoefficient( load );
|
||||
float lateralLoadCoefficient = GetLateralLoadCoefficient( load );
|
||||
|
||||
float F_roll = TirePreset.GetRollingResistance( angularVelocity * R, 1.0f ) * 10000;
|
||||
|
||||
( float W, float Sx, float Fx, float counterTq) = StepLongitudinal(
|
||||
Torque,
|
||||
Brake * BrakePowerMax + F_roll,
|
||||
forwardSpeed,
|
||||
angularVelocity,
|
||||
longitudinalLoadCoefficient,
|
||||
R,
|
||||
Inertia
|
||||
);
|
||||
|
||||
(float Sy, float Fy) = StepLateral(
|
||||
forwardSpeed,
|
||||
sideSpeed,
|
||||
lateralLoadCoefficient,
|
||||
0.95f,
|
||||
0.9f
|
||||
);
|
||||
StepLateral( forwardSpeed, sideSpeed, lateralLoadCoefficient, out float Sy, out float Fy );
|
||||
|
||||
SlipCircle( Sx, Sy, Fx, ref Fy );
|
||||
|
||||
CounterTorque = counterTq;
|
||||
angularVelocity = W;
|
||||
CounterTorque = Tcnt;
|
||||
|
||||
forwardFriction = new Friction()
|
||||
{
|
||||
Slip = Sx,
|
||||
Force = Fx.MeterToInch(),
|
||||
Speed = forwardSpeed
|
||||
};
|
||||
force += forward * Fx;
|
||||
force += right * Fy * Math.Clamp( vehicle.TotalSpeed * 0.005f, 0, 1 );
|
||||
ForwardSlip = Sx;
|
||||
SideSlip = Sy * Math.Clamp( vehicle.TotalSpeed * 0.005f, 0, 1 );
|
||||
|
||||
sideFriction = new Friction()
|
||||
{
|
||||
Slip = Sy,
|
||||
Force = Fy.MeterToInch(),
|
||||
Speed = sideSpeed
|
||||
};
|
||||
|
||||
|
||||
var frictionforce = right * sideFriction.Force + forward * forwardFriction.Force;
|
||||
|
||||
vehicle.Body.ApplyForceAt( contactPos, force + frictionforce );
|
||||
vehicle.Body.ApplyForceAt( pos, force / Time.Delta );
|
||||
|
||||
}
|
||||
|
||||
|
||||
// debug
|
||||
#if DEBUG
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
DebugOverlay.Normal( contactPos, forward * forwardFriction.Force / 10000f, Color.Red, overlay: true );
|
||||
DebugOverlay.Normal( contactPos, right * sideFriction.Force / 10000f, Color.Green, overlay: true );
|
||||
DebugOverlay.Normal( contactPos, up * force / 50000f, Color.Blue, overlay: true );
|
||||
DebugOverlay.Normal( contactPos, forward * forwardFriction, Color.Red, overlay: true );
|
||||
DebugOverlay.Normal( contactPos, right * sideFriction, Color.Green, overlay: true );
|
||||
DebugOverlay.Normal( contactPos, up * force / 1000f, Color.Blue, overlay: true );
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
@@ -14,33 +14,40 @@ public partial class VeloXCar
|
||||
[Property, Feature( "Steer" )] public float MaxSteerAngle { get; set; } = 35f;
|
||||
|
||||
[Sync] public float Steering { get; private set; }
|
||||
private float jTurnMultiplier;
|
||||
|
||||
private float inputSteer;
|
||||
|
||||
public static float SignedAngle( Vector3 from, Vector3 to, Vector3 axis )
|
||||
{
|
||||
float unsignedAngle = Vector3.GetAngle( from, to );
|
||||
|
||||
float cross_x = from.y * to.z - from.z * to.y;
|
||||
float cross_y = from.z * to.x - from.x * to.z;
|
||||
float cross_z = from.x * to.y - from.y * to.x;
|
||||
float sign = MathF.Sign( axis.x * cross_x + axis.y * cross_y + axis.z * cross_z );
|
||||
return unsignedAngle * sign;
|
||||
}
|
||||
public float VelocityAngle { get; private set; }
|
||||
public int CarDirection { get { return ForwardSpeed.InchToMeter() < 5 ? 0 : (VelocityAngle < 90 && VelocityAngle > -90 ? 1 : -1); } }
|
||||
private void UpdateSteering( float dt )
|
||||
{
|
||||
var inputSteer = Input.AnalogMove.y;
|
||||
var absInputSteer = Math.Abs( inputSteer );
|
||||
|
||||
var sideSlip = Math.Clamp( 0, -1, 1 );
|
||||
|
||||
var steerConeFactor = Math.Clamp( TotalSpeed / SteerConeMaxSpeed, 0, 1 );
|
||||
var steerCone = 1 - steerConeFactor * (1 - SteerConeMaxAngle);
|
||||
VelocityAngle = 0;// -SignedAngle( Body.Velocity, WorldRotation.Forward, WorldRotation.Up );
|
||||
|
||||
steerCone = Math.Clamp( steerCone, Math.Abs( sideSlip ), 1 );
|
||||
//var steerConeFactor = Math.Clamp( TotalSpeed / SteerConeMaxSpeed, 0, 1 );
|
||||
//var steerCone = 1 - steerConeFactor * (1 - SteerConeMaxAngle);
|
||||
|
||||
inputSteer = ExpDecay( this.inputSteer, inputSteer * steerCone, SteerConeChangeRate, dt );
|
||||
inputSteer = ExpDecay( this.inputSteer, inputSteer, SteerConeChangeRate, dt );
|
||||
this.inputSteer = inputSteer;
|
||||
var counterSteer = sideSlip * steerConeFactor * (1 - absInputSteer);
|
||||
counterSteer = Math.Clamp( counterSteer, -1, 1 ) * CounterSteer;
|
||||
|
||||
inputSteer = Math.Clamp( inputSteer + counterSteer, -1, 1 );
|
||||
float target = -inputSteer * MaxSteerAngle;
|
||||
if ( CarDirection > 0 )
|
||||
target -= VelocityAngle * CounterSteer;
|
||||
|
||||
inputSteer = Math.Clamp( inputSteer, -1, 1 );
|
||||
Steering = inputSteer;
|
||||
SteerAngle = new( 0, inputSteer * MaxSteerAngle, 0 );
|
||||
|
||||
if ( ForwardSpeed < -100 )
|
||||
jTurnMultiplier = 0.5f;
|
||||
else
|
||||
jTurnMultiplier = ExpDecay( jTurnMultiplier, 1, 2, dt );
|
||||
SteerAngle = new( 0, target, 0 );
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,27 +2,9 @@
|
||||
|
||||
public partial class VeloXCar
|
||||
{
|
||||
private float avgSideSlip;
|
||||
private float avgPoweredRPM;
|
||||
private float avgForwardSlip;
|
||||
private void WheelThink( in float dt )
|
||||
{
|
||||
float avgRPM = 0, totalSideSlip = 0, totalForwardSlip = 0;
|
||||
|
||||
foreach ( var w in Wheels )
|
||||
{
|
||||
w.Update( this, dt );
|
||||
|
||||
totalSideSlip += w.SideSlip;
|
||||
totalForwardSlip += w.ForwardSlip;
|
||||
var rpm = w.RPM;
|
||||
|
||||
avgRPM += rpm * w.DistributionFactor;
|
||||
}
|
||||
|
||||
avgPoweredRPM = avgRPM;
|
||||
avgSideSlip = totalSideSlip / Wheels.Count;
|
||||
avgForwardSlip = totalForwardSlip / Wheels.Count;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,32 +7,6 @@ namespace VeloX;
|
||||
[Title( "VeloX - Car" )]
|
||||
public partial class VeloXCar : VeloXBase
|
||||
{
|
||||
protected override void OnStart()
|
||||
{
|
||||
base.OnStart();
|
||||
//StreamPlayer = new( Stream );
|
||||
//if ( IsDriver )
|
||||
//{
|
||||
// UpdateGearList();
|
||||
// UpdatePowerDistribution();
|
||||
//}
|
||||
}
|
||||
|
||||
protected override void OnUpdate()
|
||||
{
|
||||
base.OnUpdate();
|
||||
//if ( StreamPlayer is not null )
|
||||
//{
|
||||
|
||||
// StreamPlayer.Throttle = Throttle;
|
||||
// StreamPlayer.RPMPercent = RPMPercent;
|
||||
// StreamPlayer.EngineState = EngineState;
|
||||
// StreamPlayer.IsRedlining = IsRedlining;
|
||||
|
||||
// StreamPlayer.Update( Time.Delta, WorldPosition );
|
||||
//}
|
||||
|
||||
}
|
||||
protected override void OnFixedUpdate()
|
||||
{
|
||||
if ( !IsDriver )
|
||||
|
||||
@@ -28,44 +28,38 @@ public static class PhysicsExtensions
|
||||
value.x * (xz2 - wy2) + value.y * (yz2 + wx2) + value.z * (1.0f - xx2 - yy2)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Calculates the linear and angular velocities on the center of mass for an offset impulse.
|
||||
/// Calculates the linear and angular velocities on the object's center of mass for an offset impulse.
|
||||
/// </summary>
|
||||
/// <param name="physObj">The physics object</param>
|
||||
/// <param name="impulse">The impulse acting on the object in kg*units/s (World frame)</param>
|
||||
/// <param name="position">The location of the impulse in world coordinates</param>
|
||||
/// <returns>
|
||||
/// Vector1: Linear velocity from the impulse (World frame)
|
||||
/// Vector2: Angular velocity from the impulse (Local frame)
|
||||
/// </returns>
|
||||
public static (Vector3 LinearVelocity, Vector3 AngularVelocity) CalculateVelocityOffset( this PhysicsBody physObj, Vector3 impulse, Vector3 position )
|
||||
/// <param name="LinearVelocity">Linear velocity on center of mass (World frame)</param>
|
||||
/// <param name="AngularVelocity">Angular velocity on center of mass (World frame)</param>
|
||||
public static void CalculateVelocityOffset(
|
||||
this Rigidbody physObj,
|
||||
Vector3 impulse,
|
||||
Vector3 position,
|
||||
out Vector3 LinearVelocity,
|
||||
out Vector3 AngularVelocity )
|
||||
{
|
||||
if ( !physObj.IsValid() || !physObj.MotionEnabled )
|
||||
return (Vector3.Zero, Vector3.Zero);
|
||||
{
|
||||
LinearVelocity = 0;
|
||||
AngularVelocity = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
Vector3 com = physObj.WorldTransform.PointToWorld( physObj.MassCenter );
|
||||
Rotation bodyRot = physObj.PhysicsBody.Rotation;
|
||||
|
||||
Vector3 linearVelocity = impulse / physObj.Mass;
|
||||
|
||||
Vector3 r = position - physObj.MassCenter;
|
||||
|
||||
|
||||
// Calculate torque impulse in world frame: τ = r × impulse
|
||||
Vector3 torqueImpulseWorld = r.Cross( impulse );
|
||||
Rotation worldToLocal = physObj.Rotation.Inverse;
|
||||
Vector3 torqueImpulseLocal = torqueImpulseWorld.Transform( worldToLocal );
|
||||
|
||||
var InverseInertiaDiagLocal = physObj.Inertia.Inverse;
|
||||
|
||||
// Compute angular velocity change in rad/s (local frame)
|
||||
Vector3 angularVelocityRadLocal = new(
|
||||
InverseInertiaDiagLocal.x * torqueImpulseLocal.x,
|
||||
InverseInertiaDiagLocal.y * torqueImpulseLocal.y,
|
||||
InverseInertiaDiagLocal.z * torqueImpulseLocal.z
|
||||
);
|
||||
const float radToDeg = 180f / MathF.PI;
|
||||
Vector3 angularVelocityDegLocal = angularVelocityRadLocal * radToDeg;
|
||||
|
||||
return (linearVelocity, angularVelocityDegLocal);
|
||||
Vector3 r = position - com;
|
||||
Vector3 torque = Vector3.Cross( r, impulse );
|
||||
Vector3 torqueLocal = bodyRot.Inverse * torque;
|
||||
Vector3 angularVelocityLocal = torqueLocal * physObj.PhysicsBody.Inertia.Inverse;
|
||||
AngularVelocity = bodyRot * angularVelocityLocal;
|
||||
LinearVelocity = impulse * (1 / physObj.Mass);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -74,34 +68,31 @@ public static class PhysicsExtensions
|
||||
/// <param name="physObj">The physics object</param>
|
||||
/// <param name="impulse">The impulse acting on the object in kg*units/s (World frame)</param>
|
||||
/// <param name="position">The location of the impulse in world coordinates</param>
|
||||
/// <returns>
|
||||
/// Vector1: Linear impulse on center of mass (World frame)
|
||||
/// Vector2: Angular impulse on center of mass (Local frame)
|
||||
/// </returns>
|
||||
public static (Vector3 LinearImpulse, Vector3 AngularImpulse) CalculateForceOffset(
|
||||
this PhysicsBody physObj,
|
||||
/// <param name="LinearImpulse">Linear impulse on center of mass (World frame)</param>
|
||||
/// <param name="AngularImpulse">Angular impulse on center of mass (World frame)</param>
|
||||
public static void CalculateForceOffset(
|
||||
this Rigidbody physObj,
|
||||
Vector3 impulse,
|
||||
Vector3 position )
|
||||
Vector3 position,
|
||||
out Vector3 LinearImpulse,
|
||||
out Vector3 AngularImpulse )
|
||||
{
|
||||
if ( !physObj.IsValid() || !physObj.MotionEnabled )
|
||||
{
|
||||
return (Vector3.Zero, Vector3.Zero);
|
||||
LinearImpulse = 0;
|
||||
AngularImpulse = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
// 1. Linear impulse is the same as the input impulse (conservation of momentum)
|
||||
Vector3 linearImpulse = impulse;
|
||||
Vector3 com = physObj.WorldTransform.PointToWorld( physObj.MassCenter );
|
||||
Rotation bodyRot = physObj.PhysicsBody.Rotation;
|
||||
|
||||
// 2. Calculate angular impulse (torque) from the offset force
|
||||
// τ = r * F (cross product of position relative to COM and force)
|
||||
Vector3 centerOfMass = physObj.MassCenter;
|
||||
Vector3 relativePosition = position - centerOfMass;
|
||||
Vector3 worldAngularImpulse = relativePosition.Cross( impulse );
|
||||
|
||||
// Convert angular impulse to local space (since we'll use it with LocalInertia)
|
||||
Rotation bodyRotation = physObj.Transform.Rotation;
|
||||
Vector3 localAngularImpulse = bodyRotation.Inverse * worldAngularImpulse;
|
||||
|
||||
return (linearImpulse, localAngularImpulse);
|
||||
Vector3 r = position - com;
|
||||
Vector3 torque = Vector3.Cross( r, impulse );
|
||||
Vector3 torqueLocal = bodyRot.Inverse * torque;
|
||||
Vector3 angularImpulseLocal = torqueLocal * physObj.PhysicsBody.Inertia.Inverse;
|
||||
AngularImpulse = bodyRot * angularImpulseLocal;
|
||||
LinearImpulse = impulse;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,55 +0,0 @@
|
||||
//using Editor;
|
||||
//using Editor.Assets;
|
||||
//using Sandbox;
|
||||
//using VeloX;
|
||||
//using static Editor.Inspectors.AssetInspector;
|
||||
|
||||
//[CanEdit( "asset:engstr" )]
|
||||
//public class EngineStreamInspector : Widget, IAssetInspector
|
||||
//{
|
||||
// EngineStream EngineStream;
|
||||
// ControlSheet MainSheet;
|
||||
|
||||
// public EngineStreamInspector( Widget parent ) : base( parent )
|
||||
// {
|
||||
// Layout = Layout.Column();
|
||||
// Layout.Margin = 12;
|
||||
// Layout.Spacing = 12;
|
||||
|
||||
// MainSheet = new ControlSheet();
|
||||
|
||||
// Layout.Add( MainSheet, 1 );
|
||||
|
||||
// }
|
||||
|
||||
// [EditorEvent.Hotload]
|
||||
// void RebuildSheet()
|
||||
// {
|
||||
// if ( EngineStream is null || MainSheet is null )
|
||||
// return;
|
||||
|
||||
// Layout.Clear( true );
|
||||
// var text = Layout.Add( new Editor.TextEdit() );
|
||||
// var but = Layout.Add( new Editor.Button( "Load JSON" ) );
|
||||
// but.Clicked += () =>
|
||||
// {
|
||||
// EngineStream.LoadFromJson( text.PlainText );
|
||||
// };
|
||||
|
||||
// var so = EngineStream.GetSerialized();
|
||||
|
||||
|
||||
// so.OnPropertyChanged += _ =>
|
||||
// {
|
||||
// EngineStream.StateHasChanged();
|
||||
// };
|
||||
// Layout.Add( ControlWidget.Create( so.GetProperty( nameof( EngineStream.Layers ) ) ) );
|
||||
// Layout.Add( ControlWidget.Create( so.GetProperty( nameof( EngineStream.Parameters ) ) ) );
|
||||
// }
|
||||
|
||||
// public void SetAsset( Asset asset )
|
||||
// {
|
||||
// EngineStream = asset.LoadResource<EngineStream>();
|
||||
// RebuildSheet();
|
||||
// }
|
||||
//}
|
||||
48
Editor/Wheel/PacejkaWidget.cs
Normal file
48
Editor/Wheel/PacejkaWidget.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
using Editor;
|
||||
using Sandbox;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
[CustomEditor( typeof( Pacejka ) )]
|
||||
public class PacejkaWidget : ControlObjectWidget
|
||||
{
|
||||
public override bool SupportsMultiEdit => false;
|
||||
public override bool IncludeLabel => false;
|
||||
|
||||
[CustomEditor( typeof( Pacejka.PacejkaPreset ) )]
|
||||
private class LateralForceWidget : ControlObjectWidget
|
||||
{
|
||||
public LateralForceWidget( SerializedProperty property ) : base( property, true )
|
||||
{
|
||||
Layout = Layout.Column();
|
||||
Layout.Margin = 8f;
|
||||
Layout.Spacing = 8;
|
||||
foreach ( var item in TypeLibrary.GetType<Pacejka.PacejkaPreset>().Properties )
|
||||
{
|
||||
var row = Layout.AddRow();
|
||||
row.Spacing = 8;
|
||||
var propetry = SerializedObject.GetProperty( item.Name );
|
||||
row.Add( new Label( propetry.Name ) );
|
||||
row.Add( Create( propetry ) );
|
||||
}
|
||||
}
|
||||
}
|
||||
private Pacejka Pacejka;
|
||||
public PacejkaWidget( SerializedProperty property ) : base( property, true )
|
||||
{
|
||||
|
||||
var obj = SerializedObject;
|
||||
Pacejka = obj.ParentProperty.GetValue<Pacejka>();
|
||||
|
||||
Layout = Layout.Column();
|
||||
Layout.Margin = 8f;
|
||||
Layout.Add( new Label.Body( $" {ToolTip}" ) { Color = Color.White } );
|
||||
var tabs = Layout.Add( new TabWidget( null ) );
|
||||
tabs.AddPage( nameof( Pacejka.Lateral ), null,
|
||||
Layout.Add( Create( obj.GetProperty( nameof( Pacejka.Lateral ) ) ) )
|
||||
);
|
||||
tabs.AddPage( nameof( Pacejka.Longitudinal ), null,
|
||||
Layout.Add( Create( obj.GetProperty( nameof( Pacejka.Longitudinal ) ) ) )
|
||||
);
|
||||
}
|
||||
}
|
||||
149
Editor/Wheel/TirePresetPreview.cs
Normal file
149
Editor/Wheel/TirePresetPreview.cs
Normal file
@@ -0,0 +1,149 @@
|
||||
using Editor;
|
||||
using Editor.Assets;
|
||||
using Editor.Inspectors;
|
||||
using Sandbox;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace VeloX;
|
||||
|
||||
[AssetPreview( "tire" )]
|
||||
class TirePresetPreview : AssetPreview
|
||||
{
|
||||
private Texture texture;
|
||||
public override bool IsAnimatedPreview => false;
|
||||
[Range( 0.01f, 1 )] private float Zoom { get; set; } = 1;
|
||||
private TirePreset Tire;
|
||||
public AssetPreviewWidget Widget { get; private set; }
|
||||
public override Widget CreateWidget( Widget parent )
|
||||
{
|
||||
Widget = parent as AssetPreviewWidget;
|
||||
|
||||
return null;
|
||||
}
|
||||
public override Widget CreateToolbar()
|
||||
{
|
||||
var info = new IconButton( "settings" );
|
||||
info.Layout = Layout.Row();
|
||||
info.MinimumSize = 16;
|
||||
info.MouseLeftPress = () => OpenSettings( info );
|
||||
return info;
|
||||
}
|
||||
public void OpenSettings( Widget parent )
|
||||
{
|
||||
var popup = new PopupWidget( parent )
|
||||
{
|
||||
IsPopup = true,
|
||||
Layout = Layout.Column()
|
||||
};
|
||||
|
||||
popup.Layout.Margin = 16;
|
||||
|
||||
var ps = new ControlSheet();
|
||||
|
||||
ps.AddProperty( this, x => x.Zoom );
|
||||
|
||||
popup.Layout.Add( ps );
|
||||
popup.MaximumWidth = 300;
|
||||
popup.Show();
|
||||
popup.Position = parent.ScreenRect.TopRight - popup.Size;
|
||||
popup.ConstrainToScreen();
|
||||
|
||||
}
|
||||
|
||||
public override async Task InitializeAsset()
|
||||
{
|
||||
await Task.Yield();
|
||||
|
||||
using ( Scene.Push() )
|
||||
{
|
||||
PrimaryObject = new()
|
||||
{
|
||||
WorldTransform = Transform.Zero
|
||||
};
|
||||
|
||||
var plane = PrimaryObject.AddComponent<ModelRenderer>();
|
||||
plane.Model = Model.Plane;
|
||||
plane.LocalScale = new Vector3( 1, 1, 1 );
|
||||
plane.MaterialOverride = Material.Load( "materials/dev/reflectivity_30.vmat" );
|
||||
plane.Tint = new Color( 0.02f, 0.04f, 0.03f );
|
||||
|
||||
var bounds = PrimaryObject.GetBounds();
|
||||
SceneCenter = bounds.Center;
|
||||
SceneSize = bounds.Size;
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
public override void UpdateScene( float cycle, float timeStep )
|
||||
{
|
||||
if ( !Widget.IsValid() )
|
||||
return;
|
||||
|
||||
Camera.WorldPosition = Vector3.Up * 300;
|
||||
Camera.Orthographic = true;
|
||||
Camera.WorldRotation = new Angles( 90, 0, 0 );
|
||||
|
||||
var bitmap = new Bitmap( 512, 512 );
|
||||
|
||||
Draw( bitmap );
|
||||
|
||||
texture.Clear( Color.Black );
|
||||
//texture.Update( bitmap );
|
||||
DebugOverlaySystem.Current.Texture( texture, new Rect( 0, Widget.Size ) );
|
||||
|
||||
FrameScene();
|
||||
}
|
||||
|
||||
private readonly List<Vector2> pointCache = [];
|
||||
|
||||
public TirePresetPreview( Asset asset ) : base( asset )
|
||||
{
|
||||
texture = Texture.CreateRenderTarget().WithDynamicUsage().WithScreenFormat().WithSize( 512, 512 ).Create();
|
||||
Tire = Asset.LoadResource<TirePreset>();
|
||||
}
|
||||
|
||||
private void DrawPacejka( Bitmap bitmap )
|
||||
{
|
||||
var tire = Tire.Pacejka;
|
||||
var width = bitmap.Width;
|
||||
var height = bitmap.Height;
|
||||
|
||||
|
||||
{ // draw lateral line
|
||||
pointCache.Clear();
|
||||
|
||||
bitmap.SetPen( Color.Red, 1 );
|
||||
|
||||
for ( float x = 0; x <= 1; x += 0.01f )
|
||||
{
|
||||
float val = tire.PacejkaFy( x ) * Zoom;
|
||||
pointCache.Add( new( width * x, height - height * val ) );
|
||||
}
|
||||
|
||||
bitmap.DrawLines( pointCache.ToArray() );
|
||||
}
|
||||
|
||||
{ // draw longitudinal line
|
||||
pointCache.Clear();
|
||||
|
||||
bitmap.SetPen( Color.Green, 1 );
|
||||
|
||||
for ( float x = 0; x <= 1; x += 0.01f )
|
||||
{
|
||||
float val = tire.PacejkaFx( x ) * Zoom;
|
||||
pointCache.Add( new( width * x, height - height * val ) );
|
||||
}
|
||||
bitmap.DrawLines( pointCache.ToArray() );
|
||||
}
|
||||
|
||||
pointCache.Clear();
|
||||
}
|
||||
private void Draw( Bitmap bitmap )
|
||||
{
|
||||
bitmap.Clear( Color.Black );
|
||||
bitmap.SetAntialias( true );
|
||||
DrawPacejka( bitmap );
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user