<commit_before>//===- unittests/Basic/LexerTest.cpp ------ Lexer tests -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Config/config.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace clang;

namespace {

// The test fixture.
class LexerTest : public ::testing::Test {
protected:
  LexerTest()
    : FileMgr(FileMgrOpts),
      DiagID(new DiagnosticIDs()),
      Diags(DiagID, new IgnoringDiagConsumer()),
      SourceMgr(Diags, FileMgr) {
    TargetOpts.Triple = "x86_64-apple-darwin11.1.0";
    Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
  }

  FileSystemOptions FileMgrOpts;
  FileManager FileMgr;
  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
  DiagnosticsEngine Diags;
  SourceManager SourceMgr;
  LangOptions LangOpts;
  TargetOptions TargetOpts;
  llvm::IntrusiveRefCntPtr<TargetInfo> Target;
};

class VoidModuleLoader : public ModuleLoader {
  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
                             Module::NameVisibilityKind Visibility,
                             bool IsInclusionDirective) {
    return 0;
  }
};

TEST_F(LexerTest, LexAPI) {
  const char *source =
    "#define M(x) [x]\n"
    "M(foo)";
  MemoryBuffer *buf = MemoryBuffer::getMemBuffer(source);
  FileID mainFileID = SourceMgr.createMainFileIDForMemBuffer(buf);

  VoidModuleLoader ModLoader;
  HeaderSearch HeaderInfo(FileMgr, Diags, LangOpts);
  Preprocessor PP(Diags, LangOpts,
                  Target.getPtr(),
                  SourceMgr, HeaderInfo, ModLoader,
                  /*IILookup =*/ 0,
                  /*OwnsHeaderSearch =*/false,
                  /*DelayInitialization =*/ false);
  PP.EnterMainSourceFile();

  std::vector<Token> toks;
  while (1) {
    Token tok;
    PP.Lex(tok);
    if (tok.is(tok::eof))
      break;
    toks.push_back(tok);
  }

  // Make sure we got the tokens that we expected.
  ASSERT_EQ(3U, toks.size());
  ASSERT_EQ(tok::l_square, toks[0].getKind());
  ASSERT_EQ(tok::identifier, toks[1].getKind());
  ASSERT_EQ(tok::r_square, toks[2].getKind());

  SourceLocation lsqrLoc = toks[0].getLocation();
  SourceLocation idLoc = toks[1].getLocation();
  SourceLocation rsqrLoc = toks[2].getLocation();
  std::pair<SourceLocation,SourceLocation>
    macroPair = SourceMgr.getExpansionRange(lsqrLoc);
  SourceRange macroRange = SourceRange(macroPair.first, macroPair.second);

  SourceLocation Loc;
  EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc));
  EXPECT_EQ(Loc, macroRange.getBegin());
  EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts));
  EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts));
  EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc));
  EXPECT_EQ(Loc, macroRange.getEnd());

  CharSourceRange range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, idLoc),
                                                   SourceMgr, LangOpts);
  EXPECT_TRUE(range.isInvalid());
  range = Lexer::makeFileCharRange(SourceRange(idLoc, rsqrLoc),
                                   SourceMgr, LangOpts);
  EXPECT_TRUE(range.isInvalid());
  range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, rsqrLoc),
                                   SourceMgr, LangOpts);
  EXPECT_TRUE(!range.isTokenRange());
  EXPECT_EQ(range.getAsRange(),
            SourceRange(macroRange.getBegin(),
                        macroRange.getEnd().getLocWithOffset(1)));

  StringRef text = Lexer::getSourceText(
                  CharSourceRange::getTokenRange(SourceRange(lsqrLoc, rsqrLoc)),
                  SourceMgr, LangOpts);
  EXPECT_EQ(text, "M(foo)");
}

} // anonymous namespace
<commit_msg>Silence set-but-unused warning.<commit_after>//===- unittests/Basic/LexerTest.cpp ------ Lexer tests -------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/ModuleLoader.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/Preprocessor.h"
#include "llvm/Config/config.h"

#include "gtest/gtest.h"

using namespace llvm;
using namespace clang;

namespace {

// The test fixture.
class LexerTest : public ::testing::Test {
protected:
  LexerTest()
    : FileMgr(FileMgrOpts),
      DiagID(new DiagnosticIDs()),
      Diags(DiagID, new IgnoringDiagConsumer()),
      SourceMgr(Diags, FileMgr) {
    TargetOpts.Triple = "x86_64-apple-darwin11.1.0";
    Target = TargetInfo::CreateTargetInfo(Diags, TargetOpts);
  }

  FileSystemOptions FileMgrOpts;
  FileManager FileMgr;
  llvm::IntrusiveRefCntPtr<DiagnosticIDs> DiagID;
  DiagnosticsEngine Diags;
  SourceManager SourceMgr;
  LangOptions LangOpts;
  TargetOptions TargetOpts;
  llvm::IntrusiveRefCntPtr<TargetInfo> Target;
};

class VoidModuleLoader : public ModuleLoader {
  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
                             Module::NameVisibilityKind Visibility,
                             bool IsInclusionDirective) {
    return 0;
  }
};

TEST_F(LexerTest, LexAPI) {
  const char *source =
    "#define M(x) [x]\n"
    "M(foo)";
  MemoryBuffer *buf = MemoryBuffer::getMemBuffer(source);
  SourceMgr.createMainFileIDForMemBuffer(buf);

  VoidModuleLoader ModLoader;
  HeaderSearch HeaderInfo(FileMgr, Diags, LangOpts);
  Preprocessor PP(Diags, LangOpts,
                  Target.getPtr(),
                  SourceMgr, HeaderInfo, ModLoader,
                  /*IILookup =*/ 0,
                  /*OwnsHeaderSearch =*/false,
                  /*DelayInitialization =*/ false);
  PP.EnterMainSourceFile();

  std::vector<Token> toks;
  while (1) {
    Token tok;
    PP.Lex(tok);
    if (tok.is(tok::eof))
      break;
    toks.push_back(tok);
  }

  // Make sure we got the tokens that we expected.
  ASSERT_EQ(3U, toks.size());
  ASSERT_EQ(tok::l_square, toks[0].getKind());
  ASSERT_EQ(tok::identifier, toks[1].getKind());
  ASSERT_EQ(tok::r_square, toks[2].getKind());

  SourceLocation lsqrLoc = toks[0].getLocation();
  SourceLocation idLoc = toks[1].getLocation();
  SourceLocation rsqrLoc = toks[2].getLocation();
  std::pair<SourceLocation,SourceLocation>
    macroPair = SourceMgr.getExpansionRange(lsqrLoc);
  SourceRange macroRange = SourceRange(macroPair.first, macroPair.second);

  SourceLocation Loc;
  EXPECT_TRUE(Lexer::isAtStartOfMacroExpansion(lsqrLoc, SourceMgr, LangOpts, &Loc));
  EXPECT_EQ(Loc, macroRange.getBegin());
  EXPECT_FALSE(Lexer::isAtStartOfMacroExpansion(idLoc, SourceMgr, LangOpts));
  EXPECT_FALSE(Lexer::isAtEndOfMacroExpansion(idLoc, SourceMgr, LangOpts));
  EXPECT_TRUE(Lexer::isAtEndOfMacroExpansion(rsqrLoc, SourceMgr, LangOpts, &Loc));
  EXPECT_EQ(Loc, macroRange.getEnd());

  CharSourceRange range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, idLoc),
                                                   SourceMgr, LangOpts);
  EXPECT_TRUE(range.isInvalid());
  range = Lexer::makeFileCharRange(SourceRange(idLoc, rsqrLoc),
                                   SourceMgr, LangOpts);
  EXPECT_TRUE(range.isInvalid());
  range = Lexer::makeFileCharRange(SourceRange(lsqrLoc, rsqrLoc),
                                   SourceMgr, LangOpts);
  EXPECT_TRUE(!range.isTokenRange());
  EXPECT_EQ(range.getAsRange(),
            SourceRange(macroRange.getBegin(),
                        macroRange.getEnd().getLocWithOffset(1)));

  StringRef text = Lexer::getSourceText(
                  CharSourceRange::getTokenRange(SourceRange(lsqrLoc, rsqrLoc)),
                  SourceMgr, LangOpts);
  EXPECT_EQ(text, "M(foo)");
}

} // anonymous namespace
<|endoftext|>


<commit_before>// THIS FILE IS AUTO GENERATED, EDIT AT YOUR OWN RISK

#include <tuple>
#include "ComponentImplementationInclude.h"

#define myoffsetof(st, m) static_cast<int>((size_t)(&((st *)0)->m))

// Implementation of the base entity class

// Constructor of entity
Entity::Entity(const MessageHandler *messageHandlers, const int* componentOffsets
    {% for attrib in general.common_entity_attributes %}
        ,{{attrib.get_declaration()}}
    {% endfor %}
): messageHandlers(messageHandlers), componentOffsets(componentOffsets)
    {% for attrib in general.common_entity_attributes %}
        ,{{attrib.get_initializer()}}
    {% endfor %}
{
}

Entity::~Entity() {
}

void Entity::SendMessage(int msg, const void* data) {
    MessageHandler handler = messageHandlers[msg];
    if (handler) {
        handler(this, data);
    }
}

// Entity helper functions to send message e.g.
//   void Entity::Damage(int value);
{% for message in messages %}
    void Entity::{{message.name}}({{message.get_function_args()}}) {
        {% if message.get_num_args() == 0 %}
            SendMessage({{message.get_enum_name()}}, nullptr);
        {% else %}
            {{message.get_tuple_type()}} data({{message.get_args_names()}});
            SendMessage({{message.get_enum_name()}}, &data);
        {% endif %}
    }
{% endfor %}

// Entity helper functions to get the components e.g.
//   HealthComponent* GetHealthComponent();
{% for component in components %}
    {{component.get_type_name()}}* Entity::Get{{component.get_type_name()}}() {
        int index = {{component.get_priority()}};
        int offset = componentOffsets[index];
        if (offset) {
            return ({{component.get_type_name()}}*) (((char*) this) + offset);
        } else {
            return nullptr;
        }
    }
{% endfor %}

// Implementation of the components

// Component helper functions to change the attributes values e.g.
//   void SetHealth(int value);
{% for component in components %}
    {% for attrib in component.get_own_attribs() %}
        void {{component.get_base_type_name()}}::{{attrib.get_setter_name()}}({{attrib.typ}} value) {
            entity->SendMessage({{attrib.get_message().get_enum_name()}}, new {{attrib.typ}}(value));
        }
    {% endfor %}
{% endfor %}

// Implementation of the entities

{% for entity in entities %}
    // The vtable of offset of components in an entity
    // TODO: doesn't handle component inheritance?
    const int {{entity.get_type_name()}}::componentOffsets[] = {
        {% for component in components %}
            {% if component in entity.get_components() %}
                myoffsetof({{entity.get_type_name()}}, {{component.get_variable_name()}}),
            {% else %}
                0,
            {% endif %}
        {% endfor %}
    };

    // The static message handlers put in the vtable
    {% for message in entity.get_messages_to_handle() %}
        void {{entity.get_message_handler_name(message)}}(Entity* _entity, const void* {% if message.get_num_args() > 0 %} _data {% endif %} ) {
            // Cast the entity to the correct type (receive an Entity*)
            {{entity.get_type_name()}}* entity = ({{entity.get_type_name()}}*) _entity;

            {% if message.get_num_args() == 0 %}
                // No argument for the message, just call the handlers of all the components
                {% for component in entity.get_components() %}
                    {% if message in component.get_messages_to_handle() %}
                        entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}();
                    {% endif %}
                {% endfor %}
            {% else %}
                // Cast the message content to the right type (receive a const void*)
                const {{message.get_tuple_type()}}* data = (const {{message.get_tuple_type()}}*) _data;
                {% for component in entity.get_components() %}
                    {% if message in component.get_messages_to_handle() %}
                        entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}({{message.get_unpacked_tuple_args('*data')}});
                    {% endif %}
                {% endfor %}
            {% endif %}

            // The message is for an attribute change, update the value accordingly
            {% if message.is_attrib() %}
                entity->{{message.get_attrib().get_variable_name()}} = std::get<0>(*data);
            {% endif %}
        }
    {% endfor%}

    // The vtable of message handlers for an entity
    const MessageHandler {{entity.get_type_name()}}::messageHandlers[] = {
        {% for message in messages %}
            {% if message in entity.get_messages_to_handle() %}
                {{entity.get_message_handler_name(message)}},
            {% else %}
                nullptr,
            {% endif %}
        {% endfor%}
    };

    // Fat constructor for the entity that initializes the components.
    {{entity.get_type_name()}}::{{entity.get_type_name()}}(
        {% for (i, attrib) in enumerate(general.common_entity_attributes) %}
            {% if i != 0 %}, {% endif %} {{attrib.get_declaration()}}
        {% endfor %}
    ): Entity(messageHandlers, componentOffsets
        {% for attrib in general.common_entity_attributes %}
            ,{{attrib.get_name()}}
        {% endfor %}
    )
    {% for component in entity.get_components() %}
        // Each component takes the entity it is in, its parameters, the shared attributes and the components it requires
        , {{component.get_variable_name()}}(new {{component.get_type_name()}}(
            this
            {% for param in component.get_param_names() %}
                , {{entity.get_params()[component.name][param]}}
            {% endfor %}
            {% for attrib in component.get_attribs() %}
                , {{attrib.get_variable_name()}}
            {% endfor %}
            {% for required in component.get_required_components() %}
                , {{required.get_variable_name()}}
            {% endfor %}
        ))
    {% endfor %}
    {}

    // The destructor of the entity destroys all the components in reverse order
    {{entity.get_type_name()}}::~{{entity.get_type_name()}}() {
        {% for component in entity.get_components()[::-1] %}
            delete {{component.get_variable_name()}};
        {% endfor %}
    }

{% endfor %}

#undef myoffsetof

<commit_msg>Fix the Get*Component returning a bad pointer<commit_after>// THIS FILE IS AUTO GENERATED, EDIT AT YOUR OWN RISK

#include <tuple>
#include "ComponentImplementationInclude.h"

#define myoffsetof(st, m) static_cast<int>((size_t)(&((st *)0)->m))

// Implementation of the base entity class

// Constructor of entity
Entity::Entity(const MessageHandler *messageHandlers, const int* componentOffsets
    {% for attrib in general.common_entity_attributes %}
        ,{{attrib.get_declaration()}}
    {% endfor %}
): messageHandlers(messageHandlers), componentOffsets(componentOffsets)
    {% for attrib in general.common_entity_attributes %}
        ,{{attrib.get_initializer()}}
    {% endfor %}
{
}

Entity::~Entity() {
}

void Entity::SendMessage(int msg, const void* data) {
    MessageHandler handler = messageHandlers[msg];
    if (handler) {
        handler(this, data);
    }
}

// Entity helper functions to send message e.g.
//   void Entity::Damage(int value);
{% for message in messages %}
    void Entity::{{message.name}}({{message.get_function_args()}}) {
        {% if message.get_num_args() == 0 %}
            SendMessage({{message.get_enum_name()}}, nullptr);
        {% else %}
            {{message.get_tuple_type()}} data({{message.get_args_names()}});
            SendMessage({{message.get_enum_name()}}, &data);
        {% endif %}
    }
{% endfor %}

// Entity helper functions to get the components e.g.
//   HealthComponent* GetHealthComponent();
{% for component in components %}
    {{component.get_type_name()}}* Entity::Get{{component.get_type_name()}}() {
        int index = {{component.get_priority()}};
        int offset = componentOffsets[index];
        if (offset) {
            return *({{component.get_type_name()}}**) (((char*) this) + offset);
        } else {
            return nullptr;
        }
    }
{% endfor %}

// Implementation of the components

// Component helper functions to change the attributes values e.g.
//   void SetHealth(int value);
{% for component in components %}
    {% for attrib in component.get_own_attribs() %}
        void {{component.get_base_type_name()}}::{{attrib.get_setter_name()}}({{attrib.typ}} value) {
            entity->SendMessage({{attrib.get_message().get_enum_name()}}, new {{attrib.typ}}(value));
        }
    {% endfor %}
{% endfor %}

// Implementation of the entities

{% for entity in entities %}
    // The vtable of offset of components in an entity
    // TODO: doesn't handle component inheritance?
    const int {{entity.get_type_name()}}::componentOffsets[] = {
        {% for component in components %}
            {% if component in entity.get_components() %}
                myoffsetof({{entity.get_type_name()}}, {{component.get_variable_name()}}),
            {% else %}
                0,
            {% endif %}
        {% endfor %}
    };

    // The static message handlers put in the vtable
    {% for message in entity.get_messages_to_handle() %}
        void {{entity.get_message_handler_name(message)}}(Entity* _entity, const void* {% if message.get_num_args() > 0 %} _data {% endif %} ) {
            // Cast the entity to the correct type (receive an Entity*)
            {{entity.get_type_name()}}* entity = ({{entity.get_type_name()}}*) _entity;

            {% if message.get_num_args() == 0 %}
                // No argument for the message, just call the handlers of all the components
                {% for component in entity.get_components() %}
                    {% if message in component.get_messages_to_handle() %}
                        entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}();
                    {% endif %}
                {% endfor %}
            {% else %}
                // Cast the message content to the right type (receive a const void*)
                const {{message.get_tuple_type()}}* data = (const {{message.get_tuple_type()}}*) _data;
                {% for component in entity.get_components() %}
                    {% if message in component.get_messages_to_handle() %}
                        entity->{{component.get_variable_name()}}->{{message.get_handler_name()}}({{message.get_unpacked_tuple_args('*data')}});
                    {% endif %}
                {% endfor %}
            {% endif %}

            // The message is for an attribute change, update the value accordingly
            {% if message.is_attrib() %}
                entity->{{message.get_attrib().get_variable_name()}} = std::get<0>(*data);
            {% endif %}
        }
    {% endfor%}

    // The vtable of message handlers for an entity
    const MessageHandler {{entity.get_type_name()}}::messageHandlers[] = {
        {% for message in messages %}
            {% if message in entity.get_messages_to_handle() %}
                {{entity.get_message_handler_name(message)}},
            {% else %}
                nullptr,
            {% endif %}
        {% endfor%}
    };

    // Fat constructor for the entity that initializes the components.
    {{entity.get_type_name()}}::{{entity.get_type_name()}}(
        {% for (i, attrib) in enumerate(general.common_entity_attributes) %}
            {% if i != 0 %}, {% endif %} {{attrib.get_declaration()}}
        {% endfor %}
    ): Entity(messageHandlers, componentOffsets
        {% for attrib in general.common_entity_attributes %}
            ,{{attrib.get_name()}}
        {% endfor %}
    )
    {% for component in entity.get_components() %}
        // Each component takes the entity it is in, its parameters, the shared attributes and the components it requires
        , {{component.get_variable_name()}}(new {{component.get_type_name()}}(
            this
            {% for param in component.get_param_names() %}
                , {{entity.get_params()[component.name][param]}}
            {% endfor %}
            {% for attrib in component.get_attribs() %}
                , {{attrib.get_variable_name()}}
            {% endfor %}
            {% for required in component.get_required_components() %}
                , {{required.get_variable_name()}}
            {% endfor %}
        ))
    {% endfor %}
    {}

    // The destructor of the entity destroys all the components in reverse order
    {{entity.get_type_name()}}::~{{entity.get_type_name()}}() {
        {% for component in entity.get_components()[::-1] %}
            delete {{component.get_variable_name()}};
        {% endfor %}
    }

{% endfor %}

#undef myoffsetof

<|endoftext|>


<commit_before>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2017                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/onscreengui/include/guiorigincomponent.h>

#include <openspace/engine/openspaceengine.h>
#include <openspace/interaction/interactionhandler.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>

#include <ghoul/misc/assert.h>

#include "imgui.h"

namespace openspace {
namespace gui {

GuiOriginComponent::GuiOriginComponent()
    : GuiComponent("Origin")
{}

void GuiOriginComponent::render() {
    SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode();

    std::vector<SceneGraphNode*> nodes =
        OsEng.renderEngine().scene()->allSceneGraphNodes();

    std::sort(
        nodes.begin(),
        nodes.end(),
        [](SceneGraphNode* lhs, SceneGraphNode* rhs) {
            return lhs->name() < rhs->name();
        }
    );
    std::string nodeNames = "";
    for (SceneGraphNode* n : nodes) {
        nodeNames += n->name() + '\0';
    }

    auto iCurrentFocus = std::find(nodes.begin(), nodes.end(), currentFocus);
    ghoul_assert(iCurrentFocus != nodes.end(), "Focus node not found");
    int currentPosition = static_cast<int>(std::distance(iCurrentFocus, nodes.begin()));

    bool hasChanged = ImGui::Combo("Origin", &currentPosition, nodeNames.c_str());
    if (hasChanged) {
        OsEng.scriptEngine().queueScript(
            "openspace.setPropertyValue('Interaction.origin', '" +
            nodes[currentPosition]->name() + "');",
            scripting::ScriptEngine::RemoteScripting::Yes
        );
    }
}

} // gui
} // openspace
<commit_msg>Don't assert if the focus node is not found if there are no nodes at all<commit_after>/*****************************************************************************************
 *                                                                                *
 * OpenSpace                                                                             *
 *                                                                                *
 * Copyright (c) 2014-2017                                                               *
 *                                                                                *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this  *
 * software and associated documentation files (the "Software"), to deal in the Software *
 * without restriction, including without limitation the rights to use, copy, modify,    *
 * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to    *
 * permit persons to whom the Software is furnished to do so, subject to the following   *
 * conditions:                                                                           *
 *                                                                                *
 * The above copyright notice and this permission notice shall be included in all copies *
 * or substantial portions of the Software.                                              *
 *                                                                                *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,   *
 * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A         *
 * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT    *
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF  *
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE  *
 * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                                         *
 ****************************************************************************************/

#include <modules/onscreengui/include/guiorigincomponent.h>

#include <openspace/engine/openspaceengine.h>
#include <openspace/interaction/interactionhandler.h>
#include <openspace/rendering/renderengine.h>
#include <openspace/scene/scenegraphnode.h>

#include <ghoul/misc/assert.h>

#include "imgui.h"

namespace openspace {
namespace gui {

GuiOriginComponent::GuiOriginComponent()
    : GuiComponent("Origin")
{}

void GuiOriginComponent::render() {
    SceneGraphNode* currentFocus = OsEng.interactionHandler().focusNode();

    std::vector<SceneGraphNode*> nodes =
        OsEng.renderEngine().scene()->allSceneGraphNodes();

    std::sort(
        nodes.begin(),
        nodes.end(),
        [](SceneGraphNode* lhs, SceneGraphNode* rhs) {
            return lhs->name() < rhs->name();
        }
    );
    std::string nodeNames = "";
    for (SceneGraphNode* n : nodes) {
        nodeNames += n->name() + '\0';
    }

    auto iCurrentFocus = std::find(nodes.begin(), nodes.end(), currentFocus);
    if (!nodes.empty()) {
        // Only check if we found the current focus node if we have any nodes at all
        // only then it would be a real error
        ghoul_assert(iCurrentFocus != nodes.end(), "Focus node not found");
    }
    int currentPosition = static_cast<int>(std::distance(iCurrentFocus, nodes.begin()));

    bool hasChanged = ImGui::Combo("Origin", &currentPosition, nodeNames.c_str());
    if (hasChanged) {
        OsEng.scriptEngine().queueScript(
            "openspace.setPropertyValue('Interaction.origin', '" +
            nodes[currentPosition]->name() + "');",
            scripting::ScriptEngine::RemoteScripting::Yes
        );
    }
}

} // gui
} // openspace
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2019 Nagisa Sekiguchi
 *
 * 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 <sys/utsname.h>

#include <regex>
#include <fstream>

#include <misc/util.hpp>
#include <constant.h>
#include "platform.h"

namespace ydsh {
namespace platform {

static bool reSearch(const char *reStr, const std::string &value) {
    std::regex re(reStr, std::regex_constants::ECMAScript | std::regex_constants::icase);
    std::smatch match;
    return std::regex_search(value, match, re);
}

const char *toString(PlatformType c) {
    const char *table[] = {
#define GEN_STR(E) #E,
            EACH_PLATFORM_TYPE(GEN_STR)
#undef GEN_STR
    };
    return table[static_cast<unsigned int>(c)];
}

static bool detectContainer() {
    std::ifstream stream("/proc/1/cgroup");
    if(!stream) {
        return false;
    }
    for(std::string line; std::getline(stream, line); ) {
        if(reSearch("docker|lxc", line)) {
            return true;
        }
    }
    return false;
}

static PlatformType detectImpl() {
    struct utsname name{};
    if(uname(&name) == -1) {
        return PlatformType::UNKNOWN;
    }

    std::string sysName = name.sysname;
    if(reSearch("linux", sysName)) {
        if(reSearch("microsoft", name.release)) {
            return PlatformType::WSL;
        }
        if(detectContainer()) {
            return PlatformType::CONTAINER;
        }
        return PlatformType::LINUX;
    }
    if(reSearch("darwin", sysName)) {
        return PlatformType::DARWIN;
    }
    if(reSearch("cygwin", sysName)) {
        return PlatformType::CYGWIN;
    }
    return PlatformType::UNKNOWN;
}

PlatformType platform() {
    static auto p = detectImpl();
    return p;
}

bool containPlatform(const std::string &text, PlatformType type) {
    return reSearch(toString(type), text);
}

const char *toString(ArchType c) {
    const char *table[] = {
#define GEN_STR(E, S) #E,
            EACH_ARCH_TYPE(GEN_STR)
#undef GEN_STR
    };
    return table[static_cast<unsigned int>(c)];
}

static ArchType archImpl() {
    ArchType types[] = {
#define GEN_ENUM(E, S) ArchType::E,
        EACH_ARCH_TYPE(GEN_ENUM)
#undef GEN_ENUM
    };
    for(auto &type : types) {
        if(containArch(BUILD_ARCH, type)) {
            return type;
        }
    }
    return ArchType::UNKNOWN;
}

ArchType arch() {
    static auto a = archImpl();
    return a;
}

bool containArch(const std::string &text, ArchType type) {
    const char *table[] = {
#define GEN_STR(E, S) #E "|" S,
        EACH_ARCH_TYPE(GEN_STR)
#undef GEN_STR
    };
    return reSearch(table[static_cast<unsigned int>(type)], text);
}

} // namespace platform
} // namespace ydsh<commit_msg>support containerd in platform detection<commit_after>/*
 * Copyright (C) 2019 Nagisa Sekiguchi
 *
 * 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 <sys/utsname.h>

#include <regex>
#include <fstream>

#include <misc/util.hpp>
#include <constant.h>
#include "platform.h"

namespace ydsh {
namespace platform {

static bool reSearch(const char *reStr, const std::string &value) {
    std::regex re(reStr, std::regex_constants::ECMAScript | std::regex_constants::icase);
    std::smatch match;
    return std::regex_search(value, match, re);
}

const char *toString(PlatformType c) {
    const char *table[] = {
#define GEN_STR(E) #E,
            EACH_PLATFORM_TYPE(GEN_STR)
#undef GEN_STR
    };
    return table[static_cast<unsigned int>(c)];
}

static bool detectContainer() {
    std::ifstream stream("/proc/1/cgroup");
    if(!stream) {
        return false;
    }
    for(std::string line; std::getline(stream, line); ) {
        if(reSearch("docker|lxc|containerd", line)) {
            return true;
        }
    }
    return false;
}

static PlatformType detectImpl() {
    struct utsname name{};
    if(uname(&name) == -1) {
        return PlatformType::UNKNOWN;
    }

    std::string sysName = name.sysname;
    if(reSearch("linux", sysName)) {
        if(reSearch("microsoft", name.release)) {
            return PlatformType::WSL;
        }
        if(detectContainer()) {
            return PlatformType::CONTAINER;
        }
        return PlatformType::LINUX;
    }
    if(reSearch("darwin", sysName)) {
        return PlatformType::DARWIN;
    }
    if(reSearch("cygwin", sysName)) {
        return PlatformType::CYGWIN;
    }
    return PlatformType::UNKNOWN;
}

PlatformType platform() {
    static auto p = detectImpl();
    return p;
}

bool containPlatform(const std::string &text, PlatformType type) {
    return reSearch(toString(type), text);
}

const char *toString(ArchType c) {
    const char *table[] = {
#define GEN_STR(E, S) #E,
            EACH_ARCH_TYPE(GEN_STR)
#undef GEN_STR
    };
    return table[static_cast<unsigned int>(c)];
}

static ArchType archImpl() {
    ArchType types[] = {
#define GEN_ENUM(E, S) ArchType::E,
        EACH_ARCH_TYPE(GEN_ENUM)
#undef GEN_ENUM
    };
    for(auto &type : types) {
        if(containArch(BUILD_ARCH, type)) {
            return type;
        }
    }
    return ArchType::UNKNOWN;
}

ArchType arch() {
    static auto a = archImpl();
    return a;
}

bool containArch(const std::string &text, ArchType type) {
    const char *table[] = {
#define GEN_STR(E, S) #E "|" S,
        EACH_ARCH_TYPE(GEN_STR)
#undef GEN_STR
    };
    return reSearch(table[static_cast<unsigned int>(type)], text);
}

} // namespace platform
} // namespace ydsh<|endoftext|>


<commit_before>#include "ssaorenderpass.hpp"
#include "../../engine.hpp"
#include <random>
#include <world/component/transformcomponent.hpp>

SSAORenderSystem::SSAORenderSystem(int width, int height)
{
	shaderProgram
		.attach("assets/shaders/ssao.vert", ShaderType::vertex)
		.attach("assets/shaders/ssao.frag", ShaderType::fragment)
		.finalize();

	shaderProgram
		.addUniform("positionMap")
		.addUniform("normalMap")
		.addUniform("noiseMap")
		.addUniform("noiseScale")
		.addUniform("nrOfSamples")
		.addUniform("sampleRadius")
		.addUniform("sampleBias")
		.addUniform("samplePoints")
		.addUniform("viewMatrix")
		.addUniform("projectionMatrix");

	gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1);

	shaderProgram.bind();
	generateUniformData(width, height);
}

float SSAORenderSystem::lerp(float a, float b, float f)
{
	return a + f * (b - a);
}

void SSAORenderSystem::generateUniformData(int width, int height)
{
	std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0);
	std::default_random_engine generator;

	std::vector<glm::vec3> samplePoints;
	for (size_t i = 0; i < 64; i++)
	{
		glm::vec3 samplePoint = {
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator)
		};

		samplePoint = glm::normalize(samplePoint);
		samplePoint *= randomFlaots(generator);

		float scale = float(i) / 64.0;
		scale = lerp(0.1, 1.0, scale * scale);

		samplePoint *= scale;

		samplePoints.push_back(samplePoint);
	}

	shaderProgram.setUniformArray("samplePoints", samplePoints);

	std::vector<glm::vec3> noiseData;
	for (size_t i = 0; i < 16; i++)
	{
		glm::vec3 noise = {
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator) * 2.0 - 1.0,
			0.0
		};

		noiseData.push_back(noise);
	}

	noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]);
	noiseMap->bind()
		.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT)
		.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);

	attachInputTexture(3, noiseMap);
	shaderProgram.setUniform("noiseMap", 3);

	glm::vec2 noiseScale = { width / 4.0, height / 4.0 };
	shaderProgram.setUniform("noiseScale", noiseScale);

}

void SSAORenderSystem::render(World & world)
{
	CameraEntity & camera = *Engine::getInstance().getCamera();
	shaderProgram.bind();

	shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation);
	shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation);

}

<commit_msg>formating<commit_after>#include "ssaorenderpass.hpp"
#include "../../engine.hpp"
#include <random>
#include <world/component/transformcomponent.hpp>

SSAORenderSystem::SSAORenderSystem(int width, int height)
{
	shaderProgram
		.attach("assets/shaders/ssao.vert", ShaderType::vertex)
		.attach("assets/shaders/ssao.frag", ShaderType::fragment)
		.finalize();

	shaderProgram
		.addUniform("positionMap")
		.addUniform("normalMap")
		.addUniform("noiseMap")
		.addUniform("noiseScale")
		.addUniform("nrOfSamples")
		.addUniform("sampleRadius")
		.addUniform("sampleBias")
		.addUniform("samplePoints")
		.addUniform("viewMatrix")
		.addUniform("projectionMatrix");

	gBuffer.attachTexture(0, width, height, GL_RED, GL_FLOAT, 1);

	shaderProgram.bind();
	generateUniformData(width, height);
}

float SSAORenderSystem::lerp(float a, float b, float f)
{
	return a + f * (b - a);
}

void SSAORenderSystem::generateUniformData(int width, int height)
{

	shaderProgram.setUniform("positionMap", 0);
	shaderProgram.setUniform("normalMap", 1);
	shaderProgram.setUniform("normalMap", 2);

	std::uniform_real_distribution<GLfloat> randomFlaots(0.0, 1.0);
	std::default_random_engine generator;

	std::vector<glm::vec3> samplePoints;
	for (size_t i = 0; i < 64; i++)
	{
		glm::vec3 samplePoint = {
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator)
		};

		samplePoint = glm::normalize(samplePoint);
		samplePoint *= randomFlaots(generator);

		float scale = float(i) / 64.0;
		scale = lerp(0.1, 1.0, scale * scale);

		samplePoint *= scale;

		samplePoints.push_back(samplePoint);
	}

	shaderProgram.setUniformArray("samplePoints", samplePoints);

	std::vector<glm::vec3> noiseData;
	for (size_t i = 0; i < 16; i++)
	{
		glm::vec3 noise = {
			randomFlaots(generator) * 2.0 - 1.0,
			randomFlaots(generator) * 2.0 - 1.0,
			0.0
		};

		noiseData.push_back(noise);
	}

	noiseMap = std::make_shared<Texture>(width, height, GL_RGB32F, GL_RGB, GL_FLOAT, &noiseData[0]);
	noiseMap->bind()
		.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		.setParameter(GL_TEXTURE_MAG_FILTER, GL_NEAREST)
		.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT)
		.setParameter(GL_TEXTURE_WRAP_S, GL_REPEAT);

	attachInputTexture(2, noiseMap);

	glm::vec2 noiseScale = { width / 4.0, height / 4.0 };
	shaderProgram.setUniform("noiseScale", noiseScale);
}

void SSAORenderSystem::render(World & world)
{
	CameraEntity & camera = *Engine::getInstance().getCamera();
	shaderProgram.bind();

	shaderProgram.setUniform("viewMatrix", camera.getComponent<TransformComponent>()->rotation);
	shaderProgram.setUniform("projectionMatrix", camera.getComponent<TransformComponent>()->rotation);

}

<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2016 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "ordinalpropertyanimator.h"
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/exception.h>

namespace inviwo {

const ProcessorInfo OrdinalPropertyAnimator::processorInfo_{
    "org.inviwo.OrdinalPropertyAnimator",  // Class identifier
    "Property Animator",                   // Display name
    "Various",                             // Category
    CodeState::Experimental,               // Code state
    Tags::CPU,                             // Tags
};
const ProcessorInfo OrdinalPropertyAnimator::getProcessorInfo() const {
    return processorInfo_;
}

OrdinalPropertyAnimator::OrdinalPropertyAnimator()
    : Processor()
    , type_("property", "Property")
    , delay_("delay", "Delay (ms)", 50, 1, 10000, 1)
    , pbc_("pbc", "Periodic", true)
    , active_("active", "Active", false)
    , timer_(delay_, [this]() { timerEvent(); }) {
    delay_.onChange(this, &OrdinalPropertyAnimator::updateTimerInterval);

    properties_.push_back(
        std::make_unique<PrimProp<float>>("org.inviwo.FloatProperty", "org.inviwo.FloatProperty"));
    properties_.push_back(std::make_unique<VecProp<vec2>>("org.inviwo.FloatVec2Property",
                                                          "org.inviwo.FloatVec2Property"));
    properties_.push_back(std::make_unique<VecProp<vec3>>("org.inviwo.FloatVec3Property",
                                                          "org.inviwo.FloatVec3Property"));
    properties_.push_back(std::make_unique<VecProp<vec4>>("org.inviwo.FloatVec4Property",
                                                          "org.inviwo.FloatVec4Property"));
    properties_.push_back(std::make_unique<PrimProp<double>>("org.inviwo.DoubleProperty",
                                                             "org.inviwo.DoubleProperty"));
    properties_.push_back(std::make_unique<VecProp<dvec2>>("org.inviwo.DoubleVec2Property",
                                                           "org.inviwo.DoubleVec2Property"));
    properties_.push_back(std::make_unique<VecProp<dvec3>>("org.inviwo.DoubleVec3Property",
                                                           "org.inviwo.DoubleVec3Property"));
    properties_.push_back(std::make_unique<VecProp<dvec4>>("org.inviwo.DoubleVec4Property",
                                                           "org.inviwo.DoubleVec4Property"));
    properties_.push_back(
        std::make_unique<PrimProp<int>>("org.inviwo.IntProperty", "org.inviwo.IntProperty"));
    properties_.push_back(std::make_unique<VecProp<ivec2>>("org.inviwo.IntVec2Property",
                                                           "org.inviwo.IntVec2Property"));
    properties_.push_back(std::make_unique<VecProp<ivec3>>("org.inviwo.IntVec3Property",
                                                           "org.inviwo.IntVec3Property"));
    properties_.push_back(std::make_unique<VecProp<ivec4>>("org.inviwo.IntVec4Property",
                                                           "org.inviwo.IntVec4Property"));

    addProperty(type_);
    addProperty(active_);
    addProperty(delay_);
    addProperty(pbc_);

    int count = 0;
    for (auto& p : properties_) {
        type_.addOption(p->classname_, p->displayName_, count);
        Property* prop = p->getProp();
        Property* delta = p->getDelta();

        addProperty(prop, false);
        addProperty(delta, false);
        prop->setVisible(false);
        delta->setVisible(false);
        count++;
    }
    type_.setSelectedIndex(0);
    type_.setCurrentStateAsDefault();

    type_.onChange(this, &OrdinalPropertyAnimator::changeProperty);
    active_.onChange(this, &OrdinalPropertyAnimator::changeActive);

    changeProperty();

    setAllPropertiesCurrentStateAsDefault();
}

void OrdinalPropertyAnimator::initializeResources() {
    changeProperty();
    updateTimerInterval();
}

void OrdinalPropertyAnimator::updateTimerInterval() {
    timer_.stop();
    if (active_.get()) timer_.start(delay_);
}

void OrdinalPropertyAnimator::timerEvent() {
    int ind = type_.get();
    properties_[ind]->update(pbc_.get());
}

void OrdinalPropertyAnimator::changeProperty() {
    int ind = type_.get();

    for (auto& p : properties_) {
        Property* prop = p->getProp();
        Property* delta = p->getDelta();
        prop->setVisible(false);
        delta->setVisible(false);
    }

    properties_[ind]->getProp()->setVisible(true);
    properties_[ind]->getDelta()->setVisible(true);
}

void OrdinalPropertyAnimator::changeActive() {
    updateTimerInterval();
}

} // namespace

<commit_msg>Base: bugfix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2016 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include "ordinalpropertyanimator.h"
#include <inviwo/core/common/inviwoapplication.h>
#include <inviwo/core/util/exception.h>

namespace inviwo {

const ProcessorInfo OrdinalPropertyAnimator::processorInfo_{
    "org.inviwo.OrdinalPropertyAnimator",  // Class identifier
    "Property Animator",                   // Display name
    "Various",                             // Category
    CodeState::Experimental,               // Code state
    Tags::CPU,                             // Tags
};
const ProcessorInfo OrdinalPropertyAnimator::getProcessorInfo() const {
    return processorInfo_;
}

OrdinalPropertyAnimator::OrdinalPropertyAnimator()
    : Processor()
    , type_("property", "Property")
    , delay_("delay", "Delay (ms)", 50, 1, 10000, 1)
    , pbc_("pbc", "Periodic", true)
    , active_("active", "Active", false)
    , timer_(delay_, [this]() { timerEvent(); }) {
    delay_.onChange(this, &OrdinalPropertyAnimator::updateTimerInterval);

    properties_.push_back(
        util::make_unique<PrimProp<float>>("org.inviwo.FloatProperty", "org.inviwo.FloatProperty"));
    properties_.push_back(util::make_unique<VecProp<vec2>>("org.inviwo.FloatVec2Property",
                                                          "org.inviwo.FloatVec2Property"));
    properties_.push_back(util::make_unique<VecProp<vec3>>("org.inviwo.FloatVec3Property",
                                                          "org.inviwo.FloatVec3Property"));
    properties_.push_back(util::make_unique<VecProp<vec4>>("org.inviwo.FloatVec4Property",
                                                          "org.inviwo.FloatVec4Property"));
    properties_.push_back(util::make_unique<PrimProp<double>>("org.inviwo.DoubleProperty",
                                                             "org.inviwo.DoubleProperty"));
    properties_.push_back(util::make_unique<VecProp<dvec2>>("org.inviwo.DoubleVec2Property",
                                                           "org.inviwo.DoubleVec2Property"));
    properties_.push_back(util::make_unique<VecProp<dvec3>>("org.inviwo.DoubleVec3Property",
                                                           "org.inviwo.DoubleVec3Property"));
    properties_.push_back(util::make_unique<VecProp<dvec4>>("org.inviwo.DoubleVec4Property",
                                                           "org.inviwo.DoubleVec4Property"));
    properties_.push_back(
        util::make_unique<PrimProp<int>>("org.inviwo.IntProperty", "org.inviwo.IntProperty"));
    properties_.push_back(util::make_unique<VecProp<ivec2>>("org.inviwo.IntVec2Property",
                                                           "org.inviwo.IntVec2Property"));
    properties_.push_back(util::make_unique<VecProp<ivec3>>("org.inviwo.IntVec3Property",
                                                           "org.inviwo.IntVec3Property"));
    properties_.push_back(util::make_unique<VecProp<ivec4>>("org.inviwo.IntVec4Property",
                                                           "org.inviwo.IntVec4Property"));

    addProperty(type_);
    addProperty(active_);
    addProperty(delay_);
    addProperty(pbc_);

    int count = 0;
    for (auto& p : properties_) {
        type_.addOption(p->classname_, p->displayName_, count);
        Property* prop = p->getProp();
        Property* delta = p->getDelta();

        addProperty(prop, false);
        addProperty(delta, false);
        prop->setVisible(false);
        delta->setVisible(false);
        count++;
    }
    type_.setSelectedIndex(0);
    type_.setCurrentStateAsDefault();

    type_.onChange(this, &OrdinalPropertyAnimator::changeProperty);
    active_.onChange(this, &OrdinalPropertyAnimator::changeActive);

    changeProperty();

    setAllPropertiesCurrentStateAsDefault();
}

void OrdinalPropertyAnimator::initializeResources() {
    changeProperty();
    updateTimerInterval();
}

void OrdinalPropertyAnimator::updateTimerInterval() {
    timer_.stop();
    if (active_.get()) timer_.start(delay_);
}

void OrdinalPropertyAnimator::timerEvent() {
    int ind = type_.get();
    properties_[ind]->update(pbc_.get());
}

void OrdinalPropertyAnimator::changeProperty() {
    int ind = type_.get();

    for (auto& p : properties_) {
        Property* prop = p->getProp();
        Property* delta = p->getDelta();
        prop->setVisible(false);
        delta->setVisible(false);
    }

    properties_[ind]->getProp()->setVisible(true);
    properties_[ind]->getDelta()->setVisible(true);
}

void OrdinalPropertyAnimator::changeActive() {
    updateTimerInterval();
}

} // namespace

<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/algorithm/volume/volumevoronoi.h>

namespace inviwo {
namespace util {

std::shared_ptr<Volume> voronoiSegmentation(
    const size3_t volumeDimensions, const mat4& indexToModelMatrix,
    const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices,
    const std::optional<std::vector<float>>& weights, bool weightedVoronoi) {

    if (seedPointsWithIndices.size() == 0) {
        throw Exception("No seed points, cannot create volume voronoi segmentation",
                        IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    if (weightedVoronoi && weights.has_value() &&
        weights.value().size() != seedPointsWithIndices.size()) {
        throw Exception(
            "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)",
            IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions);
    auto newVolume = std::make_shared<Volume>(newVolumeRep);

    newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size()));
    newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange;

    auto volumeIndices = newVolumeRep->getDataTyped();
    util::IndexMapper3D index(volumeDimensions);

    util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
        const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;

        if (weightedVoronoi && weights.has_value()) {
            auto zipped = util::zip(seedPointsWithIndices, weights.value());

            auto&& [posWithIndex, weight] = *std::min_element(
                zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) {
                    auto&& [p1, w1] = i1;
                    auto&& [p2, w2] = i2;

                    return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 <
                           glm::distance2(p2.second, transformedVoxelPos) - w2 * w2;
                });
            volumeIndices[index(voxelPos)] = posWithIndex.first;
        } else {
            auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(),
                                       [transformedVoxelPos](const auto& p1, const auto& p2) {
                                           return glm::distance2(p1.second, transformedVoxelPos) <
                                                  glm::distance2(p2.second, transformedVoxelPos);
                                       });
            volumeIndices[index(voxelPos)] = it->first;
        }
    });

    return newVolume;
};

}  // namespace util
}  // namespace inviwo
<commit_msg>Check if weighted outside foreach<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2020 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/base/algorithm/volume/volumevoronoi.h>

namespace inviwo {
namespace util {

std::shared_ptr<Volume> voronoiSegmentation(
    const size3_t volumeDimensions, const mat4& indexToModelMatrix,
    const std::vector<std::pair<uint32_t, vec3>>& seedPointsWithIndices,
    const std::optional<std::vector<float>>& weights, bool weightedVoronoi) {

    if (seedPointsWithIndices.size() == 0) {
        throw Exception("No seed points, cannot create volume voronoi segmentation",
                        IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    if (weightedVoronoi && weights.has_value() &&
        weights.value().size() != seedPointsWithIndices.size()) {
        throw Exception(
            "Cannot use weighted voronoi when dimensions do not match (weights and seed positions)",
            IVW_CONTEXT_CUSTOM("VoronoiSegmentation"));
    }

    auto newVolumeRep = std::make_shared<VolumeRAMPrecision<unsigned short>>(volumeDimensions);
    auto newVolume = std::make_shared<Volume>(newVolumeRep);

    newVolume->dataMap_.dataRange = dvec2(0.0, static_cast<double>(seedPointsWithIndices.size()));
    newVolume->dataMap_.valueRange = newVolume->dataMap_.dataRange;

    auto volumeIndices = newVolumeRep->getDataTyped();
    util::IndexMapper3D index(volumeDimensions);

    if (weightedVoronoi && weights.has_value()) {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto zipped = util::zip(seedPointsWithIndices, weights.value());

            auto&& [posWithIndex, weight] = *std::min_element(
                zipped.begin(), zipped.end(), [transformedVoxelPos](auto&& i1, auto&& i2) {
                    auto&& [p1, w1] = i1;
                    auto&& [p2, w2] = i2;

                    return glm::distance2(p1.second, transformedVoxelPos) - w1 * w1 <
                           glm::distance2(p2.second, transformedVoxelPos) - w2 * w2;
                });
            volumeIndices[index(voxelPos)] = posWithIndex.first;
        });
    } else {
        util::forEachVoxelParallel(volumeDimensions, [&](const size3_t& voxelPos) {
            const auto transformedVoxelPos = mat3(indexToModelMatrix) * voxelPos;
            auto it = std::min_element(seedPointsWithIndices.cbegin(), seedPointsWithIndices.cend(),
                                       [transformedVoxelPos](const auto& p1, const auto& p2) {
                                           return glm::distance2(p1.second, transformedVoxelPos) <
                                                  glm::distance2(p2.second, transformedVoxelPos);
                                       });
            volumeIndices[index(voxelPos)] = it->first;
        });
    }

    return newVolume;
};

}  // namespace util
}  // namespace inviwo
<|endoftext|>


<commit_before><commit_msg>planning: fixed a bug in navi planner dispatcher<commit_after><|endoftext|>


<commit_before>/*!
  \copyright (c) RDO-Team, 2011
  \file      context.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      06.06.2010
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/context/context.h"
#include "simulator/compiler/parser/context/context_switch_i.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

Context::Context()
{}

Context::~Context()
{}

void Context::init()
{}

void Context::deinit()
{
	m_findResult = IContextFind::Result();
}

void Context::setContextStack(CREF(LPContextStack) pContextStack)
{
	ASSERT(pContextStack   );
	ASSERT(!m_pContextStack);
	m_pContextStack = pContextStack;
}

LPContext Context::find(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPContext pThis(const_cast<PTR(Context)>(this));
	LPIContextFind pThisContextFind = pThis.interface_dynamic_cast<IContextFind>();
	if (pThisContextFind)
	{
		const_cast<PTR(Context)>(this)->m_findResult = pThisContextFind->onFindContext(pValue);
		if (m_findResult.m_pContext)
		{
			return m_findResult.m_pContext;
		}
	}
	LPContext pPrev = m_pContextStack->prev(pThis);
	return pPrev ? pPrev->find(pValue) : LPContext();
}

LPContext Context::swch(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPIContextSwitch pContextSwitch = m_findResult.m_pValueContext.interface_dynamic_cast<IContextSwitch>();
	ASSERT(pContextSwitch);
	IContextFind::Result result = pContextSwitch->onSwitchContext(m_findResult.m_pExpression, pValue);
	ASSERT(result.m_pContext);
	result.m_pContext->m_findResult = result;
	ASSERT(result.m_pContext);
	return result.m_pContext;
}

LPExpression Context::create(CREF(LPRDOValue) pValue)
{
	ASSERT(pValue);
	ASSERT(m_findResult.m_pFindByValue == pValue);
	ASSERT(m_findResult.m_pExpression);

	return m_findResult.m_pExpression;
}

CLOSE_RDO_PARSER_NAMESPACE
<commit_msg> - очистка контекста<commit_after>/*!
  \copyright (c) RDO-Team, 2011
  \file      context.cpp
  \author      (rdo@rk9.bmstu.ru)
  \date      06.06.2010
  \brief
  \indent    4T
*/

// ---------------------------------------------------------------------------- PCH
#include "simulator/compiler/parser/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/compiler/parser/rdoparser.h"
#include "simulator/compiler/parser/context/context.h"
#include "simulator/compiler/parser/context/context_switch_i.h"
// --------------------------------------------------------------------------------

OPEN_RDO_PARSER_NAMESPACE

Context::Context()
{}

Context::~Context()
{}

void Context::init()
{}

void Context::deinit()
{
	m_findResult = IContextFind::Result();
}

void Context::setContextStack(CREF(LPContextStack) pContextStack)
{
	ASSERT(pContextStack   );
	ASSERT(!m_pContextStack);
	m_pContextStack = pContextStack;
}

LPContext Context::find(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPContext pThis(const_cast<PTR(Context)>(this));
	LPIContextFind pThisContextFind = pThis.interface_dynamic_cast<IContextFind>();
	if (pThisContextFind)
	{
		const_cast<PTR(Context)>(this)->m_findResult = pThisContextFind->onFindContext(pValue);
		if (m_findResult.m_pContext)
		{
			return m_findResult.m_pContext;
		}
	}
	LPContext pPrev = m_pContextStack->prev(pThis);
	return pPrev ? pPrev->find(pValue) : LPContext();
}

LPContext Context::swch(CREF(LPRDOValue) pValue) const
{
	ASSERT(pValue);

	LPIContextSwitch pContextSwitch = m_findResult.m_pValueContext.interface_dynamic_cast<IContextSwitch>();
	ASSERT(pContextSwitch);
	IContextFind::Result result = pContextSwitch->onSwitchContext(m_findResult.m_pExpression, pValue);
	ASSERT(result.m_pContext);
	result.m_pContext->m_findResult = result;
	ASSERT(result.m_pContext);
	const_cast<PTR(Context)>(this)->deinit();
	return result.m_pContext;
}

LPExpression Context::create(CREF(LPRDOValue) pValue)
{
	ASSERT(pValue);
	ASSERT(m_findResult.m_pFindByValue == pValue);
	ASSERT(m_findResult.m_pExpression);

	LPExpression pExpression = m_findResult.m_pExpression;
	deinit();
	return pExpression;
}

CLOSE_RDO_PARSER_NAMESPACE
<|endoftext|>


<commit_before>// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
#include "CppUnitTest.h"
#include "pipe_extensions.h"
#include <memory>
#include <sstream>
#include "UIStrings.h"

namespace Microsoft
{
    namespace VisualStudio
    {
        namespace CppUnitTestFramework
        {
            template<>
            static wstring ToString<RequestLanguage>(const RequestLanguage& lang)
            {
                return lang == RequestLanguage::CSHARPCOMPILE
                    ? L"CSHARPCOMPILE" : L"VBCOMPILE";
            }

            template<>
            static wstring ToString <vector<Request::Argument>>(const vector<Request::Argument>& vec)
            {
                return L"";
            }

            template<>
            static wstring ToString <vector<BYTE>>(const vector<BYTE>& vec)
            {
                return L"";
            }
        }
    }
}

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace NativeClientTests
{
    // To run these test from command line
    // vstest.console.exe Roslyn.Compilers.NativeClient.UnitTests.dll
    TEST_CLASS(MessageTests)
    {
    public:
        TEST_METHOD(SimpleRequestWithoutUtf8)
        {
            auto language = RequestLanguage::CSHARPCOMPILE;
            list<wstring> args = {
                L"test.cs"
            };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(keepAlive.empty());

            auto request = Request(language, L"");
            request.AddCommandLineArguments(args);

            Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion);
            Assert::AreEqual(language, request.Language);

            vector<Request::Argument> expectedArgs = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"test.cs"),
            };

            Assert::AreEqual(expectedArgs, request.Arguments());

            vector<byte> expectedBytes = {
                0x32, 0x0, 0x0, 0x0, // Size of request
                0x2, 0x0, 0x0, 0x0,  // Protocol version
                0x21, 0x25, 0x53, 0x44, // C# compile token
                0x2, 0x0, 0x0, 0x0, // Number of arguments
                0x21, 0x72, 0x14, 0x51, // Current directory token
                0x0, 0x0, 0x0, 0x0, // Index
                0x0, 0x0, 0x0, 0x0, // Length of value string
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x0, 0x0, 0x0, 0x0, // Index
                0x7, 0x0, 0x0, 0x0, // Length of value string in characters
                0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's'
                0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.'
                0x63, 0x0, 0x73, 0x0 // 'c', 's'
            };

            WriteOnlyMemoryPipe pipe;
            Assert::IsTrue(request.WriteToPipe(pipe));

            Assert::AreEqual(expectedBytes, pipe.Bytes());
        }

        TEST_METHOD(SimpleRequestWithUtf8)
        {
            auto language = RequestLanguage::CSHARPCOMPILE;
            list<wstring> args = {
                L"/utf8output",
                L"test.cs"
            };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(keepAlive.empty());

            auto request = Request(language, L"");
            request.AddCommandLineArguments(args);

            Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion);
            Assert::AreEqual(language, request.Language);

            vector<Request::Argument> expectedArgs = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"/utf8output"),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 1, L"test.cs"),
            };

            Assert::AreEqual(expectedArgs, request.Arguments());

            vector<byte> expectedBytes = {
                0x54, 0x0, 0x0, 0x0, // Size of request
                0x2, 0x0, 0x0, 0x0,  // Protocol version
                0x21, 0x25, 0x53, 0x44, // C# compile token
                0x3, 0x0, 0x0, 0x0, // Number of arguments
                0x21, 0x72, 0x14, 0x51, // Current directory token
                0x0, 0x0, 0x0, 0x0, // Index
                0x0, 0x0, 0x0, 0x0, // Length of value string
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x0, 0x0, 0x0, 0x0, // Index
                0xb, 0x0, 0x0, 0x0, // Length of value string in characters
                0x2f, 0x0, 0x75, 0x0, // '/', 'u'
                0x74, 0x0, 0x66, 0x0, // 't', 'f'
                0x38, 0x0, 0x6f, 0x0, // '8, 'o'
                0x75, 0x0, 0x74, 0x0, // 'u', 't'
                0x70, 0x0, 0x75, 0x0, // 'p', 'u'
                0x74, 0x0, // 't'
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x1, 0x0, 0x0, 0x0, // Index
                0x7, 0x0, 0x0, 0x0, // Length of value string in characters
                0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's'
                0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.'
                0x63, 0x0, 0x73, 0x0 // 'c', 's'
            };

            WriteOnlyMemoryPipe pipe;
            request.WriteToPipe(pipe);

            Assert::AreEqual(expectedBytes, pipe.Bytes());
        }

        TEST_METHOD(RequestsWithKeepAlive)
        {
            list<wstring> args = { L"/keepalive:10" };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"10", keepAlive.c_str());

            auto language = RequestLanguage::CSHARPCOMPILE;
            auto request = Request(language, L"");
            request.AddKeepAlive(wstring(keepAlive));

            vector<Request::Argument> expected = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::KEEPALIVE, 0, L"10"),
            };

            Assert::AreEqual(expected, request.Arguments());

            args = { L"/keepalive=10" };
            success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"10", keepAlive.c_str());

            request = Request(language, L"");
            request.AddKeepAlive(wstring(keepAlive));

            Assert::AreEqual(expected, request.Arguments());
        }

        TEST_METHOD(NegativeValidKeepAlive)
        {
            list<wstring> args = { L"/keepalive:-1" };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"-1", keepAlive.c_str());
        }

        TEST_METHOD(ParseKeepAliveNoValue)
        {
            list<wstring> args = {
                L"/keepalive",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveNoValue2)
        {
            list<wstring> args = {
                L"/keepalive:",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveBadInteger)
        {
            list<wstring> args = {
                L"/keepalive",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveIntegerTooSmall)
        {
            list<wstring> args = {
                L"/keepalive:-2",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsTooSmall,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveOutOfRange)
        {
            list<wstring> args = {
                L"/keepalive:9999999999",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsOutOfRange,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveNotAnInt)
        {
            list<wstring> args = {
                L"/keepalive:string",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsNotAnInteger,
                errorId);
        }
    };
}
<commit_msg>Fix warnings in NativeClientTests and hide warnings in VsCppUnitTest (changeset 1410899)<commit_after>// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

// Disable warning about static explicit specialization until bug 1118730 is fixed
#pragma warning( push )
#pragma warning( disable: 4499 )
#include "CppUnitTest.h"
#pragma warning (pop)

#include "pipe_extensions.h"
#include <memory>
#include <sstream>
#include "UIStrings.h"

namespace Microsoft
{
    namespace VisualStudio
    {
        namespace CppUnitTestFramework
        {
            template<>
            wstring ToString<RequestLanguage>(const RequestLanguage& lang)
            {
                return lang == RequestLanguage::CSHARPCOMPILE
                    ? L"CSHARPCOMPILE" : L"VBCOMPILE";
            }

            template<>
            wstring ToString <vector<Request::Argument>>(const vector<Request::Argument>& vec)
            {
                return L"";
            }

            template<>
            wstring ToString <vector<BYTE>>(const vector<BYTE>& vec)
            {
                return L"";
            }
        }
    }
}

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace NativeClientTests
{
    // To run these test from command line
    // vstest.console.exe Roslyn.Compilers.NativeClient.UnitTests.dll
    TEST_CLASS(MessageTests)
    {
    public:
        TEST_METHOD(SimpleRequestWithoutUtf8)
        {
            auto language = RequestLanguage::CSHARPCOMPILE;
            list<wstring> args = {
                L"test.cs"
            };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(keepAlive.empty());

            auto request = Request(language, L"");
            request.AddCommandLineArguments(args);

            Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion);
            Assert::AreEqual(language, request.Language);

            vector<Request::Argument> expectedArgs = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"test.cs"),
            };

            Assert::AreEqual(expectedArgs, request.Arguments());

            vector<byte> expectedBytes = {
                0x32, 0x0, 0x0, 0x0, // Size of request
                0x2, 0x0, 0x0, 0x0,  // Protocol version
                0x21, 0x25, 0x53, 0x44, // C# compile token
                0x2, 0x0, 0x0, 0x0, // Number of arguments
                0x21, 0x72, 0x14, 0x51, // Current directory token
                0x0, 0x0, 0x0, 0x0, // Index
                0x0, 0x0, 0x0, 0x0, // Length of value string
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x0, 0x0, 0x0, 0x0, // Index
                0x7, 0x0, 0x0, 0x0, // Length of value string in characters
                0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's'
                0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.'
                0x63, 0x0, 0x73, 0x0 // 'c', 's'
            };

            WriteOnlyMemoryPipe pipe;
            Assert::IsTrue(request.WriteToPipe(pipe));

            Assert::AreEqual(expectedBytes, pipe.Bytes());
        }

        TEST_METHOD(SimpleRequestWithUtf8)
        {
            auto language = RequestLanguage::CSHARPCOMPILE;
            list<wstring> args = {
                L"/utf8output",
                L"test.cs"
            };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(keepAlive.empty());

            auto request = Request(language, L"");
            request.AddCommandLineArguments(args);

            Assert::AreEqual(PROTOCOL_VERSION, request.ProtocolVersion);
            Assert::AreEqual(language, request.Language);

            vector<Request::Argument> expectedArgs = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 0, L"/utf8output"),
                Request::Argument(ArgumentId::COMMANDLINEARGUMENT, 1, L"test.cs"),
            };

            Assert::AreEqual(expectedArgs, request.Arguments());

            vector<byte> expectedBytes = {
                0x54, 0x0, 0x0, 0x0, // Size of request
                0x2, 0x0, 0x0, 0x0,  // Protocol version
                0x21, 0x25, 0x53, 0x44, // C# compile token
                0x3, 0x0, 0x0, 0x0, // Number of arguments
                0x21, 0x72, 0x14, 0x51, // Current directory token
                0x0, 0x0, 0x0, 0x0, // Index
                0x0, 0x0, 0x0, 0x0, // Length of value string
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x0, 0x0, 0x0, 0x0, // Index
                0xb, 0x0, 0x0, 0x0, // Length of value string in characters
                0x2f, 0x0, 0x75, 0x0, // '/', 'u'
                0x74, 0x0, 0x66, 0x0, // 't', 'f'
                0x38, 0x0, 0x6f, 0x0, // '8, 'o'
                0x75, 0x0, 0x74, 0x0, // 'u', 't'
                0x70, 0x0, 0x75, 0x0, // 'p', 'u'
                0x74, 0x0, // 't'
                0x22, 0x72, 0x14, 0x51, // Command line arg token
                0x1, 0x0, 0x0, 0x0, // Index
                0x7, 0x0, 0x0, 0x0, // Length of value string in characters
                0x74, 0x0, 0x65, 0x0, 0x73, // 't', 'e', 's'
                0x0, 0x74, 0x0, 0x2e, 0x0, // 't', '.'
                0x63, 0x0, 0x73, 0x0 // 'c', 's'
            };

            WriteOnlyMemoryPipe pipe;
            request.WriteToPipe(pipe);

            Assert::AreEqual(expectedBytes, pipe.Bytes());
        }

        TEST_METHOD(RequestsWithKeepAlive)
        {
            list<wstring> args = { L"/keepalive:10" };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"10", keepAlive.c_str());

            auto language = RequestLanguage::CSHARPCOMPILE;
            auto request = Request(language, L"");
            request.AddKeepAlive(wstring(keepAlive));

            vector<Request::Argument> expected = {
                Request::Argument(ArgumentId::CURRENTDIRECTORY, 0, L""),
                Request::Argument(ArgumentId::KEEPALIVE, 0, L"10"),
            };

            Assert::AreEqual(expected, request.Arguments());

            args = { L"/keepalive=10" };
            success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"10", keepAlive.c_str());

            request = Request(language, L"");
            request.AddKeepAlive(wstring(keepAlive));

            Assert::AreEqual(expected, request.Arguments());
        }

        TEST_METHOD(NegativeValidKeepAlive)
        {
            list<wstring> args = { L"/keepalive:-1" };
            wstring keepAlive;
            int errorId;
            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);

            Assert::IsTrue(success);
            Assert::IsTrue(args.empty());
            Assert::AreEqual(L"-1", keepAlive.c_str());
        }

        TEST_METHOD(ParseKeepAliveNoValue)
        {
            list<wstring> args = {
                L"/keepalive",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveNoValue2)
        {
            list<wstring> args = {
                L"/keepalive:",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveBadInteger)
        {
            list<wstring> args = {
                L"/keepalive",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_MissingKeepAlive,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveIntegerTooSmall)
        {
            list<wstring> args = {
                L"/keepalive:-2",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsTooSmall,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveOutOfRange)
        {
            list<wstring> args = {
                L"/keepalive:9999999999",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsOutOfRange,
                errorId);
        }

        TEST_METHOD(ParseKeepAliveNotAnInt)
        {
            list<wstring> args = {
                L"/keepalive:string",
            };
            wstring keepAlive;
            int errorId;

            auto success = ParseAndValidateClientArguments(args, keepAlive, errorId);
            Assert::IsFalse(success);
            Assert::AreEqual(
                IDS_KeepAliveIsNotAnInteger,
                errorId);
        }
    };
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "CppUnitTest.h"

#include "../dummy_values.h"
#include "internal/internal_datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {

using DataStore = You::DataStore::Internal::DataStore;

/// Unit Test Class for DataStore class
TEST_CLASS(DataStoreTest) {
public:
	TEST_METHOD(beginTransaction) {
		DataStore& sut = DataStore::get();
		sut.post(0, task1);
		SerializedTask task = sut.getTask(0);
		Assert::AreEqual(task1.at(TASK_ID), task[TASK_ID]);
		Assert::AreEqual(task1.at(DESCRIPTION), task[DESCRIPTION]);
		Assert::AreEqual(task1.at(DEADLINE), task[DEADLINE]);
		Assert::AreEqual(task1.at(PRIORITY), task[PRIORITY]);
		Assert::AreEqual(task1.at(DEPENDENCIES), task[DEPENDENCIES]);

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(postWithoutTransaction) {
		DataStore& sut = DataStore::get();

		// Checks if the document is initially empty
		Assert::IsTrue(sut.document.first_child().empty());

		// Equivalent to postWithNewId
		Assert::IsTrue(sut.post(0, task1));

		// Checks if the document is now not empty
		Assert::IsFalse(sut.document.first_child().empty());

		// Equivalent to postWithUsedId
		Assert::IsFalse(sut.post(0, task1));

		sut.document.reset();
		sut.saveData();
	}

	/// Basic test for editing a task
	TEST_METHOD(putWithoutTransaction) {
		DataStore& sut = DataStore::get();

		// Checks if the document is initially empty
		Assert::IsTrue(sut.document.first_child().empty());

		pugi::xml_node node = sut.document.append_child(L"task");
		node.append_attribute(L"id").set_value(L"0");

		// Equivalent to putWithExistingId
		Assert::IsTrue(sut.put(0, task1));

		// Equivalent to putNonExistentId
		Assert::IsFalse(sut.put(1, task1));

		sut.document.reset();
		sut.saveData();
	}

	/// Basic test for erasing a task with the specified task id
	TEST_METHOD(eraseWithoutTransaction) {
		DataStore& sut = DataStore::get();

		pugi::xml_node node = sut.document.append_child(L"task");
		node.append_attribute(L"id").set_value(L"0");

		// Equivalent to eraseExistingId
		Assert::IsTrue(sut.erase(0));

		// Equivalent to eraseNonExistentId
		Assert::IsFalse(sut.erase(1));

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(getAllTasks) {
		DataStore& sut = DataStore::get();
		sut.document.append_child(L"task").
			append_child(pugi::xml_node_type::node_pcdata).set_value(L"what");
		std::vector<SerializedTask> result = sut.getAllTask();
		Assert::AreEqual(1, boost::lexical_cast<int>(result.size()));

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(saveThenLoad) {
		DataStore& sut = DataStore::get();
		sut.document.append_child(L"task").
			append_child(pugi::xml_node_type::node_pcdata).set_value(L"what");
		bool result = sut.saveData();
		Assert::IsTrue(result);
		sut.loadData();
		std::wstring value = sut.document.child(L"task").child_value();
		Assert::AreEqual(std::wstring(L"what"), value);

		sut.document.reset();
		sut.saveData();
	}
};
}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You
<commit_msg>Add test for pushing operations to transaction<commit_after>#include "stdafx.h"
#include "CppUnitTest.h"

#include "../dummy_values.h"
#include "internal/operations/erase_operation.h"
#include "internal/operations/post_operation.h"
#include "internal/operations/put_operation.h"
#include "internal/internal_datastore.h"

using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;

namespace You {
namespace DataStore {
namespace UnitTests {

using DataStore = You::DataStore::Internal::DataStore;

/// Unit Test Class for DataStore class
TEST_CLASS(DataStoreTest) {
public:
	TEST_METHOD(beginTransaction) {
		DataStore& sut = DataStore::get();
		sut.post(0, task1);
		SerializedTask task = sut.getTask(0);
		Assert::AreEqual(task1.at(TASK_ID), task[TASK_ID]);
		Assert::AreEqual(task1.at(DESCRIPTION), task[DESCRIPTION]);
		Assert::AreEqual(task1.at(DEADLINE), task[DEADLINE]);
		Assert::AreEqual(task1.at(PRIORITY), task[PRIORITY]);
		Assert::AreEqual(task1.at(DEPENDENCIES), task[DEPENDENCIES]);

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(postWithoutTransaction) {
		DataStore& sut = DataStore::get();

		// Checks if the document is initially empty
		Assert::IsTrue(sut.document.first_child().empty());

		// Equivalent to postWithNewId
		Assert::IsTrue(sut.post(0, task1));

		// Checks if the document is now not empty
		Assert::IsFalse(sut.document.first_child().empty());

		// Equivalent to postWithUsedId
		Assert::IsFalse(sut.post(0, task1));

		sut.document.reset();
		sut.saveData();
	}

	/// Basic test for editing a task
	TEST_METHOD(putWithoutTransaction) {
		DataStore& sut = DataStore::get();

		// Checks if the document is initially empty
		Assert::IsTrue(sut.document.first_child().empty());

		pugi::xml_node node = sut.document.append_child(L"task");
		node.append_attribute(L"id").set_value(L"0");

		// Equivalent to putWithExistingId
		Assert::IsTrue(sut.put(0, task1));

		// Equivalent to putNonExistentId
		Assert::IsFalse(sut.put(1, task1));

		sut.document.reset();
		sut.saveData();
	}

	/// Basic test for erasing a task with the specified task id
	TEST_METHOD(eraseWithoutTransaction) {
		DataStore& sut = DataStore::get();

		pugi::xml_node node = sut.document.append_child(L"task");
		node.append_attribute(L"id").set_value(L"0");

		// Equivalent to eraseExistingId
		Assert::IsTrue(sut.erase(0));

		// Equivalent to eraseNonExistentId
		Assert::IsFalse(sut.erase(1));

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(getAllTasks) {
		DataStore& sut = DataStore::get();
		sut.document.append_child(L"task").
			append_child(pugi::xml_node_type::node_pcdata).set_value(L"what");
		std::vector<SerializedTask> result = sut.getAllTask();
		Assert::AreEqual(1, boost::lexical_cast<int>(result.size()));

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(saveThenLoad) {
		DataStore& sut = DataStore::get();
		sut.document.append_child(L"task").
			append_child(pugi::xml_node_type::node_pcdata).set_value(L"what");
		bool result = sut.saveData();
		Assert::IsTrue(result);
		sut.loadData();
		std::wstring value = sut.document.child(L"task").child_value();
		Assert::AreEqual(std::wstring(L"what"), value);

		sut.document.reset();
		sut.saveData();
	}

	TEST_METHOD(pushOperationToTransaction) {
		Internal::Transaction sut;

		std::unique_ptr<Internal::IOperation> post =
			std::make_unique<Internal::PostOperation>(0, task1);
		sut.push(std::move(post));
		Assert::AreEqual(1U, sut.operationsQueue.size());

		std::unique_ptr<Internal::IOperation> put =
			std::make_unique<Internal::PutOperation>(0, task1);
		sut.push(std::move(put));
		Assert::AreEqual(2U, sut.operationsQueue.size());

		std::unique_ptr<Internal::IOperation> erase =
			std::make_unique<Internal::EraseOperation>(0);
		sut.push(std::move(erase));
		Assert::AreEqual(3U, sut.operationsQueue.size());

		sut.operationsQueue.clear();
	}
};
}  // namespace UnitTests
}  // namespace DataStore
}  // namespace You
<|endoftext|>