Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

50 lines
2.2KB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Svelto.ECS
  5. {
  6. public static class EntityDescriptorsWarmup
  7. {
  8. /// <summary>
  9. /// c# Static constructors are guaranteed to be thread safe
  10. /// Warmup all EntityDescriptors and ComponentTypeID classes to avoid huge overheads when they are first used
  11. /// </summary>
  12. internal static void Init()
  13. {
  14. List<Assembly> assemblies = AssemblyUtility.GetCompatibleAssemblies();
  15. foreach (Assembly assembly in assemblies)
  16. {
  17. var typeOfEntityDescriptors = typeof(IEntityDescriptor);
  18. foreach (Type type in AssemblyUtility.GetTypesSafe(assembly))
  19. {
  20. if (typeOfEntityDescriptors.IsAssignableFrom(type)) //IsClass and IsSealed and IsAbstract means only static classes
  21. {
  22. var warmup = typeof(EntityDescriptorTemplate<>).MakeGenericType(type);
  23. try
  24. {
  25. System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(warmup.TypeHandle);
  26. }
  27. catch
  28. {
  29. continue;
  30. }
  31. PropertyInfo field = warmup.GetProperty("descriptor", BindingFlags.Static | BindingFlags.Public);
  32. object value = field.GetValue(null); // pass null because the field is static
  33. // cast the value to your descriptor type
  34. IEntityDescriptor descriptor = (IEntityDescriptor)value;
  35. foreach (IComponentBuilder component in descriptor.componentsToBuild)
  36. {
  37. var typeArguments = component.GetEntityComponentType();
  38. var warmup2 = typeof(ComponentTypeID<>).MakeGenericType(typeArguments);
  39. System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(warmup2.TypeHandle);
  40. }
  41. }
  42. }
  43. }
  44. }
  45. }
  46. }