示例#1
0
void FurApplication::Finalize(void)
{
    glUseProgram(0);
    glDeleteProgram(fur_prog);
}
示例#2
0
文件: material.hpp 项目: krig/simplex
	void use() {
		glUseProgram(program);
	}
示例#3
0
int main(int argc, char** argv)
{
    int count = 0;
    double base;
    GLFWwindow* window;

    srand((unsigned int) time(NULL));

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    for (;;)
    {
        int width, height;
        GLFWmonitor* monitor = NULL;
        GLuint vertex_shader, fragment_shader, program, vertex_buffer;
        GLint mvp_location, vpos_location;

        if (count & 1)
        {
            int monitorCount;
            GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
            monitor = monitors[rand() % monitorCount];
        }

        if (monitor)
        {
            const GLFWvidmode* mode = glfwGetVideoMode(monitor);
            width = mode->width;
            height = mode->height;
        }
        else
        {
            width = 640;
            height = 480;
        }

        base = glfwGetTime();

        window = glfwCreateWindow(width, height, "Window Re-opener", monitor, NULL);
        if (!window)
        {
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        if (monitor)
        {
            printf("Opening full screen window on monitor %s took %0.3f seconds\n",
                   glfwGetMonitorName(monitor),
                   glfwGetTime() - base);
        }
        else
        {
            printf("Opening regular window took %0.3f seconds\n",
                   glfwGetTime() - base);
        }

        glfwSetWindowCloseCallback(window, window_close_callback);
        glfwSetKeyCallback(window, key_callback);

        glfwMakeContextCurrent(window);
        gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
        glfwSwapInterval(1);

        vertex_shader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
        glCompileShader(vertex_shader);

        fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
        glCompileShader(fragment_shader);

        program = glCreateProgram();
        glAttachShader(program, vertex_shader);
        glAttachShader(program, fragment_shader);
        glLinkProgram(program);

        mvp_location = glGetUniformLocation(program, "MVP");
        vpos_location = glGetAttribLocation(program, "vPos");

        glGenBuffers(1, &vertex_buffer);
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

        glEnableVertexAttribArray(vpos_location);
        glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                              sizeof(vertices[0]), (void*) 0);

        glfwSetTime(0.0);

        while (glfwGetTime() < 5.0)
        {
            float ratio;
            int width, height;
            mat4x4 m, p, mvp;

            glfwGetFramebufferSize(window, &width, &height);
            ratio = width / (float) height;

            glViewport(0, 0, width, height);
            glClear(GL_COLOR_BUFFER_BIT);

            mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f);

            mat4x4_identity(m);
            mat4x4_rotate_Z(m, m, (float) glfwGetTime());
            mat4x4_mul(mvp, p, m);

            glUseProgram(program);
            glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

            glfwSwapBuffers(window);
            glfwPollEvents();

            if (glfwWindowShouldClose(window))
            {
                close_window(window);
                printf("User closed window\n");

                glfwTerminate();
                exit(EXIT_SUCCESS);
            }
        }

        printf("Closing window\n");
        close_window(window);

        count++;
    }

    glfwTerminate();
}
示例#4
0
void sph_model::set_fade(double k)
{
    glUseProgram(program);
    glUniform1f(fader, k);
}
static void glfw_newwindow(char* name, int heigth, int width)
{
	int major, minor, rev;
	GLenum error;
	GLuint shaders[2];
	GLint  data[4];

	GLfloat vertexData[] = {
		//  X     Y    Z
		-1.0f,-1.0f,-1.0f,   0.0f, 0.0f,
		-1.0f, 1.0f,-1.0f,   0.0f, 1.0f,
		1.0f,-1.0f,-1.0f,   1.0f, 0.0f,
		1.0f,-1.0f,-1.0f,   1.0f, 0.0f,
		-1.0f, 1.0f,-1.0f,   0.0f, 1.0f,
		1.0f, 1.0f,-1.0f,   1.0f, 1.0f
	};

	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
	if(!glfwOpenWindow(width, heigth, 8, 8, 8, 8, 16, 0, GLFW_WINDOW))
		printf("glfwOpenWindow failed. Can your hardware handle OpenGL 3.2?");
    
	if(glewInit() != GLEW_OK)
		printf("glewInit failed");

	glShadeModel(GL_SMOOTH);   
	glClearColor(0.0f, 0.0f, 0.3f, 0.0f);  
	glClearDepth(1.0f);                         // Depth Buffer Setup
			
	glEnable(GL_BLEND);
	glEnable(GL_DEPTH_TEST);                        // Enables Depth Testing
	glEnable(GL_TEXTURE_2D);
	glDepthFunc(GL_LEQUAL);    

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glAlphaFunc( GL_GREATER, 0 );		
	glEnable(GL_POLYGON_SMOOTH);

	// print out some info about the graphics drivers
	printf( "OpenGL version: %s \n", glGetString(GL_VERSION));
	printf( "GLSL version: %s \n",glGetString(GL_SHADING_LANGUAGE_VERSION));
	printf("Vendor: %s\n",glGetString(GL_VENDOR));
	printf("Renderer: %s\n",glGetString(GL_RENDERER));


	shaders[0] = ShaderCreateFromStr(GL_VERTEX_SHADER, vertexShader);
	shaders[1] = ShaderCreateFromStr(GL_FRAGMENT_SHADER, fragmentShader);
	program = ShaderCreateProgram(shaders, 2);

	shaders[0] = ShaderCreateFromStr(GL_VERTEX_SHADER, vertexShader_gui);
	shaders[1] = ShaderCreateFromStr(GL_FRAGMENT_SHADER, fragmentShader);

	program_gui = ShaderCreateProgram(shaders, 2);

	USE_PROGRAM(program);

	error = glGetError();
	if(error != GL_NO_ERROR)
		printf( "OpenGL Error %d: %s\n", error, (const char*)glewGetErrorString(error));

	/*glm::mat4 camera = glm::lookAt(glm::vec3(0,0,1), glm::vec3(0,0,0), glm::vec3(0,1,0));
	ShaderSetUniform(ShaderGetUniform(program,"camera"), 1, glm::value_ptr(camera));
	*/
	glfwSetCamera( 0, 0, 1);

	glm::mat4 projection = glm::perspective<float>(60.0, 800.0f/600, 0.01, 10.0);
	ShaderSetUniform(ShaderGetUniform(currentProgram,"projection"), 1,  glm::value_ptr(projection));
	
	glm::mat4 rotation = glm::rotate(glm::mat4(), 0.0f, glm::vec3(0,1,0));
	ShaderSetUniform(ShaderGetUniform(currentProgram,"model"),1, glm::value_ptr(rotation));

	ShaderSetUniformInt(ShaderGetUniform(currentProgram,"debug"), 1);
	ShaderSetUniform4f(ShaderGetUniform(currentProgram,"debugcolor"), 0.0, 0, 0, 0.0f);

	USE_PROGRAM(0);
	USE_PROGRAM(program_gui);

	glfwSetCamera_ext( "projection", 0,0, 60);
	rotation = glm::rotate(glm::mat4(), 0.0f, glm::vec3(0,1,0));
	ShaderSetUniform(ShaderGetUniform(currentProgram,"model"),1, glm::value_ptr(rotation));

	ShaderSetUniformInt(ShaderGetUniform(currentProgram,"debug"), 1);
	ShaderSetUniform4f(ShaderGetUniform(currentProgram,"debugcolor"), 0.0, 0, 0, 0.0f);

	glUseProgram(0);

	glGenVertexArrays(1, &gVAO);
	glBindVertexArray(gVAO);

	// make and bind the VBO
	glGenBuffers(1, &gVBO);
	glBindBuffer(GL_ARRAY_BUFFER, gVBO);
	// Put the three triangle verticies into the VBO

	glBufferData(GL_ARRAY_BUFFER, sizeof(vertexData), vertexData, GL_STATIC_DRAW);

	// connect the xyz to the "vert" attribute of the vertex shader
	glEnableVertexAttribArray(ShaderGetAttrib(program, "vert"));
	glVertexAttribPointer(ShaderGetAttrib(program, "vert"), 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), NULL);

	// connect the uv coords to the "vertTexCoord" attribute of the vertex shader
	glEnableVertexAttribArray(ShaderGetAttrib(program,"vertTexCoord"));
	glVertexAttribPointer(ShaderGetAttrib(program,"vertTexCoord"), 2, GL_FLOAT, GL_TRUE,  5*sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat)));
    
		// connect the xyz to the "vert" attribute of the vertex shader
	glEnableVertexAttribArray(ShaderGetAttrib(program_gui, "vert"));
	glVertexAttribPointer(ShaderGetAttrib(program_gui, "vert"), 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), NULL);

	// connect the uv coords to the "vertTexCoord" attribute of the vertex shader
	glEnableVertexAttribArray(ShaderGetAttrib(program_gui,"vertTexCoord"));
	glVertexAttribPointer(ShaderGetAttrib(program_gui,"vertTexCoord"), 2, GL_FLOAT, GL_TRUE,  5*sizeof(GLfloat), (const GLvoid*)(3 * sizeof(GLfloat)));
    

	glBindBuffer(GL_ARRAY_BUFFER, 0);
	glBindVertexArray(0);

	error = glGetError();
	if(error != GL_NO_ERROR)
		printf( "OpenGL Error %d: %s\n", error, (const char*)glewGetErrorString(error));

		glfwSetMousePos(800/2, 600/2);
		glfwDisable(GLFW_MOUSE_CURSOR);
}
示例#6
0
// ----------------------------------------------------------- build_buffer ---
void
build_buffer( void )
{ 
    vec2 pen;
    texture_font_t *font;
    vec4 black  = {{0.0, 0.0, 0.0, 1.0}};
    vec4 white  = {{1.0, 1.0, 1.0, 1.0}};
    vec4 none   = {{1.0, 1.0, 1.0, 0.0}};
    vec4 color = white;
    if( p_invert )
    {
        color = black;
    }

    markup_t markup = {
        .family  = "Source Sans Pro",
        .size    = 10.0,
        .bold    = 0,
        .italic  = 0,
        .rise    = 0.0,
        .spacing = p_interval,
        .gamma   = p_gamma,
        .foreground_color    = color,
        .background_color    = none,
        .underline           = 0,
        .underline_color     = color,
        .overline            = 0,
        .overline_color      = color,
        .strikethrough       = 0,
        .strikethrough_color = color,
        .font = 0,
    };

    text_buffer_clear( buffer );
    texture_atlas_t * atlas = buffer->manager->atlas;
    texture_atlas_clear( atlas );

    if( p_family == VERA)
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/Vera.ttf" );
    }
    else if( p_family == VERA_MONO)
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/VeraMono.ttf" );
    }
    else if( p_family == LUCKIEST_GUY)
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/LuckiestGuy.ttf" );
    }
    else if( p_family == SOURCE_SANS )
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/SourceSansPro-Regular.ttf" );
    }
    else if( p_family == SOURCE_CODE )
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/SourceCodePro-Regular.ttf" );
    }
    else if( p_family == OLD_STANDARD )
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/OldStandard-Regular.ttf" );
    }
    else if( p_family == LOBSTER )
    {
        font = texture_font_new_from_file( atlas, p_size, "fonts/Lobster-Regular.ttf" );
    }
    else
    {
        fprintf( stderr, "Error : Unknown family type\n" );
        return;
    }

	if (!font)
		return;

    markup.font = font;
    font->hinting = p_hinting;
    font->kerning = p_kerning;
    font->filtering = 1;
    float norm = 1.0/(p_primary + 2*p_secondary + 2*p_tertiary);
    font->lcd_weights[0] = (unsigned char)(p_tertiary*norm*256);
    font->lcd_weights[1] = (unsigned char)(p_secondary*norm*256);
    font->lcd_weights[2] = (unsigned char)(p_primary*norm*256);
    font->lcd_weights[3] = (unsigned char)(p_secondary*norm*256);
    font->lcd_weights[4] = (unsigned char)(p_tertiary*norm*256);
    pen.x = 10;
    pen.y = 600 - font->height - 10;
    text_buffer_printf( buffer, &pen, &markup, text, NULL );

    // Post-processing for width and orientation
    vertex_buffer_t * vbuffer = buffer->buffer;
    size_t i;
    for( i=0; i < vector_size( vbuffer->items ); ++i )
    {
        ivec4 *item = (ivec4 *) vector_get( vbuffer->items, i);
        glyph_vertex_t * v0 = /* x0,y0 */
            (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+0 );
        //glyph_vertex_t * v1 = /* x0,y1 */
        //    (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+1 );
        glyph_vertex_t * v2 = /* x1,y1 */
            (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+2 );
        glyph_vertex_t * v3 = /* x1,y0 */
            (glyph_vertex_t *) vector_get( vbuffer->vertices, item->vstart+3 );

        float x0 = v0->x, y0 = v0->y;
        float x1 = v2->x, y1 = v2->y;
        v2->x = v3->x = x0 + (x1-x0)*p_width;

        float dy = abs(y1-y0);
        float dx = tan(p_faux_italic/180.0 * M_PI) * dy;
        v0->x += dx;
        v0->shift = fmod(v0->shift + dx-(int)(dx),1.0); 
        v3->x += dx;
        v3->shift = fmod(v3->shift + dx-(int)(dx),1.0); 
    }


    texture_font_delete( font );
}



// ---------------------------------------------------------------- display ---
void display(void)
{
    vec4 black  = {{0.0, 0.0, 0.0, 1.0}};
    vec4 white  = {{1.0, 1.0, 1.0, 1.0}};

    if( !p_invert )
    {
        glClearColor( 0, 0, 0, 1 );
        buffer->base_color = white;
                
    }
    else
    {
        glClearColor( 1, 1, 1, 1 );
        buffer->base_color = black;
    }
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    glUseProgram( buffer->shader );
    {
        glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "model" ),
                            1, 0, model.data);
        glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "view" ),
                            1, 0, view.data);
        glUniformMatrix4fv( glGetUniformLocation( buffer->shader, "projection" ),
                            1, 0, projection.data);
        text_buffer_render( buffer );
    }

    TwDraw( );
    glutSwapBuffers( );
}
示例#7
0
/* rune_DrawChar renders the given rune at char position (x, y) */
void rune_DrawChar(Rune *rune, uint32_t x, uint32_t y)
{
  const GLchar *vs = 
    "#version 150\n"
    "in vec2 pos;\n"
    "in vec2 texco;\n"
    "out vec2 out_texco;\n"
    "uniform sampler2D tex;\n"
    "uniform mat4 mvp;\n"
    "void main()\n"
    "{\n"
    "  out_texco = texco;\n"
    "  gl_Position = mvp * vec4(pos, 0.0, 1.0);\n"
    "}\n";
  const GLchar *fs = 
    "#version 150\n"
    "in vec2 out_texco;\n"
    "uniform sampler2D tex;\n"
    "void main()\n"
    "{\n"
    "  vec4 color = texture(tex, out_texco);\n"
    "  gl_FragColor = color;\n"
    "}\n";
  static GLuint vao = 0;
  static GLuint vbo = 0;
  static GLuint ibo = 0;
  static GLfloat vertices[4 * 4] = { /* 4 vertices. format: x-y-u-v */
    0.0f, 0.0f, 0.0f, 0.0f,
    1.0f, 0.0f, 1.0f, 0.0f,
    1.0f, 1.0f, 1.0f, 1.0f,
    0.0f, 1.0f, 0.0f, 1.0f,
  };
  static GLshort indices[3 * 2] = { /* 2 triangles */
    0, 1, 2,
    0, 3, 2
  };
  static Mat4x4 mvp;
  static GLuint mvpUniform;
  static GLuint texUniform;
  static GLuint shader;
  static GLuint sampler;

  GLenum err;
  GLint compiled, linked;
  CharRune *r;
  GLfloat u, v;

  r = (CharRune*)rune;

  /* load texture */
  if(r->texture == 0){
    r->texture = latin1_to_texture(r->id);
    glGenSamplers(1, &sampler);
    glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
    glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST_MIPMAP_NEAREST);
    glSamplerParameterf(sampler, GL_TEXTURE_MAX_ANISOTROPY_EXT, 16.0f);
  }

  /* create shader program */
  if(shader == 0){
    GLuint frag, vert;
    GLint len;

    /* vertex shader */
    vert = glCreateShader(GL_VERTEX_SHADER);
    len = strlen(vs);
    glShaderSource(vert, 1, &vs, &len);
    glCompileShader(vert);
    glGetShaderiv(vert, GL_COMPILE_STATUS, &compiled);
    if(compiled == GL_FALSE){
      GLint logSz;
      GLchar *log;

      glGetShaderiv(vert, GL_INFO_LOG_LENGTH, &logSz);
      log = malloc(logSz * sizeof(GLchar));
      glGetShaderInfoLog(vert, logSz, &logSz, log);
      puts("error: vertex shader compilation failed");
      puts(log);
      free(log);
    }
    /* fragment shader */
    frag = glCreateShader(GL_FRAGMENT_SHADER);
    len = strlen(fs);
    glShaderSource(frag, 1, &fs, &len);
    glCompileShader(frag);
    glGetShaderiv(frag, GL_COMPILE_STATUS, &compiled);
    if(compiled == GL_FALSE){
      GLint logSz;
      GLchar *log;

      glGetShaderiv(vert, GL_INFO_LOG_LENGTH, &logSz);
      log = malloc(logSz * sizeof(GLchar));
      glGetShaderInfoLog(vert, logSz, &logSz, log);
      puts("error: fragment shader compilation failed");
      puts(log);
      free(log);
    }

    /* link shaders */
    shader = glCreateProgram();
    glAttachShader(shader, vert);
    glAttachShader(shader, frag);
    glBindAttribLocation(shader, 0, "pos");
    glBindAttribLocation(shader, 1, "texco");
    glLinkProgram(shader);
    glGetProgramiv(shader, GL_LINK_STATUS, &linked);
    if(linked == GL_FALSE){
      GLint logSz;
      GLchar *log;

      glGetProgramiv(shader, GL_INFO_LOG_LENGTH, &logSz);
      log = malloc(logSz * sizeof(GLchar));
      glGetProgramInfoLog(shader, logSz, &logSz, log);
      puts(log);
      free(log);
    }
    /* get the uniforms */
    mvpUniform = glGetUniformLocation(shader, "mvp");
    mat4x4_orthographic(&mvp, 0.0f, 80.0f, 0.0f, 40.0f, -1.0f, 1.0f);
    texUniform = glGetUniformLocation(shader, "tex");
  }

  /* create vertex attribute object */
  if(vao == 0){
    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glGenBuffers(1, &ibo);

    /* vertices */
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 4 * 4,
      vertices, GL_STATIC_DRAW);

    /* indices */
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLshort) * 6,
      indices, GL_STATIC_DRAW);
  }

  /* update VBO */
  r->id = 1;
  u = 1.0f / 16.0f * (r->id % 16);
  v = 1.0f / 16.0f * (r->id / 16);
  vertices[0] = x;
  vertices[1] = y;
  //vertices[2] = u;
  //vertices[3] = v;

  vertices[0+4] = x + rune->w;
  vertices[1+4] = y;
  //vertices[2+4] = u+(1.0f/16.0f);
  //vertices[3+4] = v;

  vertices[0+8] = x + rune->w;
  vertices[1+8] = y + rune->h;
  //vertices[2+8] = u+(1.0f/16.0f);
  //vertices[3+8] = v+(1.0f/16.0f);

  vertices[0+12] = x;
  vertices[1+12] = y + rune->h;
  //vertices[2+12] = u;
  //vertices[3+12] = v+(1.0f/16.0f);
  glBindVertexArray(vao);
  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * 4 * 4,
    vertices, GL_STATIC_DRAW);

  /* draw */
  glUseProgram(shader);
  glUniformMatrix4fv(mvpUniform, 1, 0, ((GLfloat*)&mvp));

  glActiveTexture(GL_TEXTURE0);
  glBindTexture(GL_TEXTURE_2D, r->texture);
  glUniform1i(texUniform, 0);
  glBindVertexArray(vao);

  glBindBuffer(GL_ARRAY_BUFFER, vbo);
  glEnableVertexAttribArray(0);
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, (void*)0);
  glEnableVertexAttribArray(1);
  glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat)*4, (void*)8);

  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
  glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, (void*)0);
}
示例#8
0
		void Shader::disable() const {
			glUseProgram(0);
		}
示例#9
0
void AceProgram::activate() {
    glUseProgram(programId);
}
/*!***************************************************************************
 @Function		DrawPODScene
 @Input         mViewProjection
 @Input         bDrawCamera
 @Description   Draws the scene described by the loaded POD file.
 *****************************************************************************/
void OGLES3TextureStreaming::DrawPODScene(const PVRTMat4 &mViewProjection)
{
	// Clear the colour and depth buffer
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// Get the position of the first light from the scene.
	PVRTVec4 vLightPosition = m_Scene.GetLightPosition(0);
	int iTVCount            = 0;

#if defined(__ANDROID__)
	// Check if the MVP has changed
	if (m_Camera.HasImageChanged() && m_Camera.HasProjectionMatrixChanged())
	{
		m_TexCoordsProjection = PVRTMat4(m_Camera.GetProjectionMatrix());
	}
#endif

	for(unsigned int i = 0; i < m_Scene.nNumMeshNode; ++i)
	{
		SPODNode& Node = m_Scene.pNode[i];

		bool bIsTVScreen   = Node.nIdxMaterial == m_uiTVScreen;
		bool bIsRecordGlow = Node.nIdxMaterial == m_uiRecordGlow;

		// Get the node model matrix
		PVRTMat4 mWorld = m_Scene.GetWorldMatrix(Node);
		PVRTMat4 mModelView, mMVP;
		mMVP = mViewProjection * mWorld;

		GLint iMVPLoc = -1;
#if defined(__ANDROID__)
		GLint iTexProjLoc = -1;
#endif
		if(bIsTVScreen) // If we're drawing the TV screen change to the correct TV shader
		{
			_ASSERT(iTVCount < c_numTVScreens);
			if(c_screenEffects[iTVCount] == eTVNoise)
			{
				glUseProgram(m_TVNoiseShaderProgram.uiId);
				iMVPLoc = m_TVNoiseShaderProgram.uiMVP;
#if defined(__ANDROID__)
				iTexProjLoc = m_TVNoiseShaderProgram.uiVideoTexProjM;
#endif

				// Do the screen scrolling
				float fBandY1 = m_fBandScroll;
				float fBandY2 = fBandY1 + c_fBandWidth;
				glUniform2f(m_TVNoiseShaderProgram.uiScreenBand, fBandY1, fBandY2);

				// Do the noise
				PVRTVec2 vNoiseCoords;
				vNoiseCoords.x = (m_iNoiseCoordIdx % 4) * 0.25f;
				vNoiseCoords.y = (m_iNoiseCoordIdx / 4) * 0.25f;

				// Set the texmod value
				glUniform2f(m_TVNoiseShaderProgram.uiNoiseLoc, vNoiseCoords.x, vNoiseCoords.y);

				// Increment and reset
				m_iNoiseCoordIdx++;
				if(m_iNoiseCoordIdx >= 16)
					m_iNoiseCoordIdx = 0;
			}
			else if(c_screenEffects[iTVCount] == eTVGreyscale)
			{
				glUseProgram(m_TVGreyscaleShaderProgram.uiId);
				iMVPLoc = m_TVGreyscaleShaderProgram.uiMVP;
#if defined(__ANDROID__)
				iTexProjLoc = m_TVGreyscaleShaderProgram.uiVideoTexProjM;
#endif
			}
			else if(c_screenEffects[iTVCount] == eTVColour)
			{
				glUseProgram(m_TVShaderProgram.uiId);
				iMVPLoc = m_TVShaderProgram.uiMVP;
#if defined(__ANDROID__)
				iTexProjLoc = m_TVShaderProgram.uiVideoTexProjM;
#endif
			}
			else
			{
				_ASSERT(false); // Invalid enum
			}
			iTVCount++;
		}
		else if(bIsRecordGlow)
		{
			// Should the glow be active?
			unsigned long ulNow = PVRShellGetTime();
			if(ulNow - m_ulGlowTime > 1000)
			{
				m_bGlowState = !m_bGlowState;
				m_ulGlowTime = ulNow;
			}

			if(!m_bGlowState)
				continue;

			glEnable(GL_BLEND);
			glUseProgram(m_AmbientShaderProgram.uiId);
			iMVPLoc = m_AmbientShaderProgram.uiMVP;
		}
		else
		{
			glUseProgram(m_LitProgram.uiId);
			iMVPLoc = m_LitProgram.uiMVP;
		}

		glUniformMatrix4fv(iMVPLoc, 1, GL_FALSE, mMVP.f);

		// Pass the light position in model space to the shader. Don't do this for the TV screen.
		if(!bIsTVScreen && !bIsRecordGlow)
		{
			PVRTVec4 vLightPos;
			vLightPos = mWorld.inverse() * vLightPosition;

			glUniform3fv(m_LitProgram.uiLightPosition, 1, &vLightPos.x);
		}

		// Bind the correct texture
		if(Node.nIdxMaterial != -1)
		{
            if(Node.nIdxMaterial == m_uiTVScreen && m_i32Frame != 0)
			{
#if defined(__ANDROID__)
				GLuint yuvTexture = m_Camera.GetYUVTexture();

				glActiveTexture(GL_TEXTURE0);
				glBindTexture(GL_TEXTURE_EXTERNAL_OES, yuvTexture);

				// Set the sampler projection
				glUniformMatrix4fv(iTexProjLoc, 1, GL_FALSE, m_TexCoordsProjection.f);
#elif defined(__APPLE__)
				GLuint lumaTexure    = m_Camera.GetLuminanceTexture();
				GLuint chromaTexture = m_Camera.GetChrominanceTexture();
				GLenum lumaTarget    = m_Camera.GetLuminanceTextureTarget();
				GLenum chromaTarget  = m_Camera.GetChrominanceTextureTarget();

				glActiveTexture(GL_TEXTURE0);
				glBindTexture(lumaTarget, lumaTexure);

				glActiveTexture(GL_TEXTURE1);
				glBindTexture(chromaTarget, chromaTexture);
#endif

				if(c_screenEffects[iTVCount] == eTVNoise)
				{
					// Bind the noise texture
					glActiveTexture(GL_TEXTURE2);
					glBindTexture(GL_TEXTURE_2D, m_uiNoiseTex);
				}
			}
			else
			{
				glActiveTexture(GL_TEXTURE0);
				glBindTexture(GL_TEXTURE_2D, m_puiTextureIDs[Node.nIdxMaterial]);
			}
		}
		else
		{
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, 0);
		}

		/*
		 Now that the model-view matrix is set and the materials ready,
		 call another function to actually draw the mesh.
		 */
		DrawMesh(Node.nIdx, (bIsTVScreen || bIsRecordGlow) ? false : true);

		if(bIsRecordGlow)
		{
			glDisable(GL_BLEND);
		}
	}
}
示例#11
0
		void Shader::enable() const {
			glUseProgram(m_ShaderID);
		}
示例#12
0
void pie_DeactivateShader(void)
{
	currentShaderMode = SHADER_NONE;
	glUseProgram(0);
}
示例#13
0
// Initialization code
void init()
{
	glewExperimental = GL_TRUE;
	// Initializes the glew library
	glewInit();

	// Read in the shader code from a file.
	std::string vertShader = readShader("VertexShader.glsl");
	std::string fragShader = readShader("FragmentShader.glsl");

	// createShader consolidates all of the shader compilation code
	vertex_shader = createShader(vertShader, GL_VERTEX_SHADER);
	fragment_shader = createShader(fragShader, GL_FRAGMENT_SHADER);

	// A shader is a program that runs on your GPU instead of your CPU. In this sense, OpenGL refers to your groups of shaders as "programs".
	// Using glCreateProgram creates a shader program and returns a GLuint reference to it.
	program = glCreateProgram();
	glAttachShader(program, vertex_shader);		// This attaches our vertex shader to our program.
	glAttachShader(program, fragment_shader);	// This attaches our fragment shader to our program.

	// This links the program, using the vertex and fragment shaders to create executables to run on the GPU.
	glLinkProgram(program);
	// End of shader and program creation

	// Tell our code to use the program
	glUseProgram(program);

	// Enables the depth test, which you will want in most cases. You can disable this in the render loop if you need to.
	glEnable(GL_DEPTH_TEST);

	// We are drawing a quad, what this means is that we're drawing two triangles to create a rectangle that covers the entire view area.
	// Thus, we're only passing in 4 vertices in a triangle fan to the vertex shader. It will then call the pixel shader and draw the pixel at it's appropriate coordinate.
	glm::vec2 quadVerts[4];
	quadVerts[0] = glm::vec2(1.0, -1.0);
	quadVerts[1] = glm::vec2(-1.0, -1.0);
	quadVerts[2] = glm::vec2(-1.0, 1.0);
	quadVerts[3] = glm::vec2(1.0, 1.0);
	// No reason to bother with a Z parameter, as the quad will fill up the entire screen, facing the camera directly, making depth irrelevant.

	// Generate your vertex array object name.
	glGenVertexArrays(1, &vao);
	
	// Bind the vertex array object
	glBindVertexArray(vao);

	// This generates buffer object names
	// The first parameter is the number of buffer objects, and the second parameter is a pointer to an array of buffer objects (yes, before this call, vbo was an empty variable)
	// (In this example, there's only one buffer object.)
	glGenBuffers(1, &vbo);

	// Binds a named buffer object to the specified buffer binding point. Give it a target (GL_ARRAY_BUFFER) to determine where to bind the buffer.
	// There are several different target parameters, GL_ARRAY_BUFFER is for vertex attributes, feel free to Google the others to find out what else there is.
	// The second paramter is the buffer object reference. If no buffer object with the given name exists, it will create one.
	// Buffer object names are unsigned integers (like vbo). Zero is a reserved value, and there is no default buffer for each target (targets, like GL_ARRAY_BUFFER).
	// Passing in zero as the buffer name (second parameter) will result in unbinding any buffer bound to that target, and frees up the memory.
	glBindBuffer(GL_ARRAY_BUFFER, vbo);	

	// Creates and initializes a buffer object's data.
	// First parameter is the target, second parameter is the size of the buffer, third parameter is a pointer to the data that will copied into the buffer, and fourth parameter is the 
	// expected usage pattern of the data. Possible usage patterns: GL_STREAM_DRAW, GL_STREAM_READ, GL_STREAM_COPY, GL_STATIC_DRAW, GL_STATIC_READ, GL_STATIC_COPY, GL_DYNAMIC_DRAW, 
	// GL_DYNAMIC_READ, or GL_DYNAMIC_COPY
	// Stream means that the data will be modified once, and used only a few times at most. Static means that the data will be modified once, and used a lot. Dynamic means that the data 
	// will be modified repeatedly, and used a lot. Draw means that the data is modified by the application, and used as a source for GL drawing. Read means the data is modified by 
	// reading data from GL, and used to return that data when queried by the application. Copy means that the data is modified by reading from the GL, and used as a source for drawing.
	glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 4, &quadVerts[0], GL_STATIC_DRAW);
	// GL_ARRAY_BUFFER is for vertices in an array, all drawing commands of glDrawArrays will use vertices from that buffer.

	// By default, all client-side capabilities are disabled, including all generic vertex attribute arrays.
	// When enabled, the values in a generic vertex attribute array will be accessed and used for rendering when calls are made to vertex array commands (like glDrawArrays/glDrawElements)
	// A GL_INVALID_VALUE will be generated if the index parameter is greater than or equal to GL_MAX_VERTEX_ATTRIBS
	glEnableVertexAttribArray(0);

	// Defines an array of generic vertex attribute data. Takes an index, a size specifying the number of components (in this case, floats)(has a max of 4)
	// The third parameter, type, can be GL_BYTE, GL_UNSIGNED_BYTE, GL_SHORT, GL_UNSIGNED_SHORT, GL_FIXED, or GL_FLOAT
	// The fourth parameter specifies whether to normalize fixed-point data values, the fifth parameter is the stride which is the offset (in bytes) between generic vertex attributes
	// The fifth parameter is a pointer to the first component of the first generic vertex attribute in the array. If a named buffer object is bound to GL_ARRAY_BUFFER (and it is, in this case) 
	// then the pointer parameter is treated as a byte offset into the buffer object's data.
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(glm::vec2), (void*)0);
	// You'll note sizeof(glm::vec2) is our stride, because each vertex is that size.

	// This gets us a reference to the uniform variables in the vertex shader, which are called by the same name here as in the shader.
	// We're using these variables to define the camera. The eye is the camera position, and teh rays are the four corner rays of what the camera sees.
	// Only 2 parameters required: A reference to the shader program and the name of the uniform variable within the shader code.
	eye = glGetUniformLocation(program, "eye");
	ray00 = glGetUniformLocation(program, "ray00");
	ray01 = glGetUniformLocation(program, "ray01");
	ray10 = glGetUniformLocation(program, "ray10");
	ray11 = glGetUniformLocation(program, "ray11");

	// This is where we'll set up our camera location at.
	cameraPos = glm::vec3(4.0f, 8.0f, 8.0f);

	// These are four corner ray variables to store the output from our calcCameraRays function.
	glm::vec4 r00;
	glm::vec4 r01;
	glm::vec4 r10;
	glm::vec4 r11;

	// Call our function to calculate the four corner rays. We're choosing to make the point the camera centeras on at 0, 0.5, 0.
	// Our FoV angle is 60 degrees and our ratio is 800/600 which is just the pixel ratio.
	calcCameraRays(cameraPos, glm::vec3(0.0f, 0.5f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f), 60.0f, 800.0f/600.0f, &r00, &r01, &r10, &r11);

	// Now set the uniform variables in the shader to match our camera variables (cameraPos = eye, then four corner rays)
	glUniform3f(eye, cameraPos.x, cameraPos.y, cameraPos.z);
	glUniform3f(ray00, r00.x, r00.y, r00.z);
	glUniform3f(ray01, r01.x, r01.y, r01.z);
	glUniform3f(ray10, r10.x, r10.y, r10.z);
	glUniform3f(ray11, r11.x, r11.y, r11.z);

	// This is not necessary, but I prefer to handle my vertices in the clockwise order. glFrontFace defines which face of the triangles you're drawing is the front.
	// Essentially, if you draw your vertices in counter-clockwise order, by default (in OpenGL) the front face will be facing you/the screen. If you draw them clockwise, the front face 
	// will face away from you. By passing in GL_CW to this function, we are saying the opposite, and now the front face will face you if you draw in the clockwise order.
	// If you don't use this, just reverse the order of the vertices in your array when you define them so that you draw the points in a counter-clockwise order.
	glFrontFace(GL_CW);
}
示例#14
0
void FurApplication::Initialize(const char * title)
{
    base::Initialize(title);

    base_prog = glCreateProgram();

    static const char base_vs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) in vec4 position_in;\n"
        "layout (location = 1) in vec3 normal_in;\n"
        "layout (location = 2) in vec2 texcoord_in;\n"
        "\n"
        "uniform mat4 model_matrix;\n"
        "uniform mat4 projection_matrix;\n"
        "\n"
        "out VS_FS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "} vertex_out;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vertex_out.normal = normal_in;\n"
        "    gl_Position = projection_matrix * (model_matrix * position_in);\n"
        "}\n";

    static const char base_fs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) out vec4 color;\n"
        "\n"
        "in VS_FS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "} vertex_in;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vec3 normal = vertex_in.normal;\n"
        "    color = vec4(0.2, 0.1, 0.5, 1.0) * (0.2 + pow(abs(normal.z), 4.0)) + vec4(0.8, 0.8, 0.8, 0.0) * pow(abs(normal.z), 137.0);\n"
        "}\n";

    vglAttachShaderSource(base_prog, GL_VERTEX_SHADER, base_vs_source);
    vglAttachShaderSource(base_prog, GL_FRAGMENT_SHADER, base_fs_source);

    glLinkProgram(base_prog);
    glUseProgram(base_prog);

    base_model_matrix_pos = glGetUniformLocation(base_prog, "model_matrix");
    base_projection_matrix_pos = glGetUniformLocation(base_prog, "projection_matrix");

    fur_prog = glCreateProgram();

    static const char fur_vs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) in vec4 position_in;\n"
        "layout (location = 1) in vec3 normal_in;\n"
        "layout (location = 2) in vec2 texcoord_in;\n"
        "\n"
        "out VS_GS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "    vec2 tex_coord;\n"
        "} vertex_out;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vertex_out.normal = normal_in;\n"
        "    vertex_out.tex_coord = texcoord_in;\n"
        "    gl_Position = position_in;\n"
        "}\n";

    static const char fur_gs_source[] =
        "#version 410\n"
        "\n"
        "layout (triangles) in;\n"
        "layout (triangle_strip, max_vertices = 240) out;\n"
        "\n"
        "uniform mat4 model_matrix;\n"
        "uniform mat4 projection_matrix;\n"
        "\n"
        "uniform int fur_layers = 30;\n"
        "uniform float fur_depth = 5.0;\n"
        "\n"
        "in VS_GS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "    vec2 tex_coord;\n"
        "} vertex_in[];\n"
        "\n"
        "out GS_FS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "    vec2 tex_coord;\n"
        "    flat float fur_strength;\n"
        "} vertex_out;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    int i, layer;\n"
        "    float disp_delta = 1.0 / float(fur_layers);\n"
        "    float d = 0.0;\n"
        "    vec4 position;\n"
        "\n"
        "    for (layer = 0; layer < fur_layers; layer++)\n"
        "    {\n"
        "        for (i = 0; i < gl_in.length(); i++) {\n"
        "            vec3 n = vertex_in[i].normal;\n"
        "            vertex_out.normal = n;\n"
        "            vertex_out.tex_coord = vertex_in[i].tex_coord;\n"
        "            vertex_out.fur_strength = 1.0 - d;\n"
        "            position = gl_in[i].gl_Position + vec4(n * d * fur_depth, 0.0);\n"
        "            gl_Position = projection_matrix * (model_matrix * position);\n"
        "            EmitVertex();\n"
        "        }\n"
        "        d += disp_delta;\n"
        "        EndPrimitive();\n"
        "    }\n"
        "}\n";

    static const char fur_fs_source[] =
        "#version 410\n"
        "\n"
        "layout (location = 0) out vec4 color;\n"
        "\n"
        "uniform sampler2D fur_texture;\n"
        "uniform vec4 fur_color = vec4(0.8, 0.8, 0.9, 1.0);\n"
        "\n"
        "in GS_FS_VERTEX\n"
        "{\n"
        "    vec3 normal;\n"
        "    vec2 tex_coord;\n"
        "    flat float fur_strength;\n"
        "} fragment_in;\n"
        "\n"
        "void main(void)\n"
        "{\n"
        "    vec4 rgba = texture(fur_texture, fragment_in.tex_coord);\n"
        "    float t = rgba.a;\n"
        "    t *= fragment_in.fur_strength;\n"
        "    color = fur_color * vec4(1.0, 1.0, 1.0, t);\n"
        "}\n";

    vglAttachShaderSource(fur_prog, GL_VERTEX_SHADER, fur_vs_source);
    vglAttachShaderSource(fur_prog, GL_GEOMETRY_SHADER, fur_gs_source);
    vglAttachShaderSource(fur_prog, GL_FRAGMENT_SHADER, fur_fs_source);

    glLinkProgram(fur_prog);
    glUseProgram(fur_prog);

    fur_model_matrix_pos = glGetUniformLocation(fur_prog, "model_matrix");
    fur_projection_matrix_pos = glGetUniformLocation(fur_prog, "projection_matrix");

    glGenTextures(1, &fur_texture);
    unsigned char * tex = (unsigned char *)malloc(1024 * 1024 * 4);
    memset(tex, 0, 1024 * 1024 * 4);

    int n, m;

    for (n = 0; n < 256; n++)
    {
        for (m = 0; m < 1270; m++)
        {
            int x = rand() & 0x3FF;
            int y = rand() & 0x3FF;
            tex[(y * 1024 + x) * 4 + 0] = (rand() & 0x3F) + 0xC0;
            tex[(y * 1024 + x) * 4 + 1] = (rand() & 0x3F) + 0xC0;
            tex[(y * 1024 + x) * 4 + 2] = (rand() & 0x3F) + 0xC0;
            tex[(y * 1024 + x) * 4 + 3] = n;
        }
    }

    glBindTexture(GL_TEXTURE_2D, fur_texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1024, 1024, 0, GL_RGBA, GL_UNSIGNED_BYTE, tex);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    free(tex);

    object.LoadFromVBM("C:/Vermilion-Book/trunk/Code/media/ninja.vbm", 0, 1, 2);
}
示例#15
0
bool WaterBallDrawer::setup(int w, int h) {
  assert(w && h);
  win_w = w;
  win_h = h;
  pm.ortho(0, w, h, 0, 0.0f, 100.0f);

  // create basic shader 
  const char* atts[] = { "a_pos", "a_size" } ;
  const char* frags[] = { "out_normals", "out_alpha" };
  basic_prog.create(GL_VERTEX_SHADER, rx_to_data_path("shaders/waterdrop_basic.vert"));
  basic_prog.create(GL_FRAGMENT_SHADER, rx_to_data_path("shaders/waterdrop_basic.frag"));
  basic_prog.link(2, atts, 2, frags);
  glUseProgram(basic_prog.id);
  glUniformMatrix4fv(glGetUniformLocation(basic_prog.id, "u_pm"), 1, GL_FALSE, pm.ptr());
  glUniform1i(glGetUniformLocation(basic_prog.id, "u_normals_tex"), 0);
  glUniform1i(glGetUniformLocation(basic_prog.id, "u_alpha_tex"), 1);

  // create water render shader
  water_prog.create(GL_VERTEX_SHADER, rx_to_data_path("shaders/waterdrop_water.vert"));
  water_prog.create(GL_FRAGMENT_SHADER, rx_to_data_path("shaders/waterdrop_water.frag"));
  water_prog.link();
  glUseProgram(water_prog.id);
  glUniform1i(glGetUniformLocation(water_prog.id, "u_normals_tex"), 0);
  glUniform1i(glGetUniformLocation(water_prog.id, "u_alpha_tex"), 1);
  glUniform1i(glGetUniformLocation(water_prog.id, "u_background_tex"), 2);

  glGenVertexArrays(1, &water_vao);

  glGenVertexArrays(1, &basic_vao);
  glBindVertexArray(basic_vao);
  glGenBuffers(1, &basic_vbo);
  glBindBuffer(GL_ARRAY_BUFFER, basic_vbo);
  
  glEnableVertexAttribArray(0); // pos
  glEnableVertexAttribArray(1); // size
  glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(WaterDrop), (GLvoid*) 0);
  glVertexAttribPointer(1, 1, GL_FLOAT, GL_FALSE, sizeof(WaterDrop), (GLvoid*) 32);

  glVertexAttribDivisor(0, 1);
  glVertexAttribDivisor(1, 1);

  normals_tex = rx_create_texture(rx_to_data_path("images/waterdrop_normals.png"));
  alpha_tex = rx_create_texture(rx_to_data_path("images/waterdrop_alpha.png"));
  background_tex = rx_create_texture(rx_to_data_path("images/waterdrop_background.png"));
  glBindTexture(GL_TEXTURE_2D, background_tex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  // fbo
  glGenFramebuffers(1, &fbo);
  glBindFramebuffer(GL_FRAMEBUFFER, fbo);
  
  glGenTextures(1, &scene_normals_tex);
  glBindTexture(GL_TEXTURE_2D, scene_normals_tex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, win_w, win_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, scene_normals_tex, 0);

  glGenTextures(1, &scene_alpha_tex);
  glBindTexture(GL_TEXTURE_2D, scene_alpha_tex);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, win_w, win_h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, scene_alpha_tex, 0);

  if(glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
    printf("Framebuffer not complete.\n");
    return false;
  }

  glBindFramebuffer(GL_FRAMEBUFFER, 0);

  return true;
}
示例#16
0
//--------------------------------------------------------------------------------
void Shader::activate(void) const
{
    assert(mIsValid);
    glUseProgram(mProgramID);
}
示例#17
0
bool setupGraphics(int w, int h)
{

    printGLString("Version", GL_VERSION);
    printGLString("Vendor", GL_VENDOR);
    printGLString("Renderer", GL_RENDERER);
    printGLString("Extensions", GL_EXTENSIONS);

    LOGI("setupGraphics(%d, %d)", w, h);
    gProgram = createProgram(gVertexShader, gFragmentShader);
    if (!gProgram) {
        LOGE("Could not create program.");
        return false;
    }
    gvPositionHandle = glGetAttribLocation(gProgram, "vPosition");
    gShaderTexCoord  = glGetAttribLocation ( gProgram, "a_texCoord" );
    gvpMatrix 	      = glGetUniformLocation( gProgram, "u_TransMatrix" );
    gShaderImgTexture = glGetUniformLocation( gProgram, "s_ImgTexture" );


    makeCheckImages();
    glGenTextures( 1, &texName );
    glBindTexture(GL_TEXTURE_2D, texName);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, checkImageWidth,
                 checkImageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE,
                 checkImage);

    glUseProgram(gProgram);
    glEnableVertexAttribArray(gvPositionHandle);
    glEnableVertexAttribArray( gShaderTexCoord );
    glUniform1i ( gShaderImgTexture, 0 );


    gWidthd2 = w / 2;
	gHeightd2 = h / 2;

	esMatrixLoadIdentity( &gOrthographic );
	//esOrtho(&gOrthographic, 0, mWidth, -mHeight, 0, 5.0f, -5.0f );
	esOrtho(&gOrthographic, -gWidthd2, gWidthd2, -gHeightd2, gHeightd2, 5.0f, -5.0f );

	ESMatrix modelview;
	esMatrixLoadIdentity( &gMatrix );
	esMatrixLoadIdentity( &modelview );
	esMatrixMultiply( &gMatrix, &modelview, &gOrthographic );

	glViewport(0, 0, w, h);

	glUniformMatrix4fv( gvpMatrix, 1, GL_FALSE, (GLfloat *)&gMatrix );

	//glGenBuffers( 1, &guVbo );
	//glBindBuffer( GL_ARRAY_BUFFER, guVbo );
	//glBufferData( GL_ARRAY_BUFFER, 5 * 6 * sizeof( GLfloat), gTriangleVertices, GL_STREAM_DRAW );

	glActiveTexture ( GL_TEXTURE0 );
	glBindTexture ( GL_TEXTURE_2D, texName );
	createRenderBuffer();

	//ESMatrix matrixTrans;
	//ESMatrix modelview;
	//esMatrixLoadIdentity( &modelview );

	//esTranslate( &modelview, -fx, fy, 0.0 );
	//esMatrixMultiply( &matrixTrans, &modelview, &gOrthographic );
	glUniformMatrix4fv( gvpMatrix, 1, GL_FALSE, (GLfloat *)&gOrthographic );

    return true;
}
示例#18
0
		void Shader::Unbind(ShaderPtr sh)
		{
			glUseProgram(0);
			pwnAssert_NoGLError();
		}
示例#19
0
文件: lab4-1.c 项目: 3born/TSBK07
void display(void)
{
  //Read input_____________________________________________
   GLfloat t =(GLfloat)glutGet(GLUT_ELAPSED_TIME)/1000; //Scale with constant to make animation slower.


if (glutKeyIsDown('w'))
    { 
      keyz = keyz +1;
    }
  else if (glutKeyIsDown('s'))
    { 
      keyz = keyz -1;
    }
  else if (glutKeyIsDown('a'))
    { 
      keyx = keyx +1;
    }
  else if (glutKeyIsDown('d'))
    { 
      keyx = keyx -1;
    }
  else if (glutKeyIsDown('e'))
    { 
      keyy = keyy +1;
    }
  else if (glutKeyIsDown('q'))
    { 
      keyy = keyy -1;
    }
  else if (glutKeyIsDown('r'))
    { 
      exit(0);
    }
  // Clear the screen____________________________________
  glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	
  mat4 total, modelView, camMatrix;
	
  printError("pre display");

  vec3 pos = SetVector(keyx,keyy,keyz);
  vec3 up = SetVector(0,1,0);

  //Mouse control_____________________________________________
  //fmin and fmax doesn't really make sense but looks good. 
  GLfloat mousexlocal = 0;
  GLfloat mouseylocal = 0;

  if (mousex < 350 ||  mousex > 250)
    {
      mousexlocal = 300-mousex;
    }
  else
    {
      mousexlocal = 0;
    }

  deltaphi = deltaphi + deltaphi*-mousexlocal;
  deltaphi = fmin(0.0001,deltaphi);
  deltaphi = fmax(deltaphi,2 * PI - 0.0001);
  forward = MultVec3(Ry(deltaphi*-mousexlocal), forward);

  vec3 crossvec = CrossProduct(forward,up);

  if (mousey < 350 || mousey > 250)
    {
      mouseylocal = 300-mousey;
    }  
  else
    {
      mouseylocal = 0;
    }

  deltatheta = deltatheta + deltatheta* -mouseylocal;
  deltatheta = fmin(0.0001,deltatheta);
  deltatheta = fmax(deltatheta,2*PI - 0.0001);
  forward = MultVec3( ArbRotate(crossvec,deltatheta*-mouseylocal), forward);

  //Create camera matrix_____________________________________________
  

  GLfloat x = cos(t)*5 + 35;//Mult(Ry(2*5),x);
  GLfloat z = sin(t)*5 + 75;//Mult(Ry
  //GLfloat z = 65;
  GLfloat y = getHeight(&ttex,x,z) + 0.8;
  
  //  pos.y = pos.yy;

  camMatrix = lookAtv(pos,VectorAdd(forward,pos),up);

  modelView = IdentityMatrix();
  total = Mult(camMatrix, modelView);

  glUseProgram(program);
  glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
  glBindTexture(GL_TEXTURE_2D, tex1);		// Bind Our Texture tex1
  DrawModel(tm, program,"inPosition", "inNormal", "inTexCoord");


  //total = Mult(Ry(2*t),T(10,0,0));
  total = T(x,y,z);
  total = Mult(camMatrix,total);

  glUniformMatrix4fv(glGetUniformLocation(program, "mdlMatrix"), 1, GL_TRUE, total.m);
  glBindTexture(GL_TEXTURE_2D, tex2);		// Bind Our Texture tex1
  DrawModel(bunny, program, "inPosition", "inNormal", "inTexCoord");

  printError("display 2");
	
  glutSwapBuffers();
}
示例#20
0
static GLboolean
test_instancing(GLuint divisor)
{
    static const GLfloat verts[4][2] = {
        {-1, -1}, {1, -1}, {1, 1}, {-1, 1}
    };
    GLuint vbo;
    uintptr_t offset = 0;

    if (use_vbo) {
        glGenBuffers(1, &vbo);
        glBindBuffer(GL_ARRAY_BUFFER, vbo);
        glBufferData(GL_ARRAY_BUFFER,
                     sizeof(verts) + sizeof(Positions) + sizeof(Colors),
                     NULL,
                     GL_STATIC_DRAW);
        glBufferSubData(GL_ARRAY_BUFFER, offset, sizeof(verts), verts);
        glVertexPointer(2, GL_FLOAT, 0, (void*) offset);
        offset += sizeof(verts);

        glBufferSubData(GL_ARRAY_BUFFER, offset, sizeof(Positions), Positions);
        glVertexAttribPointer(PosAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*) offset);
        offset += sizeof(Positions);

        glBufferSubData(GL_ARRAY_BUFFER, offset, sizeof(Colors), Colors);
        glVertexAttribPointer(ColorAttrib, 4, GL_FLOAT, GL_FALSE, 0, (void*) offset);
        offset += sizeof(Colors);

        glBindBuffer(GL_ARRAY_BUFFER, 0);
    } else {
        glVertexPointer(2, GL_FLOAT, 0, verts);
        glVertexAttribPointer(PosAttrib, 2, GL_FLOAT, GL_FALSE, 0, Positions);
        glVertexAttribPointer(ColorAttrib, 4, GL_FLOAT, GL_FALSE, 0, Colors);
    }

    glEnableClientState(GL_VERTEX_ARRAY);
    glEnableVertexAttribArray(PosAttrib);
    glEnableVertexAttribArray(ColorAttrib);

    glVertexAttribDivisorARB(PosAttrib, 1);
    /* advance color once every 'n' instances */
    glVertexAttribDivisorARB(ColorAttrib, divisor);

    glClear(GL_COLOR_BUFFER_BIT);

    glUseProgram(Program);

    glDrawArraysInstancedARB(GL_POLYGON, 0, 4, PRIMS);

    glUseProgram(0);

    if (use_vbo) {
        glDeleteBuffers(1, &vbo);
    }

    {
        GLint i;
        GLint pos[4];

        for (i = 0; i < PRIMS; i++) {
            GLuint elem = i / divisor;

            /* use glRasterPos to determine where to read a sample pixel */
            glRasterPos2fv(Positions[i]);
            glGetIntegerv(GL_CURRENT_RASTER_POSITION, pos);

            if (!piglit_probe_pixel_rgba(pos[0], pos[1], Colors[elem])) {
                fprintf(stderr, "%s: instance %d failed to draw correctly\n",
                        TestName, i);
                fprintf(stderr, "%s: color instance divisor = %u\n",
                        TestName, divisor);
                piglit_present_results();
                return GL_FALSE;
            }
        }
    }

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableVertexAttribArray(PosAttrib);
    glDisableVertexAttribArray(ColorAttrib);

    piglit_present_results();

    return GL_TRUE;
}
示例#21
0
void sph_model::draw(const double *P, const double *V, const int *fv, int fc,
                                                       const int *pv, int pc, float alpha)
{
    double M[16];
    
    mmultiply(M, P, V);

    glMatrixMode(GL_PROJECTION);
    glLoadMatrixd(P);
    glMatrixMode(GL_MODELVIEW);
    glLoadMatrixd(V);
    
    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glBindBuffer(GL_ARRAY_BUFFER, vertices);
    glEnableClientState(GL_VERTEX_ARRAY);
    glVertexPointer(2, GL_FLOAT, 0, 0);

    for (int i = 15; i >= 0; --i)
    {
        glActiveTexture(GL_TEXTURE0 + i);
        glBindTexture(GL_TEXTURE_2D, cache.get_fill());
    }

    // This is a hack that ensures that the root pages of all files are touched.

    GLuint o;
    int tock;

    for (int i = 0; i < fc; ++i)
    {
        o = cache.get_page(fv[i], 0, time, tock);
        o = cache.get_page(fv[i], 1, time, tock);
        o = cache.get_page(fv[i], 2, time, tock);
        o = cache.get_page(fv[i], 3, time, tock);
        o = cache.get_page(fv[i], 4, time, tock);
        o = cache.get_page(fv[i], 5, time, tock);
    }
    for (int i = 0; i < pc; ++i)
    {
        o = cache.get_page(pv[i], 0, time, tock);
        o = cache.get_page(pv[i], 1, time, tock);
        o = cache.get_page(pv[i], 2, time, tock);
        o = cache.get_page(pv[i], 3, time, tock);
        o = cache.get_page(pv[i], 4, time, tock);
        o = cache.get_page(pv[i], 5, time, tock);
    }

#if 0
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
#endif

    glUseProgram(program);
    {
        glUniform1f(glGetUniformLocation(program, "zoomk"), zoomk);
	glUniform1f(glGetUniformLocation(program, "globalAlpha"), alpha);
        glUniform3f(glGetUniformLocation(program, "zoomv"),
                    zoomv[0], zoomv[1], zoomv[2]);

        for (int i = 0; i < 6; ++i)
        {
            double a[3], b[3], c[3], d[3];
            
            vnormalize(a, cube_v[cube_i[i][0]]);
            vnormalize(b, cube_v[cube_i[i][1]]);
            vnormalize(c, cube_v[cube_i[i][2]]);
            vnormalize(d, cube_v[cube_i[i][3]]);
            
            glUniform3f(pos_a, GLfloat(a[0]), GLfloat(a[1]), GLfloat(a[2]));
            glUniform3f(pos_b, GLfloat(b[0]), GLfloat(b[1]), GLfloat(b[2]));
            glUniform3f(pos_c, GLfloat(c[0]), GLfloat(c[1]), GLfloat(c[2]));
            glUniform3f(pos_d, GLfloat(d[0]), GLfloat(d[1]), GLfloat(d[2]));

            draw_face(fv, fc, pv, pc, 0, 1, 0, 1, 0, i);
        }
    }
    glUseProgram(0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
    glBindBuffer(GL_ARRAY_BUFFER,         0);
    glDisableClientState(GL_VERTEX_ARRAY);

    glActiveTexture(GL_TEXTURE0);
}
示例#22
0
void renderObjects(void)
{
	//Rendu des axes
	glDisable(GL_LIGHTING);

	glBegin(GL_LINES);
	glColor3d(1, 0, 0);
	glVertex3d(0, 0, 0);
	glVertex3d(10000, 0, 0);
	glColor3d(0, 1, 0);
	glVertex3d(0, 0, 0);
	glVertex3d(0, 10000, 0);
	glColor3d(0, 0, 1);
	glVertex3d(0, 0, 0);
	glVertex3d(0, 0, 10000);
	glEnd();

	glEnable(GL_LIGHTING);
	glShadeModel(GL_SMOOTH);
	glPushMatrix();

	//Position du soleil
	glTranslatef(g_renderer->_Camera->_Position.X, g_renderer->_Camera->_Position.Y, g_renderer->_Camera->_Position.Z);
	glTranslatef(g_sun_dir.X * 1000, g_sun_dir.Y * 1000, g_sun_dir.Z * 1000);

	//Material du soleil : de l'emissive
	GLfloat sunEmissionMaterial[] = { 0.0, 0.0, 0.0,1.0 };
	sunEmissionMaterial[0] = g_sun_color.R;
	sunEmissionMaterial[1] = g_sun_color.V;
	sunEmissionMaterial[2] = g_sun_color.B;
	glMaterialfv(GL_FRONT, GL_EMISSION, sunEmissionMaterial);

	//On dessine un cube pour le soleil
	glutSolidCube(50.0f);

	//On reset le material emissive pour la suite
	sunEmissionMaterial[0] = 0.0f;
	sunEmissionMaterial[1] = 0.0f;
	sunEmissionMaterial[2] = 0.0f;
	glMaterialfv(GL_FRONT, GL_EMISSION, sunEmissionMaterial);

	glPopMatrix();

	glPushMatrix();


	glUseProgram(g_program);
	GLuint elap = glGetUniformLocation(g_program, "elapsed");
	glUniform1f(elap, NYRenderer::_DeltaTimeCumul);
	GLuint invView = glGetUniformLocation(g_program, "invertView");
	glUniformMatrix4fv(invView, 1, true, g_renderer->_Camera->_InvertViewMatrix.Mat.t);
	GLuint posCam = glGetUniformLocation(g_program, "posCam");
	glUniform3f(posCam, g_renderer->_Camera->_Position.X, g_renderer->_Camera->_Position.Y, g_renderer->_Camera->_Position.X);
	
	//g_world->render_world_old_school();
	g_world->render_world_vbo();

	glUseProgram(0);

	glPopMatrix();

	/*
	//Rotation du cube en fonction du temps
	glRotatef(NYRenderer::_DeltaTimeCumul*50.0f, 0, 0, 1);
	glRotatef(NYRenderer::_DeltaTimeCumul*50.0f, 0, 1, 0);

	//ROTATION
	glRotatef(NYRenderer::_DeltaTimeCumul * 100, g_slider->Value*10.0f, 1, cos(NYRenderer::_DeltaTimeCumul));
	//glTranslatef(2, 2, 0);
	//glRotatef(45, 0, 0, 1);

	//BACK FACE CULLING
	//glDisable(GL_CULL_FACE);

	//MATERIALS
	GLfloat materialDiffuseR[] = { 0.7, 0, 0, 1.0 };
	GLfloat materialAmbientR[] = { 0.7, 0, 0, 1.0 };
	GLfloat materialDiffuseG[] = { 0, 0.7, 0, 1.0 };
	GLfloat materialAmbientG[] = { 0, 0.7, 0, 1.0 };
	GLfloat materialDiffuseB[] = { 0, 0, 0.7, 1.0 };
	GLfloat materialAmbientB[] = { 0, 0, 0.7, 1.0 };

	//CUBE
	glBegin(GL_QUADS);

	//Face1
	glMaterialfv(GL_FRONT, GL_DIFFUSE, materialDiffuseG);
	glMaterialfv(GL_FRONT, GL_AMBIENT, materialAmbientG);
	glColor3d(0, 0.5f, 0);
	glNormal3f(0, -1, 0);
	glVertex3f(-1, -1, -1);
	glVertex3f(1, -1, -1);
	glVertex3f(1, -1, 1);
	glVertex3f(-1, -1, 1);

	//Face2
	glColor3d(0, 0.5f, 0);
	glNormal3f(0, 1, 0);
	glVertex3f(-1, 1, -1);
	glVertex3f(-1, 1, 1);
	glVertex3f(1, 1, 1);
	glVertex3f(1, 1, -1);

	//Face3
	glMaterialfv(GL_FRONT, GL_DIFFUSE, materialDiffuseR);
	glMaterialfv(GL_FRONT, GL_AMBIENT, materialAmbientR);
	glColor3d(0.5f, 0, 0);
	glNormal3f(1, 0, 0);
	glVertex3f(1, -1, -1);
	glVertex3f(1, 1, -1);
	glVertex3f(1, 1, 1);
	glVertex3f(1, -1, 1);

	//Face4
	glColor3d(0.5f, 0, 0);
	glNormal3f(-1, 0, 0);
	glVertex3f(-1, -1, -1);
	glVertex3f(-1, -1, 1);
	glVertex3f(-1, 1, 1);
	glVertex3f(-1, 1, -1);

	//Face5
	glMaterialfv(GL_FRONT, GL_DIFFUSE, materialDiffuseB);
	glMaterialfv(GL_FRONT, GL_AMBIENT, materialAmbientB);
	glColor3d(0, 0, 0.5f);
	glNormal3f(0, 0, 1);
	glVertex3f(-1, -1, 1);
	glVertex3f(1, -1, 1);
	glVertex3f(1, 1, 1);
	glVertex3f(-1, 1, 1);

	//Face6
	glColor3d(0, 0, 0.5f);
	glNormal3f(0, 0, -1);
	glVertex3f(-1, -1, -1);
	glVertex3f(-1, 1, -1);
	glVertex3f(1, 1, -1);
	glVertex3f(1, -1, -1);

	glEnd();

	glPopMatrix();

	//SPHERE
	//Diffuse
	GLfloat materialDiffuse[] = { 0.5, 0.5, 0.5, 0.5 };
	glMaterialfv(GL_FRONT, GL_DIFFUSE, materialDiffuse);
	//Speculaire
	GLfloat whiteSpecularMaterial[] = { 0.3, 0.3, 0.3, 0.5 };
	glMaterialfv(GL_FRONT, GL_SPECULAR, whiteSpecularMaterial);
	GLfloat mShininess = 100;
	glMaterialf(GL_FRONT, GL_SHININESS, mShininess);

	glutSolidSphere(3,50,50);
	*/
}
// OpenGL initialization
void
init()
{
    colorcube();

    // Create a vertex array object
    GLuint vao;
    glGenVertexArrays( 1, &vao );
    glBindVertexArray( vao );

    // Create and initialize a buffer object
    GLuint buffer;
    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_ARRAY_BUFFER, buffer );
    glBufferData( GL_ARRAY_BUFFER, sizeof(points) + sizeof(normals),
		  NULL, GL_STATIC_DRAW );
    glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(points), points );
    glBufferSubData( GL_ARRAY_BUFFER, sizeof(points),
		     sizeof(normals), normals );

    // Load shaders and use the resulting shader program
    GLuint program = InitShader( "vshader_a6.glsl", "fshader_a6.glsl" );
    glUseProgram( program );

    // set up vertex arrays
    GLuint vPosition = glGetAttribLocation( program, "vPosition" );
    glEnableVertexAttribArray( vPosition );
    glVertexAttribPointer( vPosition, 4, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(0) );

    GLuint vNormal = glGetAttribLocation( program, "vNormal" ); 
    glEnableVertexAttribArray( vNormal );
    glVertexAttribPointer( vNormal, 3, GL_FLOAT, GL_FALSE, 0,
			   BUFFER_OFFSET(sizeof(points)) );

    // Initialize shader lighting parameters
    point4 light_position( 0.0, 0.0, -1.0, 0.0 );
    color4 light_ambient( 0.2, 0.2, 0.2, 1.0 );
    color4 light_diffuse( 1.0, 1.0, 1.0, 1.0 );
    color4 light_specular( 1.0, 1.0, 1.0, 1.0 );

    color4 material_ambient( 1.0, 0.0, 1.0, 1.0 );
    color4 material_diffuse( 1.0, 0.8, 0.0, 1.0 );
    color4 material_specular( 1.0, 0.8, 0.0, 1.0 );
    float  material_shininess = 100.0;

    color4 ambient_product = light_ambient * material_ambient;
    color4 diffuse_product = light_diffuse * material_diffuse;
    color4 specular_product = light_specular * material_specular;

    glUniform4fv( glGetUniformLocation(program, "AmbientProduct"),
		  1, ambient_product );
    glUniform4fv( glGetUniformLocation(program, "DiffuseProduct"),
		  1, diffuse_product );
    glUniform4fv( glGetUniformLocation(program, "SpecularProduct"),
		  1, specular_product );
	
    glUniform4fv( glGetUniformLocation(program, "LightPosition"),
		  1, light_position );

    glUniform1f( glGetUniformLocation(program, "Shininess"),
		 material_shininess );
		 
    // Retrieve transformation uniform variable locations
    ModelView = glGetUniformLocation( program, "ModelView" );
    Projection = glGetUniformLocation( program, "Projection" );

    glEnable( GL_DEPTH_TEST );

    glShadeModel(GL_FLAT);

    glClearColor( 1.0, 1.0, 1.0, 1.0 ); 
}
示例#24
0
void ShaderProgram::useProgram()
{
	glUseProgram(shaderProgram);
}
示例#25
0
int main() {
	// INIT

	glfwSetErrorCallback( error_callback );

	/* Initialize the library */
	if ( !glfwInit() ) {
		return -1;
	}

	// must use exactly version 3
	glfwWindowHint( GLFW_CONTEXT_VERSION_MAJOR, 3 );
	glfwWindowHint( GLFW_CONTEXT_VERSION_MINOR, 3 );
	glfwWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
	glfwWindowHint( GLFW_RESIZABLE, GL_FALSE );

	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow( WIDTH, HEIGHT, "Hello World", NULL, NULL );
	if ( !window ) {
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent( window );

	glfwSetKeyCallback( window, key_callback );
	//glfwSetCursorPosCallback(window, cursor_position_callback);
	glfwSetScrollCallback(window, scroll_callback);
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	int count;
	//printf( "%s\n", glfwGetVideoModes( glfwGetPrimaryMonitor(), &count ) );

	glewExperimental = GL_TRUE;
	if( glewInit() != GLEW_OK ) {
		fprintf( stderr, "glewInit() failed\n" );
	}

	glViewport( 0, 0, WIDTH, HEIGHT );

	glClearColor( 0.2f, 0.3f, 0.3f, 1.0f );
	glEnable( GL_DEPTH_TEST );

	// SHADER
	Shader shader( "./primitive_restart.vs.glsl", "./primitive_restart.fs.glsl" );

    static const GLfloat cube_positions[] =
    {
        -1.0f, -1.0f, -1.0f,
        -1.0f, -1.0f,  1.0f,
        -1.0f,  1.0f, -1.0f,
        -1.0f,  1.0f,  1.0f,
         1.0f, -1.0f, -1.0f,
         1.0f, -1.0f,  1.0f,
         1.0f,  1.0f, -1.0f,
         1.0f,  1.0f,  1.0f
    };
    static const GLfloat cube_colors[] =
    {
        1.0f, 1.0f, 1.0f,
        1.0f, 1.0f, 0.0f,
        1.0f, 0.0f, 1.0f,
        1.0f, 0.0f, 0.0f,
        0.0f, 1.0f, 1.0f,
        0.0f, 1.0f, 0.0f,
        0.0f, 0.0f, 1.0f,
        0.5f, 0.5f, 0.5f
    };
    static const GLushort cube_indices[] =
    {
        0, 1, 2, 3, 6, 7, 4, 5,
        0xFFFF,
        2, 6, 0, 4, 1, 5, 3, 7
    };
    GLuint VBO;
	glGenBuffers( 1, &VBO );
    glBindBuffer( GL_ARRAY_BUFFER, VBO );
    glBufferData( GL_ARRAY_BUFFER, sizeof(cube_positions) + sizeof(cube_colors), NULL, GL_STATIC_DRAW );
    glBufferSubData( GL_ARRAY_BUFFER, 0, sizeof(cube_positions), cube_positions);
    glBufferSubData( GL_ARRAY_BUFFER, sizeof(cube_positions), sizeof(cube_colors), cube_colors);
    GLuint EBO;
    glGenBuffers( 1, &EBO );
    glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
    glBufferData( GL_ELEMENT_ARRAY_BUFFER, sizeof(cube_indices), cube_indices, GL_STATIC_DRAW );
	GLuint VAO;
	glGenVertexArrays( 1, &VAO );
	glBindVertexArray( VAO );
    glEnableVertexAttribArray( 0 );
    glEnableVertexAttribArray( 1 );
    glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, 0, NULL );
    glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, 0, (const GLvoid*)sizeof(cube_positions) );

    glClearColor( 0.6f, 0.8f, 0.8f, 1.0f );




	glm::mat4 projection;
	projection = glm::perspective( 45.0f, (GLfloat)WIDTH/HEIGHT, 0.1f, 100.0f );

	// Game loop
	while( !glfwWindowShouldClose( window ) ) {
	//for( int iter = 1; iter; --iter ) {
		glfwPollEvents();
		glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

		glUseProgram( shader.Program );
		glm::mat4 models[2];
		
		updateCamera();
		//glm::mat4 rotatedView = camera[1] * camera[0] * view;
		printf( "rotation x %f, y %f, z %f\n", rotation.x, rotation.y, rotation.z );
		glm::mat4 rotatedView;
		rotatedView = glm::rotate( rotatedView, rotation.x, glm::vec3(1, 0, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.y, glm::vec3(0, 1, 0) ) ;
		rotatedView = glm::rotate( rotatedView, rotation.z, glm::vec3(0, 0, 1) ) ;
		rotatedView *= view;
		//view = glm::translate( view, position );
		//glm::mat4 rotatedView;
		
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[1]), glm::vec3(1.0f, 0.0f, 0.0f) );
		//projection = glm::rotate( projection, glm::radians(cameraOrientation[0]), glm::vec3(0.0f, 1.0f, 0.0f) );
		//projection = projection * (cameraPosition / 10.0f);
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "view" ), 1, GL_FALSE, glm::value_ptr(rotatedView) );
		glUniformMatrix4fv( glGetUniformLocation(shader.Program, "projection" ), 1, GL_FALSE, glm::value_ptr(projection) );

        glBindVertexArray( VAO );
        glBindBuffer( GL_ARRAY_BUFFER, VBO );
        glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, EBO );
        //glDrawArrays( GL_TRIANGLES, 0, 6 );
        glEnable(GL_PRIMITIVE_RESTART);
        glPrimitiveRestartIndex(0xFFFF);
        glDrawElements(GL_TRIANGLE_STRIP, 17, GL_UNSIGNED_SHORT, NULL);
        //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, NULL);
        //glBindVertexArray( 0 );
        glFlush();
		glfwSwapBuffers( window );
		fps();
		printf("\n");
	}

	glDeleteVertexArrays( 1, &VAO );
	glDeleteBuffers( 1, &VBO );
	glDeleteBuffers( 1, &EBO );

	glfwDestroyWindow( window );
	glfwTerminate();
	return 0;
}
示例#26
0
//--Implementations
void render()
{
    //--Render the scene

    //clear the screen
    glClearColor(0.0, 0.0, 0.2, 1.0);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //premultiply the matrix for this example
    mv = view * model;

    //enable the shader program
    glUseProgram(program);

    //upload the matrix to the shader
	glUniform4fv(loc_dp,1,glm::value_ptr(DP));
	glUniform4fv(loc_dp,1,glm::value_ptr(SP));
	glUniform1f(loc_shininess,shininess);
    glUniformMatrix4fv(loc_modelView, 1, GL_FALSE, glm::value_ptr(mv));
    glUniformMatrix4fv(loc_projection, 1, GL_FALSE, glm::value_ptr(projection));

	glUniform3fv(loc_slColor, 1, spotLight.color);
	glUniform3fv(loc_slPosition, 1, spotLight.position);
	glUniform3fv(loc_slDirection, 1, spotLight.direction);
	glUniform1f( loc_slFOV, spotLight.fov);
	glUniform1i( loc_slOn, spotLight.on);

	glUniform3fv(loc_plColor, 1, pointLight.color);
	glUniform3fv(loc_plPosition, 1, pointLight.position);
	glUniform1i( loc_plOn, pointLight.on);

	glUniform3fv(loc_dlColor, 1, distantLight.color);
	glUniform3fv(loc_dlDirection, 1, distantLight.direction);
	glUniform1i( loc_dlOn, distantLight.on);

	glUniform3fv(loc_alColor, 1, ambientLight.color);
	glUniform1i( loc_alOn, ambientLight.on);
	
    //set up the Vertex Buffer Object so it can be drawn
    glEnableVertexAttribArray(loc_position);
    glEnableVertexAttribArray(loc_color);
    glEnableVertexAttribArray(loc_norm);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_geometry);
    //set pointers into the vbo for each of the attributes(position and color)
    glVertexAttribPointer( loc_position,//location of attribute
                           3,//number of elements
                           GL_FLOAT,//type
                           GL_FALSE,//normalized?
                           sizeof(Vertex),//stride
                           (void*)offsetof(Vertex,position));//offset

    glVertexAttribPointer( loc_color,
                           3,
                           GL_FLOAT,
                           GL_FALSE,
                           sizeof(Vertex),
                           (void*)offsetof(Vertex,color));

    glVertexAttribPointer( loc_norm,
                           3,
                           GL_FLOAT,
                           GL_FALSE,
                           sizeof(Vertex),
                           (void*)offsetof(Vertex,normal));

    glDrawArrays(GL_TRIANGLES, 0, vertexCount);//mode, starting index, count

    //clean up
    glDisableVertexAttribArray(loc_position);
    glDisableVertexAttribArray(loc_color);
    glDisableVertexAttribArray(loc_norm);
                           
    //swap the buffers
    glutSwapBuffers();
}
示例#27
0
void Shader::use() {
    glUseProgram(ID);
}
示例#28
0
DepalShader *DepalShaderCache::GetDepalettizeShader(GEBufferFormat pixelFormat) {
	u32 id = GenerateShaderID(pixelFormat);

	auto shader = cache_.find(id);
	if (shader != cache_.end()) {
		return shader->second;
	}

	if (vertexShader_ == 0) {
		if (!CreateVertexShader()) {
			// The vertex shader failed, no need to bother trying the fragment.
			return nullptr;
		}
	}

	char *buffer = new char[2048];

	GenerateDepalShader(buffer, pixelFormat, useGL3_ ? GLSL_300 : GLSL_140);

	GLuint fragShader = glCreateShader(GL_FRAGMENT_SHADER);

	const char *buf = buffer;
	glShaderSource(fragShader, 1, &buf, 0);
	glCompileShader(fragShader);

	CheckShaderCompileSuccess(fragShader, buffer);

	GLuint program = glCreateProgram();
	glAttachShader(program, vertexShader_);
	glAttachShader(program, fragShader);
	
	glBindAttribLocation(program, 0, "a_position");
	glBindAttribLocation(program, 1, "a_texcoord0");

	glLinkProgram(program);
	glUseProgram(program);

	GLint u_tex = glGetUniformLocation(program, "tex");
	GLint u_pal = glGetUniformLocation(program, "pal");

	glUniform1i(u_tex, 0);
	glUniform1i(u_pal, 3);

	DepalShader *depal = new DepalShader();
	depal->program = program;
	depal->fragShader = fragShader;
	cache_[id] = depal;

	GLint linkStatus = GL_FALSE;
	glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);
	if (linkStatus != GL_TRUE) {
		GLint bufLength = 0;
		glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);
		if (bufLength) {
			char* errorbuf = new char[bufLength];
			glGetProgramInfoLog(program, bufLength, NULL, errorbuf);
#ifdef SHADERLOG
			OutputDebugStringUTF8(buffer);
			OutputDebugStringUTF8(errorbuf);
#endif
			ERROR_LOG(G3D, "Could not link program:\n %s  \n\n %s", errorbuf, buf);
			delete[] errorbuf;	// we're dead!
		}

		// Since it failed, let's mark it in the cache so we don't keep retrying.
		// That will only make it slower.
		depal->program = 0;

		// We will delete the shader later in Clear().
		glDeleteProgram(program);
	} else {
		depal->a_position = glGetAttribLocation(program, "a_position");
		depal->a_texcoord0 = glGetAttribLocation(program, "a_texcoord0");
	}

	delete[] buffer;
	return depal->program ? depal : nullptr;
}
示例#29
0
void shader_prog::activate()
{
	glUseProgram(program_id);
}
void cShader::UseShader(){
	glUseProgram(iShaderID);
}