-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuffer_texture.h
101 lines (84 loc) · 2.45 KB
/
buffer_texture.h
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
/*
* Copyright (C) 2015-2018, Nils Moehrle
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD 3-Clause license. See the LICENSE.txt file for details.
*/
#ifndef CACC_BUFFERTEXTURE_HEADER
#define CACC_BUFFERTEXTURE_HEADER
#include "defines.h"
#include "graphics_resource.h"
#include <cuda_runtime_api.h>
CACC_NAMESPACE_BEGIN
template<typename T>
class BufferTexture {
public:
class Accessor {
private:
cudaTextureObject_t tex;
public:
Accessor(cudaTextureObject_t tex) : tex(tex) {}
__device__ __forceinline__
T operator[](int idx) const {
return tex1Dfetch<T>(tex, idx);
}
};
private:
cudaTextureObject_t tex;
protected:
void initialize(T *ptr, size_t size);
BufferTexture() {}
public:
BufferTexture(T *ptr, size_t size);
~BufferTexture();
Accessor accessor() { return Accessor(tex); };
};
template<typename T>
class MappedBufferTexture : public BufferTexture<T> {
private:
cudaGraphicsResource_t &res;
cudaStream_t stream;
public:
MappedBufferTexture(GraphicsResource *resource,
cudaStream_t = cudaStreamLegacy);
~MappedBufferTexture();
};
template<typename T>
BufferTexture<T>::BufferTexture(T *ptr, size_t size) {
initialize(ptr, size);
}
template<typename T>
MappedBufferTexture<T>::MappedBufferTexture(GraphicsResource *resource,
cudaStream_t steam) : res(resource->ptr()), stream(stream)
{
CHECK(cudaGraphicsMapResources(1, &res, stream));
T *ptr;
size_t size;
CHECK(cudaGraphicsResourceGetMappedPointer((void **)&ptr, &size, res));
this->initialize(ptr, size);
}
template<typename T>
BufferTexture<T>::~BufferTexture() {
CHECK(cudaDestroyTextureObject(tex));
}
template<typename T>
MappedBufferTexture<T>::~MappedBufferTexture() {
CHECK(cudaGraphicsUnmapResources(1, &res, stream));
}
template<typename T>
void
BufferTexture<T>::initialize(T *ptr, size_t size) {
cudaResourceDesc resDesc;
memset(&resDesc, 0, sizeof(resDesc));
resDesc.resType = cudaResourceTypeLinear;
resDesc.res.linear.devPtr = ptr;
resDesc.res.linear.desc = cudaCreateChannelDesc<T>();
resDesc.res.linear.sizeInBytes = sizeof(T) * size;
cudaTextureDesc texDesc;
memset(&texDesc, 0, sizeof(texDesc));
texDesc.readMode = cudaReadModeElementType;
CHECK(cudaCreateTextureObject(&tex, &resDesc, &texDesc, NULL));
}
CACC_NAMESPACE_END
#endif /* CACC_BUFFERTEXTURE_HEADER */