Exemplo n.º 1
0
/* initialise textures */
static void inittextures(ModeInfo * mi)
{
    firestruct *fs = &fire[MI_SCREEN(mi)];

#if defined( I_HAVE_XPM )
    if (do_texture) {

	glGenTextures(1, &fs->groundid);
#ifdef HAVE_GLBINDTEXTURE
	glBindTexture(GL_TEXTURE_2D, fs->groundid);
#endif /* HAVE_GLBINDTEXTURE */

        if ((fs->gtexture = xpm_to_ximage(MI_DISPLAY(mi), MI_VISUAL(mi),
			 MI_COLORMAP(mi), ground)) == None) {
	    (void) fprintf(stderr, "Error reading the ground texture.\n");
	    glDeleteTextures(1, &fs->groundid);
            do_texture = False;
	    fs->groundid = 0;
	    fs->treeid   = 0;
	    return;
	}

	glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
    clear_gl_error();
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                 fs->gtexture->width, fs->gtexture->height, 0,
                 GL_RGBA,
                 /* GL_UNSIGNED_BYTE, */
                 GL_UNSIGNED_INT_8_8_8_8_REV,
                 fs->gtexture->data);
    check_gl_error("texture");

	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
	glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);

        if (fs->num_trees)
	{
	    glGenTextures(1, &fs->treeid);
#ifdef HAVE_GLBINDTEXTURE
	    glBindTexture(GL_TEXTURE_2D,fs->treeid);
#endif /* HAVE_GLBINDTEXTURE */
            if ((fs->ttexture = xpm_to_ximage(MI_DISPLAY(mi), MI_VISUAL(mi),
			 MI_COLORMAP(mi), tree)) == None) {
	      (void)fprintf(stderr,"Error reading tree texture.\n");
	      glDeleteTextures(1, &fs->treeid);
	      fs->treeid    = 0;
              fs->num_trees = 0; 
	      return;
	    }

        clear_gl_error();
	    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,
                     fs->ttexture->width, fs->ttexture->height, 0,
                     GL_RGBA,
                     /* GL_UNSIGNED_BYTE, */
                     GL_UNSIGNED_INT_8_8_8_8_REV,
                     fs->ttexture->data);
        check_gl_error("texture");

	    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_REPEAT);
	    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_REPEAT);

	    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST);
	    glTexParameterf(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST);

	    glTexEnvf(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
	}
    }
    else
    {
	fs->groundid = 0;	/* default textures */
	fs->treeid   = 0;
    }
#else /* !I_HAVE_XPM */
  do_texture = False;
  fs->groundid = 0;       /* default textures */
  fs->treeid = 0;
#endif /* !I_HAVE_XPM */
}
Exemplo n.º 2
0
int main(int argc, char **argv)
{
    int array_size_2d,totpoints,i;
    float rcol,gcol,bcol;

    FILE *fp_col;

    // The following parameters are usually read from a file, but
    // hard code them for the demo:
    ni=320;
    nj=112;
    vxin=0.04;
    roout=1.0;
    tau=0.51;
    // End of parameter list

    // Write parameters to screen
    printf ("ni = %d\n", ni);
    printf ("nj = %d\n", nj);
    printf ("vxin = %f\n", vxin);
    printf ("roout = %f\n", roout);
    printf ("tau = %f\n", tau);
    

    totpoints=ni*nj;    
    array_size_2d=ni*nj*sizeof(float);

    // Allocate memory for arrays
    
    f0 = malloc(array_size_2d);
    f1 = malloc(array_size_2d);
    f2 = malloc(array_size_2d);
    f3 = malloc(array_size_2d);
    f4 = malloc(array_size_2d);
    f5 = malloc(array_size_2d);
    f6 = malloc(array_size_2d);
    f7 = malloc(array_size_2d);
    f8 = malloc(array_size_2d);

    tmpf0 = malloc(array_size_2d);
    tmpf1 = malloc(array_size_2d);
    tmpf2 = malloc(array_size_2d);
    tmpf3 = malloc(array_size_2d);
    tmpf4 = malloc(array_size_2d);
    tmpf5 = malloc(array_size_2d);
    tmpf6 = malloc(array_size_2d);
    tmpf7 = malloc(array_size_2d);
    tmpf8 = malloc(array_size_2d);

    plotvar = malloc(array_size_2d);
    
    plot_rgba = malloc(ni*nj*sizeof(unsigned int));

    solid = malloc(ni*nj*sizeof(int));

    //
    // Some factors used to calculate the f_equilibrium values
    // 
    faceq1 = 4.f/9.f;
    faceq2 = 1.f/9.f;
    faceq3 = 1.f/36.f;


    //
    // Initialise f's by setting them to the f_equilibirum values assuming
    // that the whole domain is at velocity vx=vxin vy=0 and density ro=roout
    //
    for (i=0; i<totpoints; i++) {
	f0[i] = faceq1 * roout * (1.f                             - 1.5f*vxin*vxin);
	f1[i] = faceq2 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f2[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f3[i] = faceq2 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f4[i] = faceq2 * roout * (1.f                             - 1.5f*vxin*vxin);
	f5[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f6[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f7[i] = faceq3 * roout * (1.f - 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	f8[i] = faceq3 * roout * (1.f + 3.f*vxin + 4.5f*vxin*vxin - 1.5f*vxin*vxin);
	plotvar[i] = vxin;
	solid[i] = 1;
    }

    //
    // Read in colourmap data for OpenGL display 
    //
    fp_col = fopen("cmap.dat","r");
    if (fp_col==NULL) {
	printf("Error: can't open cmap.dat \n");
	return 1;
    }
    // allocate memory for colourmap (stored as a linear array of int's)
    fscanf (fp_col, "%d", &ncol);
    cmap_rgba = (unsigned int *)malloc(ncol*sizeof(unsigned int));
    // read colourmap and store as int's
    for (i=0;i<ncol;i++){
	fscanf(fp_col, "%f%f%f", &rcol, &gcol, &bcol);
	cmap_rgba[i]=((int)(255.0f) << 24) | // convert colourmap to int
	    ((int)(bcol * 255.0f) << 16) |
	    ((int)(gcol * 255.0f) <<  8) |
	    ((int)(rcol * 255.0f) <<  0);
    }
    fclose(fp_col);


    //
    // Iinitialise OpenGL display - use glut
    //
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(ni, nj);      // Window of ni x nj pixels
    glutInitWindowPosition(50, 50);  // position
    glutCreateWindow("2D LB");       // title

    // Check for OpenGL extension support 
    printf("Loading extensions: %s\n", glewGetErrorString(glewInit()));
    if(!glewIsSupported(
                        "GL_VERSION_2_0 " 
                        "GL_ARB_pixel_buffer_object "
                        "GL_EXT_framebuffer_object "
                        )){
        fprintf(stderr, "ERROR: Support for necessary OpenGL extensions missing.");
        fflush(stderr);
        return;
    }

    // Set up view
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0,ni,0.,nj, -200.0, 200.0);


    // Create texture which we use to display the result and bind to gl_Tex
    glEnable(GL_TEXTURE_2D);
    glGenTextures(1, &gl_Tex);                     // Generate 2D texture
    glBindTexture(GL_TEXTURE_2D, gl_Tex);          // bind to gl_Tex
    // texture properties:
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, ni, nj, 0, 
                 GL_RGBA, GL_UNSIGNED_BYTE, NULL);


    // Create pixel buffer object and bind to gl_PBO. We store the data we want to
    // plot in memory on the graphics card - in a "pixel buffer". We can then 
    // copy this to the texture defined above and send it to the screen
    glGenBuffers(1, &gl_PBO);
    glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, gl_PBO);
    printf("Buffer created.\n");
    

    // Set the call-back functions and start the glut loop
    printf("Starting GLUT main loop...\n");
    glutDisplayFunc(display);
    glutReshapeFunc(resize);
    glutIdleFunc(display);
    glutMouseFunc(mouse);
    glutMotionFunc(mouse_motion); 
    glutMainLoop();

    return 0;
}
Exemplo n.º 3
0
void CFrameBufferObject::SetFiltering(GLenum target, GLenum mode)
{
  glBindTexture(target, m_texid);
  glTexParameteri(target, GL_TEXTURE_MAG_FILTER, mode);
  glTexParameteri(target, GL_TEXTURE_MIN_FILTER, mode);
}
Exemplo n.º 4
0
int main()
{
	GLsizei multiSamples = 8;

	GLFWwindow* window = initWindow();
	if (window == nullptr)
	{
		std::cout << "Unable to initialize window." << std::endl;
		return -1;
	}

	// Start the timer
	GLfloat deltaTime, lastFrame, currentFrame;
	lastFrame = 0.0f;
	currentFrame = 0.0f;

	// Setup the viewport;
	GLfloat screenWidth = 800, screenHeight = 600;
	glViewport(0, 0, screenWidth, screenHeight);

	// Setup Camera
	Camera cam = initCamera();
	glfwSetWindowUserPointer(window, &cam);

	// Load Models
	Model planet = Model("./Models/planet/planet.obj");
	Model asteroid = Model("./Models/rock/rock.obj");

	// Load and Compile Shaders
	GLuint program = compileShaders("../OpenGL3-3/shaders/advanced/instance/basic.vert.glsl", "../OpenGL3-3/shaders/advanced/instance/basic.frag.glsl");
	GLuint modelShader = compileShaders("../OpenGL3-3/shaders/newModel/model.vert.glsl", "../OpenGL3-3/shaders/newModel/model.frag.glsl");
	GLuint instancedModelShader = compileShaders("../OpenGL3-3/shaders/newModel/imodel.vert.glsl", "../OpenGL3-3/shaders/newModel/model.frag.glsl");
	GLuint frameBufferShader = compileShaders("../OpenGL3-3/shaders/advanced/fbo.vert.glsl", "../OpenGL3-3/shaders/advanced/fbo.frag.glsl");

	// Setup MVP model
	glm::mat4 model, view, proj;
	view = cam.GetViewMatrix();
	proj = glm::perspective(glm::radians(45.0f), (float)screenWidth / (float)screenHeight, 0.1f, 1000.0f);

#pragma region quad

	GLfloat quadVertices[] = {
		// Positions     // Colors
		-0.05f, 0.05f, 1.0f, 0.0f, 0.0f,
		0.05f, -0.05f, 0.0f, 1.0f, 0.0f,
		-0.05f, -0.05f, 0.0f, 0.0f, 1.0f,

		-0.05f, 0.05f, 1.0f, 0.0f, 0.0f,
		0.05f, -0.05f, 0.0f, 1.0f, 0.0f,
		0.05f, 0.05f, 0.0f, 1.0f, 1.0f
	};

	glm::vec2 translations[100];
	int index = 0;
	GLfloat offset = 0.1f;
	for (GLint y = -10; y < 10; y += 2)
	{
		for (GLint x = -10; x < 10; x += 2)
		{
			glm::vec2 translation;
			translation.x = (GLfloat)x / 10.0f + offset;
			translation.y = (GLfloat)y / 10.0f + offset;
			translations[index++] = translation;
		}
	}

	GLfloat fboQuad[] = 
	{
		-1.0f, 1.0f, 0.0f, 1.0f,
		-1.0f, -1.0f, 0.0f, 0.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, 0.0f, 1.0f
	};

#pragma endregion

	GLuint VBO, VAO, instanceVBO;
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &instanceVBO);
	glBindBuffer(GL_ARRAY_BUFFER, instanceVBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * 100, &translations[0], GL_STATIC_DRAW);
	glBindBuffer(GL_ARRAY_BUFFER, 0);

	// Create the Framebuffer
	GLuint FBO;
	glGenFramebuffers(1, &FBO);
	glBindFramebuffer(GL_FRAMEBUFFER, FBO);

	GLuint texture;
	glGenTextures(1, &texture);
	glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, texture);

	glTexImage2DMultisample(GL_TEXTURE_2D_MULTISAMPLE, multiSamples, GL_RGB, screenWidth, screenHeight, GL_TRUE);// , GL_RGB, 800, 600, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_2D_MULTISAMPLE, 0);
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D_MULTISAMPLE, texture, 0);
	
	GLuint sampleRBO;

	glGenRenderbuffers(1, &sampleRBO);
	glBindRenderbuffer(GL_RENDERBUFFER, sampleRBO);
	glRenderbufferStorageMultisample(GL_RENDERBUFFER, multiSamples, GL_DEPTH24_STENCIL8, screenWidth, screenHeight);
	glBindRenderbuffer(GL_RENDERBUFFER, 0);

	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, sampleRBO);
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		std::cout << "FRAMEBUFFER INCOMPLETE!" << std::endl;

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	GLuint regularFBO;
	glGenFramebuffers(1, &regularFBO);
	glBindFramebuffer(GL_FRAMEBUFFER, regularFBO);

	GLuint tex;
	glGenTextures(1, &tex);
	glBindTexture(GL_TEXTURE_2D, tex);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, screenWidth, screenHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glBindTexture(GL_TEXTURE_2D, 0);

	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
		std::cout << "FRAMEBUFFER 2 INCOMPLETE!" << std::endl;

	glBindFramebuffer(GL_FRAMEBUFFER, 0);

	GLuint fboVAO, fboVBO;
	glGenVertexArrays(1, &fboVAO);
	glGenBuffers(1, &fboVBO);
	glBindVertexArray(fboVAO);
	
	glBindBuffer(GL_ARRAY_BUFFER, fboVBO);
	glBufferData(GL_ARRAY_BUFFER, sizeof(fboQuad), fboQuad, GL_STATIC_DRAW);
	glEnableVertexAttribArray(0);
	glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)0);
	glEnableVertexAttribArray(1);
	glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(GLfloat), (GLvoid*)(2*sizeof(GLfloat)));

	glBindVertexArray(0);

	glBindVertexArray(VAO);
	{
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLvoid*)0);
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(GLfloat) * 5, (GLvoid*)(sizeof(GLfloat) * 2));
		glEnableVertexAttribArray(2);
		glBindBuffer(GL_ARRAY_BUFFER, instanceVBO);
		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(GLfloat), (GLvoid*)0);
		glBindBuffer(GL_ARRAY_BUFFER, 0);
		glVertexAttribDivisor(2, 1);
	}
	glBindVertexArray(0);

	std::cout << sizeof(glm::mat4) << std::endl;

	const int amount = 100000;
	glm::mat4* modelMats;
	modelMats = new glm::mat4[amount];
	srand(glfwGetTime());
	GLfloat radius = 150.0f;
	offset = 25.0f;
	for (GLuint i = 0; i < amount; i++)
	{
		glm::mat4 model;
		GLfloat angle = (GLfloat)i / (GLfloat)amount * 360.0f;
		GLfloat displacement = (rand() % (GLint)(2 * offset)) / 100.0f - offset;
		GLfloat x = sin(angle) * radius + displacement;
		displacement = (rand() % (GLint)(2 * offset * 100)) / 100.0f - offset;
		GLfloat y = displacement * 0.4f;
		displacement = (rand() % (GLint)(2 * offset * 100)) / 100.0f - offset;
		GLfloat z = cos(angle) * radius + displacement;
		model = glm::translate(model, glm::vec3(x, y, z));
		GLfloat scale = (rand() % 20) / 100.0f + 0.05f;
		model = glm::scale(model, glm::vec3(scale));
		GLfloat rotAngle = (rand() % 360);
		model = glm::rotate(model, rotAngle, glm::vec3(0.4f, 0.6f, 0.8f));
		modelMats[i] = model;
	}


	for (GLuint i = 0; i < asteroid.meshes.size(); i++)
	{
		GLuint VAO = asteroid.meshes[i].VAO;
		GLuint buffer;
		glBindVertexArray(VAO);
		glGenBuffers(1, &buffer);
		glBindBuffer(GL_ARRAY_BUFFER, buffer);
		glBufferData(GL_ARRAY_BUFFER, amount * sizeof(glm::mat4), &modelMats[0], GL_STATIC_DRAW);
		GLsizei vec4Size = sizeof(glm::vec4);
		glEnableVertexAttribArray(3);
		glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)0);
		glEnableVertexAttribArray(4);
		glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(vec4Size));
		glEnableVertexAttribArray(5);
		glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(2 * vec4Size));
		glEnableVertexAttribArray(6);
		glVertexAttribPointer(6, 4, GL_FLOAT, GL_FALSE, 4 * vec4Size, (GLvoid*)(3 * vec4Size));

		glVertexAttribDivisor(3, 1);
		glVertexAttribDivisor(4, 1);
		glVertexAttribDivisor(5, 1);
		glVertexAttribDivisor(6, 1);
		glBindVertexArray(0);
	}

	glUseProgram(modelShader);
	glUniformMatrix4fv(glGetUniformLocation(modelShader, "projection"), 1, GL_FALSE, glm::value_ptr(proj));
	glUseProgram(instancedModelShader);
	glUniformMatrix4fv(glGetUniformLocation(instancedModelShader, "projection"), 1, GL_FALSE, glm::value_ptr(proj));

	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;
		glBindFramebuffer(GL_FRAMEBUFFER, FBO);
		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glEnable(GL_DEPTH_TEST);
		handleMovement(window, deltaTime);

		glUseProgram(instancedModelShader);
		glUniformMatrix4fv(glGetUniformLocation(instancedModelShader, "view"), 1, GL_FALSE, glm::value_ptr(cam.GetViewMatrix()));
		glUseProgram(modelShader);
		glUniformMatrix4fv(glGetUniformLocation(modelShader, "view"), 1, GL_FALSE, glm::value_ptr(cam.GetViewMatrix()));


		glm::mat4 model;
		model = glm::translate(model, glm::vec3(0.0f, -5.0f, 0.0f));
		model = glm::scale(model, glm::vec3(4.0f));
		glUniformMatrix4fv(glGetUniformLocation(modelShader, "model"), 1, GL_FALSE, glm::value_ptr(model));
		planet.draw(modelShader);

		glUseProgram(instancedModelShader);
		glBindTexture(GL_TEXTURE_2D, asteroid.textures_loaded[0].id);
		for (GLuint i = 0; i < asteroid.meshes.size(); i++)
		{
			glBindVertexArray(asteroid.meshes[i].VAO);
			glDrawElementsInstanced(GL_TRIANGLES, asteroid.meshes[i].vertices.size(), GL_UNSIGNED_INT, 0, amount);
			glBindVertexArray(0);
		}
		glBindTexture(GL_TEXTURE_2D, 0);
		glBindFramebuffer(GL_READ_FRAMEBUFFER, FBO);
		glBindFramebuffer(GL_DRAW_FRAMEBUFFER, regularFBO);
		glBlitFramebuffer(0, 0, screenWidth, screenHeight, 0, 0, screenWidth, screenHeight, GL_COLOR_BUFFER_BIT, GL_NEAREST);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);
		glDisable(GL_DEPTH_TEST);
		
		glUseProgram(frameBufferShader);
		glBindVertexArray(fboVAO);
		glBindTexture(GL_TEXTURE_2D, tex);
		//glUniform1i(glGetUniformLocation(frameBufferShader, "myTexture"), 0);
		glDrawArrays(GL_TRIANGLES, 0, 6);
		glBindVertexArray(0);
		glBindTexture(GL_TEXTURE_2D, 0);
		glfwSwapBuffers(window);

	}
	glfwTerminate();
	return 0;
}
Exemplo n.º 5
0
int main(int argc, char *argv[])
{
	auto t_start = std::chrono::high_resolution_clock::now();
	GLfloat directionx, directiony, directionz;
	directionx = 0.0f;
	directiony = 0.0f;
	directionz = 1.0f;
	GLboolean quit = GL_FALSE;
	GLenum errorValue;

	// Initialize SDL
	if (SDL_Init(SDL_INIT_VIDEO) < 0)
	{
		std::cerr << "SDL video initialization failed! Error: " << SDL_GetError() << std::endl;
		quit = GL_TRUE;
		SDL_Delay(5000);
	}
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
	SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
	SDL_Window* window = SDL_CreateWindow("OpenGL tutorial", 100, 100, width, height, SDL_WINDOW_OPENGL);
	SDL_GLContext context = SDL_GL_CreateContext(window);

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	glewInit();
	
	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after GLEW init: " << errorValue << std::endl;
	}
	
	// Create Vertex Array Objects, don't bind yet
	/*
	VAOs are used to store all of the links between the vertex attributes and VBOs with raw vertex data.
	Since VBOs are just containers for the raw data that the graphics card reads and manipulates,
	the meaning and usage of the data has to be specified for each VBO & shader program.
	This might be quite cumbersome, if many shader programs are used, since the layout of the attributes would
	have to be specified every time. This is wheree VAOs come in: they can be used to store the links between
	VBO and the specified attributes. This way, a new VAO can be bound for each different shader program,
	which can then be changed easily at will by just calling glUseProgram(shaderProg1);.
	The graphics card then knows how to use the raw data in the VBO, since its usage and meaning has been
	specified beforehand and the links between VBOs and attributes has been saved to the VAO.

	As soon as VAO has been bound, all glVertexAttribPointer calls store the information to that VAO.
	*/
	GLuint vaoCube, vaoQuad;
	glGenVertexArrays(1, &vaoCube);
	glGenVertexArrays(1, &vaoQuad);

	// Create a Vertex Buffer Objects and upload vertex data
	/*
	VBOs are used to upload the vertex data to the graphics card.
	glGenBuffers(); creates a VBO, which can then be made active by binding it
	with glBindBuffer();. When the VBO has been set as active by binding it,
	the vertex data can be loaded to it with glBufferData();.

	Note that VBO/OpenGL doesn't know what the data means or is used for, it's just raw data.
	The usage of the data has to be specified, meaning which indices in the data correspond to which
	attribute (pos, color, texcoord, etc.).
	*/
	GLuint vboCube, vboQuad;
	glGenBuffers(1, &vboCube);
	glGenBuffers(1, &vboQuad);

	glBindBuffer(GL_ARRAY_BUFFER, vboCube);
	glBufferData(GL_ARRAY_BUFFER, sizeof(cubeVertices), cubeVertices, GL_STATIC_DRAW);

	glBindBuffer(GL_ARRAY_BUFFER, vboQuad);
	glBufferData(GL_ARRAY_BUFFER, sizeof(quadVertices), quadVertices, GL_STATIC_DRAW);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after VBOs: " << errorValue << std::endl;
	}

	// Generate shader programs
	GLuint sceneVertexShader, sceneFragmentShader, sceneShaderProgram;
	createShaderprogram(sceneVertexSource, sceneFragmentSource, sceneVertexShader, sceneFragmentShader, sceneShaderProgram);

	GLuint screenVertexShader, screenFragmentShader, screenShaderProgram;
	createShaderprogram(screenVertexSource, screenFragmentSource, screenVertexShader, screenFragmentShader, screenShaderProgram);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after generating shader programs: " << errorValue << std::endl;
	}

	// Specify the layout of the vertex data (bind vertex arrays)
	/*
	Since OpenGL doesn't know how the attributes of the vertices are
	specified in the arrays containing the vertex information (position, color, texture coordinates),
	they need to be specified by the user.
	Each attribute also saves the VBO that's been bound to the current GL_ARRAY_BUFFER.
	This means different VBOs can be used for each attribute if so desired.

	Only calls after a VAO has been bound will "stick" to it.
	As soon as VAO has been bound, all glVertexAttribPointer calls store the information to that VAO.
	See more complete explanation of VAO above.
	*/
	glBindVertexArray(vaoCube);
	glBindBuffer(GL_ARRAY_BUFFER, vboCube);
	specifySceneVertexAttributes(sceneShaderProgram);

	glBindVertexArray(vaoQuad);
	glBindBuffer(GL_ARRAY_BUFFER, vboQuad);
	specifyScreenVertexAttributes(screenShaderProgram);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after specifying the layout of vertex data: " << errorValue << std::endl;
	}

	// Load textures
	GLuint texKitten = loadTexture("sample.png");
	GLuint texPuppy = loadTexture("sample2.png");

	glUseProgram(sceneShaderProgram);
	glUniform1i(glGetUniformLocation(sceneShaderProgram, "texKitten"), 0);
	glUniform1i(glGetUniformLocation(sceneShaderProgram, "texPuppy"), 1);

	glUseProgram(screenShaderProgram);
	glUniform1i(glGetUniformLocation(screenShaderProgram, "texFramebuffer"), 0);

	GLint uniModel = glGetUniformLocation(sceneShaderProgram, "model");

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after loading textures: " << errorValue << std::endl;
	}

	// Create frame buffer
	GLuint frameBuffer;
	glGenFramebuffers(1, &frameBuffer);
	glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after creating a frame buffer: " << errorValue << std::endl;
	}

	// Create texture to hold color buffer
	GLuint texColorBuffer;
	glGenTextures(1, &texColorBuffer);
	glBindTexture(GL_TEXTURE_2D, texColorBuffer);
	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, NULL);
	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, texColorBuffer, 0);

	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after color buffer texture creation: " << errorValue << std::endl;
	}

	// Create Renderbuffer Object to hold depth and stencil buffers
	GLuint rboDepthStencil;
	glGenRenderbuffers(1, &rboDepthStencil);
	glBindRenderbuffer(GL_RENDERBUFFER, rboDepthStencil);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width, height);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rboDepthStencil);


	// Error checking
	errorValue = glGetError();
	if (errorValue != 0)
	{
		std::cerr << "GL_Error after RBO: " << errorValue << std::endl;
	}

	/*
	Set up projection:
	View matrix:
	First vector gives the position of the camera
	Second vector gives the point where the camera is centered or looking at
	Third vector defines "up", here up is the z-axis, xy-plane is the "ground"
	*/
	glm::mat4 view = glm::lookAt(
		glm::vec3(2.5f, 2.5f, 2.0f),
		glm::vec3(0.0f, 0.0f, 0.0f),
		glm::vec3(0.0f, 0.0f, 1.0f)
		);

	glUseProgram(sceneShaderProgram);

	GLint uniView = glGetUniformLocation(sceneShaderProgram, "view");
	glUniformMatrix4fv(uniView, 1, GL_FALSE, glm::value_ptr(view));

	// Projection matrix
	glm::mat4 proj = glm::perspective(glm::radians(45.0f), GLfloat(width) / GLfloat(height), 1.0f, 10.0f);
	GLint uniProj = glGetUniformLocation(sceneShaderProgram, "proj");
	glUniformMatrix4fv(uniProj, 1, GL_FALSE, glm::value_ptr(proj));

	GLint uniColor = glGetUniformLocation(sceneShaderProgram, "overrideColor");

	// Final error check will write errors (if any are encountered at this point) to file
	GLint status, status2, status3, status4, OpenGLError;
	OpenGLError = glGetError();
	GLenum frameBufferStatus = glCheckFramebufferStatus(GL_FRAMEBUFFER);
	glGetShaderiv(sceneVertexShader, GL_COMPILE_STATUS, &status);
	glGetShaderiv(sceneFragmentShader, GL_COMPILE_STATUS, &status2);
	glGetShaderiv(screenVertexShader, GL_COMPILE_STATUS, &status3);
	glGetShaderiv(screenFragmentShader, GL_COMPILE_STATUS, &status4);

	if (
		OpenGLError != 0
		|| status == 0
		|| status2 == 0
		|| status3 == 0
		|| status4 == 0
		|| frameBufferStatus != GL_FRAMEBUFFER_COMPLETE)
	{
		char buffer1[512], buffer2[512], buffer3[512], buffer4[512];
		glGetShaderInfoLog(sceneVertexShader, 512, NULL, buffer1);
		glGetShaderInfoLog(sceneFragmentShader, 512, NULL, buffer2);
		glGetShaderInfoLog(screenVertexShader, 512, NULL, buffer3);
		glGetShaderInfoLog(screenFragmentShader, 512, NULL, buffer4);

		std::ofstream errorOutput;
		GLchar* errorOutFilename = "shader_errors.txt";
		errorOutput.open(errorOutFilename);
		
		errorOutput
			<< "GL_Error: " << OpenGLError
			<< "\n Scene vertex shader status: " << status
			<< "\n Scene vertex shader log: " << buffer1
			<< "\n Scene fragment shader status: " << status2
			<< "\n Scene fragment shader log: " << buffer2
			<< "\n Screen vertex shader status: " << status3
			<< "\n Screen vertex shader log: " << buffer3
			<< "\n Screen fragment shader status: " << status4
			<< "\n Screen fragment shader log: " << buffer4
			<< "\n Frame buffer status: " << frameBufferStatus
			<< "\n OpenGL version: " << glGetString(GL_VERSION);
		
		errorOutput.close();
		
		std::cerr << "An error has occured with shaders or frame buffer! See "
			<< errorOutFilename
			<< " for more info!\n Terminating program in 10s!"
			<< std::endl;

		SDL_Delay(10000);
		quit = GL_TRUE;
	}

	SDL_Event e;

	while (!quit)
	{
		while (SDL_PollEvent(&e) != 0)
		{
			if (e.type == SDL_QUIT)
			{
				quit = GL_TRUE;
			}
			else if (e.type == SDL_KEYDOWN)
			{
				switch (e.key.keysym.sym)
				{
				case SDLK_RETURN:
					directionx = 1.0f;
					directiony = 0.0f;
					directionz = 0.0f;
					break;
				case SDLK_SPACE:
					directionx = 0.0f;
					directiony = 1.0f;
					directionz = 0.0f;
					break;
				case SDLK_LCTRL:
					directionx = 0.0f;
					directiony = 0.0f;
					directionz = 1.0f;
				default:
					directionx = 0.0f;
					directiony = 0.0f;
					directionz = 1.0f;
					break;
				}
			}
		}

		// Bind framebuffer and draw 3D scene
		glBindFramebuffer(GL_FRAMEBUFFER, frameBuffer);
		glBindVertexArray(vaoCube);
		glEnable(GL_DEPTH_TEST);
		glUseProgram(sceneShaderProgram);
		
		glActiveTexture(GL_TEXTURE0);
		glBindTexture(GL_TEXTURE_2D, texKitten);
		glActiveTexture(GL_TEXTURE1);
		glBindTexture(GL_TEXTURE_2D, texPuppy);

		// Clear screen to greenish
		glClearColor(0.15f, 0.7f, 0.5f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// Calculate transformation
		auto t_now = std::chrono::high_resolution_clock::now();
		float time = std::chrono::duration_cast<std::chrono::duration<float>>(t_now - t_start).count();
		
		glm::mat4 model;
		model = glm::rotate(model, time * glm::radians(180.f), glm::vec3(directionx, directiony, directionz));
		glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model));

		// Draw cube
		glDrawArrays(GL_TRIANGLES, 0, 36);

		glEnable(GL_STENCIL_TEST);

		// Draw floor
		glStencilFunc(GL_ALWAYS, 1, 0xFF); // Set any stencil to 1
		glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
		glStencilMask(0xFF); // Write to stencil buffer
		glDepthMask(GL_FALSE); // Don't write to depth buffer
		glClear(GL_STENCIL_BUFFER_BIT); // Clear stencil buffer (0 by default)

		glDrawArrays(GL_TRIANGLES, 36, 6);

		// Draw cube reflection

		glStencilFunc(GL_EQUAL, 1, 0xFF); // Pass test if stencil value is 1
		glStencilMask(0x00); // Don't write anything to stencil buffer
		glDepthMask(GL_TRUE); // Write to depth buffer

		model = glm::scale(glm::translate(model, glm::vec3(0, 0, -1)), glm::vec3(1, 1, -1));
		glUniformMatrix4fv(uniModel, 1, GL_FALSE, glm::value_ptr(model));

		glUniform3f(uniColor, 0.3f, 0.3f, 0.3f);
		glDrawArrays(GL_TRIANGLES, 0, 36);
		glUniform3f(uniColor, 1.0f, 1.0f, 1.0f);

		glDisable(GL_STENCIL_TEST);

		// Bind default framebuffer and draw contents of our framebuffer
		glBindFramebuffer(GL_FRAMEBUFFER, 0);
		glBindVertexArray(vaoQuad);
		glDisable(GL_DEPTH_TEST);
		glUseProgram(screenShaderProgram);

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

		glDrawArrays(GL_TRIANGLES, 0, 6);

		// Swap buffers
		SDL_GL_SwapWindow(window);
		
	}
	glDeleteRenderbuffers(1, &rboDepthStencil);
	glDeleteTextures(1, &texColorBuffer);
	glDeleteFramebuffers(1, &frameBuffer);
	
	glDeleteTextures(1, &texKitten);
	glDeleteTextures(1, &texPuppy);

	glDeleteProgram(screenShaderProgram);
	glDeleteShader(screenFragmentShader);
	glDeleteShader(screenVertexShader);

	glDeleteProgram(sceneShaderProgram);
	glDeleteShader(sceneFragmentShader);
	glDeleteShader(sceneVertexShader);

	glDeleteBuffers(1, &vboCube);
	glDeleteBuffers(1, &vboQuad);

	glDeleteVertexArrays(1, &vaoCube);
	glDeleteVertexArrays(1, &vaoQuad);

	SDL_GL_DeleteContext(context);
	SDL_Quit();
	return 0;
}
Exemplo n.º 6
0
void ofTexture::allocate(const ofTextureData & textureData, int glFormat, int pixelType){
#ifndef TARGET_OPENGLES
	if(texData.textureTarget == GL_TEXTURE_2D || texData.textureTarget == GL_TEXTURE_RECTANGLE_ARB){
#else
	if(texData.textureTarget == GL_TEXTURE_2D){
#endif
		if( textureData.width <= 0.0 || textureData.height <= 0.0 ){
			ofLogError("ofTexture") << "allocate(): ofTextureData has 0 width and/or height: " << textureData.width << "x" << textureData.height;
			return;
		}
	}

	texData = textureData;
	//our graphics card might not support arb so we have to see if it is supported.
#ifndef TARGET_OPENGLES
	if( texData.textureTarget==GL_TEXTURE_RECTANGLE_ARB && ofGLSupportsNPOTTextures() ){
		texData.tex_w = texData.width;
		texData.tex_h = texData.height;
		texData.tex_t = texData.width;
		texData.tex_u = texData.height;
	}else if(texData.textureTarget == GL_TEXTURE_2D)
#endif
	{
		if(ofGLSupportsNPOTTextures()){
			texData.tex_w = texData.width;
			texData.tex_h = texData.height;
		}else{
			//otherwise we need to calculate the next power of 2 for the requested dimensions
			//ie (320x240) becomes (512x256)
			texData.tex_w = ofNextPow2(texData.width);
			texData.tex_h = ofNextPow2(texData.height);
		}

		texData.tex_t = texData.width / texData.tex_w;
		texData.tex_u = texData.height / texData.tex_h;
	}

	// attempt to free the previous bound texture, if we can:
	clear();

	glGenTextures(1, (GLuint *)&texData.textureID);   // could be more then one, but for now, just one
	retain(texData.textureID);

#ifndef TARGET_OPENGLES
	if(texData.textureTarget == GL_TEXTURE_2D || texData.textureTarget == GL_TEXTURE_RECTANGLE_ARB){
#else
	if(texData.textureTarget == GL_TEXTURE_2D){
#endif
		glBindTexture(texData.textureTarget,texData.textureID);
		glTexImage2D(texData.textureTarget, 0, texData.glInternalFormat, (GLint)texData.tex_w, (GLint)texData.tex_h, 0, glFormat, pixelType, 0);  // init to black...

		glTexParameterf(texData.textureTarget, GL_TEXTURE_MAG_FILTER, texData.magFilter);
		glTexParameterf(texData.textureTarget, GL_TEXTURE_MIN_FILTER, texData.minFilter);
		glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_S, texData.wrapModeHorizontal);
		glTexParameterf(texData.textureTarget, GL_TEXTURE_WRAP_T, texData.wrapModeVertical);

		#ifndef TARGET_PROGRAMMABLE_GL
			if (!ofIsGLProgrammableRenderer()){
				glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
			}
		#endif
		glBindTexture(texData.textureTarget,0);
	}

	texData.bAllocated = true;

#ifdef TARGET_ANDROID
	registerTexture(this);
#endif
}


void ofTexture::setRGToRGBASwizzles(bool rToRGBSwizzles){
#ifndef TARGET_OPENGLES
	glBindTexture(texData.textureTarget,texData.textureID);
	if(rToRGBSwizzles){
		if(texData.glInternalFormat==GL_R8 ||
				texData.glInternalFormat==GL_R16 ||
				texData.glInternalFormat==GL_R32F){
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_R, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_G, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_B, GL_RED);

		}else if(texData.glInternalFormat==GL_RG8 ||
				texData.glInternalFormat==GL_RG16 ||
				texData.glInternalFormat==GL_RG32F){
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_R, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_G, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_B, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_A, GL_GREEN);
		}
	}else{
		if(texData.glInternalFormat==GL_R8 ||
				texData.glInternalFormat==GL_R16 ||
				texData.glInternalFormat==GL_R32F){
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_R, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_B, GL_BLUE);

		}else if(texData.glInternalFormat==GL_RG8 ||
				texData.glInternalFormat==GL_RG16 ||
				texData.glInternalFormat==GL_RG32F){
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_R, GL_RED);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_G, GL_GREEN);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_B, GL_BLUE);
			 glTexParameteri(texData.textureTarget, GL_TEXTURE_SWIZZLE_A, GL_ALPHA);
		}
	}
	glBindTexture(texData.textureTarget,0);
#endif
}

void ofTexture::setSwizzle(GLenum srcSwizzle, GLenum dstChannel){
#ifndef TARGET_OPENGLES
	glBindTexture(texData.textureTarget,texData.textureID);
	glTexParameteri(texData.textureTarget, srcSwizzle, dstChannel);
	glBindTexture(texData.textureTarget,0);
#endif
}
Exemplo n.º 7
0
void EDA_3D_CANVAS::create_and_render_shadow_buffer( GLuint *aDst_gl_texture,
        GLuint aTexture_size, bool aDraw_body, int aBlurPasses )
{
    glDisable( GL_TEXTURE_2D );

    glViewport( 0, 0, aTexture_size, aTexture_size);

    glClearColor( 1.0f, 1.0f, 1.0f, 1.0f );
    glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

    // Render body and shapes

    if( aDraw_body && m_glLists[GL_ID_BODY] )
        glCallList( m_glLists[GL_ID_BODY] );

    if( m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] )
        glCallList( m_glLists[GL_ID_3DSHAPES_SOLID_FRONT] );

    // Create and Initialize the float depth buffer

    float *depthbufferFloat = (float*) malloc( aTexture_size * aTexture_size * sizeof(float) );

    for( unsigned int i = 0; i < (aTexture_size * aTexture_size); i++ )
        depthbufferFloat[i] = 1.0f;

    glPixelStorei( GL_PACK_ALIGNMENT, 4 );
    glPixelStorei( GL_UNPACK_ALIGNMENT, 4 );
    glReadBuffer( GL_BACK_LEFT );
    glReadPixels( 0, 0,
                  aTexture_size, aTexture_size,
                  GL_DEPTH_COMPONENT, GL_FLOAT, depthbufferFloat );

    CheckGLError( __FILE__, __LINE__ );

    glEnable( GL_TEXTURE_2D );
    glGenTextures( 1, aDst_gl_texture );
    glBindTexture( GL_TEXTURE_2D, *aDst_gl_texture );

    CIMAGE imgDepthBuffer( aTexture_size, aTexture_size );
    CIMAGE imgDepthBufferAux( aTexture_size, aTexture_size );

    imgDepthBuffer.SetPixelsFromNormalizedFloat( depthbufferFloat );

    free( depthbufferFloat );

    // Debug texture image
    //wxString filename;
    //filename.Printf( "imgDepthBuffer_%04d", *aDst_gl_texture );
    //imgDepthBuffer.SaveAsPNG( filename );

    while( aBlurPasses > 0 )
    {
        aBlurPasses--;
        imgDepthBufferAux.EfxFilter( &imgDepthBuffer, FILTER_GAUSSIAN_BLUR );
        imgDepthBuffer.EfxFilter( &imgDepthBufferAux, FILTER_GAUSSIAN_BLUR );
    }

    // Debug texture image
    //filename.Printf( "imgDepthBuffer_blur%04d", *aDst_gl_texture );
    //imgDepthBuffer.SaveAsPNG( filename );

    unsigned char *depthbufferRGBA = (unsigned char*) malloc( aTexture_size * aTexture_size * 4 );
    unsigned char *pPixels = imgDepthBuffer.GetBuffer();

    // Convert it to a RGBA buffer
    for( unsigned int i = 0; i < (aTexture_size * aTexture_size); i++ )
    {
        depthbufferRGBA[i * 4 + 0] = 0;
        depthbufferRGBA[i * 4 + 1] = 0;
        depthbufferRGBA[i * 4 + 2] = 0;
        depthbufferRGBA[i * 4 + 3] = 255 - pPixels[i];                  // Store in alpha channel the inversion of the image
    }

    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
    glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );

    glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, aTexture_size, aTexture_size, 0, GL_RGBA, GL_UNSIGNED_BYTE, depthbufferRGBA );

    free( depthbufferRGBA );

    CheckGLError( __FILE__, __LINE__ );
}
Exemplo n.º 8
0
//----------------------------------------------------------------//
void USTexture::CreateTextureFromImage ( USImage& image ) {

	if ( !image.IsOK ()) return;

	// get the dimensions before trying to get the OpenGL texture ID
	this->mWidth = image.GetWidth ();
	this->mHeight = image.GetHeight ();

	glGenTextures ( 1, &this->mGLTexID );
	if ( !this->mGLTexID ) return;

	glBindTexture ( GL_TEXTURE_2D, this->mGLTexID );

	USPixel::Format pixelFormat = image.GetPixelFormat ();
	USColor::Format colorFormat = image.GetColorFormat ();

	// generate mipmaps if set up to use them
	if (	( this->mMinFilter == GL_LINEAR_MIPMAP_LINEAR ) ||
			( this->mMinFilter == GL_LINEAR_MIPMAP_NEAREST ) ||
			( this->mMinFilter == GL_NEAREST_MIPMAP_LINEAR ) ||
			( this->mMinFilter == GL_NEAREST_MIPMAP_NEAREST )) {
		
		glTexParameteri ( GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE );
	}

	if ( pixelFormat == USPixel::TRUECOLOR ) {

		// GL_ALPHA
		// GL_RGB
		// GL_RGBA
		// GL_LUMINANCE
		// GL_LUMINANCE_ALPHA

		// GL_UNSIGNED_BYTE
		// GL_UNSIGNED_SHORT_5_6_5
		// GL_UNSIGNED_SHORT_4_4_4_4
		// GL_UNSIGNED_SHORT_5_5_5_1

		switch ( colorFormat ) {
			
			case USColor::A_8:
				this->mGLInternalFormat = GL_ALPHA;
				this->mGLPixelType = GL_UNSIGNED_BYTE;
				break;
			
			case USColor::RGB_888:
				this->mGLInternalFormat = GL_RGB;
				this->mGLPixelType = GL_UNSIGNED_BYTE;
				break;
			
			case USColor::RGB_565:
				this->mGLInternalFormat = GL_RGB;
				this->mGLPixelType = GL_UNSIGNED_SHORT_5_6_5;
				break;
			
			case USColor::RGBA_4444:
				this->mGLInternalFormat = GL_RGBA;
				this->mGLPixelType = GL_UNSIGNED_SHORT_4_4_4_4;
				break;
			
			case USColor::RGBA_8888:
				this->mGLInternalFormat = GL_RGBA;
				this->mGLPixelType = GL_UNSIGNED_BYTE;
				break;
				
			default: return;
		}

		glTexImage2D (
			GL_TEXTURE_2D,
			0,  
			this->mGLInternalFormat,
			this->mWidth,  
			this->mHeight,  
			0,  
			this->mGLInternalFormat,
			this->mGLPixelType,  
			image.GetBitmap ()
		);
	}
	else {
	
		// GL_PALETTE4_RGB8_OES
		// GL_PALETTE4_R5_G6_B5_OES
		// GL_PALETTE4_RGBA4_OES
		// GL_PALETTE4_RGB5_A1_OES
		// GL_PALETTE4_RGBA8_OES

		// GL_PALETTE8_RGB8_OES
		// GL_PALETTE8_R5_G6_B5_OES
		// GL_PALETTE8_RGBA4_OES
		// GL_PALETTE8_RGB5_A1_OES
		// GL_PALETTE8_RGBA8_OES

// TODO: check opengl version
//		this->mGLPixelType = 0;
//	
//		if ( pixelFormat == USPixel::INDEX_4 ) {
//		
//			switch ( colorFormat ) {
//			
//				case USColor::RGB_888:
//					this->mGLInternalFormat = GL_PALETTE4_RGB8_OES;
//					break;
//				
//				case USColor::RGBA_8888:
//					this->mGLInternalFormat = GL_PALETTE4_RGBA8_OES;
//					break;
//					
//				default: return;
//			}
//		}
//		else {
//			switch ( colorFormat ) {
//			
//				case USColor::RGB_888:
//					this->mGLInternalFormat = GL_PALETTE8_RGB8_OES;
//					break;
//				
//				case USColor::RGBA_8888:
//					this->mGLInternalFormat = GL_PALETTE8_RGBA8_OES;
//					break;
//					
//				default: return;
//			}
//		}
//		
//		glCompressedTexImage2D (
//			GL_TEXTURE_2D,
//			0,  
//			this->mGLInternalFormat,
//			this->mDevWidth,
//			this->mDevHeight,
//			0,  
//			image.GetDataSize (),
//			image.GetData ()
//		);
	}
}
Exemplo n.º 9
0
Arquivo: main.cpp Projeto: JoaoS/CG
void criaDefineTexturas()
{

    //textura com o blend activado, tem de ser a primeira a ser carregada senão o resto fica com uma cor esquesita
    glGenTextures(1, &tex[5]);
    glBindTexture(GL_TEXTURE_2D, tex[5]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("mirror.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());

    //----------------------------------------- Chao y=0 nivel 1
    glGenTextures(1, &tex[0]);
    glBindTexture(GL_TEXTURE_2D, tex[0]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("grass1.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());
    //----------------------------------------- obstaculos nivel 1
    glGenTextures(1, &tex[1]);
    glBindTexture(GL_TEXTURE_2D, tex[1]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("wood.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());
    //----------------------------------------- Chao y=0 nivel 2
    glGenTextures(1, &tex[2]);
    glBindTexture(GL_TEXTURE_2D, tex[2]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("paver.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());
    //----------------------------------------- obstaculos nivel 2
    glGenTextures(1, &tex[3]);
    glBindTexture(GL_TEXTURE_2D, tex[3]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("aluminium.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());
     //----------------------------------------- Chao y=0 nivel 3
    glGenTextures(1, &tex[4]);
    glBindTexture(GL_TEXTURE_2D, tex[4]);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    imag.LoadBmpFile("futuristic.bmp");
    glTexImage2D(GL_TEXTURE_2D, 0, 3, imag.GetNumCols(),imag.GetNumRows(), 0, GL_RGB, GL_UNSIGNED_BYTE,imag.ImageData());


}
Exemplo n.º 10
0
void Cube:: drawTexture(){
  glBegin(GL_QUADS);
  //Top face
  glColor3f(1.0f, 1.0f, 0.0f);
  glNormal3f(0.0, 1.0f, 0.0f);
  glVertex3f(-w / 2, h / 2, -d / 2);
  glVertex3f(-w / 2, h / 2, d / 2);
  glVertex3f(w / 2, h / 2, d / 2);
  glVertex3f(w / 2, h / 2, -d / 2);
	
  //Bottom face
  glColor3f(1.0f, 0.0f, 1.0f);
  glNormal3f(0.0, -1.0f, 0.0f);
  glVertex3f(-w / 2, -h / 2, -d / 2);
  glVertex3f(w / 2, -h / 2, -d / 2);
  glVertex3f(w / 2, -h / 2, d / 2);
  glVertex3f(-w / 2, -h / 2, d / 2);
  
  //Left face
  glNormal3f(-1.0, 0.0f, 0.0f);
  glColor3f(0.0f, 1.0f, 1.0f);
  glVertex3f(-w / 2, -h / 2, -d / 2);
  glVertex3f(-w / 2, -h / 2, d / 2);
  glColor3f(0.0f, 0.0f, 1.0f);
  glVertex3f(-w / 2, h / 2, d / 2);
  glVertex3f(-w / 2, h / 2, -d / 2);
	
  //Right face
  glNormal3f(1.0, 0.0f, 0.0f);
  glColor3f(1.0f, 0.0f, 0.0f);
  glVertex3f(w / 2, -h / 2, -d / 2);
  glVertex3f(w / 2, h / 2, -d / 2);
  glColor3f(0.0f, 1.0f, 0.0f);
  glVertex3f(w / 2, h / 2, d / 2);
  glVertex3f(w / 2, -h / 2, d / 2);
	
  glEnd();
	
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D,textureId);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glColor3f(1.0f, 1.0f, 1.0f);
  glBegin(GL_QUADS);
	
  //Front face
  glNormal3f(0.0, 0.0f, 1.0f);
  glTexCoord2f(0.0f, 0.0f);
  glVertex3f(-w / 2, -h / 2, d / 2);
  glTexCoord2f(tex_width, 0.0f);
  glVertex3f(w / 2, -h / 2, d / 2);
  glTexCoord2f(tex_width, tex_height);
  glVertex3f(w / 2 , h / 2, d / 2);
  glTexCoord2f(0.0f, tex_height);
  glVertex3f(-w / 2, h / 2, d / 2);
	
  //Back face
  glNormal3f(0.0, 0.0f, -1.0f);
  glTexCoord2f(0.0f, 0.0f);
  glVertex3f(-w / 2, -h / 2, -d / 2);
  glTexCoord2f(0.0f, tex_height);
  glVertex3f(-w / 2, h / 2, -d / 2);
  glTexCoord2f(tex_width, tex_height);
  glVertex3f(w / 2, h / 2, -d / 2);
  glTexCoord2f(tex_width, 0.0f);
  glVertex3f(w / 2, -h / 2, -d / 2);
	
  glEnd();
  glDisable(GL_TEXTURE_2D);
}
Exemplo n.º 11
0
int LoadGLTextures(const aiScene* scene)
{
	ILboolean success;

	/* initialization of DevIL */
	ilInit(); 

	/* scan scene's materials for textures */
	for (unsigned int m=0; m<scene->mNumMaterials; ++m)
	{
		int texIndex = 0;
		aiString path;	// filename

		aiReturn texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
		while (texFound == AI_SUCCESS) {
			//fill map with textures, OpenGL image ids set to 0
			textureIdMap[path.data] = 0; 
			// more textures?
			texIndex++;
			texFound = scene->mMaterials[m]->GetTexture(aiTextureType_DIFFUSE, texIndex, &path);
		}
	}

	int numTextures = textureIdMap.size();

	/* create and fill array with DevIL texture ids */
	ILuint* imageIds = new ILuint[numTextures];
	ilGenImages(numTextures, imageIds); 

	/* create and fill array with GL texture ids */
	GLuint* textureIds = new GLuint[numTextures];
	glGenTextures(numTextures, textureIds); /* Texture name generation */

	/* get iterator */
	std::map<std::string, GLuint>::iterator itr = textureIdMap.begin();
	int i=0;
	for (; itr != textureIdMap.end(); ++i, ++itr)
	{
		//save IL image ID
		std::string filename = (*itr).first;  // get filename
		(*itr).second = textureIds[i];	  // save texture id for filename in map

		ilBindImage(imageIds[i]); /* Binding of DevIL image name */
		ilEnable(IL_ORIGIN_SET);
		ilOriginFunc(IL_ORIGIN_LOWER_LEFT); 
		success = ilLoadImage((ILstring)filename.c_str());

		if (success) {
			/* Convert image to RGBA */
			ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE); 

			/* Create and load textures to OpenGL */
			glBindTexture(GL_TEXTURE_2D, textureIds[i]); 
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); 
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, ilGetInteger(IL_IMAGE_WIDTH),
				ilGetInteger(IL_IMAGE_HEIGHT), 0, GL_RGBA, GL_UNSIGNED_BYTE,
				ilGetData()); 
		}
		else 
			printf("Couldn't load Image: %s\n", filename.c_str());
	}
	/* Because we have already copied image data into texture data
	we can release memory used by image. */
	ilDeleteImages(numTextures, imageIds); 

	//Cleanup
	delete [] imageIds;
	delete [] textureIds;

	//return success;
	return true;
}
Exemplo n.º 12
0
static void Init( int argc, char *argv[] )
{
   GLuint texObj[8];
   GLint size, i;

   const char *exten = (const char *) glGetString(GL_EXTENSIONS);
   if (!strstr(exten, "GL_ATI_fragment_shader")) {
      printf("Sorry, GL_ATI_fragment_shader not supported by this renderer.\n");
      exit(1);
   }


   glGetIntegerv(GL_MAX_TEXTURE_SIZE, &size);
   printf("%d x %d max texture size\n", size, size);

   glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

   for (i = 0; i < NumUnits; i++) {
      if (i < 6)
         TexEnabled[i] = GL_TRUE;
      else
         TexEnabled[i] = GL_FALSE;
   }

   /* allocate two texture objects */
   glGenTextures(NumUnits, texObj);

   /* setup the texture objects */
   for (i = 0; i < NumUnits; i++) {

      glActiveTextureARB(GL_TEXTURE0_ARB + i);
      glBindTexture(GL_TEXTURE_2D, texObj[i]);

      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

      if (i == 0) {
         if (!LoadRGBMipmaps(TEXTURE_1_FILE, GL_RGB)) {
            printf("Error: couldn't load texture image\n");
            exit(1);
         }
      }
      else if (i == 1) {
         if (!LoadRGBMipmaps(TEXTURE_2_FILE, GL_RGB)) {
            printf("Error: couldn't load texture image\n");
            exit(1);
         }
      }
      else {
         /* checker */
         GLubyte image[8][8][3];
         GLint i, j;
         for (i = 0; i < 8; i++) {
            for (j = 0; j < 8; j++) {
               if ((i + j) & 1) {
                  image[i][j][0] = 50;
                  image[i][j][1] = 50;
                  image[i][j][2] = 50;
               }
               else {
                  image[i][j][0] = 25;
                  image[i][j][1] = 25;
                  image[i][j][2] = 25;
               }
            }
         }
         glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 8, 8, 0,
                      GL_RGB, GL_UNSIGNED_BYTE, (GLvoid *) image);
      }

      /* Bind texObj[i] to ith texture unit */
/*      if (i < 2)
         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
      else
         glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_ADD);*/

      if (TexEnabled[i])
         glEnable(GL_TEXTURE_2D);
   }

   boringshaderID = glGenFragmentShadersATI(1);
   boring2passID = glGenFragmentShadersATI(1);
   if (boring2passID == 0)
   {
      fprintf(stderr, "couldn't get frag shader id\n");
      exit(1);
   }
   glBindFragmentShaderATI(boringshaderID);
/* maybe not the most creative shader but at least I know how it should look like! */
   glBeginFragmentShaderATI();
   glSampleMapATI(GL_REG_0_ATI, GL_TEXTURE0_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_1_ATI, GL_TEXTURE1_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_2_ATI, GL_TEXTURE2_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_3_ATI, GL_TEXTURE3_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_4_ATI, GL_TEXTURE4_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_5_ATI, GL_TEXTURE5_ARB, GL_SWIZZLE_STR_ATI);
   glColorFragmentOp2ATI(GL_MUL_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_PRIMARY_COLOR, GL_NONE, GL_NONE);
   glAlphaFragmentOp1ATI(GL_MOV_ATI,
			 GL_REG_0_ATI, GL_NONE,
			 GL_PRIMARY_COLOR, GL_NONE, GL_NONE);
   glColorFragmentOp3ATI(GL_MAD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_1_ATI, GL_NONE, GL_NONE,
			 GL_REG_2_ATI, GL_NONE, GL_NONE);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_3_ATI, GL_NONE, GL_NONE);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_4_ATI, GL_NONE, GL_NONE);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_5_ATI, GL_NONE, GL_NONE);
   glEndFragmentShaderATI();

/* mathematically equivalent to first shader but using 2 passes together with
   some tex coord rerouting */
   glBindFragmentShaderATI(boring2passID);
   glBeginFragmentShaderATI();
   glPassTexCoordATI(GL_REG_1_ATI, GL_TEXTURE0_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_2_ATI, GL_TEXTURE2_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_3_ATI, GL_TEXTURE3_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_4_ATI, GL_TEXTURE4_ARB, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_5_ATI, GL_TEXTURE5_ARB, GL_SWIZZLE_STR_ATI);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_2_ATI, GL_NONE, GL_NONE,
			 GL_REG_3_ATI, GL_NONE, GL_NONE);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_4_ATI, GL_NONE, GL_NONE);
   glColorFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_5_ATI, GL_NONE, GL_NONE);
   /* not really a dependant read */
   glSampleMapATI(GL_REG_0_ATI, GL_REG_1_ATI, GL_SWIZZLE_STR_ATI);
   glSampleMapATI(GL_REG_1_ATI, GL_TEXTURE1_ARB, GL_SWIZZLE_STR_ATI);
   glPassTexCoordATI(GL_REG_5_ATI, GL_REG_0_ATI, GL_SWIZZLE_STR_ATI);
   glColorFragmentOp2ATI(GL_MUL_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_PRIMARY_COLOR, GL_NONE, GL_NONE);
   glAlphaFragmentOp1ATI(GL_MOV_ATI,
			 GL_REG_0_ATI, GL_NONE,
			 GL_PRIMARY_COLOR, GL_NONE, GL_NONE);
   glColorFragmentOp3ATI(GL_MAD_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_SATURATE_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_1_ATI, GL_NONE, GL_NONE,
			 GL_REG_5_ATI, GL_NONE, GL_NONE);
   /* in principle we're finished here, but to test a bit more
      we do some fun with dot ops, replication et al. */
   glSetFragmentShaderConstantATI(GL_CON_3_ATI, shaderconstant);
   glColorFragmentOp2ATI(GL_DOT4_ATI,
			 GL_REG_3_ATI, GL_GREEN_BIT_ATI, GL_EIGHTH_BIT_ATI,
			 GL_ZERO, GL_NONE, GL_COMP_BIT_ATI | GL_NEGATE_BIT_ATI,
			 GL_CON_3_ATI, GL_RED, GL_2X_BIT_ATI);
   /* those args must get ignored, except dstReg */
   glAlphaFragmentOp2ATI(GL_DOT4_ATI,
			 GL_REG_4_ATI, GL_NONE,
			 GL_ZERO, GL_NONE, GL_NONE,
			 GL_ZERO, GL_NONE, GL_NONE);
   /* -> reg3 g = reg4 alpha = -0.5 */
   glAlphaFragmentOp2ATI(GL_ADD_ATI,
			 GL_REG_5_ATI, GL_NONE,
			 GL_REG_3_ATI, GL_GREEN, GL_NONE,
			 GL_REG_4_ATI, GL_NONE, GL_NONE);
   /* -> reg5 a = -1 */
   glColorFragmentOp3ATI(GL_DOT2_ADD_ATI,
			 GL_REG_4_ATI, GL_BLUE_BIT_ATI, GL_HALF_BIT_ATI,
			 GL_REG_5_ATI, GL_ALPHA, GL_NEGATE_BIT_ATI,
			 GL_ONE, GL_NONE, GL_BIAS_BIT_ATI,
			 GL_ONE, GL_ALPHA, GL_2X_BIT_ATI | GL_NEGATE_BIT_ATI);
   /* -> reg 4 b = -0.5 */
   glColorFragmentOp2ATI(GL_MUL_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE,
			 GL_REG_4_ATI, GL_BLUE, GL_NEGATE_BIT_ATI | GL_2X_BIT_ATI,
			 GL_REG_0_ATI, GL_NONE, GL_NONE);
   glEndFragmentShaderATI();

   glBindFragmentShaderATI(boringshaderID);
   glEnable(GL_FRAGMENT_SHADER_ATI);

   glShadeModel(GL_FLAT);
   glClearColor(0.3, 0.3, 0.4, 1.0);

   if (argc > 1 && strcmp(argv[1], "-info")==0) {
      printf("GL_RENDERER   = %s\n", (char *) glGetString(GL_RENDERER));
      printf("GL_VERSION    = %s\n", (char *) glGetString(GL_VERSION));
      printf("GL_VENDOR     = %s\n", (char *) glGetString(GL_VENDOR));
      printf("GL_EXTENSIONS = %s\n", (char *) glGetString(GL_EXTENSIONS));
   }
   printf("output should be identical with both shaders to multiarb demo when 6 textures are enabled\n");
}
Exemplo n.º 13
0
bool CFrameBufferObjectGL::CreateAndBindToTexture(GLenum target, int width, int height, GLenum format,
                                                GLenum filter, GLenum clampmode)
{
  unsigned char* buf = NULL;
  GLenum errCode;

#ifdef HAS_GLES
  if(width > 2048 || height > 2048)
  {
    CLog::Log(LOGERROR,"CFrameBufferObjectGL::CreateAndBindToTexture size is too big width = %d height = %d",
        width, height);
    return false;
  }
#endif

  if (!IsValid())
    return false;

  if (m_texid)
    glDeleteTextures(1, &m_texid);

  m_width = width;
  m_height = height;

  // color
  glGenTextures(1, &m_texid);

  if(m_texid == 0)
  {
    printf("CreateAndBindToTexture glGenTextures failed\n");
  }

  glBindTexture(target, m_texid);
  glGetError();
  glTexImage2D(target, 0, format,  width, height, 0, format, GL_UNSIGNED_BYTE, NULL);

  if ((errCode = glGetError()) != GL_NO_ERROR)
  {
    CLog::Log(LOGERROR, "CFrameBufferObjectGL::CreateAndBindToTexture glTexImage2D failed %x", errCode);
    glBindTexture(target, 0);
    Cleanup();
    return false;
  }


  glTexParameteri(target, GL_TEXTURE_WRAP_S, clampmode);
  glTexParameteri(target, GL_TEXTURE_WRAP_T, clampmode);
  glTexParameteri(target, GL_TEXTURE_MAG_FILTER, filter);
  glTexParameteri(target, GL_TEXTURE_MIN_FILTER, filter);

#ifdef _DEBUG
  buf = (unsigned char *)malloc(width * height * 4);
  memset(buf, 128, width * height * 4);
  glTexSubImage2D(target, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, buf);
  free(buf);
#endif
  glBindTexture(target, 0);

  if(!BindToTexture(target, m_texid))
    return false;
  else
    return true;
}
Exemplo n.º 14
0
static FboDesc CreateSurfaces(GLsizei width, GLsizei height, int numComponents, int numTargets)
{
    FboDesc surface;
    glGenFramebuffers(1, &surface.FboHandle);
    glBindFramebuffer(GL_FRAMEBUFFER, surface.FboHandle);

    for (int attachment = 0; attachment < numTargets; ++attachment) {

        GLuint textureHandle;
        glGenTextures(1, &textureHandle);
        glBindTexture(GL_TEXTURE_2D, textureHandle);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
        
        surface.TextureHandle[attachment] = textureHandle;

        switch (numComponents) {
            case 1: glTexImage2D(GL_TEXTURE_2D, 0, GL_R32F, width, height, 0, GL_RED, GL_FLOAT, 0); break;
            case 2: glTexImage2D(GL_TEXTURE_2D, 0, GL_RG32F, width, height, 0, GL_RG, GL_FLOAT, 0); break;
            case 3: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB32F, width, height, 0, GL_RGB, GL_FLOAT, 0); break;
            case 4: glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, width, height, 0, GL_RGBA, GL_FLOAT, 0); break;
            default: pezFatal("Illegal slab format.");
        }

        pezCheck(GL_NO_ERROR == glGetError(), "Unable to create FBO texture");

        // glTexImage2DMultisample
        // GL_TEXTURE_2D_MULTISAMPLE
        // glRenderbufferStorageMultisample

        GLuint colorbuffer;
        glGenRenderbuffers(1, &colorbuffer);
        glBindRenderbuffer(GL_RENDERBUFFER, colorbuffer);
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + attachment, GL_TEXTURE_2D, textureHandle, 0);
        pezCheck(GL_NO_ERROR == glGetError(), "Unable to attach color buffer");
    }
    
    // Create a depth texture:
    glGenTextures(1, &surface.DepthTexture);
    glBindTexture(GL_TEXTURE_2D, surface.DepthTexture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT16, width, height, 0, GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, 0);
    pezCheck(GL_NO_ERROR == glGetError(), "Unable to create depth texture");
    
    // Create a FBO and attach the depth texture:
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, surface.DepthTexture, 0);
    pezCheck(GL_NO_ERROR == glGetError(), "Unable to attach depth texture");

    pezCheck(GL_FRAMEBUFFER_COMPLETE == glCheckFramebufferStatus(GL_FRAMEBUFFER), "Unable to create FBO.");

    glClearColor(0, 0, 0, 0);
    glClear(GL_COLOR_BUFFER_BIT);
    glBindFramebuffer(GL_FRAMEBUFFER, 0);

    return surface;
}
Exemplo n.º 15
0
void DisplayScene()
{
	// kolor tła - zawartość bufora koloru
	glClearColor(1.0, 1.0, 1.0, 1.0);

	// czyszczenie bufora koloru i bufora głębokości
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	// wybór macierzy modelowania
	glMatrixMode(GL_MODELVIEW);

	// macierz modelowania = macierz jednostkowa
	glLoadIdentity();

	// przesunięcie układu współrzędnych obiektów do środka bryły odcinania
	glTranslatef(0.0, 0.0, -(near + far) / 2);

	// obroty obiektu
	glRotatef(rotatex, 1.0, 0.0, 0.0);
	glRotatef(rotatez, 0.0, 0.0, 1.0);

	// skalowanie obiektu - klawisze "+" i "-"
	glScalef(scale, scale, scale);

	// włączenie testu bufora głębokości
	glEnable(GL_DEPTH_TEST);

	// włączenie teksturowania dwuwymiarowego
	glEnable(GL_TEXTURE_2D);

	// filtr powiększający
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	// filtr pomniejszający
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);

	// dowiązanie wybranej tekstury
	glBindTexture(GL_TEXTURE_2D, texture);

	// ustawienie parametów środowiska tekstur
	glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

	// utworzenie kwadryki
	GLUquadricObj *quadobj = gluNewQuadric();

	// styl (wygląd) generowanej kwadryki
	gluQuadricDrawStyle(quadobj, GLU_FILL);

	// sposób generacji wektorów normalnych
	gluQuadricNormals(quadobj, GLU_SMOOTH);

	// nałożenie tekstury na kwadrykę
	gluQuadricTexture(quadobj, GL_TRUE);

	// narysowanie kuli
	gluSphere(quadobj, 1.0, 30, 30);

	// usunięcie kwadryki
	gluDeleteQuadric(quadobj);

	// wyłączenie teksturowania dwuwymiarowego
	glDisable(GL_TEXTURE_2D);

	// informacje o wybranych parametrach bieżącej tekstury
	char string[200];
	GLfloat var;
	glColor3fv(Black);

	// wartość priorytetu tekstury
	glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_PRIORITY, &var);
	sprintf_s(string, "GL_TEXTURE_PRIORITY = %f", var);
	DrawString(2, 2, string);

	// czy tekstura jest rezydentna
	glGetTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_RESIDENT, &var);
	if (var == GL_FALSE)
		strcpy_s(string, "GL_TEXTURE_RESIDENT = GL_FALSE");
	else
		strcpy_s(string, "GL_TEXTURE_RESIDENT = GL_TRUE");
	DrawString(2, 16, string);

	// szerokość tekstury (poziom 0)
	glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_WIDTH, &var);
	sprintf_s(string, "GL_TEXTURE_WIDTH = %f", var);
	DrawString(2, 30, string);

	// wysokość tekstury (poziom 0)
	glGetTexLevelParameterfv(GL_TEXTURE_2D, 0, GL_TEXTURE_HEIGHT, &var);
	sprintf_s(string, "GL_TEXTURE_HEIGHT = %f", var);
	DrawString(2, 46, string);

	// skierowanie poleceñ do wykonania
	glFlush();

	// zamiana buforów koloru
	glutSwapBuffers();
}
Exemplo n.º 16
0
void XCompcapMain::updateSettings(obs_data_t settings)
{
	PLock lock(&p->lock);
	XErrorLock xlock;
	ObsGsContextHolder obsctx;

	blog(LOG_DEBUG, "Settings updating");

	Window prevWin = p->win;

	xcc_cleanup(p);

	if (settings) {
		const char *windowName = obs_data_getstring(settings,
				"capture_window");

		p->win = getWindowFromString(windowName);

		p->cut_top = obs_data_getint(settings, "cut_top");
		p->cut_left = obs_data_getint(settings, "cut_left");
		p->cut_right = obs_data_getint(settings, "cut_right");
		p->cut_bot = obs_data_getint(settings, "cut_bot");
		p->lockX = obs_data_getbool(settings, "lock_x");
		p->swapRedBlue = obs_data_getbool(settings, "swap_redblue");
	} else {
		p->win = prevWin;
	}

	xlock.resetError();

	XCompositeRedirectWindow(xdisp, p->win, CompositeRedirectAutomatic);

	if (xlock.gotError()) {
		blog(LOG_ERROR, "XCompositeRedirectWindow failed: %s",
				xlock.getErrorText().c_str());
		return;
	}

	XSelectInput(xdisp, p->win, StructureNotifyMask);
	XSync(xdisp, 0);

	XWindowAttributes attr;
	if (!XGetWindowAttributes(xdisp, p->win, &attr)) {
		p->win = 0;
		p->width = 0;
		p->height = 0;
		return;
	}

	gs_color_format cf = GS_RGBA;

	p->width = attr.width;
	p->height = attr.height;

	if (p->cut_top + p->cut_bot < (int)p->height) {
		p->cur_cut_top = p->cut_top;
		p->cur_cut_bot = p->cut_bot;
	} else {
		p->cur_cut_top = 0;
		p->cur_cut_bot = 0;
	}

	if (p->cut_left + p->cut_right < (int)p->width) {
		p->cur_cut_left = p->cut_left;
		p->cur_cut_right = p->cut_right;
	} else {
		p->cur_cut_left = 0;
		p->cur_cut_right = 0;
	}

	if (p->tex)
		texture_destroy(p->tex);

	uint8_t *texData = new uint8_t[width() * height() * 4];

	for (unsigned int i = 0; i < width() * height() * 4; i += 4) {
		texData[i + 0] = p->swapRedBlue ? 0 : 0xFF;
		texData[i + 1] = 0;
		texData[i + 2] = p->swapRedBlue ? 0xFF : 0;
		texData[i + 3] = 0xFF;
	}

	const uint8_t* texDataArr[] = { texData, 0 };

	p->tex = gs_create_texture(width(), height(), cf, 1,
			texDataArr, 0);

	delete[] texData;

	if (p->swapRedBlue) {
		GLuint tex = *(GLuint*)texture_getobj(p->tex);
		glBindTexture(GL_TEXTURE_2D, tex);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_B, GL_RED);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_R, GL_BLUE);
		glBindTexture(GL_TEXTURE_2D, 0);
	}

	const int attrs[] =
	{
		GLX_BIND_TO_TEXTURE_RGBA_EXT, GL_TRUE,
		GLX_DRAWABLE_TYPE, GLX_PIXMAP_BIT,
		GLX_BIND_TO_TEXTURE_TARGETS_EXT, GLX_TEXTURE_2D_BIT_EXT,
		GLX_DOUBLEBUFFER, GL_FALSE,
		None
	};

	int nelem = 0;
	GLXFBConfig* configs = glXChooseFBConfig(xdisp,
			XCompcap::getRootWindowScreen(attr.root),
			attrs, &nelem);

	if (nelem <= 0) {
		blog(LOG_ERROR, "no matching fb config found");
		p->win = 0;
		p->height = 0;
		p->width = 0;
		return;
	}

	glXGetFBConfigAttrib(xdisp, configs[0], GLX_Y_INVERTED_EXT, &nelem);
	p->inverted = nelem != 0;

	xlock.resetError();

	p->pixmap = XCompositeNameWindowPixmap(xdisp, p->win);

	if (xlock.gotError()) {
		blog(LOG_ERROR, "XCompositeNameWindowPixmap failed: %s",
				xlock.getErrorText().c_str());
		p->pixmap = 0;
		XFree(configs);
		return;
	}

	const int attribs[] =
	{
		GLX_TEXTURE_TARGET_EXT, GLX_TEXTURE_2D_EXT,
		GLX_TEXTURE_FORMAT_EXT, GLX_TEXTURE_FORMAT_RGBA_EXT,
		None
	};

	p->glxpixmap = glXCreatePixmap(xdisp, configs[0], p->pixmap, attribs);

	if (xlock.gotError()) {
		blog(LOG_ERROR, "glXCreatePixmap failed: %s",
				xlock.getErrorText().c_str());
		XFreePixmap(xdisp, p->pixmap);
		XFree(configs);
		p->pixmap = 0;
		p->glxpixmap = 0;
		return;
	}

	XFree(configs);

	p->gltex = gs_create_texture(p->width, p->height, cf, 1, 0,
			GS_GL_DUMMYTEX);

	GLuint gltex = *(GLuint*)texture_getobj(p->gltex);
	glBindTexture(GL_TEXTURE_2D, gltex);
	glXBindTexImageEXT(xdisp, p->glxpixmap, GLX_FRONT_LEFT_EXT, NULL);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
Exemplo n.º 17
0
void gl_load_texture_data(GLuint id,
      enum gfx_wrap_type wrap_type,
      enum texture_filter_type filter_type,
      unsigned alignment,
      unsigned width, unsigned height,
      const void *frame, unsigned base_size)
{
   GLint mag_filter, min_filter;
   bool want_mipmap = false;
   bool rgb32 = (base_size == (sizeof(uint32_t)));
   driver_t *driver = driver_get_ptr();
   GLenum wrap = gl_wrap_type_to_enum(wrap_type);

   glBindTexture(GL_TEXTURE_2D, id);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrap);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrap);
    
#if defined(HAVE_OPENGLES2) || defined(HAVE_PSGL) || defined(OSX_PPC)
   if (filter_type == TEXTURE_FILTER_MIPMAP_LINEAR)
       filter_type = TEXTURE_FILTER_LINEAR;
   if (filter_type == TEXTURE_FILTER_MIPMAP_NEAREST)
       filter_type = TEXTURE_FILTER_NEAREST;
#endif

   switch (filter_type)
   {
      case TEXTURE_FILTER_MIPMAP_LINEAR:
         min_filter = GL_LINEAR_MIPMAP_NEAREST;
         mag_filter = GL_LINEAR;
         want_mipmap = true;
         break;
      case TEXTURE_FILTER_MIPMAP_NEAREST:
         min_filter = GL_NEAREST_MIPMAP_NEAREST;
         mag_filter = GL_NEAREST;
         want_mipmap = true;
         break;
      case TEXTURE_FILTER_NEAREST:
         min_filter = GL_NEAREST;
         mag_filter = GL_NEAREST;
         break;
      case TEXTURE_FILTER_LINEAR:
      default:
         min_filter = GL_LINEAR;
         mag_filter = GL_LINEAR;
         break;
   }

   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, mag_filter);
   glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, min_filter);

   glPixelStorei(GL_UNPACK_ALIGNMENT, alignment);
   glTexImage2D(GL_TEXTURE_2D,
         0,
         (driver->gfx_use_rgba || !rgb32) ? GL_RGBA : RARCH_GL_INTERNAL_FORMAT32,
         width, height, 0,
         (driver->gfx_use_rgba || !rgb32) ? GL_RGBA : RARCH_GL_TEXTURE_TYPE32,
         (rgb32) ? RARCH_GL_FORMAT32 : GL_UNSIGNED_SHORT_4_4_4_4, frame);

   if (want_mipmap)
      glGenerateMipmap(GL_TEXTURE_2D);
}
Exemplo n.º 18
0
Texture::Texture(const std::string &filename, const GLint filter_param)
{

	//haidi haida. oikea kurahaara ja jakorasia.

	// LODEPNG STUFF!

	std::vector<unsigned char> raw_pixels;
	unsigned width, height;
	unsigned error = lodepng::decode(raw_pixels, width, height, filename);
	
	if(error) { printf("lodepng decoder error: %s\n", lodepng_error_text(error)); _otherbad = true; return; }
	
	name = filename;

	/*std::ifstream infile(filename, std::ios::in | std::ios::binary);

	if (!infile.is_open()) {
		_nosuch = true;
		return;
	}

	char *buffer = NULL;

	decompress_qlz(infile, &buffer);
	infile.close();
	
	_badheader = _nosuch = _otherbad = false;
	
	if (!((*buffer) == 'B' && (*(buffer+1) == 'M')))
	{
		delete [] buffer;
		_badheader = true;
		return;
	}
	*/
	
	_badheader = _nosuch = _otherbad = false;
	// start reading header file.

	// the windows BMP file has a 54-byte header

	/*char* iter = buffer + 2;	// the first two bytes are 'B' and 'M', and this we already have checked.

	BMPHEADER header;

	memcpy(&header, iter, sizeof(header));
	
	// validate image OpenGL-wise

	if (header.width == header.height) 
	{
		if ((header.width & (header.width - 1)) == 0)	// if power of two
		{ */
	if ((width & (width - 1)) == 0 && width == height) {
			// image is valid, carry on
			hasAlpha = true;	// lodepng loads as RGBARGBA...

			// read actual image data to buffer.
		//	GLbyte *const imagedata = (GLbyte*)(buffer + 54);
			glEnable(GL_TEXTURE_2D);
			glGenTextures(1, &textureId);
			glBindTexture( GL_TEXTURE_2D, textureId);
			glTexStorage2D(GL_TEXTURE_2D, 4, GL_RGBA8, width, height);
			glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, &raw_pixels[0]);
			glGenerateMipmap(GL_TEXTURE_2D);	// requires glew
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter_param);
			glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);

			//glTexImage2D( GL_TEXTURE_2D, 0, 3, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, imagedata);
			//glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR );
			
			//glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR );


			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
			//glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

		}
	
		else {	// if not power of two
			_otherbad = true;
		}
}
Exemplo n.º 19
0
bool setupDeferred(int w, int h) {
  std::cout << "setupDeferred " << w << " " << h << std::endl;
  glBindFramebuffer(GL_DRAW_FRAMEBUFFER, deferredFbo);

  //color
  glBindTexture(GL_TEXTURE_2D, deferredColorTex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,w,h,0,GL_RGBA,GL_FLOAT,0);
  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_COLOR_ATTACHMENT0,
                         GL_TEXTURE_2D,deferredColorTex,0);

  //normal
  GLenum normalInnerFormat;
  GLenum normalType;

  normalInnerFormat=GL_RGBA32F;
  normalType=GL_FLOAT;

  // normalInnerFormat=GL_RGBA16F;
  // normalType=GL_HALF_FLOAT;

  glBindTexture(GL_TEXTURE_2D, deferredNormalTex);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexImage2D(GL_TEXTURE_2D,0,normalInnerFormat,w,h,0,GL_RGBA,normalType,0);

  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_COLOR_ATTACHMENT1,
                         GL_TEXTURE_2D,deferredNormalTex,0);

  //depth
  glBindTexture(GL_TEXTURE_2D, deferredDepthTex);
  glTexImage2D(GL_TEXTURE_2D,0,GL_DEPTH_COMPONENT32F,w,h,0,GL_DEPTH_COMPONENT,GL_FLOAT,0);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
  glTexParameteri(GL_TEXTURE_2D, GL_DEPTH_TEXTURE_MODE, GL_INTENSITY);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_MODE, GL_COMPARE_R_TO_TEXTURE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_COMPARE_FUNC, GL_LEQUAL);

  glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER,GL_DEPTH_ATTACHMENT,
                         GL_TEXTURE_2D,deferredDepthTex,0);

  //
  GLenum drawBufs[]={GL_COLOR_ATTACHMENT0,GL_COLOR_ATTACHMENT1};
  glDrawBuffers(2,drawBufs);

  //check fbo status
  GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER);

  if(status == GL_FRAMEBUFFER_COMPLETE) {
    //restore default FBO
    glBindFramebuffer(GL_FRAMEBUFFER, 0);
    return true;
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) {
    std::cout << "fbo error: incomplete attachment\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) {
    std::cout << "fbo error: incomplete missing attachment\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER) {
    std::cout << "fbo error: incomplete draw buffer\n";
  } else if(status==GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER) {
    std::cout << "fbo error: incomplete read buffer\n";
  } else if(status==GL_FRAMEBUFFER_UNSUPPORTED) {
    std::cout << "fbo error: unsupported\n";
  }

  return false;
}
Exemplo n.º 20
0
void RoutePoint::EnableDragHandle(bool bEnable)
{
    m_bDrawDragHandle = bEnable;
    if(bEnable){
        if(!m_dragIcon.IsOk()){    
            // Get the icon
            // What size?
            int bm_size = g_Platform->GetDisplayDPmm() * 9;     //9 mm nominal
        
            // What icon?
            wxString UserIconPath = g_Platform->GetSharedDataDir() + _T("uidata") + wxFileName::GetPathSeparator();
            
            wxImage iconSVG = LoadSVGIcon( UserIconPath  + _T("DragHandle.svg"), bm_size, bm_size );
            if(iconSVG.IsOk())
                m_dragIcon = wxBitmap(iconSVG);
            else
                m_dragIcon = *m_pbmIcon;                // Drag handle icon not found
                
            // build a texture
#ifdef ocpnUSE_GL
        /* make rgba texture */
            if(m_dragIconTexture == 0){
                glGenTextures(1, &m_dragIconTexture);
                glBindTexture(GL_TEXTURE_2D, m_dragIconTexture);
                    
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );
                glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
            
            
                wxImage image = iconSVG;
                int w = image.GetWidth(), h = image.GetHeight();
            
                m_dragIconTextureWidth = NextPow2(w);
                m_dragIconTextureHeight = NextPow2(h);
            
                unsigned char *d = image.GetData();
                unsigned char *a = image.GetAlpha();
                
                unsigned char mr, mg, mb;
                image.GetOrFindMaskColour( &mr, &mg, &mb );
        
                unsigned char *e = new unsigned char[4 * w * h];
                if(d && e){
                    for( int y = 0; y < h; y++ )
                        for( int x = 0; x < w; x++ ) {
                            unsigned char r, g, b;
                            int off = ( y * image.GetWidth() + x );
                            r = d[off * 3 + 0];
                            g = d[off * 3 + 1];
                            b = d[off * 3 + 2];
                            e[off * 4 + 0] = r;
                            e[off * 4 + 1] = g;
                            e[off * 4 + 2] = b;
                        
                            e[off * 4 + 3] =  a ? a[off] : ( ( r == mr ) && ( g == mg ) && ( b == mb ) ? 0 : 255 );
                        }
                }
        
                glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, m_dragIconTextureWidth, m_dragIconTextureHeight,
                        0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
                glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h,
                            GL_RGBA, GL_UNSIGNED_BYTE, e);

                delete [] e;
            }
#endif

            // set the drawing metrics
            if(iconSVG.IsOk()){
                m_drag_line_length_man = bm_size;
                m_drag_icon_offset = bm_size;
            }
            else{
                m_drag_line_length_man = 64;
                m_drag_icon_offset = 64;
            }
        }
    }
}
Exemplo n.º 21
0
/**
 *	this is identical to the old TextureRender::load()
 *
 *	component parameter requirements:
 *		"filename" : std::string => path to the image/texture file
 *
 *	TODO: add crop support
 */
bool RenderService::loadTextureInfo(Renderable *c)
{
	printf("loading new sprite\n");
	SDL_Surface *surf;
	if ((surf = IMG_Load(c->filename.c_str())))
	{
	
		//if the dimensions are not specified use the texture dimensions
		if (c->w == -1 && c->h == -1)
		{
			c->w = surf->w;
			c->h = surf->h;
		}
		
		if ((surf->w & (surf->w - 1)) != 0)
		{
			printf("Error loading %s: width is not a power of 2 (%ix%i)\n", c->filename.c_str(), surf->w, surf->h);
			return false;
		}
		if ((surf->h & (surf->h - 1)) != 0)
		{
			printf("Error loading %s: height is not a power of 2 (%ix%i)\n", c->filename.c_str(), surf->w, surf->h);
			return false;
		}
		
		GLint nColors = surf->format->BytesPerPixel;
		GLenum format;
		if (nColors == 4)
		{
			if (surf->format->Rmask == 0x000000ff)
				format = GL_RGBA;
			else
				format = GL_BGRA;
		}
		else if (nColors == 3)
		{
			if (surf->format->Rmask == 0x000000ff)
				format = GL_RGB;
			else
				format = GL_BGR;
		}
		else
		{
			printf("Error loading %s: image is not truecolor (%ibpp)\n", c->filename.c_str(), nColors);
		}
		
		GLuint t;
		glEnable(GL_TEXTURE_2D);
		glGenTextures(1, &t);
		glBindTexture(GL_TEXTURE_2D, t);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexImage2D(GL_TEXTURE_2D, 0, nColors, surf->w, surf->h, 0, 
								 format, GL_UNSIGNED_BYTE, surf->pixels);
		glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
		glDisable(GL_TEXTURE_2D);
		
		c->tex = t;
		if (surf)
			SDL_FreeSurface(surf);
		
		return true;
	}
	else
	{
		printf("Error loading %s: invalid file\n", c->filename.c_str());
		printf("SDL: %s\n", SDL_GetError());
		return false;
	}
}
Exemplo n.º 22
0
void RoutePoint::DrawGL( ViewPort &vp, ChartCanvas *canvas, bool use_cached_screen_coords )
{
//     if( !m_bIsVisible ) 
//         return;
//     if( !m_bIsActive)  //  An active route point must always be visible
//         if( !IsScaVisible( canvas) )          
//             return;  ;
    if ( !IsVisibleSelectable(canvas) ) return;
    
    //    Optimization, especially apparent on tracks in normal cases
    if( m_IconName == _T("empty") && !m_bShowName && !m_bPtIsSelected ) return;

    if(m_wpBBox.GetValid() &&
       vp.view_scale_ppm == m_wpBBox_view_scale_ppm &&
       vp.rotation == m_wpBBox_rotation) {
        /* see if this waypoint can intersect with bounding box */
        LLBBox vpBBox = vp.GetBBox();
        if( vpBBox.IntersectOut( m_wpBBox ) ){
            
            // Are Range Rings enabled?
            if(m_bShowWaypointRangeRings && (m_iWaypointRangeRingsNumber > 0)){
                double factor = 1.00;
                if( m_iWaypointRangeRingsStepUnits == 1 )          // convert kilometers to NMi
                    factor = 1 / 1.852;
            
                double radius = factor * m_iWaypointRangeRingsNumber * m_fWaypointRangeRingsStep  / 60.;

                LLBBox radar_box = m_wpBBox;
                radar_box.EnLarge(radius * 2 );
                if( vpBBox.IntersectOut( radar_box ) ){
                    return;
                }
            }
            else
                return;
        }
    }

    wxPoint r;
    wxRect hilitebox;
    unsigned char transparency = 150;
    
    if(use_cached_screen_coords && m_pos_on_screen)
        r.x = m_screen_pos.m_x, r.y = m_screen_pos.m_y;
    else
        canvas->GetCanvasPointPix( m_lat, m_lon, &r );

    if(r.x == INVALID_COORD)
        return;

//    Substitute icon?
    wxBitmap *pbm;
    if( ( m_bIsActive ) && ( m_IconName != _T("mob") ) )
        pbm = pWayPointMan->GetIconBitmap(  _T ( "activepoint" ) );
    else
        pbm = m_pbmIcon;

    //  If icon is corrupt, there is really nothing else to do...
    if(!pbm->IsOk())
        return;
    
    int sx2 = pbm->GetWidth() / 2;
    int sy2 = pbm->GetHeight() / 2;

//    Calculate the mark drawing extents
    wxRect r1( r.x - sx2, r.y - sy2, sx2 * 2, sy2 * 2 );           // the bitmap extents

    wxRect r3 = r1;
    if( m_bShowName ) {
        if( !m_pMarkFont ) {
            m_pMarkFont = FontMgr::Get().GetFont( _( "Marks" ) );
            m_FontColor = FontMgr::Get().GetFontColor( _( "Marks" ) );
            CalculateNameExtents();
        }

        if( m_pMarkFont ) {
            wxRect r2( r.x + m_NameLocationOffsetX, r.y + m_NameLocationOffsetY,
                       m_NameExtents.x, m_NameExtents.y );
            r3.Union( r2 );
        }
    }

    hilitebox = r3;
    hilitebox.x -= r.x;
    hilitebox.y -= r.y;
    
    if(!m_bPreScaled){
        hilitebox.x *= g_ChartScaleFactorExp;
        hilitebox.y *= g_ChartScaleFactorExp;
        hilitebox.width  *= g_ChartScaleFactorExp;
        hilitebox.height *= g_ChartScaleFactorExp;
    }
    
    float radius;
    if( g_btouch ){
        hilitebox.Inflate( 20 );
        radius = 20.0f;
    }
    else{
        hilitebox.Inflate( 4 );
        radius = 4.0f;
    }
    
    /* update bounding box */
    if(!m_wpBBox.GetValid() || vp.view_scale_ppm != m_wpBBox_view_scale_ppm || vp.rotation != m_wpBBox_rotation) {
        double lat1, lon1, lat2, lon2;
        canvas->GetCanvasPixPoint(r.x+hilitebox.x, r.y+hilitebox.y+hilitebox.height, lat1, lon1);
        canvas->GetCanvasPixPoint(r.x+hilitebox.x+hilitebox.width, r.y+hilitebox.y, lat2, lon2);

        if(lon1 > lon2)
            m_wpBBox.Set(lat1, lon1, lat2, lon2+360);
        else
            m_wpBBox.Set(lat1, lon1, lat2, lon2);

        m_wpBBox_view_scale_ppm = vp.view_scale_ppm;
        m_wpBBox_rotation = vp.rotation;
    }

//    if(region.Contains(r3) == wxOutRegion)
//        return;
    

    ocpnDC dc;

    //  Highlite any selected point
    if( m_bPtIsSelected ) {
        wxColour hi_colour;
        if( m_bBlink ){
            wxPen *pen = g_pRouteMan->GetActiveRoutePointPen();
            hi_colour = pen->GetColour();
        }
        else{
            hi_colour = GetGlobalColor( _T ( "YELO1" ) );
        }
        
        AlphaBlending( dc, r.x + hilitebox.x, r.y + hilitebox.y, hilitebox.width, hilitebox.height, radius,
                       hi_colour, transparency );
    }
    
    bool bDrawHL = false;

    if( m_bBlink && ( gFrame->nBlinkerTick & 1 ) ) bDrawHL = true;

    if( ( !bDrawHL ) && ( NULL != m_pbmIcon ) ) {
        int glw, glh;
        unsigned int IconTexture = pWayPointMan->GetIconTexture( pbm, glw, glh );
        
        glBindTexture(GL_TEXTURE_2D, IconTexture);
        
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        
        glColor3f(1, 1, 1);
        
        int x = r1.x, y = r1.y, w = r1.width, h = r1.height;
        
        float scale = 1.0;
        if(!m_bPreScaled){
            scale =  g_ChartScaleFactorExp;
        }
            
        float ws = r1.width * scale;
        float hs = r1.height * scale;
        float xs = r.x - ws/2.;
        float ys = r.y - hs/2.;
        float u = (float)w/glw, v = (float)h/glh;
        
        glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex2f(xs, ys);
        glTexCoord2f(u, 0); glVertex2f(xs+ws, ys);
        glTexCoord2f(u, v); glVertex2f(xs+ws, ys+hs);
        glTexCoord2f(0, v); glVertex2f(xs, ys+hs);
        glEnd();
        
//         glBegin(GL_QUADS);
//         glTexCoord2f(0, 0); glVertex2f(x, y);
//         glTexCoord2f(u, 0); glVertex2f(x+w, y);
//         glTexCoord2f(u, v); glVertex2f(x+w, y+h);
//         glTexCoord2f(0, v); glVertex2f(x, y+h);
//         glEnd();

        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);
    }

    if( m_bShowName && m_pMarkFont ) {
        int w = m_NameExtents.x, h = m_NameExtents.y;
        if(!m_iTextTexture && w && h) {
            wxBitmap tbm(w, h); /* render text on dc */
            wxMemoryDC dc;
            dc.SelectObject( tbm );               
            dc.SetBackground( wxBrush( *wxBLACK ) );
            dc.Clear();
            dc.SetFont( *m_pMarkFont );
            dc.SetTextForeground( *wxWHITE );
            dc.DrawText( m_MarkName, 0, 0);
            dc.SelectObject( wxNullBitmap );
            
            /* make alpha texture for text */
            wxImage image = tbm.ConvertToImage();
            unsigned char *d = image.GetData();
            unsigned char *e = new unsigned char[w * h];
            if(d && e){
                for( int p = 0; p < w*h; p++)
                    e[p] = d[3*p + 0];
            }
            
            /* create texture for rendered text */
            glGenTextures(1, &m_iTextTexture);
            glBindTexture(GL_TEXTURE_2D, m_iTextTexture);
            
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST );
            glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST );

            m_iTextTextureWidth = NextPow2(w);
            m_iTextTextureHeight = NextPow2(h);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, m_iTextTextureWidth, m_iTextTextureHeight,
                         0, GL_ALPHA, GL_UNSIGNED_BYTE, NULL);
            glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, w, h,
                            GL_ALPHA, GL_UNSIGNED_BYTE, e);
            delete [] e;
        }

        if(m_iTextTexture) {
            /* draw texture with text */
            glBindTexture(GL_TEXTURE_2D, m_iTextTexture);
            
            glEnable(GL_TEXTURE_2D);
            glEnable(GL_BLEND);
        
            glColor3ub(m_FontColor.Red(), m_FontColor.Green(), m_FontColor.Blue());
            
            int x = r.x + m_NameLocationOffsetX, y = r.y + m_NameLocationOffsetY;
            float u = (float)w/m_iTextTextureWidth, v = (float)h/m_iTextTextureHeight;
            glBegin(GL_QUADS);
            glTexCoord2f(0, 0); glVertex2f(x, y);
            glTexCoord2f(u, 0); glVertex2f(x+w, y);
            glTexCoord2f(u, v); glVertex2f(x+w, y+h);
            glTexCoord2f(0, v); glVertex2f(x, y+h);
            glEnd();

            glDisable(GL_BLEND);
            glDisable(GL_TEXTURE_2D);
        }
    }
    
    // Draw waypoint radar rings if activated
    if( m_iWaypointRangeRingsNumber && m_bShowWaypointRangeRings ) {
        double factor = 1.00;
        if( m_iWaypointRangeRingsStepUnits == 1 )          // nautical miles
            factor = 1 / 1.852;
        
        factor *= m_fWaypointRangeRingsStep;
        
        double tlat, tlon;
        wxPoint r1;
        ll_gc_ll( m_lat, m_lon, 0, factor, &tlat, &tlon );
        canvas->GetCanvasPointPix( tlat, tlon, &r1 );
        
        double lpp = sqrt( pow( (double) (r.x - r1.x), 2) +
        pow( (double) (r.y - r1.y), 2 ) );
        int pix_radius = (int) lpp;

        extern wxColor GetDimColor(wxColor c);
        wxColor ring_dim_color = GetDimColor(m_wxcWaypointRangeRingsColour);
        
        double platform_pen_width = wxRound(wxMax(1.0, g_Platform->GetDisplayDPmm() / 2));             // 0.5 mm nominal, but not less than 1 pixel
        wxPen ppPen1( ring_dim_color, platform_pen_width );
        wxBrush saveBrush = dc.GetBrush();
        wxPen savePen = dc.GetPen();
        dc.SetPen( ppPen1 );
        dc.SetBrush( wxBrush( ring_dim_color, wxBRUSHSTYLE_TRANSPARENT ) );
        
        for( int i = 1; i <= m_iWaypointRangeRingsNumber; i++ )
            dc.StrokeCircle( r.x, r.y, i * pix_radius );
        dc.SetPen( savePen );
        dc.SetBrush( saveBrush );
    }
    
    // Render Drag handle if enabled
    if(m_bDrawDragHandle){
        
        //  A line, southeast, scaled to the size of the icon
        double platform_pen_width = wxRound(wxMax(1.0, g_Platform->GetDisplayDPmm() / 2));             // 0.5 mm nominal, but not less than 1 pixel
        
        wxColor dh_color = wxColor(0,0,0);
        wxPen ppPen1( dh_color, 3 * platform_pen_width );
        dc.SetPen( ppPen1 );
        dc.DrawLine(r.x + hilitebox.width/4, r.y + hilitebox.height/4, r.x + m_drag_line_length_man, r.y + m_drag_line_length_man);
 
        dh_color = GetGlobalColor( _T ( "YELO1" ) );
        wxPen ppPen2( dh_color, platform_pen_width );
        dc.SetPen( ppPen2 );
        dc.DrawLine(r.x + hilitebox.width/4, r.y + hilitebox.height/4, r.x + m_drag_line_length_man, r.y + m_drag_line_length_man);
        
        // The drag handle
        glBindTexture(GL_TEXTURE_2D, m_dragIconTexture);
        
        glEnable(GL_TEXTURE_2D);
        glEnable(GL_BLEND);
        glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
        
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        
        glColor3f(1, 1, 1);
        
        int x = r.x + m_drag_icon_offset, y = r.y + m_drag_icon_offset, w = m_dragIcon.GetWidth(), h = m_dragIcon.GetHeight();
        
        float scale =  1.0;
            
        float ws = w * scale;
        float hs = h * scale;
        float xs = x - ws/2.;
        float ys = y - hs/2.;
        float u = (float)w/m_dragIconTextureWidth, v = (float)h/m_dragIconTextureWidth;
        
        glBegin(GL_QUADS);
        glTexCoord2f(0, 0); glVertex2f(xs, ys);
        glTexCoord2f(u, 0); glVertex2f(xs+ws, ys);
        glTexCoord2f(u, v); glVertex2f(xs+ws, ys+hs);
        glTexCoord2f(0, v); glVertex2f(xs, ys+hs);
        glEnd();
        
        glDisable(GL_BLEND);
        glDisable(GL_TEXTURE_2D);

    }
 
 
    if( m_bBlink ) g_blink_rect = CurrentRect_in_DC;               // also save for global blinker
    
    //    This will be useful for fast icon redraws
    CurrentRect_in_DC.x = r.x + hilitebox.x;
    CurrentRect_in_DC.y = r.y + hilitebox.y;
    CurrentRect_in_DC.width = hilitebox.width;
    CurrentRect_in_DC.height = hilitebox.height;

    if( m_bBlink ) g_blink_rect = CurrentRect_in_DC;               // also save for global blinker
}
Exemplo n.º 23
0
void	KeyHandler(unsigned char key, int x, int y)
{
	// Set the speed level of the viewer.
	if (key >= '0' && key <= '9') {
		Speed = 1 << (key - '0');
	}

	// Toggle wireframe on 'w'.
	static bool	Wireframe = false;
	if (key == 'w') {
		Wireframe = !Wireframe;
		if (Wireframe) {
			glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
		} else {
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
		}
	}

	// Toggle backface culling on 'c'.
	static bool	BackfaceCulling = false;
	if (key == 'c') {
		BackfaceCulling = !BackfaceCulling;
		if (BackfaceCulling) {
			glCullFace(GL_BACK);
			glEnable(GL_CULL_FACE);
		} else {
			glDisable(GL_CULL_FACE);
		}
	}
	
	// Toggle texturing on 't' input.
	static unsigned int	TextureName = 0;
	if (key == 't') {
		Textured = !Textured;

		if (Textured) {
			if (TextureName == 0) {
				// Load and create texture.
				glGenTextures(1, &TextureName);
				glBindTexture(GL_TEXTURE_2D, TextureName);

				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
				glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
				
				char*	data = new char[1024 * 1024 * 3];
				FILE*	fp = fopen("demdata/gctexcolored.raw", "rb");
				fread(data, 1, 1024 * 1024 * 3, fp);
				fclose(fp);
				
				glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 1024, 1024, 0, GL_RGB, GL_UNSIGNED_BYTE, data);
				gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, 1024, 1024, GL_RGB, GL_UNSIGNED_BYTE, data);

				delete [] data;
				
				glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
			}

			glBindTexture(GL_TEXTURE_2D, TextureName);
			glEnable(GL_TEXTURE_2D);

			glColor3f(1, 1, 1);
		} else {
			glDisable(GL_TEXTURE_2D);
		}
	}

	// Toggle PinToGround mode on 'p'.
	if (key == 'p') {
		PinToGround = !PinToGround;

		if (PinToGround) {
			ViewerHeight = ViewerLoc.Y() - root->GetHeight(RootCornerData, ViewerLoc.X(), ViewerLoc.Z());
		}
	}

	// Toggle MoveForward mode on 'm'.
	if (key == 'm') {
		MoveForward = !MoveForward;
	}


	// =/- keys adjust the detail threshold.
	if (key == '-') {
		Detail *= 0.9;
		if (Detail < 10) Detail = 10;
		printf("DetailThreshold = %g\n", Detail);
	}
	if (key == '=') {
		Detail *= 1.11111111;
		if (Detail > 1500) Detail = 1500;
		printf("DetailThreshold = %g\n", Detail);
	}
	

	// On 'd', hijack the app for a second while we run some
	// performance tests.  Because of limitations in GLUT, Idle()
	// only gets called up to 18 times a second, so we can't get
	// good performance numbers that way.
	if (key == 'd') {
		int	StartTicks = glutGet(GLUT_ELAPSED_TIME);
		int	ticks;
		TriangleCounter = 0;
		int	FrameCounter = 0;
		int	TrisPerFrame = 0;

		// For approximately one second, render frames as fast as we can.
		for (;;) {
			Display();
			FrameCounter++;
			if (FrameCounter == 1) TrisPerFrame = TriangleCounter;
			
			ticks = glutGet(GLUT_ELAPSED_TIME);
			if (ticks - StartTicks > 1000) break;
		}

		// Show the fps and tps results.
		float	dt = (ticks - StartTicks) / 1000.0;
		printf("Rendered %0.1f frames/sec, %d tris/frame, %d tris/sec\n", FrameCounter / dt, TrisPerFrame, int(TriangleCounter / dt));
	}
}
Exemplo n.º 24
0
void jit_gl_hap_submit_texture(t_jit_gl_hap *x)
{
	GLenum type;
	GLvoid *baseAddress = CVPixelBufferGetBaseAddress(x->buffer);
	
	glPushAttrib(GL_ENABLE_BIT | GL_TEXTURE_BIT);
	glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);
		
	// Create a new texture if our current one isn't adequate
	if (
		!x->texture ||
		(x->roundedWidth > x->backingWidth) ||
		(x->roundedHeight > x->backingHeight) ||
		(x->newInternalFormat != x->internalFormat)
	) {
		glEnable(x->target);
		
		if (x->texture != 0) {
			glDeleteTextures(1, &x->texture);
		}
		glGenTextures(1, &x->texture);
		glBindTexture(x->target, x->texture);
		x->deletetex = 1;
		
		// On NVIDIA hardware there is a massive slowdown if DXT textures aren't POT-dimensioned, so we use POT-dimensioned backing
		x->backingWidth = 1;
		while (x->backingWidth < x->roundedWidth) x->backingWidth <<= 1;
		x->backingHeight = 1;
		while (x->backingHeight < x->roundedHeight) x->backingHeight <<= 1;
		
		glTexParameteri(x->target, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(x->target, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
		glTexParameteri(x->target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(x->target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
#ifdef MAC_VERSION
		glTexParameteri(x->target, GL_TEXTURE_STORAGE_HINT_APPLE , GL_STORAGE_SHARED_APPLE);
		type = GL_UNSIGNED_INT_8_8_8_8_REV;
#else
		type = GL_UNSIGNED_BYTE;
#endif

		// We allocate the texture with no pixel data, then use CompressedTexSubImage to update the content region			
		glTexImage2D(x->target, 0, x->newInternalFormat, x->backingWidth, x->backingHeight, 0, GL_BGRA, type, NULL);
		
		x->internalFormat = x->newInternalFormat;
	}
	else {
		glBindTexture(x->target, x->texture);
	}

#ifdef MAC_VERSION
	glTextureRangeAPPLE(GL_TEXTURE_2D, x->newDataLength, baseAddress);
	glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, GL_TRUE);
#else
// not sure what this should be, so leaving as default for now
//	glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
#endif

	glCompressedTexSubImage2D(GL_TEXTURE_2D,
							  0,
							  0,
							  0,
							  x->roundedWidth,
							  x->roundedHeight,
							  x->newInternalFormat,
							  x->newDataLength,
							  baseAddress);

	glPopClientAttrib();
	glPopAttrib();

}
Exemplo n.º 25
0
PsychError SCREENTestTexture(void) 
{
#if PSYCH_SYSTEM == PSYCH_OSX

    PsychWindowRecordType 	*winRec;
    CGContextRef			cgContext;
    unsigned int			memoryTotalSizeBytes, memoryRowSizeBytes;
    UInt32					*textureMemory;
    int						stringLength, totalTexels, i;
    GLuint					myTexture;
    CGColorSpaceRef			cgColorSpace;
    
    			
    //all subfunctions should have these two lines.  
    PsychPushHelp(useString, synopsisString, seeAlsoString);
    if(PsychIsGiveHelp()){PsychGiveHelp();return(PsychError_none);};
    
    //Get the window structure for the onscreen window.  It holds the onscreein GL context which we will need in the
    //final step when we copy the texture from system RAM onto the screen.
    PsychErrorExit(PsychCapNumInputArgs(1));   	
    PsychErrorExit(PsychRequireNumInputArgs(1)); 	
    PsychErrorExit(PsychCapNumOutputArgs(1));  
    PsychAllocInWindowRecordArg(1, TRUE, &winRec);
    if(!PsychIsOnscreenWindow(winRec))
        PsychErrorExitMsg(PsychError_user, "Onscreen window pointer required");
        
    //allocate memory for the surface
    memoryRowSizeBytes=sizeof(UInt32) * textureSizeX;
    memoryTotalSizeBytes= memoryRowSizeBytes * textureSizeY;
    textureMemory=(UInt32 *)malloc(memoryTotalSizeBytes);
    if(!textureMemory)
            PsychErrorExitMsg(PsychError_internal, "Failed to allocate surface memory\n");
    
    if(useQuartz){
        //Create the Core Graphics bitmap graphics context.  We have to be careful to specify arguments which will allow us to store the texture as an OpenGL texture. 
        //The choice of color space needs to be checked.  
        cgColorSpace=CGColorSpaceCreateDeviceRGB();
        cgContext= CGBitmapContextCreate(textureMemory, textureSizeX, textureSizeY, cg_RGBA_32_BitsPerComponent, memoryRowSizeBytes, cgColorSpace, cg_RGBA_32_AlphaOption);
        if(!cgContext){
            free((void *)textureMemory);
            PsychErrorExitMsg(PsychError_internal, "Failed to allocate CG Bimap Context\n");
        }
            
        //	Draw some text into the bitmap context.  We need to set font, size, pen (drawing mode), color, alpha, text position.
        
        //	There are two ways to select the font in a Core Graphics Quartz context depending on the type of font.
        //	1) CGContextSetFont() for Apple Type Services (ATS) font aka "The Right Way"
        //		A) call CGFontCreateWithPlatformFont() which returns a CGFontRef
        //		B) call CGContextSetFont() to set the font to be the drawing font within a context.
        //  2) CGContextSelectFont() for MacRoman aka "How We Do It"
        //
        //  Using MacRoman seems to mean that we just change the coding, though CGContextSelectFont().  For info on using ATS fonts see:
        // 	http://developer.apple.com/documentation/Carbon/Reference/ATS/
        CGContextSelectFont(cgContext, "Helvetica", (float)24, kCGEncodingMacRoman);		//set the font and its size.
        CGContextSetTextDrawingMode(cgContext, kCGTextFill);					//set the pen to be a filled pen
        CGContextSetRGBStrokeColor(cgContext, (float)0.5, (float)0.5, (float)0.0, (float)1.0);	//set the stroke color and alpha
        CGContextSetRGBFillColor(cgContext, (float)0.5, (float)0.5, (float)0.0, (float)1.0);	//set the fill color and alpha
        stringLength=strlen(textString);
        CGContextShowTextAtPoint(cgContext, (float)textPositionX, (float)textPositionY, textString, stringLength);	//draw at specified location.
        CGContextFlush(cgContext); 	//this might not be necessary but do it just in case.
    }else{
        //fill the texture memory by poking bits in the array which will be turned into a texture.
        totalTexels=textureSizeX * textureSizeY;
        for(i=0;i<totalTexels;i++)
            textureMemory[i]=	redFill << 24 | greenFill | 16 << blueFill << 8 | alphaFill;
     }       

    //Convert the CG graphics bitmap (Quartz surface) into a CG texture.  GL thinks we are loading the texture from memory we indicate to glTexImage2D, but really
    //we are just setting the texture to share the same memory as the Quartz surface.
    PsychSetGLContext(winRec); 
    glEnable(GL_TEXTURE_RECTANGLE_EXT);
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
    glGenTextures(1, &myTexture);						//create an index "name" for our texture
    glBindTexture(GL_TEXTURE_RECTANGLE_EXT, myTexture);			//instantiate a texture of type associated with the index and set it to be the target for subsequent gl texture operators.
    glPixelStorei(GL_UNPACK_CLIENT_STORAGE_APPLE, 1);			//tell gl how to unpack from our memory when creating a surface, namely don't really unpack it but use it for texture storage.
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MIN_FILTER, GL_NEAREST);	//specify interpolation scaling rule for copying from texture.  
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_MAG_FILTER, GL_NEAREST);  //specify interpolation scaling rule from copying from texture.
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_RECTANGLE_EXT, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    glTexImage2D(GL_TEXTURE_RECTANGLE_EXT, 0, GL_RGBA,  textureSizeX, textureSizeY, 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, textureMemory);
    
    //Copy the texture to the display.  What are the s and  t indices  of the first pixel of the texture ? 0 or 1 ?
    //set the GL context to be the onscreen window
    glBegin(GL_QUADS);
        glTexCoord2d(0.0, 0.0);					glVertex2d(0.0, 0.0);
        glTexCoord2d(textureSizeX, 0.0 );			glVertex2d(textureSizeX, 0.0);
        glTexCoord2d(textureSizeX, textureSizeY);		glVertex2d(textureSizeX, textureSizeY);
        glTexCoord2d(0.0, textureSizeY);			glVertex2d(0.0, textureSizeY);
    glEnd();
    glFlush();	
    glDisable(GL_TEXTURE_RECTANGLE_EXT);

    //Close  up shop.  Unlike with normal textures is important to release the context before deallocating the memory which glTexImage2D() was given. 
    //First release the GL context, then the CG context, then free the memory.
    glDeleteTextures(1, &myTexture);	//Remove references from gl to the texture memory  & free gl's associated resources   
    if(useQuartz) CGContextRelease(cgContext);	//Remove references from Core Graphics to the texture memory & free Core Graphics' associated resources.
    free((void *)textureMemory);	//Free the memory
#endif
    return(PsychError_none);

}
Exemplo n.º 26
0
void PRFilledPolygon::draw() {
    
    if(areaTrianglePointCount <= 1)
        return;
    
#ifdef __GLES2
    
    CC_NODE_DRAW_SETUP();
    
    ccGLBindTexture2D(texture->getName());
    
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    
    ccGLBlendFunc(blendFunc.src, blendFunc.dst);
    
    ccGLEnableVertexAttribs(kCCVertexAttribFlag_Position | kCCVertexAttribFlag_TexCoords);
    
    if(sizeof(CCPoint) == sizeof(ccVertex2F)) {
        
        glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, areaTrianglePoints);
        glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, textureCoordinates);
        glDrawArrays(GL_TRIANGLES, 0, (GLsizei)areaTrianglePointCount);

    } else {
        
        ccVertex2F* newAreaTrianglePoints = new ccVertex2F[areaTrianglePointCount];
        ccVertex2F* newTextureCoordinates = new ccVertex2F[areaTrianglePointCount];
        
        if(newAreaTrianglePoints != NULL && newTextureCoordinates != NULL) {
           
            for( unsigned int i = 0; i < areaTrianglePointCount; i++) {
                newTextureCoordinates[i].x = textureCoordinates[i].x;
                newTextureCoordinates[i].y = textureCoordinates[i].y;
                
                newAreaTrianglePoints[i].x = areaTrianglePoints[i].x;
                newAreaTrianglePoints[i].y = areaTrianglePoints[i].y;
            }
            glVertexAttribPointer(kCCVertexAttrib_Position, 2, GL_FLOAT, GL_FALSE, 0, newAreaTrianglePoints);
            glVertexAttribPointer(kCCVertexAttrib_TexCoords, 2, GL_FLOAT, GL_FALSE, 0, newTextureCoordinates);
            glDrawArrays(GL_TRIANGLES, 0, (GLsizei)areaTrianglePointCount);
            
            CC_SAFE_DELETE_ARRAY(newAreaTrianglePoints);
            CC_SAFE_DELETE_ARRAY(newTextureCoordinates);
        }
    }
    
    CC_INCREMENT_GL_DRAWS(1);
    
#else
    
    CCNode::draw();
    
    glDisableClientState(GL_COLOR_ARRAY);
    
    // we have a pointer to vertex points so enable client state
    glBindTexture(GL_TEXTURE_2D, texture->getName());
    
    
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
	glVertexPointer(2, GL_FLOAT, 0, areaTrianglePoints);
	glTexCoordPointer(2, GL_FLOAT, 0, textureCoordinates);
	
    glDrawArrays(GL_TRIANGLES, 0, areaTrianglePointCount);
    
    glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
    
    //Restore texture matrix and switch back to modelview matrix
    glEnableClientState(GL_COLOR_ARRAY);
#endif
    
    
    
}
Exemplo n.º 27
0
static void
load_textures (ModeInfo *mi, Bool flip_p)
{
  matrix_configuration *mp = &mps[MI_SCREEN(mi)];
  XImage *xi;
  int x, y;
  int cw, ch;
  int orig_w, orig_h;

  /* The Matrix XPM is 512x598 -- but GL texture sizes must be powers of 2.
     So we waste some padding rows to round up.
   */
  xi = xpm_to_ximage (mi->dpy, mi->xgwa.visual, mi->xgwa.colormap,
                      matrix3_xpm);
  orig_w = xi->width;
  orig_h = xi->height;
  mp->real_char_rows = CHAR_ROWS;
  spank_image (mp, xi);

  if (xi->height != 512 && xi->height != 1024)
    {
      xi->height = (xi->height < 512 ? 512 : 1024);
      xi->data = realloc (xi->data, xi->height * xi->bytes_per_line);
      if (!xi->data)
        {
          fprintf(stderr, "%s: out of memory\n", progname);
          exit(1);
        }
    }

  if (xi->width != 512) abort();
  if (xi->height != 512 && xi->height != 1024) abort();

  /* char size in pixels */
  cw = orig_w / CHAR_COLS;
  ch = orig_h / CHAR_ROWS;

  /* char size in ratio of final (padded) texture size */
  mp->tex_char_width  = (GLfloat) cw / xi->width;
  mp->tex_char_height = (GLfloat) ch / xi->height;

  /* Flip each character's bits horizontally -- we could also just do this
     by reversing the texture coordinates on the quads, but on some systems
     that slows things down a lot.
   */
  if (flip_p)
    {
      int xx, col;
      unsigned long buf[100];
      for (y = 0; y < xi->height; y++)
        for (col = 0, xx = 0; col < CHAR_COLS; col++, xx += cw)
          {
            for (x = 0; x < cw; x++)
              buf[x] = XGetPixel (xi, xx+x, y);
            for (x = 0; x < cw; x++)
              XPutPixel (xi, xx+x, y, buf[cw-x-1]);
          }
    }

  /* The pixmap is a color image with no transparency.  Set the texture's
     alpha to be the green channel, and set the green channel to be 100%.
   */
  {
    int rpos, gpos, bpos, apos;  /* bitfield positions */
#if 0
    /* #### Cherub says that the little-endian case must be taken on MacOSX,
            or else the colors/alpha are the wrong way around.  How can
            that be the case?
     */
    if (bigendian())
      rpos = 24, gpos = 16, bpos =  8, apos =  0;
    else
#endif
      rpos =  0, gpos =  8, bpos = 16, apos = 24;

    for (y = 0; y < xi->height; y++)
      for (x = 0; x < xi->width; x++)
        {
          unsigned long p = XGetPixel (xi, x, y);
          unsigned char r = (p >> rpos) & 0xFF;
          unsigned char g = (p >> gpos) & 0xFF;
          unsigned char b = (p >> bpos) & 0xFF;
          unsigned char a = g;
          g = 0xFF;
          p = (r << rpos) | (g << gpos) | (b << bpos) | (a << apos);
          XPutPixel (xi, x, y, p);
        }
  }

  /* Now load the texture into GL.
   */
  clear_gl_error();
  glGenTextures (1, &mp->texture);

  glPixelStorei (GL_UNPACK_ALIGNMENT, 4);
  /* messes up -fps */
  /* glPixelStorei (GL_UNPACK_ROW_LENGTH, xi->width);*/
  glBindTexture (GL_TEXTURE_2D, mp->texture);
  check_gl_error ("texture init");
  glTexImage2D (GL_TEXTURE_2D, 0, GL_RGBA, xi->width, xi->height, 0, GL_RGBA,
                GL_UNSIGNED_INT_8_8_8_8_REV, xi->data);
  {
    char buf[255];
    sprintf (buf, "creating %dx%d texture:", xi->width, xi->height);
    check_gl_error (buf);
  }

  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

  /* I'd expect CLAMP to be the thing to do here, but oddly, we get a
     faint solid green border around the texture if it is *not* REPEAT!
  */
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
  glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

  glTexEnvi (GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
  glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
  check_gl_error ("texture param");

  XDestroyImage (xi);
}
Exemplo n.º 28
0
Arquivo: gl.c Projeto: Chuongv/uTox
_Bool gl_init(void)
{
    GLuint vertshader, fragshader;
    GLint status;
    const GLchar *data;

    vertshader = glCreateShader(GL_VERTEX_SHADER);
    if(!vertshader) {
        debug("glCreateShader() failed (vert)\n");
        return 0;
    }

    data = &vertex_shader[0];
    glShaderSource(vertshader, 1, &data, NULL);
    glCompileShader(vertshader);
    glGetShaderiv(vertshader, GL_COMPILE_STATUS, &status);
    if(!status) {
        #ifdef DEBUG
        debug("glCompileShader() failed (vert):\n%s\n", data);
        GLint infologsize = 0;
        glGetShaderiv(vertshader, GL_INFO_LOG_LENGTH, &infologsize);
        if(infologsize)
        {
            char* infolog = malloc(infologsize);
            glGetShaderInfoLog(vertshader, infologsize, NULL, (GLbyte*)infolog);
            debug("Infolog: %s\n", infolog);
            free(infolog);
        }
        #endif
        return 0;
    }

    fragshader = glCreateShader(GL_FRAGMENT_SHADER);
    if(!fragshader)
    {
        return 0;
    }

    data = &fragment_shader[0];
    glShaderSource(fragshader, 1, &data, NULL);
    glCompileShader(fragshader);
    glGetShaderiv(fragshader, GL_COMPILE_STATUS, &status);
    if(!status)
    {
        #ifdef DEBUG
        debug("glCompileShader failed (frag):\n%s\n", data);
        GLint infologsize = 0;
        glGetShaderiv(fragshader, GL_INFO_LOG_LENGTH, &infologsize);
        if(infologsize)
        {
            char* infolog = malloc(infologsize);
            glGetShaderInfoLog(fragshader, infologsize, NULL, (GLbyte*)infolog);
            debug("Infolog: %s\n", infolog);
            free(infolog);
        }
        #endif
        return 0;
    }

    prog = glCreateProgram();
    glAttachShader(prog, vertshader);
    glAttachShader(prog, fragshader);
    glBindAttribLocation(prog, 0, "pos");
    glBindAttribLocation(prog, 1, "tex");

    glLinkProgram(prog);
    glGetProgramiv(prog, GL_LINK_STATUS, &status);
    if(!status)
    {
        #ifdef DEBUG
        debug("glLinkProgram failed\n");
        GLint infologsize = 0;
        glGetShaderiv(prog, GL_INFO_LOG_LENGTH, &infologsize);
        if(infologsize)
        {
            char* infolog = malloc(infologsize);
            glGetShaderInfoLog(prog, infologsize, NULL, (GLbyte*)infolog);
            debug("Infolog: %s\n", infolog);
            free(infolog);
        }
        #endif
        return 0;
    }

    glUseProgram(prog);

    matrix = glGetUniformLocation(prog, "matrix");
    k = glGetUniformLocation(prog, "k");
    k2 = glGetUniformLocation(prog, "k2");
    samp = glGetUniformLocation(prog, "samp");

    debug("uniforms: %i %i %i\n", matrix, k, samp);

    GLint zero = 0;
    float one[] = {1.0, 1.0, 1.0};
    glUniform1iv(samp, 1, &zero);
    glUniform3fv(k2, 1, one);

    uint8_t wh = {255};
    glGenTextures(1, &white);
    glBindTexture(GL_TEXTURE_2D, white);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 1, 1, 0, GL_ALPHA, GL_UNSIGNED_BYTE, &wh);

    //
    glVertexAttribPointer(0, 2, GL_SHORT, GL_FALSE, sizeof(VERTEX2D), &quads[0]);
    glVertexAttribPointer(1, 2, GL_UNSIGNED_SHORT, GL_FALSE, sizeof(VERTEX2D), &quads[0].vertex[0].tx);
    glEnableVertexAttribArray(0);
    glEnableVertexAttribArray(1);

    //Alpha blending
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glEnable(GL_BLEND);

    //
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

    #ifndef NO_OPENGL_ES
    uint8_t i = 0;
    uint16_t ii = 0;
    do {
        quad_indices[ii] = i + 0;
        quad_indices[ii + 1] = i + 1;
        quad_indices[ii + 2] = i + 3;
        quad_indices[ii + 3] = i + 3;
        quad_indices[ii + 4] = i + 1;
        quad_indices[ii + 5] = i + 2;
        i += 4;
        ii += 6;
    } while(i);
    #endif

    glGenTextures(countof(bitmap), bitmap);

    svg_draw(0);
    loadfonts();

    float vec[4];
    vec[0] = -(float)utox_window_width / 2.0;
    vec[1] = -(float)utox_window_height / 2.0;
    vec[2] = 2.0 / (float)utox_window_width;
    vec[3] = -2.0 / (float)utox_window_height;
    glUniform4fv(matrix, 1, vec);

    ui_size(utox_window_width, utox_window_height);

    glViewport(0, 0, utox_window_width, utox_window_height);

    redraw();

    return 1;
}
Exemplo n.º 29
0
static void *gl_init(const video_info_t *video, const input_driver_t **input, void **input_data)
{
#ifdef _WIN32
   gfx_set_dwm();
#endif

   if (!sdlwrap_init())
      return NULL;

   const SDL_VideoInfo *video_info = SDL_GetVideoInfo();
   rarch_assert(video_info);
   unsigned full_x = video_info->current_w;
   unsigned full_y = video_info->current_h;
   RARCH_LOG("Detecting desktop resolution %ux%u.\n", full_x, full_y);

   sdlwrap_set_swap_interval(video->vsync ? 1 : 0, false);

   unsigned win_width = video->width;
   unsigned win_height = video->height;
   if (video->fullscreen && (win_width == 0) && (win_height == 0))
   {
      win_width = full_x;
      win_height = full_y;
   }

   if (!sdlwrap_set_video_mode(win_width, win_height,
            g_settings.video.force_16bit ? 15 : 0, video->fullscreen))
      return NULL;

   gfx_window_title_reset();
   char buf[128];
   if (gfx_window_title(buf, sizeof(buf)))
      sdlwrap_wm_set_caption(buf);

   // Remove that ugly mouse :D
   SDL_ShowCursor(SDL_DISABLE);
   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

#if (defined(HAVE_XML) || defined(HAVE_CG)) && defined(_WIN32)
   // Win32 GL lib doesn't have some functions needed for XML shaders.
   // Need to load dynamically :(
   if (!load_gl_proc())
   {
      sdlwrap_destroy();
      return NULL;
   }
#endif

   gl_t *gl = (gl_t*)calloc(1, sizeof(gl_t));
   if (!gl)
   {
      sdlwrap_destroy();
      return NULL;
   }

   gl->vsync = video->vsync;
   gl->fullscreen = video->fullscreen;
   
   gl->full_x = full_x;
   gl->full_y = full_y;
   gl->win_width = win_width;
   gl->win_height = win_height;

   RARCH_LOG("GL: Using resolution %ux%u\n", gl->win_width, gl->win_height);

   if (!gl_shader_init())
   {
      RARCH_ERR("Shader init failed.\n");
      sdlwrap_destroy();
      free(gl);
      return NULL;
   }

   RARCH_LOG("GL: Loaded %u program(s).\n", gl_shader_num());

#ifdef HAVE_FBO
   // Set up render to texture.
   gl_init_fbo(gl, RARCH_SCALE_BASE * video->input_scale,
         RARCH_SCALE_BASE * video->input_scale);
#endif
   
   gl->keep_aspect = video->force_aspect;

   // Apparently need to set viewport for passes when we aren't using FBOs.
   gl_shader_use(0);
   set_viewport(gl, gl->win_width, gl->win_height, false, true);
   gl_shader_use(1);
   set_viewport(gl, gl->win_width, gl->win_height, false, true);

   bool force_smooth;
   if (gl_shader_filter_type(1, &force_smooth))
      gl->tex_filter = force_smooth ? GL_LINEAR : GL_NEAREST;
   else
      gl->tex_filter = video->smooth ? GL_LINEAR : GL_NEAREST;

   gl->texture_type = GL_BGRA;
   gl->texture_fmt = video->rgb32 ? GL_UNSIGNED_INT_8_8_8_8_REV : GL_UNSIGNED_SHORT_1_5_5_5_REV;
   gl->base_size = video->rgb32 ? sizeof(uint32_t) : sizeof(uint16_t);

   glEnable(GL_TEXTURE_2D);
   glDisable(GL_DEPTH_TEST);
   glDisable(GL_DITHER);
   glClearColor(0, 0, 0, 1);

   glMatrixMode(GL_MODELVIEW);
   glLoadIdentity();

   glGenTextures(TEXTURES, gl->texture);

   for (unsigned i = 0; i < TEXTURES; i++)
   {
      glBindTexture(GL_TEXTURE_2D, gl->texture[i]);

      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);

      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, gl->tex_filter);
      glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, gl->tex_filter);
   }

   glEnableClientState(GL_VERTEX_ARRAY);
   glEnableClientState(GL_TEXTURE_COORD_ARRAY);
   glEnableClientState(GL_COLOR_ARRAY);
   glVertexPointer(2, GL_FLOAT, 0, vertexes_flipped);

   memcpy(gl->tex_coords, tex_coords, sizeof(tex_coords));
   glTexCoordPointer(2, GL_FLOAT, 0, gl->tex_coords);

   glColorPointer(4, GL_FLOAT, 0, white_color);

   set_lut_texture_coords(tex_coords);

   gl->tex_w = RARCH_SCALE_BASE * video->input_scale;
   gl->tex_h = RARCH_SCALE_BASE * video->input_scale;

   // Empty buffer that we use to clear out the texture with on res change.
   gl->empty_buf = calloc(gl->tex_w * gl->tex_h, gl->base_size);

   for (unsigned i = 0; i < TEXTURES; i++)
   {
      glBindTexture(GL_TEXTURE_2D, gl->texture[i]);
      glPixelStorei(GL_UNPACK_ROW_LENGTH, gl->tex_w);
      glTexImage2D(GL_TEXTURE_2D,
            0, GL_RGBA, gl->tex_w, gl->tex_h, 0, gl->texture_type,
            gl->texture_fmt, gl->empty_buf ? gl->empty_buf : NULL);
   }
   glBindTexture(GL_TEXTURE_2D, gl->texture[gl->tex_index]);

   for (unsigned i = 0; i < TEXTURES; i++)
   {
      gl->last_width[i] = gl->tex_w;
      gl->last_height[i] = gl->tex_h;
   }

   for (unsigned i = 0; i < TEXTURES; i++)
   {
      gl->prev_info[i].tex = gl->texture[(gl->tex_index - (i + 1)) & TEXTURES_MASK];
      gl->prev_info[i].input_size[0] = gl->tex_w;
      gl->prev_info[i].tex_size[0] = gl->tex_w;
      gl->prev_info[i].input_size[1] = gl->tex_h;
      gl->prev_info[i].tex_size[1] = gl->tex_h;
      memcpy(gl->prev_info[i].coord, tex_coords, sizeof(tex_coords)); 
   }

   // Hook up SDL input driver to get SDL_QUIT events and RESIZE.
   sdl_input_t *sdl_input = (sdl_input_t*)input_sdl.init();
   if (sdl_input)
   {
      *input = &input_sdl;
      *input_data = sdl_input;
   }
   else
      *input = NULL;

   gl_init_font(gl, g_settings.video.font_path, g_settings.video.font_size);
      
   if (!gl_check_error())
   {
      sdlwrap_destroy();
      free(gl);
      return NULL;
   }

   return gl;
}
Exemplo n.º 30
0
Arquivo: Font.cpp Projeto: m1h4/Touch
bool Font::LoadFromMemory(const unsigned char* data,unsigned long size)
{
	ASSERT(data);
	ASSERT(size);

	if(size < sizeof(mHeader))
		return false;

	ZeroMemory(&mHeader,sizeof(mHeader));
	ZeroMemory(mElements,sizeof(mElements));
	CopyMemory(&mHeader,data,sizeof(mHeader));

	data += sizeof(mHeader);
	size -= sizeof(mHeader);

	if(mHeader.magic != FontMagic)
		return false;

	if(mHeader.version != FontVersion)
		return false;

	if(!mHeader.tsize)
		return false;

	if(mHeader.chars > FontChars)
		return false;

	if(size < sizeof(mElements[0]) * mHeader.chars)
		return false;

	for(unsigned long i = 0; i < mHeader.chars; ++i)
	{
		CopyMemory(&mElements[i],data,sizeof(mElements[i]));

		data += sizeof(mElements[i]);
		size -= sizeof(mElements[i]);
	}

	if(size < mHeader.tsize)
		return false;

	Targa tga;

	if(!tga.LoadFromMemory(data,mHeader.tsize))
		return false;

	mTextureWidth = tga.GetWidth();
	mTextureHeight = tga.GetHeight();

	glGenTextures(1,&mTextureID);
	if(glGetError() != GL_NO_ERROR)
		return false;

	glBindTexture(GL_TEXTURE_2D,mTextureID);
	if(glGetError() != GL_NO_ERROR)
		return false;

	glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,mTextureWidth,mTextureHeight,0,GL_RGBA,GL_UNSIGNED_BYTE,tga.GetData());
	if(glGetError() != GL_NO_ERROR)
		return false;

	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	glBindTexture(GL_TEXTURE_2D,NULL);

	return true;
}