Created
May 4, 2018 20:39
-
-
Save WaffleMan0310/ee6702f48957c96035b99ae6e5e8e868 to your computer and use it in GitHub Desktop.
GL Buffer with CUDA
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef CUDA_GL_BUFFER | |
#define CUDA_GL_BUFFER | |
#include <glad\glad.h> | |
#include <cuda_runtime.h> | |
#include <device_launch_parameters.h> | |
#include <cuda_gl_interop.h> | |
#include <thrust\device_vector.h> | |
#include <thrust\host_vector.h> | |
#include <memory> | |
namespace CudaGL { | |
template <typename T> | |
void create_buffer( | |
GLenum type, GLenum usage, cudaGraphicsRegisterFlags flags, | |
std::unique_ptr <GLuint> &buffer, std::unique_ptr <cudaGraphicsResource*> &cuda_buffer, | |
const thrust::host_vector<T> &data) { | |
glGenBuffers(1, buffer.get()); | |
glBindBuffer(type, *buffer); | |
glBufferData(type, data.size(), (void*)0, usage); | |
cudaGraphicsGLRegisterBuffer(cuda_buffer.get(), *buffer, flags); | |
send_data_to_buffer(cuda_buffer, data); | |
} | |
template <typename T> | |
void send_data_to_buffer(std::unique_ptr <cudaGraphicsResource*> &cuda_buffer, const thrust::host_vector<T> &data) { | |
thrust::device_vector<T> dev_data = data; | |
T* data_ptr = thrust::raw_pointer_cast(dev_data.data()); | |
T* buffer; | |
size_t size; | |
cudaGraphicsMapResources(1, cuda_buffer.get()); | |
cudaGraphicsResourceGetMappedPointer((void**)&buffer, &size, *cuda_buffer); | |
send_data_kernel<<<1, size >>>(buffer, data_ptr); | |
cudaDeviceSynchronize(); | |
}; | |
void delete_buffer(std::unique_ptr<GLuint> &buffer, std::unique_ptr <cudaGraphicsResource*> &cuda_buffer) { | |
cudaGraphicsUnregisterResource(*cuda_buffer); | |
glDeleteBuffers(1, buffer.get()); | |
} | |
template <typename T> | |
__global__ void send_data_kernel(T* buffer, T* data) { | |
int idx = (blockDim.x * blockIdx.x) + threadIdx.x; | |
if ((*buffer)[idx] != (*data)[idx]) (*buffer)[idx] = (*data)[idx]; | |
} | |
} | |
#endif // !CUDA_GL_BUFFER |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment