glbind.h 2.19 KB
#ifndef RTS_GL_BIND_H
#define RTS_GL_BIND_H

#include <GL/glew.h>
#include <GL/gl.h>

#include <stdio.h>
#include <cstring>

//#include <cudaHandleError.h>
#include "cuda_gl_interop.h"
#include <stim/gl/error.h>

namespace stim

static void InitGLEW()
	//Initialize the GLEW toolkit

	GLenum err = glewInit();
	if(GLEW_OK != err)
		printf("Error starting GLEW.");
	fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

static void cudaSetDevice(int major = 1, int minor = 3)
	cudaDeviceProp prop;
	int dev;

	//find a CUDA device that can handle an offscreen buffer
	int num_gpu;
	printf("Number of CUDA devices detected: %d\n", num_gpu);
	memset(&prop, 0, sizeof(cudaDeviceProp));
	HANDLE_ERROR(cudaChooseDevice(&dev, &prop));
	HANDLE_ERROR(cudaGetDeviceProperties(&prop, dev));

static void* cudaMapResource(cudaGraphicsResource* cudaBufferResource)
	//this function takes a predefined CUDA resource and maps it to a pointer
	void* buffer;
	HANDLE_ERROR(cudaGraphicsMapResources(1, &cudaBufferResource, NULL));
	size_t size;
	HANDLE_ERROR(cudaGraphicsResourceGetMappedPointer( (void**)&buffer, &size, cudaBufferResource));
	return buffer;
static void cudaUnmapResource(cudaGraphicsResource* resource)
	//this function unmaps the CUDA resource so it can be used by OpenGL
	HANDLE_ERROR(cudaGraphicsUnmapResources(1, &resource, NULL));

static void cudaCreateRenderBuffer(GLuint &glBufferName, cudaGraphicsResource* &cudaBufferResource, int resX, int resY)
	//delete the previous buffer name and resource
	if(cudaBufferResource != 0)
	if(glBufferName != 0)
		glDeleteBuffers(1, &glBufferName);

	//generate an OpenGL offscreen buffer
	glGenBuffers(1, &glBufferName);

	//bind the buffer - directs all calls to this buffer
	glBindBuffer(GL_PIXEL_UNPACK_BUFFER, glBufferName);
	glBufferData(GL_PIXEL_UNPACK_BUFFER, resX * resY * sizeof(uchar3), NULL, GL_DYNAMIC_DRAW_ARB);
	HANDLE_ERROR(cudaGraphicsGLRegisterBuffer(&cudaBufferResource, glBufferName, cudaGraphicsMapFlagsNone));