<commit_before>// Copyright 2017-2020 The Verible Authors.
//
// 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 "verilog/CST/parameters.h"

#include <memory>
#include <vector>

#include "absl/strings/string_view.h"
#include "common/analysis/matcher/matcher.h"
#include "common/analysis/matcher/matcher_builders.h"
#include "common/analysis/syntax_tree_search.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/symbol.h"
#include "common/text/token_info.h"
#include "common/text/tree_utils.h"
#include "common/util/casts.h"
#include "common/util/logging.h"
#include "verilog/CST/identifier.h"
#include "verilog/CST/verilog_matchers.h"  // IWYU pragma: keep
#include "verilog/parser/verilog_token_enum.h"

namespace verilog {

using verible::down_cast;
using verible::SyntaxTreeLeaf;

std::vector<verible::TreeSearchMatch> FindAllParamDeclarations(
    const verible::Symbol& root) {
  return verible::SearchSyntaxTree(root, NodekParamDeclaration());
}

verilog_tokentype GetParamKeyword(const verible::Symbol& symbol) {
  // Currently the LRM is vague on what to do if no parameter/localparam is
  // declared, see example below. As such, if it's not declared, we will treat
  // it as a parameter.
  //
  // module foo #(int Bar = 1); endmodule
  //
  const auto* param_keyword_symbol =
      verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 0);
  if (param_keyword_symbol == nullptr) return TK_parameter;
  const auto* leaf =
      down_cast<const SyntaxTreeLeaf*>(ABSL_DIE_IF_NULL(param_keyword_symbol));
  return static_cast<verilog_tokentype>(leaf->get().token_enum);
}

const verible::Symbol* GetParamTypeSymbol(const verible::Symbol& symbol) {
  return verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 1);
}

const verible::TokenInfo& GetParameterNameToken(const verible::Symbol& symbol) {
  const auto* param_type_symbol = GetParamTypeSymbol(symbol);

  // Check for implicit type declaration, in which case [2] will be a leaf.
  const auto* identifier_symbol =
      verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType, 2);
  auto t = ABSL_DIE_IF_NULL(identifier_symbol)->Tag();
  const SyntaxTreeLeaf* identifier_leaf = nullptr;
  if (t.kind == verible::SymbolKind::kNode)
    identifier_leaf = GetIdentifier(*identifier_symbol);
  else
    identifier_leaf = down_cast<const SyntaxTreeLeaf*>(identifier_symbol);

  return ABSL_DIE_IF_NULL(identifier_leaf)->get();
}

std::vector<const verible::TokenInfo*> GetAllParameterNameTokens(
    const verible::Symbol& symbol) {
  std::vector<const verible::TokenInfo*> identifiers;
  identifiers.push_back(&GetParameterNameToken(symbol));

  for (const auto* s : GetAllAssignedParameterSymbols(symbol)) {
    identifiers.push_back(&GetAssignedParameterNameToken(*s));
  }

  return identifiers;
}

const verible::TokenInfo& GetAssignedParameterNameToken(
    const verible::Symbol& symbol) {
  const auto* identifier = SymbolCastToNode(symbol)[0].get();

  return AutoUnwrapIdentifier(*ABSL_DIE_IF_NULL(identifier))->get();
}

std::vector<const verible::Symbol*> GetAllAssignedParameterSymbols(
    const verible::Symbol& root) {
  std::vector<const verible::Symbol*> symbols;

  for (auto id : SearchSyntaxTree(root, NodekParameterAssign())) {
    symbols.push_back(id.match);
  }

  return symbols;
}

const verible::TokenInfo& GetSymbolIdentifierFromParamDeclaration(
    const verible::Symbol& symbol) {
  // Assert that symbol is a 'parameter type' declaration.
  CHECK(IsParamTypeDeclaration(symbol));

  const auto* type_symbol = GetTypeAssignmentFromParamDeclaration(symbol);
  const auto* symbol_identifier_leaf =
      GetIdentifierLeafFromTypeAssignment(*ABSL_DIE_IF_NULL(type_symbol));
  return ABSL_DIE_IF_NULL(symbol_identifier_leaf)->get();
}

bool IsParamTypeDeclaration(const verible::Symbol& symbol) {
  // Assert that symbol is a parameter declaration.
  auto t = symbol.Tag();
  CHECK_EQ(t.kind, verible::SymbolKind::kNode);
  CHECK_EQ(NodeEnum(t.tag), NodeEnum::kParamDeclaration);

  const auto* param_type_symbol = GetParamTypeSymbol(symbol);
  if (param_type_symbol->Kind() == verible::SymbolKind::kLeaf) {
    // Check that its token_enum is TK_type.
    const auto* tk_type_leaf =
        down_cast<const SyntaxTreeLeaf*>(param_type_symbol);
    CHECK_EQ(tk_type_leaf->get().token_enum, TK_type);
    return true;
  }
  return false;
}

const verible::Symbol* GetTypeAssignmentFromParamDeclaration(
    const verible::Symbol& symbol) {
  // Get the Type AssignmentList or kTypeAssignment symbol.
  const auto& assignment_symbol =
      verible::GetSubtreeAsNode(symbol, NodeEnum::kParamDeclaration, 2);
  const auto assignment_tag = assignment_symbol.Tag();

  // Check which type of node it is.
  if (NodeEnum(assignment_tag.tag) == NodeEnum::kTypeAssignment) {
    return &assignment_symbol;
  } else {
    const auto& type_symbol = verible::GetSubtreeAsNode(
        assignment_symbol, NodeEnum::kTypeAssignmentList, 0,
        NodeEnum::kTypeAssignment);
    return &type_symbol;
  }
}

const verible::SyntaxTreeLeaf* GetIdentifierLeafFromTypeAssignment(
    const verible::Symbol& symbol) {
  return &verible::GetSubtreeAsLeaf(symbol, NodeEnum::kTypeAssignment, 0);
}

const verible::Symbol* GetParamTypeInfoSymbol(const verible::Symbol& symbol) {
  const auto* param_type_symbol = GetParamTypeSymbol(symbol);
  return verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType,
                                     0);
}

namespace {
// TODO(hzeller): provide something like this in tree_utils.h ?
struct EnumTokenIndex {
  NodeEnum expected_type;
  int next_index;
};
const verible::Symbol* TryDescentPath(
    const verible::Symbol& symbol, std::initializer_list<EnumTokenIndex> path) {
  const verible::Symbol* value = &symbol;
  for (auto p : path) {
    value = GetSubtreeAsSymbol(*value, p.expected_type, p.next_index);
    if (value == nullptr) return nullptr;
  }
  return value;
}
}  // namespace

const verible::Symbol* GetParamAssignExpression(const verible::Symbol& symbol) {
  return TryDescentPath(symbol, {{NodeEnum::kParamDeclaration, 2},
                                 {NodeEnum::kTrailingAssign, 1},
                                 {NodeEnum::kExpression, 0}});
}

bool IsTypeInfoEmpty(const verible::Symbol& symbol) {
  // Assert that symbol is NodekTypeInfo
  CHECK_EQ(symbol.Kind(), verible::SymbolKind::kNode);
  CHECK_EQ(NodeEnum(symbol.Tag().tag), NodeEnum::kTypeInfo);

  const auto& type_info_node = verible::SymbolCastToNode(symbol);

  return (type_info_node[0] == nullptr && type_info_node[1] == nullptr &&
          type_info_node[2] == nullptr);
}

}  // namespace verilog
<commit_msg>Internal change<commit_after>// Copyright 2017-2020 The Verible Authors.
//
// 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 "verilog/CST/parameters.h"

#include <memory>
#include <vector>

#include "absl/strings/string_view.h"
#include "common/analysis/matcher/matcher.h"
#include "common/analysis/matcher/matcher_builders.h"
#include "common/analysis/syntax_tree_search.h"
#include "common/text/concrete_syntax_leaf.h"
#include "common/text/concrete_syntax_tree.h"
#include "common/text/symbol.h"
#include "common/text/token_info.h"
#include "common/text/tree_utils.h"
#include "common/util/casts.h"
#include "common/util/logging.h"
#include "verilog/CST/identifier.h"
#include "verilog/CST/verilog_matchers.h"  // IWYU pragma: keep
#include "verilog/parser/verilog_token_enum.h"

namespace verilog {

using verible::down_cast;
using verible::SyntaxTreeLeaf;

std::vector<verible::TreeSearchMatch> FindAllParamDeclarations(
    const verible::Symbol& root) {
  return verible::SearchSyntaxTree(root, NodekParamDeclaration());
}

verilog_tokentype GetParamKeyword(const verible::Symbol& symbol) {
  // Currently the LRM is vague on what to do if no parameter/localparam is
  // declared, see example below. As such, if it's not declared, we will treat
  // it as a parameter.
  //
  // module foo #(int Bar = 1); endmodule
  //
  const auto* param_keyword_symbol =
      verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 0);
  if (param_keyword_symbol == nullptr) return TK_parameter;
  const auto* leaf =
      down_cast<const SyntaxTreeLeaf*>(ABSL_DIE_IF_NULL(param_keyword_symbol));
  return static_cast<verilog_tokentype>(leaf->get().token_enum);
}

const verible::Symbol* GetParamTypeSymbol(const verible::Symbol& symbol) {
  return verible::GetSubtreeAsSymbol(symbol, NodeEnum::kParamDeclaration, 1);
}

const verible::TokenInfo& GetParameterNameToken(const verible::Symbol& symbol) {
  const auto* param_type_symbol = GetParamTypeSymbol(symbol);

  // Check for implicit type declaration, in which case [2] will be a leaf.
  const auto* identifier_symbol =
      verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType, 2);
  auto t = ABSL_DIE_IF_NULL(identifier_symbol)->Tag();
  const SyntaxTreeLeaf* identifier_leaf = nullptr;
  if (t.kind == verible::SymbolKind::kNode)
    identifier_leaf = GetIdentifier(*identifier_symbol);
  else
    identifier_leaf = down_cast<const SyntaxTreeLeaf*>(identifier_symbol);

  return ABSL_DIE_IF_NULL(identifier_leaf)->get();
}

std::vector<const verible::TokenInfo*> GetAllParameterNameTokens(
    const verible::Symbol& symbol) {
  std::vector<const verible::TokenInfo*> identifiers;
  identifiers.push_back(&GetParameterNameToken(symbol));

  for (const auto* s : GetAllAssignedParameterSymbols(symbol)) {
    identifiers.push_back(&GetAssignedParameterNameToken(*s));
  }

  return identifiers;
}

const verible::TokenInfo& GetAssignedParameterNameToken(
    const verible::Symbol& symbol) {
  const auto* identifier = SymbolCastToNode(symbol)[0].get();

  return AutoUnwrapIdentifier(*ABSL_DIE_IF_NULL(identifier))->get();
}

std::vector<const verible::Symbol*> GetAllAssignedParameterSymbols(
    const verible::Symbol& root) {
  std::vector<const verible::Symbol*> symbols;

  for (const auto& id : SearchSyntaxTree(root, NodekParameterAssign())) {
    symbols.push_back(id.match);
  }

  return symbols;
}

const verible::TokenInfo& GetSymbolIdentifierFromParamDeclaration(
    const verible::Symbol& symbol) {
  // Assert that symbol is a 'parameter type' declaration.
  CHECK(IsParamTypeDeclaration(symbol));

  const auto* type_symbol = GetTypeAssignmentFromParamDeclaration(symbol);
  const auto* symbol_identifier_leaf =
      GetIdentifierLeafFromTypeAssignment(*ABSL_DIE_IF_NULL(type_symbol));
  return ABSL_DIE_IF_NULL(symbol_identifier_leaf)->get();
}

bool IsParamTypeDeclaration(const verible::Symbol& symbol) {
  // Assert that symbol is a parameter declaration.
  auto t = symbol.Tag();
  CHECK_EQ(t.kind, verible::SymbolKind::kNode);
  CHECK_EQ(NodeEnum(t.tag), NodeEnum::kParamDeclaration);

  const auto* param_type_symbol = GetParamTypeSymbol(symbol);
  if (param_type_symbol->Kind() == verible::SymbolKind::kLeaf) {
    // Check that its token_enum is TK_type.
    const auto* tk_type_leaf =
        down_cast<const SyntaxTreeLeaf*>(param_type_symbol);
    CHECK_EQ(tk_type_leaf->get().token_enum, TK_type);
    return true;
  }
  return false;
}

const verible::Symbol* GetTypeAssignmentFromParamDeclaration(
    const verible::Symbol& symbol) {
  // Get the Type AssignmentList or kTypeAssignment symbol.
  const auto& assignment_symbol =
      verible::GetSubtreeAsNode(symbol, NodeEnum::kParamDeclaration, 2);
  const auto assignment_tag = assignment_symbol.Tag();

  // Check which type of node it is.
  if (NodeEnum(assignment_tag.tag) == NodeEnum::kTypeAssignment) {
    return &assignment_symbol;
  } else {
    const auto& type_symbol = verible::GetSubtreeAsNode(
        assignment_symbol, NodeEnum::kTypeAssignmentList, 0,
        NodeEnum::kTypeAssignment);
    return &type_symbol;
  }
}

const verible::SyntaxTreeLeaf* GetIdentifierLeafFromTypeAssignment(
    const verible::Symbol& symbol) {
  return &verible::GetSubtreeAsLeaf(symbol, NodeEnum::kTypeAssignment, 0);
}

const verible::Symbol* GetParamTypeInfoSymbol(const verible::Symbol& symbol) {
  const auto* param_type_symbol = GetParamTypeSymbol(symbol);
  return verible::GetSubtreeAsSymbol(*param_type_symbol, NodeEnum::kParamType,
                                     0);
}

namespace {
// TODO(hzeller): provide something like this in tree_utils.h ?
struct EnumTokenIndex {
  NodeEnum expected_type;
  int next_index;
};
const verible::Symbol* TryDescentPath(
    const verible::Symbol& symbol, std::initializer_list<EnumTokenIndex> path) {
  const verible::Symbol* value = &symbol;
  for (auto p : path) {
    value = GetSubtreeAsSymbol(*value, p.expected_type, p.next_index);
    if (value == nullptr) return nullptr;
  }
  return value;
}
}  // namespace

const verible::Symbol* GetParamAssignExpression(const verible::Symbol& symbol) {
  return TryDescentPath(symbol, {{NodeEnum::kParamDeclaration, 2},
                                 {NodeEnum::kTrailingAssign, 1},
                                 {NodeEnum::kExpression, 0}});
}

bool IsTypeInfoEmpty(const verible::Symbol& symbol) {
  // Assert that symbol is NodekTypeInfo
  CHECK_EQ(symbol.Kind(), verible::SymbolKind::kNode);
  CHECK_EQ(NodeEnum(symbol.Tag().tag), NodeEnum::kTypeInfo);

  const auto& type_info_node = verible::SymbolCastToNode(symbol);

  return (type_info_node[0] == nullptr && type_info_node[1] == nullptr &&
          type_info_node[2] == nullptr);
}

}  // namespace verilog
<|endoftext|>


<commit_before>/*
gpe_editor_helppage.cpp
This file is part of:
GAME PENCIL ENGINE
https://create.pawbyte.com
Copyright (c) 2014-2020 Nathan Hurde, Chase Lee.

Copyright (c) 2014-2020 PawByte LLC.
Copyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )

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.

-Game Pencil Engine <https://create.pawbyte.com>

*/

#include "gpe_editor_helppage.h"

gamePencilHelpPageResource * MAIN_HELP_PAGE = NULL;

gamePencilHelpPageResource::gamePencilHelpPageResource()
{
    isFullScreenResource = true;

    resourceFileName = "";
    resourceName = "Help Page";
    parentProjectName = "";
    parentProjectDirectory = "";
    engineLogo = new GPE_Label_Image( guiRCM->texture_add( APP_DIRECTORY_NAME+"resources/gfx/textures/game_penciil_logo.png"),"Game Pencil Engine", "Game Pencil Engine","http://create.pawbyte.com" );
    engineLogo->resizeAspect = 0.5;
    engineLogo->set_full_width( true );
    sideAreaPanel = new GPE_SelectBoxBasic("Mode");
    sideAreaPanel->set_width(160);
    sideAreaPanel->set_option_height(64);
    sideAreaPanel->add_option("General Help",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/question.png"),NULL,2, false, false);
    sideAreaPanel->add_option("Version Info",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/info.png"),NULL,2, false, false);
    sideAreaPanel->add_option("Changelog",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/file-text.png"),NULL,2, false, false);
    sideAreaPanel->add_option("Shortkeys",-1,guiRCM->texture_add(APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/keyboard-o.png"),NULL,2, false, false);

    sidePanelRect = new GPE_Rect();

    helpPageList = new GPE_GuiElementList();

    //Information Tab
    pencilChangelog = new GPE_TextAreaInputBasic();
    pencilChangelog->set_read_only();
    pencilChangelog->isCodeEditor = false;
    pencilChangelog->clear_all_lines();
    pencilChangelog->import_text(APP_DIRECTORY_NAME+"changelog.txt");

    pencilInformation = new GPE_TextAreaInputBasic();
    pencilInformation->set_read_only();
    pencilInformation->isCodeEditor = false;
    pencilInformation->clear_all_lines();
    pencilInformation->add_line("Name:                          Game Pencil Engine");
    std::string versionInfoLine = "";
    if( GPE_VERSION_UPDATE_NUMBER==0)
    {
        versionInfoLine = "Version:                       "+float_to_string(GPE_VERSION_FLOAT_NUMBER)+"0";
    }
    else
    {
        versionInfoLine = "Version:                       "+float_to_string(GPE_VERSION_FLOAT_NUMBER);
    }
    if( GPE_MAIN_GUI!=NULL)
    {
        if( GPE_MAIN_GUI->editorReleaseType==RELEASE_TYPE_PRODUCTION)
        {
            versionInfoLine+=" [PRODUCTION]";
        }
        if( GPE_MAIN_GUI->editorReleaseType==RELEASE_TYPE_RC)
        {
            versionInfoLine+=" [Release Candidate]";
        }
        else if( GPE_MAIN_GUI->editorReleaseType==RELEASE_TYPE_BETA)
        {
            versionInfoLine+=" [Beta Version]";
        }
        else if( GPE_MAIN_GUI->editorReleaseType==RELEASE_TYPE_ALPHA)
        {
            versionInfoLine+=" [Alpha Version]";
        }
    }
    pencilInformation->add_line( versionInfoLine+"." );
    pencilInformation->add_line("SDL Version:                   "+int_to_string(SDL_MAJOR_VERSION)+"."+int_to_string(SDL_MINOR_VERSION)+"."+int_to_string(SDL_PATCHLEVEL)+"." );
    pencilInformation->add_line("Renderer:                      "+GPE_MAIN_RENDERER->get_renderer_name() + " - " + GPE_MAIN_RENDERER->get_renderer_type() + "." );
    pencilInformation->add_line("PGUI Version:                  "+int_to_string(PGUI_MAJOR_VERSION)+"."+int_to_string(PGUI_MINOR_VERSION)+"."+int_to_string(PGUI_PATCHLEVEL)+"." );
    pencilInformation->add_line("GPE(runtime) Version:          "+int_to_string(GPR_MAJOR_VERSION)+"."+int_to_string(GPR_MINOR_VERSION)+"."+int_to_string(GPR_PATCHLEVEL)+"." );

    pencilInformation->add_line("Release Date:                  03-18-2020");
    pencilInformation->add_line("Author:                        PawByte");
    pencilInformation->add_line("Lead Developer:                Nathan Hurde aka theweirdn8");
    pencilInformation->add_line("Email:                         help@pawbyte.com");
    pencilInformation->add_line("Website:                       gamepencil.pawbyte.com");
    pencilInformation->isCodeEditor = false;

    updateCheckerButton = new GPE_ToolPushButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/download.png","Download new updates...","Compares latest version to your copy");
    updateCheckerButton->set_website("http://gamepencil.pawbyte.com/get-game-pencil-engine/");

    pencilShortkeys= new GPE_TextAreaInputBasic();
    pencilShortkeys->set_read_only();
    pencilShortkeys->isCodeEditor = false;

    pencilShortkeys->clear_all_lines();
    pencilShortkeys->import_text(APP_DIRECTORY_NAME+"shortkeys.txt");
    pencilShortkeys->set_height(640);

    helpPageList->barXPadding = GENERAL_GPE_GUI_PADDING;
    helpPageList->barXMargin = 0;

    helpfulLinksTitle = new GPE_Label_Title("Helpful Links","Some links you might find useful while using GPE.");

    GPE_TextURL * tHelpfulLink = NULL;

    tHelpfulLink = new GPE_TextURL("Introduction","Introduction","http://gamepencil.pawbyte.com/introduction");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Community","Community","http://community.pawbyte.com/");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Documentation","Documentation","http://docs.pawbyte.com/");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Tutorials","Tutorials","http://gamepencil.pawbyte.com/category/tutorials/");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Examples","Examples","http://gamepencil.pawbyte.com/examples");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Demos","Demos","http://gamepencil.pawbyte.com/demos");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("itch.io Page","itch.io Page","https://pawbyte.itch.io/game-pencil-engine");
    add_helpfullink(tHelpfulLink);

    tHelpfulLink = new GPE_TextURL("Steam Greenlight","Steam Greenlight","http://steamcommunity.com/sharedfiles/filedetails/?id=722454621");
    add_helpfullink(tHelpfulLink);

    //Community
    communityLinksTitle = new GPE_Label_Title("Community","Community links to stay connected");
    GPE_ToolIconButton * tSocialButton = NULL;

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/facebook.png","Facebook" );
    tSocialButton->set_website("https://facebook.com/pawbyte");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/reddit.png","Reddit" );
    tSocialButton->set_website("https://reddit.com/r/gamepencil");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/github.png","GitHub repo");
    tSocialButton->set_website("https://github.com/pawbyte/Game-Pencil-Engine");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/comments.png","Discord Chat Group" );
    tSocialButton->set_website("https://discord.gg/bua3rDW");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/twitter.png","Twitter" );
    tSocialButton->set_website("https://twitter.com/pawbyte");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/youtube.png","YouTube" );
    tSocialButton->set_website("https://www.youtube.com/user/PawByte");
    add_communitylink(tSocialButton);

    tSocialButton = new GPE_ToolIconButton( APP_DIRECTORY_NAME+"resources/gfx/iconpacks/fontawesome/gamecontroller.png","IndieDB" );
    tSocialButton->set_website("http://www.indiedb.com/engines/game-pencil-engine");
    add_communitylink(tSocialButton);
}

gamePencilHelpPageResource::~gamePencilHelpPageResource()
{
    subViewedSpace.x = GENERAL_GPE_GUI_PADDING;
    subViewedSpace.y = GENERAL_GPE_GUI_PADDING;
    subViewedSpace.w = 400;
    subViewedSpace.h = 400;
    resourceType = -2;
    subResouceId = -2;
    parentProjectName = "";

    if( helpPageList!=NULL)
    {
        delete helpPageList;
        helpPageList = NULL;
    }
    if( engineLogo!=NULL)
    {
        delete engineLogo;
        engineLogo = NULL;
    }
    if( updateCheckerButton!=NULL)
    {
        delete updateCheckerButton;
        updateCheckerButton = NULL;
    }

    if( helpfulLinksTitle!=NULL)
    {
        delete helpfulLinksTitle;
        helpfulLinksTitle = NULL;
    }

    if( communityLinksTitle!=NULL)
    {
        delete communityLinksTitle;
        communityLinksTitle = NULL;
    }
}

void gamePencilHelpPageResource::add_helpfulbutton(GPE_ToolPushButton * newButton)
{
    if( newButton!=NULL)
    {
        newButton->scale_object( 2 );
        helpfulButtons.push_back(newButton);
    }
}

void gamePencilHelpPageResource::add_helpfullink(GPE_TextURL * newLink)
{
    if( newLink!=NULL)
    {
        helpfulLinks.push_back(newLink);
    }
}

void gamePencilHelpPageResource::add_communitylink( GPE_ToolIconButton * newLink)
{
    if( newLink!=NULL)
    {
        newLink->scale_object( 2 );
        communityButtons.push_back(newLink);
    }
}

bool gamePencilHelpPageResource::include_local_files( std::string pBuildDir , int buildType )
{
    return true;
}

void gamePencilHelpPageResource::prerender_self( )
{

}

void gamePencilHelpPageResource::preprocess_self(std::string alternatePath)
{

}

void gamePencilHelpPageResource::process_self(GPE_Rect * viewedSpace, GPE_Rect * cam )
{
    viewedSpace = GPE_find_camera(viewedSpace);
    cam = GPE_find_camera(cam);
    if( viewedSpace!=NULL && helpPageList!=NULL)
    {
        int prevTab = sideAreaPanel->get_selection();
        if( PANEL_GENERAL_EDITOR!=NULL )
        {
            subViewedSpace.x = 0;
            subViewedSpace.y = 0;
            subViewedSpace.w = viewedSpace->w;
            subViewedSpace.h = viewedSpace->h;
            PANEL_GENERAL_EDITOR->add_gui_element_fullsize( sideAreaPanel );
            PANEL_GENERAL_EDITOR->process_self();
        }
        else
        {
            sideAreaPanel->set_coords(0, 0 );
            sideAreaPanel->set_height( viewedSpace->h );
            sideAreaPanel->process_self( viewedSpace, cam );
            subViewedSpace.x = sideAreaPanel->get_x2pos();
            subViewedSpace.y = 0;
            subViewedSpace.w = viewedSpace->w - sideAreaPanel->get_width();
            subViewedSpace.h = viewedSpace->h;
        }

        if( prevTab!=sideAreaPanel->get_selection() )
        {
            helpPageList->reset_self();
        }

        helpPageList->barXPadding = GENERAL_GPE_GUI_PADDING;
        helpPageList->barYPadding = GENERAL_GPE_GUI_PADDING;
        helpPageList->hAlign = FA_CENTER;
        helpPageList->clear_list();

        helpPageList->set_coords(subViewedSpace.x,subViewedSpace.y);
        helpPageList->set_width(subViewedSpace.w);
        helpPageList->set_height(subViewedSpace.h );

        if( sideAreaPanel->get_selected_name()=="General Help" || sideAreaPanel->get_selected_name()=="General")
        {
            int subMenuI = 0;
            GPE_TextURL * tempTextUrl = NULL;
            helpPageList->add_gui_element(engineLogo, true );
            helpPageList->add_gui_element(helpfulLinksTitle,true);
            for( subMenuI= 0; subMenuI <(int)helpfulLinks.size(); subMenuI++)
            {
                tempTextUrl = helpfulLinks.at(subMenuI);
                if( tempTextUrl!=NULL)
                {
                    helpPageList->add_gui_element(tempTextUrl, true);
                }
            }
            helpPageList->add_gui_element(communityLinksTitle,true);
            GPE_ToolIconButton * tCommunityButton = NULL;
            int menuLinksTotal = (int)communityButtons.size();
            for( subMenuI= 0; subMenuI < menuLinksTotal; subMenuI++)
            {
                tCommunityButton = communityButtons.at(subMenuI);
                if( tCommunityButton!=NULL)
                {
                    helpPageList->add_gui_element( tCommunityButton, subMenuI == menuLinksTotal-1 );
                }
            }
        }
        else if( sideAreaPanel->get_selected_name()=="Changelog" )
        {
            helpPageList->add_gui_element_fullsize(pencilChangelog );
        }
        else if( sideAreaPanel->get_selected_name()=="Version Info" )
        {
            helpPageList->add_gui_element(engineLogo, true );
            helpPageList->add_gui_element(updateCheckerButton, true );
            helpPageList->add_gui_element(pencilInformation, true );
        }
        else if( sideAreaPanel->get_selected_name()=="Shortkeys" )
        {
            helpPageList->add_gui_element_fullsize(pencilShortkeys );
        }
        helpPageList->process_self(viewedSpace,cam);
    }
}

void gamePencilHelpPageResource::render_self(GPE_Rect * viewedSpace, GPE_Rect * cam )
{
    viewedSpace = GPE_find_camera(viewedSpace);
    cam = GPE_find_camera(cam);
    if( cam!=NULL && viewedSpace!=NULL)
    {
        if(  sideAreaPanel!=NULL && PANEL_GENERAL_EDITOR==NULL )
        {
            sideAreaPanel->render_self( viewedSpace,cam);
        }
        if( helpPageList!=NULL )
        {
            helpPageList->render_self( viewedSpace,cam);
        }
    }
}

void gamePencilHelpPageResource::save_resource(std::string alternatePath, int backupId)
{
    bool usingAltSaveSource = false;
    isModified = false;
}

bool gamePencilHelpPageResource::write_data_into_projectfile(std::ofstream * fileTarget, int nestedFoldersIn)
{
    return true;
}
<commit_msg>Delete gpe_editor_helppage.cpp<commit_after><|endoftext|>


<commit_before>#include "qrwar.hpp"

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/System/Time.hpp>

#include "config/settings.hpp"
#include "config/tilesetprocessor.hpp"

#include "gui/texturemanager.hpp"

#include "rendering/rendersystem.hpp"
#include "eventsystem/eventsystem.hpp"
#include "eventsystem/sfeventsource.hpp"
#include "animation/animationsystem.hpp"

#include "game/states/introstate.hpp"
#include "game/states/mainmenustate.hpp"
#include "game/states/mapeditorstate.hpp"
#include "game/states/skirmishpreparationstate.hpp"
#include "game/states/deploystate.hpp"
#include "game/states/skirmishstate.hpp"

#include "game/path.hpp"

namespace qrw
{

RenderSystem g_renderSystem;
Scene g_scene;
EventSystem g_eventSystem;
AnimationSystem g_animationSystem;

QRWar::QRWar()
{
	// Init
	g_renderSystem.startUp(_renderWindow);
	preloadResources();
	g_scene.setRenderTarget(&_renderWindow);
	g_eventSystem.startUp(new SfEventSource(_renderWindow));

	// Set and initialize start state
	_currentState = createGameState(EGSID_INTRO_STATE);
	_currentState->init(nullptr);
}

QRWar::~QRWar()
{
	g_eventSystem.shutDown();
	g_renderSystem.shutDown();
}

void QRWar::run()
{
	sf::Clock timer;

	bool quit = false;
	EGameStateId nextStateId;

	while(!quit)
	{
		sf::Time elapsedTime = timer.restart();

		_renderWindow.clear(sf::Color::Black);

		g_eventSystem.processEvents();

		nextStateId = _currentState->update();

		// Quit the application
		if(nextStateId == EGameStateId::EGSID_QUIT)
		{
			quit = true;
			delete _currentState;
			g_scene.reset();
		}
		// If no state change occured: draw the current state
		else if(nextStateId == EGameStateId::EGSID_NO_CHANGE)
		{
			g_renderSystem.renderAll();
			// Todo: Remove _currentState->draw() which only renders gui
			guiCamera_.applyTo(_renderWindow);
			_currentState->draw();
			_renderWindow.display();
		}
		// Perform a state change
		else
		{
			GameState* previousState = _currentState;
			_currentState = createGameState(nextStateId);
			_currentState->init(previousState);
			delete previousState;
		}

		g_scene.update();
		g_animationSystem.update(elapsedTime.asSeconds());
	}
}

void QRWar::preloadResources()
{
	// Start initialization of qrw...
	// Load Settings
	qrw::Settings* settings = qrw::Settings::getInstance();
	settings->loadFromFile();

	TextureManager::getInstance()->loadTexture("mainmenubackground", "./res/img/mainmenubackground.png");

	// Loading tilesets
	qrw::TilesetProcessor tilesetprocessor;
	tilesetprocessor.loadTileset(settings->getEntityTilesetPath());
	tilesetprocessor.loadTileset(settings->getGuiTilesetPath());
}

GameState* QRWar::createGameState(EGameStateId id)
{
	switch(id)
	{
	case EGSID_INTRO_STATE: return new IntroState(&_renderWindow);
	case EGSID_MAIN_MENU_STATE: return new MainMenuState(&_renderWindow);
	case EGSID_MAP_EDITOR_STATE: return new MapEditorState(&_renderWindow);
	case EGSID_SKIRMISH_PREPARATION_STATE: return new SkirmishPreparationState(&_renderWindow);
	case EGSID_DEPLOY_STATE: return new DeployState(&_renderWindow);
	case EGSID_SKIRMISH_STATE: return new SkirmishState(&_renderWindow);
	default: return nullptr;
	}
}

} // namespace qrw
<commit_msg>Quick fix for screen-to-world mouse position conversion<commit_after>#include "qrwar.hpp"

#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/System/Time.hpp>

#include "config/settings.hpp"
#include "config/tilesetprocessor.hpp"

#include "gui/texturemanager.hpp"

#include "rendering/rendersystem.hpp"
#include "eventsystem/eventsystem.hpp"
#include "eventsystem/sfeventsource.hpp"
#include "animation/animationsystem.hpp"

#include "game/states/introstate.hpp"
#include "game/states/mainmenustate.hpp"
#include "game/states/mapeditorstate.hpp"
#include "game/states/skirmishpreparationstate.hpp"
#include "game/states/deploystate.hpp"
#include "game/states/skirmishstate.hpp"

#include "game/path.hpp"

namespace qrw
{

RenderSystem g_renderSystem;
Scene g_scene;
EventSystem g_eventSystem;
AnimationSystem g_animationSystem;

QRWar::QRWar()
{
	// Init
	g_renderSystem.startUp(_renderWindow);
	preloadResources();
	g_scene.setRenderTarget(&_renderWindow);
	g_eventSystem.startUp(new SfEventSource(_renderWindow));

	// Set and initialize start state
	_currentState = createGameState(EGSID_INTRO_STATE);
	_currentState->init(nullptr);
}

QRWar::~QRWar()
{
	g_eventSystem.shutDown();
	g_renderSystem.shutDown();
}

void QRWar::run()
{
	sf::Clock timer;

	bool quit = false;
	EGameStateId nextStateId;

	while(!quit)
	{
		sf::Time elapsedTime = timer.restart();

		_renderWindow.clear(sf::Color::Black);

		g_eventSystem.processEvents();

		nextStateId = _currentState->update();

		// Quit the application
		if(nextStateId == EGameStateId::EGSID_QUIT)
		{
			quit = true;
			delete _currentState;
			g_scene.reset();
		}
		// If no state change occured: draw the current state
		else if(nextStateId == EGameStateId::EGSID_NO_CHANGE)
		{
			g_renderSystem.renderAll();
			// Todo: Remove _currentState->draw() which only renders gui
			sf::View view = _renderWindow.getView();
			guiCamera_.applyTo(_renderWindow);
			_currentState->draw();
			_renderWindow.setView(view);

			_renderWindow.display();
		}
		// Perform a state change
		else
		{
			GameState* previousState = _currentState;
			_currentState = createGameState(nextStateId);
			_currentState->init(previousState);
			delete previousState;
		}

		g_scene.update();
		g_animationSystem.update(elapsedTime.asSeconds());
	}
}

void QRWar::preloadResources()
{
	// Start initialization of qrw...
	// Load Settings
	qrw::Settings* settings = qrw::Settings::getInstance();
	settings->loadFromFile();

	TextureManager::getInstance()->loadTexture("mainmenubackground", "./res/img/mainmenubackground.png");

	// Loading tilesets
	qrw::TilesetProcessor tilesetprocessor;
	tilesetprocessor.loadTileset(settings->getEntityTilesetPath());
	tilesetprocessor.loadTileset(settings->getGuiTilesetPath());
}

GameState* QRWar::createGameState(EGameStateId id)
{
	switch(id)
	{
	case EGSID_INTRO_STATE: return new IntroState(&_renderWindow);
	case EGSID_MAIN_MENU_STATE: return new MainMenuState(&_renderWindow);
	case EGSID_MAP_EDITOR_STATE: return new MapEditorState(&_renderWindow);
	case EGSID_SKIRMISH_PREPARATION_STATE: return new SkirmishPreparationState(&_renderWindow);
	case EGSID_DEPLOY_STATE: return new DeployState(&_renderWindow);
	case EGSID_SKIRMISH_STATE: return new SkirmishState(&_renderWindow);
	default: return nullptr;
	}
}

} // namespace qrw
<|endoftext|>


<commit_before>#include "GameState.h"
#include <algorithm>
#include <util/Math.h>
#include <logging/Logger.h>

GameState::GameState() :
	_exitFlag(false),
	_tLast(0.0) {
}

GameState::~GameState() {
}

void GameState::updateManPosition(const Man& manLastFrame, const float dt) {

	// Move man forward
	_man.pos() += _man.vel() * dt;

	/*
	// Keep the man at correct height above ground
	// -> that is: Rightmost leg should be on the ground
	const glm::vec2 frontFootPos = _man.pos() + _man.frontLeg().edgePos();
	const float dy = _terrain.vertexAtX(frontFootPos.x).y - frontFootPos.y;
	_man.pos().y += dy;*/

	const glm::vec2 rightFootPos = _man.rightLeg().edgePos();
	const glm::vec2 leftFootPos = _man.leftLeg().edgePos();
	const float stepLength = _man.leftLeg().length()*0.25f;
	const float manIdealHeightAboveTerrain = 1.10f * std::hypotf(_man.leftLeg().linkLength1(), _man.leftLeg().linkLength2());
	const glm::vec2 terrainUnderMan = _terrain.vertexAtX(_man.pos().x);
	const glm::vec2 terrainLeftOfMan = _terrain.vertexAtX(std::max(0.0f, _man.pos().x - stepLength));
	const glm::vec2 terrainRightOfMan = _terrain.vertexAtX(_man.pos().x + stepLength);
	const float avgTerrainUnderMan = 0.5f * (terrainLeftOfMan.y + terrainRightOfMan.y);
	const float correctHeight = avgTerrainUnderMan + manIdealHeightAboveTerrain;
	_man.pos().y = correctHeight;
}

void GameState::swapLiftedLegIfHitGround(const Man& manLastFrame) {

	if (manLastFrame.liftedLegEnum() == _man.liftedLegEnum()) {

		const auto footPos = _man.liftedLeg().edgePos();
		const auto lastFrameFootPos = manLastFrame.liftedLeg().edgePos();
		const glm::vec2 footPosChange = footPos - lastFrameFootPos;

		if (footPosChange.y < 0 && _terrain.isBelowGround(footPos)) {
		//	_man.swapLegMovingForward();
		}
	}

}

void GameState::clampFootAboveGround(Limb& leg) {
	const float worldX = _man.pos().x + leg.edgePos().x;
	const float worldY = _man.pos().y + leg.edgePos().y;
	const float terrainY = _terrain.vertexAtX(worldX).y;
	if (worldY < terrainY) {
		placeFootAt(glm::vec2(worldX, terrainY), leg);
	}
}

void GameState::clampFeetAboveGround() {
	clampFootAboveGround(_man.leftLeg());
	clampFootAboveGround(_man.rightLeg());
}

void GameState::placeFootAt(const glm::vec2& targetWorldPos, Limb& leg) {
	leg.placeEdgeAt(targetWorldPos - _man.pos());
}

void GameState::placeFootOnGroundAt(const float x, Limb& leg) {
	placeFootAt(glm::vec2(x, _terrain.vertexAtX(x).y), leg);
}

void GameState::updateGroundedLeg(const Man& manLastFrame, const float dt) {
	const float worldX = manLastFrame.pos().x + manLastFrame.groundedLeg().edgePos().x;
	placeFootOnGroundAt(worldX, _man.groundedLeg());
}

void GameState::updateLiftedLeg(const Man& manLastFrame, const float dt) {
	// Lifted foot makes a circle movement
	// Angles then taken from invese kinematics
	const auto lastManX = manLastFrame.pos().x;
	const auto manX = _man.pos().x;
	if (manX != lastManX) {
	}
}

void GameState::updateLegPositions(const Man& manLastFrame, const float dt) {
	clampFeetAboveGround();
	updateGroundedLeg(manLastFrame, dt);
	updateLiftedLeg(manLastFrame, dt);
	swapLiftedLegIfHitGround(manLastFrame);
}

void GameState::update(const double time) {

	const float dt = static_cast<float>(time - _tLast);
	const Man manLastFrame = _man;

	updateManPosition(manLastFrame, dt);
	updateLegPositions(manLastFrame, dt);
	updateArmPositions(manLastFrame, dt);

	_tLast = time;
}

void GameState::setExitFlag(const bool state) {
	_exitFlag = state;
}

void GameState::updateArmPositions(const Man& manLastFrame, const float dt) {
	// TODO: Something fun in the future
}
<commit_msg>first steps<commit_after>#include "GameState.h"
#include <algorithm>
#include <util/Math.h>
#include <logging/Logger.h>

GameState::GameState() :
	_exitFlag(false),
	_tLast(0.0) {
}

GameState::~GameState() {
}

void GameState::updateManPosition(const Man& manLastFrame, const float dt) {

	// Move man forward
	_man.pos() += _man.vel() * dt;

	/*
	// Keep the man at correct height above ground
	// -> that is: Rightmost leg should be on the ground
	const glm::vec2 frontFootPos = _man.pos() + _man.frontLeg().edgePos();
	const float dy = _terrain.vertexAtX(frontFootPos.x).y - frontFootPos.y;
	_man.pos().y += dy;*/

	const glm::vec2 rightFootPos = _man.rightLeg().edgePos();
	const glm::vec2 leftFootPos = _man.leftLeg().edgePos();
	const float stepLength = _man.leftLeg().length()*0.25f;
	const float manIdealHeightAboveTerrain = 1.10f * std::hypotf(_man.leftLeg().linkLength1(), _man.leftLeg().linkLength2());
	const glm::vec2 terrainUnderMan = _terrain.vertexAtX(_man.pos().x);
	const glm::vec2 terrainLeftOfMan = _terrain.vertexAtX(std::max(0.0f, _man.pos().x - stepLength));
	const glm::vec2 terrainRightOfMan = _terrain.vertexAtX(_man.pos().x + stepLength);
	const float avgTerrainUnderMan = 0.5f * (terrainLeftOfMan.y + terrainRightOfMan.y);
	const float correctHeight = avgTerrainUnderMan + manIdealHeightAboveTerrain;
	_man.pos().y = correctHeight;
}

void GameState::swapLiftedLegIfHitGround(const Man& manLastFrame) {

	if (manLastFrame.liftedLegEnum() == _man.liftedLegEnum()) {

		const glm::vec2 relFootPos = _man.liftedLeg().edgePos();
		const glm::vec2 lastFrameRelFootPos = manLastFrame.liftedLeg().edgePos();
		const glm::vec2 footPosChange = relFootPos - lastFrameRelFootPos;
		const glm::vec2 absFootPos = _man.pos() + relFootPos;

		if (footPosChange.y < 0 && _terrain.isBelowGround(absFootPos)) {
			Logger::global().info("LegSwap: Now moving the other leg forward!");
			_man.swapLegMovingForward();
		}
	}

}

void GameState::clampFootAboveGround(Limb& leg) {
	const float worldX = _man.pos().x + leg.edgePos().x;
	const float worldY = _man.pos().y + leg.edgePos().y;
	const float terrainY = _terrain.vertexAtX(worldX).y;
	if (worldY < terrainY) {
		placeFootAt(glm::vec2(worldX, terrainY), leg);
	}
}

void GameState::clampFeetAboveGround() {
	clampFootAboveGround(_man.leftLeg());
	clampFootAboveGround(_man.rightLeg());
}

void GameState::placeFootAt(const glm::vec2& targetWorldPos, Limb& leg) {
	leg.placeEdgeAt(targetWorldPos - _man.pos());
}

void GameState::placeFootOnGroundAt(const float x, Limb& leg) {
	placeFootAt(glm::vec2(x, _terrain.vertexAtX(x).y), leg);
}

void GameState::updateGroundedLeg(const Man& manLastFrame, const float dt) {
	const float worldX = manLastFrame.pos().x + manLastFrame.groundedLeg().edgePos().x;
	placeFootOnGroundAt(worldX, _man.groundedLeg());
}

void GameState::updateLiftedLeg(const Man& manLastFrame, const float dt) {
	// Lifted foot makes a circle movement
	// Angles then taken from invese kinematics
	const auto lastManX = manLastFrame.pos().x;
	const auto manX = _man.pos().x;
	if (manX != lastManX) {
		Limb& leg = _man.liftedLeg();
		const float dx = dt * _man.vel().x;
		const float dy = leg.edgePos().x < 0.0f ? dx : -dx;
		const glm::vec2 prevPos = leg.edgePos();
		leg.placeEdgeAt(prevPos + glm::vec2(dx, dy));
	}
}

void GameState::updateLegPositions(const Man& manLastFrame, const float dt) {
	clampFeetAboveGround();
	updateGroundedLeg(manLastFrame, dt);
	updateLiftedLeg(manLastFrame, dt);
	swapLiftedLegIfHitGround(manLastFrame);
}

void GameState::update(const double time) {

	const float dt = static_cast<float>(time - _tLast);
	const Man manLastFrame = _man;

	updateManPosition(manLastFrame, dt);
	updateLegPositions(manLastFrame, dt);
	updateArmPositions(manLastFrame, dt);

	_tLast = time;
}

void GameState::setExitFlag(const bool state) {
	_exitFlag = state;
}

void GameState::updateArmPositions(const Man& manLastFrame, const float dt) {
	// TODO: Something fun in the future
}
<|endoftext|>


<commit_before>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 <miopen/config.h>
#include <miopen/hip_build_utils.hpp>
#include <miopen/stringutils.hpp>
#include <miopen/exec_utils.hpp>
#include <miopen/logger.hpp>
#include <miopen/env.hpp>
#include <miopen/target_properties.hpp>
#include <boost/optional.hpp>
#include <sstream>
#include <string>

MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_ENFORCE_COV3)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_VERBOSE)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_DUMP)

namespace miopen {

bool IsHccCompiler()
{
    static const auto isHcc = EndsWith(MIOPEN_HIP_COMPILER, "hcc");
    return isHcc;
}

bool IsHipClangCompiler()
{
    static const auto isClangXX = EndsWith(MIOPEN_HIP_COMPILER, "clang++");
    return isClangXX;
}

namespace {

inline bool ProduceCoV3()
{
    // If env.var is set, then let's follow it.
    if(IsEnabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return true;
    if(IsDisabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return false;
    // Otherwise, let's enable CO v3 for HIP kernels since ROCm 3.0.
    return (HipCompilerVersion() >= external_tool_version_t{3, 0, -1});
}

/// Returns option for enabling/disabling CO v3 generation for the compiler
/// that builds HIP kernels, depending on compiler version etc.
inline const std::string& GetCoV3Option(const bool enable)
{
    /// \note PR #2166 uses the "--hcc-cov3" option when isHCC is true.
    /// It's unclear why... HCC included in ROCm 2.8 does not support it,
    /// perhaps it suits for some older HCC?
    ///
    /// These options are Ok for ROCm 3.0:
    static const std::string option_enable{"-mcode-object-v3"};
    static const std::string no_option{};
    if(enable)
        return option_enable;
    else
        return no_option;
}
} // namespace

struct LcOptionTargetStrings
{
    const std::string& device;
    const std::string xnack;
    const std::string sramecc;
    LcOptionTargetStrings(const TargetProperties& target)
        : device(target.Name()),
          xnack(std::string{":xnack"} + (target.Xnack() ? "+" : "-")),
          sramecc(std::string{":sramecc"} + (target.Sramecc() ? "+" : "-"))
    {
    }
};

static boost::filesystem::path HipBuildImpl(boost::optional<TmpDir>& tmp_dir,
                                            const std::string& filename,
                                            std::string src,
                                            std::string params,
                                            const TargetProperties& target,
                                            const bool testing_mode)
{
#ifdef __linux__
    // Write out the include files
    // Let's assume includes are overkill for feature tests & optimize'em out.
    if(!testing_mode)
    {
        auto inc_list = GetKernelIncList();
        auto inc_path = tmp_dir->path;
        boost::filesystem::create_directories(inc_path);
        for(auto inc_file : inc_list)
        {
            auto inc_src = GetKernelInc(inc_file);
            WriteFile(inc_src, inc_path / inc_file);
        }
    }
    src += "\nint main() {}\n";
    WriteFile(src, tmp_dir->path / filename);

    // cppcheck-suppress unreadVariable
    const LcOptionTargetStrings lots(target);

    auto env = std::string("");
    if(IsHccCompiler())
    {
        params += " -amdgpu-target=" + target.Name();
        params += " " + GetCoV3Option(ProduceCoV3());
    }
    else if(IsHipClangCompiler())
    {
        if(params.find("-std=") == std::string::npos)
            params += " --std=c++11";

        if(HipCompilerVersion() < external_tool_version_t{4, 1, 0})
            params += " --cuda-gpu-arch=" + lots.device;
        else
            params += " --cuda-gpu-arch=" + lots.device + lots.xnack;

        params += " --cuda-device-only";
        params += " -c";
        params += " -O3 ";
    }

    params += " -Wno-unused-command-line-argument -I. ";
    params += MIOPEN_STRINGIZE(HIP_COMPILER_FLAGS);
    if(IsHccCompiler())
    {
        env += std::string("KMOPTLLC=\"-mattr=+enable-ds128 ");
        if(HipCompilerVersion() >= external_tool_version_t{2, 8, 0})
            env += " --amdgpu-spill-vgpr-to-agpr=0";
        env += '\"';
    }
    else if(IsHipClangCompiler())
    {
        params += " -mllvm --amdgpu-spill-vgpr-to-agpr=0";
    }

#if MIOPEN_BUILD_DEV
    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_VERBOSE{}))
    {
        params += " -v";
    }

    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_DUMP{}))
    {
        if(IsHccCompiler())
        {
            params += " -gline-tables-only";
            env += " KMDUMPISA=1";
            env += " KMDUMPLLVM=1";
        }
        else if(IsHipClangCompiler())
        {
            params += " -gline-tables-only";
            params += " -save-temps";
        }
    }
#endif

    // hip version
    params +=
        std::string(" -DHIP_PACKAGE_VERSION_FLAT=") + std::to_string(HIP_PACKAGE_VERSION_FLAT);

    params += " ";
    auto bin_file = tmp_dir->path / (filename + ".o");

    // compile
    const std::string redirector = testing_mode ? " 1>/dev/null 2>&1" : "";
    tmp_dir->Execute(env + std::string(" ") + MIOPEN_HIP_COMPILER,
                     params + filename + " -o " + bin_file.string() + redirector);
    if(!boost::filesystem::exists(bin_file))
        MIOPEN_THROW(filename + " failed to compile");
#ifdef EXTRACTKERNEL_BIN
    if(IsHccCompiler())
    {
        // call extract kernel
        tmp_dir->Execute(EXTRACTKERNEL_BIN, " -i " + bin_file.string());
        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }

        return hsaco->path();
    }
#endif
#if defined(MIOPEN_OFFLOADBUNDLER_BIN) && !MIOPEN_BACKEND_HIP
    // Unbundling is not required for HIP runtime && hip-clang
    if(IsHipClangCompiler())
    {
        tmp_dir->Execute(MIOPEN_OFFLOADBUNDLER_BIN,
                         "--type=o --targets=hip-amdgcn-amd-amdhsa-" +
                             (HipCompilerVersion() < external_tool_version_t{4, 1, 0}
                                  ? lots.device
                                  : (std::string{'-'} + lots.device + lots.xnack)) +
                             " --inputs=" + bin_file.string() + " --outputs=" + bin_file.string() +
                             ".hsaco --unbundle");

        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }
        return hsaco->path();
    }
    else
#endif
    {
        return bin_file;
    }
#else
    (void)filename;
    (void)params;
    MIOPEN_THROW("HIP kernels are only supported in Linux");
#endif
}

static bool
HipBuildTest(const std::string& program_name, std::string params, const TargetProperties& target)
{
    boost::optional<miopen::TmpDir> dir(program_name);
    std::string source = miopen::GetKernelSrc(program_name);
    try
    {
        std::ignore = HipBuildImpl(dir, program_name, source, params, target, true);
    }
    catch(...)
    {
        return false;
    }
    return true;
}

static bool DetectIfBufferAtomicFaddReturnsFloatImpl(const TargetProperties& target)
{
    const std::string program_name("detect_llvm_amdgcn_buffer_atomic_fadd_f32_float.cpp");
    std::string params;

    if(HipBuildTest(program_name, params, target))
    {
        MIOPEN_LOG_NQI("Yes");
        return true;
    }
    MIOPEN_LOG_NQI("No");
    return false;
}

static bool DetectIfBufferAtomicFaddReturnsFloat(const TargetProperties& target)
{
    static const bool once = DetectIfBufferAtomicFaddReturnsFloatImpl(target);
    return once;
}

boost::filesystem::path HipBuild(boost::optional<TmpDir>& tmp_dir,
                                 const std::string& filename,
                                 std::string src,
                                 std::string params,
                                 const TargetProperties& target)
{
    if(target.Name() == "gfx908")
        if(DetectIfBufferAtomicFaddReturnsFloat(target))
            params += " -DCK_AMD_BUFFER_ATOMIC_FADD_RETURNS_FLOAT=1";
    return HipBuildImpl(tmp_dir, filename, src, params, target, false);
}

void bin_file_to_str(const boost::filesystem::path& file, std::string& buf)
{
    std::ifstream bin_file_ptr(file.string().c_str(), std::ios::binary);
    std::ostringstream bin_file_strm;
    bin_file_strm << bin_file_ptr.rdbuf();
    buf = bin_file_strm.str();
}

static external_tool_version_t HipCompilerVersionImpl()
{
    external_tool_version_t version;
    if(IsHccCompiler())
    {
        const std::string path(MIOPEN_HIP_COMPILER);
        const std::string mandatory_prefix("(based on HCC ");
        do
        {
            if(path.empty() || !std::ifstream(path).good())
                break;

            std::stringstream out;
            MIOPEN_LOG_NQI2("Running: " << '\'' << path << " --version" << '\'');
            if(miopen::exec::Run(path + " --version", nullptr, &out) != 0)
                break;

            std::string line;
            while(!out.eof())
            {
                std::getline(out, line);
                MIOPEN_LOG_NQI2(line);
                auto begin = line.find(mandatory_prefix);
                if(begin == std::string::npos)
                    continue;

                begin += mandatory_prefix.size();
                int v3, v2, v1 = v2 = v3 = -1;
                char c2, c1 = c2 = 'X';
                std::istringstream iss(line.substr(begin));
                iss >> v1 >> c1 >> v2 >> c2 >> v3;
                if(!iss.fail() && v1 >= 0)
                {
                    version.major = v1;
                    if(c1 == '.' && v2 >= 0)
                    {
                        version.minor = v2;
                        if(c2 == '.' && v3 >= 0)
                            version.patch = v3;
                    }
                }
                break;
            }
        } while(false);
    }
    else
    {
#ifdef HIP_PACKAGE_VERSION_MAJOR
        MIOPEN_LOG_NQI2("Read version information from HIP package...");
        version.major = HIP_PACKAGE_VERSION_MAJOR;
#ifdef HIP_PACKAGE_VERSION_MINOR
        version.minor = HIP_PACKAGE_VERSION_MINOR;
#else
        version.minor = 0;
#endif
#ifdef HIP_PACKAGE_VERSION_PATCH
        version.patch = HIP_PACKAGE_VERSION_PATCH;
#else
        version.patch = 0;
#endif
#else // HIP_PACKAGE_VERSION_MAJOR is not defined. CMake failed to find HIP package.
        MIOPEN_LOG_NQI2("...assuming 3.2.0 (hip-clang RC)");
        version.major = 3;
        version.minor = 2;
        version.patch = 0;
#endif
    }
    MIOPEN_LOG_NQI(version.major << '.' << version.minor << '.' << version.patch);
    return version;
}

external_tool_version_t HipCompilerVersion()
{
    static auto once = HipCompilerVersionImpl();
    return once;
}

bool operator>(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    if(lhs.major > rhs.major)
        return true;
    else if(lhs.major == rhs.major)
    {
        if(lhs.minor > rhs.minor)
            return true;
        else if(lhs.minor == rhs.minor)
            return (lhs.patch > rhs.patch);
        else
            return false;
    }
    else
        return false;
}

bool operator<(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return rhs > lhs;
}
bool operator>=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs < rhs);
}

bool operator<=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs > rhs);
}

} // namespace miopen
<commit_msg>[OCL BE][HIP] Use "hipv4" for unbundler in 4.1 and in 4.2 starting from 21072. (#787)<commit_after>/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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 <miopen/config.h>
#include <miopen/hip_build_utils.hpp>
#include <miopen/stringutils.hpp>
#include <miopen/exec_utils.hpp>
#include <miopen/logger.hpp>
#include <miopen/env.hpp>
#include <miopen/target_properties.hpp>
#include <boost/optional.hpp>
#include <sstream>
#include <string>

MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_ENFORCE_COV3)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_VERBOSE)
MIOPEN_DECLARE_ENV_VAR(MIOPEN_DEBUG_HIP_DUMP)

namespace miopen {

bool IsHccCompiler()
{
    static const auto isHcc = EndsWith(MIOPEN_HIP_COMPILER, "hcc");
    return isHcc;
}

bool IsHipClangCompiler()
{
    static const auto isClangXX = EndsWith(MIOPEN_HIP_COMPILER, "clang++");
    return isClangXX;
}

namespace {

inline bool ProduceCoV3()
{
    // If env.var is set, then let's follow it.
    if(IsEnabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return true;
    if(IsDisabled(MIOPEN_DEBUG_HIP_ENFORCE_COV3{}))
        return false;
    // Otherwise, let's enable CO v3 for HIP kernels since ROCm 3.0.
    return (HipCompilerVersion() >= external_tool_version_t{3, 0, -1});
}

/// Returns option for enabling/disabling CO v3 generation for the compiler
/// that builds HIP kernels, depending on compiler version etc.
inline const std::string& GetCoV3Option(const bool enable)
{
    /// \note PR #2166 uses the "--hcc-cov3" option when isHCC is true.
    /// It's unclear why... HCC included in ROCm 2.8 does not support it,
    /// perhaps it suits for some older HCC?
    ///
    /// These options are Ok for ROCm 3.0:
    static const std::string option_enable{"-mcode-object-v3"};
    static const std::string no_option{};
    if(enable)
        return option_enable;
    else
        return no_option;
}
} // namespace

struct LcOptionTargetStrings
{
    const std::string& device;
    const std::string xnack;
    const std::string sramecc;
    LcOptionTargetStrings(const TargetProperties& target)
        : device(target.Name()),
          xnack(std::string{":xnack"} + (target.Xnack() ? "+" : "-")),
          sramecc(std::string{":sramecc"} + (target.Sramecc() ? "+" : "-"))
    {
    }
};

static boost::filesystem::path HipBuildImpl(boost::optional<TmpDir>& tmp_dir,
                                            const std::string& filename,
                                            std::string src,
                                            std::string params,
                                            const TargetProperties& target,
                                            const bool testing_mode)
{
#ifdef __linux__
    // Write out the include files
    // Let's assume includes are overkill for feature tests & optimize'em out.
    if(!testing_mode)
    {
        auto inc_list = GetKernelIncList();
        auto inc_path = tmp_dir->path;
        boost::filesystem::create_directories(inc_path);
        for(auto inc_file : inc_list)
        {
            auto inc_src = GetKernelInc(inc_file);
            WriteFile(inc_src, inc_path / inc_file);
        }
    }
    src += "\nint main() {}\n";
    WriteFile(src, tmp_dir->path / filename);

    // cppcheck-suppress unreadVariable
    const LcOptionTargetStrings lots(target);

    auto env = std::string("");
    if(IsHccCompiler())
    {
        params += " -amdgpu-target=" + target.Name();
        params += " " + GetCoV3Option(ProduceCoV3());
    }
    else if(IsHipClangCompiler())
    {
        if(params.find("-std=") == std::string::npos)
            params += " --std=c++11";

        if(HipCompilerVersion() < external_tool_version_t{4, 1, 0})
            params += " --cuda-gpu-arch=" + lots.device;
        else
            params += " --cuda-gpu-arch=" + lots.device + lots.xnack;

        params += " --cuda-device-only";
        params += " -c";
        params += " -O3 ";
    }

    params += " -Wno-unused-command-line-argument -I. ";
    params += MIOPEN_STRINGIZE(HIP_COMPILER_FLAGS);
    if(IsHccCompiler())
    {
        env += std::string("KMOPTLLC=\"-mattr=+enable-ds128 ");
        if(HipCompilerVersion() >= external_tool_version_t{2, 8, 0})
            env += " --amdgpu-spill-vgpr-to-agpr=0";
        env += '\"';
    }
    else if(IsHipClangCompiler())
    {
        params += " -mllvm --amdgpu-spill-vgpr-to-agpr=0";
    }

#if MIOPEN_BUILD_DEV
    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_VERBOSE{}))
    {
        params += " -v";
    }

    if(miopen::IsEnabled(MIOPEN_DEBUG_HIP_DUMP{}))
    {
        if(IsHccCompiler())
        {
            params += " -gline-tables-only";
            env += " KMDUMPISA=1";
            env += " KMDUMPLLVM=1";
        }
        else if(IsHipClangCompiler())
        {
            params += " -gline-tables-only";
            params += " -save-temps";
        }
    }
#endif

    // hip version
    params +=
        std::string(" -DHIP_PACKAGE_VERSION_FLAT=") + std::to_string(HIP_PACKAGE_VERSION_FLAT);

    params += " ";
    auto bin_file = tmp_dir->path / (filename + ".o");

    // compile
    const std::string redirector = testing_mode ? " 1>/dev/null 2>&1" : "";
    tmp_dir->Execute(env + std::string(" ") + MIOPEN_HIP_COMPILER,
                     params + filename + " -o " + bin_file.string() + redirector);
    if(!boost::filesystem::exists(bin_file))
        MIOPEN_THROW(filename + " failed to compile");
#ifdef EXTRACTKERNEL_BIN
    if(IsHccCompiler())
    {
        // call extract kernel
        tmp_dir->Execute(EXTRACTKERNEL_BIN, " -i " + bin_file.string());
        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }

        return hsaco->path();
    }
#endif
#if defined(MIOPEN_OFFLOADBUNDLER_BIN) && !MIOPEN_BACKEND_HIP
    // Unbundling is not required for HIP runtime && hip-clang
    if(IsHipClangCompiler())
    {
        tmp_dir->Execute(MIOPEN_OFFLOADBUNDLER_BIN,
                         "--type=o "
#if(HIP_PACKAGE_VERSION_FLAT >= 4001021072 && HIP_PACKAGE_VERSION_FLAT < 4002000000) || \
    HIP_PACKAGE_VERSION_FLAT >= 4002021072
                         "--targets=hipv4-amdgcn-amd-amdhsa-"
#else
                         "--targets=hip-amdgcn-amd-amdhsa-"
#endif
                             +
                             (HipCompilerVersion() < external_tool_version_t{4, 1, 0}
                                  ? lots.device
                                  : (std::string{'-'} + lots.device + lots.xnack)) +
                             " --inputs=" + bin_file.string() + " --outputs=" + bin_file.string() +
                             ".hsaco --unbundle");

        auto hsaco =
            std::find_if(boost::filesystem::directory_iterator{tmp_dir->path},
                         {},
                         [](auto entry) { return (entry.path().extension() == ".hsaco"); });

        if(hsaco == boost::filesystem::directory_iterator{})
        {
            MIOPEN_LOG_E("failed to find *.hsaco in " << hsaco->path().string());
        }
        return hsaco->path();
    }
    else
#endif
    {
        return bin_file;
    }
#else
    (void)filename;
    (void)params;
    MIOPEN_THROW("HIP kernels are only supported in Linux");
#endif
}

static bool
HipBuildTest(const std::string& program_name, std::string params, const TargetProperties& target)
{
    boost::optional<miopen::TmpDir> dir(program_name);
    std::string source = miopen::GetKernelSrc(program_name);
    try
    {
        std::ignore = HipBuildImpl(dir, program_name, source, params, target, true);
    }
    catch(...)
    {
        return false;
    }
    return true;
}

static bool DetectIfBufferAtomicFaddReturnsFloatImpl(const TargetProperties& target)
{
    const std::string program_name("detect_llvm_amdgcn_buffer_atomic_fadd_f32_float.cpp");
    std::string params;

    if(HipBuildTest(program_name, params, target))
    {
        MIOPEN_LOG_NQI("Yes");
        return true;
    }
    MIOPEN_LOG_NQI("No");
    return false;
}

static bool DetectIfBufferAtomicFaddReturnsFloat(const TargetProperties& target)
{
    static const bool once = DetectIfBufferAtomicFaddReturnsFloatImpl(target);
    return once;
}

boost::filesystem::path HipBuild(boost::optional<TmpDir>& tmp_dir,
                                 const std::string& filename,
                                 std::string src,
                                 std::string params,
                                 const TargetProperties& target)
{
    if(target.Name() == "gfx908")
        if(DetectIfBufferAtomicFaddReturnsFloat(target))
            params += " -DCK_AMD_BUFFER_ATOMIC_FADD_RETURNS_FLOAT=1";
    return HipBuildImpl(tmp_dir, filename, src, params, target, false);
}

void bin_file_to_str(const boost::filesystem::path& file, std::string& buf)
{
    std::ifstream bin_file_ptr(file.string().c_str(), std::ios::binary);
    std::ostringstream bin_file_strm;
    bin_file_strm << bin_file_ptr.rdbuf();
    buf = bin_file_strm.str();
}

static external_tool_version_t HipCompilerVersionImpl()
{
    external_tool_version_t version;
    if(IsHccCompiler())
    {
        const std::string path(MIOPEN_HIP_COMPILER);
        const std::string mandatory_prefix("(based on HCC ");
        do
        {
            if(path.empty() || !std::ifstream(path).good())
                break;

            std::stringstream out;
            MIOPEN_LOG_NQI2("Running: " << '\'' << path << " --version" << '\'');
            if(miopen::exec::Run(path + " --version", nullptr, &out) != 0)
                break;

            std::string line;
            while(!out.eof())
            {
                std::getline(out, line);
                MIOPEN_LOG_NQI2(line);
                auto begin = line.find(mandatory_prefix);
                if(begin == std::string::npos)
                    continue;

                begin += mandatory_prefix.size();
                int v3, v2, v1 = v2 = v3 = -1;
                char c2, c1 = c2 = 'X';
                std::istringstream iss(line.substr(begin));
                iss >> v1 >> c1 >> v2 >> c2 >> v3;
                if(!iss.fail() && v1 >= 0)
                {
                    version.major = v1;
                    if(c1 == '.' && v2 >= 0)
                    {
                        version.minor = v2;
                        if(c2 == '.' && v3 >= 0)
                            version.patch = v3;
                    }
                }
                break;
            }
        } while(false);
    }
    else
    {
#ifdef HIP_PACKAGE_VERSION_MAJOR
        MIOPEN_LOG_NQI2("Read version information from HIP package...");
        version.major = HIP_PACKAGE_VERSION_MAJOR;
#ifdef HIP_PACKAGE_VERSION_MINOR
        version.minor = HIP_PACKAGE_VERSION_MINOR;
#else
        version.minor = 0;
#endif
#ifdef HIP_PACKAGE_VERSION_PATCH
        version.patch = HIP_PACKAGE_VERSION_PATCH;
#else
        version.patch = 0;
#endif
#else // HIP_PACKAGE_VERSION_MAJOR is not defined. CMake failed to find HIP package.
        MIOPEN_LOG_NQI2("...assuming 3.2.0 (hip-clang RC)");
        version.major = 3;
        version.minor = 2;
        version.patch = 0;
#endif
    }
    MIOPEN_LOG_NQI(version.major << '.' << version.minor << '.' << version.patch);
    return version;
}

external_tool_version_t HipCompilerVersion()
{
    static auto once = HipCompilerVersionImpl();
    return once;
}

bool operator>(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    if(lhs.major > rhs.major)
        return true;
    else if(lhs.major == rhs.major)
    {
        if(lhs.minor > rhs.minor)
            return true;
        else if(lhs.minor == rhs.minor)
            return (lhs.patch > rhs.patch);
        else
            return false;
    }
    else
        return false;
}

bool operator<(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return rhs > lhs;
}
bool operator>=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs < rhs);
}

bool operator<=(const external_tool_version_t& lhs, const external_tool_version_t& rhs)
{
    return !(lhs > rhs);
}

} // namespace miopen
<|endoftext|>


<commit_before>#define DEBUG_DRAW_TABLE_MARKERS
#define DEBUG_DRAW_TABLETOP_OBJECTS

//ROS
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/PoseStamped.h>
#include <sensor_msgs/PointCloud2.h>

//PCL
#include <pcl_ros/filters/passthrough.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/surface/convex_hull.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_ros/transforms.h>
#include <pcl/filters/statistical_outlier_removal.h>

//TF
#include <tf/transform_listener.h>

//PR2
#include <pr2_controllers_msgs/PointHeadAction.h>

//Manipulation
#include <arm_navigation_msgs/MoveArmAction.h>
#include <arm_navigation_msgs/utils.h>

//STL
#include <string.h>

//VISUALIZATION
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>

#include <plane_extractor.h>

typedef actionlib::SimpleActionClient<pr2_controllers_msgs::PointHeadAction> PointHeadClient;
typedef pcl::PointCloud<pcl::PointXYZ> XYZPointCloud;
typedef pcl::PointXYZ Point;
typedef pcl::KdTree<Point>::Ptr KdTreePtr;

class book_stacking
{

private:
  PointHeadClient* point_head_client_;
  ros::Subscriber point_cloud_sub_;
  double min_table_z_, max_table_z_,leaf_size;
  bool use_downsample;
  double table_ransac_thresh_;
  tf::TransformListener tf_listener;
  std::string workspace_frame;

  bool filter_spatial;
  double filter_spatial_xmin, filter_spatial_xmax;
  double filter_spatial_ymin, filter_spatial_ymax;
  double filter_spatial_zmin, filter_spatial_zmax;

  bool filter_outliers;
  int filter_outliers_meank;
  double filter_outliers_stddev_thresh;
  bool downsample_cloud;
  double downsample_grid_size_;

  bool concave_hull_mode_;
  bool use_normal_seg_;
  int max_planes_;
  bool use_omp_;
  double plane_distance_thresh_;
  double normal_search_radius_;
  int min_plane_inliers_;
  int max_sac_iterations_;
  double sac_probability_;

  std::string base_frame_tf;

public:
  ros::NodeHandle n_;
  ros::Publisher filtered_cloud_pub_;
  ros::Publisher plane_marker_pub_;
  ros::Publisher obj_marker_pub_;

book_stacking():
  n_("~")
{
  point_head_client_ = new PointHeadClient("/head_traj_controller/point_head_action", true);
  while(!point_head_client_->waitForServer(ros::Duration(5.0)))
    {
      ROS_INFO("Waiting for the point_head_action server to come up");
    }
point_cloud_sub_=n_.subscribe("/camera/depth/points",1,&book_stacking::KinectCallback,this);
filtered_cloud_pub_ = n_.advertise<sensor_msgs::PointCloud2>("filtered_cloud",1);

//Visualization Publishers
 plane_marker_pub_ = n_.advertise<visualization_msgs::MarkerArray>("/visualization_marker_array",1);
 obj_marker_pub_ = n_.advertise<visualization_msgs::Marker>("obj_markers",1);

 LoadParameters();

 //lookAt("base_link", 1.5, 0.0, 0.2);
//TestArm();
//shakeHead(2);
}
  void LoadParameters()
  {
    n_.param("min_table_z", min_table_z_, -0.5);
    n_.param("max_table_z", max_table_z_, 1.5);
    n_.param("use_downsample", use_downsample, true);
    n_.param("leaf_size", leaf_size, 0.01);
    std::string default_workspace_frame="/base_link";
    n_.param("workspace_frame", workspace_frame, default_workspace_frame);

    //Spatial Filtering Params
    n_.param("filter_spatial",filter_spatial,true);
    n_.param("filter_spatial_zmax",filter_spatial_zmax,3.0);
    n_.param("filter_spatial_zmin",filter_spatial_zmin,0.05);
    n_.param("filter_spatial_ymax",filter_spatial_ymax,10.0);
    n_.param("filter_spatial_ymin",filter_spatial_ymin,-10.0);
    n_.param("filter_spatial_xmax",filter_spatial_xmax,10.0);
    n_.param("filter_spatial_xmin",filter_spatial_xmin,-10.0);

    //Outlier Filtering Params
    n_.param("filter_outliers",filter_outliers,true);
    n_.param("filter_outliers_meank",filter_outliers_meank,50);
    n_.param("filter_outliers_stddev_thresh", filter_outliers_stddev_thresh,1.0);

    //Downsampling Params
    n_.param("downsample_cloud",downsample_cloud,true);
    n_.param("downsample_grid_size",downsample_grid_size_,0.01);

    //Plane Extraction Parameters
    n_.param("max_planes",max_planes_,4);
    n_.param("use_omp",use_omp_,false);
    n_.param("plane_distance_thresh",plane_distance_thresh_,0.03);
    n_.param("normal_search_radius",normal_search_radius_,0.1);
    n_.param("min_plane_inliers",min_plane_inliers_,1000);
    n_.param("max_sac_iterations",max_sac_iterations_,1000);
    n_.param("sac_probability",sac_probability_,0.99);
    n_.param("concave_hull_mode",concave_hull_mode_,false);
    n_.param("use_normal_seg",use_normal_seg_,false);
    n_.param("base_frame_tf", base_frame_tf,std::string("/base_link"));

  }

void lookAt(std::string frame_id, double x, double y, double z)
  {
    //the goal message we will be sending
    pr2_controllers_msgs::PointHeadGoal goal;

    //the target point, expressed in the requested frame
    geometry_msgs::PointStamped point;
    point.header.frame_id = frame_id;
    point.point.x = x; point.point.y = y; point.point.z = z;
    goal.target = point;

    //we are pointing the high-def camera frame
    //(pointing_axis defaults to X-axis)
    goal.pointing_frame = "high_def_frame";

    //take at least 0.5 seconds to get there
    goal.min_duration = ros::Duration(0.5);

    //and go no faster than 1 rad/s
    goal.max_velocity = 1.0;

    //send the goal
    point_head_client_->sendGoal(goal);

    //wait for it to get there (abort after 2 secs to prevent getting stuck)
    point_head_client_->waitForResult(ros::Duration(2));
  }

  void shakeHead(int n)
  {
    int count = 0;
    while (ros::ok() && ++count <= n )
    {
      //Looks at a point forward (x=5m), slightly left (y=1m), and 1.2m up
      lookAt("base_link", 5.0, 1.0, 1.2);

      //Looks at a point forward (x=5m), slightly right (y=-1m), and 1.2m up
      lookAt("base_link", 5.0, -1.0, 1.2);
    }
  }

void TestArm()
{
ROS_INFO("In TestArm()");
  actionlib::SimpleActionClient<arm_navigation_msgs::MoveArmAction> move_arm("move_right_arm",true);
  move_arm.waitForServer();
  ROS_INFO("Connected to server");
  arm_navigation_msgs::MoveArmGoal goalA;

  goalA.motion_plan_request.group_name = "right_arm";
  goalA.motion_plan_request.num_planning_attempts = 1;
  goalA.motion_plan_request.planner_id = std::string("");
  goalA.planner_service_name = std::string("ompl_planning/plan_kinematic_path");
  goalA.motion_plan_request.allowed_planning_time = ros::Duration(5.0);

  arm_navigation_msgs::SimplePoseConstraint desired_pose;
  desired_pose.header.frame_id = "torso_lift_link";
  desired_pose.link_name = "r_wrist_roll_link";
  desired_pose.pose.position.x = 0.75;
  desired_pose.pose.position.y = -0.188;
  desired_pose.pose.position.z = 0;

  desired_pose.pose.orientation.x = 0.0;
  desired_pose.pose.orientation.y = 0.0;
  desired_pose.pose.orientation.z = 0.0;
  desired_pose.pose.orientation.w = 1.0;

  desired_pose.absolute_position_tolerance.x = 0.02;
  desired_pose.absolute_position_tolerance.y = 0.02;
  desired_pose.absolute_position_tolerance.z = 0.02;

  desired_pose.absolute_roll_tolerance = 0.04;
  desired_pose.absolute_pitch_tolerance = 0.04;
  desired_pose.absolute_yaw_tolerance = 0.04;

  arm_navigation_msgs::addGoalConstraintToMoveArmGoal(desired_pose,goalA);

  if (n_.ok())
  {
    bool finished_within_time = false;
ROS_INFO("BOOKSTACK Giving Goal");
    move_arm.sendGoal(goalA);
    finished_within_time = move_arm.waitForResult(ros::Duration(200.0));
    if (!finished_within_time)
    {
      move_arm.cancelGoal();
      ROS_INFO("Timed out achieving goal A");
    }
    else
    {
      actionlib::SimpleClientGoalState state = move_arm.getState();
      bool success = (state == actionlib::SimpleClientGoalState::SUCCEEDED);
      if(success)
        ROS_INFO("Action finished: %s",state.toString().c_str());
      else
        ROS_INFO("Action failed: %s",state.toString().c_str());
    }
  }

}

void KinectCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg)
{
ROS_INFO("PT CLOUD");

 XYZPointCloud cloud;
 pcl::fromROSMsg(*cloud_msg,cloud);
 pcl_ros::transformPointCloud(workspace_frame,cloud,cloud,tf_listener);
 book_stacking_msgs::PlaneInfo table_plane_info=getTablePlane(cloud);

 bool detect_objects=true;
    if(detect_objects)
      {
	ROS_INFO("Extracting objects...");
	book_stacking_msgs::ObjectInfos objects = getObjectsOverPlane(table_plane_info,cloud);

#ifdef DEBUG_DRAW_TABLETOP_OBJECTS
	if(objects.objects.size() < 1)
	  {
	    ROS_WARN("No objects over this plane.");
	  }
	else
	  {
	    drawObjectPrisms(objects,obj_marker_pub_,table_plane_info,0.0f,1.0f,0.0f);
	    //object_pub_.publish(objects);
	  }
      }
#endif

}

book_stacking_msgs::PlaneInfo getTablePlane(XYZPointCloud& cloud)
  {
    if(filter_spatial)
      {
	pcl::PassThrough<Point> pass;
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("z");
	pass.setFilterLimits(filter_spatial_zmin,filter_spatial_zmax);
	pass.filter(cloud);
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("x");
	pass.setFilterLimits(filter_spatial_xmin,filter_spatial_xmax);
	pass.filter(cloud);
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("y");
	pass.setFilterLimits(filter_spatial_ymin,filter_spatial_ymax);
	pass.filter(cloud);
      }

    //Filter Outliers
    if(filter_outliers){
      pcl::StatisticalOutlierRemoval<Point> sor_filter;
      sor_filter.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
      sor_filter.setMeanK(filter_outliers_meank);//50
      sor_filter.setStddevMulThresh(filter_outliers_stddev_thresh);
      sor_filter.filter(cloud);
    }

    //Downsample Cloud
    if(downsample_cloud)
      {
      //downsample
      pcl::VoxelGrid<Point> grid;
      grid.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
      grid.setLeafSize(downsample_grid_size_,downsample_grid_size_,downsample_grid_size_);//0.05
      grid.filter(cloud);
    }

    //Publish the filtered cloud
    sensor_msgs::PointCloud2 filtered_msg;
    pcl::toROSMsg(cloud,filtered_msg);
    ROS_INFO("Publishing filtered cloud...");
    filtered_cloud_pub_.publish(filtered_msg);

    book_stacking_msgs::PlaneInfos plane_infos= getPlanesByNormals(cloud,1,true,concave_hull_mode_,use_omp_,plane_distance_thresh_,max_sac_iterations_,sac_probability_,min_plane_inliers_,normal_search_radius_,0.1);
    plane_infos.header.stamp=cloud.header.stamp;
#ifdef DEBUG_DRAW_TABLE_MARKERS
    drawPlaneMarkers(plane_infos,plane_marker_pub_,1.0,0.0,0.0);
#endif
    return plane_infos.planes[0];

  }

};

int main(int argc, char** argv)
{
ros::init(argc, argv, "BookStackingNode");
book_stacking bs;
//bs.TestArm();
ros::spin();

}
<commit_msg>Fixed tf to workspace frame<commit_after>#define DEBUG_DRAW_TABLE_MARKERS
#define DEBUG_DRAW_TABLETOP_OBJECTS

//ROS
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <geometry_msgs/PoseStamped.h>
#include <sensor_msgs/PointCloud2.h>

//PCL
#include <pcl_ros/filters/passthrough.h>
#include <pcl/segmentation/sac_segmentation.h>
#include <pcl/sample_consensus/method_types.h>
#include <pcl/sample_consensus/model_types.h>
#include <pcl/surface/convex_hull.h>
#include <pcl/filters/extract_indices.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl_ros/transforms.h>
#include <pcl/filters/statistical_outlier_removal.h>

//TF
#include <tf/transform_listener.h>

//PR2
#include <pr2_controllers_msgs/PointHeadAction.h>

//Manipulation
#include <arm_navigation_msgs/MoveArmAction.h>
#include <arm_navigation_msgs/utils.h>

//STL
#include <string.h>

//VISUALIZATION
#include <visualization_msgs/Marker.h>
#include <visualization_msgs/MarkerArray.h>

#include <plane_extractor.h>

typedef actionlib::SimpleActionClient<pr2_controllers_msgs::PointHeadAction> PointHeadClient;
typedef pcl::PointCloud<pcl::PointXYZ> XYZPointCloud;
typedef pcl::PointXYZ Point;
typedef pcl::KdTree<Point>::Ptr KdTreePtr;

class book_stacking
{

private:
  PointHeadClient* point_head_client_;
  ros::Subscriber point_cloud_sub_;
  double min_table_z_, max_table_z_,leaf_size;
  bool use_downsample;
  double table_ransac_thresh_;
  tf::TransformListener tf_listener;
  std::string workspace_frame;

  bool filter_spatial;
  double filter_spatial_xmin, filter_spatial_xmax;
  double filter_spatial_ymin, filter_spatial_ymax;
  double filter_spatial_zmin, filter_spatial_zmax;

  bool filter_outliers;
  int filter_outliers_meank;
  double filter_outliers_stddev_thresh;
  bool downsample_cloud;
  double downsample_grid_size_;

  bool concave_hull_mode_;
  bool use_normal_seg_;
  int max_planes_;
  bool use_omp_;
  double plane_distance_thresh_;
  double normal_search_radius_;
  int min_plane_inliers_;
  int max_sac_iterations_;
  double sac_probability_;

  std::string base_frame_tf;

public:
  ros::NodeHandle n_;
  ros::Publisher filtered_cloud_pub_;
  ros::Publisher plane_marker_pub_;
  ros::Publisher obj_marker_pub_;

book_stacking():
  n_("~")
{
  point_head_client_ = new PointHeadClient("/head_traj_controller/point_head_action", true);
  while(!point_head_client_->waitForServer(ros::Duration(5.0)))
    {
      ROS_INFO("Waiting for the point_head_action server to come up");
    }
point_cloud_sub_=n_.subscribe("/camera/depth/points",1,&book_stacking::KinectCallback,this);
filtered_cloud_pub_ = n_.advertise<sensor_msgs::PointCloud2>("filtered_cloud",1);

//Visualization Publishers
 plane_marker_pub_ = n_.advertise<visualization_msgs::MarkerArray>("/visualization_marker_array",1);
 obj_marker_pub_ = n_.advertise<visualization_msgs::Marker>("obj_markers",1);

 LoadParameters();

 //lookAt("base_link", 1.5, 0.0, 0.2);
//TestArm();
//shakeHead(2);
}
  void LoadParameters()
  {
    n_.param("min_table_z", min_table_z_, -0.5);
    n_.param("max_table_z", max_table_z_, 1.5);
    n_.param("use_downsample", use_downsample, true);
    n_.param("leaf_size", leaf_size, 0.01);
    std::string default_workspace_frame="/base_link";
    n_.param("workspace_frame", workspace_frame, default_workspace_frame);

    //Spatial Filtering Params
    n_.param("filter_spatial",filter_spatial,true);
    n_.param("filter_spatial_zmax",filter_spatial_zmax,3.0);
    n_.param("filter_spatial_zmin",filter_spatial_zmin,0.05);
    n_.param("filter_spatial_ymax",filter_spatial_ymax,10.0);
    n_.param("filter_spatial_ymin",filter_spatial_ymin,-10.0);
    n_.param("filter_spatial_xmax",filter_spatial_xmax,10.0);
    n_.param("filter_spatial_xmin",filter_spatial_xmin,-10.0);

    //Outlier Filtering Params
    n_.param("filter_outliers",filter_outliers,true);
    n_.param("filter_outliers_meank",filter_outliers_meank,50);
    n_.param("filter_outliers_stddev_thresh", filter_outliers_stddev_thresh,1.0);

    //Downsampling Params
    n_.param("downsample_cloud",downsample_cloud,true);
    n_.param("downsample_grid_size",downsample_grid_size_,0.01);

    //Plane Extraction Parameters
    n_.param("max_planes",max_planes_,4);
    n_.param("use_omp",use_omp_,false);
    n_.param("plane_distance_thresh",plane_distance_thresh_,0.03);
    n_.param("normal_search_radius",normal_search_radius_,0.1);
    n_.param("min_plane_inliers",min_plane_inliers_,1000);
    n_.param("max_sac_iterations",max_sac_iterations_,1000);
    n_.param("sac_probability",sac_probability_,0.99);
    n_.param("concave_hull_mode",concave_hull_mode_,false);
    n_.param("use_normal_seg",use_normal_seg_,false);
    n_.param("base_frame_tf", base_frame_tf,std::string("/base_link"));

  }

void lookAt(std::string frame_id, double x, double y, double z)
  {
    //the goal message we will be sending
    pr2_controllers_msgs::PointHeadGoal goal;

    //the target point, expressed in the requested frame
    geometry_msgs::PointStamped point;
    point.header.frame_id = frame_id;
    point.point.x = x; point.point.y = y; point.point.z = z;
    goal.target = point;

    //we are pointing the high-def camera frame
    //(pointing_axis defaults to X-axis)
    goal.pointing_frame = "high_def_frame";

    //take at least 0.5 seconds to get there
    goal.min_duration = ros::Duration(0.5);

    //and go no faster than 1 rad/s
    goal.max_velocity = 1.0;

    //send the goal
    point_head_client_->sendGoal(goal);

    //wait for it to get there (abort after 2 secs to prevent getting stuck)
    point_head_client_->waitForResult(ros::Duration(2));
  }

  void shakeHead(int n)
  {
    int count = 0;
    while (ros::ok() && ++count <= n )
    {
      //Looks at a point forward (x=5m), slightly left (y=1m), and 1.2m up
      lookAt("base_link", 5.0, 1.0, 1.2);

      //Looks at a point forward (x=5m), slightly right (y=-1m), and 1.2m up
      lookAt("base_link", 5.0, -1.0, 1.2);
    }
  }

void TestArm()
{
ROS_INFO("In TestArm()");
  actionlib::SimpleActionClient<arm_navigation_msgs::MoveArmAction> move_arm("move_right_arm",true);
  move_arm.waitForServer();
  ROS_INFO("Connected to server");
  arm_navigation_msgs::MoveArmGoal goalA;

  goalA.motion_plan_request.group_name = "right_arm";
  goalA.motion_plan_request.num_planning_attempts = 1;
  goalA.motion_plan_request.planner_id = std::string("");
  goalA.planner_service_name = std::string("ompl_planning/plan_kinematic_path");
  goalA.motion_plan_request.allowed_planning_time = ros::Duration(5.0);

  arm_navigation_msgs::SimplePoseConstraint desired_pose;
  desired_pose.header.frame_id = "torso_lift_link";
  desired_pose.link_name = "r_wrist_roll_link";
  desired_pose.pose.position.x = 0.75;
  desired_pose.pose.position.y = -0.188;
  desired_pose.pose.position.z = 0;

  desired_pose.pose.orientation.x = 0.0;
  desired_pose.pose.orientation.y = 0.0;
  desired_pose.pose.orientation.z = 0.0;
  desired_pose.pose.orientation.w = 1.0;

  desired_pose.absolute_position_tolerance.x = 0.02;
  desired_pose.absolute_position_tolerance.y = 0.02;
  desired_pose.absolute_position_tolerance.z = 0.02;

  desired_pose.absolute_roll_tolerance = 0.04;
  desired_pose.absolute_pitch_tolerance = 0.04;
  desired_pose.absolute_yaw_tolerance = 0.04;

  arm_navigation_msgs::addGoalConstraintToMoveArmGoal(desired_pose,goalA);

  if (n_.ok())
  {
    bool finished_within_time = false;
ROS_INFO("BOOKSTACK Giving Goal");
    move_arm.sendGoal(goalA);
    finished_within_time = move_arm.waitForResult(ros::Duration(200.0));
    if (!finished_within_time)
    {
      move_arm.cancelGoal();
      ROS_INFO("Timed out achieving goal A");
    }
    else
    {
      actionlib::SimpleClientGoalState state = move_arm.getState();
      bool success = (state == actionlib::SimpleClientGoalState::SUCCEEDED);
      if(success)
        ROS_INFO("Action finished: %s",state.toString().c_str());
      else
        ROS_INFO("Action failed: %s",state.toString().c_str());
    }
  }

}

void KinectCallback(const sensor_msgs::PointCloud2ConstPtr &cloud_msg)
{
ROS_INFO("PT CLOUD");

 XYZPointCloud cloud;
 pcl::fromROSMsg(*cloud_msg,cloud);

 //pcl_ros::transformPointCloud(workspace_frame,cloud,cloud,tf_listener); //didn't work.

    //Transform it to base frame
    tf::StampedTransform transf;
    try{
      tf_listener.waitForTransform(base_frame_tf, raw_cloud.header.frame_id,
				   msg->header.stamp, ros::Duration(2.0));
      tf_listener.lookupTransform(base_frame_tf, raw_cloud.header.frame_id,
				  msg->header.stamp, transf);
    }catch(tf::TransformException ex){
      ROS_ERROR("Scene segmentation unable to put kinect data in ptu reference frame due to TF error:%s", ex.what());
      return;
    }

    tf::Vector3 v3 = transf.getOrigin();
    tf::Quaternion quat = transf.getRotation();
    Eigen::Quaternionf rot(quat.w(), quat.x(), quat.y(), quat.z());
    Eigen::Vector3f offset(v3.x(), v3.y(), v3.z());
    pcl::transformPointCloud(raw_cloud,cloud,offset,rot);
    cloud.header = raw_cloud.header;
    cloud.header.frame_id = base_frame_tf;

 book_stacking_msgs::PlaneInfo table_plane_info=getTablePlane(cloud);

 bool detect_objects=true;
    if(detect_objects)
      {
	ROS_INFO("Extracting objects...");
	book_stacking_msgs::ObjectInfos objects = getObjectsOverPlane(table_plane_info,cloud);

#ifdef DEBUG_DRAW_TABLETOP_OBJECTS
	if(objects.objects.size() < 1)
	  {
	    ROS_WARN("No objects over this plane.");
	  }
	else
	  {
	    drawObjectPrisms(objects,obj_marker_pub_,table_plane_info,0.0f,1.0f,0.0f);
	    //object_pub_.publish(objects);
	  }
      }
#endif

}

book_stacking_msgs::PlaneInfo getTablePlane(XYZPointCloud& cloud)
  {
    if(filter_spatial)
      {
	pcl::PassThrough<Point> pass;
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("z");
	pass.setFilterLimits(filter_spatial_zmin,filter_spatial_zmax);
	pass.filter(cloud);
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("x");
	pass.setFilterLimits(filter_spatial_xmin,filter_spatial_xmax);
	pass.filter(cloud);
	pass.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
	pass.setFilterFieldName("y");
	pass.setFilterLimits(filter_spatial_ymin,filter_spatial_ymax);
	pass.filter(cloud);
      }

    //Filter Outliers
    if(filter_outliers){
      pcl::StatisticalOutlierRemoval<Point> sor_filter;
      sor_filter.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
      sor_filter.setMeanK(filter_outliers_meank);//50
      sor_filter.setStddevMulThresh(filter_outliers_stddev_thresh);
      sor_filter.filter(cloud);
    }

    //Downsample Cloud
    if(downsample_cloud)
      {
      //downsample
      pcl::VoxelGrid<Point> grid;
      grid.setInputCloud(boost::make_shared<pcl::PointCloud<Point> >(cloud));
      grid.setLeafSize(downsample_grid_size_,downsample_grid_size_,downsample_grid_size_);//0.05
      grid.filter(cloud);
    }

    //Publish the filtered cloud
    sensor_msgs::PointCloud2 filtered_msg;
    pcl::toROSMsg(cloud,filtered_msg);
    ROS_INFO("Publishing filtered cloud...");
    filtered_cloud_pub_.publish(filtered_msg);

    book_stacking_msgs::PlaneInfos plane_infos= getPlanesByNormals(cloud,1,true,concave_hull_mode_,use_omp_,plane_distance_thresh_,max_sac_iterations_,sac_probability_,min_plane_inliers_,normal_search_radius_,0.1);
    plane_infos.header.stamp=cloud.header.stamp;
#ifdef DEBUG_DRAW_TABLE_MARKERS
    drawPlaneMarkers(plane_infos,plane_marker_pub_,1.0,0.0,0.0);
#endif
    return plane_infos.planes[0];

  }

};

int main(int argc, char** argv)
{
ros::init(argc, argv, "BookStackingNode");
book_stacking bs;
//bs.TestArm();
ros::spin();

}
<|endoftext|>