<commit_before>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              <NAME> <<EMAIL>>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "AbstractTexture.h"

#include <Corrade/Containers/Array.h>

#ifndef MAGNUM_TARGET_GLES2
#include "Magnum/BufferImage.h"
#endif
#include "Magnum/Array.h"
#include "Magnum/ColorFormat.h"
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/Image.h"
#include "Magnum/TextureFormat.h"
#include "Magnum/Math/Color.h"
#include "Magnum/Math/Range.h"

#ifndef MAGNUM_TARGET_WEBGL
#include "Implementation/DebugState.h"
#endif
#include "Implementation/State.h"
#include "Implementation/TextureState.h"

namespace Magnum {

#ifndef MAGNUM_TARGET_GLES2
Float AbstractTexture::maxLodBias() {
    GLfloat& value = Context::current()->state().texture->maxLodBias;

    /* Get the value, if not already cached */
    if(value == 0.0f)
        glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &value);

    return value;
}
#endif

#if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
Int AbstractTexture::maxColorSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxColorSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_COLOR_TEXTURE_SAMPLES, &value);

    return value;
}

Int AbstractTexture::maxDepthSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxDepthSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &value);

    return value;
}

Int AbstractTexture::maxIntegerSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxIntegerSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_INTEGER_SAMPLES, &value);

    return value;
}
#endif

void AbstractTexture::unbind(const Int textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* If given texture unit is already unbound, nothing to do */
    if(textureState.bindings[textureUnit].second == 0) return;

    /* Unbind the texture, reset state tracker */
    Context::current()->state().texture->unbindImplementation(textureUnit);
    textureState.bindings[textureUnit] = {};
}

void AbstractTexture::unbindImplementationDefault(const GLint textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* Activate given texture unit if not already active, update state tracker */
    if(textureState.currentTextureUnit != textureUnit)
        glActiveTexture(GL_TEXTURE0 + (textureState.currentTextureUnit = textureUnit));

    CORRADE_INTERNAL_ASSERT(textureState.bindings[textureUnit].first != 0);
    glBindTexture(textureState.bindings[textureUnit].first, 0);
}

#ifndef MAGNUM_TARGET_GLES
void AbstractTexture::unbindImplementationMulti(const GLint textureUnit) {
    constexpr static GLuint zero = 0;
    glBindTextures(textureUnit, 1, &zero);
}

void AbstractTexture::unbindImplementationDSA(const GLint textureUnit) {
    CORRADE_INTERNAL_ASSERT(Context::current()->state().texture->bindings[textureUnit].first != 0);
    glBindTextureUnit(textureUnit, 0);
}

void AbstractTexture::unbindImplementationDSAEXT(const GLint textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    CORRADE_INTERNAL_ASSERT(textureState.bindings[textureUnit].first != 0);
    glBindMultiTextureEXT(GL_TEXTURE0 + textureUnit, textureState.bindings[textureUnit].first, 0);
}
#endif

void AbstractTexture::unbind(const Int firstTextureUnit, const std::size_t count) {
    /* State tracker is updated in the implementations */
    Context::current()->state().texture->bindMultiImplementation(firstTextureUnit, {nullptr, count});
}

/** @todoc const std::initializer_list makes Doxygen grumpy */
void AbstractTexture::bind(const Int firstTextureUnit, std::initializer_list<AbstractTexture*> textures) {
    /* State tracker is updated in the implementations */
    Context::current()->state().texture->bindMultiImplementation(firstTextureUnit, {textures.begin(), textures.size()});
}

void AbstractTexture::bindImplementationFallback(const GLint firstTextureUnit, const Containers::ArrayView<AbstractTexture* const> textures) {
    for(std::size_t i = 0; i != textures.size(); ++i)
        textures && textures[i] ? textures[i]->bind(firstTextureUnit + i) : unbind(firstTextureUnit + i);
}

#ifndef MAGNUM_TARGET_GLES
/** @todoc const Containers::ArrayView makes Doxygen grumpy */
void AbstractTexture::bindImplementationMulti(const GLint firstTextureUnit, Containers::ArrayView<AbstractTexture* const> textures) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* Create array of IDs and also update bindings in state tracker */
    /** @todo VLAs */
    Containers::Array<GLuint> ids{textures ? textures.size() : 0};
    bool different = false;
    for(std::size_t i = 0; i != textures.size(); ++i) {
        const GLuint id = textures && textures[i] ? textures[i]->_id : 0;

        if(textures) {
            if(textures[i]) textures[i]->createIfNotAlready();
            ids[i] = id;
        }

        if(textureState.bindings[firstTextureUnit + i].second != id) {
            different = true;
            textureState.bindings[firstTextureUnit + i].second = id;
        }
    }

    /* Avoid doing the binding if there is nothing different */
    if(different) glBindTextures(firstTextureUnit, textures.size(), ids);
}
#endif

AbstractTexture::AbstractTexture(GLenum target): _target{target}, _flags{ObjectFlag::DeleteOnDestruction} {
    (this->*Context::current()->state().texture->createImplementation)();
    CORRADE_INTERNAL_ASSERT(_id != Implementation::State::DisengagedBinding);
}

void AbstractTexture::createImplementationDefault() {
    glGenTextures(1, &_id);
}

#ifndef MAGNUM_TARGET_GLES
void AbstractTexture::createImplementationDSA() {
    glCreateTextures(_target, 1, &_id);
    _flags |= ObjectFlag::Created;
}
#endif

AbstractTexture::~AbstractTexture() {
    /* Moved out or not deleting on destruction, nothing to do */
    if(!_id || !(_flags & ObjectFlag::DeleteOnDestruction)) return;

    /* Remove all bindings */
    for(auto& binding: Context::current()->state().texture->bindings)
        if(binding.second == _id) binding = {};

    glDeleteTextures(1, &_id);
}

inline void AbstractTexture::createIfNotAlready() {
    if(_flags & ObjectFlag::Created) return;

    /* glGen*() does not create the object, just reserves the name. Some
       commands (such as glBindTextures() or glObjectLabel()) operate with IDs
       directly and they require the object to be created. Binding the texture
       to desired target finally creates it. Also all EXT DSA functions
       implicitly create it. */
    bindInternal();
    CORRADE_INTERNAL_ASSERT(_flags & ObjectFlag::Created);
}

#ifndef MAGNUM_TARGET_WEBGL
std::string AbstractTexture::label() {
    createIfNotAlready();
    return Context::current()->state().debug->getLabelImplementation(GL_TEXTURE, _id);
}

AbstractTexture& AbstractTexture::setLabelInternal(const Containers::ArrayView<const char> label) {
    createIfNotAlready();
    Context::current()->state().debug->labelImplementation(GL_TEXTURE, _id, label);
    return *this;
}
#endif

void AbstractTexture::bind(Int textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;<commit_msg>This function is used also outside of this file.<commit_after>/*
    This file is part of Magnum.

    Copyright © 2010, 2011, 2012, 2013, 2014, 2015
              <NAME> <<EMAIL>>

    Permission is hereby granted, free of charge, to any person obtaining a
    copy of this software and associated documentation files (the "Software"),
    to deal in the Software without restriction, including without limitation
    the rights to use, copy, modify, merge, publish, distribute, sublicense,
    and/or sell copies of the Software, and to permit persons to whom the
    Software is furnished to do so, subject to the following conditions:

    The above copyright notice and this permission notice shall be included
    in all copies or substantial portions of the Software.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
    FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
    DEALINGS IN THE SOFTWARE.
*/

#include "AbstractTexture.h"

#include <Corrade/Containers/Array.h>

#ifndef MAGNUM_TARGET_GLES2
#include "Magnum/BufferImage.h"
#endif
#include "Magnum/Array.h"
#include "Magnum/ColorFormat.h"
#include "Magnum/Context.h"
#include "Magnum/Extensions.h"
#include "Magnum/Image.h"
#include "Magnum/TextureFormat.h"
#include "Magnum/Math/Color.h"
#include "Magnum/Math/Range.h"

#ifndef MAGNUM_TARGET_WEBGL
#include "Implementation/DebugState.h"
#endif
#include "Implementation/State.h"
#include "Implementation/TextureState.h"

namespace Magnum {

#ifndef MAGNUM_TARGET_GLES2
Float AbstractTexture::maxLodBias() {
    GLfloat& value = Context::current()->state().texture->maxLodBias;

    /* Get the value, if not already cached */
    if(value == 0.0f)
        glGetFloatv(GL_MAX_TEXTURE_LOD_BIAS, &value);

    return value;
}
#endif

#if !defined(MAGNUM_TARGET_GLES2) && !defined(MAGNUM_TARGET_WEBGL)
Int AbstractTexture::maxColorSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxColorSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_COLOR_TEXTURE_SAMPLES, &value);

    return value;
}

Int AbstractTexture::maxDepthSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxDepthSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_DEPTH_TEXTURE_SAMPLES, &value);

    return value;
}

Int AbstractTexture::maxIntegerSamples() {
    #ifndef MAGNUM_TARGET_GLES
    if(!Context::current()->isExtensionSupported<Extensions::GL::ARB::texture_multisample>())
    #else
    if(!Context::current()->isVersionSupported(Version::GLES310))
    #endif
        return 0;

    GLint& value = Context::current()->state().texture->maxIntegerSamples;

    /* Get the value, if not already cached */
    if(value == 0)
        glGetIntegerv(GL_MAX_INTEGER_SAMPLES, &value);

    return value;
}
#endif

void AbstractTexture::unbind(const Int textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* If given texture unit is already unbound, nothing to do */
    if(textureState.bindings[textureUnit].second == 0) return;

    /* Unbind the texture, reset state tracker */
    Context::current()->state().texture->unbindImplementation(textureUnit);
    textureState.bindings[textureUnit] = {};
}

void AbstractTexture::unbindImplementationDefault(const GLint textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* Activate given texture unit if not already active, update state tracker */
    if(textureState.currentTextureUnit != textureUnit)
        glActiveTexture(GL_TEXTURE0 + (textureState.currentTextureUnit = textureUnit));

    CORRADE_INTERNAL_ASSERT(textureState.bindings[textureUnit].first != 0);
    glBindTexture(textureState.bindings[textureUnit].first, 0);
}

#ifndef MAGNUM_TARGET_GLES
void AbstractTexture::unbindImplementationMulti(const GLint textureUnit) {
    constexpr static GLuint zero = 0;
    glBindTextures(textureUnit, 1, &zero);
}

void AbstractTexture::unbindImplementationDSA(const GLint textureUnit) {
    CORRADE_INTERNAL_ASSERT(Context::current()->state().texture->bindings[textureUnit].first != 0);
    glBindTextureUnit(textureUnit, 0);
}

void AbstractTexture::unbindImplementationDSAEXT(const GLint textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    CORRADE_INTERNAL_ASSERT(textureState.bindings[textureUnit].first != 0);
    glBindMultiTextureEXT(GL_TEXTURE0 + textureUnit, textureState.bindings[textureUnit].first, 0);
}
#endif

void AbstractTexture::unbind(const Int firstTextureUnit, const std::size_t count) {
    /* State tracker is updated in the implementations */
    Context::current()->state().texture->bindMultiImplementation(firstTextureUnit, {nullptr, count});
}

/** @todoc const std::initializer_list makes Doxygen grumpy */
void AbstractTexture::bind(const Int firstTextureUnit, std::initializer_list<AbstractTexture*> textures) {
    /* State tracker is updated in the implementations */
    Context::current()->state().texture->bindMultiImplementation(firstTextureUnit, {textures.begin(), textures.size()});
}

void AbstractTexture::bindImplementationFallback(const GLint firstTextureUnit, const Containers::ArrayView<AbstractTexture* const> textures) {
    for(std::size_t i = 0; i != textures.size(); ++i)
        textures && textures[i] ? textures[i]->bind(firstTextureUnit + i) : unbind(firstTextureUnit + i);
}

#ifndef MAGNUM_TARGET_GLES
/** @todoc const Containers::ArrayView makes Doxygen grumpy */
void AbstractTexture::bindImplementationMulti(const GLint firstTextureUnit, Containers::ArrayView<AbstractTexture* const> textures) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;

    /* Create array of IDs and also update bindings in state tracker */
    /** @todo VLAs */
    Containers::Array<GLuint> ids{textures ? textures.size() : 0};
    bool different = false;
    for(std::size_t i = 0; i != textures.size(); ++i) {
        const GLuint id = textures && textures[i] ? textures[i]->_id : 0;

        if(textures) {
            if(textures[i]) textures[i]->createIfNotAlready();
            ids[i] = id;
        }

        if(textureState.bindings[firstTextureUnit + i].second != id) {
            different = true;
            textureState.bindings[firstTextureUnit + i].second = id;
        }
    }

    /* Avoid doing the binding if there is nothing different */
    if(different) glBindTextures(firstTextureUnit, textures.size(), ids);
}
#endif

AbstractTexture::AbstractTexture(GLenum target): _target{target}, _flags{ObjectFlag::DeleteOnDestruction} {
    (this->*Context::current()->state().texture->createImplementation)();
    CORRADE_INTERNAL_ASSERT(_id != Implementation::State::DisengagedBinding);
}

void AbstractTexture::createImplementationDefault() {
    glGenTextures(1, &_id);
}

#ifndef MAGNUM_TARGET_GLES
void AbstractTexture::createImplementationDSA() {
    glCreateTextures(_target, 1, &_id);
    _flags |= ObjectFlag::Created;
}
#endif

AbstractTexture::~AbstractTexture() {
    /* Moved out or not deleting on destruction, nothing to do */
    if(!_id || !(_flags & ObjectFlag::DeleteOnDestruction)) return;

    /* Remove all bindings */
    for(auto& binding: Context::current()->state().texture->bindings)
        if(binding.second == _id) binding = {};

    glDeleteTextures(1, &_id);
}

void AbstractTexture::createIfNotAlready() {
    if(_flags & ObjectFlag::Created) return;

    /* glGen*() does not create the object, just reserves the name. Some
       commands (such as glBindTextures() or glObjectLabel()) operate with IDs
       directly and they require the object to be created. Binding the texture
       to desired target finally creates it. Also all EXT DSA functions
       implicitly create it. */
    bindInternal();
    CORRADE_INTERNAL_ASSERT(_flags & ObjectFlag::Created);
}

#ifndef MAGNUM_TARGET_WEBGL
std::string AbstractTexture::label() {
    createIfNotAlready();
    return Context::current()->state().debug->getLabelImplementation(GL_TEXTURE, _id);
}

AbstractTexture& AbstractTexture::setLabelInternal(const Containers::ArrayView<const char> label) {
    createIfNotAlready();
    Context::current()->state().debug->labelImplementation(GL_TEXTURE, _id, label);
    return *this;
}
#endif

void AbstractTexture::bind(Int textureUnit) {
    Implementation::TextureState& textureState = *Context::current()->state().texture;
{'fraction_non_alphanumeric': 0.1188965368896537, 'fraction_numerical': 0.006668100666810067, 'mean_word_length': 4.681943171402383, 'pattern_counts': {'":': 0, '<': 27, '<?xml version=': 0, '>': 105, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2111191', 'n_tokens_mistral': 5530, 'n_tokens_neox': 5234, 'n_words': 1354}