1 module meld.gameObject; 2 3 import meld; 4 5 import std.algorithm; 6 7 abstract class Component(T) 8 { 9 package: 10 static T[int] componentMap; 11 static T[] componentList; 12 public: 13 GameObject gameObject; 14 15 @property Transform transform() 16 { 17 return gameObject.m_transform; 18 } 19 } 20 21 class GameObject 22 { 23 private: 24 int m_maxInstanceID = 0; 25 package: 26 immutable int m_instanceID; 27 Transform m_transform; 28 29 public: 30 @property Transform transform() { return m_transform; } 31 32 this(Transform parent = null) 33 { 34 m_transform = new Transform(); 35 m_transform.gameObject = this; 36 m_transform.parent = parent; 37 m_instanceID = m_maxInstanceID++; 38 } 39 40 T Add(T,A...)(A a) 41 { 42 T component = new T(a); 43 component.gameObject = this; 44 T.componentList ~= component; 45 T.componentMap[m_instanceID] = component; 46 return component; 47 } 48 49 void Remove(T)() 50 { 51 T* component = m_instanceID in T.componentMap; 52 if (component !is null) 53 { 54 int ind = countUntil(T.componentList, *component); 55 T.componentList = remove(T.componentList, ind); 56 T.componentMap.remove(m_instanceID); 57 } 58 } 59 60 T* Get(T)() 61 { 62 return m_instanceID in T.componentMap; 63 } 64 65 static T[] GetComponentList(T)() 66 { 67 return T.componentList; 68 } 69 } 70 71 class MeshRenderer : Component!MeshRenderer 72 { 73 private: 74 Mesh m_mesh; 75 Material m_material; 76 77 public: 78 this(Mesh mesh, Material material) 79 { 80 this.m_mesh = mesh; 81 this.m_material = material; 82 } 83 84 static void Draw() 85 { 86 foreach (MeshRenderer renderer; GameObject.GetComponentList!MeshRenderer()) 87 { 88 renderer.DrawInternal(); 89 } 90 } 91 92 void DrawInternal() 93 { 94 m_material.Bind(transform.localToWorld); 95 m_mesh.Draw(); 96 } 97 }