1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
|
#include <stdio.h> #include <stdlib.h>
#include "GL\glut.h" #include "GL\glext.h"
#include <cuda_runtime.h>
#include <pcl\cuda\cutil_inline.h> #include <cuda.h> #include <cuda_gl_interop.h>
#define GET_PROC_ADDRESS(str) wglGetProcAddress(str) #define DIM 512
PFNGLBINDBUFFERARBPROC glBindBuffer = NULL; PFNGLDELETEBUFFERSARBPROC glDeleteBuffers = NULL; PFNGLGENBUFFERSARBPROC glGenBuffers = NULL; PFNGLBUFFERDATAARBPROC glBufferData = NULL;
GLuint bufferObj; cudaGraphicsResource *resource;
__global__ void cudaGLKernel(uchar4 *ptr) { int x = threadIdx.x + blockIdx.x * blockDim.x; int y = threadIdx.y + blockIdx.y * blockDim.y; int offset = x + y * blockDim.x * gridDim.x;
float fx = x / (float)DIM - 0.5f; float fy = y / (float)DIM - 0.5f;
unsigned char green = 128 + 127 * sin(abs(fx * 100) - abs(fy * 100));
ptr[offset].x = 0; ptr[offset].y = green; ptr[offset].z = 0; ptr[offset].w = 255;
}
void drawFunc(void) { glDrawPixels(DIM, DIM, GL_RGBA, GL_UNSIGNED_BYTE, 0); glutSwapBuffers(); }
static void keyFunc(unsigned char key, int x, int y) { switch (key){ case 27: cutilSafeCall(cudaGraphicsUnregisterResource(resource)); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, 0); glDeleteBuffers(1, &bufferObj); exit(0); } }
int main(int argc, char* argv[]) { cudaDeviceProp prop; int dev;
memset(&prop, 0, sizeof(cudaDeviceProp)); prop.major = 1; prop.minor = 0; cutilSafeCall(cudaChooseDevice(&dev, &prop)); cutilSafeCall(cudaGLSetGLDevice(dev));
glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA); glutInitWindowSize(DIM, DIM); glutCreateWindow("CUDA interact with OpenGL");
glBindBuffer = (PFNGLBINDBUFFERARBPROC)GET_PROC_ADDRESS("glBindBuffer"); glDeleteBuffers = (PFNGLDELETEBUFFERSARBPROC)GET_PROC_ADDRESS("glDeleteBuffers"); glGenBuffers = (PFNGLGENBUFFERSARBPROC)GET_PROC_ADDRESS("glGenBuffers"); glBufferData = (PFNGLBUFFERDATAARBPROC)GET_PROC_ADDRESS("glBufferData");
glGenBuffers(1, &bufferObj); glBindBuffer(GL_PIXEL_UNPACK_BUFFER_ARB, bufferObj); glBufferData(GL_PIXEL_UNPACK_BUFFER_ARB, DIM*DIM * 4, NULL, GL_DYNAMIC_DRAW_ARB);
cutilSafeCall(cudaGraphicsGLRegisterBuffer(&resource, bufferObj, cudaGraphicsMapFlagsNone));
uchar4* devPtr; size_t size; cutilSafeCall(cudaGraphicsMapResources(1, &resource, NULL)); cutilSafeCall(cudaGraphicsResourceGetMappedPointer((void**)&devPtr, &size, resource));
dim3 grids(DIM / 16, DIM / 16); dim3 threads(16, 16); cudaGLKernel << <grids, threads >> >(devPtr);
cutilSafeCall(cudaGraphicsUnmapResources(1, &resource, NULL)); glutKeyboardFunc(keyFunc); glutDisplayFunc(drawFunc); glutMainLoop(); return 0; }
|