1.源码实现
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
//void glGenerateMipmap (GLenum target);
float angle = 0.0;
GLuint textureID;
void init()
{
glEnable(GL_DEPTH_TEST);
glEnable(GL_MULTISAMPLE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
//glEnable(GL_TEXTURE_2D);
glDepthFunc(GL_LEQUAL);
glClearDepth(1.0f);
GLfloat light_position[] = {1.0, -1.0, -0.5, 0.0};
GLfloat light_ambient[] = {0.2, 0.2, 0.2, 1.0};
GLfloat light_diffuse[] = {0.8, 0.8, 0.8, 1.0};
glLightfv(GL_LIGHT0, GL_POSITION, light_position);
glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
glEnable(GL_COLOR_MATERIAL);
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
//生成纹理对象
glGenTextures(1, &textureID);
glBindTexture(GL_TEXTURE_2D, textureID);
//加载图片并设置纹理参数
int width, height, channels;
unsigned char *image = stbi_load("earth.jpg", &width, &height, &channels, STBI_rgb);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
glGenerateMipmapEXT(GL_TEXTURE_2D);
stbi_image_free(image);
}
void update(int value)
{
angle += 2.0f;
if(angle > 360)
{
angle -= 360;
}
glutPostRedisplay();
glutTimerFunc(32, update, 0);
}
void drawSphere()
{
GLUquadric *quadric = gluNewQuadric();
gluQuadricTexture(quadric, GL_TRUE);
gluQuadricDrawStyle(quadric, GLU_FILL);
gluQuadricOrientation(quadric, GLU_OUTSIDE);
gluQuadricNormals(quadric, GLU_SMOOTH);
gluSphere(quadric, 0.8, 50, 50);
gluDeleteQuadric(quadric);
}
void display()
{
glClearColor(0.0, 0.0, 0.0, 1.0);
glClear(GL_COLOR_BUFFER_BIT);
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
glRotatef(angle, 0.0f, 1.0f, 0.0f);
glRotatef(angle, 0.0f, 0.0f, 1.0f);
glEnable(GL_TEXTURE_2D);
//glTranslatef(0.0f, 0.0f, -0.3f);
glBindTexture(GL_TEXTURE_2D, textureID);
//glutSolidCube(0.8);
//glutSolidSphere(0.8, 50, 50);
glBegin(GL_TRIANGLES);
drawSphere();
glEnd();
glDisable(GL_TEXTURE_2D);
glFlush();
glutSwapBuffers();
}
int main(int argc, char **argv)
{
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGB|GLUT_DOUBLE|GLUT_DEPTH|GLUT_MULTISAMPLE);
glutInitWindowSize(400, 400);
glutCreateWindow("OpenGL Sphere with Lighting");
init();
glutDisplayFunc(display);
glutTimerFunc(16, update, 0);
glutMainLoop();
return 0;
}
2.素材图片
3.编译源码
$ g++ -o example example.cpp -std=c++11 -I/opt/apps/wxwidget/include -L/opt/apps/wxwidget/lib -lGL -lglut -Wl,-rpath=/opt/apps/wxwidget/lib
4.运行结果
屏幕截图 2024-08-10 202538.png
网友评论