<commit_before>//===--- ResolveLocation.cpp - Source location resolver ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This defines the ResolveLocationInAST function, which resolves a
//  source location into a <Decl *, Stmt *> pair.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/Utils.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/Compiler.h"
using namespace clang;

namespace {

/// \brief Base for the LocResolver classes. Mostly does source range checking.
class VISIBILITY_HIDDEN LocResolverBase {
protected:
  ASTContext &Ctx;
  SourceLocation Loc;

  Decl *Dcl;
  Stmt *Stm;
  bool PassedLoc;

  /// \brief Checks whether Loc is in the source range of 'D'.
  ///
  /// If it is, updates Dcl. If Loc is passed the source range, it sets
  /// PassedLoc, otherwise it does nothing.
  void CheckRange(Decl *D);

  /// \brief Checks whether Loc is in the source range of 'Node'.
  ///
  /// If it is, updates Stm. If Loc is passed the source range, it sets
  /// PassedLoc, otherwise it does nothing.
  void CheckRange(Stmt *Node);

  /// \brief Updates the end source range to cover the full length of the token
  /// positioned at the end of the source range.
  ///
  /// e.g.,
  /// @code
  ///   int foo
  ///   ^   ^
  /// @endcode
  /// will be updated to
  /// @code
  ///   int foo
  ///   ^     ^
  /// @endcode
  void FixRange(SourceRange &Range);

public:
  LocResolverBase(ASTContext &ctx, SourceLocation loc)
    : Ctx(ctx), Loc(loc), Dcl(0), Stm(0), PassedLoc(0) {}

  /// \brief We found a AST node that corresponds to the source location.
  bool FoundIt() const { return Dcl != 0 || Stm != 0; }

  /// \brief We either found a AST node or we passed the source location while
  /// searching.
  bool Finished() const { return FoundIt() || PassedLoc; }

  Decl *getDecl() const { return Dcl; }
  Stmt *getStmt() const { return Stm; }

  std::pair<Decl *, Stmt *> getResult() const {
    return std::make_pair(getDecl(), getStmt());
  }

  /// \brief Debugging output.
  void print(Decl *D);
  /// \brief Debugging output.
  void print(Stmt *Node);
};

/// \brief Searches a statement for the AST node that corresponds to a source
/// location.
class VISIBILITY_HIDDEN StmtLocResolver : public LocResolverBase,
                                          public StmtVisitor<StmtLocResolver> {
public:
  StmtLocResolver(ASTContext &ctx, SourceLocation loc)
    : LocResolverBase(ctx, loc) {}

  void VisitDeclStmt(DeclStmt *Node);
  void VisitStmt(Stmt *Node);
};

/// \brief Searches a declaration for the AST node that corresponds to a source
/// location.
class VISIBILITY_HIDDEN DeclLocResolver : public LocResolverBase,
                                          public DeclVisitor<DeclLocResolver> {
public:
  DeclLocResolver(ASTContext &ctx, SourceLocation loc)
    : LocResolverBase(ctx, loc) {}

  void VisitDeclContext(DeclContext *DC);
  void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
  void VisitVarDecl(VarDecl *D);
  void VisitFunctionDecl(FunctionDecl *D);
  void VisitDecl(Decl *D);
};

} // anonymous namespace

void StmtLocResolver::VisitDeclStmt(DeclStmt *Node) {
  CheckRange(Node);
  if (!FoundIt())
    return;
  assert(Stm == Node && "Result not updated ?");

  // Search all declarations of this DeclStmt. If we found the one corresponding
  // to the source location, update this StmtLocResolver's result.
  DeclLocResolver DLR(Ctx, Loc);
  for (DeclStmt::decl_iterator
         I = Node->decl_begin(), E = Node->decl_end(); I != E; ++I) {
    DLR.Visit(*I);
    if (DLR.Finished()) {
      if (DLR.FoundIt())
        llvm::tie(Dcl, Stm) = DLR.getResult();
      return;
    }
  }
}

void StmtLocResolver::VisitStmt(Stmt *Node) {
  CheckRange(Node);
  if (!FoundIt())
    return;
  assert(Stm == Node && "Result not updated ?");

  // Search the child statements.
  StmtLocResolver SLR(Ctx, Loc);
  for (Stmt::child_iterator
         I = Node->child_begin(), E = Node->child_end(); I != E; ++I) {
    SLR.Visit(*I);
    if (!SLR.Finished())
      continue;

    // We either found it or we passed the source location.

    if (SLR.FoundIt()) {
      // Only update Dcl if we found another more immediate 'parent' Decl for
      // the statement.
      if (SLR.getDecl())
        Dcl = SLR.getDecl();
      Stm = SLR.getStmt();
    }

    return;
  }
}

void DeclLocResolver::VisitDeclContext(DeclContext *DC) {
  DeclLocResolver DLR(Ctx, Loc);
  for (DeclContext::decl_iterator
         I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
    DLR.Visit(*I);
    if (DLR.Finished()) {
      if (DLR.FoundIt())
        llvm::tie(Dcl, Stm) = DLR.getResult();
      return;
    }
  }
}

void DeclLocResolver::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
  VisitDeclContext(TU);
}

void DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) {
  CheckRange(D);
  if (!FoundIt())
    return;
  assert(Dcl == D && "Result not updated ?");

  // First, search through the parameters of the function.
  DeclLocResolver ParmRes(Ctx, Loc);
  for (FunctionDecl::param_iterator
         I = D->param_begin(), E = D->param_end(); I != E; ++I) {
    ParmRes.Visit(*I);
    if (ParmRes.Finished()) {
      if (ParmRes.FoundIt())
        llvm::tie(Dcl, Stm) = ParmRes.getResult();
      return;
    }
  }

  // We didn't found the location in the parameters and we didn't get passed it.

  // Second, search through the declarations that are part of the function.
  // If we find he location there, we won't have to search through its body.
  DeclLocResolver DLR(Ctx, Loc);
  DLR.VisitDeclContext(D);
  if (DLR.FoundIt()) {
    llvm::tie(Dcl, Stm) = DLR.getResult();
    return;
  }

  // We didn't find a declaration that corresponds to the source location.

  // Finally, search through the body of the function.
  if (D->isThisDeclarationADefinition()) {
    StmtLocResolver SLR(Ctx, Loc);
    SLR.Visit(D->getBody());
    if (SLR.FoundIt()) {
      llvm::tie(Dcl, Stm) = SLR.getResult();
      // If we didn't find a more immediate 'parent' declaration for the
      // statement, set the function as the parent.
      if (Dcl == 0)
        Dcl = D;
    }
  }
}

void DeclLocResolver::VisitVarDecl(VarDecl *D) {
  CheckRange(D);
  if (!FoundIt())
    return;
  assert(Dcl == D && "Result not updated ?");

  // Check whether the location points to the init expression.
  if (D->getInit()) {
    StmtLocResolver SLR(Ctx, Loc);
    SLR.Visit(D->getInit());
    Stm = SLR.getStmt();
  }
}

void DeclLocResolver::VisitDecl(Decl *D) {
  CheckRange(D);
}

void LocResolverBase::CheckRange(Decl *D) {
  SourceRange Range = D->getSourceRange();
  if (!Range.isValid())
    return;

  FixRange(Range);

  SourceManager &SourceMgr = Ctx.getSourceManager();
  if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc))
    return;

  if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin()))
    PassedLoc = true;
  else
    Dcl = D;
}

void LocResolverBase::CheckRange(Stmt *Node) {
  SourceRange Range = Node->getSourceRange();
  if (!Range.isValid())
    return;

  FixRange(Range);

  SourceManager &SourceMgr = Ctx.getSourceManager();
  if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc))
    return;

  if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin()))
    PassedLoc = true;
  else
    Stm = Node;
}

void LocResolverBase::FixRange(SourceRange &Range) {
  if (!Range.isValid())
    return;

  unsigned TokSize = Lexer::MeasureTokenLength(Range.getEnd(),
                                               Ctx.getSourceManager(),
                                               Ctx.getLangOptions());
  Range.setEnd(Range.getEnd().getFileLocWithOffset(TokSize-1));
}

void LocResolverBase::print(Decl *D) {
  llvm::raw_ostream &OS = llvm::outs();
  OS << "#### DECL ####\n";
  D->print(OS);
  OS << " <";
  D->getLocStart().print(OS, Ctx.getSourceManager());
  OS << " > - <";
  D->getLocEnd().print(OS, Ctx.getSourceManager());
  OS << ">\n\n";
  OS.flush();
}

void LocResolverBase::print(Stmt *Node) {
  llvm::raw_ostream &OS = llvm::outs();
  OS << "#### STMT ####\n";
  Node->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions()));
  OS << " <";
  Node->getLocStart().print(OS, Ctx.getSourceManager());
  OS << " > - <";
  Node->getLocEnd().print(OS, Ctx.getSourceManager());
  OS << ">\n\n";
  OS.flush();
}

/// \brief Returns the AST node that a source location points to.
///
std::pair<Decl *, Stmt *>
clang::ResolveLocationInAST(ASTContext &Ctx, SourceLocation Loc) {
  if (Loc.isInvalid())
    return std::make_pair((Decl*)0, (Stmt*)0);

  DeclLocResolver DLR(Ctx, Loc);
  DLR.Visit(Ctx.getTranslationUnitDecl());
  return DLR.getResult();
}
<commit_msg>Do an early check for function definition.<commit_after>//===--- ResolveLocation.cpp - Source location resolver ---------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This defines the ResolveLocationInAST function, which resolves a
//  source location into a <Decl *, Stmt *> pair.
//
//===----------------------------------------------------------------------===//

#include "clang/Frontend/Utils.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Lex/Lexer.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/Compiler.h"
using namespace clang;

namespace {

/// \brief Base for the LocResolver classes. Mostly does source range checking.
class VISIBILITY_HIDDEN LocResolverBase {
protected:
  ASTContext &Ctx;
  SourceLocation Loc;

  Decl *Dcl;
  Stmt *Stm;
  bool PassedLoc;

  /// \brief Checks whether Loc is in the source range of 'D'.
  ///
  /// If it is, updates Dcl. If Loc is passed the source range, it sets
  /// PassedLoc, otherwise it does nothing.
  void CheckRange(Decl *D);

  /// \brief Checks whether Loc is in the source range of 'Node'.
  ///
  /// If it is, updates Stm. If Loc is passed the source range, it sets
  /// PassedLoc, otherwise it does nothing.
  void CheckRange(Stmt *Node);

  /// \brief Updates the end source range to cover the full length of the token
  /// positioned at the end of the source range.
  ///
  /// e.g.,
  /// @code
  ///   int foo
  ///   ^   ^
  /// @endcode
  /// will be updated to
  /// @code
  ///   int foo
  ///   ^     ^
  /// @endcode
  void FixRange(SourceRange &Range);

public:
  LocResolverBase(ASTContext &ctx, SourceLocation loc)
    : Ctx(ctx), Loc(loc), Dcl(0), Stm(0), PassedLoc(0) {}

  /// \brief We found a AST node that corresponds to the source location.
  bool FoundIt() const { return Dcl != 0 || Stm != 0; }

  /// \brief We either found a AST node or we passed the source location while
  /// searching.
  bool Finished() const { return FoundIt() || PassedLoc; }

  Decl *getDecl() const { return Dcl; }
  Stmt *getStmt() const { return Stm; }

  std::pair<Decl *, Stmt *> getResult() const {
    return std::make_pair(getDecl(), getStmt());
  }

  /// \brief Debugging output.
  void print(Decl *D);
  /// \brief Debugging output.
  void print(Stmt *Node);
};

/// \brief Searches a statement for the AST node that corresponds to a source
/// location.
class VISIBILITY_HIDDEN StmtLocResolver : public LocResolverBase,
                                          public StmtVisitor<StmtLocResolver> {
public:
  StmtLocResolver(ASTContext &ctx, SourceLocation loc)
    : LocResolverBase(ctx, loc) {}

  void VisitDeclStmt(DeclStmt *Node);
  void VisitStmt(Stmt *Node);
};

/// \brief Searches a declaration for the AST node that corresponds to a source
/// location.
class VISIBILITY_HIDDEN DeclLocResolver : public LocResolverBase,
                                          public DeclVisitor<DeclLocResolver> {
public:
  DeclLocResolver(ASTContext &ctx, SourceLocation loc)
    : LocResolverBase(ctx, loc) {}

  void VisitDeclContext(DeclContext *DC);
  void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
  void VisitVarDecl(VarDecl *D);
  void VisitFunctionDecl(FunctionDecl *D);
  void VisitDecl(Decl *D);
};

} // anonymous namespace

void StmtLocResolver::VisitDeclStmt(DeclStmt *Node) {
  CheckRange(Node);
  if (!FoundIt())
    return;
  assert(Stm == Node && "Result not updated ?");

  // Search all declarations of this DeclStmt. If we found the one corresponding
  // to the source location, update this StmtLocResolver's result.
  DeclLocResolver DLR(Ctx, Loc);
  for (DeclStmt::decl_iterator
         I = Node->decl_begin(), E = Node->decl_end(); I != E; ++I) {
    DLR.Visit(*I);
    if (DLR.Finished()) {
      if (DLR.FoundIt())
        llvm::tie(Dcl, Stm) = DLR.getResult();
      return;
    }
  }
}

void StmtLocResolver::VisitStmt(Stmt *Node) {
  CheckRange(Node);
  if (!FoundIt())
    return;
  assert(Stm == Node && "Result not updated ?");

  // Search the child statements.
  StmtLocResolver SLR(Ctx, Loc);
  for (Stmt::child_iterator
         I = Node->child_begin(), E = Node->child_end(); I != E; ++I) {
    SLR.Visit(*I);
    if (!SLR.Finished())
      continue;

    // We either found it or we passed the source location.

    if (SLR.FoundIt()) {
      // Only update Dcl if we found another more immediate 'parent' Decl for
      // the statement.
      if (SLR.getDecl())
        Dcl = SLR.getDecl();
      Stm = SLR.getStmt();
    }

    return;
  }
}

void DeclLocResolver::VisitDeclContext(DeclContext *DC) {
  DeclLocResolver DLR(Ctx, Loc);
  for (DeclContext::decl_iterator
         I = DC->decls_begin(), E = DC->decls_end(); I != E; ++I) {
    DLR.Visit(*I);
    if (DLR.Finished()) {
      if (DLR.FoundIt())
        llvm::tie(Dcl, Stm) = DLR.getResult();
      return;
    }
  }
}

void DeclLocResolver::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
  VisitDeclContext(TU);
}

void DeclLocResolver::VisitFunctionDecl(FunctionDecl *D) {
  CheckRange(D);
  if (!FoundIt())
    return;
  assert(Dcl == D && "Result not updated ?");

  // First, search through the parameters of the function.
  DeclLocResolver ParmRes(Ctx, Loc);
  for (FunctionDecl::param_iterator
         I = D->param_begin(), E = D->param_end(); I != E; ++I) {
    ParmRes.Visit(*I);
    if (ParmRes.Finished()) {
      if (ParmRes.FoundIt())
        llvm::tie(Dcl, Stm) = ParmRes.getResult();
      return;
    }
  }

  // We didn't found the location in the parameters and we didn't get passed it.

  if (!D->isThisDeclarationADefinition())
    return;

  // Second, search through the declarations that are part of the function.
  // If we find he location there, we won't have to search through its body.
  DeclLocResolver DLR(Ctx, Loc);
  DLR.VisitDeclContext(D);
  if (DLR.FoundIt()) {
    llvm::tie(Dcl, Stm) = DLR.getResult();
    return;
  }

  // We didn't find a declaration that corresponds to the source location.

  // Finally, search through the body of the function.
  assert(D->getBody() && "Expected definition");
  StmtLocResolver SLR(Ctx, Loc);
  SLR.Visit(D->getBody());
  if (SLR.FoundIt()) {
    llvm::tie(Dcl, Stm) = SLR.getResult();
    // If we didn't find a more immediate 'parent' declaration for the
    // statement, set the function as the parent.
    if (Dcl == 0)
      Dcl = D;
  }
}

void DeclLocResolver::VisitVarDecl(VarDecl *D) {
  CheckRange(D);
  if (!FoundIt())
    return;
  assert(Dcl == D && "Result not updated ?");

  // Check whether the location points to the init expression.
  if (D->getInit()) {
    StmtLocResolver SLR(Ctx, Loc);
    SLR.Visit(D->getInit());
    Stm = SLR.getStmt();
  }
}

void DeclLocResolver::VisitDecl(Decl *D) {
  CheckRange(D);
}

void LocResolverBase::CheckRange(Decl *D) {
  SourceRange Range = D->getSourceRange();
  if (!Range.isValid())
    return;

  FixRange(Range);

  SourceManager &SourceMgr = Ctx.getSourceManager();
  if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc))
    return;

  if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin()))
    PassedLoc = true;
  else
    Dcl = D;
}

void LocResolverBase::CheckRange(Stmt *Node) {
  SourceRange Range = Node->getSourceRange();
  if (!Range.isValid())
    return;

  FixRange(Range);

  SourceManager &SourceMgr = Ctx.getSourceManager();
  if (SourceMgr.isBeforeInTranslationUnit(Range.getEnd(), Loc))
    return;

  if (SourceMgr.isBeforeInTranslationUnit(Loc, Range.getBegin()))
    PassedLoc = true;
  else
    Stm = Node;
}

void LocResolverBase::FixRange(SourceRange &Range) {
  if (!Range.isValid())
    return;

  unsigned TokSize = Lexer::MeasureTokenLength(Range.getEnd(),
                                               Ctx.getSourceManager(),
                                               Ctx.getLangOptions());
  Range.setEnd(Range.getEnd().getFileLocWithOffset(TokSize-1));
}

void LocResolverBase::print(Decl *D) {
  llvm::raw_ostream &OS = llvm::outs();
  OS << "#### DECL ####\n";
  D->print(OS);
  OS << " <";
  D->getLocStart().print(OS, Ctx.getSourceManager());
  OS << " > - <";
  D->getLocEnd().print(OS, Ctx.getSourceManager());
  OS << ">\n\n";
  OS.flush();
}

void LocResolverBase::print(Stmt *Node) {
  llvm::raw_ostream &OS = llvm::outs();
  OS << "#### STMT ####\n";
  Node->printPretty(OS, Ctx, 0, PrintingPolicy(Ctx.getLangOptions()));
  OS << " <";
  Node->getLocStart().print(OS, Ctx.getSourceManager());
  OS << " > - <";
  Node->getLocEnd().print(OS, Ctx.getSourceManager());
  OS << ">\n\n";
  OS.flush();
}

/// \brief Returns the AST node that a source location points to.
///
std::pair<Decl *, Stmt *>
clang::ResolveLocationInAST(ASTContext &Ctx, SourceLocation Loc) {
  if (Loc.isInvalid())
    return std::make_pair((Decl*)0, (Stmt*)0);

  DeclLocResolver DLR(Ctx, Loc);
  DLR.Visit(Ctx.getTranslationUnitDecl());
  return DLR.getResult();
}
<|endoftext|>


<commit_before>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"

// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"
#include "sg/Renderer.h"

#include <string>

namespace ospray {
  namespace importer {

    void importOSP(const FileName &fileName, Group *existingGroupToAddTo);
    void importRM(const FileName &fileName, Group *existingGroupToAddTo);

    Group *import(const std::string &fn, Group *existingGroupToAddTo)
    {
      FileName fileName = fn;
      Group *group = existingGroupToAddTo;
      if (!group) group = new Group;

      if (fileName.ext() == "osp") {
          importOSP(fileName, group);
#if 0 // NOTE(jda) - using ospray::sg is broken, needs fixed before enabling
//#ifndef _WIN32
          std::shared_ptr<sg::World> world;;
          world = sg::loadOSP(fn);
          std::shared_ptr<sg::Volume> volumeNode;
          for (auto node : world->nodes) {
            if (node->toString().find("Volume") != std::string::npos)
              volumeNode = std::dynamic_pointer_cast<sg::Volume>(node);
          }
          if (!volumeNode) {
            throw std::runtime_error("#ospray:importer: no volume found "
                                     "in osg file");
          }
          sg::RenderContext ctx;
          std::shared_ptr<sg::Integrator>  integrator;
          integrator = std::make_shared<sg::Integrator>("scivis");
          ctx.integrator = integrator;
          integrator->commit();
          if (!world) {
            std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
            exit(1);
          }

          world->render(ctx);

          OSPVolume volume = volumeNode->volume;

          Volume* msgVolume = new Volume;
          msgVolume->bounds = volumeNode->getBounds();
          msgVolume->handle = volumeNode->volume;
          group->volume.push_back(msgVolume);
#endif
      } else if (fileName.ext() == "bob") {
        importRM(fn, group);
      } else {
        throw std::runtime_error("#ospray:importer: do not know how to import file of type "
            + fileName.ext());
      }

      return group;
    }

  } // ::ospray::importer
} // ::ospray
<commit_msg>fixing sg osp parsing<commit_after>// ======================================================================== //
// Copyright 2009-2017 Intel Corporation                                    //
//                                                                          //
// 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.                                           //
// ======================================================================== //

// own
#include "Importer.h"
// ospcommon
#include "ospcommon/FileName.h"

// scene graph
#include "sg/module/Module.h"
#include "sg/importer/Importer.h"
#include "sg/Renderer.h"

#include <string>

namespace ospray {
  namespace importer {

    void importOSP(const FileName &fileName, Group *existingGroupToAddTo);
    void importRM(const FileName &fileName, Group *existingGroupToAddTo);

    Group *import(const std::string &fn, Group *existingGroupToAddTo)
    {
      FileName fileName = fn;
      Group *group = existingGroupToAddTo;
      if (!group) group = new Group;

      if (fileName.ext() == "osp" || fileName.ext() == "osg") {
          // importOSP(fileName, group);
#if 1 // NOTE(jda) - using ospray::sg is broken, needs fixed before enabling
//#ifndef _WIN32
          std::shared_ptr<sg::World> world;;
          world = sg::loadOSP(fn);
          std::shared_ptr<sg::Volume> volumeNode;
          for (auto node : world->nodes) {
            if (node->toString().find("Volume") != std::string::npos)
              volumeNode = std::dynamic_pointer_cast<sg::Volume>(node);
          }
          if (!volumeNode) {
            throw std::runtime_error("#ospray:importer: no volume found "
                                     "in osp file");
          }
          sg::RenderContext ctx;
          std::shared_ptr<sg::Integrator>  integrator;
          integrator = std::make_shared<sg::Integrator>("scivis");
          ctx.integrator = integrator;
          integrator->commit();
          if (!world) {
            std::cout << "#osp:qtv: no world defined. exiting." << std::endl;
            exit(1);
          }

          world->render(ctx);

          OSPVolume volume = volumeNode->volume;

          Volume* msgVolume = new Volume;
          msgVolume->bounds = volumeNode->getBounds();
          msgVolume->handle = volumeNode->volume;
          group->volume.push_back(msgVolume);
#endif
      } else if (fileName.ext() == "bob") {
        importRM(fn, group);
      } else {
        throw std::runtime_error("#ospray:importer: do not know how to import file of type "
            + fileName.ext());
      }

      return group;
    }

  } // ::ospray::importer
} // ::ospray
<|endoftext|>


<commit_before>#include <osgProducer/KeyboardMouseCallback>

#include <osg/Math>
#include <osg/Notify>

#include <float.h>

using namespace osgProducer;

KeyboardMouseCallback::KeyboardMouseCallback(Producer::KeyboardMouse* keyboardMouse, bool &done, bool escapeKeySetsDone):
    Producer::KeyboardMouseCallback(),
    _keyboardMouse(keyboardMouse),
    _mx(0.0f),_my(0.0f),_mbutton(0),
    _done(done),
    _escapeKeySetsDone(escapeKeySetsDone)
{
    updateWindowSize();
}

void KeyboardMouseCallback::mouseScroll( Producer::KeyboardMouseCallback::ScrollingMotion sm )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseScroll((osgGA::GUIEventAdapter::ScrollingMotion)sm);
}

void KeyboardMouseCallback::buttonPress( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonPress(mx,my,mbutton);
}

void KeyboardMouseCallback::buttonRelease( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonRelease(mx,my,mbutton);
}

void KeyboardMouseCallback::doubleButtonPress( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonPress(mx,my,mbutton);
}

void KeyboardMouseCallback::keyPress( Producer::KeyCharacter key )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->keyPress((osgGA::GUIEventAdapter::KeySymbol)key);

    // check against adapted key symbol.
    if (_escapeKeySetsDone &&
        (osgGA::GUIEventAdapter::KeySymbol)key==osgGA::GUIEventAdapter::KEY_Escape) _done = true;
}

void KeyboardMouseCallback::keyRelease( Producer::KeyCharacter key )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->keyRelease((osgGA::GUIEventAdapter::KeySymbol)key);
}

void KeyboardMouseCallback::specialKeyPress( Producer::KeyCharacter key )
{
    updateWindowSize();
    keyPress(key);
}

void KeyboardMouseCallback::specialKeyRelease( Producer::KeyCharacter key )
{
    updateWindowSize();
    keyRelease(key);
}

void KeyboardMouseCallback::windowConfig( int x, int y, unsigned int width, unsigned int height )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->windowResize(x,y,x+width,y+height);
}

void KeyboardMouseCallback::mouseMotion( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseMotion(mx,my);
}

void KeyboardMouseCallback::passiveMouseMotion( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseMotion(mx,my);
}

void KeyboardMouseCallback::mouseWarp( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseWarp(mx,my); // need mouse warp??
}

void KeyboardMouseCallback::updateWindowSize()
{
    if (!_eventQueue) return;

    osgGA::GUIEventAdapter* ea = _eventQueue->getCurrentEventState();

    Producer::InputArea* ia = _keyboardMouse->getInputArea();
    Producer::RenderSurface* rs = _keyboardMouse->getRenderSurface();
    if (ia)
    {

        float minX = FLT_MAX;
        float minY = FLT_MAX;
        float maxX = -FLT_MAX;
        float maxY = -FLT_MAX;
        //int numInputRectangle = ia->getNumInputRectangle();
        int numRenderSurfaces = ia->getNumRenderSurfaces();
        for (int i=0;i<numRenderSurfaces;++i)
        {
            const Producer::RenderSurface::InputRectangle &ir =
                ia->getRenderSurface(i)->getInputRectangle();

            minX = osg::minimum(minX,ir.left());
            minX = osg::minimum(minX,ir.left()+ir.width());

            minY = osg::minimum(minY,ir.bottom());
            minY = osg::minimum(minY,ir.bottom()+ir.height());

            maxX = osg::maximum(maxX,ir.left());
            maxX = osg::maximum(maxX,ir.left()+ir.width());

            maxY = osg::maximum(maxY,ir.bottom());
            maxY = osg::maximum(maxY,ir.bottom()+ir.height());
        }
        ea->setWindowSize(minX,minY,maxX,maxY);
    }
    else if (rs)
    {
        //ea->setWindowSize(-1.0f,-1.0f,1.0f,1.0f);

        const Producer::RenderSurface::InputRectangle &ir = rs->getInputRectangle();

        float minX = osg::minimum(ir.left(),ir.left()+ir.width());
        float maxX = osg::maximum(ir.left(),ir.left()+ir.width());
        float minY = osg::minimum(ir.bottom(),ir.bottom()+ir.height());
        float maxY = osg::maximum(ir.bottom(),ir.bottom()+ir.height());

        ea->setWindowSize(minX,minY,maxX,maxY);
    }
}

bool KeyboardMouseCallback::takeEventQueue(EventQueue& queue)
{
    updateWindowSize();
    return _eventQueue->takeEvents(queue);
}

bool KeyboardMouseCallback::copyEventQueue(EventQueue& queue) const
{
    return _eventQueue->copyEvents(queue);
}

void KeyboardMouseCallback::setEventQueue(EventQueue& queue)
{
    _eventQueue->setEvents(queue);
}

void KeyboardMouseCallback::appendEventQueue(EventQueue& queue)
{
    _eventQueue->appendEvents(queue);
}

void KeyboardMouseCallback::shutdown()
{
    _done = true;
    _keyboardMouse->cancel();
}

osgGA::GUIEventAdapter* KeyboardMouseCallback::createEventAdapter()
{
    return new osgGA::GUIEventAdapter(*(_eventQueue->getCurrentEventState()));
}
<commit_msg>Fixed mouse scroll mapping.<commit_after>#include <osgProducer/KeyboardMouseCallback>

#include <osg/Math>
#include <osg/Notify>

#include <float.h>

using namespace osgProducer;

KeyboardMouseCallback::KeyboardMouseCallback(Producer::KeyboardMouse* keyboardMouse, bool &done, bool escapeKeySetsDone):
    Producer::KeyboardMouseCallback(),
    _keyboardMouse(keyboardMouse),
    _mx(0.0f),_my(0.0f),_mbutton(0),
    _done(done),
    _escapeKeySetsDone(escapeKeySetsDone)
{
    updateWindowSize();
}

void KeyboardMouseCallback::mouseScroll( Producer::KeyboardMouseCallback::ScrollingMotion sm )
{
    updateWindowSize();
    if (_eventQueue.valid())
    {
        switch(sm)
        {
            case(Producer::KeyboardMouseCallback::ScrollNone): break;
            case(Producer::KeyboardMouseCallback::ScrollUp): _eventQueue->mouseScroll(osgGA::GUIEventAdapter::SCROLL_UP); break;
            case(Producer::KeyboardMouseCallback::ScrollDown): _eventQueue->mouseScroll(osgGA::GUIEventAdapter::SCROLL_DOWN); break;
        }
    }
}

void KeyboardMouseCallback::buttonPress( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonPress(mx,my,mbutton);
}

void KeyboardMouseCallback::buttonRelease( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonRelease(mx,my,mbutton);
}

void KeyboardMouseCallback::doubleButtonPress( float mx, float my, unsigned int mbutton )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseButtonPress(mx,my,mbutton);
}

void KeyboardMouseCallback::keyPress( Producer::KeyCharacter key )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->keyPress((osgGA::GUIEventAdapter::KeySymbol)key);

    // check against adapted key symbol.
    if (_escapeKeySetsDone &&
        (osgGA::GUIEventAdapter::KeySymbol)key==osgGA::GUIEventAdapter::KEY_Escape) _done = true;
}

void KeyboardMouseCallback::keyRelease( Producer::KeyCharacter key )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->keyRelease((osgGA::GUIEventAdapter::KeySymbol)key);
}

void KeyboardMouseCallback::specialKeyPress( Producer::KeyCharacter key )
{
    updateWindowSize();
    keyPress(key);
}

void KeyboardMouseCallback::specialKeyRelease( Producer::KeyCharacter key )
{
    updateWindowSize();
    keyRelease(key);
}

void KeyboardMouseCallback::windowConfig( int x, int y, unsigned int width, unsigned int height )
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->windowResize(x,y,x+width,y+height);
}

void KeyboardMouseCallback::mouseMotion( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseMotion(mx,my);
}

void KeyboardMouseCallback::passiveMouseMotion( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseMotion(mx,my);
}

void KeyboardMouseCallback::mouseWarp( float mx, float my)
{
    updateWindowSize();
    if (_eventQueue.valid()) _eventQueue->mouseWarp(mx,my); // need mouse warp??
}

void KeyboardMouseCallback::updateWindowSize()
{
    if (!_eventQueue) return;

    osgGA::GUIEventAdapter* ea = _eventQueue->getCurrentEventState();

    Producer::InputArea* ia = _keyboardMouse->getInputArea();
    Producer::RenderSurface* rs = _keyboardMouse->getRenderSurface();
    if (ia)
    {

        float minX = FLT_MAX;
        float minY = FLT_MAX;
        float maxX = -FLT_MAX;
        float maxY = -FLT_MAX;
        //int numInputRectangle = ia->getNumInputRectangle();
        int numRenderSurfaces = ia->getNumRenderSurfaces();
        for (int i=0;i<numRenderSurfaces;++i)
        {
            const Producer::RenderSurface::InputRectangle &ir =
                ia->getRenderSurface(i)->getInputRectangle();

            minX = osg::minimum(minX,ir.left());
            minX = osg::minimum(minX,ir.left()+ir.width());

            minY = osg::minimum(minY,ir.bottom());
            minY = osg::minimum(minY,ir.bottom()+ir.height());

            maxX = osg::maximum(maxX,ir.left());
            maxX = osg::maximum(maxX,ir.left()+ir.width());

            maxY = osg::maximum(maxY,ir.bottom());
            maxY = osg::maximum(maxY,ir.bottom()+ir.height());
        }
        ea->setWindowSize(minX,minY,maxX,maxY);
    }
    else if (rs)
    {
        //ea->setWindowSize(-1.0f,-1.0f,1.0f,1.0f);

        const Producer::RenderSurface::InputRectangle &ir = rs->getInputRectangle();

        float minX = osg::minimum(ir.left(),ir.left()+ir.width());
        float maxX = osg::maximum(ir.left(),ir.left()+ir.width());
        float minY = osg::minimum(ir.bottom(),ir.bottom()+ir.height());
        float maxY = osg::maximum(ir.bottom(),ir.bottom()+ir.height());

        ea->setWindowSize(minX,minY,maxX,maxY);
    }
}

bool KeyboardMouseCallback::takeEventQueue(EventQueue& queue)
{
    updateWindowSize();
    return _eventQueue->takeEvents(queue);
}

bool KeyboardMouseCallback::copyEventQueue(EventQueue& queue) const
{
    return _eventQueue->copyEvents(queue);
}

void KeyboardMouseCallback::setEventQueue(EventQueue& queue)
{
    _eventQueue->setEvents(queue);
}

void KeyboardMouseCallback::appendEventQueue(EventQueue& queue)
{
    _eventQueue->appendEvents(queue);
}

void KeyboardMouseCallback::shutdown()
{
    _done = true;
    _keyboardMouse->cancel();
}

osgGA::GUIEventAdapter* KeyboardMouseCallback::createEventAdapter()
{
    return new osgGA::GUIEventAdapter(*(_eventQueue->getCurrentEventState()));
}
<|endoftext|>


<commit_before>#include "GapHeatPointSourceMaster.h"
#include "SystemBase.h"

template<>
InputParameters validParams<GapHeatPointSourceMaster>()
{
  InputParameters params = validParams<DiracKernel>();
  params.addRequiredParam<unsigned int>("boundary", "The master boundary");
  params.addRequiredParam<unsigned int>("slave", "The slave boundary");
  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

GapHeatPointSourceMaster::GapHeatPointSourceMaster(const std::string & name, InputParameters parameters)
  :DiracKernel(name, parameters),
   _penetration_locator(getPenetrationLocator(getParam<unsigned int>("boundary"), getParam<unsigned int>("slave"))),
   _slave_flux(_sys.getVector("slave_flux"))
{}

void
GapHeatPointSourceMaster::addPoints()
{
  point_to_info.clear();

  _slave_flux.close();

  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();

  for(; it!=end; ++it)
  {
    unsigned int slave_node_num = it->first;
    PenetrationLocator::PenetrationInfo * pinfo = it->second;

    if(!pinfo)
      continue;

    const Node * node = pinfo->_node;

    addPoint(pinfo->_elem, pinfo->_closest_point);
    point_to_info[pinfo->_closest_point] = pinfo;
  }
}

Real
GapHeatPointSourceMaster::computeQpResidual()
{
  PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point];
  const Node * node = pinfo->_node;
  long int dof_number = node->dof_number(0, _var.number(), 0);

  return -_phi[_i][_qp] * _slave_flux(dof_number);
}

Real
GapHeatPointSourceMaster::computeQpJacobian()
{
  return 0;
}
<commit_msg>Preparing the code for full Jacobian assembling<commit_after>#include "GapHeatPointSourceMaster.h"
#include "SystemBase.h"

template<>
InputParameters validParams<GapHeatPointSourceMaster>()
{
  InputParameters params = validParams<DiracKernel>();
  params.addRequiredParam<unsigned int>("boundary", "The master boundary");
  params.addRequiredParam<unsigned int>("slave", "The slave boundary");
  params.set<bool>("use_displaced_mesh") = true;

  return params;
}

GapHeatPointSourceMaster::GapHeatPointSourceMaster(const std::string & name, InputParameters parameters)
  :DiracKernel(name, parameters),
   _penetration_locator(getPenetrationLocator(getParam<unsigned int>("boundary"), getParam<unsigned int>("slave"))),
   _slave_flux(_sys.getVector("slave_flux"))
{}

void
GapHeatPointSourceMaster::addPoints()
{
  point_to_info.clear();

  _slave_flux.close();

  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator it = _penetration_locator._penetration_info.begin();
  std::map<unsigned int, PenetrationLocator::PenetrationInfo *>::iterator end = _penetration_locator._penetration_info.end();

  for(; it!=end; ++it)
  {
    unsigned int slave_node_num = it->first;
    PenetrationLocator::PenetrationInfo * pinfo = it->second;

    if(!pinfo)
      continue;

    const Node * node = pinfo->_node;

    addPoint(pinfo->_elem, pinfo->_closest_point);
    point_to_info[pinfo->_closest_point] = pinfo;
  }
}

Real
GapHeatPointSourceMaster::computeQpResidual()
{
  PenetrationLocator::PenetrationInfo * pinfo = point_to_info[_current_point];
  const Node * node = pinfo->_node;
  long int dof_number = node->dof_number(_sys.number(), _var.number(), 0);

  return -_test[_i][_qp] * _slave_flux(dof_number);
}

Real
GapHeatPointSourceMaster::computeQpJacobian()
{
  return 0;
}
<|endoftext|>


<commit_before>/*
 * istream facade that ignores read() calls until it is resumed.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_pause.hxx"
#include "istream_forward.hxx"

class PauseIstream : public ForwardIstream {
    bool resumed = false;

public:
    PauseIstream(struct pool &p, struct istream &_input)
        :ForwardIstream(p, MakeIstreamClass<PauseIstream>::cls,
                        _input,
                        MakeIstreamHandler<PauseIstream>::handler, this) {}

    void Resume() {
        resumed = true;
    }

    /* istream */

    void Read() {
        if (resumed)
            ForwardIstream::Read();
        else
            CopyDirect();
    }

    int AsFd() {
        return resumed
            ? ForwardIstream::AsFd()
            : -1;
    }
};

struct istream *
istream_pause_new(struct pool *pool, struct istream *input)
{
    return NewIstream<PauseIstream>(*pool, *input);
}

void
istream_pause_resume(struct istream *istream)
{
    assert(istream != nullptr);

    auto &pause = *(PauseIstream *)istream;
    pause.Resume();
}
<commit_msg>istream_pause: use Istream::Cast()<commit_after>/*
 * istream facade that ignores read() calls until it is resumed.
 *
 * author: Max Kellermann <mk@cm4all.com>
 */

#include "istream_pause.hxx"
#include "istream_forward.hxx"

class PauseIstream : public ForwardIstream {
    bool resumed = false;

public:
    PauseIstream(struct pool &p, struct istream &_input)
        :ForwardIstream(p, MakeIstreamClass<PauseIstream>::cls,
                        _input,
                        MakeIstreamHandler<PauseIstream>::handler, this) {}

    void Resume() {
        resumed = true;
    }

    /* istream */

    void Read() {
        if (resumed)
            ForwardIstream::Read();
        else
            CopyDirect();
    }

    int AsFd() {
        return resumed
            ? ForwardIstream::AsFd()
            : -1;
    }
};

struct istream *
istream_pause_new(struct pool *pool, struct istream *input)
{
    return NewIstream<PauseIstream>(*pool, *input);
}

void
istream_pause_resume(struct istream *istream)
{
    assert(istream != nullptr);

    auto &pause = (PauseIstream &)Istream::Cast(*istream);
    pause.Resume();
}
<|endoftext|>


<commit_before>/*
 * Copyright 2018 Google Inc.
 *
 * 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 <algorithm>
#include <blobs-ipmid/manager.hpp>
#include <memory>
#include <string>
#include <vector>

namespace blobs
{

void BlobManager::incrementOpen(const std::string& path)
{
    if (path.empty())
    {
        return;
    }

    openFiles[path] += 1;
}

void BlobManager::decrementOpen(const std::string& path)
{
    if (path.empty())
    {
        return;
    }

    /* TODO(venture): Check into the iterator from find, does it makes sense
     * to just update it directly? */
    auto entry = openFiles.find(path);
    if (entry != openFiles.end())
    {
        /* found it, decrement it and remove it if 0. */
        openFiles[path] -= 1;
        if (openFiles[path] == 0)
        {
            openFiles.erase(path);
        }
    }
}

int BlobManager::getOpen(const std::string& path) const
{
    /* No need to input check on the read-only call. */
    auto entry = openFiles.find(path);
    if (entry != openFiles.end())
    {
        return entry->second;
    }

    return 0;
}

bool BlobManager::registerHandler(std::unique_ptr<GenericBlobInterface> handler)
{
    if (!handler)
    {
        return false;
    }

    handlers.push_back(std::move(handler));
    return true;
}

uint32_t BlobManager::buildBlobList()
{
    /* Clear out the current list (IPMI handler is presently single-threaded).
     */
    ids.clear();

    /* Grab the list of blobs and extend the local list */
    for (const auto& h : handlers)
    {
        std::vector<std::string> blobs = h->getBlobIds();
        ids.insert(ids.end(), blobs.begin(), blobs.end());
    }

    return ids.size();
}

std::string BlobManager::getBlobId(uint32_t index)
{
    /* Range check. */
    if (index >= ids.size())
    {
        return "";
    }

    return ids[index];
}

bool BlobManager::open(uint16_t flags, const std::string& path,
                       uint16_t* session)
{
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* No sessions availabe... */
    if (!getSession(session))
    {
        return false;
    }

    /* Verify flags - must be at least read or write */
    if (!(flags & (OpenFlags::read | OpenFlags::write)))
    {
        /* Neither read not write set, which means calls to Read/Write will
         * reject. */
        return false;
    }

    if (!handler->open(*session, flags, path))
    {
        return false;
    }

    /* Associate session with handler */
    sessions[*session] = SessionInfo(path, handler, flags);
    incrementOpen(path);
    return true;
}

GenericBlobInterface* BlobManager::getHandler(const std::string& path)
{
    /* Find a handler. */
    auto h = std::find_if(
        handlers.begin(), handlers.end(),
        [&path](const auto& iter) { return (iter->canHandleBlob(path)); });
    if (h != handlers.end())
    {
        return h->get();
    }

    return nullptr;
}

GenericBlobInterface* BlobManager::getHandler(uint16_t session)
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return nullptr;
    }

    return item->second.handler;
}

SessionInfo* BlobManager::getSessionInfo(uint16_t session)
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return nullptr;
    }

    /* If we go to multi-threaded, this pointer can be invalidated and this
     * method will need to change.
     */
    return &item->second;
}

std::string BlobManager::getPath(uint16_t session) const
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return "";
    }

    return item->second.blobId;
}

bool BlobManager::stat(const std::string& path, struct BlobMeta* meta)
{
    /* meta should never be NULL. */
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->stat(path, meta);
}

bool BlobManager::stat(uint16_t session, struct BlobMeta* meta)
{
    /* meta should never be NULL. */
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->stat(session, meta);
}

bool BlobManager::commit(uint16_t session, const std::vector<uint8_t>& data)
{
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->commit(session, data);
}

bool BlobManager::close(uint16_t session)
{
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* Handler returns failure */
    if (!handler->close(session))
    {
        return false;
    }

    sessions.erase(session);
    decrementOpen(getPath(session));
    return true;
}

std::vector<uint8_t> BlobManager::read(uint16_t session, uint32_t offset,
                                       uint32_t requestedSize)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return std::vector<uint8_t>();
    }

    /* Check flags. */
    if (!(info->flags & OpenFlags::read))
    {
        return std::vector<uint8_t>();
    }

    /* Try reading from it. */
    return info->handler->read(session, offset, requestedSize);
}

bool BlobManager::write(uint16_t session, uint32_t offset,
                        const std::vector<uint8_t>& data)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return false;
    }

    /* Check flags. */
    if (!(info->flags & OpenFlags::write))
    {
        return false;
    }

    /* Try writing to it. */
    return info->handler->write(session, offset, data);
}

bool BlobManager::deleteBlob(const std::string& path)
{
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* Check if the file has any open handles. */
    if (getOpen(path) > 0)
    {
        return false;
    }

    /* Try deleting it. */
    return handler->deleteBlob(path);
}

bool BlobManager::writeMeta(uint16_t session, uint32_t offset,
                            const std::vector<uint8_t>& data)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return false;
    }

    /* Try writing metadata to it. */
    return info->handler->writeMeta(session, offset, data);
}

bool BlobManager::getSession(uint16_t* sess)
{
    uint16_t tries = 0;

    if (!sess)
    {
        return false;
    }

    /* This is not meant to fail as you have 64KiB values available. */

    /* TODO(venture): We could just count the keys in the session map to know
     * if it's full.
     */
    do
    {
        uint16_t lsess = next++;
        if (!sessions.count(lsess))
        {
            /* value not in use, return it. */
            (*sess) = lsess;
            return true;
        }
    } while (++tries < 0xffff);

    return false;
}

static std::unique_ptr<BlobManager> manager;

ManagerInterface* getBlobManager()
{
    if (manager == nullptr)
    {
        manager = std::make_unique<BlobManager>();
    }

    return manager.get();
}

} // namespace blobs
<commit_msg>manager: typo fix available<commit_after>/*
 * Copyright 2018 Google Inc.
 *
 * 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 <algorithm>
#include <blobs-ipmid/manager.hpp>
#include <memory>
#include <string>
#include <vector>

namespace blobs
{

void BlobManager::incrementOpen(const std::string& path)
{
    if (path.empty())
    {
        return;
    }

    openFiles[path] += 1;
}

void BlobManager::decrementOpen(const std::string& path)
{
    if (path.empty())
    {
        return;
    }

    /* TODO(venture): Check into the iterator from find, does it makes sense
     * to just update it directly? */
    auto entry = openFiles.find(path);
    if (entry != openFiles.end())
    {
        /* found it, decrement it and remove it if 0. */
        openFiles[path] -= 1;
        if (openFiles[path] == 0)
        {
            openFiles.erase(path);
        }
    }
}

int BlobManager::getOpen(const std::string& path) const
{
    /* No need to input check on the read-only call. */
    auto entry = openFiles.find(path);
    if (entry != openFiles.end())
    {
        return entry->second;
    }

    return 0;
}

bool BlobManager::registerHandler(std::unique_ptr<GenericBlobInterface> handler)
{
    if (!handler)
    {
        return false;
    }

    handlers.push_back(std::move(handler));
    return true;
}

uint32_t BlobManager::buildBlobList()
{
    /* Clear out the current list (IPMI handler is presently single-threaded).
     */
    ids.clear();

    /* Grab the list of blobs and extend the local list */
    for (const auto& h : handlers)
    {
        std::vector<std::string> blobs = h->getBlobIds();
        ids.insert(ids.end(), blobs.begin(), blobs.end());
    }

    return ids.size();
}

std::string BlobManager::getBlobId(uint32_t index)
{
    /* Range check. */
    if (index >= ids.size())
    {
        return "";
    }

    return ids[index];
}

bool BlobManager::open(uint16_t flags, const std::string& path,
                       uint16_t* session)
{
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* No sessions available... */
    if (!getSession(session))
    {
        return false;
    }

    /* Verify flags - must be at least read or write */
    if (!(flags & (OpenFlags::read | OpenFlags::write)))
    {
        /* Neither read not write set, which means calls to Read/Write will
         * reject. */
        return false;
    }

    if (!handler->open(*session, flags, path))
    {
        return false;
    }

    /* Associate session with handler */
    sessions[*session] = SessionInfo(path, handler, flags);
    incrementOpen(path);
    return true;
}

GenericBlobInterface* BlobManager::getHandler(const std::string& path)
{
    /* Find a handler. */
    auto h = std::find_if(
        handlers.begin(), handlers.end(),
        [&path](const auto& iter) { return (iter->canHandleBlob(path)); });
    if (h != handlers.end())
    {
        return h->get();
    }

    return nullptr;
}

GenericBlobInterface* BlobManager::getHandler(uint16_t session)
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return nullptr;
    }

    return item->second.handler;
}

SessionInfo* BlobManager::getSessionInfo(uint16_t session)
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return nullptr;
    }

    /* If we go to multi-threaded, this pointer can be invalidated and this
     * method will need to change.
     */
    return &item->second;
}

std::string BlobManager::getPath(uint16_t session) const
{
    auto item = sessions.find(session);
    if (item == sessions.end())
    {
        return "";
    }

    return item->second.blobId;
}

bool BlobManager::stat(const std::string& path, struct BlobMeta* meta)
{
    /* meta should never be NULL. */
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->stat(path, meta);
}

bool BlobManager::stat(uint16_t session, struct BlobMeta* meta)
{
    /* meta should never be NULL. */
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->stat(session, meta);
}

bool BlobManager::commit(uint16_t session, const std::vector<uint8_t>& data)
{
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    return handler->commit(session, data);
}

bool BlobManager::close(uint16_t session)
{
    GenericBlobInterface* handler = getHandler(session);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* Handler returns failure */
    if (!handler->close(session))
    {
        return false;
    }

    sessions.erase(session);
    decrementOpen(getPath(session));
    return true;
}

std::vector<uint8_t> BlobManager::read(uint16_t session, uint32_t offset,
                                       uint32_t requestedSize)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return std::vector<uint8_t>();
    }

    /* Check flags. */
    if (!(info->flags & OpenFlags::read))
    {
        return std::vector<uint8_t>();
    }

    /* Try reading from it. */
    return info->handler->read(session, offset, requestedSize);
}

bool BlobManager::write(uint16_t session, uint32_t offset,
                        const std::vector<uint8_t>& data)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return false;
    }

    /* Check flags. */
    if (!(info->flags & OpenFlags::write))
    {
        return false;
    }

    /* Try writing to it. */
    return info->handler->write(session, offset, data);
}

bool BlobManager::deleteBlob(const std::string& path)
{
    GenericBlobInterface* handler = getHandler(path);

    /* No handler found. */
    if (!handler)
    {
        return false;
    }

    /* Check if the file has any open handles. */
    if (getOpen(path) > 0)
    {
        return false;
    }

    /* Try deleting it. */
    return handler->deleteBlob(path);
}

bool BlobManager::writeMeta(uint16_t session, uint32_t offset,
                            const std::vector<uint8_t>& data)
{
    SessionInfo* info = getSessionInfo(session);

    /* No session found. */
    if (!info)
    {
        return false;
    }

    /* Try writing metadata to it. */
    return info->handler->writeMeta(session, offset, data);
}

bool BlobManager::getSession(uint16_t* sess)
{
    uint16_t tries = 0;

    if (!sess)
    {
        return false;
    }

    /* This is not meant to fail as you have 64KiB values available. */

    /* TODO(venture): We could just count the keys in the session map to know
     * if it's full.
     */
    do
    {
        uint16_t lsess = next++;
        if (!sessions.count(lsess))
        {
            /* value not in use, return it. */
            (*sess) = lsess;
            return true;
        }
    } while (++tries < 0xffff);

    return false;
}

static std::unique_ptr<BlobManager> manager;

ManagerInterface* getBlobManager()
{
    if (manager == nullptr)
    {
        manager = std::make_unique<BlobManager>();
    }

    return manager.get();
}

} // namespace blobs
<|endoftext|>


<commit_before>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>

#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>

static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;

QByteArray convertToQmlType(const QByteArray &cppName)
{
    QByteArray qmlName = cppToQml.value(cppName, cppName);
    qmlName.replace("::", ".");
    qmlName.replace("/", ".");
    return qmlName;
}

void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
    static QByteArray declListPrefix = "QDeclarativeListProperty<";

    if (typeName->endsWith('*')) {
        *isPointer = true;
        typeName->truncate(typeName->length() - 1);
        erasure(typeName, isList, isPointer);
    } else if (typeName->startsWith(declListPrefix)) {
        *isList = true;
        typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
        *typeName = typeName->mid(declListPrefix.size());
        erasure(typeName, isList, isPointer);
    }

    *typeName = convertToQmlType(*typeName);
}

void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
    if (! meta || metas->contains(meta))
        return;

    metas->insert(meta);
    processMetaObject(meta->superClass(), metas);
}

void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
    if (! object)
        return;

    const QMetaObject *meta = object->metaObject();
    processMetaObject(meta, metas);

    for (int index = 0; index < meta->propertyCount(); ++index) {
        QMetaProperty prop = meta->property(index);
        if (QDeclarativeMetaType::isQObject(prop.userType())) {
            QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
            processObject(oo, metas);
        }
    }

}

void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
    processMetaObject(ty->metaObject(), metas);
}

void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
    bool isList = false, isPointer = false;
    erasure(&typeName, &isList, &isPointer);
    attrs->append(QXmlStreamAttribute("type", typeName));
    if (isList)
        attrs->append(QXmlStreamAttribute("isList", "true"));
}

void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
    xml->writeStartElement("property");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));

    writeType(&attributes, prop.typeName());

    xml->writeAttributes(attributes);
    xml->writeEndElement();
}

void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
    if (meth.methodType() == QMetaMethod::Signal) {
        if (meth.access() != QMetaMethod::Protected)
            return; // nothing to do.
    } else if (meth.access() != QMetaMethod::Public) {
        return; // nothing to do.
    }

    QByteArray name = meth.signature();
    int lparenIndex = name.indexOf('(');
    if (lparenIndex == -1) {
        return; // invalid signature
    }

    name = name.left(lparenIndex);

    QString elementName = QLatin1String("method");

    QXmlStreamAttributes attributes;
    if (meth.methodType() == QMetaMethod::Signal)
        elementName = QLatin1String("signal");

    xml->writeStartElement(elementName);

    attributes.append(QXmlStreamAttribute("name", name));

    const QString typeName = convertToQmlType(meth.typeName());
    if (! typeName.isEmpty())
        attributes.append(QXmlStreamAttribute("type", typeName));

    xml->writeAttributes(attributes);

    for (int i = 0; i < meth.parameterTypes().size(); ++i) {
        QByteArray argName = meth.parameterNames().at(i);

        xml->writeStartElement("param");

        QXmlStreamAttributes attrs;

        if (! argName.isEmpty())
            attrs.append(QXmlStreamAttribute("name", argName));

        writeType(&attrs, meth.parameterTypes().at(i));
        xml->writeAttributes(attrs);

        xml->writeEndElement();
    }

    xml->writeEndElement();
}

void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
    xml->writeStartElement("enum");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
    xml->writeAttributes(attributes);

    for (int index = 0; index < e.keyCount(); ++index) {
        xml->writeStartElement("enumerator");

        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
        attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
        xml->writeAttributes(attributes);

        xml->writeEndElement();
    }

    xml->writeEndElement();
}

class FriendlyQObject: public QObject
{
public:
    static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};

void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
    xml->writeStartElement("type");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", convertToQmlType(meta->className())));

    if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
        attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
    }

    QString version;

    if (meta->superClass())
        attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));

    if (! version.isEmpty())
        attributes.append(QXmlStreamAttribute("version", version));

    xml->writeAttributes(attributes);

    for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
        dump(meta->enumerator(index), xml);

    for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
        dump(meta->property(index), xml);

    for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
        dump(meta->method(index), xml);

    xml->writeEndElement();
}

void writeScriptElement(QXmlStreamWriter *xml)
{
    xml->writeStartElement("type");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "Script"));
        xml->writeAttributes(attributes);
    }

    xml->writeStartElement("property");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "script"));
        attributes.append(QXmlStreamAttribute("type", "string"));
        xml->writeAttributes(attributes);
    }
    xml->writeEndElement();

    xml->writeStartElement("property");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "source"));
        attributes.append(QXmlStreamAttribute("type", "QUrl"));
        xml->writeAttributes(attributes);
    }
    xml->writeEndElement();

    xml->writeEndElement();
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QDeclarativeView view;
    QDeclarativeEngine *engine = view.engine();

    {
        QByteArray code;
        code += "import Qt 4.6;\n";
        code += "import Qt.widgets 4.6;\n";
        code += "import Qt.multimedia 1.0;\n";
        code += "import Qt.labs.particles 4.6;\n";
        code += "import org.webkit 1.0;\n";
        code += "Item {}";
        QDeclarativeComponent c(engine);
        c.setData(code, QUrl("xxx"));
        c.create();
    }

    cppToQml.insert("QString", "string");

    QSet<const QMetaObject *> metas;

    metas.insert(FriendlyQObject::qtMeta());

    foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
        cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
        qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
        processDeclarativeType(ty, &metas);
    }

    foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
        QByteArray tyName = ty->qmlTypeName();
        tyName = tyName.mid(tyName.lastIndexOf('/') + 1);

        QByteArray code;
        code += "import Qt 4.6;\n";
        code += "import Qt.widgets 4.6;\n";
        code += "import Qt.multimedia 1.0;\n";
        code += "import Qt.labs.particles 4.6;\n";
        code += "import org.webkit 1.0;\n";
        code += tyName;
        code += " {}\n";

        QDeclarativeComponent c(engine);
        c.setData(code, QUrl("xxx"));
        processObject(c.create(), &metas);
    }

    QByteArray bytes;
    QXmlStreamWriter xml(&bytes);
    xml.setAutoFormatting(true);

    xml.writeStartDocument("1.0");
    xml.writeStartElement("module");

    QMap<QString, const QMetaObject *> nameToMeta;
    foreach (const QMetaObject *meta, metas) {
        nameToMeta.insert(convertToQmlType(meta->className()), meta);
    }
    foreach (const QMetaObject *meta, nameToMeta) {
        dump(meta, &xml);
    }

    writeScriptElement(&xml);

    xml.writeEndElement();
    xml.writeEndDocument();

    std::cout << bytes.constData();

    QTimer timer;
    timer.setSingleShot(true);
    timer.setInterval(0);
    QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));

    timer.start();

    return app.exec();
}
<commit_msg>Changed qmldump to also output the default property when there is one.<commit_after>#include <QApplication>
#include <QSet>
#include <QXmlStreamWriter>
#include <QXmlStreamReader>

#include <QMetaObject>
#include <QMetaProperty>
#include <QPushButton>
#include <QDebug>
#include <iostream>
#include <QtDeclarative>
#include <QtDeclarative/private/qdeclarativemetatype_p.h>
#include <QtDeclarative/QDeclarativeView>

static QHash<QByteArray, const QDeclarativeType *> qmlTypeByCppName;
static QHash<QByteArray, QByteArray> cppToQml;

QByteArray convertToQmlType(const QByteArray &cppName)
{
    QByteArray qmlName = cppToQml.value(cppName, cppName);
    qmlName.replace("::", ".");
    qmlName.replace("/", ".");
    return qmlName;
}

void erasure(QByteArray *typeName, bool *isList, bool *isPointer)
{
    static QByteArray declListPrefix = "QDeclarativeListProperty<";

    if (typeName->endsWith('*')) {
        *isPointer = true;
        typeName->truncate(typeName->length() - 1);
        erasure(typeName, isList, isPointer);
    } else if (typeName->startsWith(declListPrefix)) {
        *isList = true;
        typeName->truncate(typeName->length() - 1); // get rid of the suffix '>'
        *typeName = typeName->mid(declListPrefix.size());
        erasure(typeName, isList, isPointer);
    }

    *typeName = convertToQmlType(*typeName);
}

void processMetaObject(const QMetaObject *meta, QSet<const QMetaObject *> *metas)
{
    if (! meta || metas->contains(meta))
        return;

    metas->insert(meta);
    processMetaObject(meta->superClass(), metas);
}

void processObject(QObject *object, QSet<const QMetaObject *> *metas)
{
    if (! object)
        return;

    const QMetaObject *meta = object->metaObject();
    processMetaObject(meta, metas);

    for (int index = 0; index < meta->propertyCount(); ++index) {
        QMetaProperty prop = meta->property(index);
        if (QDeclarativeMetaType::isQObject(prop.userType())) {
            QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));
            if (oo && !metas->contains(oo->metaObject()))
                processObject(oo, metas);
        }
    }
}

void processDeclarativeType(const QDeclarativeType *ty, QSet<const QMetaObject *> *metas)
{
    processMetaObject(ty->metaObject(), metas);
}

void writeType(QXmlStreamAttributes *attrs, QByteArray typeName)
{
    bool isList = false, isPointer = false;
    erasure(&typeName, &isList, &isPointer);
    attrs->append(QXmlStreamAttribute("type", typeName));
    if (isList)
        attrs->append(QXmlStreamAttribute("isList", "true"));
}

void dump(const QMetaProperty &prop, QXmlStreamWriter *xml)
{
    xml->writeStartElement("property");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(prop.name())));

    writeType(&attributes, prop.typeName());

    xml->writeAttributes(attributes);
    xml->writeEndElement();
}

void dump(const QMetaMethod &meth, QXmlStreamWriter *xml)
{
    if (meth.methodType() == QMetaMethod::Signal) {
        if (meth.access() != QMetaMethod::Protected)
            return; // nothing to do.
    } else if (meth.access() != QMetaMethod::Public) {
        return; // nothing to do.
    }

    QByteArray name = meth.signature();
    int lparenIndex = name.indexOf('(');
    if (lparenIndex == -1) {
        return; // invalid signature
    }

    name = name.left(lparenIndex);

    QString elementName = QLatin1String("method");

    QXmlStreamAttributes attributes;
    if (meth.methodType() == QMetaMethod::Signal)
        elementName = QLatin1String("signal");

    xml->writeStartElement(elementName);

    attributes.append(QXmlStreamAttribute("name", name));

    const QString typeName = convertToQmlType(meth.typeName());
    if (! typeName.isEmpty())
        attributes.append(QXmlStreamAttribute("type", typeName));

    xml->writeAttributes(attributes);

    for (int i = 0; i < meth.parameterTypes().size(); ++i) {
        QByteArray argName = meth.parameterNames().at(i);

        xml->writeStartElement("param");

        QXmlStreamAttributes attrs;

        if (! argName.isEmpty())
            attrs.append(QXmlStreamAttribute("name", argName));

        writeType(&attrs, meth.parameterTypes().at(i));
        xml->writeAttributes(attrs);

        xml->writeEndElement();
    }

    xml->writeEndElement();
}

void dump(const QMetaEnum &e, QXmlStreamWriter *xml)
{
    xml->writeStartElement("enum");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.name()))); // ### FIXME
    xml->writeAttributes(attributes);

    for (int index = 0; index < e.keyCount(); ++index) {
        xml->writeStartElement("enumerator");

        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", QString::fromUtf8(e.key(index))));
        attributes.append(QXmlStreamAttribute("value", QString::number(e.value(index))));
        xml->writeAttributes(attributes);

        xml->writeEndElement();
    }

    xml->writeEndElement();
}

class FriendlyQObject: public QObject
{
public:
    static const QMetaObject *qtMeta() { return &staticQtMetaObject; }
};

void dump(const QMetaObject *meta, QXmlStreamWriter *xml)
{
    xml->writeStartElement("type");

    QXmlStreamAttributes attributes;
    attributes.append(QXmlStreamAttribute("name", convertToQmlType(meta->className())));

    if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {
        attributes.append(QXmlStreamAttribute("version", QString("%1.%2").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));
    }

    for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {
        QMetaClassInfo classInfo = meta->classInfo(index);
        if (QLatin1String(classInfo.name()) == QLatin1String("DefaultProperty")) {
            attributes.append(QXmlStreamAttribute("defaultProperty", QLatin1String(classInfo.value())));
            break;
        }
    }

    QString version;

    if (meta->superClass())
        attributes.append(QXmlStreamAttribute("extends", convertToQmlType(meta->superClass()->className())));

    if (! version.isEmpty())
        attributes.append(QXmlStreamAttribute("version", version));

    xml->writeAttributes(attributes);

    for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)
        dump(meta->enumerator(index), xml);

    for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)
        dump(meta->property(index), xml);

    for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)
        dump(meta->method(index), xml);

    xml->writeEndElement();
}

void writeScriptElement(QXmlStreamWriter *xml)
{
    xml->writeStartElement("type");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "Script"));
        xml->writeAttributes(attributes);
    }

    xml->writeStartElement("property");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "script"));
        attributes.append(QXmlStreamAttribute("type", "string"));
        xml->writeAttributes(attributes);
    }
    xml->writeEndElement();

    xml->writeStartElement("property");
    {
        QXmlStreamAttributes attributes;
        attributes.append(QXmlStreamAttribute("name", "source"));
        attributes.append(QXmlStreamAttribute("type", "QUrl"));
        xml->writeAttributes(attributes);
    }
    xml->writeEndElement();

    xml->writeEndElement();
}

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QDeclarativeView view;
    QDeclarativeEngine *engine = view.engine();

    {
        QByteArray code;
        code += "import Qt 4.6;\n";
        code += "import Qt.widgets 4.6;\n";
        code += "import Qt.multimedia 1.0;\n";
        code += "import Qt.labs.particles 4.6;\n";
        code += "import org.webkit 1.0;\n";
        code += "Item {}";
        QDeclarativeComponent c(engine);
        c.setData(code, QUrl("xxx"));
        c.create();
    }

    cppToQml.insert("QString", "string");

    QSet<const QMetaObject *> metas;

    metas.insert(FriendlyQObject::qtMeta());

    foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
        cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());
        qmlTypeByCppName.insert(ty->metaObject()->className(), ty);
        processDeclarativeType(ty, &metas);
    }

    foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {
        QByteArray tyName = ty->qmlTypeName();
        tyName = tyName.mid(tyName.lastIndexOf('/') + 1);

        QByteArray code;
        code += "import Qt 4.6;\n";
        code += "import Qt.widgets 4.6;\n";
        code += "import Qt.multimedia 1.0;\n";
        code += "import Qt.labs.particles 4.6;\n";
        code += "import org.webkit 1.0;\n";
        code += tyName;
        code += " {}\n";

        QDeclarativeComponent c(engine);
        c.setData(code, QUrl("xxx"));
        processObject(c.create(), &metas);
    }

    QByteArray bytes;
    QXmlStreamWriter xml(&bytes);
    xml.setAutoFormatting(true);

    xml.writeStartDocument("1.0");
    xml.writeStartElement("module");

    QMap<QString, const QMetaObject *> nameToMeta;
    foreach (const QMetaObject *meta, metas) {
        nameToMeta.insert(convertToQmlType(meta->className()), meta);
    }
    foreach (const QMetaObject *meta, nameToMeta) {
        dump(meta, &xml);
    }

    writeScriptElement(&xml);

    xml.writeEndElement();
    xml.writeEndDocument();

    std::cout << bytes.constData();

    QTimer timer;
    timer.setSingleShot(true);
    timer.setInterval(0);
    QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));

    timer.start();

    return app.exec();
}
<|endoftext|>


<commit_before>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"

template <>
InputParameters
validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  return params;
}

SolidWall::SolidWall(const InputParameters & params) : BoundaryBase(params) {}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects1Phase()
{
  std::vector<unsigned int> bnd_id(1, getBoundaryId());
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<unsigned int>>("r7:boundary") = bnd_id;
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
  }
}

void
SolidWall::addMooseObjects2Phase()
{
  std::vector<unsigned int> bnd_id(1, getBoundaryId());
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
    params.set<std::vector<unsigned int>>("r7:boundary") = bnd_id;
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
  }
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
    params.set<std::vector<unsigned int>>("r7:boundary") = bnd_id;
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
  }
}

void
SolidWall::addMooseObjects()
{
  if (_model_id == RELAP7::FM_SINGLE_PHASE)
    addMooseObjects1Phase();
  else if (_model_id == RELAP7::FM_TWO_PHASE)
    addMooseObjects2Phase();
}
<commit_msg>Removed r7:boundary parameters<commit_after>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"

template <>
InputParameters
validParams<SolidWall>()
{
  InputParameters params = validParams<BoundaryBase>();
  return params;
}

SolidWall::SolidWall(const InputParameters & params) : BoundaryBase(params) {}

void
SolidWall::addVariables()
{
}

void
SolidWall::addMooseObjects1Phase()
{
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
  }
}

void
SolidWall::addMooseObjects2Phase()
{
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
  }
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
  }
}

void
SolidWall::addMooseObjects()
{
  if (_model_id == RELAP7::FM_SINGLE_PHASE)
    addMooseObjects1Phase();
  else if (_model_id == RELAP7::FM_TWO_PHASE)
    addMooseObjects2Phase();
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/surface/mls.h>
#include <pcl/kdtree/kdtree_flann.h>

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
      if (*stop_computing_) std::cout << "Press 's' to start computing!\n"; \
    } \
}while(false)

int default_polynomial_order = 2;
bool default_use_polynomial_fit = false;
double default_search_radius = 0.0,
    default_sqr_gauss_param = 0.0;

template <typename PointType>
class OpenNISmoothing;

void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event,
                            void *stop_void)
{
  boost::shared_ptr<bool> stop = *static_cast<boost::shared_ptr<bool>*> (stop_void);
  if (event.getKeySym () == "s" && event.keyDown ())
  {
    *stop = ! *stop;
    if (*stop) std::cout << "Computing is now stopped!\n";
    else std::cout << "Computing commencing!\n";
  }
}

template <typename PointType>
class OpenNISmoothing
{
  public:
    typedef pcl::PointCloud<PointType> Cloud;
    typedef typename Cloud::Ptr CloudPtr;
    typedef typename Cloud::ConstPtr CloudConstPtr;

    OpenNISmoothing (double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,
                     bool use_polynomial_fit, int polynomial_order,
                     const std::string& device_id = "")
    : viewer ("PCL OpenNI MLS Smoothing")
    , device_id_(device_id)
    {
      smoother_.setSearchRadius (search_radius);
      if (sqr_gauss_param_set) smoother_.setSqrGaussParam (sqr_gauss_param);
      smoother_.setPolynomialFit (use_polynomial_fit);
      smoother_.setPolynomialOrder (polynomial_order);

      typename pcl::search::KdTree<PointType>::Ptr tree (new typename pcl::search::KdTree<PointType> ());
      smoother_.setSearchMethod (tree);
      pcl::PointCloud<pcl::Normal>::Ptr smoother_normals (new pcl::PointCloud<pcl::Normal> ());
      smoother_.setOutputNormals (smoother_normals);

      viewer.createViewPort (0.0, 0.0, 0.5, 1.0, viewport_input_);
      viewer.setBackgroundColor (0, 0, 0, viewport_input_);
      viewer.createViewPort (0.5, 0.0, 1.0, 1.0, viewport_smoothed_);
      viewer.setBackgroundColor (0, 0, 0, viewport_smoothed_);

      stop_computing_.reset (new bool(true));
      cloud_.reset ();
      cloud_smoothed_.reset (new Cloud);
    }

    void
    cloud_cb_ (const CloudConstPtr& cloud)
    {
      FPS_CALC ("computation");

      mtx_.lock ();
      if (! *stop_computing_)
      {
        smoother_.setInputCloud (cloud);
        smoother_.reconstruct (*cloud_smoothed_);
      }
      cloud_ = cloud;
      mtx_.unlock ();
    }

    void
    run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);

      boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNISmoothing::cloud_cb_, this, _1);
      boost::signals2::connection c = interface->registerCallback (f);

      viewer.registerKeyboardCallback (keyboardEventOccurred, (void*) &stop_computing_);

      interface->start ();

      while (!viewer.wasStopped ())
      {
        FPS_CALC ("visualization");
        viewer.spinOnce ();

        if (cloud_ && mtx_.try_lock ())
        {
          if (!viewer.updatePointCloud (cloud_, "input_cloud"))
            viewer.addPointCloud (cloud_, "input_cloud", viewport_input_);
          if (! *stop_computing_ && !viewer.updatePointCloud (cloud_smoothed_, "smoothed_cloud"))
            viewer.addPointCloud (cloud_smoothed_, "smoothed_cloud", viewport_smoothed_);
          mtx_.unlock ();
        }
      }

      interface->stop ();
    }

    pcl::MovingLeastSquares<PointType, pcl::Normal> smoother_;
    pcl::visualization::PCLVisualizer viewer;
    std::string device_id_;
    boost::mutex mtx_;
    CloudConstPtr cloud_;
    CloudPtr cloud_smoothed_;
    int viewport_input_, viewport_smoothed_;
    boost::shared_ptr<bool> stop_computing_;
};

void
usage (char ** argv)
{
  std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n"
            << "where options are:\n"
            << "                     -search_radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: " << default_search_radius << ")\n"
            << "                     -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: " << default_sqr_gauss_param << ")\n"
            << "                     -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: " << default_use_polynomial_fit << ")\n"
            << "                     -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: " << default_polynomial_order << ")\n";

  openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
  if (driver.getNumberDevices () > 0)
  {
    for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
    {
      cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
      cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
           << "                 bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl
           << "                 <serial-number> (only in Linux and for devices which provide serial numbers)"  << endl;
    }
  }
  else
    cout << "No devices connected." << endl;
}

int
main (int argc, char ** argv)
{
  if (argc < 2)
  {
    usage (argv);
    return 1;
  }

  std::string arg (argv[1]);

  if (arg == "--help" || arg == "-h")
  {
    usage (argv);
    return 1;
  }

  // Command line parsing
  double search_radius = default_search_radius;
  double sqr_gauss_param = default_sqr_gauss_param;
  bool sqr_gauss_param_set = true;
  int polynomial_order = default_polynomial_order;
  bool use_polynomial_fit = default_use_polynomial_fit;

  pcl::console::parse_argument (argc, argv, "-search_radius", search_radius);
  if (pcl::console::parse_argument (argc, argv, "-sqr_gauss_param", sqr_gauss_param) == -1)
    sqr_gauss_param_set = false;
  if (pcl::console::parse_argument (argc, argv, "-polynomial_order", polynomial_order) == -1 )
    use_polynomial_fit = true;
  pcl::console::parse_argument (argc, argv, "-use_polynomial_fit", use_polynomial_fit);

  pcl::OpenNIGrabber grabber (arg);
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
  {
    OpenNISmoothing<pcl::PointXYZRGB> v (search_radius, sqr_gauss_param, sqr_gauss_param_set,
                                         use_polynomial_fit, polynomial_order, arg);
    v.run ();
  }
  else
  {
    OpenNISmoothing<pcl::PointXYZ> v (search_radius, sqr_gauss_param, sqr_gauss_param_set,
                                      use_polynomial_fit, polynomial_order, arg);
    v.run ();
  }

  return (0);
}
<commit_msg>testing MovingLeastSquaresOMP on 4 cores<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2011, Willow Garage, Inc.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 *
 */

#include <boost/thread/thread.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/visualization/cloud_viewer.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/surface/mls_omp.h>
#include <pcl/kdtree/kdtree_flann.h>

#define FPS_CALC(_WHAT_) \
do \
{ \
    static unsigned count = 0;\
    static double last = pcl::getTime ();\
    double now = pcl::getTime (); \
    ++count; \
    if (now - last >= 1.0) \
    { \
      std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" <<  std::endl; \
      count = 0; \
      last = now; \
      if (*stop_computing_) std::cout << "Press 's' to start computing!\n"; \
    } \
}while(false)

int default_polynomial_order = 2;
bool default_use_polynomial_fit = false;
double default_search_radius = 0.0,
    default_sqr_gauss_param = 0.0;

template <typename PointType>
class OpenNISmoothing;

void keyboardEventOccurred (const pcl::visualization::KeyboardEvent &event,
                            void *stop_void)
{
  boost::shared_ptr<bool> stop = *static_cast<boost::shared_ptr<bool>*> (stop_void);
  if (event.getKeySym () == "s" && event.keyDown ())
  {
    *stop = ! *stop;
    if (*stop) std::cout << "Computing is now stopped!\n";
    else std::cout << "Computing commencing!\n";
  }
}

template <typename PointType>
class OpenNISmoothing
{
  public:
    typedef pcl::PointCloud<PointType> Cloud;
    typedef typename Cloud::Ptr CloudPtr;
    typedef typename Cloud::ConstPtr CloudConstPtr;

    OpenNISmoothing (double search_radius, bool sqr_gauss_param_set, double sqr_gauss_param,
                     bool use_polynomial_fit, int polynomial_order,
                     const std::string& device_id = "")
    : viewer ("PCL OpenNI MLS Smoothing")
    , device_id_(device_id)
    {
      // Start 4 threads
      smoother_.setNumberOfThreads (4);
      smoother_.setSearchRadius (search_radius);
      if (sqr_gauss_param_set) smoother_.setSqrGaussParam (sqr_gauss_param);
      smoother_.setPolynomialFit (use_polynomial_fit);
      smoother_.setPolynomialOrder (polynomial_order);

      typename pcl::search::KdTree<PointType>::Ptr tree (new typename pcl::search::KdTree<PointType> ());
      smoother_.setSearchMethod (tree);
      pcl::PointCloud<pcl::Normal>::Ptr smoother_normals (new pcl::PointCloud<pcl::Normal> ());
      smoother_.setOutputNormals (smoother_normals);

      viewer.createViewPort (0.0, 0.0, 0.5, 1.0, viewport_input_);
      viewer.setBackgroundColor (0, 0, 0, viewport_input_);
      viewer.createViewPort (0.5, 0.0, 1.0, 1.0, viewport_smoothed_);
      viewer.setBackgroundColor (0, 0, 0, viewport_smoothed_);

      stop_computing_.reset (new bool(true));
      cloud_.reset ();
      cloud_smoothed_.reset (new Cloud);
    }

    void
    cloud_cb_ (const CloudConstPtr& cloud)
    {
      FPS_CALC ("computation");

      mtx_.lock ();
      if (! *stop_computing_)
      {
        smoother_.setInputCloud (cloud);
        smoother_.reconstruct (*cloud_smoothed_);
      }
      cloud_ = cloud;
      mtx_.unlock ();
    }

    void
    run ()
    {
      pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);

      boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNISmoothing::cloud_cb_, this, _1);
      boost::signals2::connection c = interface->registerCallback (f);

      viewer.registerKeyboardCallback (keyboardEventOccurred, (void*) &stop_computing_);

      interface->start ();

      while (!viewer.wasStopped ())
      {
        FPS_CALC ("visualization");
        viewer.spinOnce ();

        if (cloud_ && mtx_.try_lock ())
        {
          if (!viewer.updatePointCloud (cloud_, "input_cloud"))
            viewer.addPointCloud (cloud_, "input_cloud", viewport_input_);
          if (! *stop_computing_ && !viewer.updatePointCloud (cloud_smoothed_, "smoothed_cloud"))
            viewer.addPointCloud (cloud_smoothed_, "smoothed_cloud", viewport_smoothed_);
          mtx_.unlock ();
        }
      }

      interface->stop ();
    }

    pcl::MovingLeastSquaresOMP<PointType, pcl::Normal> smoother_;
    pcl::visualization::PCLVisualizer viewer;
    std::string device_id_;
    boost::mutex mtx_;
    CloudConstPtr cloud_;
    CloudPtr cloud_smoothed_;
    int viewport_input_, viewport_smoothed_;
    boost::shared_ptr<bool> stop_computing_;
};

void
usage (char ** argv)
{
  std::cout << "usage: " << argv[0] << " <device_id> <options>\n\n"
            << "where options are:\n"
            << "                     -search_radius X = sphere radius to be used for finding the k-nearest neighbors used for fitting (default: " << default_search_radius << ")\n"
            << "                     -sqr_gauss_param X = parameter used for the distance based weighting of neighbors (recommended = search_radius^2) (default: " << default_sqr_gauss_param << ")\n"
            << "                     -use_polynomial_fit X = decides whether the surface and normal are approximated using a polynomial or only via tangent estimation (default: " << default_use_polynomial_fit << ")\n"
            << "                     -polynomial_order X = order of the polynomial to be fit (implicitly, use_polynomial_fit = 1) (default: " << default_polynomial_order << ")\n";

  openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
  if (driver.getNumberDevices () > 0)
  {
    for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
    {
      cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
              << ", connected: " << (int)driver.getBus (deviceIdx) << " @ " << (int)driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
      cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
           << "                 bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl
           << "                 <serial-number> (only in Linux and for devices which provide serial numbers)"  << endl;
    }
  }
  else
    cout << "No devices connected." << endl;
}

int
main (int argc, char ** argv)
{
  if (argc < 2)
  {
    usage (argv);
    return 1;
  }

  std::string arg (argv[1]);

  if (arg == "--help" || arg == "-h")
  {
    usage (argv);
    return 1;
  }

  // Command line parsing
  double search_radius = default_search_radius;
  double sqr_gauss_param = default_sqr_gauss_param;
  bool sqr_gauss_param_set = true;
  int polynomial_order = default_polynomial_order;
  bool use_polynomial_fit = default_use_polynomial_fit;

  pcl::console::parse_argument (argc, argv, "-search_radius", search_radius);
  if (pcl::console::parse_argument (argc, argv, "-sqr_gauss_param", sqr_gauss_param) == -1)
    sqr_gauss_param_set = false;
  if (pcl::console::parse_argument (argc, argv, "-polynomial_order", polynomial_order) == -1 )
    use_polynomial_fit = true;
  pcl::console::parse_argument (argc, argv, "-use_polynomial_fit", use_polynomial_fit);

  pcl::OpenNIGrabber grabber (arg);
  if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgb> ())
  {
    OpenNISmoothing<pcl::PointXYZRGB> v (search_radius, sqr_gauss_param, sqr_gauss_param_set,
                                         use_polynomial_fit, polynomial_order, arg);
    v.run ();
  }
  else
  {
    OpenNISmoothing<pcl::PointXYZ> v (search_radius, sqr_gauss_param, sqr_gauss_param_set,
                                      use_polynomial_fit, polynomial_order, arg);
    v.run ();
  }

  return (0);
}
<|endoftext|>