<commit_before>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "InstanceScript.h"
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "TemporarySummon.h"
#include "molten_core.h"

MinionData const minionData[] =
{
    { NPC_FIRESWORN,                DATA_GARR },
    { NPC_FLAMEWALKER,              DATA_GEHENNAS },
    { NPC_FLAMEWALKER_PROTECTOR,    DATA_LUCIFRON },
    { NPC_FLAMEWALKER_PRIEST,       DATA_SULFURON },
    { NPC_FLAMEWALKER_HEALER,       DATA_MAJORDOMO_EXECUTUS },
    { NPC_FLAMEWALKER_ELITE,        DATA_MAJORDOMO_EXECUTUS },
    { 0, 0 } // END
};

struct MCBossObject
{
    uint32 bossId;
    uint32 runeId;
    uint32 circleId;
};

constexpr uint8 MAX_MC_LINKED_BOSS_OBJ = 7;
MCBossObject const linkedBossObjData[MAX_MC_LINKED_BOSS_OBJ]=
{
    { DATA_MAGMADAR,    GO_RUNE_KRESS,      GO_CIRCLE_MAGMADAR  },
    { DATA_GEHENNAS,    GO_RUNE_MOHN,       GO_CIRCLE_GEHENNAS  },
    { DATA_GARR,        GO_RUNE_BLAZ,       GO_CIRCLE_GARR      },
    { DATA_SHAZZRAH,    GO_RUNE_MAZJ,       GO_CIRCLE_SHAZZRAH  },
    { DATA_GEDDON,      GO_RUNE_ZETH,       GO_CIRCLE_GEDDON    },
    { DATA_GOLEMAGG,    GO_RUNE_THERI,      GO_CIRCLE_GOLEMAGG  },
    { DATA_SULFURON,    GO_RUNE_KORO,       GO_CIRCLE_SULFURON  },
};

constexpr uint8 SAY_SPAWN = 1;

class instance_molten_core : public InstanceMapScript
{
public:
    instance_molten_core() : InstanceMapScript(MCScriptName, 409) {}

    struct instance_molten_core_InstanceMapScript : public InstanceScript
    {
        instance_molten_core_InstanceMapScript(Map* map) : InstanceScript(map)
        {
            SetBossNumber(MAX_ENCOUNTER);
            LoadMinionData(minionData);
        }

        void OnPlayerEnter(Player* /*player*/) override
        {
            if (CheckMajordomoExecutus())
            {
                SummonMajordomoExecutus();
            }
        }

        void OnCreatureCreate(Creature* creature) override
        {
            switch (creature->GetEntry())
            {
                case NPC_GOLEMAGG_THE_INCINERATOR:
                {
                    _golemaggGUID = creature->GetGUID();
                    break;
                }
                case NPC_CORE_RAGER:
                {
                    _golemaggMinionsGUIDS.insert(creature->GetGUID());
                    break;
                }
                case NPC_MAJORDOMO_EXECUTUS:
                {
                    _majordomoExecutusGUID = creature->GetGUID();
                    break;
                }
                case NPC_GARR:
                {
                    _garrGUID = creature->GetGUID();
                    break;
                }
                case NPC_RAGNAROS:
                {
                    _ragnarosGUID = creature->GetGUID();
                    break;
                }
                case NPC_FIRESWORN:
                case NPC_FLAMEWALKER:
                case NPC_FLAMEWALKER_PROTECTOR:
                case NPC_FLAMEWALKER_PRIEST:
                case NPC_FLAMEWALKER_HEALER:
                case NPC_FLAMEWALKER_ELITE:
                {
                    AddMinion(creature, true);
                    break;
                }
            }
        }

        void OnCreatureRemove(Creature* creature) override
        {
            switch (creature->GetEntry())
            {
                case NPC_FIRESWORN:
                {
                    AddMinion(creature, false);
                    break;
                }
                case NPC_FLAMEWALKER:
                case NPC_FLAMEWALKER_PROTECTOR:
                case NPC_FLAMEWALKER_PRIEST:
                case NPC_FLAMEWALKER_HEALER:
                case NPC_FLAMEWALKER_ELITE:
                {
                    AddMinion(creature, false);
                    break;
                }
            }
        }

        void OnGameObjectCreate(GameObject* go) override
        {
            switch (go->GetEntry())
            {
                case GO_CACHE_OF_THE_FIRELORD:
                {
                    _cacheOfTheFirelordGUID = go->GetGUID();
                    break;
                }
                case GO_CIRCLE_GEDDON:
                case GO_CIRCLE_GARR:
                case GO_CIRCLE_GEHENNAS:
                case GO_CIRCLE_GOLEMAGG:
                case GO_CIRCLE_MAGMADAR:
                case GO_CIRCLE_SHAZZRAH:
                case GO_CIRCLE_SULFURON:
                {
                    for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i)
                    {
                        if (linkedBossObjData[i].circleId != go->GetEntry())
                        {
                            continue;
                        }

                        if (GetBossState(linkedBossObjData[i].bossId) == DONE)
                        {
                            go->DespawnOrUnsummon();
                        }
                        else
                        {
                            _circlesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID();
                        }
                    }

                    break;
                }
                case GO_RUNE_KRESS:
                case GO_RUNE_MOHN:
                case GO_RUNE_BLAZ:
                case GO_RUNE_MAZJ:
                case GO_RUNE_ZETH:
                case GO_RUNE_THERI:
                case GO_RUNE_KORO:
                {
                    for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i)
                    {
                        if (linkedBossObjData[i].runeId != go->GetEntry())
                        {
                            continue;
                        }

                        if (GetBossState(linkedBossObjData[i].bossId) == DONE)
                        {
                            go->SetGoState(GO_STATE_ACTIVE);
                        }
                        else
                        {
                            _runesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID();
                        }
                    }
                    break;
                }
                case GO_LAVA_STEAM:
                {
                    _lavaSteamGUID = go->GetGUID();
                    break;
                }
                case GO_LAVA_SPLASH:
                {
                    _lavaSplashGUID = go->GetGUID();
                    break;
                }
                case GO_LAVA_BURST:
                {
                    if (Creature* ragnaros = instance->GetCreature(_ragnarosGUID))
                    {
                        ragnaros->AI()->SetGUID(go->GetGUID(), GO_LAVA_BURST);
                    }
                    break;
                }
            }
        }

        ObjectGuid GetGuidData(uint32 type) const override
        {
            switch (type)
            {
                case DATA_GOLEMAGG:
                    return _golemaggGUID;
                case DATA_MAJORDOMO_EXECUTUS:
                    return _majordomoExecutusGUID;
                case DATA_GARR:
                    return _garrGUID;
                case DATA_LAVA_STEAM:
                    return _lavaSteamGUID;
                case DATA_LAVA_SPLASH:
                    return _lavaSplashGUID;
                case DATA_RAGNAROS:
                    return _ragnarosGUID;
            }

            return ObjectGuid::Empty;
        }

        bool SetBossState(uint32 bossId, EncounterState state) override
        {
            if (!InstanceScript::SetBossState(bossId, state))
            {
                return false;
            }

            if (bossId == DATA_MAJORDOMO_EXECUTUS && state == DONE)
            {
                DoRespawnGameObject(_cacheOfTheFirelordGUID, 7 * DAY);
            }
            else if (bossId == DATA_GOLEMAGG)
            {
                switch (state)
                {
                    case NOT_STARTED:
                    case FAIL:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                Creature* minion = instance->GetCreature(minionGuid);
                                if (minion && minion->isDead())
                                {
                                    minion->Respawn();
                                }
                            }
                        }
                        break;
                    }
                    case IN_PROGRESS:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                if (Creature* minion = instance->GetCreature(minionGuid))
                                {
                                    minion->AI()->DoZoneInCombat(nullptr, 150.0f);
                                }
                            }
                        }
                        break;
                    }
                    case DONE:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                if (Creature* minion = instance->GetCreature(minionGuid))
                                {
                                    minion->CastSpell(minion, SPELL_CORE_RAGER_QUIET_SUICIDE, true);
                                }
                            }
                            _golemaggMinionsGUIDS.clear();
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            // Perform needed checks for Majordomu
            if (bossId < DATA_MAJORDOMO_EXECUTUS && state == DONE)
            {
                if (GameObject* circle = instance->GetGameObject(_circlesGUIDs[bossId]))
                {
                    circle->DespawnOrUnsummon();
                    _circlesGUIDs[bossId].Clear();
                }

                if (GameObject* rune = instance->GetGameObject(_runesGUIDs[bossId]))
                {
                    rune->SetGoState(GO_STATE_ACTIVE);
                    _runesGUIDs[bossId].Clear();
                }

                if (CheckMajordomoExecutus())
                {
                    SummonMajordomoExecutus();
                }
            }

            return true;
        }

        void DoAction(int32 action) override
        {
            if (action == ACTION_RESET_GOLEMAGG_ENCOUNTER)
            {
                if (Creature* golemagg = instance->GetCreature(_golemaggGUID))
                {
                    golemagg->AI()->EnterEvadeMode();
                }

                if (!_golemaggMinionsGUIDS.empty())
                {
                    for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                    {
                        if (Creature* minion = instance->GetCreature(minionGuid))
                        {
                            minion->AI()->EnterEvadeMode();
                        }
                    }
                }
            }
        }

        void SummonMajordomoExecutus()
        {
            if (instance->GetCreature(_majordomoExecutusGUID))
            {
                return;
            }

            if (GetBossState(DATA_MAJORDOMO_EXECUTUS) != DONE)
            {
                if (Creature* creature = instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoSummonPos))
                {
                    creature->AI()->Talk(SAY_SPAWN);
                }
            }
            else
            {
                instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoRagnaros);
            }
        }

        bool CheckMajordomoExecutus() const
        {
            if (GetBossState(DATA_RAGNAROS) == DONE)
            {
                return false;
            }

            for (uint8 i = 0; i < DATA_MAJORDOMO_EXECUTUS; ++i)
            {
                if (i == DATA_LUCIFRON)
                {
                    continue;
                }

                if (GetBossState(i) != DONE)
                {
                    return false;
                }
            }

            // Prevent spawning if Ragnaros is present
            if (instance->GetCreature(_ragnarosGUID))
            {
                return false;
            }

            return true;
        }

        std::string GetSaveData() override
        {
            OUT_SAVE_INST_DATA;

            std::ostringstream saveStream;
            saveStream << "M C " << GetBossSaveData();

            OUT_SAVE_INST_DATA_COMPLETE;
            return saveStream.str();
        }

        void Load(char const* data) override
        {
            if (!data)
            {
                OUT_LOAD_INST_DATA_FAIL;
                return;
            }

            OUT_LOAD_INST_DATA(data);

            char dataHead1, dataHead2;

            std::istringstream loadStream(data);
            loadStream >> dataHead1 >> dataHead2;

            if (dataHead1 == 'M' && dataHead2 == 'C')
            {
                for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
                {
                    uint32 tmpState;
                    loadStream >> tmpState;
                    if (tmpState == IN_PROGRESS || tmpState > TO_BE_DECIDED)
                    {
                        tmpState = NOT_STARTED;
                    }

                    SetBossState(i, static_cast<EncounterState>(tmpState));
                }

                if (CheckMajordomoExecutus())
                {
                    SummonMajordomoExecutus();
                }
            }
            else
            {
                OUT_LOAD_INST_DATA_FAIL;
            }

            OUT_LOAD_INST_DATA_COMPLETE;
        }

    private:
        std::unordered_map<uint32/*bossid*/, ObjectGuid/*circleGUID*/> _circlesGUIDs;
        std::unordered_map<uint32/*bossid*/, ObjectGuid/*runeGUID*/> _runesGUIDs;

        // Golemagg encounter related
        ObjectGuid _golemaggGUID;
        GuidSet _golemaggMinionsGUIDS;

        // Ragnaros encounter related
        ObjectGuid _ragnarosGUID;
        ObjectGuid _lavaSteamGUID;
        ObjectGuid _lavaSplashGUID;

        ObjectGuid _majordomoExecutusGUID;
        ObjectGuid _cacheOfTheFirelordGUID;
        ObjectGuid _garrGUID;
        ObjectGuid _magmadarGUID;
    };

    InstanceScript* GetInstanceScript(InstanceMap* map) const override
    {
        return new instance_molten_core_InstanceMapScript(map);
    }
};

void AddSC_instance_molten_core()
{
    new instance_molten_core();
}
<commit_msg>fix(Scripts/MoltenCore): Boss' runes should not respawn after 5 min o… (#13127)<commit_after>/*
 * This file is part of the AzerothCore Project. See AUTHORS file for Copyright information
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Affero General Public License as published by the
 * Free Software Foundation; either version 3 of the License, or (at your
 * option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */

#include "InstanceScript.h"
#include "ObjectMgr.h"
#include "ScriptMgr.h"
#include "TemporarySummon.h"
#include "molten_core.h"

MinionData const minionData[] =
{
    { NPC_FIRESWORN,                DATA_GARR },
    { NPC_FLAMEWALKER,              DATA_GEHENNAS },
    { NPC_FLAMEWALKER_PROTECTOR,    DATA_LUCIFRON },
    { NPC_FLAMEWALKER_PRIEST,       DATA_SULFURON },
    { NPC_FLAMEWALKER_HEALER,       DATA_MAJORDOMO_EXECUTUS },
    { NPC_FLAMEWALKER_ELITE,        DATA_MAJORDOMO_EXECUTUS },
    { 0, 0 } // END
};

struct MCBossObject
{
    uint32 bossId;
    uint32 runeId;
    uint32 circleId;
};

constexpr uint8 MAX_MC_LINKED_BOSS_OBJ = 7;
MCBossObject const linkedBossObjData[MAX_MC_LINKED_BOSS_OBJ]=
{
    { DATA_MAGMADAR,    GO_RUNE_KRESS,      GO_CIRCLE_MAGMADAR  },
    { DATA_GEHENNAS,    GO_RUNE_MOHN,       GO_CIRCLE_GEHENNAS  },
    { DATA_GARR,        GO_RUNE_BLAZ,       GO_CIRCLE_GARR      },
    { DATA_SHAZZRAH,    GO_RUNE_MAZJ,       GO_CIRCLE_SHAZZRAH  },
    { DATA_GEDDON,      GO_RUNE_ZETH,       GO_CIRCLE_GEDDON    },
    { DATA_GOLEMAGG,    GO_RUNE_THERI,      GO_CIRCLE_GOLEMAGG  },
    { DATA_SULFURON,    GO_RUNE_KORO,       GO_CIRCLE_SULFURON  },
};

constexpr uint8 SAY_SPAWN = 1;

class instance_molten_core : public InstanceMapScript
{
public:
    instance_molten_core() : InstanceMapScript(MCScriptName, 409) {}

    struct instance_molten_core_InstanceMapScript : public InstanceScript
    {
        instance_molten_core_InstanceMapScript(Map* map) : InstanceScript(map)
        {
            SetBossNumber(MAX_ENCOUNTER);
            LoadMinionData(minionData);
        }

        void OnPlayerEnter(Player* /*player*/) override
        {
            if (CheckMajordomoExecutus())
            {
                SummonMajordomoExecutus();
            }
        }

        void OnCreatureCreate(Creature* creature) override
        {
            switch (creature->GetEntry())
            {
                case NPC_GOLEMAGG_THE_INCINERATOR:
                {
                    _golemaggGUID = creature->GetGUID();
                    break;
                }
                case NPC_CORE_RAGER:
                {
                    _golemaggMinionsGUIDS.insert(creature->GetGUID());
                    break;
                }
                case NPC_MAJORDOMO_EXECUTUS:
                {
                    _majordomoExecutusGUID = creature->GetGUID();
                    break;
                }
                case NPC_GARR:
                {
                    _garrGUID = creature->GetGUID();
                    break;
                }
                case NPC_RAGNAROS:
                {
                    _ragnarosGUID = creature->GetGUID();
                    break;
                }
                case NPC_FIRESWORN:
                case NPC_FLAMEWALKER:
                case NPC_FLAMEWALKER_PROTECTOR:
                case NPC_FLAMEWALKER_PRIEST:
                case NPC_FLAMEWALKER_HEALER:
                case NPC_FLAMEWALKER_ELITE:
                {
                    AddMinion(creature, true);
                    break;
                }
            }
        }

        void OnCreatureRemove(Creature* creature) override
        {
            switch (creature->GetEntry())
            {
                case NPC_FIRESWORN:
                {
                    AddMinion(creature, false);
                    break;
                }
                case NPC_FLAMEWALKER:
                case NPC_FLAMEWALKER_PROTECTOR:
                case NPC_FLAMEWALKER_PRIEST:
                case NPC_FLAMEWALKER_HEALER:
                case NPC_FLAMEWALKER_ELITE:
                {
                    AddMinion(creature, false);
                    break;
                }
            }
        }

        void OnGameObjectCreate(GameObject* go) override
        {
            switch (go->GetEntry())
            {
                case GO_CACHE_OF_THE_FIRELORD:
                {
                    _cacheOfTheFirelordGUID = go->GetGUID();
                    break;
                }
                case GO_CIRCLE_GEDDON:
                case GO_CIRCLE_GARR:
                case GO_CIRCLE_GEHENNAS:
                case GO_CIRCLE_GOLEMAGG:
                case GO_CIRCLE_MAGMADAR:
                case GO_CIRCLE_SHAZZRAH:
                case GO_CIRCLE_SULFURON:
                {
                    for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i)
                    {
                        if (linkedBossObjData[i].circleId != go->GetEntry())
                        {
                            continue;
                        }

                        if (GetBossState(linkedBossObjData[i].bossId) == DONE)
                        {
                            go->DespawnOrUnsummon(0ms, Seconds(WEEK));
                        }
                        else
                        {
                            _circlesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID();
                        }
                    }

                    break;
                }
                case GO_RUNE_KRESS:
                case GO_RUNE_MOHN:
                case GO_RUNE_BLAZ:
                case GO_RUNE_MAZJ:
                case GO_RUNE_ZETH:
                case GO_RUNE_THERI:
                case GO_RUNE_KORO:
                {
                    for (uint8 i = 0; i < MAX_MC_LINKED_BOSS_OBJ; ++i)
                    {
                        if (linkedBossObjData[i].runeId != go->GetEntry())
                        {
                            continue;
                        }

                        if (GetBossState(linkedBossObjData[i].bossId) == DONE)
                        {
                            go->UseDoorOrButton(WEEK * IN_MILLISECONDS);
                        }
                        else
                        {
                            _runesGUIDs[linkedBossObjData[i].bossId] = go->GetGUID();
                        }
                    }
                    break;
                }
                case GO_LAVA_STEAM:
                {
                    _lavaSteamGUID = go->GetGUID();
                    break;
                }
                case GO_LAVA_SPLASH:
                {
                    _lavaSplashGUID = go->GetGUID();
                    break;
                }
                case GO_LAVA_BURST:
                {
                    if (Creature* ragnaros = instance->GetCreature(_ragnarosGUID))
                    {
                        ragnaros->AI()->SetGUID(go->GetGUID(), GO_LAVA_BURST);
                    }
                    break;
                }
            }
        }

        ObjectGuid GetGuidData(uint32 type) const override
        {
            switch (type)
            {
                case DATA_GOLEMAGG:
                    return _golemaggGUID;
                case DATA_MAJORDOMO_EXECUTUS:
                    return _majordomoExecutusGUID;
                case DATA_GARR:
                    return _garrGUID;
                case DATA_LAVA_STEAM:
                    return _lavaSteamGUID;
                case DATA_LAVA_SPLASH:
                    return _lavaSplashGUID;
                case DATA_RAGNAROS:
                    return _ragnarosGUID;
            }

            return ObjectGuid::Empty;
        }

        bool SetBossState(uint32 bossId, EncounterState state) override
        {
            if (!InstanceScript::SetBossState(bossId, state))
            {
                return false;
            }

            if (bossId == DATA_MAJORDOMO_EXECUTUS && state == DONE)
            {
                DoRespawnGameObject(_cacheOfTheFirelordGUID, 7 * DAY);
            }
            else if (bossId == DATA_GOLEMAGG)
            {
                switch (state)
                {
                    case NOT_STARTED:
                    case FAIL:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                Creature* minion = instance->GetCreature(minionGuid);
                                if (minion && minion->isDead())
                                {
                                    minion->Respawn();
                                }
                            }
                        }
                        break;
                    }
                    case IN_PROGRESS:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                if (Creature* minion = instance->GetCreature(minionGuid))
                                {
                                    minion->AI()->DoZoneInCombat(nullptr, 150.0f);
                                }
                            }
                        }
                        break;
                    }
                    case DONE:
                    {
                        if (!_golemaggMinionsGUIDS.empty())
                        {
                            for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                            {
                                if (Creature* minion = instance->GetCreature(minionGuid))
                                {
                                    minion->CastSpell(minion, SPELL_CORE_RAGER_QUIET_SUICIDE, true);
                                }
                            }
                            _golemaggMinionsGUIDS.clear();
                        }
                        break;
                    }
                    default:
                        break;
                }
            }
            // Perform needed checks for Majordomu
            if (bossId < DATA_MAJORDOMO_EXECUTUS && state == DONE)
            {
                if (GameObject* circle = instance->GetGameObject(_circlesGUIDs[bossId]))
                {
                    circle->DespawnOrUnsummon(0ms, Seconds(WEEK));
                    _circlesGUIDs[bossId].Clear();
                }

                if (GameObject* rune = instance->GetGameObject(_runesGUIDs[bossId]))
                {
                    rune->UseDoorOrButton(WEEK * IN_MILLISECONDS);
                    _runesGUIDs[bossId].Clear();
                }

                if (CheckMajordomoExecutus())
                {
                    SummonMajordomoExecutus();
                }
            }

            return true;
        }

        void DoAction(int32 action) override
        {
            if (action == ACTION_RESET_GOLEMAGG_ENCOUNTER)
            {
                if (Creature* golemagg = instance->GetCreature(_golemaggGUID))
                {
                    golemagg->AI()->EnterEvadeMode();
                }

                if (!_golemaggMinionsGUIDS.empty())
                {
                    for (ObjectGuid const& minionGuid : _golemaggMinionsGUIDS)
                    {
                        if (Creature* minion = instance->GetCreature(minionGuid))
                        {
                            minion->AI()->EnterEvadeMode();
                        }
                    }
                }
            }
        }

        void SummonMajordomoExecutus()
        {
            if (instance->GetCreature(_majordomoExecutusGUID))
            {
                return;
            }

            if (GetBossState(DATA_MAJORDOMO_EXECUTUS) != DONE)
            {
                if (Creature* creature = instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoSummonPos))
                {
                    creature->AI()->Talk(SAY_SPAWN);
                }
            }
            else
            {
                instance->SummonCreature(NPC_MAJORDOMO_EXECUTUS, MajordomoRagnaros);
            }
        }

        bool CheckMajordomoExecutus() const
        {
            if (GetBossState(DATA_RAGNAROS) == DONE)
            {
                return false;
            }

            for (uint8 i = 0; i < DATA_MAJORDOMO_EXECUTUS; ++i)
            {
                if (i == DATA_LUCIFRON)
                {
                    continue;
                }

                if (GetBossState(i) != DONE)
                {
                    return false;
                }
            }

            // Prevent spawning if Ragnaros is present
            if (instance->GetCreature(_ragnarosGUID))
            {
                return false;
            }

            return true;
        }

        std::string GetSaveData() override
        {
            OUT_SAVE_INST_DATA;

            std::ostringstream saveStream;
            saveStream << "M C " << GetBossSaveData();

            OUT_SAVE_INST_DATA_COMPLETE;
            return saveStream.str();
        }

        void Load(char const* data) override
        {
            if (!data)
            {
                OUT_LOAD_INST_DATA_FAIL;
                return;
            }

            OUT_LOAD_INST_DATA(data);

            char dataHead1, dataHead2;

            std::istringstream loadStream(data);
            loadStream >> dataHead1 >> dataHead2;

            if (dataHead1 == 'M' && dataHead2 == 'C')
            {
                for (uint8 i = 0; i < MAX_ENCOUNTER; ++i)
                {
                    uint32 tmpState;
                    loadStream >> tmpState;
                    if (tmpState == IN_PROGRESS || tmpState > TO_BE_DECIDED)
                    {
                        tmpState = NOT_STARTED;
                    }

                    SetBossState(i, static_cast<EncounterState>(tmpState));
                }

                if (CheckMajordomoExecutus())
                {
                    SummonMajordomoExecutus();
                }
            }
            else
            {
                OUT_LOAD_INST_DATA_FAIL;
            }

            OUT_LOAD_INST_DATA_COMPLETE;
        }

    private:
        std::unordered_map<uint32/*bossid*/, ObjectGuid/*circleGUID*/> _circlesGUIDs;
        std::unordered_map<uint32/*bossid*/, ObjectGuid/*runeGUID*/> _runesGUIDs;

        // Golemagg encounter related
        ObjectGuid _golemaggGUID;
        GuidSet _golemaggMinionsGUIDS;

        // Ragnaros encounter related
        ObjectGuid _ragnarosGUID;
        ObjectGuid _lavaSteamGUID;
        ObjectGuid _lavaSplashGUID;

        ObjectGuid _majordomoExecutusGUID;
        ObjectGuid _cacheOfTheFirelordGUID;
        ObjectGuid _garrGUID;
        ObjectGuid _magmadarGUID;
    };

    InstanceScript* GetInstanceScript(InstanceMap* map) const override
    {
        return new instance_molten_core_InstanceMapScript(map);
    }
};

void AddSC_instance_molten_core()
{
    new instance_molten_core();
}
<|endoftext|>


<commit_before>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// Qmitk
#include "SpectralUnmixing.h"

// Qt
#include <QMessageBox>

// mitk image
#include <mitkImage.h>

// Include to perform Spectral Unmixing
#include "mitkPASpectralUnmixingFilterBase.h"
#include "mitkPALinearSpectralUnmixingFilter.h"
#include "mitkPASpectralUnmixingSO2.h"

const std::string SpectralUnmixing::VIEW_ID = "org.mitk.views.spectralunmixing";

void SpectralUnmixing::SetFocus()
{
  m_Controls.buttonPerformImageProcessing->setFocus();
}

void SpectralUnmixing::CreateQtPartControl(QWidget *parent)
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi(parent);
  connect(m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &SpectralUnmixing::DoImageProcessing);
  connect(m_Controls.ButtonAddWavelength, &QPushButton::clicked, this, &SpectralUnmixing::Wavelength);
  connect(m_Controls.ButtonClearWavelength, &QPushButton::clicked, this, &SpectralUnmixing::ClearWavelength);
}

// Adds Wavelength @ Plugin with button
void SpectralUnmixing::Wavelength()
{
  if (m_Wavelengths.empty())
  {
      size = 0;
  }

  unsigned int wavelength = m_Controls.spinBoxAddWavelength->value();
  m_Wavelengths.push_back(wavelength);
  size += 1; // size implemented like this because '.size' is const
  MITK_INFO << "ALL WAVELENGTHS: ";

  for (int i = 0; i < size; ++i)
  {
    MITK_INFO << m_Wavelengths[i] << "nm";
  }
}

void SpectralUnmixing::ClearWavelength()
{
  m_Wavelengths.clear();
}

void SpectralUnmixing::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/,
                                                const QList<mitk::DataNode::Pointer> &nodes)
{
  // iterate all selected objects, adjust warning visibility
  foreach (mitk::DataNode::Pointer node, nodes)
  {
    if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData()))
    {
      m_Controls.labelWarning->setVisible(false);
      m_Controls.buttonPerformImageProcessing->setEnabled(true);
      return;
    }
  }

  m_Controls.labelWarning->setVisible(true);
  m_Controls.buttonPerformImageProcessing->setEnabled(false);
}

void SpectralUnmixing::DoImageProcessing()
{
  QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
  if (nodes.empty())
    return;

  mitk::DataNode *node = nodes.front();

  if (!node)
  {
    // Nothing selected. Inform the user and return
    QMessageBox::information(nullptr, "Template", "Please load and select an image before starting image processing.");
    return;
  }

  // here we have a valid mitk::DataNode

  // a node itself is not very useful, we need its data item (the image)
  mitk::BaseData *data = node->GetData();
  if (data)
  {
    // test if this data item is an image or not (could also be a surface or something totally different)
    mitk::Image *image = dynamic_cast<mitk::Image *>(data);
    if (image)
    {
      std::stringstream message;
      std::string name;
      message << "PERFORMING SPECTRAL UNMIXING ";
      if (node->GetName(name))
      {
        // a property called "name" was found for this DataNode
        message << "'" << name << "'";
      }
      message << ".";
      MITK_INFO << message.str();

      auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();

      m_SpectralUnmixingFilter->SetInput(image);

      // Set Algortihm to filter
      auto qs = m_Controls.QComboBoxAlgorithm->currentText();
      std::string Algorithm = qs.toUtf8().constData();

      if (Algorithm == "householderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr);

      else if (Algorithm == "ldlt")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt);

      else if (Algorithm == "llt")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt);

      else if (Algorithm == "colPivHouseholderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr);

      else if (Algorithm == "jacobiSvd")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd);

      else if (Algorithm == "fullPivLu")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu);

      else if (Algorithm == "fullPivHouseholderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr);

      else if (Algorithm == "test")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test);
      else
        mitkThrow() << "ALGORITHM ERROR!";

      // Wavelength implementation into filter
      for (unsigned int imageIndex = 0; imageIndex < m_Wavelengths.size(); imageIndex++)
      {
        unsigned int wavelength = m_Wavelengths[imageIndex];
        m_SpectralUnmixingFilter->AddWavelength(wavelength);
      }

      // Checking which chromophores wanted for SU if none throw exeption!
      unsigned int numberofChromophores = 0;
      DeOxbool = m_Controls.checkBoxDeOx->isChecked();
      Oxbool = m_Controls.checkBoxOx->isChecked();
      if (DeOxbool || Oxbool)
      {
        MITK_INFO << "CHOSEN CHROMOPHORES:";
      }
      if (Oxbool)
      {
        numberofChromophores += 1;
        MITK_INFO << "- Oxyhemoglobin";
        // Set chromophore Oxyhemoglobon:
        m_SpectralUnmixingFilter->AddChromophore(
        mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::OXYGENATED_HEMOGLOBIN);
      }
      if (DeOxbool)
      {
        numberofChromophores += 1;
         MITK_INFO << "- Deoxygenated hemoglobin";
        // Set chromophore Deoxygenated hemoglobin:
        m_SpectralUnmixingFilter->AddChromophore(
        mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::DEOXYGENATED_HEMOGLOBIN);
      }
      if (numberofChromophores == 0)
      {
        mitkThrow() << "PRESS 'IGNORE' AND CHOOSE A CHROMOPHORE!";
      }

      MITK_INFO << "Updating Filter...";

      m_SpectralUnmixingFilter->Update();

      if (Oxbool)
      {
        mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0);
        mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New();
        dataNodeHbO2->SetData(HbO2);
        dataNodeHbO2->SetName("HbO2");
        this->GetDataStorage()->Add(dataNodeHbO2);
      }

      if (DeOxbool)
      {
        mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1);
        mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New();
        dataNodeHb->SetData(Hb);
        dataNodeHb->SetName("Hb");
        this->GetDataStorage()->Add(dataNodeHb);
      }

      //mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());

      //*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      //FRAGE zu SetInput: reicht es dort einen image pointer anzugeben?
      //wenn ja zweite Variante wenn nein dann erste. funktioniern aber leider beide nicht:/
      bool sO2bool = m_Controls.checkBoxsO2->isChecked();

      //1:
      /*
      mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0);
      mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New();
      dataNodeHbO2->SetData(HbO2);
      mitk::BaseData *dataHbO2 = dataNodeHbO2->GetData();
      mitk::Image *imageHbO2 = dynamic_cast<mitk::Image *>(dataHbO2);

      mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1);
      mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New();
      dataNodeHb->SetData(Hb);
      mitk::BaseData *dataHb = dataNodeHb->GetData();
      mitk::Image *imageHb = dynamic_cast<mitk::Image *>(dataHb);

      auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
      m_sO2->SetInput(0,imageHbO2);
      m_sO2->SetInput(1,imageHb);

      m_sO2->Update();

      mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
      mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New();
      dataNodesO2->SetData(sO2);
      dataNodesO2->SetName("sO2");
      this->GetDataStorage()->Add(dataNodesO2);/**/

      //2:
      /*
      if (sO2bool)
      {
        if (DeOxbool)
        {
          if (Oxbool)
          {
            MITK_INFO << "CALCULATE OXYGEN SATURATION ...";
            auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
            m_sO2->SetInput(0, m_SpectralUnmixingFilter->GetOutput(0));
            m_sO2->SetInput(1, m_SpectralUnmixingFilter->GetOutput(1));

            //http://docs.mitk.org/nightly/PipelineingConceptPage.html
            //m_SpectralUnmixingFilter->Update();
            //m_sO2->SetInput(m_SpectralUnmixingFilter->GetOutput());

            m_sO2->Update();

            mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
            mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New();
            dataNodesO2->SetData(sO2);
            dataNodesO2->SetName("sO2");
            this->GetDataStorage()->Add(dataNodesO2);

            MITK_INFO << "[DONE]";
          }
          else
            mitkThrow() << "SELECT CHROMOPHORE OXYHEMOGLOBIN!";
        }
        else
          mitkThrow() << "SELECT CHROMOPHORE DEOXYHEMOGLOBIN!";
      }
      mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());/**/

      //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/**/

      MITK_INFO << "Adding images to DataStorage...[DONE]";
    }
  }
}
<commit_msg>changed name of output files and solved rendering.<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

===================================================================*/

// Blueberry
#include <berryISelectionService.h>
#include <berryIWorkbenchWindow.h>

// Qmitk
#include "SpectralUnmixing.h"

// Qt
#include <QMessageBox>

// mitk image
#include <mitkImage.h>

// Include to perform Spectral Unmixing
#include "mitkPASpectralUnmixingFilterBase.h"
#include "mitkPALinearSpectralUnmixingFilter.h"
#include "mitkPASpectralUnmixingSO2.h"

const std::string SpectralUnmixing::VIEW_ID = "org.mitk.views.spectralunmixing";

void SpectralUnmixing::SetFocus()
{
  m_Controls.buttonPerformImageProcessing->setFocus();
}

void SpectralUnmixing::CreateQtPartControl(QWidget *parent)
{
  // create GUI widgets from the Qt Designer's .ui file
  m_Controls.setupUi(parent);
  connect(m_Controls.buttonPerformImageProcessing, &QPushButton::clicked, this, &SpectralUnmixing::DoImageProcessing);
  connect(m_Controls.ButtonAddWavelength, &QPushButton::clicked, this, &SpectralUnmixing::Wavelength);
  connect(m_Controls.ButtonClearWavelength, &QPushButton::clicked, this, &SpectralUnmixing::ClearWavelength);
}

// Adds Wavelength @ Plugin with button
void SpectralUnmixing::Wavelength()
{
  if (m_Wavelengths.empty())
  {
      size = 0;
  }

  unsigned int wavelength = m_Controls.spinBoxAddWavelength->value();
  m_Wavelengths.push_back(wavelength);
  size += 1; // size implemented like this because '.size' is const
  MITK_INFO << "ALL WAVELENGTHS: ";

  for (int i = 0; i < size; ++i)
  {
    MITK_INFO << m_Wavelengths[i] << "nm";
  }
}

void SpectralUnmixing::ClearWavelength()
{
  m_Wavelengths.clear();
}

void SpectralUnmixing::OnSelectionChanged(berry::IWorkbenchPart::Pointer /*source*/,
                                                const QList<mitk::DataNode::Pointer> &nodes)
{
  // iterate all selected objects, adjust warning visibility
  foreach (mitk::DataNode::Pointer node, nodes)
  {
    if (node.IsNotNull() && dynamic_cast<mitk::Image *>(node->GetData()))
    {
      m_Controls.labelWarning->setVisible(false);
      m_Controls.buttonPerformImageProcessing->setEnabled(true);
      return;
    }
  }

  m_Controls.labelWarning->setVisible(true);
  m_Controls.buttonPerformImageProcessing->setEnabled(false);
}

void SpectralUnmixing::DoImageProcessing()
{
  QList<mitk::DataNode::Pointer> nodes = this->GetDataManagerSelection();
  if (nodes.empty())
    return;

  mitk::DataNode *node = nodes.front();

  if (!node)
  {
    // Nothing selected. Inform the user and return
    QMessageBox::information(nullptr, "Template", "Please load and select an image before starting image processing.");
    return;
  }

  // here we have a valid mitk::DataNode

  // a node itself is not very useful, we need its data item (the image)
  mitk::BaseData *data = node->GetData();
  if (data)
  {
    // test if this data item is an image or not (could also be a surface or something totally different)
    mitk::Image *image = dynamic_cast<mitk::Image *>(data);
    if (image)
    {
      std::stringstream message;
      std::string name;
      message << "PERFORMING SPECTRAL UNMIXING ";
      if (node->GetName(name))
      {
        // a property called "name" was found for this DataNode
        message << "'" << name << "'";
      }
      message << ".";
      MITK_INFO << message.str();

      auto m_SpectralUnmixingFilter = mitk::pa::LinearSpectralUnmixingFilter::New();

      m_SpectralUnmixingFilter->SetInput(image);

      // Set Algortihm to filter
      auto qs = m_Controls.QComboBoxAlgorithm->currentText();
      std::string Algorithm = qs.toUtf8().constData();

      if (Algorithm == "householderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::householderQr);

      else if (Algorithm == "ldlt")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::ldlt);

      else if (Algorithm == "llt")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::llt);

      else if (Algorithm == "colPivHouseholderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::colPivHouseholderQr);

      else if (Algorithm == "jacobiSvd")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::jacobiSvd);

      else if (Algorithm == "fullPivLu")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivLu);

      else if (Algorithm == "fullPivHouseholderQr")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::fullPivHouseholderQr);

      else if (Algorithm == "test")
        m_SpectralUnmixingFilter->SetAlgorithm(mitk::pa::LinearSpectralUnmixingFilter::AlgortihmType::test);
      else
        mitkThrow() << "ALGORITHM ERROR!";

      // Wavelength implementation into filter
      for (unsigned int imageIndex = 0; imageIndex < m_Wavelengths.size(); imageIndex++)
      {
        unsigned int wavelength = m_Wavelengths[imageIndex];
        m_SpectralUnmixingFilter->AddWavelength(wavelength);
      }

      // Checking which chromophores wanted for SU if none throw exeption!
      unsigned int numberofChromophores = 0;
      DeOxbool = m_Controls.checkBoxDeOx->isChecked();
      Oxbool = m_Controls.checkBoxOx->isChecked();
      if (DeOxbool || Oxbool)
      {
        MITK_INFO << "CHOSEN CHROMOPHORES:";
      }
      if (Oxbool)
      {
        numberofChromophores += 1;
        MITK_INFO << "- Oxyhemoglobin";
        // Set chromophore Oxyhemoglobon:
        m_SpectralUnmixingFilter->AddChromophore(
        mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::OXYGENATED_HEMOGLOBIN);
      }
      if (DeOxbool)
      {
        numberofChromophores += 1;
         MITK_INFO << "- Deoxygenated hemoglobin";
        // Set chromophore Deoxygenated hemoglobin:
        m_SpectralUnmixingFilter->AddChromophore(
        mitk::pa::SpectralUnmixingFilterBase::ChromophoreType::DEOXYGENATED_HEMOGLOBIN);
      }
      if (numberofChromophores == 0)
      {
        mitkThrow() << "PRESS 'IGNORE' AND CHOOSE A CHROMOPHORE!";
      }

      MITK_INFO << "Updating Filter...";

      m_SpectralUnmixingFilter->Update();

      if (Oxbool)
      {
        mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0);
        mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New();
        dataNodeHbO2->SetData(HbO2);
        dataNodeHbO2->SetName("HbO2: " + Algorithm);
        this->GetDataStorage()->Add(dataNodeHbO2);
      }

      if (DeOxbool)
      {
        mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1);
        mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New();
        dataNodeHb->SetData(Hb);
        dataNodeHb->SetName("Hb: " + Algorithm);
        this->GetDataStorage()->Add(dataNodeHb);
      }

      mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());

      //*++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
      //FRAGE zu SetInput: reicht es dort einen image pointer anzugeben?
      //wenn ja zweite Variante wenn nein dann erste. funktioniern aber leider beide nicht:/
      bool sO2bool = m_Controls.checkBoxsO2->isChecked();

      //1:
      /*
      mitk::Image::Pointer HbO2 = m_SpectralUnmixingFilter->GetOutput(0);
      mitk::DataNode::Pointer dataNodeHbO2 = mitk::DataNode::New();
      dataNodeHbO2->SetData(HbO2);
      mitk::BaseData *dataHbO2 = dataNodeHbO2->GetData();
      mitk::Image *imageHbO2 = dynamic_cast<mitk::Image *>(dataHbO2);

      mitk::Image::Pointer Hb = m_SpectralUnmixingFilter->GetOutput(1);
      mitk::DataNode::Pointer dataNodeHb = mitk::DataNode::New();
      dataNodeHb->SetData(Hb);
      mitk::BaseData *dataHb = dataNodeHb->GetData();
      mitk::Image *imageHb = dynamic_cast<mitk::Image *>(dataHb);

      auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
      m_sO2->SetInput(0,imageHbO2);
      m_sO2->SetInput(1,imageHb);

      m_sO2->Update();

      mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
      mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New();
      dataNodesO2->SetData(sO2);
      dataNodesO2->SetName("sO2");
      this->GetDataStorage()->Add(dataNodesO2);/**/

      //2:
      /*
      if (sO2bool)
      {
        if (DeOxbool)
        {
          if (Oxbool)
          {
            MITK_INFO << "CALCULATE OXYGEN SATURATION ...";
            auto m_sO2 = mitk::pa::SpectralUnmixingSO2::New();
            m_sO2->SetInput(0, m_SpectralUnmixingFilter->GetOutput(0));
            m_sO2->SetInput(1, m_SpectralUnmixingFilter->GetOutput(1));

            //http://docs.mitk.org/nightly/PipelineingConceptPage.html
            //m_SpectralUnmixingFilter->Update();
            //m_sO2->SetInput(m_SpectralUnmixingFilter->GetOutput());

            m_sO2->Update();

            mitk::Image::Pointer sO2 = m_sO2->GetOutput(0);
            mitk::DataNode::Pointer dataNodesO2 = mitk::DataNode::New();
            dataNodesO2->SetData(sO2);
            dataNodesO2->SetName("sO2");
            this->GetDataStorage()->Add(dataNodesO2);

            MITK_INFO << "[DONE]";
          }
          else
            mitkThrow() << "SELECT CHROMOPHORE OXYHEMOGLOBIN!";
        }
        else
          mitkThrow() << "SELECT CHROMOPHORE DEOXYHEMOGLOBIN!";
      }
      mitk::RenderingManager::GetInstance()->InitializeViewsByBoundingObjects(this->GetDataStorage());/**/

      //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++/**/

      MITK_INFO << "Adding images to DataStorage...[DONE]";
    }
  }
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
//
// Main.cxx
//
////////////////////////////////////////////////////////////////////////////////
//
// Developed by Donnacha Forde (@DonnachaForde)
//
// Copyright  2006-2008, Donnacha Forde. All rights reserved.
//
// This software is provided 'as is' without warranty, expressed or implied.
// Donnacha Forde accepts no responsibility for the use or reliability of this software.
//
////////////////////////////////////////////////////////////////////////////////

// espresso lib
#include <espresso.hxx>
using namespace espresso;

// crt
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <cctype>
using namespace std;

#include <errno.h>

#ifdef WIN32
	#include <io.h>
#else
	#include <unistd.h>
#endif

// prototypes
void ProcessFile(const Args& args);

/******************************************************************************\
 ******************************************************************************
 ******************************************************************************
 *********************************    MAIN    *********************************
 ******************************************************************************
 ******************************************************************************
\******************************************************************************/

int main(int argc, char* argv[], char* envp[])
{

	//
	// arg parsing
	//

	Args args(argc,
			  argv,
			  "bin2txt",
			  "Displays binary files in text format.",
			  "1.0 (Beta)",
			  "Donnacha Forde",
			  "2005-2007",
			  "@DonnachaForde");

	// pick up default args/switches
	args.Initialize();

	// specify our switches & aliases
	args.Add("columns",	Arg::INTEGER,	"Number of hexadecimal columns to display on each line.", true);
	args.Add("file",	Arg::STRING,	"Filename to modify.", true, "filename");
	args.Add("text",	Arg::NOARG,		"Display text only.");
	args.Add("hex",		Arg::NOARG,		"Display hexadecimal only.");

	args.AddAlias("columns", 'c');
	args.AddAlias("file", 'f');
	args.AddAlias("text", 't');
	args.AddAlias("hex", 'x');

	// create argmgr to handle default switches
	ArgMgrCLI argMgr;
	if (!argMgr.ParseAndProcess(args))
	{
		::exit(0);
	}

	// check display preferences
	if (args.IsPresent("hex") && args.IsPresent("text"))
	{
		cout << "ERROR: Cannot display only hex and only text at once." << endl;
		argMgr.OnArgError(args);
		::exit(0);
	}

	if (args.IsPresent("text") && args.IsPresent("columns"))
	{
		cout << "ERROR: Specifying number of columns in not applicable when displaying text only." << endl;
		argMgr.OnArgError(args);
		::exit(0);
	}

	ProcessFile(args);

	return 0;
}

//------------------------------------------------------------------------------
//
// Function       : ProcessFile
//
// Return type    : void
//
// Argument       : const Args& args
//
// Description    :
//
// Notes          :
//
//------------------------------------------------------------------------------
void ProcessFile(const Args& args)
{
	//
	// now use any args specified
	//

	bool IsDisplayHexOnly = args.IsPresent("hex");
	bool IsDisplayTextOnly = args.IsPresent("text");

	// default to 16 wide
	int nNumColumnsToDisplay = 16;
	if (args.IsPresent("columns"))
	{
		nNumColumnsToDisplay = args.GetNumericValue("columns");
	}

	// handle the file/target
	FILE* fdIn = NULL;
	if (args.IsPresent("file") || args.IsTargetPresent())
	{
		const char* szInputFilename = NULL;

		if (args.IsPresent("file"))
		{
			szInputFilename = args.GetStringValue("file").c_str();
		}
		else
		{
			szInputFilename = args.GetTarget().c_str();
		}

		// check the filename
		if (!espresso::strings::IsValidString(szInputFilename))
		{
			cout << "ERROR: Unable to process empty filename." << endl;
			::exit(-1);
		}

		// can we open the file for reading (and hence, does it even exist)...
		int nRetCode = ::access(szInputFilename, 04);
		if ((nRetCode == EACCES) || (nRetCode == ENOENT))
		{
			cout << "ERROR: Either the file '" << szInputFilename << "' does not exist or is not available for reading purposes." << endl;
			::exit(-1);
		}

		// open the file
		fdIn = ::fopen(szInputFilename, "rb");
		assert(fdIn != NULL);

		if (fdIn == NULL)
		{
			cout << "ERROR: Failed to open file: '" << szInputFilename << "' for reading." << endl;
			::exit(-1);
		}
	}
	else
	{
		// use stdin
		fdIn = stdin;
	}

	//
	// main processing loop
	//

	::setvbuf(stdin, NULL, _IOLBF, 0);
	::setvbuf(stdout, NULL, _IOLBF, 0);

	int ch = 0;
	int nNumColumnsShown = 0;

	if (IsDisplayTextOnly)
	{
		while ((ch = ::fgetc(fdIn)) != EOF)
		{
			// if we're showing text, we must handle CR/LF (for this we must read ahead by one char, hence the two similar 'else' clauses
			if ((char)ch == '\\')
			{
				// read next char
				ch = ::fgetc(fdIn);
				if ((char)ch == 'n')
				{
					::fprintf(stdout, "\n");
				}
				else
				{
					// if not a printable char, substitute with a dot
					if (isprint(ch))
					{
						::fprintf(stdout, "\\%c", (char)ch);
					}
					else
					{
						::fprintf(stdout, "\\.");
					}
				}
			}
			else
			{
				if (isprint(ch))
				{
					::fprintf(stdout, "%c", (char)ch);
				}
				else
				{
					::fprintf(stdout, ".");
				}

			}
		}
	}
	else
	{
		// create buffer for string representation
		char* szBuffer = new char[nNumColumnsToDisplay + 1];
		::memset(szBuffer, 0, (nNumColumnsToDisplay + 1));
		char* pch = szBuffer;

		while ((ch = ::fgetc(fdIn)) != EOF)
		{
			// build up string representation
			if (!IsDisplayHexOnly)
			{
				// if not a printable char, substitute with a dot
				if (!isprint(ch))
				{
					ch = '.';
				}

				*pch++ = (char)ch;
			}

			// display the hex representation
			::fprintf(stdout, "%02x ", ch);

			// handle column display logic
			nNumColumnsShown++;
			if (nNumColumnsShown == nNumColumnsToDisplay)
			{
				assert(::strlen(szBuffer) <=  nNumColumnsToDisplay);
				::fprintf(stdout, "    %s\n", szBuffer);
				nNumColumnsShown = 0;
				::memset(szBuffer, 0, (nNumColumnsToDisplay + 1));
				pch = szBuffer;
			}
		}

		// write blank columns at end where necessary
		for (int i = nNumColumnsToDisplay; i > nNumColumnsShown; i--)
		{
			::fprintf(stdout, "   ");
		}

		// deal with stragling buffer
		szBuffer[nNumColumnsShown] = '\0';
		::fprintf(stdout, "    %s\n", szBuffer);

		//
		// tidy up
		//

		delete [] szBuffer;

	}

	::fclose(fdIn);
	::fclose(stdout);

	return;
}

<commit_msg>Explicity disable CRT Security Warnings.<commit_after>////////////////////////////////////////////////////////////////////////////////
//
// Main.cxx
//
////////////////////////////////////////////////////////////////////////////////
//
// Developed by Donnacha Forde (@DonnachaForde)
//
// Copyright  2006-2008, Donnacha Forde. All rights reserved.
//
// This software is provided 'as is' without warranty, expressed or implied.
// Donnacha Forde accepts no responsibility for the use or reliability of this software.
//
////////////////////////////////////////////////////////////////////////////////

// disable newer warnings
#ifdef WIN32
	#pragma message("note : CRT security warning (so we can use ol'fashion 'C' calls)")
	#define _CRT_SECURE_NO_WARNINGS
#endif

// espresso lib
#include <espresso.hxx>
using namespace espresso;

// crt
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <iostream>
#include <cctype>
using namespace std;

#include <errno.h>

#ifdef WIN32
	#include <io.h>
#else
	#include <unistd.h>
#endif

// prototypes
void ProcessFile(const Args& args);

/******************************************************************************\
 ******************************************************************************
 ******************************************************************************
 *********************************    MAIN    *********************************
 ******************************************************************************
 ******************************************************************************
\******************************************************************************/

int main(int argc, char* argv[], char* envp[])
{

	//
	// arg parsing
	//

	Args args(argc,
			  argv,
			  "bin2txt",
			  "Displays binary files in text format.",
			  "1.0 (Beta)",
			  "Donnacha Forde",
			  "2005-2007",
			  "@DonnachaForde");

	// pick up default args/switches
	args.Initialize();

	// specify our switches & aliases
	args.Add("columns",	Arg::INTEGER,	"Number of hexadecimal columns to display on each line.", true);
	args.Add("file",	Arg::STRING,	"Filename to modify.", true, "filename");
	args.Add("text",	Arg::NOARG,		"Display text only.");
	args.Add("hex",		Arg::NOARG,		"Display hexadecimal only.");

	args.AddAlias("columns", 'c');
	args.AddAlias("file", 'f');
	args.AddAlias("text", 't');
	args.AddAlias("hex", 'x');

	// create argmgr to handle default switches
	ArgMgrCLI argMgr;
	if (!argMgr.ParseAndProcessArgs(args))
	{
		::exit(0);
	}

	// check display preferences
	if (args.IsPresent("hex") && args.IsPresent("text"))
	{
		cout << "ERROR: Cannot display only hex and only text at once." << endl;
		argMgr.OnArgError(args);
		::exit(0);
	}

	if (args.IsPresent("text") && args.IsPresent("columns"))
	{
		cout << "ERROR: Specifying number of columns in not applicable when displaying text only." << endl;
		argMgr.OnArgError(args);
		::exit(0);
	}

	ProcessFile(args);

	return 0;
}

//------------------------------------------------------------------------------
//
// Function       : ProcessFile
//
// Return type    : void
//
// Argument       : const Args& args
//
// Description    :
//
// Notes          :
//
//------------------------------------------------------------------------------
void ProcessFile(const Args& args)
{
	//
	// now use any args specified
	//

	bool IsDisplayHexOnly = args.IsPresent("hex");
	bool IsDisplayTextOnly = args.IsPresent("text");

	// default to 16 wide
	int nNumColumnsToDisplay = 16;
	if (args.IsPresent("columns"))
	{
		nNumColumnsToDisplay = args.GetNumericValue("columns");
	}

	// handle the file/target
	FILE* fdIn = NULL;
	if (args.IsPresent("file") || args.IsTargetPresent())
	{
		const char* szInputFilename = NULL;

		if (args.IsPresent("file"))
		{
			szInputFilename = args.GetStringValue("file").c_str();
		}
		else
		{
			szInputFilename = args.GetTarget().c_str();
		}

		// check the filename
		if (!espresso::strings::IsValidString(szInputFilename))
		{
			cout << "ERROR: Unable to process empty filename." << endl;
			::exit(-1);
		}

		// can we open the file for reading (and hence, does it even exist)...
		int nRetCode = ::access(szInputFilename, 04);
		if ((nRetCode == EACCES) || (nRetCode == ENOENT))
		{
			cout << "ERROR: Either the file '" << szInputFilename << "' does not exist or is not available for reading purposes." << endl;
			::exit(-1);
		}

		// open the file
		fdIn = ::fopen(szInputFilename, "rb");
		assert(fdIn != NULL);

		if (fdIn == NULL)
		{
			cout << "ERROR: Failed to open file: '" << szInputFilename << "' for reading." << endl;
			::exit(-1);
		}
	}
	else
	{
		// use stdin
		fdIn = stdin;
	}

	//
	// main processing loop
	//

	::setvbuf(stdin, NULL, _IOLBF, 0);
	::setvbuf(stdout, NULL, _IOLBF, 0);

	int ch = 0;
	int nNumColumnsShown = 0;

	if (IsDisplayTextOnly)
	{
		while ((ch = ::fgetc(fdIn)) != EOF)
		{
			// if we're showing text, we must handle CR/LF (for this we must read ahead by one char, hence the two similar 'else' clauses
			if ((char)ch == '\\')
			{
				// read next char
				ch = ::fgetc(fdIn);
				if ((char)ch == 'n')
				{
					::fprintf(stdout, "\n");
				}
				else
				{
					// if not a printable char, substitute with a dot
					if (isprint(ch))
					{
						::fprintf(stdout, "\\%c", (char)ch);
					}
					else
					{
						::fprintf(stdout, "\\.");
					}
				}
			}
			else
			{
				if (isprint(ch))
				{
					::fprintf(stdout, "%c", (char)ch);
				}
				else
				{
					::fprintf(stdout, ".");
				}

			}
		}
	}
	else
	{
		// create buffer for string representation
		char* szBuffer = new char[nNumColumnsToDisplay + 1];
		::memset(szBuffer, 0, (nNumColumnsToDisplay + 1));
		char* pch = szBuffer;

		while ((ch = ::fgetc(fdIn)) != EOF)
		{
			// build up string representation
			if (!IsDisplayHexOnly)
			{
				// if not a printable char, substitute with a dot
				if (!isprint(ch))
				{
					ch = '.';
				}

				*pch++ = (char)ch;
			}

			// display the hex representation
			::fprintf(stdout, "%02x ", ch);

			// handle column display logic
			nNumColumnsShown++;
			if (nNumColumnsShown == nNumColumnsToDisplay)
			{
				assert(::strlen(szBuffer) <=  nNumColumnsToDisplay);
				::fprintf(stdout, "    %s\n", szBuffer);
				nNumColumnsShown = 0;
				::memset(szBuffer, 0, (nNumColumnsToDisplay + 1));
				pch = szBuffer;
			}
		}

		// write blank columns at end where necessary
		for (int i = nNumColumnsToDisplay; i > nNumColumnsShown; i--)
		{
			::fprintf(stdout, "   ");
		}

		// deal with stragling buffer
		szBuffer[nNumColumnsShown] = '\0';
		::fprintf(stdout, "    %s\n", szBuffer);

		//
		// tidy up
		//

		delete [] szBuffer;

	}

	::fclose(fdIn);
	::fclose(stdout);

	return;
}

<|endoftext|>


<commit_before>// ========================================================================================
//  ApproxMVBB
//  Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz
//  (døt) ch>
//
//  This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================================

#include <iostream>

#include "ApproxMVBB/ComputeApproxMVBB.hpp"

int main(int argc, char** argv)
{
    unsigned int nPoints = 100000;

    std::cout << "Sample " << nPoints << " points in unite cube (coordinates are in world frame I) " << std::endl;
    ApproxMVBB::Matrix3Dyn points(3, nPoints);
    points.setRandom();

    ApproxMVBB::OOBB oobb = ApproxMVBB::approximateMVBB(points,
                                                        0.001,
                                                        500,
                                                        5 /*increasing the grid size decreases speed */
                                                        ,
                                                        0,
                                                        5);

    std::cout << "Computed OOBB: " << std::endl
              << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl
              << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl
              << "---> coordinate transformation A_IK matrix from OOBB frame K "
                 "to world frame I"
              << std::endl
              << oobb.m_q_KI.matrix() << std::endl
              << "---> this is also the rotation matrix R_KI  which turns the "
                 "world frame I into the OOBB frame K"
              << std::endl
              << std::endl;

    // To make all points inside the OOBB :
    ApproxMVBB::Matrix33 A_KI = oobb.m_q_KI.matrix().transpose();  // faster to store the transformation matrix first
    auto size                 = points.cols();
    for (unsigned int i = 0; i < size; ++i)
    {
        oobb.unite(A_KI * points.col(i));
    }
    std::cout << "OOBB with all point included: " << std::endl
              << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl
              << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl;

    return 0;
}
<commit_msg>Documentation<commit_after>// ========================================================================================
//  ApproxMVBB
//  Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz
//  (døt) ch>
//
//  This Source Code Form is subject to the terms of the Mozilla Public
//  License, v. 2.0. If a copy of the MPL was not distributed with this
//  file, You can obtain one at http://mozilla.org/MPL/2.0/.
// ========================================================================================

#include <iostream>

#include "ApproxMVBB/ComputeApproxMVBB.hpp"

int main(int argc, char** argv)
{
    unsigned int nPoints = 100000;

    std::cout << "Sample " << nPoints << " points in unite cube (coordinates are in world frame I) " << std::endl;
    ApproxMVBB::Matrix3Dyn points(3, nPoints);
    points.setRandom();

    ApproxMVBB::OOBB oobb = ApproxMVBB::approximateMVBB(points,
                                                        0.001,
                                                        500,
                                                        5, /*increasing the grid size decreases speed */
                                                        0,
                                                        5);

    std::cout << "Computed OOBB: " << std::endl
              << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl
              << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl
              << "---> coordinate transformation A_IK matrix from OOBB frame K "
                 "to world frame I"
              << std::endl
              << oobb.m_q_KI.matrix() << std::endl
              << "---> this is also the rotation matrix R_KI  which turns the "
                 "world frame I into the OOBB frame K"
              << std::endl
              << std::endl;

    // To make all points inside the OOBB :
    ApproxMVBB::Matrix33 A_KI = oobb.m_q_KI.matrix().transpose();  // faster to store the transformation matrix first
    auto size                 = points.cols();
    for (unsigned int i = 0; i < size; ++i)
    {
        oobb.unite(A_KI * points.col(i));
    }
    std::cout << "OOBB with all point included: " << std::endl
              << "---> lower point in OOBB frame: " << oobb.m_minPoint.transpose() << std::endl
              << "---> upper point in OOBB frame: " << oobb.m_maxPoint.transpose() << std::endl;

    return 0;
}
<|endoftext|>


<commit_before>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/legacy/legacy.hpp>

#include <math.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

//--------------------- Classes ---------------------
class MovObj{
  private:
    int h, w;
    int area;
    cv::Point2f square_origin;
    cv::Point2f center;
    cv::Point2f vel;
    cv::Mat template_obj;

  public:
    MovObj(int h_, int w_, int area_){
      //center = center_;
      //square_origin = square_origin_;
      h = h_;
      w = w_;
      area = area_;
    }
    //~MovObj();

    int get_height(){
      return(h);
    }

    int get_width(){
      return(w);
    }

    int get_area(){
      return(area);
    }
};

class Opt_flow {
  private:
    cv::VideoCapture video;
    cv::String filename;
    cv::Mat frame;
    cv::Mat opt_flow,flow_mask,cont_mask;
    cv::Mat prev_frame,next_frame;
    cv::Mat x_vals,y_vals;
    std::vector<float> vel_x;
    std::vector<float> vel_y;
    float std_error;
    cv::Vec3b frame_intensity,next_frame_intensity;
    float errors;
    int counter;
    CvSize win_size;
    int step,interval_pixels,tam_vel;
    int kernel_size;
    int threshold,ratio;
    int pyr_scale, levels, winsize, iterations, poly_n, poly_sigma;
    std::vector<cv::Vec4i> hierarchy;
    std::vector<std::vector<cv::Point> > contours;
    std::vector<MovObj> mov_objects;

  public:

    Opt_flow(cv::VideoCapture video_ , cv::String filename_) {
      cv::namedWindow("Video");
      cv::namedWindow("OPT_FLOW");
      cv::namedWindow("Contours");
      cv::namedWindow("Trackbars");
      //cv::namedWindow("OPT_FLOW-X");
      //cv::namedWindow("OPT_FLOW-Y");
      video=video_;
      filename=filename_;
      std_error=80;
      counter=0;
      std_error=(std_error/100);
      win_size.height=3;
      win_size.width=3;
      kernel_size=3;
      interval_pixels=2;
      tam_vel=1;
      step=5;
      threshold=2;
      ratio=1;
      pyr_scale = 5; //Will be divided for 10
      levels = 3;
      winsize = 15;
      iterations = 3;
      poly_n = 5;
      poly_sigma = 1.2;

      video.open(filename);
    }

    ~Opt_flow(){
      cv::destroyWindow("Video");
      //cv::destroyWindow("OPT_FLOW-X");
      //cv::destroyWindow("OPT_FLOW-Y");
      cv::destroyWindow("OPT_FLOW");
      cv::destroyWindow("Contours");
      cv::destroyWindow("Trackbars");
    }

    void play(){
      int i=0;
      while (char(cv::waitKey(1))!='q'&&video.isOpened()){
        video >> frame;

        if (i==0){
          cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
        }

        if(i!=0&&i%step==0){
          getchar();
          cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);

          //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n';
          //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n';

          cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow,
                                      pyr_scale/10.0, levels, winsize,
                                      iterations, poly_n, poly_sigma, 0);
          //draw_flow(opt_flow,frame);

          get_xvals(opt_flow);
          get_yvals(opt_flow);
          generate_flowmask(x_vals,y_vals);
          cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
          cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY);

          flow_mask.convertTo(cont_mask,CV_8U);

          cv::findContours(cont_mask,contours, hierarchy, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
          get_contours(flow_mask);
          create_trackbars();

          show_frame();
          //print_moving_objects_vector();
          //getchar();

          prev_frame=next_frame.clone();
        }

        std::cout << "i = " << i << '\n';
        i++;
      }
    }

    void show_frame(){
      cv::imshow("Video",frame);
      cv::imshow("OPT_FLOW",flow_mask);
      cv::imshow("Contours",cont_mask);
    }

    void create_trackbars(){
      cv::createTrackbar("Pyramid Scale", "Trackbars", &pyr_scale, 9);
      cv::createTrackbar("Levels", "Trackbars", &levels, 10);
      cv::createTrackbar("Window Size", "Trackbars", &winsize, 50);
      cv::createTrackbar("Iterations", "Trackbars", &iterations, 10);
      cv::createTrackbar("Pixel Neighborhood Size", "Trackbars", &poly_n, 10);
    }

    void background_extr(){
      int i,j,aux_error;

      for(i=0;i<(frame.rows)-1;i++){
        for(j=0;j<(frame.cols)-1;j++){
          counter++;

          frame_intensity = frame.at<uint>(i,j);
          next_frame_intensity = next_frame.at<uint>(i,j);

          if (next_frame_intensity.val[0]==0){
            next_frame_intensity.val[0]=1;
          }
          errors=frame_intensity.val[0]/next_frame_intensity.val[0];

          if(errors<1-std_error||errors>1+std_error){
            opt_flow.at<uint>(i,j)=255;
            //std::cout << "MUDOU O PIXEL" << '\n';
          }
        }
      }
      //std::cout << "TROCOU FRAME" << '\n';

    }

    void blackfy(cv::Mat input){
      for(int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          input.at<uint>(i,j)=0;
          //std::cout << "(" << i << "," << j << ")" << '\n';
        }
      }
    }

    void draw_flow(cv::Mat input, cv::Mat output){
      for (int y = 0; y < output.rows; y += interval_pixels) {
          for (int x = 0; x < output.cols; x += interval_pixels)
          {
              const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel;
              cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0));
              cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1);
          }
      }
    }

    void get_xvals(cv::Mat input){
      x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n';

          x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x;
        }
      }
    }

    void get_yvals(cv::Mat input){
      y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n';

          y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y;
        }
      }
    }

    void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) {

      flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F);

      for (int i=0;i<x_matrix.rows;i++){
        for(int j=0;j<x_matrix.cols;j++){
          flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j));
        }
      }
    }

    float magnitude(float a, float b){
      float mag;

      mag=sqrt((a*a)+(b*b));

      return(mag);
    }

    void get_contours(cv::Mat input){
      std::vector<std::vector<cv::Point> > contours_poly(contours.size());
      std::vector<cv::Rect> boundRect(contours.size());

      for(int i=0;i<contours.size();i++){
        cv::approxPolyDP(cv::Mat(contours[i]),contours_poly[i],3,true );
        boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i]));
        draw_rectangles(boundRect);
        get_mov_obj(boundRect);
     }
    }

    void draw_rectangles(std::vector<cv::Rect> boundRect){
      for(int i=0; i< contours.size(); i++ ){
        rectangle(frame, boundRect[i].tl(), boundRect[i].br(), cv::Scalar(0,0,255), 2, 8, 0 );
      }
    }

    void get_mov_obj(std::vector<cv::Rect> boundRect){
      for (int i=0;i<contours.size();i++){
        MovObj aux(boundRect[i].height,boundRect[i].width,boundRect[i].area());
        mov_objects.push_back(aux);
        /*std::cout << "Object i=" << i << ':' << '\n';
        std::cout << "Height:" << mov_objects[i].get_height() << '\n';
        std::cout << "Width:" << mov_objects[i].get_width() << '\n';
        getchar();*/
      }
    }

    void print_moving_objects_vector(){
      for(int i=0;i<mov_objects.size();i++){
        std::cout << "i=" << i << '\n';
        std::cout << "Height:" << mov_objects[i].get_height() << '\n';
        std::cout << "Width:" << mov_objects[i].get_width() << '\n';
        std::cout << "Area:" << mov_objects[i].get_area() << '\n';
        std::cout << "----------------------------------" << '\n';
      }
    }
};

//--------------------- Global Variables ---------------------

//--------------------- Main Function ---------------------

int main(int argc, char *argv[]){
  cv::String filename;
  cv::VideoCapture video;

  if (argc<=1){
    std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>";
    getchar();
    return(-1);
  }

  filename=argv[1];

  Opt_flow opt_flow(video,filename);
  opt_flow.play();

  return(0);
}
<commit_msg>Getting moving objects square_origin and center<commit_after>#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/opencv.hpp>
#include "opencv2/nonfree/nonfree.hpp"
#include "opencv2/features2d/features2d.hpp"
#include "opencv2/nonfree/features2d.hpp"
#include "opencv2/calib3d/calib3d.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/legacy/legacy.hpp>

#include <math.h>
#include <iostream>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>

//--------------------- Classes ---------------------
class MovObj{
  private:
    int h, w;
    int area;
    cv::Point2f square_origin;
    cv::Point2f center;
    cv::Point2f vel;
    cv::Mat template_obj;

  public:
    MovObj(cv::Point2f square_origin_,int h_, int w_, int area_){
      //center = center_;
      //square_origin = square_origin_;
      h = h_;
      w = w_;
      area = area_;
      square_origin=square_origin_;
      center.x=((square_origin.x)+(square_origin.x+w))/2;
      center.y=((square_origin.y)+(square_origin.y+h))/2;
    }
    //~MovObj();

    int get_height(){
      return(h);
    }

    int get_width(){
      return(w);
    }

    int get_area(){
      return(area);
    }

    cv::Point2f get_origin(){
      return(square_origin);
    }
};

class Opt_flow {
  private:
    cv::VideoCapture video;
    cv::String filename;
    cv::Mat frame;
    cv::Mat opt_flow,flow_mask,cont_mask;
    cv::Mat prev_frame,next_frame;
    cv::Mat x_vals,y_vals;
    std::vector<float> vel_x;
    std::vector<float> vel_y;
    float std_error;
    cv::Vec3b frame_intensity,next_frame_intensity;
    float errors;
    int counter;
    CvSize win_size;
    int step,interval_pixels,tam_vel;
    int kernel_size;
    int threshold,ratio;
    int pyr_scale, levels, winsize, iterations, poly_n, poly_sigma;
    std::vector<cv::Vec4i> hierarchy;
    std::vector<std::vector<cv::Point> > contours;
    std::vector<MovObj> mov_objects;

  public:

    Opt_flow(cv::VideoCapture video_ , cv::String filename_) {
      cv::namedWindow("Video");
      cv::namedWindow("OPT_FLOW");
      cv::namedWindow("Contours");
      cv::namedWindow("Trackbars");
      //cv::namedWindow("OPT_FLOW-X");
      //cv::namedWindow("OPT_FLOW-Y");
      video=video_;
      filename=filename_;
      std_error=80;
      counter=0;
      std_error=(std_error/100);
      win_size.height=3;
      win_size.width=3;
      kernel_size=3;
      interval_pixels=2;
      tam_vel=1;
      step=5;
      threshold=2;
      ratio=1;
      pyr_scale = 5; //Will be divided for 10
      levels = 3;
      winsize = 15;
      iterations = 3;
      poly_n = 5;
      poly_sigma = 1.2;

      video.open(filename);
    }

    ~Opt_flow(){
      cv::destroyWindow("Video");
      //cv::destroyWindow("OPT_FLOW-X");
      //cv::destroyWindow("OPT_FLOW-Y");
      cv::destroyWindow("OPT_FLOW");
      cv::destroyWindow("Contours");
      cv::destroyWindow("Trackbars");
    }

    void play(){
      int i=0;
      while (char(cv::waitKey(1))!='q'&&video.isOpened()){
        video >> frame;

        if (i==0){
          cv::cvtColor(frame,prev_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(prev_frame,prev_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
        }

        if(i!=0&&i%step==0){
          //getchar();
          cv::cvtColor(frame,next_frame,cv::COLOR_BGR2GRAY);
          cv::GaussianBlur(next_frame,next_frame,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);

          //std::cout << "PREV_FRAME:" << prev_frame.size() << '|' << prev_frame.channels() << '\n';
          //std::cout << "NEXT_FRAME:" << next_frame.size() << '|' << next_frame.channels() << '\n';

          cv::calcOpticalFlowFarneback(prev_frame, next_frame, opt_flow,
                                      pyr_scale/10.0, levels, winsize,
                                      iterations, poly_n, poly_sigma, 0);
          //draw_flow(opt_flow,frame);

          get_xvals(opt_flow);
          get_yvals(opt_flow);
          generate_flowmask(x_vals,y_vals);
          cv::GaussianBlur(flow_mask,flow_mask,cv::Size(kernel_size,kernel_size) ,0,0,cv::BORDER_DEFAULT);
          cv::threshold(flow_mask,flow_mask,threshold, threshold*ratio,cv::THRESH_BINARY);

          flow_mask.convertTo(cont_mask,CV_8U);

          cv::findContours(cont_mask,contours, hierarchy, CV_RETR_EXTERNAL,CV_CHAIN_APPROX_NONE);
          get_contours(flow_mask);
          create_trackbars();

          show_frame();
          //print_moving_objects_vector();
          //getchar();

          prev_frame=next_frame.clone();
        }

        std::cout << "i = " << i << '\n';
        i++;
      }
    }

    void show_frame(){
      cv::imshow("Video",frame);
      cv::imshow("OPT_FLOW",flow_mask);
      cv::imshow("Contours",cont_mask);
    }

    void create_trackbars(){
      cv::createTrackbar("Pyramid Scale", "Trackbars", &pyr_scale, 9);
      cv::createTrackbar("Levels", "Trackbars", &levels, 10);
      cv::createTrackbar("Window Size", "Trackbars", &winsize, 50);
      cv::createTrackbar("Iterations", "Trackbars", &iterations, 10);
      cv::createTrackbar("Pixel Neighborhood Size", "Trackbars", &poly_n, 10);
    }

    void background_extr(){
      int i,j,aux_error;

      for(i=0;i<(frame.rows)-1;i++){
        for(j=0;j<(frame.cols)-1;j++){
          counter++;

          frame_intensity = frame.at<uint>(i,j);
          next_frame_intensity = next_frame.at<uint>(i,j);

          if (next_frame_intensity.val[0]==0){
            next_frame_intensity.val[0]=1;
          }
          errors=frame_intensity.val[0]/next_frame_intensity.val[0];

          if(errors<1-std_error||errors>1+std_error){
            opt_flow.at<uint>(i,j)=255;
            //std::cout << "MUDOU O PIXEL" << '\n';
          }
        }
      }
      //std::cout << "TROCOU FRAME" << '\n';

    }

    void blackfy(cv::Mat input){
      for(int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          input.at<uint>(i,j)=0;
          //std::cout << "(" << i << "," << j << ")" << '\n';
        }
      }
    }

    void draw_flow(cv::Mat input, cv::Mat output){
      for (int y = 0; y < output.rows; y += interval_pixels) {
          for (int x = 0; x < output.cols; x += interval_pixels)
          {
              const cv::Point2f flowatxy = input.at<cv::Point2f>(y, x) * tam_vel;
              cv::line(output, cv::Point(x, y), cv::Point(cvRound(x + flowatxy.x), cvRound(y + flowatxy.y)), cv::Scalar(255, 0, 0));
              cv::circle(output, cv::Point(x, y), 1, cv::Scalar(0, 0, 0), -1);
          }
      }
    }

    void get_xvals(cv::Mat input){
      x_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "X_VALS:" << x_vals.size() << '|' << x_vals.channels() << '|' << x_vals.type() << '\n';

          x_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).x;
        }
      }
    }

    void get_yvals(cv::Mat input){
      y_vals=cv::Mat::zeros(input.rows,input.cols, CV_32F);

      for (int i=0;i<input.rows;i++){
        for(int j=0;j<input.cols;j++){
          //std::cout << "Y_VALS:" << y_vals.size() << '|' << y_vals.channels() << '|' << y_vals.type() << '\n';

          y_vals.at<float>(i,j)=input.at<cv::Point2f>(i,j).y;
        }
      }
    }

    void generate_flowmask(cv::Mat x_matrix,cv::Mat y_matrix) {

      flow_mask=cv::Mat::zeros(x_matrix.rows,x_matrix.cols, CV_32F);

      for (int i=0;i<x_matrix.rows;i++){
        for(int j=0;j<x_matrix.cols;j++){
          flow_mask.at<float>(i,j)=magnitude(x_matrix.at<float>(i,j), y_matrix.at<float>(i,j));
        }
      }
    }

    float magnitude(float a, float b){
      float mag;

      mag=sqrt((a*a)+(b*b));

      return(mag);
    }

    void get_contours(cv::Mat input){
      std::vector<std::vector<cv::Point> > contours_poly(contours.size());
      std::vector<cv::Rect> boundRect(contours.size());

      for(int i=0;i<contours.size();i++){
        cv::approxPolyDP(cv::Mat(contours[i]),contours_poly[i],3,true );
        boundRect[i] = cv::boundingRect(cv::Mat(contours_poly[i]));
        draw_rectangles(boundRect);
        get_mov_obj(boundRect);
     }
    }

    void draw_rectangles(std::vector<cv::Rect> boundRect){
      for(int i=0; i< contours.size(); i++ ){
        rectangle(frame, boundRect[i].tl(), boundRect[i].br(), cv::Scalar(0,0,255), 2, 8, 0 );
      }
    }

    void get_mov_obj(std::vector<cv::Rect> boundRect){
      cv::Point2f origin_point_aux;
      for (int i=0;i<contours.size();i++){
        origin_point_aux.x=boundRect[i].x;
        origin_point_aux.y=boundRect[i].y;
        MovObj aux(origin_point_aux,boundRect[i].height,boundRect[i].width,boundRect[i].area());
        mov_objects.push_back(aux);
        /*std::cout << "Object i=" << i << ':' << '\n';
        std::cout << "Height:" << mov_objects[i].get_height() << '\n';
        std::cout << "Width:" << mov_objects[i].get_width() << '\n';
        getchar();*/
      }
    }

    void print_moving_objects_vector(){
      for(int i=0;i<mov_objects.size();i++){
        std::cout << "i=" << i << '\n';
        std::cout << "Height:" << mov_objects[i].get_height() << '\n';
        std::cout << "Width:" << mov_objects[i].get_width() << '\n';
        std::cout << "Area:" << mov_objects[i].get_area() << '\n';
        std::cout << "Origin Point:" << mov_objects[i].get_origin() << '\n';
        std::cout << "----------------------------------" << '\n';
      }
    }
};

//--------------------- Global Variables ---------------------

//--------------------- Main Function ---------------------

int main(int argc, char *argv[]){
  cv::String filename;
  cv::VideoCapture video;

  if (argc<=1){
    std::cout << "\n\nThere was no input video to run.\nPress ENTER to quit.\n>>";
    getchar();
    return(-1);
  }

  filename=argv[1];

  Opt_flow opt_flow(video,filename);
  opt_flow.play();

  return(0);
}
<|endoftext|>