Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
GL Buffer with CUDA
#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(;
T* buffer;
size_t size;
cudaGraphicsMapResources(1, cuda_buffer.get());
cudaGraphicsResourceGetMappedPointer((void**)&buffer, &size, *cuda_buffer);
send_data_kernel<<<1, size >>>(buffer, data_ptr);
void delete_buffer(std::unique_ptr<GLuint> &buffer, std::unique_ptr <cudaGraphicsResource*> &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
You can’t perform that action at this time.