<commit_before>#include "config.h"

#include <immintrin.h>
#include <x86intrin.h>

#include <cstdint>
#include <cstdlib>
#include <string>

// --------------------------------------------------

#include "config.h"

// --------------------------------------------------

#include "popcnt-lookup.cpp"
#include "popcnt-bit-parallel-scalar.cpp"
#include "popcnt-harley-seal.cpp"

#include "sse_operators.cpp"
#include "popcnt-sse-bit-parallel.cpp"
#include "popcnt-sse-lookup.cpp"
#include "popcnt-cpu.cpp"
#if defined(HAVE_AVX2_INSTRUCTIONS)
#   include "popcnt-avx2-lookup.cpp"
#endif

// --------------------------------------------------

void verify(const char* name, const std::uint8_t* data, const size_t size);

struct function_t {
    const bool     is_reference;
    const char*    name;
    std::uint64_t (*function)(const uint8_t* data, const size_t size);
};

function_t functions[] = {
    {true,  "lookup-8",                popcnt_lookup_8bit},
    {true,  "lookup-64",               popcnt_lookup_64bit},
    {false, "bit-parallel",            popcnt_parallel_64bit_naive},
    {false, "bit-parallel-optimized",  popcnt_parallel_64bit_optimized},
    {false, "harley-seal",             popcnt_harley_seal},
    {false, "sse-bit-parallel",        popcnt_SSE_bit_parallel},
    {false, "sse-lookup",              popcnt_SSE_lookup},
#if defined(HAVE_AVX2_INSTRUCTIONS)
    {false, "avx2-lookup",             popcnt_AVX2_lookup},
#endif
#if defined(HAVE_POPCNT_INSTRUCTION)
    {false, "cpu",                     popcnt_cpu_64bit},
#endif
    {false, nullptr, nullptr}
};

int main() {

    static const size_t size = 1024;
    std::uint8_t data[size];

    // 1. all zeros
    for (size_t i=0; i < size; i++) {
        data[i] = 0;
    }

    verify("all zeros", data, size);

    // 2. all ones
    for (size_t i=0; i < size; i++) {
        data[i] = 1;
    }

    verify("all ones", data, size);

    // 3. ascending
    for (size_t i=0; i < size; i++) {
        data[i] = i;
    }

    verify("asending", data, size);

    // 4. quasirandom
    for (size_t i=0; i < size; i++) {
        data[i] = i*33 + 12345;
    }

    verify("quasirandom", data, size);

    return EXIT_SUCCESS;
}

#if HAVE_ANSI_CONSOLE
void puts(const char* str, int ansi_color) {
    printf("\033[%dm%s\033[0m\n", ansi_color, str);
}
#else
void puts(const char* str, int) {
    puts(str);
}
#endif // HAVE_ANSI_CONSOLE

static const int RED   = 31;
static const int GREEN = 32;

void verify(const char* name, const std::uint8_t* data, const size_t size) {

    puts("");
    printf("test '%s':\n", name);

    const size_t reference = popcnt_lookup_8bit(data, size);

    for (auto& item: functions) {
        if (item.function == nullptr) {
            continue;
        }

        if (item.is_reference) {
            continue;
        }

        printf("%-30s: ", item.name);
        const size_t result = item.function(data, size);

        if (result == reference) {
            puts("OK", GREEN);
        } else {
            puts("ERROR", RED);
        }
    }
}
<commit_msg>plug the imported functions into verify util<commit_after>#include "config.h"

#include <immintrin.h>
#include <x86intrin.h>

#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <string>

// --------------------------------------------------

#include "config.h"

// --------------------------------------------------

#include "popcnt-lookup.cpp"
#include "popcnt-bit-parallel-scalar.cpp"
#include "popcnt-harley-seal.cpp"

#include "sse_operators.cpp"
#include "popcnt-sse-bit-parallel.cpp"
#include "popcnt-sse-lookup.cpp"
#include "popcnt-cpu.cpp"
#include "popcnt-builtin.cpp"
#if defined(HAVE_AVX2_INSTRUCTIONS)
#   include "popcnt-avx2-lookup.cpp"
#endif

// --------------------------------------------------

bool verify(const char* name, const std::uint8_t* data, const size_t size);
size_t widest_name();

struct function_t {
    const bool     is_reference;
    const char*    name;
    std::uint64_t (*function)(const uint8_t* data, const size_t size);
    std::uint64_t (*function_64)(const uint64_t* data, int size);
};

function_t functions[] = {
    {true,  "lookup-8",                popcnt_lookup_8bit, nullptr},
    {true,  "lookup-64",               popcnt_lookup_64bit, nullptr},
    {false, "bit-parallel",            popcnt_parallel_64bit_naive, nullptr},
    {false, "bit-parallel-optimized",  popcnt_parallel_64bit_optimized, nullptr},
    {false, "harley-seal",             popcnt_harley_seal, nullptr},
    {false, "sse-bit-parallel",        popcnt_SSE_bit_parallel, nullptr},
    {false, "sse-lookup",              popcnt_SSE_lookup, nullptr},
#if defined(HAVE_AVX2_INSTRUCTIONS)
    {false, "avx2-lookup",             popcnt_AVX2_lookup, nullptr},
#endif
#if defined(HAVE_POPCNT_INSTRUCTION)
    {false, "cpu",                     popcnt_cpu_64bit, nullptr},
#endif
    // from popcnt-builtin.cpp
    {false, "builtin-popcnt",                           nullptr, builtin_popcnt},
    {false, "builtin-popcnt32",                         nullptr, builtin_popcnt32},
    {false, "builtin-popcnt-unrolled",                  nullptr, builtin_popcnt_unrolled},
    {false, "builtin-popcnt-unrolled32",                nullptr, builtin_popcnt_unrolled32},
    {false, "builtin-popcnt-unrolled-errata",           nullptr, builtin_popcnt_unrolled_errata},
    {false, "builtin-popcnt-unrolled-errata-manual",    nullptr, builtin_popcnt_unrolled_errata_manual},
    {false, "builtin-popcnt-movdq",                     nullptr, builtin_popcnt_movdq},
    {false, "builtin-popcnt-movdq-unrolled",            nullptr, builtin_popcnt_movdq_unrolled},
    {false, "builtin-popcnt-movdq-unrolled_manual",     nullptr, builtin_popcnt_movdq_unrolled_manual},

    // sentinel
    {false, nullptr, nullptr, nullptr}
};

#if HAVE_ANSI_CONSOLE
void puts(const char* str, int ansi_color) {
    printf("\033[%dm%s\033[0m\n", ansi_color, str);
}
#else
void puts(const char* str, int) {
    puts(str);
}
#endif // HAVE_ANSI_CONSOLE

static const int RED   = 31;
static const int GREEN = 32;

int main() {

    static const size_t size = 1024;
    std::uint8_t data[size];
    bool all_ok = true;

    // 1. all zeros
    for (size_t i=0; i < size; i++) {
        data[i] = 0;
    }

    all_ok &= verify("all zeros", data, size);

    // 2. all ones
    for (size_t i=0; i < size; i++) {
        data[i] = 1;
    }

    all_ok &= verify("all ones", data, size);

    // 3. ascending
    for (size_t i=0; i < size; i++) {
        data[i] = i;
    }

    all_ok &= verify("ascending", data, size);

    // 4. quasirandom
    for (size_t i=0; i < size; i++) {
        data[i] = i*33 + 12345;
    }

    all_ok &= verify("quasirandom", data, size);

    if (all_ok) {
        return EXIT_SUCCESS;
    } else {
        puts("There are errors", RED);
        return EXIT_FAILURE;
    }
}

bool verify(const char* name, const std::uint8_t* data, const size_t size) {

    const int w = widest_name();

    puts("");
    printf("test '%s' :\n", name);

    const size_t reference = popcnt_lookup_8bit(data, size);

    bool all_ok = true;

    for (auto& item: functions) {
        if (item.name == nullptr) {
            continue;
        }

        if (item.is_reference) {
            continue;
        }

        printf("%*s: ", -w, item.name);
        size_t result;
        if (item.function)
            result = item.function(data, size);
        else
            result = item.function_64(reinterpret_cast<const uint64_t*>(data), size/8);

        if (result == reference) {
            puts("OK", GREEN);
        } else {
            puts("ERROR", RED);
            all_ok = false;
        }
    }

    return all_ok;
}

size_t widest_name() {

    size_t width = 0;

    for (auto& item: functions) {
        if (item.name != nullptr) {
            width = std::max(width, strlen(item.name));
        }
    }

    return width;
}
<|endoftext|>


<commit_before>#ifndef TESTS_H
#define TESTS_H

#include <boost/test/unit_test.hpp>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>

#include "grune/grune_fwd.hpp"
#include "grune/sentence_iterator.hpp"
#include "grune-yaml/grune-yaml.hpp"

template<class T>
struct grune_assertion_traits
{
    static bool equal(const T& x, const T& y)
    {
        return x == y;
    }

    static std::string toString(const T& x)
    {
#ifndef GRUNE_ASSERTION_TRAITS_NO_YAML
        return YAML::Dump(YAML::Node(x));
#else /* GRUNE_ASSERTION_TRAITS_NO_YAML */
        return grune::to_string(x);
#endif
    }

};

#define GRUNE_ASSERTION_TRAITS(t) \
    template<> \
    struct assertion_traits<t> : \
        public grune_assertion_traits<t> \
    { };

namespace CppUnit {
GRUNE_ASSERTION_TRAITS(grune::symbol);
GRUNE_ASSERTION_TRAITS(grune::non_terminal);
GRUNE_ASSERTION_TRAITS(grune::sequence);
GRUNE_ASSERTION_TRAITS(grune::sequence_list);
GRUNE_ASSERTION_TRAITS(grune::production);
GRUNE_ASSERTION_TRAITS(grune::production_list);
GRUNE_ASSERTION_TRAITS(grune::grammar);

template<>
struct assertion_traits<grune::sentence_iterator>
{
    typedef grune::sentence_iterator T;
    static bool equal(const T& x, const T& y) { return x == y; }
    static std::string toString(const T& x)
    {
        using namespace grune;
        if (x != sentence_iterator())
        {
            return assertion_traits<sequence>::toString(*x);
        }
        return "<end>";
    }
};

}

#endif /* TESTS_H */
<commit_msg>Add boost wrappers for CppUnit assertion_traits<commit_after>#ifndef TESTS_H
#define TESTS_H

#include <boost/test/unit_test.hpp>
#include <cppunit/CompilerOutputter.h>
#include <cppunit/extensions/HelperMacros.h>
#include <cppunit/TestAssert.h>
#include <cppunit/TestFixture.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>

#include "grune/grune_fwd.hpp"
#include "grune/sentence_iterator.hpp"
#include "grune-yaml/grune-yaml.hpp"

template<class T>
struct grune_assertion_traits
{
    static bool equal(const T& x, const T& y)
    {
        return x == y;
    }

    static std::string toString(const T& x)
    {
#ifndef GRUNE_ASSERTION_TRAITS_NO_YAML
        return YAML::Dump(YAML::Node(x));
#else /* GRUNE_ASSERTION_TRAITS_NO_YAML */
        return grune::to_string(x);
#endif
    }

};

#define GRUNE_ASSERTION_TRAITS(t) \
    namespace CppUnit { \
    template<> \
    struct assertion_traits<t> : \
        public grune_assertion_traits<t> \
    { }; }\
    namespace boost { namespace test_tools { \
    template<> \
    struct print_log_value<t> { \
        template<class T=void> \
        void operator()(std::ostream& os, const t& v) { \
            grune_assertion_traits<t>::toString(v); \
        } \
    }; \
    } }

GRUNE_ASSERTION_TRAITS(grune::symbol);
GRUNE_ASSERTION_TRAITS(grune::non_terminal);
GRUNE_ASSERTION_TRAITS(grune::sequence);
GRUNE_ASSERTION_TRAITS(grune::sequence_list);
GRUNE_ASSERTION_TRAITS(grune::production);
GRUNE_ASSERTION_TRAITS(grune::production_list);
GRUNE_ASSERTION_TRAITS(grune::grammar);

namespace CppUnit {
template<>
struct assertion_traits<grune::sentence_iterator>
{
    typedef grune::sentence_iterator T;
    static bool equal(const T& x, const T& y) { return x == y; }
    static std::string toString(const T& x)
    {
        using namespace grune;
        if (x != sentence_iterator())
        {
            return assertion_traits<sequence>::toString(*x);
        }
        return "<end>";
    }
};

}

namespace boost {
namespace test_tools {
    template<>
    struct print_log_value<grune::sentence_iterator>
    {
        void operator()(std::ostream& os, const grune::sentence_iterator& v)
        {
            os << CppUnit::assertion_traits<grune::sentence_iterator>::toString(v);
        }
    };
}
}

#endif /* TESTS_H */
<|endoftext|>


<commit_before>/*
    Copyright 2015 Ahnaf Siddiqui

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "CollideDemo.h"
#include "D_ComponentNames.h"
#include "D_Input.h"
using namespace Diamond;

CollideDemo::CollideDemo(Engine2D &engine, float movespeed)
    : Game2D(engine), movespeed(movespeed),
      spike1(engine.makeTransform()),
      spike2(engine.makeTransform()),
      zapper1(engine.makeTransform()),
      zapper2(engine.makeTransform()) {
    Renderer2D *renderer = engine.getRenderer();

    SharedPtr<Texture> spike_sprite = renderer->loadTexture("spike.png");

    if (!spike_sprite) {
        std::cout << "Couldn't load sprites!" << std::endl;
        engine.quit();
        return;
    }

    spike1.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(spike1.transform(), spike_sprite));
    spike1.transform().position = Vector2<int>(500, 400);
    spike1.transform().scale = Vector2<float>(0.1f, 0.1f);

    spike2.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(spike2.transform(), spike_sprite));
    spike2.transform().position = Vector2<int>(900, 200);
    spike2.transform().scale = Vector2<float>(0.1f, 0.1f);

    zapper_anim.sprite_sheet = renderer->loadTexture("zapper.png");
    zapper_anim.rows = 2;
    zapper_anim.columns = 2;
    zapper_anim.num_frames = 4;

    zapper1.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(zapper1.transform(), spike_sprite));
    zapper1.addComponent(ANIMATOR,
        makeShared<AnimatorSheet>(zapper1.getComponent<RenderComponent2D>(RENDERCOMPONENT), &zapper_anim));
    zapper1.transform().position = Vector2<int>(300, 100);
    zapper1.transform().scale = Vector2<float>(0.5f, 0.5f);

    zapper2.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(zapper2.transform(), spike_sprite));
    zapper2.addComponent(ANIMATOR,
        makeShared<AnimatorSheet>(zapper2.getComponent<RenderComponent2D>(RENDERCOMPONENT), &zapper_anim));
    zapper2.transform().position = Vector2<int>(700, 300);
    zapper2.transform().scale = Vector2<float>(0.5f, 0.5f);

    // Setup physics
    PhysicsWorld2D *physworld = engine.getPhysWorld();
    std::function<void(void*)> callback = std::bind(&CollideDemo::m_onCollision, this, std::placeholders::_1);

    SharedPtr<Rigidbody2D> rbody = physworld->makeRigidbody(spike1.transform());
    spike1.addComponent(RIGIDBODY, rbody);

    float scale = spike1.transform().scale.x;
    tD_pos radius = spike_sprite->getWidth() * scale / 2.0;
    spike1.addComponent(COLLIDER,
        physworld->makeCircleCollider(rbody, &spike1, callback, radius, Vector2<tD_pos>(radius, radius)));

    rbody = physworld->makeRigidbody(spike2.transform());
    spike2.addComponent(RIGIDBODY, rbody);
    scale = spike2.transform().scale.x;
    radius = spike_sprite->getWidth() * scale / 2.0;
    spike2.addComponent(COLLIDER,
        physworld->makeCircleCollider(rbody, &spike2, callback, radius, Vector2<tD_pos>(radius, radius)));

    rbody = physworld->makeRigidbody(zapper1.transform());
    zapper1.addComponent(RIGIDBODY, rbody);
    float partial_width = zapper_anim.sprite_sheet->getWidth() / zapper_anim.columns / 5.0;
    scale = zapper1.transform().scale.x;
    zapper1.addComponent(COLLIDER,
        physworld->makeAABBCollider(rbody, &zapper1, callback,
        Vector2<tD_pos>(partial_width * scale, zapper_anim.sprite_sheet->getHeight() / zapper_anim.rows * scale),
        Vector2<tD_pos>(2 * partial_width * scale, 0)));

    rbody = physworld->makeRigidbody(zapper2.transform());
    zapper2.addComponent(RIGIDBODY, rbody);
    scale = zapper2.transform().scale.x;
    zapper2.addComponent(COLLIDER,
        physworld->makeAABBCollider(rbody, &zapper2, callback,
        Vector2<tD_pos>(partial_width * scale, zapper_anim.sprite_sheet->getHeight() / zapper_anim.rows * scale),
        Vector2<tD_pos>(2 * partial_width * scale, 0)));

}

void CollideDemo::update(tD_delta delta) {
    // zapper1 controls
    if (Input::keydown[Input::K_W]) {
        zapper1.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_S]) {
        zapper1.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_A]) {
        zapper1.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_D]) {
        zapper1.transform().position.x += movespeed * delta;
    }

    // zapper2 controls
    if (Input::keydown[Input::K_UP]) {
        zapper2.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_DOWN]) {
        zapper2.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_LEFT]) {
        zapper2.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_RIGHT]) {
        zapper2.transform().position.x += movespeed * delta;
    }

    // spike2 controls
    if (Input::keydown[Input::K_P8]) {
        spike2.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_P2]) {
        spike2.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_P4]) {
        spike2.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_P6]) {
        spike2.transform().position.x += movespeed * delta;
    }

    // update entities
    spike1.updateComponents(delta);
    spike2.updateComponents(delta);
    zapper1.updateComponents(delta);
    zapper2.updateComponents(delta);
}

void CollideDemo::quit() {
    //
}

void CollideDemo::m_onCollision(void *other) {
    /*
    SharedPtr<Rigidbody2D> rbody = ((Entity2D*)other)->getComponent<Rigidbody2D>(RIGIDBODY);
    if (rbody) {
        rbody->setRotation(rbody->getRotation() + 20);
    }
    */
    std::cout << "Hit by " << other << std::endl;
}

<commit_msg>Added some spinning fun to collide demo<commit_after>/*
    Copyright 2015 Ahnaf Siddiqui

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
*/

#include "CollideDemo.h"
#include "D_ComponentNames.h"
#include "D_Input.h"
using namespace Diamond;

CollideDemo::CollideDemo(Engine2D &engine, float movespeed)
    : Game2D(engine), movespeed(movespeed),
      spike1(engine.makeTransform()),
      spike2(engine.makeTransform()),
      zapper1(engine.makeTransform()),
      zapper2(engine.makeTransform()) {
    Renderer2D *renderer = engine.getRenderer();

    SharedPtr<Texture> spike_sprite = renderer->loadTexture("spike.png");

    if (!spike_sprite) {
        std::cout << "Couldn't load sprites!" << std::endl;
        engine.quit();
        return;
    }

    spike1.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(spike1.transform(), spike_sprite));
    spike1.transform().position = Vector2<int>(500, 400);
    spike1.transform().scale = Vector2<float>(0.1f, 0.1f);

    spike2.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(spike2.transform(), spike_sprite));
    spike2.transform().position = Vector2<int>(900, 200);
    spike2.transform().scale = Vector2<float>(0.1f, 0.1f);

    zapper_anim.sprite_sheet = renderer->loadTexture("zapper.png");
    zapper_anim.rows = 2;
    zapper_anim.columns = 2;
    zapper_anim.num_frames = 4;

    zapper1.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(zapper1.transform(), spike_sprite));
    zapper1.addComponent(ANIMATOR,
        makeShared<AnimatorSheet>(zapper1.getComponent<RenderComponent2D>(RENDERCOMPONENT), &zapper_anim));
    zapper1.transform().position = Vector2<int>(300, 100);
    zapper1.transform().scale = Vector2<float>(0.5f, 0.5f);

    zapper2.addComponent(RENDERCOMPONENT,
        renderer->makeRenderComponent(zapper2.transform(), spike_sprite));
    zapper2.addComponent(ANIMATOR,
        makeShared<AnimatorSheet>(zapper2.getComponent<RenderComponent2D>(RENDERCOMPONENT), &zapper_anim));
    zapper2.transform().position = Vector2<int>(700, 300);
    zapper2.transform().scale = Vector2<float>(0.5f, 0.5f);

    // Setup physics
    PhysicsWorld2D *physworld = engine.getPhysWorld();
    std::function<void(void*)> callback = std::bind(&CollideDemo::m_onCollision, this, std::placeholders::_1);

    SharedPtr<Rigidbody2D> rbody = physworld->makeRigidbody(spike1.transform());
    spike1.addComponent(RIGIDBODY, rbody);

    float scale = spike1.transform().scale.x;
    tD_pos radius = spike_sprite->getWidth() * scale / 2.0;
    spike1.addComponent(COLLIDER,
        physworld->makeCircleCollider(rbody, &spike1, callback, radius, Vector2<tD_pos>(radius, radius)));

    rbody = physworld->makeRigidbody(spike2.transform());
    spike2.addComponent(RIGIDBODY, rbody);
    scale = spike2.transform().scale.x;
    radius = spike_sprite->getWidth() * scale / 2.0;
    spike2.addComponent(COLLIDER,
        physworld->makeCircleCollider(rbody, &spike2, callback, radius, Vector2<tD_pos>(radius, radius)));

    rbody = physworld->makeRigidbody(zapper1.transform());
    zapper1.addComponent(RIGIDBODY, rbody);
    float partial_width = zapper_anim.sprite_sheet->getWidth() / zapper_anim.columns / 5.0;
    scale = zapper1.transform().scale.x;
    zapper1.addComponent(COLLIDER,
        physworld->makeAABBCollider(rbody, &zapper1, callback,
        Vector2<tD_pos>(partial_width * scale, zapper_anim.sprite_sheet->getHeight() / zapper_anim.rows * scale),
        Vector2<tD_pos>(2 * partial_width * scale, 0)));

    rbody = physworld->makeRigidbody(zapper2.transform());
    zapper2.addComponent(RIGIDBODY, rbody);
    scale = zapper2.transform().scale.x;
    zapper2.addComponent(COLLIDER,
        physworld->makeAABBCollider(rbody, &zapper2, callback,
        Vector2<tD_pos>(partial_width * scale, zapper_anim.sprite_sheet->getHeight() / zapper_anim.rows * scale),
        Vector2<tD_pos>(2 * partial_width * scale, 0)));

}

void CollideDemo::update(tD_delta delta) {
    // zapper1 controls
    if (Input::keydown[Input::K_W]) {
        zapper1.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_S]) {
        zapper1.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_A]) {
        zapper1.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_D]) {
        zapper1.transform().position.x += movespeed * delta;
    }

    // zapper2 controls
    if (Input::keydown[Input::K_UP]) {
        zapper2.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_DOWN]) {
        zapper2.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_LEFT]) {
        zapper2.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_RIGHT]) {
        zapper2.transform().position.x += movespeed * delta;
    }

    // spike2 controls
    if (Input::keydown[Input::K_P8]) {
        spike2.transform().position.y -= movespeed * delta;
    }
    if (Input::keydown[Input::K_P2]) {
        spike2.transform().position.y += movespeed * delta;
    }
    if (Input::keydown[Input::K_P4]) {
        spike2.transform().position.x -= movespeed * delta;
    }
    if (Input::keydown[Input::K_P6]) {
        spike2.transform().position.x += movespeed * delta;
    }

    // update entities
    spike1.updateComponents(delta);
    spike2.updateComponents(delta);
    zapper1.updateComponents(delta);
    zapper2.updateComponents(delta);
}

void CollideDemo::quit() {
    //
}

void CollideDemo::m_onCollision(void *other) {
    Entity *other_entity = (Entity*)other;
    Entity2D *other_entity2d = dynamic_cast<Entity2D*>(other_entity);

    if (other_entity2d)
        other_entity2d->transform().rotation += 20;

    std::cout << "Hit by " << other << std::endl;
}

<|endoftext|>


<commit_before>/*
 *  Copyright 2019-2021 Diligent Graphics LLC
 *  Copyright 2015-2019 Egor Yusov
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#pragma once

#include <vector>
#include <array>
#include <memory>
#include <cfloat>
#include <unordered_map>
#include <mutex>
#include <atomic>

#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/RenderDevice.h"
#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/DeviceContext.h"
#include "../../../DiligentCore/Common/interface/RefCntAutoPtr.hpp"
#include "../../../DiligentCore/Common/interface/AdvancedMath.hpp"
#include "GLTFResourceManager.hpp"

namespace tinygltf
{

class Node;
class Model;

} // namespace tinygltf

namespace Diligent
{

namespace GLTF
{

struct ResourceCacheUseInfo
{
    ResourceManager* pResourceMgr = nullptr;

    Uint8 IndexBufferIdx   = 0;
    Uint8 VertexBuffer0Idx = 0;
    Uint8 VertexBuffer1Idx = 0;

    /// Base color texture format.
    TEXTURE_FORMAT BaseColorFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Base color texture format for alpha-cut and alpha-blend materials.
    TEXTURE_FORMAT BaseColorAlphaFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Physical descriptor texture format.
    TEXTURE_FORMAT PhysicalDescFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Normal map format.
    TEXTURE_FORMAT NormalFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Occlusion texture format.
    TEXTURE_FORMAT OcclusionFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Emissive texture format.
    TEXTURE_FORMAT EmissiveFormat = TEX_FORMAT_RGBA8_UNORM;
};

struct Material
{
    Material() noexcept
    {
        TextureIds.fill(-1);
    }

    enum PBR_WORKFLOW
    {
        PBR_WORKFLOW_METALL_ROUGH = 0,
        PBR_WORKFLOW_SPEC_GLOSS
    };

    enum ALPHA_MODE
    {
        ALPHA_MODE_OPAQUE = 0,
        ALPHA_MODE_MASK,
        ALPHA_MODE_BLEND,
        ALPHA_MODE_NUM_MODES
    };

    // Material attributes packed in a shader-friendly format
    struct ShaderAttribs
    {
        float4 BaseColorFactor = float4{1, 1, 1, 1};
        float4 EmissiveFactor  = float4{1, 1, 1, 1};
        float4 SpecularFactor  = float4{1, 1, 1, 1};

        int   Workflow                     = PBR_WORKFLOW_METALL_ROUGH;
        float BaseColorUVSelector          = -1;
        float PhysicalDescriptorUVSelector = -1;
        float NormalUVSelector             = -1;

        float OcclusionUVSelector     = -1;
        float EmissiveUVSelector      = -1;
        float BaseColorSlice          = 0;
        float PhysicalDescriptorSlice = 0;

        float NormalSlice    = 0;
        float OcclusionSlice = 0;
        float EmissiveSlice  = 0;
        float MetallicFactor = 1;

        float RoughnessFactor = 1;
        int   AlphaMode       = ALPHA_MODE_OPAQUE;
        float AlphaCutoff     = 0.5f;
        float Dummy0;

        // When texture atlas is used, UV scale and bias applied to
        // each texture coordinate set
        float4 BaseColorUVScaleBias          = float4{1, 1, 0, 0};
        float4 PhysicalDescriptorUVScaleBias = float4{1, 1, 0, 0};
        float4 NormalUVScaleBias             = float4{1, 1, 0, 0};
        float4 OcclusionUVScaleBias          = float4{1, 1, 0, 0};
        float4 EmissiveUVScaleBias           = float4{1, 1, 0, 0};
    };
    static_assert(sizeof(ShaderAttribs) % 16 == 0, "ShaderAttribs struct must be 16-byte aligned");
    ShaderAttribs Attribs;

    bool DoubleSided = false;

    enum TEXTURE_ID
    {
        // Base color for metallic-roughness workflow or
        // diffuse color for specular-glossinees workflow
        TEXTURE_ID_BASE_COLOR = 0,

        // Metallic-roughness or specular-glossinees map
        TEXTURE_ID_PHYSICAL_DESC,

        TEXTURE_ID_NORMAL_MAP,
        TEXTURE_ID_OCCLUSION,
        TEXTURE_ID_EMISSIVE,
        TEXTURE_ID_NUM_TEXTURES
    };
    // Texture indices in Model.Textures array
    std::array<int, TEXTURE_ID_NUM_TEXTURES> TextureIds = {};
};

struct Primitive
{
    const Uint32 FirstIndex;
    const Uint32 IndexCount;
    const Uint32 VertexCount;
    const Uint32 MaterialId;

    const BoundBox BB;

    Primitive(Uint32        _FirstIndex,
              Uint32        _IndexCount,
              Uint32        _VertexCount,
              Uint32        _MaterialId,
              const float3& BBMin,
              const float3& BBMax) :
        FirstIndex{_FirstIndex},
        IndexCount{_IndexCount},
        VertexCount{_VertexCount},
        MaterialId{_MaterialId},
        BB{BBMin, BBMax}
    {
    }

    Primitive(Primitive&&) = default;

    bool HasIndices() const
    {
        return IndexCount > 0;
    }
};

struct Mesh
{
    std::vector<Primitive> Primitives;

    BoundBox BB;

    // There may be no primitives in the mesh, in which
    // case the bounding box will be invalid.
    bool IsValidBB() const
    {
        return !Primitives.empty();
    }

    struct TransformData
    {
        float4x4              matrix;
        std::vector<float4x4> jointMatrices;
    };

    TransformData Transforms;

    Mesh(const float4x4& matrix);
};

struct Node;
struct Skin
{
    std::string           Name;
    Node*                 pSkeletonRoot = nullptr;
    std::vector<float4x4> InverseBindMatrices;
    std::vector<Node*>    Joints;
};

struct Camera
{
    enum class Projection
    {
        Unknown,
        Perspective,
        Orthographic
    } Type = Projection::Unknown;

    std::string Name;

    struct PerspectiveAttribs
    {
        float AspectRatio;
        float YFov;
        float ZNear;
        float ZFar;
    };
    struct OrthographicAttribs
    {
        float XMag;
        float YMag;
        float ZNear;
        float ZFar;
    };
    union
    {
        PerspectiveAttribs  Perspective = {};
        OrthographicAttribs Orthographic;
    };

    float4x4 matrix;
};

struct Node
{
    std::string Name;
    Node*       Parent = nullptr;
    Uint32      Index;

    std::vector<std::unique_ptr<Node>> Children;

    float4x4                Matrix;
    std::unique_ptr<Mesh>   pMesh;
    std::unique_ptr<Camera> pCamera;
    Skin*                   pSkin     = nullptr;
    Int32                   SkinIndex = -1;
    float3                  Translation;
    float3                  Scale = float3{1, 1, 1};
    Quaternion              Rotation;
    BoundBox                BVH;
    BoundBox                AABB;

    bool IsValidBVH = false;

    float4x4 LocalMatrix() const;
    float4x4 GetMatrix() const;
    void     UpdateTransforms();
};

struct AnimationChannel
{
    enum PATH_TYPE
    {
        TRANSLATION,
        ROTATION,
        SCALE
    };
    PATH_TYPE PathType;
    Node*     pNode        = nullptr;
    Uint32    SamplerIndex = static_cast<Uint32>(-1);
};

struct AnimationSampler
{
    enum INTERPOLATION_TYPE
    {
        LINEAR,
        STEP,
        CUBICSPLINE
    };
    INTERPOLATION_TYPE  Interpolation;
    std::vector<float>  Inputs;
    std::vector<float4> OutputsVec4;
};

struct Animation
{
    std::string                   Name;
    std::vector<AnimationSampler> Samplers;
    std::vector<AnimationChannel> Channels;

    float Start = std::numeric_limits<float>::max();
    float End   = std::numeric_limits<float>::min();
};

struct Model
{
    struct VertexBasicAttribs
    {
        float3 pos;
        float3 normal;
        float2 uv0;
        float2 uv1;
    };

    struct VertexSkinAttribs
    {
        float4 joint0;
        float4 weight0;
    };

    enum BUFFER_ID
    {
        BUFFER_ID_VERTEX_BASIC_ATTRIBS = 0,
        BUFFER_ID_VERTEX_SKIN_ATTRIBS,
        BUFFER_ID_INDEX,
        BUFFER_ID_NUM_BUFFERS
    };

    Uint32 IndexCount = 0;

    /// Transformation matrix that transforms unit cube [0,1]x[0,1]x[0,1] into
    /// axis-aligned bounding box in model space.
    float4x4 AABBTransform;

    std::vector<std::unique_ptr<Node>> Nodes;
    std::vector<Node*>                 LinearNodes;

    std::vector<std::unique_ptr<Skin>> Skins;

    std::vector<RefCntAutoPtr<ISampler>> TextureSamplers;
    std::vector<Material>                Materials;
    std::vector<Animation>               Animations;
    std::vector<std::string>             Extensions;

    struct Dimensions
    {
        float3 min = float3{+FLT_MAX, +FLT_MAX, +FLT_MAX};
        float3 max = float3{-FLT_MAX, -FLT_MAX, -FLT_MAX};
    } dimensions;

    struct TextureCacheType
    {
        std::mutex TexturesMtx;

        std::unordered_map<std::string, RefCntWeakPtr<ITexture>> Textures;
    };

    /// Model create information
    struct CreateInfo
    {
        /// File name
        const char* FileName = nullptr;

        /// Optional texture cache to use when loading the model.
        /// The loader will try to find all the textures in the cache
        /// and add all new textures to the cache.
        TextureCacheType* pTextureCache = nullptr;

        /// Optional resource cache usage info.
        ResourceCacheUseInfo* pCacheInfo = nullptr;

        /// Whether to load animation and initialize skin attributes
        /// buffer.
        bool LoadAnimationAndSkin = true;

        CreateInfo() = default;

        explicit CreateInfo(const char*           _FileName,
                            TextureCacheType*     _pTextureCache        = nullptr,
                            ResourceCacheUseInfo* _pCacheInfo           = nullptr,
                            bool                  _LoadAnimationAndSkin = true) :
            // clang-format off
            FileName            {_FileName},
            pTextureCache       {_pTextureCache},
            pCacheInfo          {_pCacheInfo},
            LoadAnimationAndSkin{_LoadAnimationAndSkin}
        // clang-format on
        {
        }
    };
    Model(IRenderDevice*    pDevice,
          IDeviceContext*   pContext,
          const CreateInfo& CI);

    ~Model();

    void UpdateAnimation(Uint32 index, float time);

    void PrepareGPUResources(IRenderDevice* pDevice, IDeviceContext* pCtx);

    bool IsGPUDataInitialized() const
    {
        return GPUDataInitialized.load();
    }

    void Transform(const float4x4& Matrix);

    IBuffer* GetBuffer(BUFFER_ID BuffId)
    {
        return Buffers[BuffId].pBuffer;
    }

    ITexture* GetTexture(Uint32 Index)
    {
        return Textures[Index].pTexture;
    }

    Uint32 GetFirstIndexLocation() const
    {
        auto& IndBuff = Buffers[BUFFER_ID_INDEX];
        VERIFY(!IndBuff.pSuballocation || IndBuff.pSuballocation->GetOffset() % sizeof(Uint32) == 0,
               "Allocation offset is not multiple of sizeof(Uint32)");
        return IndBuff.pSuballocation ?
            static_cast<Uint32>(IndBuff.pSuballocation->GetOffset() / sizeof(Uint32)) :
            0;
    }

    Uint32 GetBaseVertex() const
    {
        auto& VertBuff = Buffers[BUFFER_ID_VERTEX_BASIC_ATTRIBS];
        VERIFY(!VertBuff.pSuballocation || VertBuff.pSuballocation->GetOffset() % sizeof(VertexBasicAttribs) == 0,
               "Allocation offset is not multiple of sizeof(VertexAttribs0)");
        return VertBuff.pSuballocation ?
            static_cast<Uint32>(VertBuff.pSuballocation->GetOffset() / sizeof(VertexBasicAttribs)) :
            0;
    }

private:
    void LoadFromFile(IRenderDevice*    pDevice,
                      IDeviceContext*   pContext,
                      const CreateInfo& CI);

    void LoadNode(Node*                            parent,
                  const tinygltf::Node&            gltf_node,
                  uint32_t                         nodeIndex,
                  const tinygltf::Model&           gltf_model,
                  std::vector<Uint32>&             IndexData,
                  std::vector<VertexBasicAttribs>& VertexBasicData,
                  std::vector<VertexSkinAttribs>*  pVertexSkinData);

    void LoadSkins(const tinygltf::Model& gltf_model);

    void LoadTextures(IRenderDevice*         pDevice,
                      const tinygltf::Model& gltf_model,
                      const std::string&     BaseDir,
                      TextureCacheType*      pTextureCache,
                      ResourceManager*       pResourceMgr);

    void  LoadTextureSamplers(IRenderDevice* pDevice, const tinygltf::Model& gltf_model);
    void  LoadMaterials(const tinygltf::Model& gltf_model);
    void  LoadAnimations(const tinygltf::Model& gltf_model);
    void  CalculateBoundingBox(Node* node, const Node* parent);
    void  CalculateSceneDimensions();
    Node* FindNode(Node* parent, Uint32 index);
    Node* NodeFromIndex(uint32_t index);

    std::atomic_bool GPUDataInitialized = false;

    struct BufferInfo
    {
        RefCntAutoPtr<IBuffer>              pBuffer;
        RefCntAutoPtr<IBufferSuballocation> pSuballocation;
    };
    std::array<BufferInfo, BUFFER_ID_NUM_BUFFERS> Buffers;

    struct TextureInfo
    {
        RefCntAutoPtr<ITexture>                   pTexture;
        RefCntAutoPtr<ITextureAtlasSuballocation> pAtlasSuballocation;

        bool IsValid() const
        {
            return pTexture || pAtlasSuballocation;
        }
    };
    std::vector<TextureInfo> Textures;
};

} // namespace GLTF

} // namespace Diligent
<commit_msg>Fixed gcc/clang error<commit_after>/*
 *  Copyright 2019-2021 Diligent Graphics LLC
 *  Copyright 2015-2019 Egor Yusov
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 *  In no event and under no legal theory, whether in tort (including negligence),
 *  contract, or otherwise, unless required by applicable law (such as deliberate
 *  and grossly negligent acts) or agreed to in writing, shall any Contributor be
 *  liable for any damages, including any direct, indirect, special, incidental,
 *  or consequential damages of any character arising as a result of this License or
 *  out of the use or inability to use the software (including but not limited to damages
 *  for loss of goodwill, work stoppage, computer failure or malfunction, or any and
 *  all other commercial damages or losses), even if such Contributor has been advised
 *  of the possibility of such damages.
 */

#pragma once

#include <vector>
#include <array>
#include <memory>
#include <cfloat>
#include <unordered_map>
#include <mutex>
#include <atomic>

#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/RenderDevice.h"
#include "../../../DiligentCore/Graphics/GraphicsEngine/interface/DeviceContext.h"
#include "../../../DiligentCore/Common/interface/RefCntAutoPtr.hpp"
#include "../../../DiligentCore/Common/interface/AdvancedMath.hpp"
#include "GLTFResourceManager.hpp"

namespace tinygltf
{

class Node;
class Model;

} // namespace tinygltf

namespace Diligent
{

namespace GLTF
{

struct ResourceCacheUseInfo
{
    ResourceManager* pResourceMgr = nullptr;

    Uint8 IndexBufferIdx   = 0;
    Uint8 VertexBuffer0Idx = 0;
    Uint8 VertexBuffer1Idx = 0;

    /// Base color texture format.
    TEXTURE_FORMAT BaseColorFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Base color texture format for alpha-cut and alpha-blend materials.
    TEXTURE_FORMAT BaseColorAlphaFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Physical descriptor texture format.
    TEXTURE_FORMAT PhysicalDescFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Normal map format.
    TEXTURE_FORMAT NormalFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Occlusion texture format.
    TEXTURE_FORMAT OcclusionFormat = TEX_FORMAT_RGBA8_UNORM;

    /// Emissive texture format.
    TEXTURE_FORMAT EmissiveFormat = TEX_FORMAT_RGBA8_UNORM;
};

struct Material
{
    Material() noexcept
    {
        TextureIds.fill(-1);
    }

    enum PBR_WORKFLOW
    {
        PBR_WORKFLOW_METALL_ROUGH = 0,
        PBR_WORKFLOW_SPEC_GLOSS
    };

    enum ALPHA_MODE
    {
        ALPHA_MODE_OPAQUE = 0,
        ALPHA_MODE_MASK,
        ALPHA_MODE_BLEND,
        ALPHA_MODE_NUM_MODES
    };

    // Material attributes packed in a shader-friendly format
    struct ShaderAttribs
    {
        float4 BaseColorFactor = float4{1, 1, 1, 1};
        float4 EmissiveFactor  = float4{1, 1, 1, 1};
        float4 SpecularFactor  = float4{1, 1, 1, 1};

        int   Workflow                     = PBR_WORKFLOW_METALL_ROUGH;
        float BaseColorUVSelector          = -1;
        float PhysicalDescriptorUVSelector = -1;
        float NormalUVSelector             = -1;

        float OcclusionUVSelector     = -1;
        float EmissiveUVSelector      = -1;
        float BaseColorSlice          = 0;
        float PhysicalDescriptorSlice = 0;

        float NormalSlice    = 0;
        float OcclusionSlice = 0;
        float EmissiveSlice  = 0;
        float MetallicFactor = 1;

        float RoughnessFactor = 1;
        int   AlphaMode       = ALPHA_MODE_OPAQUE;
        float AlphaCutoff     = 0.5f;
        float Dummy0;

        // When texture atlas is used, UV scale and bias applied to
        // each texture coordinate set
        float4 BaseColorUVScaleBias          = float4{1, 1, 0, 0};
        float4 PhysicalDescriptorUVScaleBias = float4{1, 1, 0, 0};
        float4 NormalUVScaleBias             = float4{1, 1, 0, 0};
        float4 OcclusionUVScaleBias          = float4{1, 1, 0, 0};
        float4 EmissiveUVScaleBias           = float4{1, 1, 0, 0};
    };
    static_assert(sizeof(ShaderAttribs) % 16 == 0, "ShaderAttribs struct must be 16-byte aligned");
    ShaderAttribs Attribs;

    bool DoubleSided = false;

    enum TEXTURE_ID
    {
        // Base color for metallic-roughness workflow or
        // diffuse color for specular-glossinees workflow
        TEXTURE_ID_BASE_COLOR = 0,

        // Metallic-roughness or specular-glossinees map
        TEXTURE_ID_PHYSICAL_DESC,

        TEXTURE_ID_NORMAL_MAP,
        TEXTURE_ID_OCCLUSION,
        TEXTURE_ID_EMISSIVE,
        TEXTURE_ID_NUM_TEXTURES
    };
    // Texture indices in Model.Textures array
    std::array<int, TEXTURE_ID_NUM_TEXTURES> TextureIds = {};
};

struct Primitive
{
    const Uint32 FirstIndex;
    const Uint32 IndexCount;
    const Uint32 VertexCount;
    const Uint32 MaterialId;

    const BoundBox BB;

    Primitive(Uint32        _FirstIndex,
              Uint32        _IndexCount,
              Uint32        _VertexCount,
              Uint32        _MaterialId,
              const float3& BBMin,
              const float3& BBMax) :
        FirstIndex{_FirstIndex},
        IndexCount{_IndexCount},
        VertexCount{_VertexCount},
        MaterialId{_MaterialId},
        BB{BBMin, BBMax}
    {
    }

    Primitive(Primitive&&) = default;

    bool HasIndices() const
    {
        return IndexCount > 0;
    }
};

struct Mesh
{
    std::vector<Primitive> Primitives;

    BoundBox BB;

    // There may be no primitives in the mesh, in which
    // case the bounding box will be invalid.
    bool IsValidBB() const
    {
        return !Primitives.empty();
    }

    struct TransformData
    {
        float4x4              matrix;
        std::vector<float4x4> jointMatrices;
    };

    TransformData Transforms;

    Mesh(const float4x4& matrix);
};

struct Node;
struct Skin
{
    std::string           Name;
    Node*                 pSkeletonRoot = nullptr;
    std::vector<float4x4> InverseBindMatrices;
    std::vector<Node*>    Joints;
};

struct Camera
{
    enum class Projection
    {
        Unknown,
        Perspective,
        Orthographic
    } Type = Projection::Unknown;

    std::string Name;

    struct PerspectiveAttribs
    {
        float AspectRatio;
        float YFov;
        float ZNear;
        float ZFar;
    };
    struct OrthographicAttribs
    {
        float XMag;
        float YMag;
        float ZNear;
        float ZFar;
    };
    union
    {
        PerspectiveAttribs  Perspective = {};
        OrthographicAttribs Orthographic;
    };

    float4x4 matrix;
};

struct Node
{
    std::string Name;
    Node*       Parent = nullptr;
    Uint32      Index;

    std::vector<std::unique_ptr<Node>> Children;

    float4x4                Matrix;
    std::unique_ptr<Mesh>   pMesh;
    std::unique_ptr<Camera> pCamera;
    Skin*                   pSkin     = nullptr;
    Int32                   SkinIndex = -1;
    float3                  Translation;
    float3                  Scale = float3{1, 1, 1};
    Quaternion              Rotation;
    BoundBox                BVH;
    BoundBox                AABB;

    bool IsValidBVH = false;

    float4x4 LocalMatrix() const;
    float4x4 GetMatrix() const;
    void     UpdateTransforms();
};

struct AnimationChannel
{
    enum PATH_TYPE
    {
        TRANSLATION,
        ROTATION,
        SCALE
    };
    PATH_TYPE PathType;
    Node*     pNode        = nullptr;
    Uint32    SamplerIndex = static_cast<Uint32>(-1);
};

struct AnimationSampler
{
    enum INTERPOLATION_TYPE
    {
        LINEAR,
        STEP,
        CUBICSPLINE
    };
    INTERPOLATION_TYPE  Interpolation;
    std::vector<float>  Inputs;
    std::vector<float4> OutputsVec4;
};

struct Animation
{
    std::string                   Name;
    std::vector<AnimationSampler> Samplers;
    std::vector<AnimationChannel> Channels;

    float Start = std::numeric_limits<float>::max();
    float End   = std::numeric_limits<float>::min();
};

struct Model
{
    struct VertexBasicAttribs
    {
        float3 pos;
        float3 normal;
        float2 uv0;
        float2 uv1;
    };

    struct VertexSkinAttribs
    {
        float4 joint0;
        float4 weight0;
    };

    enum BUFFER_ID
    {
        BUFFER_ID_VERTEX_BASIC_ATTRIBS = 0,
        BUFFER_ID_VERTEX_SKIN_ATTRIBS,
        BUFFER_ID_INDEX,
        BUFFER_ID_NUM_BUFFERS
    };

    Uint32 IndexCount = 0;

    /// Transformation matrix that transforms unit cube [0,1]x[0,1]x[0,1] into
    /// axis-aligned bounding box in model space.
    float4x4 AABBTransform;

    std::vector<std::unique_ptr<Node>> Nodes;
    std::vector<Node*>                 LinearNodes;

    std::vector<std::unique_ptr<Skin>> Skins;

    std::vector<RefCntAutoPtr<ISampler>> TextureSamplers;
    std::vector<Material>                Materials;
    std::vector<Animation>               Animations;
    std::vector<std::string>             Extensions;

    struct Dimensions
    {
        float3 min = float3{+FLT_MAX, +FLT_MAX, +FLT_MAX};
        float3 max = float3{-FLT_MAX, -FLT_MAX, -FLT_MAX};
    } dimensions;

    struct TextureCacheType
    {
        std::mutex TexturesMtx;

        std::unordered_map<std::string, RefCntWeakPtr<ITexture>> Textures;
    };

    /// Model create information
    struct CreateInfo
    {
        /// File name
        const char* FileName = nullptr;

        /// Optional texture cache to use when loading the model.
        /// The loader will try to find all the textures in the cache
        /// and add all new textures to the cache.
        TextureCacheType* pTextureCache = nullptr;

        /// Optional resource cache usage info.
        ResourceCacheUseInfo* pCacheInfo = nullptr;

        /// Whether to load animation and initialize skin attributes
        /// buffer.
        bool LoadAnimationAndSkin = true;

        CreateInfo() = default;

        explicit CreateInfo(const char*           _FileName,
                            TextureCacheType*     _pTextureCache        = nullptr,
                            ResourceCacheUseInfo* _pCacheInfo           = nullptr,
                            bool                  _LoadAnimationAndSkin = true) :
            // clang-format off
            FileName            {_FileName},
            pTextureCache       {_pTextureCache},
            pCacheInfo          {_pCacheInfo},
            LoadAnimationAndSkin{_LoadAnimationAndSkin}
        // clang-format on
        {
        }
    };
    Model(IRenderDevice*    pDevice,
          IDeviceContext*   pContext,
          const CreateInfo& CI);

    ~Model();

    void UpdateAnimation(Uint32 index, float time);

    void PrepareGPUResources(IRenderDevice* pDevice, IDeviceContext* pCtx);

    bool IsGPUDataInitialized() const
    {
        return GPUDataInitialized.load();
    }

    void Transform(const float4x4& Matrix);

    IBuffer* GetBuffer(BUFFER_ID BuffId)
    {
        return Buffers[BuffId].pBuffer;
    }

    ITexture* GetTexture(Uint32 Index)
    {
        return Textures[Index].pTexture;
    }

    Uint32 GetFirstIndexLocation() const
    {
        auto& IndBuff = Buffers[BUFFER_ID_INDEX];
        VERIFY(!IndBuff.pSuballocation || IndBuff.pSuballocation->GetOffset() % sizeof(Uint32) == 0,
               "Allocation offset is not multiple of sizeof(Uint32)");
        return IndBuff.pSuballocation ?
            static_cast<Uint32>(IndBuff.pSuballocation->GetOffset() / sizeof(Uint32)) :
            0;
    }

    Uint32 GetBaseVertex() const
    {
        auto& VertBuff = Buffers[BUFFER_ID_VERTEX_BASIC_ATTRIBS];
        VERIFY(!VertBuff.pSuballocation || VertBuff.pSuballocation->GetOffset() % sizeof(VertexBasicAttribs) == 0,
               "Allocation offset is not multiple of sizeof(VertexAttribs0)");
        return VertBuff.pSuballocation ?
            static_cast<Uint32>(VertBuff.pSuballocation->GetOffset() / sizeof(VertexBasicAttribs)) :
            0;
    }

private:
    void LoadFromFile(IRenderDevice*    pDevice,
                      IDeviceContext*   pContext,
                      const CreateInfo& CI);

    void LoadNode(Node*                            parent,
                  const tinygltf::Node&            gltf_node,
                  uint32_t                         nodeIndex,
                  const tinygltf::Model&           gltf_model,
                  std::vector<Uint32>&             IndexData,
                  std::vector<VertexBasicAttribs>& VertexBasicData,
                  std::vector<VertexSkinAttribs>*  pVertexSkinData);

    void LoadSkins(const tinygltf::Model& gltf_model);

    void LoadTextures(IRenderDevice*         pDevice,
                      const tinygltf::Model& gltf_model,
                      const std::string&     BaseDir,
                      TextureCacheType*      pTextureCache,
                      ResourceManager*       pResourceMgr);

    void  LoadTextureSamplers(IRenderDevice* pDevice, const tinygltf::Model& gltf_model);
    void  LoadMaterials(const tinygltf::Model& gltf_model);
    void  LoadAnimations(const tinygltf::Model& gltf_model);
    void  CalculateBoundingBox(Node* node, const Node* parent);
    void  CalculateSceneDimensions();
    Node* FindNode(Node* parent, Uint32 index);
    Node* NodeFromIndex(uint32_t index);

    std::atomic_bool GPUDataInitialized{false};

    struct BufferInfo
    {
        RefCntAutoPtr<IBuffer>              pBuffer;
        RefCntAutoPtr<IBufferSuballocation> pSuballocation;
    };
    std::array<BufferInfo, BUFFER_ID_NUM_BUFFERS> Buffers;

    struct TextureInfo
    {
        RefCntAutoPtr<ITexture>                   pTexture;
        RefCntAutoPtr<ITextureAtlasSuballocation> pAtlasSuballocation;

        bool IsValid() const
        {
            return pTexture || pAtlasSuballocation;
        }
    };
    std::vector<TextureInfo> Textures;
};

} // namespace GLTF

} // namespace Diligent
<|endoftext|>


<commit_before>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */
#include <iostream>
#include <vector>
#include <cstring>
#include <dlfcn.h>
#include <string>
#import <Cocoa/Cocoa.h>
#include "host.h"

namespace kroll
{
	OSXHost::OSXHost(int _argc, const char **_argv) : Host(_argc,_argv)
	{
	}

	OSXHost::~OSXHost()
	{
	}

	const char* OSXHost::GetPlatform()
	{
		return "osx";
	}

	const char* OSXHost::GetModuleSuffix()
	{
		return "module.dylib";
	}

	bool OSXHost::Start()
	{
		Host::Start();
		NSApplication *app = [NSApplication sharedApplication];
		[app finishLaunching];
		return true;
	}

	bool OSXHost::RunLoop()
	{
		NSApplication *app = [NSApplication sharedApplication];
		// we pull out an event from the queue, blocking a little bit before returning
		try
		{
			@try
			{
				NSEvent *event = [app nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate distantPast] inMode:NSDefaultRunLoopMode dequeue:YES];
				if (event)
				{
					[app sendEvent:event];
					[app updateWindows];
				}
			}
			@catch(NSException *e)
			{
				std::cerr << "Caught NSException in main loop: " << [[e reason] UTF8String] << std::endl;
			}
		}
		catch (std::exception &e)
		{
			std::cerr << "Caught exception in main loop: " << e.what() << std::endl;
		}
		catch (...)
		{
			std::cerr << "Caught unhandled exception in main loop: " << std::endl;
		}
		return true;
	}

	Module* OSXHost::CreateModule(std::string& path)
	{
		void* lib_handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
		if (!lib_handle)
		{
			std::cerr << "Error load module: " << path << ", error: " << dlerror() << std::endl;
			return 0;
		}

		// get the module factory
		ModuleCreator* create = (ModuleCreator*)dlsym(lib_handle, "CreateModule");
		if (!create)
		{
			std::cerr << "Error load create entry from module: " << path << std::endl;
			return 0;
		}

		std::string dir = FileUtils::GetDirectory(path);
		return create(this,dir.c_str());
	}
}

@interface KrollMainThreadCaller : NSObject
{
	kroll::BoundMethod *method;
	SharedPtr<kroll::Value> *result;
	const ValueList* args;
	SharedPtr<kroll::Value> *exception;
}
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)method args:(const ValueList*)args;
- (void)call;
- (SharedPtr<kroll::Value>)getResult;
- (SharedPtr<kroll::Value>)getException;
@end

@implementation KrollMainThreadCaller
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)m args:(const ValueList*)a
{
	self = [super init];
	if (self)
	{
		method = m.get();
		args = a;
		result = new SharedPtr<kroll::Value>();
		exception = new SharedPtr<kroll::Value>();
	}
	return self;
}
- (void)dealloc
{
	delete result;
	delete exception;
	[super dealloc];
}
- (SharedPtr<kroll::Value>)getResult
{
	return *result;
}
- (SharedPtr<kroll::Value>)getException
{
	return *exception;
}
- (void)call
{
	try
	{
		result->assign(method->Call(*args));
	}
	catch (ValueException &e)
	{
		exception->assign(e.GetValue());
	}
	catch (std::exception &e)
	{
		exception->assign(Value::NewString(e.what()));
	}
	catch (...)
	{
		exception->assign(Value::NewString("unhandled exception"));
	}
}
@end

@interface NSThread(isMainThreadIsSafeReally)
+ (BOOL) isMainThread;
@end

@interface NSThread(isMainThreadLegacy)
+ (void) TiLegacyGetCurrentThread: (NSMutableData *) currentThreadData;
@end

@implementation NSThread(isMainThreadLegacy)
+ (void) TiLegacyGetCurrentThread: (NSMutableData *) currentThreadData;
{
	NSThread * currentThread = [NSThread currentThread];
	NSRange pointerRange = NSMakeRange(0,sizeof(NSThread *));
	[currentThreadData replaceBytesInRange:pointerRange withBytes:&currentThread]; //This copies the contents of currentThread, not its address.
}
@end

namespace kroll
{
	SharedValue OSXHost::InvokeMethodOnMainThread(SharedBoundMethod method,
	                                              const ValueList& args)
	{
		// make sure to just invoke if we're already on the
		// main thread
		bool isMainThread;
		if ([NSThread respondsToSelector:@selector(isMainThread)]) {
			isMainThread = [NSThread isMainThread];
		} else {
			NSMutableData * mainThreadData= [[NSMutableData alloc] initWithLength:sizeof(NSThread *)];
			[NSThread performSelectorOnMainThread:@selector(TiLegacyGetCurrentThread:) withObject:mainThreadData waitUntilDone:YES];
			NSThread * mainThread = *((id *)[mainThreadData bytes]);
			isMainThread = mainThread == [NSThread currentThread];
		}

		if (isMainThread)
		{
			return method->Call(args);
		}
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		KrollMainThreadCaller *caller = [[[KrollMainThreadCaller alloc] initWithBoundMethod:method args:&args] autorelease];
		[caller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:YES];
		SharedValue exception = [caller getException];
		if (exception.isNull())
		{
			SharedValue result = [caller getResult];
			[pool release];
			return result;
		}
		[pool release];
		return exception;
	}
}

extern "C"
{
	int Execute(int argc,const char **argv)
	{
		kroll::Host *host = new kroll::OSXHost(argc,argv);
		return host->Run();
	}
}
<commit_msg>Disabling Adobe AIR mode (No longer takes up 100% CPU)<commit_after>/**
 * Appcelerator Kroll - licensed under the Apache Public License 2
 * see LICENSE in the root folder for details on the license.
 * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved.
 */
#include <iostream>
#include <vector>
#include <cstring>
#include <dlfcn.h>
#include <string>
#import <Cocoa/Cocoa.h>
#include "host.h"

namespace kroll
{
	OSXHost::OSXHost(int _argc, const char **_argv) : Host(_argc,_argv)
	{
	}

	OSXHost::~OSXHost()
	{
	}

	const char* OSXHost::GetPlatform()
	{
		return "osx";
	}

	const char* OSXHost::GetModuleSuffix()
	{
		return "module.dylib";
	}

	bool OSXHost::Start()
	{
		Host::Start();
		NSApplication *app = [NSApplication sharedApplication];
		[app finishLaunching];
		return true;
	}

	bool OSXHost::RunLoop()
	{
		NSApplication *app = [NSApplication sharedApplication];
		// we pull out an event from the queue, blocking a little bit before returning
		try
		{
			@try
			{
				NSEvent *event = [app nextEventMatchingMask:NSAnyEventMask untilDate:[NSDate dateWithTimeIntervalSinceNow:10.0] inMode:NSDefaultRunLoopMode dequeue:YES];
				if (event)
				{
					[app sendEvent:event];
					[app updateWindows];
				}
			}
			@catch(NSException *e)
			{
				std::cerr << "Caught NSException in main loop: " << [[e reason] UTF8String] << std::endl;
			}
		}
		catch (std::exception &e)
		{
			std::cerr << "Caught exception in main loop: " << e.what() << std::endl;
		}
		catch (...)
		{
			std::cerr << "Caught unhandled exception in main loop: " << std::endl;
		}
		return true;
	}

	Module* OSXHost::CreateModule(std::string& path)
	{
		void* lib_handle = dlopen(path.c_str(), RTLD_LAZY | RTLD_GLOBAL);
		if (!lib_handle)
		{
			std::cerr << "Error load module: " << path << ", error: " << dlerror() << std::endl;
			return 0;
		}

		// get the module factory
		ModuleCreator* create = (ModuleCreator*)dlsym(lib_handle, "CreateModule");
		if (!create)
		{
			std::cerr << "Error load create entry from module: " << path << std::endl;
			return 0;
		}

		std::string dir = FileUtils::GetDirectory(path);
		return create(this,dir.c_str());
	}
}

@interface KrollMainThreadCaller : NSObject
{
	kroll::BoundMethod *method;
	SharedPtr<kroll::Value> *result;
	const ValueList* args;
	SharedPtr<kroll::Value> *exception;
}
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)method args:(const ValueList*)args;
- (void)call;
- (SharedPtr<kroll::Value>)getResult;
- (SharedPtr<kroll::Value>)getException;
@end

@implementation KrollMainThreadCaller
- (id)initWithBoundMethod:(SharedPtr<kroll::BoundMethod>)m args:(const ValueList*)a
{
	self = [super init];
	if (self)
	{
		method = m.get();
		args = a;
		result = new SharedPtr<kroll::Value>();
		exception = new SharedPtr<kroll::Value>();
	}
	return self;
}
- (void)dealloc
{
	delete result;
	delete exception;
	[super dealloc];
}
- (SharedPtr<kroll::Value>)getResult
{
	return *result;
}
- (SharedPtr<kroll::Value>)getException
{
	return *exception;
}
- (void)call
{
	try
	{
		result->assign(method->Call(*args));
	}
	catch (ValueException &e)
	{
		exception->assign(e.GetValue());
	}
	catch (std::exception &e)
	{
		exception->assign(Value::NewString(e.what()));
	}
	catch (...)
	{
		exception->assign(Value::NewString("unhandled exception"));
	}
}
@end

@interface NSThread(isMainThreadIsSafeReally)
+ (BOOL) isMainThread;
@end

@interface NSThread(isMainThreadLegacy)
+ (void) TiLegacyGetCurrentThread: (NSMutableData *) currentThreadData;
@end

@implementation NSThread(isMainThreadLegacy)
+ (void) TiLegacyGetCurrentThread: (NSMutableData *) currentThreadData;
{
	NSThread * currentThread = [NSThread currentThread];
	NSRange pointerRange = NSMakeRange(0,sizeof(NSThread *));
	[currentThreadData replaceBytesInRange:pointerRange withBytes:&currentThread]; //This copies the contents of currentThread, not its address.
}
@end

namespace kroll
{
	SharedValue OSXHost::InvokeMethodOnMainThread(SharedBoundMethod method,
	                                              const ValueList& args)
	{
		// make sure to just invoke if we're already on the
		// main thread
		bool isMainThread;
		if ([NSThread respondsToSelector:@selector(isMainThread)]) {
			isMainThread = [NSThread isMainThread];
		} else {
			NSMutableData * mainThreadData= [[NSMutableData alloc] initWithLength:sizeof(NSThread *)];
			[NSThread performSelectorOnMainThread:@selector(TiLegacyGetCurrentThread:) withObject:mainThreadData waitUntilDone:YES];
			NSThread * mainThread = *((id *)[mainThreadData bytes]);
			isMainThread = mainThread == [NSThread currentThread];
		}

		if (isMainThread)
		{
			return method->Call(args);
		}
		NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
		KrollMainThreadCaller *caller = [[[KrollMainThreadCaller alloc] initWithBoundMethod:method args:&args] autorelease];
		[caller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:YES];
		SharedValue exception = [caller getException];
		if (exception.isNull())
		{
			SharedValue result = [caller getResult];
			[pool release];
			return result;
		}
		[pool release];
		return exception;
	}
}

extern "C"
{
	int Execute(int argc,const char **argv)
	{
		kroll::Host *host = new kroll::OSXHost(argc,argv);
		return host->Run();
	}
}
<|endoftext|>


<commit_before>#include "stdafx.h"

#include "RendererModule.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>

#include "ShaderManager.h"
#include "RenderUtility.h"
#include "Cube.h"

GLuint windowWidth = 800;
GLuint windowHeight = 600;
const char * windowTitle = "Real-timeish Cloud Renderer";

ShaderManager shaderManager;
GLuint billboardShaderProgram;
GLuint raycasterShaderProgram;
GLuint VAOs [2];
GLuint billboardVBO;
GLuint cubeVBO;

RendererModule::RendererModule() {};

bool RendererModule::initialize( int gridX, int gridY, int gridZ ) {

	// Initialize GLFW and opens a window
	if( glfwInit() != GL_TRUE ) {
		return false;
	}

	glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
	glfwOpenWindowHint( GLFW_WINDOW_NO_RESIZE, GL_TRUE );
	glfwOpenWindowHint( GLFW_OPENGL_PROFILE, 0 );

	if (glfwOpenWindow( windowWidth, windowHeight, 0, 0, 0, 0, 24, 8,
		GLFW_WINDOW ) != GL_TRUE) {
			glfwTerminate();
			return false;
	}
	glfwSetWindowTitle( windowTitle );

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if(err != GLEW_OK) {
		std::cerr << "Failed to initialize GLEW: " <<
			glewGetErrorString(err) << "\n";
		return false;
	}

	std::cout << "Running OpenGL version " << glGetString(GL_VERSION) << "\n";

	glGenVertexArrays( 2, VAOs );
	glBindVertexArray( VAOs[0] );

	// Load and compile shaders
	billboardShaderProgram = shaderManager.createFromFile(
		"BillboardShader.vert", "BillboardShader.frag" );
	raycasterShaderProgram = shaderManager.createFromFile(
		"RaycasterShader.vert", "RaycasterShader.frag" );

	initializeTextures();

	// A single billboard data
	float vertexSize = 1.8f;
	float vertices[] = {
		//	Vertex position		      Texcoords
		-vertexSize,  vertexSize, 0.0f, 1.0f,  		// Vertex 1 (-X,  Y)
		-vertexSize, -vertexSize, 0.0f, 0.0f,		// Vertex 2 (-X, -Y)
		 vertexSize,  vertexSize, 1.0f, 1.0f,		// Vertex 3 ( X,  Y)
		 vertexSize,  vertexSize, 1.0f, 1.0f,		// Vertex 3 ( X,  Y)
		-vertexSize, -vertexSize, 0.0f, 0.0f,		// Vertex 2 (-X, -Y)
		 vertexSize, -vertexSize, 1.0f, 0.0f		// Vertex 4 ( X, -Y)
	};

	billboardVBO = createVBO( vertices, sizeof( vertices ) );
	defineBillboardLayout( billboardShaderProgram );

	// Create cube that encapsulates the grid for ray casting
	float cubeVertices[48];
	getCubeVertices( 0, gridX, 0, gridY, 0, gridZ, cubeVertices );

	cubeVBO = createVBO( cubeVertices, sizeof( cubeVertices )) ;
	glBindVertexArray( VAOs[1] );
	defineRaycasterLayout( raycasterShaderProgram );

	int cubeElements[36];
	getCubeElements( cubeElements );
	createEBO( cubeElements, sizeof( cubeElements ));

	// Initialize the camera and the projetion matrices
	camera.initialize( gridX, gridY, gridZ );
	perspectiveProjection = glm::perspective( 85.0f,
		(float)windowWidth / (float)windowHeight, 0.4f, 300.0f );
	orthographicProjection = glm::ortho( -(gridX/2.0f), gridX/2.0f,
		-(gridY/2.0f), gridY/2.0f, 0.0f, 500.0f );

	// Set the sun position and sun position matrix (looking at the center of
	// the cloud)
	sunPosition = glm::vec3( 300, 250, 250 );
	glm::vec3 lookAtPoint = glm::vec3( gridX/2, gridY/2, -gridZ/2 );
	sunTransformation = glm::lookAt( sunPosition,
		lookAtPoint, glm::vec3(0, 0, 1));

	return true;

}

void RendererModule::defineBillboardLayout( GLuint billboardShaderProgram ) {

	// Define data layout
	GLint posAttrib = glGetAttribLocation( billboardShaderProgram,
		"vertPos" );
	glEnableVertexAttribArray( posAttrib );
	glVertexAttribPointer( posAttrib, 2, GL_FLOAT, GL_FALSE,
		4*sizeof(float), 0 );

	GLint texAttrib = glGetAttribLocation( billboardShaderProgram,
		"texCoord" );
	glEnableVertexAttribArray( texAttrib );
	glVertexAttribPointer( texAttrib, 2, GL_FLOAT, GL_FALSE,
		4*sizeof(float), (void*)( 2*sizeof(float) ) );

}

void RendererModule::defineRaycasterLayout( GLuint raycasterShaderProgram ) {

	GLint posAttrib = glGetAttribLocation( raycasterShaderProgram,
		"cubeVert" );
	glEnableVertexAttribArray( posAttrib );
	glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE,
		6*sizeof(float), 0 );

	GLint colAttrib = glGetAttribLocation( raycasterShaderProgram,
		"startColor" );
	glEnableVertexAttribArray( colAttrib );
	glVertexAttribPointer( colAttrib, 3, GL_FLOAT, GL_FALSE,
		6*sizeof(float), (void*)( 3*sizeof(float) ) );
}

void RendererModule::draw( SimulationData* data, GLFWmutex simMutex, double time ) {

	// Update the camera
	camera.updateCamera();

	// Clear the screen with background (sky) color
	glClearColor( 155/256.0f, 225/256.0f, 251/256.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	// Lock mutex because we will use data, which is shared with simulation
	glfwLockMutex( simMutex );

	renderRayCastingClouds( data, time );

	renderSplattingClouds( data, time );

	glfwUnlockMutex( simMutex );

	// Check for errors
	GLint glErr = glGetError();
	if ( glErr ) std::cout << "OpenGL error " << glErr << "!\n";

	// Swap the buffer
	glfwSwapBuffers();

}

// Shade clouds by performing volume ray casting
void RendererModule::renderRayCastingClouds( SimulationData* data,
											double time ) {

	glBindVertexArray( VAOs[1] );
	glUseProgram( raycasterShaderProgram );

	setUniform( "view", camera.getLookAtMatrix() );
	setUniform( "proj", perspectiveProjection );
	setUniform( "viewDirection", camera.getViewDirection() );

	glEnable( GL_CULL_FACE );
	glEnable( GL_DEPTH_TEST );

	int x = data->getGridLength();
	int y = data->getGridWidth();
	int z = data->getGridHeight();

	// Convert float*** to float* (stream of data)
	float* texData = new float[x*y*z];
	int pos = 0;
	for( int i = 0; i != x; ++i ) // TODO: might be wrong order
		for( int j = 0; j != y; ++j )
			for( int k = 0; k != z; ++k ) {
				texData[pos] = data->prevDen[i][j][k]; //TODO: interpolate
				++pos;
			}

	// Fill the data into 3D texture. A texture cell includes only one
	// component (GL_RED = density, float).
	glTexImage3D( GL_TEXTURE_3D, 0, GL_R32F, x, y, z, 0, GL_RED,
		GL_FLOAT, texData );

	delete[] texData;

	glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 );

}

void RendererModule::renderSplattingClouds( SimulationData* data, double time ) {

	glBindVertexArray( VAOs[0] );
	glUseProgram( billboardShaderProgram );

	setUniform( "view", camera.getLookAtMatrix() );
	setUniform( "proj", perspectiveProjection );

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable( GL_BLEND );
	glDisable( GL_CULL_FACE );
	glDisable( GL_DEPTH_TEST );

	GLint uniPosition = glGetUniformLocation( billboardShaderProgram, "position" );
	GLint uniAlpha = glGetUniformLocation( billboardShaderProgram, "alpha" );

	int x = data->getGridLength();
	int y = data->getGridWidth();
	int z = data->getGridHeight();

	// Calculate relative difference for linear interpolation
	float relDiff = (time - data->nextTime)/(data->nextTime - data->prevTime);
	if( relDiff > 1.0f )relDiff = 1.0f;

	for( int i = 0; i < x; ++i )
		for( int j = 0; j < y; ++j )
			for( int k = 0; k < z; ++k )
				if( data->nextDen[i][j][k] > 0.0f ) {

					// Lineary interpolate the density
					float density = data->prevDen[i][j][k] + relDiff
						* (data->nextDen[i][j][k] - data->prevDen[i][j][k] );

					if( density > 0.0f) {
						// Build a translation (model) matrix in the shader,
						// because it's a lot faster than creating the matrix
						// here.
						glUniform3f( uniPosition, i, j, -k );
						glUniform1f( uniAlpha, density );

						glDrawArrays( GL_TRIANGLES, 0, 6 );
					}
				}
}

void RendererModule::terminate() {

	glDeleteProgram( billboardShaderProgram );
	shaderManager.terminate();
	glDeleteVertexArrays( 2, VAOs );
	deleteTextures();

	// Terminate GLFW
	glfwTerminate();

}<commit_msg>Restricted OpenGL to core profile<commit_after>#include "stdafx.h"

#include "RendererModule.h"

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <iostream>

#include "ShaderManager.h"
#include "RenderUtility.h"
#include "Cube.h"

GLuint windowWidth = 800;
GLuint windowHeight = 600;
const char * windowTitle = "Real-timeish Cloud Renderer";

ShaderManager shaderManager;
GLuint billboardShaderProgram;
GLuint raycasterShaderProgram;
GLuint VAOs [2];
GLuint billboardVBO;
GLuint cubeVBO;

RendererModule::RendererModule() {};

bool RendererModule::initialize( int gridX, int gridY, int gridZ ) {

	// Initialize GLFW and opens a window
	if( glfwInit() != GL_TRUE ) {
		return false;
	}

	glfwOpenWindowHint( GLFW_OPENGL_VERSION_MAJOR, 3 );
	glfwOpenWindowHint( GLFW_OPENGL_VERSION_MINOR, 2 );
	glfwOpenWindowHint( GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE );
	glfwOpenWindowHint( GLFW_WINDOW_NO_RESIZE, GL_TRUE );

	if (glfwOpenWindow( windowWidth, windowHeight, 0, 0, 0, 0, 24, 8,
		GLFW_WINDOW ) != GL_TRUE) {
			glfwTerminate();
			return false;
	}

	glfwSetWindowTitle( windowTitle );

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	GLenum err = glewInit();
	if(err != GLEW_OK) {
		std::cerr << "Failed to initialize GLEW: " <<
			glewGetErrorString(err) << "\n";
		return false;
	}
	// Ignore the OpenGL error (1280) that glewInit() causes
	glGetError();

	std::cout << "Running OpenGL version " << glGetString(GL_VERSION) << "\n";

	glGenVertexArrays( 2, VAOs );
	glBindVertexArray( VAOs[0] );

	// Load and compile shaders
	billboardShaderProgram = shaderManager.createFromFile(
		"BillboardShader.vert", "BillboardShader.frag" );
	raycasterShaderProgram = shaderManager.createFromFile(
		"RaycasterShader.vert", "RaycasterShader.frag" );

	initializeTextures();

	// A single billboard data
	float vertexSize = 1.8f;
	float vertices[] = {
		//	Vertex position		      Texcoords
		-vertexSize,  vertexSize, 0.0f, 1.0f,  		// Vertex 1 (-X,  Y)
		-vertexSize, -vertexSize, 0.0f, 0.0f,		// Vertex 2 (-X, -Y)
		 vertexSize,  vertexSize, 1.0f, 1.0f,		// Vertex 3 ( X,  Y)
		 vertexSize,  vertexSize, 1.0f, 1.0f,		// Vertex 3 ( X,  Y)
		-vertexSize, -vertexSize, 0.0f, 0.0f,		// Vertex 2 (-X, -Y)
		 vertexSize, -vertexSize, 1.0f, 0.0f		// Vertex 4 ( X, -Y)
	};

	billboardVBO = createVBO( vertices, sizeof( vertices ) );
	defineBillboardLayout( billboardShaderProgram );

	// Create cube that encapsulates the grid for ray casting
	float cubeVertices[48];
	getCubeVertices( 0, gridX, 0, gridY, 0, gridZ, cubeVertices );

	cubeVBO = createVBO( cubeVertices, sizeof( cubeVertices )) ;
	glBindVertexArray( VAOs[1] );
	defineRaycasterLayout( raycasterShaderProgram );

	int cubeElements[36];
	getCubeElements( cubeElements );
	createEBO( cubeElements, sizeof( cubeElements ));

	// Initialize the camera and the projetion matrices
	camera.initialize( gridX, gridY, gridZ );
	perspectiveProjection = glm::perspective( 85.0f,
		(float)windowWidth / (float)windowHeight, 0.4f, 300.0f );
	orthographicProjection = glm::ortho( -(gridX/2.0f), gridX/2.0f,
		-(gridY/2.0f), gridY/2.0f, 0.0f, 500.0f );

	// Set the sun position and sun position matrix (looking at the center of
	// the cloud)
	sunPosition = glm::vec3( 300, 250, 250 );
	glm::vec3 lookAtPoint = glm::vec3( gridX/2, gridY/2, -gridZ/2 );
	sunTransformation = glm::lookAt( sunPosition,
		lookAtPoint, glm::vec3(0, 0, 1));

	return true;

}

void RendererModule::defineBillboardLayout( GLuint billboardShaderProgram ) {

	// Define data layout
	GLint posAttrib = glGetAttribLocation( billboardShaderProgram,
		"vertPos" );
	glEnableVertexAttribArray( posAttrib );
	glVertexAttribPointer( posAttrib, 2, GL_FLOAT, GL_FALSE,
		4*sizeof(float), 0 );

	GLint texAttrib = glGetAttribLocation( billboardShaderProgram,
		"texCoord" );
	glEnableVertexAttribArray( texAttrib );
	glVertexAttribPointer( texAttrib, 2, GL_FLOAT, GL_FALSE,
		4*sizeof(float), (void*)( 2*sizeof(float) ) );

}

void RendererModule::defineRaycasterLayout( GLuint raycasterShaderProgram ) {

	GLint posAttrib = glGetAttribLocation( raycasterShaderProgram,
		"cubeVert" );
	glEnableVertexAttribArray( posAttrib );
	glVertexAttribPointer( posAttrib, 3, GL_FLOAT, GL_FALSE,
		6*sizeof(float), 0 );

	GLint colAttrib = glGetAttribLocation( raycasterShaderProgram,
		"startColor" );
	glEnableVertexAttribArray( colAttrib );
	glVertexAttribPointer( colAttrib, 3, GL_FLOAT, GL_FALSE,
		6*sizeof(float), (void*)( 3*sizeof(float) ) );
}

void RendererModule::draw( SimulationData* data, GLFWmutex simMutex, double time ) {

	// Update the camera
	camera.updateCamera();

	// Clear the screen with background (sky) color
	glClearColor( 155/256.0f, 225/256.0f, 251/256.0f, 1.0f );
	glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );

	// Lock mutex because we will use data, which is shared with simulation
	glfwLockMutex( simMutex );

	renderRayCastingClouds( data, time );

	renderSplattingClouds( data, time );

	glfwUnlockMutex( simMutex );

	// Check for errors
	GLint glErr = glGetError();
	if ( glErr ) std::cout << "OpenGL error " << glErr << "!\n";

	// Swap the buffer
	glfwSwapBuffers();

}

// Shade clouds by performing volume ray casting
void RendererModule::renderRayCastingClouds( SimulationData* data,
											double time ) {

	glBindVertexArray( VAOs[1] );
	glUseProgram( raycasterShaderProgram );

	setUniform( "view", camera.getLookAtMatrix() );
	setUniform( "proj", perspectiveProjection );
	setUniform( "viewDirection", camera.getViewDirection() );

	glEnable( GL_CULL_FACE );
	glEnable( GL_DEPTH_TEST );

	int x = data->getGridLength();
	int y = data->getGridWidth();
	int z = data->getGridHeight();

	// Convert float*** to float* (stream of data)
	float* texData = new float[x*y*z];
	int pos = 0;
	for( int i = 0; i != x; ++i ) // TODO: might be wrong order
		for( int j = 0; j != y; ++j )
			for( int k = 0; k != z; ++k ) {
				texData[pos] = data->prevDen[i][j][k]; //TODO: interpolate
				++pos;
			}

	// Fill the data into 3D texture. A texture cell includes only one
	// component (GL_RED = density, float).
	glTexImage3D( GL_TEXTURE_3D, 0, GL_R32F, x, y, z, 0, GL_RED,
		GL_FLOAT, texData );

	delete[] texData;

	glDrawElements( GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0 );

}

void RendererModule::renderSplattingClouds( SimulationData* data, double time ) {

	glBindVertexArray( VAOs[0] );
	glUseProgram( billboardShaderProgram );

	setUniform( "view", camera.getLookAtMatrix() );
	setUniform( "proj", perspectiveProjection );

	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable( GL_BLEND );
	glDisable( GL_CULL_FACE );
	glDisable( GL_DEPTH_TEST );

	GLint uniPosition = glGetUniformLocation( billboardShaderProgram, "position" );
	GLint uniAlpha = glGetUniformLocation( billboardShaderProgram, "alpha" );

	int x = data->getGridLength();
	int y = data->getGridWidth();
	int z = data->getGridHeight();

	// Calculate relative difference for linear interpolation
	float relDiff = (time - data->nextTime)/(data->nextTime - data->prevTime);
	if( relDiff > 1.0f )relDiff = 1.0f;

	for( int i = 0; i < x; ++i )
		for( int j = 0; j < y; ++j )
			for( int k = 0; k < z; ++k )
				if( data->nextDen[i][j][k] > 0.0f ) {

					// Lineary interpolate the density
					float density = data->prevDen[i][j][k] + relDiff
						* (data->nextDen[i][j][k] - data->prevDen[i][j][k] );

					if( density > 0.0f) {
						// Build a translation (model) matrix in the shader,
						// because it's a lot faster than creating the matrix
						// here.
						glUniform3f( uniPosition, i, j, -k );
						glUniform1f( uniAlpha, density );

						glDrawArrays( GL_TRIANGLES, 0, 6 );
					}
				}
}

void RendererModule::terminate() {

	glDeleteProgram( billboardShaderProgram );
	shaderManager.terminate();
	glDeleteVertexArrays( 2, VAOs );
	deleteTextures();

	// Terminate GLFW
	glfwTerminate();

}<|endoftext|>