Хорошо, я создаю движок 2D-игры, используя OpenGL для C#. Когда мы запускаем проект, мы создаем фон, который представляет собой простой квадрат, достаточно большой, чтобы покрыть весь экран, затем я добавляю игровой объект, который снова квадрат с текстурой. если я добавлю, скажем, 10, он начнет работать очень медленно, и я попробовал все виды оптимизации: создать сетку один раз, а затем использовать ее повсюду, загружать текстуры только один раз, а не каждый кадр и т. д. Вот мой github для проекта: https:/ /github.com/Stily-TUES/Elysium/tree/master
Изменить: я исправил утечку памяти, но это не особо помогло производительности. Если я добавляю больше игровых объектов, движение камеры становится очень медленным, запаздывающим и не плавным, но перетаскивание игровых объектов работает как обычно и плавно. В чем может быть проблема?
и код для справки:
mesh.cs
public class Mesh
{
private int VAO, VBO, EBO;
public Mesh(float[] vertices, uint[] indices, string texturePath = null)
{
VAO = GL.GenVertexArray();
VBO = GL.GenBuffer();
EBO = GL.GenBuffer();
GL.BindVertexArray(VAO);
GL.BindBuffer(BufferTarget.ArrayBuffer, VBO);
GL.BufferData(BufferTarget.ArrayBuffer, vertices.Length * sizeof(float), vertices, BufferUsageHint.StaticDraw);
GL.BindBuffer(BufferTarget.ElementArrayBuffer, EBO);
GL.BufferData(BufferTarget.ElementArrayBuffer, indices.Length * sizeof(uint), indices, BufferUsageHint.StaticDraw);
GL.VertexAttribPointer(0, 3, VertexAttribPointerType.Float, false, 5 * sizeof(float), 0);
GL.EnableVertexAttribArray(0);
GL.VertexAttribPointer(1, 2, VertexAttribPointerType.Float, false, 5 * sizeof(float), 3 * sizeof(float));
GL.EnableVertexAttribArray(1);
GL.BindVertexArray(0);
}
public void Render(int shaderProgram, int textureId)
{
if (textureId > 0)
{
GL.ActiveTexture(TextureUnit.Texture0);
GL.BindTexture(TextureTarget.Texture2D, textureId);
GL.Uniform1(GL.GetUniformLocation(shaderProgram, "texture1"), 0);
GL.Uniform1(GL.GetUniformLocation(shaderProgram, "useTexture"), 1);
}
else
{
GL.Uniform1(GL.GetUniformLocation(shaderProgram, "useTexture"), 0);
}
GL.BindVertexArray(VAO);
GL.DrawElements(PrimitiveType.Triangles, 6, DrawElementsType.UnsignedInt, 0);
GL.BindVertexArray(0);
}
public void Dispose()
{
GL.DeleteVertexArray(VAO);
GL.DeleteBuffer(VBO);
GL.DeleteBuffer(EBO);
}
public static Mesh CreateSquare(float sideLength)
{
float halfSide = sideLength / 2;
float[] vertices = {
// positions // texture coords
-halfSide, -halfSide, 0.0f, 0.0f, 1.0f,
halfSide, -halfSide, 0.0f, 1.0f, 1.0f,
halfSide, halfSide, 0.0f, 1.0f, 0.0f,
-halfSide, halfSide, 0.0f, 0.0f, 0.0f
};
uint[] indices = {
0, 1, 2,
2, 3, 0
};
return new Mesh(vertices, indices);
}
}
Renderer.cs
public class Renderer
{
private int shaderProgram;
private int _backgroundTextureId;
public static void Main() { }
public Renderer()
{
shaderProgram = CreateShaderProgram("shader.vert", "shader.frag");
}
private int CreateShaderProgram(string vertexPath, string fragmentPath)
{
string vertexShaderSource = File.ReadAllText(vertexPath);
string fragmentShaderSource = File.ReadAllText(fragmentPath);
int vertexShader = CompileShader(ShaderType.VertexShader, vertexShaderSource);
int fragmentShader = CompileShader(ShaderType.FragmentShader, fragmentShaderSource);
int program = GL.CreateProgram();
GL.AttachShader(program, vertexShader);
GL.AttachShader(program, fragmentShader);
GL.LinkProgram(program);
GL.DeleteShader(vertexShader);
GL.DeleteShader(fragmentShader);
return program;
}
private int CompileShader(ShaderType type, string source)
{
int shader = GL.CreateShader(type);
GL.ShaderSource(shader, source);
GL.CompileShader(shader);
GL.GetShader(shader, ShaderParameter.CompileStatus, out int success);
if (success == 0)
{
string infoLog = GL.GetShaderInfoLog(shader);
throw new Exception($"Error compiling {type}: {infoLog}");
}
return shader;
}
public void RenderMesh(int textureId, Mesh mesh, Matrix4 modelMatrix, Matrix4 viewMatrix, Matrix4 projectionMatrix)
{
GL.UseProgram(shaderProgram);
Matrix4 transformMatrix = modelMatrix * viewMatrix * projectionMatrix;
int transformLoc = GL.GetUniformLocation(shaderProgram, "transform");
GL.UniformMatrix4(transformLoc, false, ref transformMatrix);
mesh.Render(shaderProgram, textureId);
}
public void RenderBackground(Mesh mesh, string texturePath)
{
if (_backgroundTextureId x.Transform.Position.Z).Last();
dragDelta = mousePosition.Xy;
}
else
{
selectedEntity = null;
}
}
}
private void GlControl_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Delta > 0)
{
camera.ZoomIn(0.1f);
}
else
{
camera.ZoomOut(0.1f);
}
}
private void GlControl_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
lastMousePosition = new Point(0, 0);
}
if (e.Button == System.Windows.Forms.MouseButtons.Left)
{
isDragging = false;
}
}
private void Render()
{
if (projectManager != null)
{
GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
if (projectManager.GetActiveScene().Background == null)
{
projectManager.GetActiveScene().Background = new TextureFile();
}
renderer.RenderBackground(backgroundMesh, projectManager.GetActiveScene().Background.ImagePath);
projectManager.RenderProject(camera, aspectRatio);
glControl.SwapBuffers();
}
}
private void LoadTextures()
{
if (TextureFile.TextureFiles.Any())
{
TexturesListBox.ItemsSource = TextureFile.TextureFiles;
}
else
{
MessageBox.Show("Textures folder not found.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
private void onUndoButton_Click(object sender, RoutedEventArgs e)
{
projectManager?.Undo();
}
private void onRedoButton_Click(object sender, RoutedEventArgs e)
{
projectManager?.Redo();
}
private void onSaveButton_Click(object sender, RoutedEventArgs e)
{
projectManager?.Save();
}
private void onTextureDrag_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var stackPanel = sender as StackPanel;
var textureFile = stackPanel.DataContext as TextureFile;
if (textureFile != null)
{
DragDrop.DoDragDrop(stackPanel, textureFile, DragDropEffects.Copy);
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/792 ... 2-entities
Создание движка 2D-игры, но он очень медленный даже с двумя объектами [закрыто] ⇐ C#
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Очень неожиданная производительность fprintf против std::ofstream (fprintf очень медленный)
Anonymous » » в форуме C++ - 0 Ответы
- 86 Просмотры
-
Последнее сообщение Anonymous
-