コード例 #1
0
ファイル: Shader.cpp プロジェクト: tim099/CG-project-
void Shader::LoadShader(const char* vertex_file_path,const char* fragment_file_path){
    GLuint VertexShaderID=glCreateShader(GL_VERTEX_SHADER);
    GLuint FragmentShaderID=glCreateShader(GL_FRAGMENT_SHADER);

    std::string VertexShaderCode;
    read_shader(VertexShaderCode,vertex_file_path);

    std::string FragmentShaderCode;
    read_shader(FragmentShaderCode,fragment_file_path);

    GLint Result=GL_FALSE;
    int InfoLogLength;
    // Compile Vertex Shader
    compile_shader(VertexShaderID,VertexShaderCode);
    check_shader(VertexShaderID,Result,InfoLogLength);// Check Vertex Shader
    // Compile Fragment Shader
    compile_shader(FragmentShaderID,FragmentShaderCode);
    check_shader(FragmentShaderID,Result,InfoLogLength);

    // Link the program
    GLuint ProgramID=glCreateProgram();
    glAttachShader(ProgramID,VertexShaderID);
    glAttachShader(ProgramID,FragmentShaderID);
    glLinkProgram(ProgramID);

    // Check the program
    glGetProgramiv(ProgramID,GL_LINK_STATUS,&Result);
    glGetProgramiv(ProgramID,GL_INFO_LOG_LENGTH,&InfoLogLength);
    check_program(ProgramID,InfoLogLength);

    glDeleteShader(VertexShaderID);
    glDeleteShader(FragmentShaderID);

    programID=ProgramID;
}
コード例 #2
0
GLuint init_shaders(char* vertex_shader_name, char* geometry_shader_name,
char* fragment_shader_name)
{
	GLuint p, v, g, f;

	p = glCreateProgram();
	v = read_shader(vertex_shader_name, VERTEX);
	g = read_shader(geometry_shader_name, GEOMETRY);
	f = read_shader(fragment_shader_name, FRAGMENT);
	
	glCompileShader(v);
	print_shader_error(v);

	glCompileShader(g);
	print_shader_error(g);

	glCompileShader(f);
	print_shader_error(f);

	glAttachShader(p,v);
	glAttachShader(p,g);
	glAttachShader(p,f);

	glLinkProgram(p);

	print_program_error(p);

	return p;
}
コード例 #3
0
ファイル: Shader.cpp プロジェクト: tim099/GameTest
GLuint Shader::create_shader(const char* src,GLenum type) {
    GLuint ShaderID=glCreateShader(type);
    std::string ShaderCode;
    read_shader(ShaderCode,src);
    // Compile Shader
    compile_shader(ShaderID,ShaderCode);
    return ShaderID;
}
コード例 #4
0
ファイル: demo-subpixel.c プロジェクト: andrey013/freetype-gl
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitWindowSize( 260, 330 );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
    glutCreateWindow( "Freetype OpenGL / subpixel rendering" );
    glutReshapeFunc( reshape );
    glutDisplayFunc( display );
    glutKeyboardFunc( keyboard );

    size_t i;
    texture_font_t *font;
    const char * filename = "./Vera.ttf";
    wchar_t *text = L"|... A Quick Brown Fox Jumps Over The Lazy Dog";
    vec2 pen = {{0,0}};
    vec4 black = {{0,0,0,1}};

    atlas = texture_atlas_new( 512, 512, 3 );
    font = texture_font_new( atlas, filename, 9 );
    buffer = vertex_buffer_new( "v3f:t2f:c4f:1g1f" ); 

    pen.x = 0; pen.y = 0;
    pen.y -= font->ascender;
    for( i=0; i < 30; ++i)
    {
        pen.x = 20  + i * 0.1;
        pen.y = 310 - i * 10;
        add_text( buffer, font, text, &black, &pen );
    }

    // Create the GLSL program
    char * vertex_shader_source   = read_shader("./subpixel.vert");
    char * fragment_shader_source = read_shader("./subpixel.frag");
    program = build_program( vertex_shader_source, fragment_shader_source );
    texture_location = glGetUniformLocation(program, "texture");
    pixel_location   = glGetUniformLocation(program, "pixel");

    glBindTexture( GL_TEXTURE_2D, atlas->id );
    glutMainLoop( );
    return 0;
}
コード例 #5
0
ファイル: line_opengl.cpp プロジェクト: Lyriix/openCVproject
void line_opengl::init()
{

    shader_id_data = read_shader("shaders/shader_line.vert","shaders/shader_line.frag");

    vec3 line[]={ {0.0f,0.0f,0.0f} , {1.0f,0.0f,0.0f} };
    glGenBuffers(1,&vbo_data);                                             PRINT_OPENGL_ERROR();

    ASSERT_CPE(vbo_data!=0,"Problem creating VBO");

    glBindBuffer(GL_ARRAY_BUFFER,vbo_data);                                PRINT_OPENGL_ERROR();
    glBufferData(GL_ARRAY_BUFFER,6*sizeof(float),&line[0],GL_DYNAMIC_DRAW); PRINT_OPENGL_ERROR();

    ASSERT_CPE(glIsBuffer(vbo_data),"Problem creating VBO");
}
コード例 #6
0
ファイル: shader.c プロジェクト: jbalestr42/42
GLuint			load_shader(const char *filename, GLenum shader_type)
{
	GLuint		shader_id;
	char		*glsl_source;

	shader_id = 0;
	glsl_source = read_shader(filename);
	shader_id = glCreateShader(shader_type);
	if (glsl_source && shader_id != 0)
	{
		glShaderSource(shader_id, 1, (const GLchar **)&glsl_source, NULL);
		glCompileShader(shader_id);
		free(glsl_source);
		exit_on_glerror("Could not compile a shader");
	}
	else
		ft_putendl("ERROR: Could not create a shader.");
	return (shader_id);
}
コード例 #7
0
ファイル: load_shader.c プロジェクト: Julow/scop
static bool		load_shaders_file(char const *file, uint32_t *dst)
{
	uint32_t		shaders[g_shader_t.length];
	int				tmp;
	bool			success;
	t_list			lines;

	if ((tmp = open(file, O_RDONLY)) < 0)
		return (false);
	ft_bzero(shaders, sizeof(uint32_t[g_shader_t.length]));
	lines = LIST(t_sub);
	success = read_shader(tmp, &lines, shaders, g_shader_t.all);
	close(tmp);
	ft_listremove_next(&lines, LIST_IT(&lines), -1);
	success = success && link_shader(shaders, dst);
	tmp = -1;
	while (++tmp < g_shader_t.length)
		if (shaders[tmp] > 0)
			glDeleteShader(shaders[tmp]);
	return (success);
}
コード例 #8
0
ファイル: Shader.cpp プロジェクト: tim099/GameTest
void Shader::read_shader(std::string &ShaderCode,const char* path) {
    std::ifstream ShaderStream(path, std::ios::in);
    if(ShaderStream.is_open()) {
        ShaderCode="";
        std::string Line ="";
        while(getline(ShaderStream,Line)) {
            if(!Line.empty()) {
                if(Line.find(std::string("#include"))!=std::string::npos) {
                    Line=Tim::String::cut(Line,std::string("#include"),true,true);
                    Line=Tim::String::cut(Line,std::string(" "),true,true);
                    Line=Tim::String::cut(Line,std::string("<"),true,true);
                    Line=Tim::String::cut(Line,std::string(">"),true,true);
                    //std::cout<<Line<<std::endl;
                    read_shader(Line,Line.c_str());
                    //std::cout<<Line<<std::endl;
                }
                ShaderCode+="\n"+Line;
            }
        }
        ShaderStream.close();
    } else {
        std::cout<<"load Shader:"<<path<<"false"<<std::endl;
    }
}
コード例 #9
0
ファイル: demo-gamma.c プロジェクト: 382309009/Core3D
// ------------------------------------------------------------------- main ---
int main( int argc, char **argv )
{
    glutInit( &argc, argv );
    glutInitWindowSize( 512, 512 );
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
    glutCreateWindow( "Freetype OpenGL" );
    glutReshapeFunc( reshape );
    glutDisplayFunc( display );
    glutKeyboardFunc( keyboard );

    size_t i;
    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}};
    markup_t markup = {
        .family  = "Bitstream Vera Sans",
        .size    = 15.0,
        .bold    = 0,
        .italic  = 0,
        .rise    = 0.0,
        .spacing = 0.0,
        .gamma   = 1.5,
        .foreground_color    = white,
        .background_color    = none,
        .underline           = 0,
        .underline_color     = white,
        .overline            = 0,
        .overline_color      = white,
        .strikethrough       = 0,
        .strikethrough_color = white,
        .font = 0,
    };

    atlas = texture_atlas_new( 512, 512, 3 );
    buffer = vertex_buffer_new( "v3f:t2f:c4f:1g1f:2g1f" ); 
    markup.font = texture_font_new( atlas, "./Vera.ttf", markup.size );

    vec2 pen;
    pen.y = 512.0 - markup.font->ascender - 5;
    for( i=0; i < 14; ++i )
    {
        pen.x = 25.0;
        markup.gamma = 0.75 + 1.5*i*(1.0/14);
        add_text( buffer, &pen,
                  &markup, L"The quick brown fox jumps over the lazy dog. ",
                  &markup, L"0123456789.", NULL);
        pen.y -= markup.font->height;
    }

    markup.foreground_color = black;
    pen.y = 256.0 - markup.font->ascender - 5;
    for( i=0; i < 14; ++i )
    {
        pen.x = 25.0;
        markup.gamma = 0.75 + 1.5*i*(1.0/14);
        add_text( buffer, &pen,
                  &markup, L"The quick brown fox jumps over the lazy dog. ",
                  &markup, L"0123456789.", NULL);
        pen.y -= markup.font->height;

    }



    // Create the GLSL program
    char * vertex_shader_source   = read_shader("./markup.vert");
    char * fragment_shader_source = read_shader("./markup.frag");
    program = build_program( vertex_shader_source, fragment_shader_source );
    texture_location = glGetUniformLocation(program, "texture");
    pixel_location   = glGetUniformLocation(program, "pixel");

    glutMainLoop( );
    return 0;
}
コード例 #10
0
ファイル: bezier.c プロジェクト: eviom/mesademos
static void init(void)
{
    static const char *fragShaderText =
        "void main() {\n"
        "    gl_FragColor = gl_Color;\n"
        "}\n";
    static const char *vertShaderText =
        "void main() {\n"
        "   gl_FrontColor = gl_Color;\n"
        "   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
        "}\n";
    static const char *geoShaderText =
        "#version 120\n"
        "#extension GL_ARB_geometry_shader4 : enable\n"
        "void main()\n"
        "{\n"
        "  for(int i = 0; i < gl_VerticesIn; ++i)\n"
        "  {\n"
        "    gl_FrontColor = gl_FrontColorIn[i];\n"
        "    gl_Position = gl_PositionIn[i];\n"
        "    EmitVertex();\n"
        "  }\n"
        "}\n";


    if (!ShadersSupported())
        exit(1);

    if (!glutExtensionSupported("GL_ARB_geometry_shader4")) {
        printf("This demo requires GL_ARB_geometry_shader4\n");
        exit(1);
    }

    menu_init();

    fragShader = glCreateShader(GL_FRAGMENT_SHADER);
    load_and_compile_shader(fragShader, fragShaderText);

    vertShader = glCreateShader(GL_VERTEX_SHADER);
    load_and_compile_shader(vertShader, vertShaderText);

    geoShader = glCreateShader(GL_GEOMETRY_SHADER_ARB);
    if (filename)
        read_shader(geoShader, filename);
    else
        load_and_compile_shader(geoShader,
                                geoShaderText);

    program = glCreateProgram();
    glAttachShader(program, vertShader);
    glAttachShader(program, geoShader);
    glAttachShader(program, fragShader);

    glProgramParameteriARB(program, GL_GEOMETRY_INPUT_TYPE_ARB,
                           GL_LINES_ADJACENCY_ARB);
    glProgramParameteriARB(program, GL_GEOMETRY_OUTPUT_TYPE_ARB,
                           GL_LINE_STRIP);

    {
        int temp;
        glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB,&temp);
        glProgramParameteriARB(program,GL_GEOMETRY_VERTICES_OUT_ARB,temp);
    }

    glLinkProgram(program);
    check_link(program);
    glUseProgram(program);

    SetUniformValues(program, Uniforms);
    PrintUniforms(Uniforms);

    assert(glGetError() == 0);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_COLOR_ARRAY );

    glVertexPointer( 3, GL_FLOAT, sizeof(vertices[0]), vertices );
    glColorPointer( 4, GL_FLOAT, sizeof(color[0]), color );
}
コード例 #11
0
ファイル: shaderapi.c プロジェクト: UIKit0/mesa
/**
 * Called via glShaderSource() and glShaderSourceARB() API functions.
 * Basically, concatenate the source code strings into one long string
 * and pass it to _mesa_shader_source().
 */
void GLAPIENTRY
_mesa_ShaderSourceARB(GLhandleARB shaderObj, GLsizei count,
                      const GLcharARB ** string, const GLint * length)
{
   GET_CURRENT_CONTEXT(ctx);
   GLint *offsets;
   GLsizei i, totalLength;
   GLcharARB *source;
   GLuint checksum;

   if (!shaderObj || string == NULL) {
      _mesa_error(ctx, GL_INVALID_VALUE, "glShaderSourceARB");
      return;
   }

   /*
    * This array holds offsets of where the appropriate string ends, thus the
    * last element will be set to the total length of the source code.
    */
   offsets = (GLint *) malloc(count * sizeof(GLint));
   if (offsets == NULL) {
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
      return;
   }

   for (i = 0; i < count; i++) {
      if (string[i] == NULL) {
         free((GLvoid *) offsets);
         _mesa_error(ctx, GL_INVALID_OPERATION,
                     "glShaderSourceARB(null string)");
         return;
      }
      if (length == NULL || length[i] < 0)
         offsets[i] = strlen(string[i]);
      else
         offsets[i] = length[i];
      /* accumulate string lengths */
      if (i > 0)
         offsets[i] += offsets[i - 1];
   }

   /* Total length of source string is sum off all strings plus two.
    * One extra byte for terminating zero, another extra byte to silence
    * valgrind warnings in the parser/grammer code.
    */
   totalLength = offsets[count - 1] + 2;
   source = (GLcharARB *) malloc(totalLength * sizeof(GLcharARB));
   if (source == NULL) {
      free((GLvoid *) offsets);
      _mesa_error(ctx, GL_OUT_OF_MEMORY, "glShaderSourceARB");
      return;
   }

   for (i = 0; i < count; i++) {
      GLint start = (i > 0) ? offsets[i - 1] : 0;
      memcpy(source + start, string[i],
             (offsets[i] - start) * sizeof(GLcharARB));
   }
   source[totalLength - 1] = '\0';
   source[totalLength - 2] = '\0';

   if (SHADER_SUBST) {
      /* Compute the shader's source code checksum then try to open a file
       * named newshader_<CHECKSUM>.  If it exists, use it in place of the
       * original shader source code.  For debugging.
       */
      char filename[100];
      GLcharARB *newSource;

      checksum = _mesa_str_checksum(source);

      _mesa_snprintf(filename, sizeof(filename), "newshader_%d", checksum);

      newSource = read_shader(filename);
      if (newSource) {
         fprintf(stderr, "Mesa: Replacing shader %u chksum=%d with %s\n",
                       shaderObj, checksum, filename);
         free(source);
         source = newSource;
      }
   }

   shader_source(ctx, shaderObj, source);

   if (SHADER_SUBST) {
      struct gl_shader *sh = _mesa_lookup_shader(ctx, shaderObj);
      if (sh)
         sh->SourceChecksum = checksum; /* save original checksum */
   }

   free(offsets);
}
コード例 #12
0
ファイル: simpleGL.cpp プロジェクト: leios/simuleios
int main(){

    std::string vertex_string = read_shader("vertex.glsl");
    std::string fragment_string = read_shader("fragment.glsl");
    const GLchar* vertexShaderSource = vertex_string.c_str();
    const GLchar* fragmentShaderSource = fragment_string.c_str();

    // Initializing glfw for window generation
    glfwInit();

    // Setting window variables
    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);

    // Generating window instance
    GLFWwindow *window = glfwCreateWindow(800, 600, "Hello World", 
                                          nullptr, nullptr);
    if (window == nullptr){
        std::cout << "Window could not be created!" << '\n';
        glfwTerminate();
        return(-1);
    }

    glfwMakeContextCurrent(window);

    // GLEW manages function pointers for OpenGL
    // GL_TRUE gives us a more modern GLEW to work with
    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK){
        std::cout << "Failed to initialize GLEW" << '\n';
    }

    // Setting viewport up so OpenGL knows what to draw to and where
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);

    // Read from LL to UR
    // Here, we map -1 < x < 1 in x and y to 800 x 600
    glViewport(0,0,width,height);

    // Registering closing callback function
    // glfwPollEvents later should be waiting for key callbacks
    glfwSetKeyCallback(window, key_callback);

    // Building / compiling shader program
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);

    // Check for errors
    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success){
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR: vertex shader compilation failed!" << '\n';
    }

    // Now the same for the Fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);

    // Check for fragment shader errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success){
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR: fragment shader compilation failed!" << '\n';
    }

    // Now to link the shaders together
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);

    // Checking for linking errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success){
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR: program linking failed!" << '\n';
    }

    // Removing shaders after program is built
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);

    // Rendering a triangle.. first, we need to define the vertices
    // Note: GL assumes 3 dimensions, and likely parses the vertices by groups
    //       of three.
    int max_depth = 4;
    std::vector<vec> vertices;
    vertices.reserve(3 * pow(4,max_depth));
    std::vector<triangle> indices;
    indices.reserve(pow(4,max_depth));
    //create_triangle_vertex(vertices, indices, 4096);
    //std::vector<vec> init_corners(3);
    vec init_corners[3];
    init_corners[0] = vec(0,1,0);
    init_corners[1] = vec(-1,-1,-1);
    init_corners[2] = vec(1,-1,1);
    divide_triangle(init_corners, indices, vertices, max_depth);

    // Now to request space on the GPU with Vertex Buffer Objects (VBO)
    // VAO is Vertex Array Object
    // Buffer has a unique ID
    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    // Binding VAO first
    glBindVertexArray(VAO);

    // Specify the type of buffer:
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);

    // Now to do the copying
    // GL_STATIC_DRAW: No changes in vertices expected
    // GL_DYNAMIC_DRAW:  Regular changes expected
    // GL_STREAM_DRAW: Changes expected every step
    glBufferData(GL_ARRAY_BUFFER, vertices.size() * 3 * sizeof(float), 
                 vertices.data(), GL_STATIC_DRAW);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * 3 * sizeof(int), 
                 indices.data(), GL_STATIC_DRAW);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 
                          3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBindVertexArray(0);

    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    // Called a "game loop" continues until window needs to close
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        // Render
        // Clear the color buffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Using the program we created
        glUseProgram(shaderProgram);

        // Create transformations
        glm::mat4 model;
        glm::mat4 view;
        glm::mat4 projection;
        model = glm::rotate(model, -55.0f, glm::vec3(1.0f, 0.0f, 0.0f));
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
        projection = glm::perspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 100.0f);
        // Get their uniform location
        GLint modelLoc = glGetUniformLocation(shaderProgram, "model");
        GLint viewLoc = glGetUniformLocation(shaderProgram, "view");
        GLint projLoc = glGetUniformLocation(shaderProgram, "projection"); 
        // Pass them to the shaders
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection)); 

        // Draw container
        glBindVertexArray(VAO);
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
/*
    while (!glfwWindowShouldClose(window)){
        glfwPollEvents();

        // Setting window color and such:
        glClearColor(0.2f, 0.3f, 0.3f, 0.5f);
        glClear(GL_COLOR_BUFFER_BIT);

        // Using the program we created
        glUseProgram(shaderProgram);

        glm:: mat4 view, projection, model;
        model = glm::rotate(model, 55.0f, glm::vec3(1.0f, 0.0f, 0.0f));
        projection = glm::perspective(55.0f,
                                      (float)width / (float)height, 
                                      0.1f, 100.0f);
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, 3.0f));
        
        GLint modelLoc = glGetUniformLocation(shaderProgram, "model");
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        GLint viewLoc = glGetUniformLocation(shaderProgram, "view");
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        GLint projLoc = glGetUniformLocation(shaderProgram, "projection");
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

        glBindVertexArray(VAO);
        //glDrawArrays(GL_TRIANGLES, 0, 3);
        glDrawElements(GL_TRIANGLES, indices.size() * 3, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
*/

    // termination
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    glfwTerminate();

}
コード例 #13
0
int main(void) {

    if(!glfwInit()) {
        fprintf(stderr, "Could not load GLFW, aborting.\n");
        return(EXIT_FAILURE);
    }

    int WIDTH, HEIGHT;
    WIDTH = 800;
    HEIGHT = 600;

    GLFWwindow *window;
    window = glfwCreateWindow(WIDTH,HEIGHT,"05 camera.", NULL, NULL);

    if(!window) {
        fprintf(stderr, "Could not create main window, aborting.\n");
        return(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);
    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
        fprintf(stderr, "Could not initialize GLEW, aborting.\n");
        return(EXIT_FAILURE);
    }

    glEnable(GL_DEPTH_TEST);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    GLuint VAO, VBO, lightVAO;

    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    //glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
    //                      (GLvoid*)(3*sizeof(GLfloat)));
    //glEnableVertexAttribArray(1);

    glBindVertexArray(0);

    /* LightVAO definition. */

    glGenVertexArrays(1, &lightVAO);
    glBindVertexArray(lightVAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO); // Same vertex data as cube.
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);

    char* vertex_source = read_shader("shaders/07.vert");
    char* fragment_source = read_shader("shaders/07.frag");
    char* lamp_fragment_source = read_shader("shaders/07_lamp.frag");

    GLuint shader_program, lamp_program;
    shader_program = create_shader_program(vertex_source, fragment_source);
    lamp_program = create_shader_program(vertex_source, lamp_fragment_source);

    free(vertex_source);
    free(fragment_source);
    free(lamp_fragment_source);

    //GLuint texture;

    //glActiveTexture(GL_TEXTURE0);
    //glGenTextures(1, &texture);
    //glBindTexture(GL_TEXTURE_2D, texture);

    //load_texture("textures/02_container.jpg");
    //glUniform1i(glGetUniformLocation(shader_program, "texture_sampler"), 0);

    //glBindTexture(GL_TEXTURE_2D, 0);

    Mat4f *projection, *model, *view, *temp, *temp2;
    mat4f_allocate(&projection);
    mat4f_allocate(&model);
    mat4f_allocate(&view);
    mat4f_allocate(&temp);
    mat4f_allocate(&temp2);

    mat4f_translate(view, 0.0f, 0.0f, -3.0f);
    //mat4f_rotate_x(model, -M_PI/4);
    mat4f_rotate_x(model, 0.0f);

    Vec3f *light_position;
    vec3f_allocate(&light_position);

    vec3f_allocate(&camera_pos);
    vec3f_allocate(&camera_target);
    vec3f_allocate(&camera_up);
    vec3f_allocate(&camera_front);
    vec3f_allocate(&temp_vec3f);

    vec3f_set(camera_target, 0.0f, 0.0f, 0.0f);
    vec3f_set(camera_up, 0.0f, 1.0f, 0.0f);
    vec3f_set(camera_front, 0.0f, 0.0f, -1.0f);
    vec3f_set(camera_pos, 0.0f, 0.0f, 3.0f);
    vec3f_set(light_position, 1.2f, 1.0f, 2.0f);

    /* shader locations */

    GLuint model_location, projection_location, view_location, light_position_location,
           view_position_location;

    glUseProgram(shader_program);

    model_location = glGetUniformLocation(shader_program, "model");
    projection_location = glGetUniformLocation(shader_program, "perspective");
    view_location = glGetUniformLocation(shader_program, "view");
    light_position_location = glGetUniformLocation(shader_program, "light_position");
    view_position_location = glGetUniformLocation(shader_program, "view_position");

    GLuint object_color_location, light_color_location;

    object_color_location = glGetUniformLocation(shader_program, "object_color");
    light_color_location = glGetUniformLocation(shader_program, "light_color");

    glUniform3f(object_color_location, 1.0f, 0.5f, 0.31f);
    glUniform3f(light_color_location, 1.0f, 1.0f, 1.0);
    glUniform3f(light_position_location, light_position->data[0],
                                         light_position->data[1],
                                         light_position->data[2]);
    glUseProgram(0);

    glUseProgram(lamp_program);

    GLuint lamp_model_location, lamp_projection_location, lamp_view_location;

    lamp_model_location = glGetUniformLocation(lamp_program, "model");
    lamp_projection_location = glGetUniformLocation(lamp_program, "perspective");
    lamp_view_location = glGetUniformLocation(lamp_program, "view");

    glUseProgram(0);


    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    current_frame = 0.0f;
    last_frame = 0.0f;
    last_x = WIDTH / 2.0f;
    last_y = HEIGHT / 2.0f;
    fov = M_PI/4;
    yaw = -M_PI/2;
    pitch = 0.0f;
    first_mouse = true;

    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        current_frame = glfwGetTime();
        delta_time = current_frame - last_frame;
        last_frame = current_frame;
        do_movement();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glUseProgram(shader_program);


     //   glActiveTexture(GL_TEXTURE0);
     //   glBindTexture(GL_TEXTURE_2D, texture);

//        cam_x = sinf(time) * radius;
//        cam_z = cosf(time) * radius;
        vec3f_add(camera_target, camera_pos, camera_front);
        mat4f_look_at(view, camera_pos, camera_target, camera_up);

        mat4f_perspective(projection, fov, (float)WIDTH/(float)HEIGHT,
                          0.1f, 100.0f);

        //mat4f_rotate_x(model, sinf(time) * M_PI);
        glUniformMatrix4fv(model_location, 1, GL_TRUE,
                           mat4f_pointer(model));
        glUniformMatrix4fv(view_location, 1, GL_TRUE,
                           mat4f_pointer(view));
        glUniformMatrix4fv(projection_location, 1, GL_TRUE,
                           mat4f_pointer(projection));

        glUniform3f(view_position_location, camera_pos->data[0],
                                            camera_pos->data[1],
                                            camera_pos->data[2]);

        glBindVertexArray(VAO);

        glDrawArrays(GL_TRIANGLES, 0, 36);

     //   glBindTexture(GL_TEXTURE_2D, 0);

        glBindVertexArray(0);

        glUseProgram(lamp_program);
        //glUseProgram(shader_program);


        mat4f_scale(temp, 0.2f, 0.2f, 0.2f);
        mat4f_mul(temp, temp, model);
        mat4f_translate_vec3f(temp2, light_position);
        mat4f_mul(temp2, temp2, temp);
        //mat4f_print(temp);

        glUniformMatrix4fv(lamp_model_location, 1, GL_TRUE,
                           mat4f_pointer(temp2));
        glUniformMatrix4fv(lamp_view_location, 1, GL_TRUE,
                           mat4f_pointer(view));
        glUniformMatrix4fv(lamp_projection_location, 1, GL_TRUE,
                           mat4f_pointer(projection));

        glBindVertexArray(lightVAO);

        glDrawArrays(GL_TRIANGLES, 0, 36);

        glBindVertexArray(0);

        glfwSwapBuffers(window);

    }
    glfwTerminate();

    return(EXIT_SUCCESS);
}
コード例 #14
0
int main(void) {

    if (!glfwInit()) {
        fprintf(stderr, "Could not initialize GLFW, aborting.\n");
        return(EXIT_FAILURE);
    }

    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);

    int WIDTH, HEIGHT;
    WIDTH = 800;
    HEIGHT = 600;

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    GLFWwindow* window;

    window = glfwCreateWindow(WIDTH, HEIGHT, "04 coordinate systems.", NULL, NULL);
    glfwSetKeyCallback(window, key_callback);
    if (!window) {
        fprintf(stderr, "Could not create window, aborting.\n");
        return(EXIT_FAILURE);
    }
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    if(glewInit() != GLEW_OK) {
        fprintf(stderr, "Could not initialize GLEW, aborting.\n");
        return(EXIT_FAILURE);
    }

    glEnable(GL_DEPTH_TEST);

    GLuint VAO, VBO, EBO;
    glGenVertexArrays(1 ,&VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, stride, (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, stride,
                          (GLvoid*)(3*sizeof(GLfloat)));
    glEnableVertexAttribArray(1);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,
                 GL_STATIC_DRAW);

    glBindVertexArray(0);

    char *vertex_source = read_shader("shaders/04.vert");
    char *fragment_source = read_shader("shaders/04.frag");

    GLuint shader_program;
    shader_program = create_shader_program(vertex_source, fragment_source);

    glUseProgram(shader_program);

    GLuint texture;

    glActiveTexture(GL_TEXTURE0);
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);

    load_texture("textures/02_container.jpg");
    glUniform1i(glGetUniformLocation(shader_program, "texture_sampler"), 0);

    glBindTexture(GL_TEXTURE_2D, 0);

    float rotation_step;
    rotation_step = M_PI/6;

    Mat4f *model, *view, *projection, *rotation, *temp;
    mat4f_allocate(&model);
    mat4f_allocate(&view);
    mat4f_allocate(&projection);
    mat4f_allocate(&rotation);
    mat4f_allocate(&temp);

    mat4f_translate(view, 0.0f, 0.0f, -3.0f);
    mat4f_perspective(projection, (float)M_PI/4, (float)WIDTH/(float)HEIGHT, 0.1f, 100.0f);

    GLuint model_location, view_location, projection_location;
    model_location = glGetUniformLocation(shader_program, "model");
    view_location = glGetUniformLocation(shader_program, "view");
    projection_location = glGetUniformLocation(shader_program, "projection");

    int num_cubes = 10;
    srand (time(NULL));
    Vec4f positions[num_cubes];
    float a = 4.0f;
    for (int i = 0; i < num_cubes; i++) {
        Vec4f vector;
        for (int j = 0; j < 4; j++) {
            if (j == 2) {
                vector.data[j] = ((float)rand()/(float)(RAND_MAX/1.0f)-2.0f);
            } else {
                vector.data[j] = ((float)rand()/(float)(RAND_MAX/a))-2.0f;
                //vector.data[j] = 1.0f*i*j;
            }
            printf("%f, ",vector.data[j]);
        }
        printf("\n");
        positions[i] = vector;
    };

    glClearColor(1.0f, 0.5f, 1.0f, 1.0f);
    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBindVertexArray(VAO);
        float time = glfwGetTime();
        for(int i = 0; i < num_cubes; i++) {
            float *pos = positions[i].data;

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, texture);

            mat4f_rotate_x(rotation, rotation_step*time*(i+1));
            mat4f_rotate_y(temp, rotation_step*time*(i+1));
            mat4f_mul(rotation, rotation, temp);

            mat4f_translate(temp, pos[0], pos[1], pos[2]);
            mat4f_rotate_x(model, -M_PI/4);
            mat4f_mul(model, model, temp);
            mat4f_mul(model, model, rotation);

            glUniformMatrix4fv(model_location, 1, GL_TRUE, mat4f_pointer(model));
            glUniformMatrix4fv(view_location, 1, GL_TRUE, mat4f_pointer(view));
            glUniformMatrix4fv(projection_location, 1, GL_TRUE, mat4f_pointer(projection));

            glDrawArrays(GL_TRIANGLES, 0, 36);
            glBindTexture(GL_TEXTURE_2D, 0);
        }
        //glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return EXIT_SUCCESS;
}
コード例 #15
0
ファイル: gs-tri.c プロジェクト: Distrotech/mesa-demos
static void prepare_shaders(void)
{
   static const char *fragShaderText =
      "void main() {\n"
      "    gl_FragColor = gl_Color;\n"
      "}\n";
   static const char *vertShaderText =
      "void main() {\n"
      "   gl_FrontColor = gl_Color;\n"
      "   gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;\n"
      "}\n";
   static const char *geoShaderText =
      "#version 120\n"
      "#extension GL_ARB_geometry_shader4 : enable\n"
      "void main()\n"
      "{\n"
      "  for(int i = 0; i < gl_VerticesIn; ++i)\n"
      "  {\n"
      "    gl_FrontColor = gl_FrontColorIn[i];\n"
      "    gl_Position = gl_PositionIn[i];\n"
      "    EmitVertex();\n"
      "  }\n"
      "}\n";

   if (!glutExtensionSupported("GL_ARB_geometry_shader4")) {
      fprintf(stderr, "needs GL_ARB_geometry_shader4 extension\n");
      exit(1);
   }

   fragShader = glCreateShader(GL_FRAGMENT_SHADER);
   load_and_compile_shader(fragShader, fragShaderText);

   vertShader = glCreateShader(GL_VERTEX_SHADER);
   load_and_compile_shader(vertShader, vertShaderText);

   geoShader = glCreateShader(GL_GEOMETRY_SHADER_ARB);
   if (filename)
      read_shader(geoShader, filename);
   else
      load_and_compile_shader(geoShader,
                              geoShaderText);

   program = glCreateProgram();
   glAttachShader(program, vertShader);
   glAttachShader(program, geoShader);
   glAttachShader(program, fragShader);

   glProgramParameteriARB(program, GL_GEOMETRY_INPUT_TYPE_ARB, GL_TRIANGLES);
   glProgramParameteriARB(program, GL_GEOMETRY_OUTPUT_TYPE_ARB,
                          GL_TRIANGLE_STRIP);

   {
      int temp;
      glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB,&temp);
      glProgramParameteriARB(program,GL_GEOMETRY_VERTICES_OUT_ARB,temp);
   }

   glLinkProgram(program);
   check_link(program);
   glUseProgram(program);
}