PhysicsBasedAnimationToolkit 0.0.10
Cross-platform C++20 library of algorithms and data structures commonly used in computer graphics research on physically-based simulation.
Loading...
Searching...
No Matches
Var.cuh
1#ifndef PBAT_GPU_IMPL_COMMON_VAR_H
2#define PBAT_GPU_IMPL_COMMON_VAR_H
3
4#include <cstddef>
5#include <cuda/api.hpp>
6#include <memory>
7
8namespace pbat {
9namespace gpu {
10namespace impl {
11namespace common {
12
13template <class T>
14class Var
15{
16 public:
17 Var(T const& value = T{},
18 std::shared_ptr<cuda::stream_t> stream =
19 std::make_shared<cuda::stream_t>(cuda::device::current::get().default_stream()));
20
21 Var(Var const&) = delete;
22 Var& operator=(Var const&) = delete;
23 Var& operator=(T const& value);
24
25 Var(Var&&) = delete;
26 Var operator=(Var&&) = delete;
27
28 T Get() const;
29 operator T() const;
30
31 T* Raw();
32 T const* Raw() const;
33
34 void SetStream(std::shared_ptr<cuda::stream_t> stream) { mStream = stream; }
35 std::shared_ptr<cuda::stream_t> Stream() const { return mStream; }
36
37 ~Var();
38
39 private:
40 cuda::memory::region_t mDeviceMemory;
41 std::shared_ptr<cuda::stream_t> mStream;
42};
43
44template <class T>
45Var<T>::Var(T const& value, std::shared_ptr<cuda::stream_t> stream)
46 : mDeviceMemory(), mStream(stream)
47{
48 mStream->device().make_current();
49 mDeviceMemory = cuda::memory::device::allocate(sizeof(T), *mStream);
50 cuda::memory::copy(mDeviceMemory, reinterpret_cast<void*>(const_cast<T*>(&value)), *mStream);
51}
52
53template <class T>
54Var<T>& Var<T>::operator=(T const& value)
55{
56 mStream->device().make_current();
57 cuda::memory::copy(mDeviceMemory, reinterpret_cast<void*>(const_cast<T*>(&value)), *mStream);
58 return *this;
59}
60
61template <class T>
62T Var<T>::Get() const
63{
64 std::byte memory[sizeof(T)];
65 mStream->device().make_current();
66 cuda::memory::copy(reinterpret_cast<void*>(&memory), mDeviceMemory, *mStream);
67 mStream->synchronize();
68 return *reinterpret_cast<T*>(&memory);
69}
70
71template <class T>
72Var<T>::operator T() const
73{
74 return Get();
75}
76
77template <class T>
78T* Var<T>::Raw()
79{
80 return static_cast<T*>(mDeviceMemory.data());
81}
82
83template <class T>
84T const* Var<T>::Raw() const
85{
86 return static_cast<T const*>(mDeviceMemory.data());
87}
88
89template <class T>
90Var<T>::~Var()
91{
92 mStream->device().make_current();
93 cuda::memory::device::free(mDeviceMemory);
94}
95
96} // namespace common
97} // namespace impl
98} // namespace gpu
99} // namespace pbat
100
101#endif // PBAT_GPU_IMPL_COMMON_VAR_H
GPU algorithm implementations.
Definition VertexTriangleMixedCcdDcd.h:21
GPU related public functionality.
Definition Buffer.cu:16
The main namespace of the library.
Definition Aliases.h:15