AUI Framework  develop
Cross-platform base for C++ UI apps
Loading...
Searching...
No Matches
ResourcePool.h
    1/*
    2 * AUI Framework - Declarative UI toolkit for modern C++20
    3 * Copyright (C) 2020-2025 Alex2772 and Contributors
    4 *
    5 * SPDX-License-Identifier: MPL-2.0
    6 *
    7 * This Source Code Form is subject to the terms of the Mozilla Public
    8 * License, v. 2.0. If a copy of the MPL was not distributed with this
    9 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
   10 */
   11
   12#pragma once
   13
   14#include <AUI/GL/gl.h>
   15#include "AUI/Common/AQueue.h"
   16
   17namespace gl {
   18
   19    enum class ResourceKind {
   20        VERTEX_BUFFER,
   21        INDEX_BUFFER,
   22        TEXTURE,
   23    };
   24
   25    namespace impl {
   26        template<ResourceKind T>
   27        struct resource;
   28
   29        struct resource_basic_buffer {
   30            static GLuint gen() noexcept {
   31                GLuint b = 0;
   32                glGenBuffers(1, &b);
   33                return b;
   34            }
   35            static void del(GLuint b) noexcept {
   36                glDeleteBuffers(1, &b);
   37            }
   38        };
   39
   40        template<> struct resource<ResourceKind::VERTEX_BUFFER>: resource_basic_buffer {};
   41        template<> struct resource<ResourceKind::INDEX_BUFFER>: resource_basic_buffer {};
   42
   43        template<> struct resource<ResourceKind::TEXTURE> {
   44            static GLuint gen() noexcept {
   45                GLuint b = 0;
   46                glGenTextures(1, &b);
   47                return b;
   48            }
   49            static void del(GLuint b) noexcept {
   50                glDeleteTextures(1, &b);
   51            }
   52        };
   53    }
   54
   55    template<ResourceKind T>
   56    class ResourcePool {
   57    public:
   58        static GLuint get() {
   59            return inst().mObjects.popOrGenerate([] {
   60                return gl::impl::resource<T>::gen();
   61            });
   62        }
   63        static void put(GLuint obj) {
   64            inst().mObjects.push(obj);
   65        }
   66
   67        ~ResourcePool() {
   68            while (!mObjects.empty()) {
   69                gl::impl::resource<T>::del(mObjects.front());
   70                mObjects.pop();
   71            }
   72        }
   73
   74    private:
   75        AQueue<GLuint> mObjects;
   76
   77        static ResourcePool& inst() noexcept {
   78            static ResourcePool r;
   79            return r;
   80        }
   81    };
   82}
A std::queue with AUI extensions.
Definition AQueue.h:24
StoredType popOrGenerate(Factory factory) noexcept(noexcept(factory()))
Pops the element and returns it. If queue is empty, the result of factory() returned....
Definition AQueue.h:83
Definition ResourcePool.h:56
Definition ResourcePool.h:29
Definition ResourcePool.h:27