Skip to content
0.2.0-dev Download ZIP
235 lines ·8.8 KB Raw
1using EvilEngine.Formats.Collision;
2using EvilEngine.Formats.Maps;
3using EvilEngine.Formats.Records;
4using EvilEngine.Host.Collision;
5using Godot;
6using Godot.Collections;
7
8namespace EvilEngine.Shared.World;
9
10public sealed partial class WorldCollision : Node3D
11{
12 public const uint WorldLayer = 1;
13 public const uint PlayerClipLayer = 2;
14 public const uint NpcClipLayer = 4;
15 public const uint VehicleClipLayer = 8;
16 public const uint PhysicsClipLayer = 16;
17 public const uint PropLayer = 32;
18 public const uint CharacterLayer = 64;
19 public const PhysicsServer3D.BodyParameter ShapeSurfacesParameter = (PhysicsServer3D.BodyParameter)100;
20 private const int BatchSize = 256;
21
22 private readonly List<Rid> _bodies = [];
23 private readonly MapColliderSet _colliders;
24 private readonly List<Rid> _shapes = [];
25
26 public WorldCollision(MapColliderSet colliders)
27 {
28 _colliders = colliders;
29 Name = "Collision";
30 }
31
32 public int Shapes => _shapes.Count;
33
34 public static uint Layer(IReadOnlyList<string> contents)
35 {
36 if (SolidContents.Blocks(contents))
37 return WorldLayer;
38 if (contents.Contains(SolidContents.PlayerClip))
39 return PlayerClipLayer;
40 if (contents.Contains(SolidContents.NpcClip))
41 return NpcClipLayer;
42 if (contents.Contains(SolidContents.VehicleClip))
43 return VehicleClipLayer;
44 return contents.Contains(SolidContents.PhysicsClip) ? PhysicsClipLayer : 0;
45 }
46
47 public override void _Ready()
48 {
49 Build(_colliders, GetWorld3D().Space, _bodies, _shapes);
50 }
51
52 public static void Build(MapColliderSet colliders, Rid space, List<Rid> bodies, List<Rid> shapes,
53 WorldSurfaces? surfaces = null, Func<CollisionSurface, SurfaceRecord?>? records = null)
54 {
55 var meshes = new System.Collections.Generic.Dictionary<ColliderMesh, Rid>(ReferenceEqualityComparer.Instance);
56 var open = new System.Collections.Generic.Dictionary<uint, (Rid Body, int Shapes)>();
57 var made = new List<(Rid Body, List<MapCollider> Shapes)>();
58 var placedOn = new System.Collections.Generic.Dictionary<Rid, List<MapCollider>>();
59 var known = new System.Collections.Generic.Dictionary<CollisionSurface, (float Friction, float Bounce)>();
60
61 (float Friction, float Bounce) Values(CollisionSurface surface)
62 {
63 if (surface == CollisionSurface.None || records is null)
64 return (float.NaN, float.NaN);
65 if (known.TryGetValue(surface, out var values))
66 return values;
67 var record = records(surface);
68 return known[surface] = ((float?)record?.Friction ?? float.NaN, (float?)record?.Bounce ?? float.NaN);
69 }
70
71 Rid Body(uint layer)
72 {
73 var body = PhysicsServer3D.BodyCreate();
74 PhysicsServer3D.BodySetMode(body, PhysicsServer3D.BodyMode.Static);
75 PhysicsServer3D.BodySetCollisionLayer(body, layer);
76 PhysicsServer3D.BodySetCollisionMask(body, 0);
77 bodies.Add(body);
78 List<MapCollider> placed = [];
79 made.Add((body, placed));
80 placedOn[body] = placed;
81 return body;
82 }
83
84 foreach (var collider in colliders.Colliders)
85 {
86 var layer = Layer(collider.Contents);
87 if (layer == 0)
88 continue;
89 if (collider.Shape is MapColliderShape.Triangles triangles)
90 {
91 if (!meshes.TryGetValue(triangles.Mesh, out var mesh))
92 meshes[triangles.Mesh] = mesh = Mesh(triangles.Mesh, shapes, Values);
93 var body = Body(layer);
94 PhysicsServer3D.BodyAddShape(body, mesh, Affine(triangles.Transform));
95 made[^1].Shapes.Add(collider);
96 continue;
97 }
98
99 if (Shape(collider.Shape, shapes) is not var (shape, transform))
100 continue;
101 if (!open.TryGetValue(layer, out var batch) || batch.Shapes == BatchSize)
102 batch = (Body(layer), 0);
103
104 PhysicsServer3D.BodyAddShape(batch.Body, shape, transform);
105 placedOn[batch.Body].Add(collider);
106 open[layer] = (batch.Body, batch.Shapes + 1);
107 }
108
109 foreach (var (body, placed) in made)
110 {
111 if (records is not null)
112 {
113 var pairs = new float[placed.Count * 2];
114 var any = false;
115 for (var index = 0; index < placed.Count; index++)
116 {
117 var (friction, bounce) = placed[index].Shape is MapColliderShape.Triangles
118 ? (float.NaN, float.NaN)
119 : Values(WorldSurfaces.Of(placed[index].Shape));
120 pairs[index * 2] = friction;
121 pairs[index * 2 + 1] = bounce;
122 any |= !float.IsNaN(friction) || !float.IsNaN(bounce);
123 }
124
125 if (any)
126 PhysicsServer3D.BodySetParam(body, ShapeSurfacesParameter, pairs);
127 }
128
129 foreach (var collider in placed)
130 surfaces?.Add(body, collider);
131 PhysicsServer3D.BodySetSpace(body, space);
132 }
133 }
134
135 private static Rid Mesh(ColliderMesh mesh, List<Rid> shapes,
136 Func<CollisionSurface, (float Friction, float Bounce)> values)
137 {
138 var rid = PhysicsServer3D.ConcavePolygonShapeCreate();
139 var data = new Dictionary
140 {
141 ["faces"] = mesh.Indices.Select(index => Vector(mesh.Positions[index])).ToArray(),
142 ["backface_collision"] = true
143 };
144 if (mesh.Surfaces.Count > 0)
145 {
146 var parts = mesh.Surfaces.Select(values).ToArray();
147 data["friction"] = Enumerable.Range(0, mesh.Count).Select(face => parts[mesh.Parts[face]].Friction).ToArray();
148 data["bounce"] = Enumerable.Range(0, mesh.Count).Select(face => parts[mesh.Parts[face]].Bounce).ToArray();
149 }
150
151 PhysicsServer3D.ShapeSetData(rid, data);
152 PhysicsServer3D.ShapeSetMargin(rid, 0);
153 shapes.Add(rid);
154 return rid;
155 }
156
157 private static Transform3D Affine(MapAffine affine)
158 {
159 var m = affine.Basis;
160 return new Transform3D(new Basis(new Vector3(m[0], m[3], m[6]), new Vector3(m[1], m[4], m[7]),
161 new Vector3(m[2], m[5], m[8])), Vector(affine.Origin));
162 }
163
164 public override void _ExitTree()
165 {
166 foreach (var body in _bodies)
167 PhysicsServer3D.FreeRid(body);
168 foreach (var shape in _shapes)
169 PhysicsServer3D.FreeRid(shape);
170 _bodies.Clear();
171 _shapes.Clear();
172 }
173
174 private static (Rid, Transform3D)? Shape(MapColliderShape shape, List<Rid> shapes)
175 {
176 Rid rid;
177 var transform = Transform3D.Identity;
178 switch (shape)
179 {
180 case MapColliderShape.Hull hull:
181 rid = PhysicsServer3D.ConvexPolygonShapeCreate();
182 PhysicsServer3D.ShapeSetData(rid, hull.Points.Select(Vector).ToArray());
183 break;
184 case MapColliderShape.Primitive primitive:
185 var rotation = primitive.Rotation;
186 transform = new Transform3D(new Basis(new Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W)),
187 Vector(primitive.Position));
188 if (Primitive(primitive.Shape) is not { } made)
189 return null;
190 rid = made;
191 break;
192 default:
193 return null;
194 }
195
196 PhysicsServer3D.ShapeSetMargin(rid, 0);
197 shapes.Add(rid);
198 return (rid, transform);
199 }
200
201 public static Rid? Primitive(ColliderShape shape)
202 {
203 Rid rid;
204 switch (shape)
205 {
206 case ColliderShape.Box box:
207 rid = PhysicsServer3D.BoxShapeCreate();
208 PhysicsServer3D.ShapeSetData(rid, new Vector3(box.Size.X, box.Size.Y, box.Size.Z) / 2);
209 break;
210 case ColliderShape.Sphere sphere:
211 rid = PhysicsServer3D.SphereShapeCreate();
212 PhysicsServer3D.ShapeSetData(rid, sphere.Radius);
213 break;
214 case ColliderShape.Capsule capsule:
215 rid = PhysicsServer3D.CapsuleShapeCreate();
216 PhysicsServer3D.ShapeSetData(rid, new Dictionary
217 { ["radius"] = capsule.Radius, ["height"] = capsule.Height + 2 * capsule.Radius });
218 break;
219 case ColliderShape.Cylinder cylinder:
220 rid = PhysicsServer3D.CylinderShapeCreate();
221 PhysicsServer3D.ShapeSetData(rid, new Dictionary
222 { ["radius"] = cylinder.Radius, ["height"] = cylinder.Height });
223 break;
224 default:
225 return null;
226 }
227
228 return rid;
229 }
230
231 private static Vector3 Vector(MapVector point)
232 {
233 return new Vector3(point.X, point.Y, point.Z);
234 }
235}