using System; using System.Collections.Generic; using System.Numerics; using static OpenGL.GL; using OpenGLTutorial.Rendering.Cameras; using OpenGLTutorial.Rendering.Display; using OpenGLTutorial.Rendering.Objects.Components; using OpenGLTutorial.Rendering.Shaders; namespace OpenGLTutorial.Rendering.Objects { public class GameObject { public Shader Shader { get; set; } public Shape Shape { get; set; } public Texture Texture { get; set; } public Vector2 Position { get; set; } public Vector2 Scale { get; set; } public float Rotation { get; set; } private List _components; public GameObject(Shader shader, Shape shape, Texture texture) { Position = Vector2.Zero; Scale = Vector2.One; Rotation = 0; Shader = shader; Shape = shape; Texture = texture; _components = new List(); } public void Load() { Shader?.Load(); Shape?.Load(); Texture?.Load(); _components.ForEach(component => component.Load(this)); } public void Update() { _components.ForEach(component => component.Update(this)); } public void Render(Camera2D cam, int renderMode = GL_TRIANGLES) { Matrix4x4 trans = Matrix4x4.CreateTranslation(Position.X, -Position.Y, 0); Matrix4x4 sca = Matrix4x4.CreateScale(Scale.X, Scale.Y, 1); Matrix4x4 rot = Matrix4x4.CreateRotationZ(Rotation); Texture?.Use(); Shader?.Use(); Shader?.SetMatrix4X4("model", sca * rot * trans); Shader?.SetMatrix4X4("projection", cam.GetProjectionMatrix()); if (Shape?.Vao != null) { glBindVertexArray(Shape.Vao); glDrawArrays(renderMode, 0, Shape.GetVertexCount()); glBindVertexArray(0); } _components.ForEach(component => component.Render(this)); } public void Destroy() { _components.ForEach(component => component.Destroy(this)); Shader?.Delete(); Shape?.Delete(); Texture?.Delete(); } public void AddComponent(IComponent component) => _components.Add(component); public T GetComponent() { foreach (var component in _components) { if (component.GetType() == typeof(T)) return (T)component; } throw new NullReferenceException("Object does not contain a component of type " + typeof(T)); } public void RemoveComponent() { foreach (var component in _components) { if (component.GetType() == typeof(T)) { _components.Remove(component); return; } } throw new NullReferenceException("Object does not contain a component of type " + typeof(T)); } } }