-
-
Notifications
You must be signed in to change notification settings - Fork 947
/
Entity.cs
359 lines (315 loc) · 13 KB
/
Entity.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Stride.Core;
using Stride.Core.Annotations;
using Stride.Core.Collections;
using Stride.Core.Mathematics;
using Stride.Core.Serialization;
using Stride.Core.Serialization.Contents;
namespace Stride.Engine
{
/// <summary>
/// Represents a game entity that typically aggregates multiple <see cref="EntityComponent"/> instances.
/// For more information about entities, see <see href="https://doc.stride3d.net/latest/en/manual/game-studio/add-entities.html">Adding entities</see>
/// and <see href="https://doc.stride3d.net/latest/en/manual/game-studio/manage-entities.html">Managing entities</see>.
/// </summary>
//[ContentSerializer(typeof(EntityContentSerializer))]
//[ContentSerializer(typeof(DataContentSerializer<Entity>))]
[DebuggerTypeProxy(typeof(EntityDebugView))]
[ContentSerializer(typeof(EntityContentSerializer))]
[DataSerializer(typeof(EntitySerializer))]
[DataStyle(DataStyle.Normal)]
[DataContract("Entity")]
public sealed class Entity : ComponentBase, IEnumerable<EntityComponent>, IIdentifiable
{
internal TransformComponent TransformValue;
internal Scene SceneValue;
/// <summary>
/// Create a new <see cref="Entity"/> instance.
/// </summary>
public Entity()
: this(null)
{
}
/// <summary>
/// Create a new <see cref="Entity"/> instance having the provided name.
/// </summary>
/// <param name="name">The name to give to the entity</param>
public Entity(string name)
: this(name, Vector3.Zero)
{
}
/// <summary>
/// Create a new <see cref="Entity" /> instance having the provided name, initial position, rotation and scale.
/// </summary>
/// <param name="name">The name to give to the entity</param>
/// <param name="position">The initial position of the entity</param>
/// <param name="rotation">The initial rotation of the entity</param>
/// <param name="scale">The initial scale of the entity</param>
public Entity(string name = null, Vector3 position = default, Quaternion? rotation = null, Vector3? scale = null)
: this(name, false)
{
Id = Guid.NewGuid();
TransformValue = new TransformComponent { Position = position, Rotation = rotation ?? Quaternion.Identity, Scale = scale ?? Vector3.One };
Components.Add(TransformValue);
}
/// <summary>
/// Create a new entity without any components (used for binary deserialization)
/// </summary>
/// <param name="name">Name of this component, might be null</param>
/// <param name="notUsed">This parameter is not used</param>
private Entity(string name, bool notUsed) : base(name)
{
Components = new EntityComponentCollection(this);
}
[DataMember(-10), Display(Browsable = false)]
[NonOverridable]
public Guid Id { get; set; }
[DataMember(0)] // Name is serialized
public override string Name
{
get
{
return base.Name;
}
set
{
base.Name = value;
}
}
/// <summary>
/// The scene this entity is in. <br/>
/// Setting this to null will remove the entity from the scene and detach it from its parent if it has one.
/// </summary>
[DataMemberIgnore]
public Scene Scene
{
get
{
return this.FindRoot().SceneValue;
}
set
{
if (Transform.Parent != null)
{
if (value != null)
throw new InvalidOperationException("This entity is another entity's child. Detach it before changing its scene.");
Transform.Parent = null;
return;
}
var oldScene = SceneValue;
if (oldScene == value)
return;
oldScene?.Entities.Remove(this);
value?.Entities.Add(this);
}
}
/// <summary>
/// The entity manager which processes this entity.
/// </summary>
[DataMemberIgnore]
public EntityManager EntityManager { get; internal set; }
/// <summary>
/// Gets or sets the <see cref="Transform"/> associated to this entity.
/// Added for convenience over usual Get/Set method.
/// </summary>
[DataMemberIgnore]
public TransformComponent Transform => TransformValue;
/// <summary>
/// The components stored in this entity.
/// </summary>
[DataMember(100, DataMemberMode.Content)]
[MemberCollection(CanReorderItems = true, NotNullItems = true)]
public EntityComponentCollection Components { get; }
/// <summary>
/// Gets or create a component with the specified key.
/// </summary>
/// <typeparam name="T">Type of the entity component</typeparam>
/// <returns>A new or existing instance of {T}</returns>
public T GetOrCreate<T>() where T : EntityComponent, new()
{
var component = Components.Get<T>();
if (component == null)
{
component = new T();
Components.Add(component);
}
return component;
}
/// <summary>
/// Adds the specified component to the entity.
/// </summary>
/// <param name="component">The component to add.</param>
/// <exception cref="System.ArgumentNullException">Thrown if the component is null.</exception>
public void Add(EntityComponent component)
{
Components.Add(component);
}
/// <summary>
/// Gets the first component of the specified type.
/// </summary>
/// <typeparam name="T">Type of the component</typeparam>
/// <returns>The component or null if does no exist</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Get<T>() where T : EntityComponent
{
return Components.Get<T>();
}
/// <summary>
/// Gets the index'th component of the specified type. See remarks.
/// </summary>
/// <typeparam name="T">Type of the component</typeparam>
/// <param name="index">The index'th component to select.</param>
/// <returns>The component or null if does no exist</returns>
/// <remarks>
/// <ul>
/// <li>If index > 0, it will take the index'th component of the specified <typeparamref name="T"/>.</li>
/// <li>An index == 0 is equivalent to calling <see cref="Get{T}()"/></li>
/// <li>if index < 0, it will start from the end of the list to the beginning. A value of -1 means the first last component.</li>
/// </ul>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Get<T>(int index) where T : EntityComponent
{
return Components.Get<T>(index);
}
/// <summary>
/// Gets all components of the specified type.
/// </summary>
/// <typeparam name="T">Type of the component</typeparam>
/// <returns>The component or null if does no exist</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IEnumerable<T> GetAll<T>() where T : EntityComponent
{
return Components.GetAll<T>();
}
/// <summary>
/// Removes the first component of the specified type or derived type.
/// </summary>
/// <typeparam name="T">Type of the component</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Remove<T>() where T : EntityComponent
{
Components.Remove<T>();
}
/// <summary>
/// Removes the specified component.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Remove(EntityComponent component)
{
Components.Remove(component);
}
/// <summary>
/// Removes all components of the specified type or derived type.
/// </summary>
/// <typeparam name="T">Type of the component</typeparam>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveAll<T>() where T : EntityComponent
{
Components.RemoveAll<T>();
}
internal void OnComponentChanged(int index, EntityComponent oldComponent, EntityComponent newComponent)
{
// Don't use events but directly call the Owner
EntityManager?.NotifyComponentChanged(this, index, oldComponent, newComponent);
}
public override string ToString()
{
return $"Entity {Name}";
}
/// <summary>
/// Gets the enumerator of <see cref="EntityComponent"/>
/// </summary>
/// <returns></returns>
public FastCollection<EntityComponent>.Enumerator GetEnumerator()
{
return Components.GetEnumerator();
}
IEnumerator<EntityComponent> IEnumerable<EntityComponent>.GetEnumerator()
{
return Components.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return Components.GetEnumerator();
}
/// <summary>
/// Serializer which will not populate the new entity with a default transform
/// </summary>
internal class EntityContentSerializer : DataContentSerializerWithReuse<Entity>
{
public override object Construct(ContentSerializerContext context)
{
return new Entity(null, false);
}
}
/// <summary>
/// Dedicated Debugger for an entity that displays children from Entity.Transform.Children
/// </summary>
internal class EntityDebugView
{
private readonly Entity entity;
public EntityDebugView(Entity entity)
{
this.entity = entity;
}
public string Name => entity.Name;
public Guid Id => entity.Id;
public Entity Parent => entity.Transform?.Parent?.Entity;
public Entity[] Children => entity.Transform?.Children.Select(x => x.Entity).ToArray();
public EntityComponent[] Components => entity.Components.ToArray();
}
/// <summary>
/// Specialized serializer
/// </summary>
/// <seealso cref="Entity" />
internal class EntitySerializer : DataSerializer<Entity>
{
private DataSerializer<Guid> guidSerializer;
private DataSerializer<string> stringSerializer;
private DataSerializer<EntityComponentCollection> componentCollectionSerializer;
/// <inheritdoc/>
public override void Initialize(SerializerSelector serializerSelector)
{
guidSerializer = MemberSerializer<Guid>.Create(serializerSelector);
stringSerializer = MemberSerializer<string>.Create(serializerSelector);
componentCollectionSerializer = MemberSerializer<EntityComponentCollection>.Create(serializerSelector);
}
public override void PreSerialize(ref Entity obj, ArchiveMode mode, SerializationStream stream)
{
// Create an empty Entity without a Transform component by default when deserializing
if (mode == ArchiveMode.Deserialize)
{
if (obj == null)
obj = new Entity(null, false);
else
obj.Components.Clear();
}
}
public override void Serialize(ref Entity obj, ArchiveMode mode, SerializationStream stream)
{
// Serialize Id
var id = obj.Id;
guidSerializer.Serialize(ref id, mode, stream);
if (mode == ArchiveMode.Deserialize)
{
obj.Id = id;
}
// Serialize Name
var name = obj.Name;
stringSerializer.Serialize(ref name, mode, stream);
obj.Name = name;
// Components
var collection = obj.Components;
componentCollectionSerializer.Serialize(ref collection, mode, stream);
}
}
}
}