using System;
using System.Drawing;
using System.Windows.Forms;
using OpenTK;
using OpenTK.Graphics.OpenGL;

namespace ComputerGraphicsLab2
{
    public partial class Form1 : Form
    {
        private bool glLoaded = false;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // Форма загружена
        }

        private void glControl1_Load(object sender, EventArgs e)
        {
            glLoaded = true;
            
            // Настройка OpenGL
            GL.ClearColor(Color.White);
            GL.Enable(EnableCap.DepthTest);
            
            // Настройка viewport
            GL.Viewport(0, 0, glControl1.Width, glControl1.Height);
            
            // Настройка проекции
            GL.MatrixMode(MatrixMode.Projection);
            GL.LoadIdentity();
            GL.Ortho(-2.0, 2.0, -2.0, 2.0, -1.0, 1.0);
            
            GL.MatrixMode(MatrixMode.Modelview);
            GL.LoadIdentity();
            
            // Принудительная перерисовка
            glControl1.Invalidate();
        }

        private void glControl1_Paint(object sender, PaintEventArgs e)
        {
            if (!glLoaded) return;
            
            // Очистка экрана
            GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit);
            
            drawTriangle();
            
            // Отображение результата
            glControl1.SwapBuffers();
        }

        private void drawTriangle()
        {
            var z = 4.0f;
            var pointsCoint = 3;
            var colors = new Vector3[pointsCoint];
            var points = new Vector3[pointsCoint];

            colors[0] = new Vector3(1.0f, 0.0f, 0.0f);
            colors[1] = new Vector3(0.0f, 1.0f, 0.0f);
            colors[2] = new Vector3(0.0f, 0.0f, 1.0f);
            
            points[0] = new Vector3(-1.0f, -1.0f, z);
            points[1] = new Vector3(1.0f, -1.0f, z);
            points[2] = new Vector3(0.0f, 1.0f, z);
            
            drawPolygon(points, colors, pointsCoint, BeginMode.Polygon);
        }

        private void drawPolygon(Vector3[] points, Vector3[] colors, int n, BeginMode mode)
        {
            GL.Begin(mode);
            for (int i = 0; i < n; i++)
            {
                GL.Color3(colors[i]);
                GL.Vertex2(points[i].X, points[i].Y);
            }
            GL.End();
        }
    }
}