Paradox Game Engine  v1.0.0 beta06
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Events Macros Pages
EntityComponentReferenceDataConverter.cs
Go to the documentation of this file.
1 // Copyright (c) 2014 Silicon Studio Corp. (http://siliconstudio.co.jp)
2 // This file is distributed under GPL v3. See LICENSE.md for details.
3 using System;
4 using SiliconStudio.Core;
5 using SiliconStudio.Core.Serialization;
6 using SiliconStudio.Core.Serialization.Converters;
7 using SiliconStudio.Paradox.Engine;
8 using SiliconStudio.Paradox.EntityModel;
9 using SiliconStudio.Paradox.EntityModel.Data;
10 
11 namespace SiliconStudio.Paradox.Data
12 {
13  internal class EntityComponentReferenceDataConverter<TSource> : DataConverter<EntityComponentReference<TSource>, TSource>
14  where TSource : EntityComponent
15  {
16  public override bool CacheResult
17  {
18  get { return true; }
19  }
20 
21  public override void ConvertFromData(ConverterContext converterContext, EntityComponentReference<TSource> componentReference, ref TSource component)
22  {
23  // Load entity
24  var entity = converterContext.ConvertFromData<Entity>(componentReference.Entity);
25 
26  // Get its component
27  component = entity.Get(componentReference.Component);
28  }
29 
30  public override void ConvertToData(ConverterContext converterContext, ref EntityComponentReference<TSource> componentReference, TSource component)
31  {
32  ContentReference<EntityData> entityReference = null;
33  converterContext.ConvertToData(ref entityReference, component.Entity);
34 
35  // Find key of this component
36  PropertyKey<TSource> componentKey = null;
37  if (component.Entity == null)
38  throw new InvalidOperationException("Entity of a referenced component can't be null");
39 
40  foreach (var entityComponent in component.Entity.Tags)
41  {
42  if (entityComponent.Value is EntityComponent
43  && entityComponent.Value == component)
44  {
45  componentKey = (PropertyKey<TSource>)entityComponent.Key;
46  }
47  }
48 
49  if (componentKey == null)
50  throw new InvalidOperationException("Could not find the component in its entity");
51 
52  componentReference = new EntityComponentReference<TSource>(entityReference, componentKey);
53  }
54  }
55 }
Game entity. It usually aggregates multiple EntityComponent
Definition: Entity.cs:28
Base class for converters to/from a data type.
A class that represents a tag propety.
Definition: PropertyKey.cs:17