VisuTwin Canvas
C++ 3D Engine — Metal Backend
Loading...
Searching...
No Matches
deviceCache.h
Go to the documentation of this file.
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2025-2026 Arnis Lektauers
3//
4// Created by Arnis Lektauers on 12.10.2025.
5//
6#pragma once
7
8#include <functional>
9#include <memory>
10
11#include "graphicsDevice.h"
12
13namespace visutwin::canvas
14{
20 {
21 public:
22 void remove(const std::shared_ptr<GraphicsDevice>& _graphicsDevice);
23
24 template <class T>
25 std::shared_ptr<T> get(const std::shared_ptr<GraphicsDevice>& device,
26 std::function<std::shared_ptr<T>()> onCreate);
27
28 private:
29 void handleDeviceLost(GraphicsDevice* device);
30
31 std::unordered_map<GraphicsDevice*, std::shared_ptr<void>> _cache;
32 };
33
34 template<typename T>
35 std::shared_ptr<T> DeviceCache::get(const std::shared_ptr<GraphicsDevice>& device, std::function<std::shared_ptr<T>()> onCreate) {
36 auto it = _cache.find(device.get());
37
38 if (it == _cache.end()) {
39 // Create the resource
40 auto resource = onCreate();
41
42 // Store in cache (casting to void* for storage)
43 _cache[device.get()] = std::static_pointer_cast<void>(resource);
44
45 // Set up event handlers for the device lifecycle
46 auto destroyCallback = [this, device]() {
47 remove(device);
48 };
49
50 auto deviceLostCallback = [this, device]() {
51 handleDeviceLost(device.get());
52 };
53
54 // Register event handlers
55 device->on("destroy", destroyCallback);
56 device->on("devicelost", deviceLostCallback);
57
58 return resource;
59 }
60
61 // Return cached resource (casting back from void*)
62 return std::static_pointer_cast<T>(_cache[device.get()]);
63 }
64}
void remove(const std::shared_ptr< GraphicsDevice > &_graphicsDevice)
std::shared_ptr< T > get(const std::shared_ptr< GraphicsDevice > &device, std::function< std::shared_ptr< T >()> onCreate)
Definition deviceCache.h:35
Abstract GPU interface for resource creation, state management, and draw submission.