OpenGL+WebGL——绘制球体

  • 编写C++程序main.cpp,包括构建点的数据结构、计算球体的参数、绘制球面、初始化设置、绘图函数与主函数调用
#include <GL\glut.h>
#include <math.h>

#define PI 3.14159265358979323846
#define PI2 6.28318530717958647692

GLsizei width = 600, height = 600;

int uStepsNum = 50, vStepNum = 50;
static float rotate = 0;
static int times = 0;

class Point
{
	public:
		Point() {};
		Point(float a, float b, float c) :x(a), y(b), z(c) {};
	public:
		float x;
		float y;
		float z;
};

Point getPoint(float u, float v)
{
	float x = sin(PI*v)*cos(PI2*u);
	float y = sin(PI*v)*sin(PI2*u);
	float z = cos(PI*v);
	return Point(x, y, z);
}


void drawWire()
{
	float ustep = 1 / (float)uStepsNum, vstep = 1 / (float)vStepNum;
	float u = 0, v = 0;
	//绘制下端三角形组
	for (int i = 0;i<uStepsNum;i++)
	{
		glBegin(GL_LINE_LOOP);
		Point a = getPoint(0, 0);
		glVertex3f(a.x, a.y, a.z);
		Point b = getPoint(u, vstep);
		glVertex3f(b.x, b.y, b.z);
		Point c = getPoint(u + ustep, vstep);
		glVertex3f(c.x, c.y, c.z);
		u += ustep;
		glEnd();
	}
	//绘制中间四边形组
	u = 0, v = vstep;
	for (int i = 1;i<vStepNum - 1;i++)
	{
		for (int j = 0;j<uStepsNum;j++)
		{
			glBegin(GL_LINE_LOOP);
			Point a = getPoint(u, v);
			Point b = getPoint(u + ustep, v);
			Point c = getPoint(u + ustep, v + vstep);
			Point d = getPoint(u, v + vstep);
			glVertex3f(a.x, a.y, a.z);
			glVertex3f(b.x, b.y, b.z);
			glVertex3f(c.x, c.y, c.z);
			glVertex3f(d.x, d.y, d.z);
			u += ustep;
			glEnd();
		}
		v += vstep;
	}
	//绘制下端三角形组
	u = 0;
	for (int i = 0;i<uStepsNum;i++)
	{
		glBegin(GL_LINE_LOOP);
		Point a = getPoint(0, 1);
		Point b = getPoint(u, 1 - vstep);
		Point c = getPoint(u + ustep, 1 - vstep);
		glVertex3f(a.x, a.y, a.z);
		glVertex3f(b.x, b.y, b.z);
		glVertex3f(c.x, c.y, c.z);
		glEnd();
	}
}

void init()
{
	glEnable(GL_COLOR_MATERIAL);
	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	glEnable(GL_AUTO_NORMAL);
	glEnable(GL_NORMALIZE);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
}
void displayFunc()
{
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glColor3f(1.0, 1.0, 1.0);
	//glPointSize(1.0);

	times++;
	if (times > 100)
		times = 0;

	if (times % 5 == 0)
		rotate += 1;

	glRotatef(rotate, 0, 1, 0);//设置自转方式
	glRotatef(rotate, 1, 0, 0);
	glRotatef(rotate, 0, 0, 1);

	drawWire();
	glutSwapBuffers();
}

int main(int argc, char* argv[])
{
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
	glutInitWindowPosition(100, 100);
	glutInitWindowSize(width, height);
	glutCreateWindow("Sphere");

	init();
	glutDisplayFunc(displayFunc);
	glutIdleFunc(displayFunc);//回调函数,产生动画
	glutMainLoop();
}
  • 通过命令emcc main.cpp -s WASM=1 -s LEGACY_GL_EMULATION=1 -o index.html生成.js.wasm.html文件
  • 通过命令emrun --no_browser --port 8080 index.html在浏览器上查看绘制的球体效果图

运行结果如下:

发布了315 篇原创文章 · 获赞 119 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/w144215160044/article/details/100159979