GLES3.0中文API-glGetActiveUniform详解

前言

         glGetActiveUniform()函数看了官方的解释,也看了别人的一些帖子,但是基本上都没有实际的代码,没有实操总觉得隔了一层,雾里看花理解不了。下面亲自写段代码验证下这个函数。

官方文档

官方文档解释

Name

glGetActiveUniform — Returns information about an active uniform variable for the specified program object

C Specification

void glGetActiveUniform(GLuint program,
GLuint index,
GLsizei bufSize,
GLsizei *length,
GLint *size,
GLenum *type,
GLchar *name);

Parameters

program

Specifies the program object to be queried.

index

Specifies the index of the uniform variable to be queried.

bufSize

Specifies the maximum number of characters OpenGL is allowed to write in the character buffer indicated by name.

length

Returns the number of characters actually written by OpenGL in the string indicated by name (excluding the null terminator) if a value other than NULL is passed.

size

Returns the size of the uniform variable.

type

Returns the data type of the uniform variable.

name

Returns a null terminated string containing the name of the uniform variable.

Description

glGetActiveUniform returns information about an active uniform variable in the program object specified by program. The number of active uniform variables can be obtained by calling glGetProgramiv with the value GL_ACTIVE_UNIFORMS. A value of zero for index selects the first active uniform variable. Permissible values for index range from zero to the number of active uniform variables minus one.

Shaders may use either built-in uniform variables, user-defined uniform variables, or both. Built-in uniform variables have a prefix of "gl_" and reference existing OpenGL state or values derived from such state (e.g., gl_DepthRange, see the OpenGL Shading Language specification for a complete list.) User-defined uniform variables have arbitrary names and obtain their values from the application through calls to glUniform. A uniform variable (either built-in or user-defined) is considered active if it is determined during the link operation that it may be accessed during program execution. Therefore, program should have previously been the target of a call to glLinkProgram, but it is not necessary for it to have been linked successfully.

The size of the character buffer required to store the longest uniform variable name in program can be obtained by calling glGetProgramiv with the value GL_ACTIVE_UNIFORM_MAX_LENGTH. This value should be used to allocate a buffer of sufficient size to store the returned uniform variable name. The size of this character buffer is passed in bufSize, and a pointer to this character buffer is passed in name.

glGetActiveUniform returns the name of the uniform variable indicated by index, storing it in the character buffer specified by name. The string returned will be null terminated. The actual number of characters written into this buffer is returned in length, and this count does not include the null termination character. If the length of the returned string is not required, a value of NULL can be passed in the length argument.

The type argument will return a pointer to the uniform variable's data type. The symbolic constants returned for uniform types are shown in the table below.

Returned Symbolic ContantShader Uniform Type
GL_FLOATfloat
GL_FLOAT_VEC2vec2
GL_FLOAT_VEC3vec3
GL_FLOAT_VEC4vec4
GL_INTint
GL_INT_VEC2ivec2
GL_INT_VEC3ivec3
GL_INT_VEC4ivec4
GL_UNSIGNED_INTunsigned int
GL_UNSIGNED_INT_VEC2uvec2
GL_UNSIGNED_INT_VEC3uvec3
GL_UNSIGNED_INT_VEC4uvec4
GL_BOOLbool
GL_BOOL_VEC2bvec2
GL_BOOL_VEC3bvec3
GL_BOOL_VEC4bvec4
GL_FLOAT_MAT2mat2
GL_FLOAT_MAT3mat3
GL_FLOAT_MAT4mat4
GL_FLOAT_MAT2x3mat2x3
GL_FLOAT_MAT2x4mat2x4
GL_FLOAT_MAT3x2mat3x2
GL_FLOAT_MAT3x4mat3x4
GL_FLOAT_MAT4x2mat4x2
GL_FLOAT_MAT4x3mat4x3
GL_SAMPLER_2Dsampler2D
GL_SAMPLER_3Dsampler3D
GL_SAMPLER_CUBEsamplerCube
GL_SAMPLER_2D_SHADOWsampler2DShadow
GL_SAMPLER_2D_ARRAYsampler2DArray
GL_SAMPLER_2D_ARRAY_SHADOWsampler2DArrayShadow
GL_SAMPLER_2D_MULTISAMPLEsampler2DMS
GL_SAMPLER_2D_MULTISAMPLE_ARRAYsampler2DMSArray
GL_SAMPLER_CUBE_SHADOWsamplerCubeShadow
GL_SAMPLER_CUBE_MAP_ARRAYsamplerCubeArray
GL_SAMPLER_CUBE_MAP_ARRAY_SHADOWsamplerCubeArrayShadow
GL_SAMPLER_BUFFERsamplerBuffer
GL_INT_SAMPLER_2Disampler2D
GL_INT_SAMPLER_3Disampler3D
GL_INT_SAMPLER_CUBEisamplerCube
GL_INT_SAMPLER_2D_ARRAYisampler2DArray
GL_INT_SAMPLER_2D_MULTISAMPLEisampler2DMS
GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAYisampler2DMSArray
GL_INT_SAMPLER_CUBE_MAP_ARRAYisamplerCubeArray
GL_INT_SAMPLER_BUFFERisamplerBuffer
GL_UNSIGNED_INT_SAMPLER_2Dusampler2D
GL_UNSIGNED_INT_SAMPLER_3Dusampler3D
GL_UNSIGNED_INT_SAMPLER_CUBEusamplerCube
GL_UNSIGNED_INT_SAMPLER_2D_ARRAYusampler2DArray
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLEusampler2DMS
GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAYusampler2DMSArray
GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAYusamplerCubeArray
GL_UNSIGNED_INT_SAMPLER_BUFFERusamplerBuffer
GL_IMAGE_2Dimage2D
GL_IMAGE_3Dimage3D
GL_IMAGE_CUBEimageCube
GL_IMAGE_2D_ARRAYimage2DArray
GL_IMAGE_CUBE_MAP_ARRAYimageCubeArray
GL_IMAGE_BUFFERimageBuffer
GL_INT_IMAGE_2Diimage2D
GL_INT_IMAGE_3Diimage3D
GL_INT_IMAGE_CUBEiimageCube
GL_INT_IMAGE_2D_ARRAYiimage2DArray
GL_INT_IMAGE_CUBE_MAP_ARRAYiimageCubeArray
GL_INT_IMAGE_BUFFERiimageBuffer
GL_UNSIGNED_INT_IMAGE_2Duimage2D
GL_UNSIGNED_INT_IMAGE_3Duimage3D
GL_UNSIGNED_INT_IMAGE_CUBEuimageCube
GL_UNSIGNED_INT_IMAGE_2D_ARRAYuimage2DArray
GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAYuimageCubeArray
GL_UNSIGNED_INT_IMAGE_BUFFERuimageBuffer
GL_UNSIGNED_INT_ATOMIC_COUNTERatomic_uint

If one or more elements of an array are active, the name of the array is returned in name, the type is returned in type, and the size parameter returns the highest array element index used, plus one, as determined by the compiler and/or linker. Only one active uniform variable will be reported for a uniform array. If the active uniform is an array, the uniform name returned in name will always be the name of the uniform array appended with "[0]".

Uniform variables that are declared as structures or arrays of structures will not be returned directly by this function. Instead, each of these uniform variables will be reduced to its fundamental components containing the "." and "[]" operators such that each of the names is valid as an argument to glGetUniformLocation. Each of these reduced uniform variables is counted as one active uniform variable and is assigned an index. A valid name cannot be a structure, an array of structures, or a subcomponent of a vector or matrix.

The size of the uniform variable will be returned in size. Uniform variables other than arrays will have a size of 1. Structures and arrays of structures will be reduced as described earlier, such that each of the names returned will be a data type in the earlier list. If this reduction results in an array, the size returned will be as described for uniform arrays; otherwise, the size returned will be 1.

The list of active uniform variables may include both built-in uniform variables (which begin with the prefix "gl_") as well as user-defined uniform variable names.

This function will return as much information as it can about the specified active uniform variable. If no information is available, length will be 0, and name will be an empty string. This situation could occur if this function is called after a link operation that failed. If an error occurs, the return values lengthsizetype, and name will be unmodified.

Errors

GL_INVALID_VALUE is generated if program is not a value generated by OpenGL.

GL_INVALID_OPERATION is generated if program is not a program object.

GL_INVALID_VALUE is generated if index is greater than or equal to the number of active uniform variables in program.

GL_INVALID_VALUE is generated if bufSize is less than 0.

Associated Gets

glGet with argument GL_MAX_VERTEX_UNIFORM_COMPONENTSGL_MAX_FRAGMENT_UNIFORM_COMPONENTSGL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS, or GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS.

glGetProgramiv with argument GL_ACTIVE_UNIFORMS or GL_ACTIVE_UNIFORM_MAX_LENGTH.

glIsProgram

API Version Support

OpenGL ES API Version
Function Name2.03.03.13.2
glGetActiveUniform

See Also

glGetUniformglGetUniformLocationglLinkProgramglUniformglUseProgram

Copyright

Copyright © 2003-2005 3Dlabs Inc. Ltd. Copyright © 2010-2015 Khronos Group This material may be distributed subject to the terms and conditions set forth in the Open Publication License, v 1.0, 8 June 1999. http://opencontent.org/openpub/.

中文翻译

    这里感谢

flycatdeng

flycatdeng的翻译

名称

glGetActiveUniform - 返回有关活动统一变量的信息

C规范

void glGetActiveUniform(GLuint program,

                                                 GLuint index,

                                                 GLsizei bufSize,

                                                 GLsizei *length,

                                                 GLint *size,

                                                 GLenum *type,

                                                 GLchar *name);

参数

program

指定要查询的程序对象。

index

指定要查询的统一变量的索引。

bufSize

指定允许OpenGL在由name指示的字符缓冲区中写入的最大字符数。

length

如果传递NULL以外的值,则返回由name指示的字符串中的OpenGL实际写入的字符数(不包括空终止符)。

size

返回统一变量的大小。

type

返回统一变量的数据类型。

name

返回包含统一变量名称的以null结尾的字符串。

描述

glGetActiveUniform返回有关程序指定的程序对象中的活动统一变量的信息。可以通过使用值GL_ACTIVE_UNIFORMS调用glGetProgramiv来获得活动的统一变量的数量。索引的值为0的是选择第一个活动的统一变量。索引的允许值范围从0到活动统一变量的数量减1。

着色器可以使用内置的统一变量,用户定义的统一变量或两者。内置的统一变量具有前缀“gl_”并且引用现有的OpenGL状态或从这种状态导出的值(例如,gl_DepthRange)。用户定义的统一变量具有任意名称,并通过调用glUniform从应用程序获取它们的值。如果在链接操作期间确定可以在程序执行期间访问它,则统一变量(内置或用户定义)被认为是活动的。因此,程序之前应该是调用glLinkProgram的目标,但它没有必要成功链接。

在程序中存储最长的统一变量名所需的字符缓冲区的大小可以通过调用值为GL_ACTIVE_UNIFORM_MAX_LENGTHglGetProgramiv来获得。此值应用于分配足够大小的缓冲区来存储返回的统一变量名称。该字符缓冲区的大小在bufSize中传递,并且在该名称中传递指向该字符缓冲区的指针。

glGetActiveUniform返回由index指示的统一变量的名称,将其存储在name指定的字符缓冲区中。返回的字符串将以null结尾。写入此缓冲区的实际字符数以长度形式返回,并且此计数不包括空终止字符。如果不需要返回字符串的长度,则可以在length参数中传递NULL值。

type参数将返回指向统一变量数据类型的指针。可以返回符号常数GL_FLOATGL_FLOAT_VEC2GL_FLOAT_VEC3GL_FLOAT_VEC4GL_INT_GLEC_VEC2GL_INT_VEC3GL_INT_VEC4GL_BOOLGL_BOOL_VEC2GL_BOOL_VEC3GL_BOOL_VEC4GL_FLOAT_MAT2GL_FLOAT_MAT3GL_FLOAT_MAT4GL_SAMPLER_2DGL_SAMPLER_CUBE

如果数组的一个或多个元素处于活动状态,则在name中返回数组的名称,类型以type返回,并且size参数返回使用的最高数组元素索引加上1,具体由编译器确定和/或链接器。对于统一阵列,仅报告一个活动的统一变量。

声明为结构或结构数组的统一变量不会由此函数直接返回。相反,这些统一变量中的每一个都将被简化为包含“.”和“[]”运算符的基本组成部分,使得每个名称作为glGetUniformLocation的参数有效。

统一变量的大小将以size返回。除数组之外的统一变量将具有1的维度大小。结构和结构数组将如前所述减少,使得返回的每个名称将是先前列表中的数据类型。

活动统一变量列表可以包括内置的统一变量(以前缀“gl_”开头)以及用户定义的统一变量名称。

此函数将返回尽可能多的有关指定的活动统一变量的信息。如果没有可用信息,则length为0,name为空字符串(如果在失败的链接操作后调用此函数,则可能发生这种情况)。如果发生错误,则返回值lengthsizetypename将不会被修改。

错误

GL_INVALID_VALUEprogram不是OpenGL生成的值。

GL_INVALID_OPERATIONprogram不是程序对象。

GL_INVALID_VALUEindex>=程序中活动统一变量的数量。

GL_INVALID_VALUEbufSize<0

相关Gets

glGet 参数GL_MAX_VERTEX_UNIFORM_VECTORSGL_MAX_FRAGMENT_UNIFORM_VECTORS

glGetProgramiv 参数GL_ACTIVE_UNIFORMSGL_ACTIVE_UNIFORM_MAX_LENGTH

glIsProgram

另见

glGetActiveAttribglGetUniformglGetUniformLocationglLinkProgramglUniformglUseProgram

版权

https://www.khronos.org/registry/OpenGL-Refpages/es2.0/xhtml/glGetActiveUniform.xml

https://blog.csdn.net/flycatdeng

Copyright © 1991-2006 Silicon Graphics, Inc.本文档的许可是根据SGI Free Software B License.详见http://oss.sgi.com/projects/FreeB/.

代码

//
//    Demonstrates drawing multiple objects in a single draw call with
//    geometry instancing
//

#include "esUtil.h"
#include <stdlib.h>
#include <math.h>

//随机种子
#ifdef _WIN32
#define srandom srand
#define random  rand
#endif

//函数功能:找到uniform统一变量的位置
//glGetUniformLocation()

//函数功能:加载uniform统一变量值
//glUniform1f()
//glUniformMatrix4fv()





#define NUM_INSTANCES					100
#define POSITION_LOC					0
#define COLOR_LOC						1
#define	MVP_LOC							2

typedef struct
{
	// Handle to a program object
	GLuint programObject;

	// VBOs
	GLuint positionVBO;
	GLuint colorVBO;
	GLuint mvpVBO;
	GLuint indicesIBO;

	// Number of indices
	int    numIndices;

	// Rotation angle
	GLfloat angle[NUM_INSTANCES];
}UserData;


void test(ESContext* esContext)
{
	UserData* userData = esContext->userData;
	GLint maxUniformLen;
	GLint numUniforms;
	char* uniformName;
	GLint index;
	glGetProgramiv(userData->programObject, GL_ACTIVE_UNIFORMS, &numUniforms);
	glGetProgramiv(userData->programObject, GL_ACTIVE_UNIFORM_MAX_LENGTH,
		&maxUniformLen);
	uniformName = malloc(sizeof(char) * maxUniformLen);
	for (index = 0; index < numUniforms; index++)
	{
		GLint size;
		GLenum type;
		GLint location;
		// Get the uniform info
		glGetActiveUniform(userData->programObject, index, maxUniformLen, NULL,
			&size, &type, uniformName);
		// Get the uniform location
		location = glGetUniformLocation(userData->programObject, uniformName);
		switch (type)
		{
		case GL_FLOAT:
			//
			break;
		case GL_FLOAT_VEC2:
			//
			break;
		case GL_FLOAT_VEC3:
			//
			break;
		case GL_FLOAT_VEC4:
			//
			break;
		case GL_INT:
			//
			break;
			// ... Check for all the types ...
		default:
			// Unknown type

			break;
		}
	}
}


// 打印日志信息
void PrintLogMessage(ESContext* esContext, const char* msg)
{
	UserData* userData = esContext->userData;
	//GLint infoLen = GL_INFO_LOG_LENGTH;
	GLint infoLen = 512;
	char* infoLog = malloc(sizeof(char) * 512);
	glGetProgramInfoLog(userData->programObject, infoLen, &infoLen, infoLog);
	GLint headLen = strlen("Invoke ");
	strcpy_s(infoLog, headLen + 3, "Invoke ");  //这里长度必须+1,要覆盖'\0',否则越界,vs2019边界检查更严格
	/********* (1)src和dest所指内存区域不可以重叠且dest必须有足够的空间来容纳src的字符串。
	/*********(2)strcat返回值有什么作用? 链式传递:strcat(a, strcat(b, c));
	/********* 最重要的是,strcat函数不检查这些。*********/
	//strcat(infoLog, "Invoke ");
											  //strcat_s(infoLog, msg, strlen(msg)+1);
	int strMsgSize = strlen(msg);
	int strInfoSize = strlen(infoLog);
	//注意!!!strcat_s()第二个参数的大小是 src+des+1总和大小,+1是'\0'的大小
	int retStatue = strcat_s(infoLog, strMsgSize + strInfoSize + 1, msg);
	esLogMessage(" failed:Error message:%s\n", infoLog);

	free(infoLog);
}

///
// Initialize the shader and program object
//
int Init(ESContext* esContext)
{
	GLfloat* positions = NULL;
	GLuint* indices = NULL;

	UserData* userData = esContext->userData;
	const char vShaderStr[] =
		"#version 300 es                             \n"
		"layout(location = 0) in vec4 a_position;    \n"
		"layout(location = 1) in vec4 a_color;       \n"
		"layout(location = 2) in mat4 a_mvpMatrix;   \n"
		"out vec4 v_color;                           \n"
		"void main()                                 \n"
		"{                                           \n"
		"   v_color = a_color;                       \n"
		"   gl_Position = a_mvpMatrix * a_position;  \n"
		"}                                           \n";

	const char fShaderStr[] =
		"#version 300 es                                \n"
		"precision mediump float;                       \n"
		"in vec4 v_color;                               \n"
		"layout(location = 0) out vec4 outColor;        \n"
		"void main()                                    \n"
		"{                                              \n"
		"  outColor = v_color;                          \n"
		"}                                              \n";

	// Load the shaders and get a linked program object
	userData->programObject = esLoadProgram(vShaderStr, fShaderStr);

	// Generate the vertex data
	//这里暂时没有用到法线和纹理坐标这2个参数:所以第一个normal是NULL,第二个texCoords是NULL
	userData->numIndices = esGenCube(0.1f, &positions, NULL, NULL, &indices);

	// Index buffer object
	glGenBuffers(1, &userData->indicesIBO);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, userData->indicesIBO);

	//glGetActiveUniform(userData->programObject, 0, NULL, NULL, )
		/****** 功能:更新/修改uniform统一变量缓冲区中的统一变量数据
		* **************/
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * userData->numIndices,
			indices, GL_STATIC_DRAW);
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	//这里为什么要释放局部指针变量,函数调用完成会释放2次?
	free(indices);

	// Position VBO for cube model
	glGenBuffers(1, &userData->positionVBO);
	glBindBuffer(GL_ARRAY_BUFFER, userData->positionVBO);
	//立方体是6个面,每个面4个顶点,所以是6*4=24,为什么还要*3 ????
	glBufferData(GL_ARRAY_BUFFER, 24 * sizeof(GLfloat) * 3, positions, GL_STATIC_DRAW);
	//这里没有恢复到默认绑定状态
	//glBindBuffer(GL_ARRAY_BUFFER, 0);
	free(positions);

	// Random color for each instance
	{
		GLubyte colors[NUM_INSTANCES][4];
		int instance;

		srandom(0);

		for (instance = 0; instance < NUM_INSTANCES; instance++)
		{
			colors[instance][0] = random() % 255;
			//colors[NUM_INSTANCES][0] = random() % 255;

			colors[instance][1] = random() % 255;
			//colors[NUM_INSTANCES][1] = random() % 255;

			colors[instance][2] = random() % 255;
			//colors[NUM_INSTANCES][2] = random() % 255;

			//最后一个alpha值
			colors[instance][3] = 0;
			//colors[instance][3] = 0;
			//colors[NUM_INSTANCES][3] = random() % 255;
		}

		glGenBuffers(1, &userData->colorVBO);
		glBindBuffer(GL_ARRAY_BUFFER, userData->colorVBO);
		//glBufferData(GL_ARRAY_BUFFER, sizeof(GLubyte) * NUM_INSTANCES * 4, colors, GL_STATIC_DRAW);
		GLint gluByteSize = sizeof(GLubyte);
		glBufferData(GL_ARRAY_BUFFER, sizeof(GLubyte) * NUM_INSTANCES * 4, colors, GL_STATIC_DRAW);
	}

	// Allocate storage to store MVP per instance
	{
		int instance;

		// Random angle for each instance, compute the MVP later
		for (instance = 0; instance < NUM_INSTANCES; instance++)
		{
			userData->angle[instance] = (float)(random() % 32768) / 32767.0f * 360;
		}

		glGenBuffers(1, &userData->mvpVBO);
		glBindBuffer(GL_ARRAY_BUFFER, userData->mvpVBO);
		//这里参数为什么是NULL:为实例化存储数据到存储区的指针,如果为NULL,说明不需要拷贝数据
		glBufferData(GL_ARRAY_BUFFER, sizeof(ESMatrix) * NUM_INSTANCES, NULL, GL_DYNAMIC_DRAW);
	}

	//恢复到默认绑定状态
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	glClearColor(1.0f, 0.0f, 1.0f, 1.0f);

	return GL_TRUE;
}

///
// Update MVP matrix based on time
//
void Updata(ESContext* esContext, float deltaTime)
{
	UserData* userData = esContext->userData;
	ESMatrix* matrixBuf;
	ESMatrix  perspective;
	float     aspect;
	int		  instance = 0;
	int		  numRows = 0;
	int		  numColumns = 0;

	// Compute the window aspect ratio
	aspect = (GLfloat)esContext->width / (float)esContext->height;

	// Generate a perspective matrix with a 60 degree FOV
	//esMatrixLoadIdentity(matrixBuf);
	esMatrixLoadIdentity(&perspective);
	esPerspective(&perspective, 45.0f, aspect, 1.0f, 20.0f);

	glBindBuffer(GL_ARRAY_BUFFER, userData->mvpVBO);
	/****** 功能:将缓冲区对象数据存储映射到应用程序的地址空间,这个指针供应用程序使用,
	/****** 以读取和更新缓冲区对象的内容。他可以代替**************/
	/****** glBufferData或者glBufferSubData函数,以减少程序内存占用     ********/
	/****** 返回值:返回请求的缓冲区数据存储范围的指针    ********/
	/****** GL_MAP_READ_BIT:表示返回的指针可用于读取缓冲区对象数据。
	*       如果指针用于查询排除此标志的映射,则不会产生GL错误,
	*       但结果是未定义的,并且可能发生系统错误(可能包括程序终止)。
	/****** GL_MAP_WRITE_BIT:表示返回的指针可用于修改缓冲区对象数据。
	/*      如果指针用于修改一个排除此标志的映射,则不会产生GL错误,
	/*      但结果是未定义的,并且可能发生系统错误(可能包括程序终止)。
	* ********/
	matrixBuf = glMapBufferRange(GL_ARRAY_BUFFER, 0,
		sizeof(ESMatrix) * NUM_INSTANCES,
		GL_MAP_WRITE_BIT);

	// Compute a per-instance MVP that translates and rotates each instance differently
	numRows = (int)sqrtf(NUM_INSTANCES);
	numColumns = numRows;

	for (instance = 0; instance < NUM_INSTANCES; instance++)
	{
		ESMatrix modelView;
		float translateX = ((float)(instance % numRows) / (float)(numRows)) * 2.0f - 1.0f;
		float translateY = ((float)(instance / numColumns) / (float)(numColumns)) * 2.0f - 1.0f;

		// Generate a model view matrix to rotate/translate the cube
		esMatrixLoadIdentity(&modelView);

		// Per-instance translation
		esTranslate(&modelView, translateX, translateY, -2.0f);

		// Compute a rotation angle based on time to rotate the cube
		userData->angle[instance] += (deltaTime * 40.0f);

		if (userData->angle[instance] >= 360.0f)
		{
			userData->angle[instance] -= 360.0f;
		}

		// Rotate the cube
		esRotate(&modelView, userData->angle[instance], 1.0f, 0.0f, 1.0f);

		// Compute the final MVP by multiplying the
		// modeler's and perspective matrices together
		//matrixBuf[instance]:乘积,modelView:被乘数,perspective:乘数
		esMatrixMultiply(&matrixBuf[instance], &modelView, &perspective);
	}

	// 指示更新已经完成和释放映射的指针
	glUnmapBuffer(GL_ARRAY_BUFFER);
}

///
// Draw a triangle using the shader pair created in Init()
//
void Draw(ESContext* esContext)
{
	UserData* userData = esContext->userData;
	GLfloat* indices;

	// Set the viewport
	glViewport(0, 0, esContext->width, esContext->height);

	// Clear the color buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Use the program object
	glUseProgram(userData->programObject);

	// Load the vertex position
	glBindBuffer(GL_ARRAY_BUFFER, userData->positionVBO);
	glVertexAttribPointer(POSITION_LOC, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat),
		(GLvoid*)NULL);
	glEnableVertexAttribArray(POSITION_LOC);

	// Load the instance color buffer
	glBindBuffer(GL_ARRAY_BUFFER, userData->colorVBO);
	//为什么不用glBufferData(),因为在Init()初始化时调用过了
	//glBufferData(GL_ARRAY_BUFFER, 4 * sizeof(GLfloat) * NUM_INSTANCES, indices, GL_DYNAMIC_DRAW);
	//把最后一个参数变成(GLvoid*)(3 * sizeof(GLint)颜色更好看
	glVertexAttribPointer(COLOR_LOC, 4, GL_UNSIGNED_BYTE, GL_TRUE,
		4 * sizeof(GLubyte),
		(GLvoid*)(3 * sizeof(GLint)));
	//最后一个参数为什么是NULL
	/*glVertexAttribPointer(COLOR_LOC, 4, GL_UNSIGNED_BYTE, GL_FLOAT, GL_FALSE,
						  4 * sizeof(GLubyte), (GLvoid*)(NULL));*/
	glEnableVertexAttribArray(COLOR_LOC);

	/****** 功能:访问每个实例的颜色数据
	/****** 参数:COLOR_LOC:指定顶点颜色属性索引
	/****** 参数:1:指定COLOR_LOC索引位置的通用颜色属性更新之间传递的是实例数量
	*       如果divisor=0:默认情况下,如果没有指定,或者顶点属性的divisor等于0,
	*       对每个顶点将读取一次顶点属性;
	*       如果divisor=1:则每个图元实例颜色属性读取一次顶点属性
	******/
	glVertexAttribDivisor(COLOR_LOC, 1);

	// Load the instance MVP buffer
	glBindBuffer(GL_ARRAY_BUFFER, userData->mvpVBO);

	// Load each matrix row of the MVP.  Each row gets an increasing attribute location.
	glVertexAttribPointer(MVP_LOC + 0, 4, GL_FLOAT, GL_FALSE,
		sizeof(ESMatrix), (GLvoid*)NULL);
	glVertexAttribPointer(MVP_LOC + 1, 4, GL_FLOAT, GL_FALSE,
		sizeof(ESMatrix), (GLvoid*)(4 * sizeof(GLfloat)));
	glVertexAttribPointer(MVP_LOC + 2, 4, GL_FLOAT, GL_FALSE,
		sizeof(ESMatrix), (GLvoid*)(8 * sizeof(float)));
	glVertexAttribPointer(MVP_LOC + 3, 4, GL_FLOAT, GL_FALSE,
		sizeof(ESMatrix), (GLvoid*)(12 * sizeof(GLfloat)));
	glEnableVertexAttribArray(MVP_LOC + 0);
	glEnableVertexAttribArray(MVP_LOC + 1);
	glEnableVertexAttribArray(MVP_LOC + 2);
	glEnableVertexAttribArray(MVP_LOC + 3);

	/****** 功能:访问每个实例的颜色数据
	/****** 参数:MVP_LOC:指定模型视图投影矩阵(modelViewProjectionMatrix)位置属性索引
	/****** 参数:1:指定MVP_LOC索引位置的通用颜色属性更新之间传递的是实例数量
	*       如果divisor=0:默认情况下,如果没有指定,或者顶点属性的divisor等于0,
	*       对每个顶点将读取一次顶点属性;
	*       如果divisor=1:则每个图元实例颜色属性读取一次顶点属性
	*       One MVP per instance
	******/
	glVertexAttribDivisor(MVP_LOC + 0, 1);
	glVertexAttribDivisor(MVP_LOC + 1, 1);
	glVertexAttribDivisor(MVP_LOC + 2, 1);
	glVertexAttribDivisor(MVP_LOC + 3, 1);

	// Bind the index buffer  索引缓冲区对象
	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, userData->indicesIBO);

	// Draw the cubes
	glDrawElementsInstanced(GL_TRIANGLES, userData->numIndices, GL_UNSIGNED_INT,
		NULL, NUM_INSTANCES);
}

///
// Cleanup
//
void Shutdown(ESContext* esContext)
{
	UserData* userData = esContext->userData;

	glDeleteBuffers(1, &userData->positionVBO);
	glDeleteBuffers(1, &userData->colorVBO);
	glDeleteBuffers(1, &userData->mvpVBO);
	glDeleteBuffers(1, &userData->indicesIBO);

	// Delete program object
	glDeleteProgram(userData->programObject);
}

int esMain(ESContext* esContext)
{
	esContext->userData = malloc(sizeof(UserData));

	GLboolean createWindowStatue = esCreateWindow(esContext, "openGLESExample_7_Instancing", 800, 600, ES_WINDOW_RGB);
	if (GL_FALSE == createWindowStatue)
	{
		PrintLogMessage(esContext, "esCreateWindow");
		return GL_FALSE;
	}

	if (!Init(esContext))
	{
		PrintLogMessage(esContext, "Init");
		return GL_FALSE;
	}

	esRegisterShutdownFunc(esContext, Shutdown);
	esRegisterUpdateFunc(esContext, Updata);
	esRegisterDrawFunc(esContext, Draw);

	return GL_TRUE;
}

程序运行效果

 稍微修改202行的代码,让透明度也随机

 运行效果如下

工程源码下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: gles2-gears是一个基于OpenGL ES 2.0的图形渲染示例程序。该程序主要用于演示OpenGL ES 2.0中的基本图形渲染功能和性能。它由几个齿轮组成,每个齿轮由多个三角形组成,通过旋转和平移操作,可以观察到各个齿轮之间的相互作用和渲染效果。 通过使用OpenGL ES 2.0,gles2-gears可以利用硬件加速图形渲染,提供高性能的图形处理能力。它支持通过着色器程序来实现各种渲染效果,如光照、阴影和纹理等。同时,该示例程序也提供了用户交互接口,用户可以通过触摸或鼠标操作来改变齿轮的旋转速度和方向,从而观察不同的视觉效果。 gles2-gears不仅是一个学习OpenGL ES 2.0的示例程序,也是一个性能测试工具。通过改变齿轮数量和分辨率等参数,可以测试设备对于大规模场景和高分辨率渲染的性能表现。这对于开发者来说是非常有价值的,可以帮助他们评估设备的图形处理能力,并根据测试结果进行相应的优化。 总而言之,gles2-gears是一个基于OpenGL ES 2.0的演示和性能测试程序,可以帮助开发者学习和评估设备的图形处理能力。它充分利用硬件加速,通过渲染齿轮的旋转和交互操作,展示了OpenGL ES 2.0的高性能实时图形渲染能力。 ### 回答2: gles2-gears是一个基于OpenGL ES 2.0的开源项目,它展示了使用OpenGL ES 2.0绘制的齿轮模型。它是一个典型的图形学示例,用于演示OpenGL ES 2.0的功能和特性。 在gles2-gears中,通过使用OpenGL ES 2.0的着色器语言GLSL,实现了光照、纹理贴图等高级渲染技术。整个场景由齿轮模型组成,通过旋转、缩放等操作,可以观察到齿轮之间的互动效果。 gles2-gears的源代码可用于学习OpenGL ES 2.0编程,了解图形渲染的基本原理和技术。通过阅读和理解其代码结构和逻辑,可以了解OpenGL ES 2.0的编程模式和渲染流程。 此外,gles2-gears还可以用作性能测试工具,用于测试硬件设备的图形渲染性能。通过调整渲染分辨率、齿轮数量等参数,可以评估设备的图形处理能力,并进行性能对比。 总的来说,gles2-gears是一个教育和性能测试的工具,用于展示和验证OpenGL ES 2.0的功能和性能。无论是初学者还是专业开发者,都可以使用它来学习和优化图形渲染技术。 ### 回答3: gles2-gears是一个使用OpenGL ES 2.0图形库编写的一个开源项目,它展示了三个互动的齿轮,用于测试和演示OpenGL ES 2.0的性能和功能。 在它的实现过程中,作者使用了OpenGL ES 2.0的着色器语言GLSL来处理图形渲染。齿轮之间的转动是通过在每个齿轮上应用旋转变换来实现的,通过修改齿轮的旋转角度和速度,可以调整和控制齿轮之间的相对运动。此外,作者还为齿轮和整个场景设计了适当的材质、光照和阴影效果,以增强视觉效果。 这个项目最初是为了展示OpenGL ES 2.0在移动设备上的性能和功能而创建的,但它也可以在其他支持OpenGL ES 2.0的平台上运行。用户可以通过触摸或鼠标交互来控制和改变齿轮的旋转和速度,从而创建不同的视觉效果和交互体验。 值得一提的是,该项目的源代码开放,并经常作为一种教学工具,帮助人们学习和理解OpenGL ES 2.0的基本概念和应用技巧。许多人使用和修改这个项目,以满足不同的需求和目标。 总的来说,gles2-gears是一个展示和测试OpenGL ES 2.0在三维图形渲染中的性能和功能的开源项目。它不仅仅是一个演示程序,还可以作为学习和教学工具来帮助人们更好地理解和应用OpenGL ES 2.0。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值