#include <GL/glut.h>
#include <iostream>

const int TEX_SIZE = 64;
GLubyte chessboard[TEX_SIZE][TEX_SIZE][3]; // Textura en memoria
GLuint textureID; // Identificador de textura

float angleX = 0.0f, angleY = 0.0f; // Ángulos de rotación
int lastX, lastY; // Última posición del mouse
bool isDragging = false; // Indica si el mouse está presionado

void generateChessboardTexture() {
    for (int i = 0; i < TEX_SIZE; i++) {
        for (int j = 0; j < TEX_SIZE; j++) {
            int color = ((i / 8 + j / 8) % 2) * 255;
            chessboard[i][j][0] = color;
            chessboard[i][j][1] = color;
            chessboard[i][j][2] = color;
        }
    }
    
    glGenTextures(1, &textureID);
    glBindTexture(GL_TEXTURE_2D, textureID);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, TEX_SIZE, TEX_SIZE, 0, GL_RGB, GL_UNSIGNED_BYTE, chessboard);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}

void display() {
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0.0f, 0.0f, -5.0f); // Alejamos la cámara

    glRotatef(angleX, 1, 0, 0); // Rotar en X
    glRotatef(angleY, 0, 1, 0); // Rotar en Y

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, textureID);
    
    GLUquadric* quad = gluNewQuadric();
    gluQuadricTexture(quad, GL_TRUE);
    gluSphere(quad, 1.0, 32, 32);

    gluDeleteQuadric(quad);
    glDisable(GL_TEXTURE_2D);

    glutSwapBuffers();
}

// Función de movimiento del mouse
void mouseMotion(int x, int y) {
    if (isDragging) {
        angleY += (x - lastX) * 0.5f; // Rotación en Y
        angleX += (y - lastY) * 0.5f; // Rotación en X
        lastX = x;
        lastY = y;
        glutPostRedisplay();
    }
}

// Función para detectar si el botón del mouse está presionado
void mouse(int button, int state, int x, int y) {
    if (button == GLUT_LEFT_BUTTON) {
        if (state == GLUT_DOWN) {
            isDragging = true;
            lastX = x;
            lastY = y;
        } else {
            isDragging = false;
        }
    }
}

void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45.0, (float)w / (float)h, 1.0, 100.0);
    glMatrixMode(GL_MODELVIEW);
}

void init() {
    glEnable(GL_DEPTH_TEST);
    generateChessboardTexture();
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
    glutInitWindowSize(800, 600);
    glutCreateWindow("Esfera con textura de ajedrez y control de mouse");

    init();
    
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMouseFunc(mouse);
    glutMotionFunc(mouseMotion); // Detecta movimiento del mouse con botón presionado
    
    glutMainLoop();
    return 0;
}

