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 "rts/gl/error.h"


static void rtsInitGLEW()
{
	//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 rts_cudaSetDevice(int major = 1, int minor = 3)
{
	cudaDeviceProp prop;
	int dev;

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

static void* rts_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 rts_cudaUnmapResource(cudaGraphicsResource* resource)
{
	//this function unmaps the CUDA resource so it can be used by OpenGL
	HANDLE_ERROR(cudaGraphicsUnmapResources(1, &resource, NULL));
}

static void rts_cudaCreateRenderBuffer(GLuint &glBufferName, cudaGraphicsResource* &cudaBufferResource, int resX, int resY)
{
	//delete the previous buffer name and resource
	if(cudaBufferResource != 0)
		HANDLE_ERROR(cudaGraphicsUnregisterResource(cudaBufferResource));
	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);
	CHECK_OPENGL_ERROR
	HANDLE_ERROR(cudaGraphicsGLRegisterBuffer(&cudaBufferResource, glBufferName, cudaGraphicsMapFlagsNone));
}

#endif