<commit_before>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate unreachable internal globals from the
// program.  It uses an aggressive algorithm, searching out globals that are
// known to be alive.  After it finds all of the globals which are needed, it
// deletes whatever is left over.  This allows it to delete recursive chunks of
// the program which are unreachable.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "globaldce"
#include "llvm/Transforms/IPO.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include <set>
using namespace llvm;

STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");

namespace {
  struct VISIBILITY_HIDDEN GlobalDCE : public ModulePass {
    static char ID; // Pass identification, replacement for typeid
    GlobalDCE() : ModulePass(&ID) {}

    // run - Do the GlobalDCE pass on the specified module, optionally updating
    // the specified callgraph to reflect the changes.
    //
    bool runOnModule(Module &M);

  private:
    std::set<GlobalValue*> AliveGlobals;

    /// MarkGlobalIsNeeded - the specific global value as needed, and
    /// recursively mark anything that it uses as also needed.
    void GlobalIsNeeded(GlobalValue *GV);
    void MarkUsedGlobalsAsNeeded(Constant *C);

    bool SafeToDestroyConstant(Constant* C);
    bool RemoveUnusedGlobalValue(GlobalValue &GV);
  };
}

char GlobalDCE::ID = 0;
static RegisterPass<GlobalDCE> X("globaldce", "Dead Global Elimination");

ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }

bool GlobalDCE::runOnModule(Module &M) {
  bool Changed = false;
  // Loop over the module, adding globals which are obviously necessary.
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
    Changed |= RemoveUnusedGlobalValue(*I);
    // Functions with external linkage are needed if they have a body
    if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&
        !I->isDeclaration())
      GlobalIsNeeded(I);
  }

  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
       I != E; ++I) {
    Changed |= RemoveUnusedGlobalValue(*I);
    // Externally visible & appending globals are needed, if they have an
    // initializer.
    if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&
        !I->isDeclaration())
      GlobalIsNeeded(I);
  }

  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
       I != E; ++I) {
    // Aliases are always needed even if they are not used.
    MarkUsedGlobalsAsNeeded(I->getAliasee());
  }

  // Now that all globals which are needed are in the AliveGlobals set, we loop
  // through the program, deleting those which are not alive.
  //

  // The first pass is to drop initializers of global variables which are dead.
  std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    if (!AliveGlobals.count(I)) {
      DeadGlobalVars.push_back(I);         // Keep track of dead globals
      I->setInitializer(0);
    }

  // The second pass drops the bodies of functions which are dead...
  std::vector<Function*> DeadFunctions;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    if (!AliveGlobals.count(I)) {
      DeadFunctions.push_back(I);         // Keep track of dead globals
      if (!I->isDeclaration())
        I->deleteBody();
    }

  if (!DeadFunctions.empty()) {
    // Now that all interreferences have been dropped, delete the actual objects
    // themselves.
    for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
      RemoveUnusedGlobalValue(*DeadFunctions[i]);
      M.getFunctionList().erase(DeadFunctions[i]);
    }
    NumFunctions += DeadFunctions.size();
    Changed = true;
  }

  if (!DeadGlobalVars.empty()) {
    for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
      RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
      M.getGlobalList().erase(DeadGlobalVars[i]);
    }
    NumVariables += DeadGlobalVars.size();
    Changed = true;
  }

  // Make sure that all memory is released
  AliveGlobals.clear();
  return Changed;
}

/// MarkGlobalIsNeeded - the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
  std::set<GlobalValue*>::iterator I = AliveGlobals.find(G);

  // If the global is already in the set, no need to reprocess it.
  if (I != AliveGlobals.end()) return;

  // Otherwise insert it now, so we do not infinitely recurse
  AliveGlobals.insert(I, G);

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
    // If this is a global variable, we must make sure to add any global values
    // referenced by the initializer to the alive set.
    if (GV->hasInitializer())
      MarkUsedGlobalsAsNeeded(GV->getInitializer());
  } else if (!isa<GlobalAlias>(G)) {
    // Otherwise this must be a function object.  We have to scan the body of
    // the function looking for constants and global values which are used as
    // operands.  Any operands of these types must be processed to ensure that
    // any globals used will be marked as needed.
    Function *F = cast<Function>(G);
    // For all basic blocks...
    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
      // For all instructions...
      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
        // For all operands...
        for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
          if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
            GlobalIsNeeded(GV);
          else if (Constant *C = dyn_cast<Constant>(*U))
            MarkUsedGlobalsAsNeeded(C);
  }
}

void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
  if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
    GlobalIsNeeded(GV);
  else {
    // Loop over all of the operands of the constant, adding any globals they
    // use to the list of needed globals.
    for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I)
      MarkUsedGlobalsAsNeeded(cast<Constant>(*I));
  }
}

// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it.  This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
  if (GV.use_empty()) return false;
  GV.removeDeadConstantUsers();
  return GV.use_empty();
}

// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
// by constants itself.  Note that constants cannot be cyclic, so this test is
// pretty easy to implement recursively.
//
bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
  for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
    if (Constant *User = dyn_cast<Constant>(*I)) {
      if (!SafeToDestroyConstant(User)) return false;
    } else {
      return false;
    }
  return true;
}
<commit_msg>Use actual function name in comments.<commit_after>//===-- GlobalDCE.cpp - DCE unreachable internal functions ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This transform is designed to eliminate unreachable internal globals from the
// program.  It uses an aggressive algorithm, searching out globals that are
// known to be alive.  After it finds all of the globals which are needed, it
// deletes whatever is left over.  This allows it to delete recursive chunks of
// the program which are unreachable.
//
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "globaldce"
#include "llvm/Transforms/IPO.h"
#include "llvm/Constants.h"
#include "llvm/Module.h"
#include "llvm/Pass.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Support/Compiler.h"
#include <set>
using namespace llvm;

STATISTIC(NumFunctions, "Number of functions removed");
STATISTIC(NumVariables, "Number of global variables removed");

namespace {
  struct VISIBILITY_HIDDEN GlobalDCE : public ModulePass {
    static char ID; // Pass identification, replacement for typeid
    GlobalDCE() : ModulePass(&ID) {}

    // run - Do the GlobalDCE pass on the specified module, optionally updating
    // the specified callgraph to reflect the changes.
    //
    bool runOnModule(Module &M);

  private:
    std::set<GlobalValue*> AliveGlobals;

    /// GlobalIsNeeded - the specific global value as needed, and
    /// recursively mark anything that it uses as also needed.
    void GlobalIsNeeded(GlobalValue *GV);
    void MarkUsedGlobalsAsNeeded(Constant *C);

    bool SafeToDestroyConstant(Constant* C);
    bool RemoveUnusedGlobalValue(GlobalValue &GV);
  };
}

char GlobalDCE::ID = 0;
static RegisterPass<GlobalDCE> X("globaldce", "Dead Global Elimination");

ModulePass *llvm::createGlobalDCEPass() { return new GlobalDCE(); }

bool GlobalDCE::runOnModule(Module &M) {
  bool Changed = false;
  // Loop over the module, adding globals which are obviously necessary.
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I) {
    Changed |= RemoveUnusedGlobalValue(*I);
    // Functions with external linkage are needed if they have a body
    if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&
        !I->isDeclaration())
      GlobalIsNeeded(I);
  }

  for (Module::global_iterator I = M.global_begin(), E = M.global_end();
       I != E; ++I) {
    Changed |= RemoveUnusedGlobalValue(*I);
    // Externally visible & appending globals are needed, if they have an
    // initializer.
    if ((!I->hasInternalLinkage() && !I->hasLinkOnceLinkage()) &&
        !I->isDeclaration())
      GlobalIsNeeded(I);
  }

  for (Module::alias_iterator I = M.alias_begin(), E = M.alias_end();
       I != E; ++I) {
    // Aliases are always needed even if they are not used.
    MarkUsedGlobalsAsNeeded(I->getAliasee());
  }

  // Now that all globals which are needed are in the AliveGlobals set, we loop
  // through the program, deleting those which are not alive.
  //

  // The first pass is to drop initializers of global variables which are dead.
  std::vector<GlobalVariable*> DeadGlobalVars;   // Keep track of dead globals
  for (Module::global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I)
    if (!AliveGlobals.count(I)) {
      DeadGlobalVars.push_back(I);         // Keep track of dead globals
      I->setInitializer(0);
    }

  // The second pass drops the bodies of functions which are dead...
  std::vector<Function*> DeadFunctions;
  for (Module::iterator I = M.begin(), E = M.end(); I != E; ++I)
    if (!AliveGlobals.count(I)) {
      DeadFunctions.push_back(I);         // Keep track of dead globals
      if (!I->isDeclaration())
        I->deleteBody();
    }

  if (!DeadFunctions.empty()) {
    // Now that all interreferences have been dropped, delete the actual objects
    // themselves.
    for (unsigned i = 0, e = DeadFunctions.size(); i != e; ++i) {
      RemoveUnusedGlobalValue(*DeadFunctions[i]);
      M.getFunctionList().erase(DeadFunctions[i]);
    }
    NumFunctions += DeadFunctions.size();
    Changed = true;
  }

  if (!DeadGlobalVars.empty()) {
    for (unsigned i = 0, e = DeadGlobalVars.size(); i != e; ++i) {
      RemoveUnusedGlobalValue(*DeadGlobalVars[i]);
      M.getGlobalList().erase(DeadGlobalVars[i]);
    }
    NumVariables += DeadGlobalVars.size();
    Changed = true;
  }

  // Make sure that all memory is released
  AliveGlobals.clear();
  return Changed;
}

/// GlobalIsNeeded - the specific global value as needed, and
/// recursively mark anything that it uses as also needed.
void GlobalDCE::GlobalIsNeeded(GlobalValue *G) {
  std::set<GlobalValue*>::iterator I = AliveGlobals.find(G);

  // If the global is already in the set, no need to reprocess it.
  if (I != AliveGlobals.end()) return;

  // Otherwise insert it now, so we do not infinitely recurse
  AliveGlobals.insert(I, G);

  if (GlobalVariable *GV = dyn_cast<GlobalVariable>(G)) {
    // If this is a global variable, we must make sure to add any global values
    // referenced by the initializer to the alive set.
    if (GV->hasInitializer())
      MarkUsedGlobalsAsNeeded(GV->getInitializer());
  } else if (!isa<GlobalAlias>(G)) {
    // Otherwise this must be a function object.  We have to scan the body of
    // the function looking for constants and global values which are used as
    // operands.  Any operands of these types must be processed to ensure that
    // any globals used will be marked as needed.
    Function *F = cast<Function>(G);
    // For all basic blocks...
    for (Function::iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
      // For all instructions...
      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
        // For all operands...
        for (User::op_iterator U = I->op_begin(), E = I->op_end(); U != E; ++U)
          if (GlobalValue *GV = dyn_cast<GlobalValue>(*U))
            GlobalIsNeeded(GV);
          else if (Constant *C = dyn_cast<Constant>(*U))
            MarkUsedGlobalsAsNeeded(C);
  }
}

void GlobalDCE::MarkUsedGlobalsAsNeeded(Constant *C) {
  if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
    GlobalIsNeeded(GV);
  else {
    // Loop over all of the operands of the constant, adding any globals they
    // use to the list of needed globals.
    for (User::op_iterator I = C->op_begin(), E = C->op_end(); I != E; ++I)
      MarkUsedGlobalsAsNeeded(cast<Constant>(*I));
  }
}

// RemoveUnusedGlobalValue - Loop over all of the uses of the specified
// GlobalValue, looking for the constant pointer ref that may be pointing to it.
// If found, check to see if the constant pointer ref is safe to destroy, and if
// so, nuke it.  This will reduce the reference count on the global value, which
// might make it deader.
//
bool GlobalDCE::RemoveUnusedGlobalValue(GlobalValue &GV) {
  if (GV.use_empty()) return false;
  GV.removeDeadConstantUsers();
  return GV.use_empty();
}

// SafeToDestroyConstant - It is safe to destroy a constant iff it is only used
// by constants itself.  Note that constants cannot be cyclic, so this test is
// pretty easy to implement recursively.
//
bool GlobalDCE::SafeToDestroyConstant(Constant *C) {
  for (Value::use_iterator I = C->use_begin(), E = C->use_end(); I != E; ++I)
    if (Constant *User = dyn_cast<Constant>(*I)) {
      if (!SafeToDestroyConstant(User)) return false;
    } else {
      return false;
    }
  return true;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief console input using linenoise
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "LinenoiseShell.h"

extern "C" {
#include <linenoise.h>
}

#include "Utilities/Completer.h"
#include "Utilities/LineEditor.h"

using namespace std;
using namespace arangodb;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief active completer
////////////////////////////////////////////////////////////////////////////////

static Completer* COMPLETER = nullptr;

////////////////////////////////////////////////////////////////////////////////
/// @brief completer generator
////////////////////////////////////////////////////////////////////////////////

static void LinenoiseCompletionGenerator (char const* text,
                                          linenoiseCompletions* lc) {
  if (COMPLETER) {
    std::vector<string> alternatives = COMPLETER->alternatives(text);
    ShellBase::sortAlternatives(alternatives);

    for (auto& it : alternatives) {
      linenoiseAddCompletion(lc, it.c_str());
    }
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                              class LinenoiseShell
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

LinenoiseShell::LinenoiseShell (std::string const& history,
                                Completer* completer)
  : ShellBase(history, completer) {
  COMPLETER = completer;
  linenoiseSetMultiLine(1);
  linenoiseSetCompletionCallback(LinenoiseCompletionGenerator);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

LinenoiseShell::~LinenoiseShell() {
  COMPLETER = nullptr;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::open (bool) {
  linenoiseHistoryLoad(_historyFilename.c_str());
  _state = STATE_OPENED;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::close () {

  // avoid duplicate saving of history
  if (_state != STATE_OPENED) {
    return true;
  }

  _state = STATE_CLOSED;
  return writeHistory();
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void LinenoiseShell::addHistory (std::string const& str) {
  if (str.empty()) {
    return;
  }

  linenoiseHistoryAdd(str.c_str());
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::writeHistory () {
  linenoiseHistorySave(_historyFilename.c_str());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

std::string LinenoiseShell::getLine (std::string const& prompt, bool& eof) {
  char* line = linenoise(prompt.c_str());

  if (line != nullptr) {
    eof = false;
    std::string const stringValue(line);
    ::free(line);
    return stringValue;
  }

  eof = true;
  return "";
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------
<commit_msg>yawe: yet another windows exception<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief console input using linenoise
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2014 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2014, ArangoDB GmbH, Cologne, Germany
/// @author Copyright 2011-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "LinenoiseShell.h"

extern "C" {
#include <linenoise.h>
}

#include "Utilities/Completer.h"
#include "Utilities/LineEditor.h"

using namespace std;
using namespace arangodb;

// -----------------------------------------------------------------------------
// --SECTION--                                                 private functions
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief active completer
////////////////////////////////////////////////////////////////////////////////

static Completer* COMPLETER = nullptr;

////////////////////////////////////////////////////////////////////////////////
/// @brief completer generator
////////////////////////////////////////////////////////////////////////////////

static void LinenoiseCompletionGenerator (char const* text,
                                          linenoiseCompletions* lc) {
  if (COMPLETER) {
    std::vector<string> alternatives = COMPLETER->alternatives(text);
    ShellBase::sortAlternatives(alternatives);

    for (auto& it : alternatives) {
      linenoiseAddCompletion(lc, it.c_str());
    }
  }
}

// -----------------------------------------------------------------------------
// --SECTION--                                              class LinenoiseShell
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// --SECTION--                                      constructors and destructors
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// @brief constructor
////////////////////////////////////////////////////////////////////////////////

LinenoiseShell::LinenoiseShell (std::string const& history,
                                Completer* completer)
  : ShellBase(history, completer) {
  COMPLETER = completer;
#ifndef _WIN32
  linenoiseSetMultiLine(1);
#endif
  linenoiseSetCompletionCallback(LinenoiseCompletionGenerator);
}

////////////////////////////////////////////////////////////////////////////////
/// @brief destructor
////////////////////////////////////////////////////////////////////////////////

LinenoiseShell::~LinenoiseShell() {
  COMPLETER = nullptr;
}

// -----------------------------------------------------------------------------
// --SECTION--                                                    public methods
// -----------------------------------------------------------------------------

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::open (bool) {
  linenoiseHistoryLoad(_historyFilename.c_str());
  _state = STATE_OPENED;
  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::close () {

  // avoid duplicate saving of history
  if (_state != STATE_OPENED) {
    return true;
  }

  _state = STATE_CLOSED;
  return writeHistory();
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

void LinenoiseShell::addHistory (std::string const& str) {
  if (str.empty()) {
    return;
  }

  linenoiseHistoryAdd(str.c_str());
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

bool LinenoiseShell::writeHistory () {
  linenoiseHistorySave(_historyFilename.c_str());

  return true;
}

////////////////////////////////////////////////////////////////////////////////
/// {@inheritDoc}
////////////////////////////////////////////////////////////////////////////////

std::string LinenoiseShell::getLine (std::string const& prompt, bool& eof) {
  char* line = linenoise(prompt.c_str());

  if (line != nullptr) {
    eof = false;
    std::string const stringValue(line);
    ::free(line);
    return stringValue;
  }

  eof = true;
  return "";
}

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before><commit_msg>Missing GL_PROGRAM_POINT_SIZE in Contex.enable / disable<commit_after><|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkPickingManager.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

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

  Library: MSVTK

  Copyright (c) Kitware 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.txt

  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.

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

// VTK includes
#include "vtkAbstractPicker.h"
#include "vtkAbstractPropPicker.h"
#include "vtkCamera.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPickingManager.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTimeStamp.h"

// STL includes
#include <algorithm>
#include <limits>
#include <map>
#include <vector>

//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkPickingManager);

//------------------------------------------------------------------------------
class vtkPickingManager::vtkInternal
{
public:
  vtkInternal(vtkPickingManager* external);
  ~vtkInternal();

  // Callback used to update the current time
  // of the manager when an event occurs in the RenderWindowInteractor.
  // Time is used to know if the cached information is still valid or obsolete.
  static void UpdateTime(vtkObject *caller,
                         unsigned long event,
                         void *clientData,
                         void *callData);

  // Select the best picker based on various criterias such as z-depth,
  // 2D overlay and/or distance to picked point.
  vtkAbstractPicker* SelectPicker();

  // Compute the selection. The current implementation use the distance
  // between the world coordinates of a pick to the camera's ones.
  vtkAbstractPicker* ComputePickerSelection(double X, double Y, double Z,
                                            vtkRenderer* renderer);

  // Check if a given Observator is associated with a given Picker
  bool IsObjectLinked(vtkAbstractPicker* picker, vtkObject* object);

  // Create a new list of associated observers
  void CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object);

  // Instead of a vtkCollection we are using a vector of a vtkSmartPointer
  // containing vtkObject to allow using 0 as a valid value because it is
  // allowed the return a picker event if he is not associated to a specific
  // object.
  // This is related with the capacity when a picker associated with a given
  // object does not manage others object,
  // it will automatically be removed from the list as well.
  typedef std::vector<vtkSmartPointer<vtkObject> > CollectionType;

  // For code clearance and performances during the computation std::map is
  // used instead of a vector of pair. Nevertheless, it makes internally use of
  // vtkSmartPointer and this class does not overload the order operators;
  // therefore to following functor has to be implemented to keep the data
  // structure consistent.
  struct less_smartPtrPicker
  {
    bool operator () (const vtkSmartPointer<vtkAbstractPicker>& first,
                      const vtkSmartPointer<vtkAbstractPicker>& second) const
      {
      return first.GetPointer() < second.GetPointer();
      }
  };

  typedef std::map<vtkSmartPointer<vtkAbstractPicker>,
                   CollectionType, less_smartPtrPicker > PickerObjectsType;

  typedef std::pair<vtkSmartPointer<vtkAbstractPicker>,
                    CollectionType> PickerObjectsPairType;

  // Associate a given vtkObject to a particular picker.
  void LinkPickerObject(const PickerObjectsType::iterator& it,
                        vtkObject* object);

  // Predicate comparing a vtkAbstractPicker*
  // and a vtkSmartPointer<vtkAbstractPicker> using the PickerObjectsType.
  // As we use a vtkSmartPointer, this predicate allows to compare the equality
  // of a pointer on a vtkAbstractPicker with the adress contained in
  // a corresponding vtkSmartPointer.
  struct equal_smartPtrPicker
  {
    equal_smartPtrPicker(vtkAbstractPicker* picker) : Picker(picker) {}

    bool operator () (const PickerObjectsPairType& pickerObjs) const
      {
      return this->Picker == pickerObjs.first.GetPointer();
      }

    vtkAbstractPicker* Picker;
  };

  // Predicate comparing a vtkObject*
  // and a vtkSmartPointer<vtkObject> using the PickerObjectsType.
  // As we use a vtkSmartPointer, this predicate allows to compare the equality
  // of a pointer on a vtkObject with the adress contained in
  // a corresponding vtkSmartPointer.
  struct equal_smartPtrObject
  {
    equal_smartPtrObject(vtkObject* object) : Object(object) {}

    bool operator () (const vtkSmartPointer<vtkObject>& smartObj) const
      {
      return this->Object == smartObj.GetPointer();
      }

    vtkObject* Object;
  };

  PickerObjectsType Pickers;           // Map the picker with the objects
  vtkTimeStamp CurrentInteractionTime; // Time of the last interaction event
  vtkTimeStamp LastPickingTime;        // Time of the last picking process
  vtkSmartPointer<vtkAbstractPicker> LastSelectedPicker;

  // Define callback to keep track of the CurrentTime and the LastPickingTime.
  // The timeStamp is use to avoid repeating the picking process if the
  // vtkWindowInteractor has not been modified, it is a huge optimization
  // avoiding each picker to relaunch the whole mechanisme to determine which
  // picker has been selected at a state of the rendering.
  vtkSmartPointer<vtkCallbackCommand> TimerCallback;

  vtkPickingManager*  External;
};

//------------------------------------------------------------------------------
// vtkInternal methods

//------------------------------------------------------------------------------
vtkPickingManager::vtkInternal::vtkInternal(vtkPickingManager* external)
{
  this->External = external;

  this->TimerCallback = vtkSmartPointer<vtkCallbackCommand>::New();
  this->TimerCallback->SetClientData(this);
  this->TimerCallback->SetCallback(UpdateTime);

}

//------------------------------------------------------------------------------
vtkPickingManager::vtkInternal::~vtkInternal()
{}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::
CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object)
{
  CollectionType objects;
  objects.push_back(object);

  this->Pickers.insert(PickerObjectsPairType(picker, objects));
}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::
LinkPickerObject(const PickerObjectsType::iterator& it, vtkObject* object)
{
  CollectionType::iterator itObj = std::find_if(it->second.begin(),
                                                it->second.end(),
                                                equal_smartPtrObject(object));

  if (itObj != it->second.end() && object)
    {
    vtkDebugWithObjectMacro(
      this->External, "vtkPickingtManager::Internal::LinkPickerObject: "
      << "Current object already linked with the given picker.");

    return;
    }

  it->second.push_back(object);
}

//------------------------------------------------------------------------------
bool vtkPickingManager::vtkInternal::
IsObjectLinked(vtkAbstractPicker* picker, vtkObject* obj)
{
  if(!picker || !obj)
    {
    return false;
    }

  PickerObjectsType::iterator itPick = std::find_if(
    this->Pickers.begin(), this->Pickers.end(), equal_smartPtrPicker(picker));
  if(itPick == this->Pickers.end())
    {
    return false;
    }

  CollectionType::iterator itObj = std::find_if(itPick->second.begin(),
                                                itPick->second.end(),
                                                equal_smartPtrObject(obj));
  return (itObj != itPick->second.end());
}

//------------------------------------------------------------------------------
vtkAbstractPicker* vtkPickingManager::vtkInternal::SelectPicker()
{
  if (!this->External->Interactor)
    {
    return 0;
    }
  else if (this->External->GetOptimizeOnInteractorEvents() &&
           this->CurrentInteractionTime.GetMTime() == this->LastPickingTime)
    {
    return this->LastSelectedPicker;
    }

  // Get the event position
  double X = this->External->Interactor->GetEventPosition()[0];
  double Y = this->External->Interactor->GetEventPosition()[1];

  // Get the poked renderer
  vtkRenderer* renderer = this->External->Interactor->FindPokedRenderer(X, Y);
  vtkAbstractPicker* selectedPicker =
    this->ComputePickerSelection(X, Y, 0., renderer);

  // Keep track of the lastet picker choosen & last picking time.
  this->LastSelectedPicker = selectedPicker;
  this->LastPickingTime = this->CurrentInteractionTime;

  return selectedPicker;
}

//------------------------------------------------------------------------------
vtkAbstractPicker* vtkPickingManager::vtkInternal::
ComputePickerSelection(double X, double Y, double Z, vtkRenderer* renderer)
{
  vtkAbstractPicker* closestPicker = 0;
  if (!renderer)
    {
    return closestPicker;
    }

  double* camPos = renderer->GetActiveCamera()->GetPosition();
  double smallestDistance2 = std::numeric_limits<double>::max();

  for(PickerObjectsType::iterator it = this->Pickers.begin();
      it != this->Pickers.end(); ++it)
    {
    int pickResult = it->first->Pick(X, Y, Z, renderer);
    double* pPos = it->first->GetPickPosition();

    if(pickResult > 0) // Keep closest object picked.
      {
      double distance2 = vtkMath::Distance2BetweenPoints(camPos, pPos);

      if(smallestDistance2 > distance2)
        {
        smallestDistance2 = distance2;
        closestPicker = it->first;
        }
      }
    }

  return closestPicker;
}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::UpdateTime(vtkObject *vtkNotUsed(caller),
                                                unsigned long vtkNotUsed(event),
                                                void *clientData,
                                                void *vtkNotUsed(calldata))
{
  vtkPickingManager::vtkInternal* self =
    reinterpret_cast<vtkPickingManager::vtkInternal*>(clientData);
  if (!self)
    {
    return;
    }

  self->CurrentInteractionTime.Modified();
}

//------------------------------------------------------------------------------
// vtkPickingManager methods

//------------------------------------------------------------------------------
vtkPickingManager::vtkPickingManager()
  : Interactor(0)
  , Enabled(false)
  , OptimizeOnInteractorEvents(true)
  , Internal(0)
{
  this->Internal = new vtkInternal(this);
}

//------------------------------------------------------------------------------
vtkPickingManager::~vtkPickingManager()
{
  this->SetInteractor(0);
  delete this->Internal;
}

//------------------------------------------------------------------------------
void vtkPickingManager::SetInteractor(vtkRenderWindowInteractor* rwi)
{
  if (rwi == this->Interactor)
    {
    return;
    }
  if (this->Interactor)
    {
    this->Interactor->RemoveObserver(this->Internal->TimerCallback);
    }

  this->Interactor = rwi;
  if (this->Interactor)
    {
    this->Interactor->AddObserver(
      vtkCommand::ModifiedEvent, this->Internal->TimerCallback);
    }

  this->Modified();
}

//------------------------------------------------------------------------------
void vtkPickingManager::SetOptimizeOnInteractorEvents(bool optimize)
{
  if (this->OptimizeOnInteractorEvents == optimize)
    {
    return;
    }

  this->OptimizeOnInteractorEvents = optimize;
  this->Modified();
}

//------------------------------------------------------------------------------
void vtkPickingManager::AddPicker(vtkAbstractPicker* picker,
                                  vtkObject* object)
{
  if (!picker)
    {
    return;
    }

  // Linke the object if the picker is already registered
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  if (it != this->Internal->Pickers.end() )
    {
    vtkDebugMacro("vtkPickingtManager::AddPicker: "
      << "Picker already in the manager, the object will be linked");

    this->Internal->LinkPickerObject(it, object);
    return;
    }

  // The picker does not exists in the manager yet.
  // Create the list of associated objects
  this->Internal->CreateDefaultCollection(picker, object);
}

//------------------------------------------------------------------------------
void vtkPickingManager::RemovePicker(vtkAbstractPicker* picker,
                                     vtkObject* object)
{
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  // The Picker does not exist
  if (it == this->Internal->Pickers.end())
    {
    return;
    }

  vtkPickingManager::vtkInternal::CollectionType::iterator itObj =
    std::find_if(it->second.begin(),
                 it->second.end(),
                 vtkPickingManager::vtkInternal::equal_smartPtrObject(object));

  // The object is not associated with the given picker.
  if (itObj == it->second.end())
    {
    return;
    }

  it->second.erase(itObj);

  // Delete the picker when it is not associated with any object anymore.
  if(it->second.size() == 0)
    {
    this->Internal->Pickers.erase(it);
    }
}

//------------------------------------------------------------------------------
void vtkPickingManager::RemoveObject(vtkObject* object)
{
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    this->Internal->Pickers.begin();

  for(; it != this->Internal->Pickers.end();)
    {
    vtkPickingManager::vtkInternal::CollectionType::iterator itObj =
      std::find_if(it->second.begin(),
                   it->second.end(),
                   vtkPickingManager::vtkInternal::equal_smartPtrObject(object));

    if (itObj != it->second.end())
      {
      it->second.erase(itObj);

      if (it->second.size() == 0)
        {
        this->Internal->Pickers.erase(it);
        continue;
        }
      }

    ++it;
    }
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkAbstractPicker* picker, vtkObject* obj)
{
  if (!this->Internal->IsObjectLinked(picker, obj))
    {
    return false;
    }

  return (this->Pick(picker));
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkObject* obj)
{
  vtkAbstractPicker* picker = this->Internal->SelectPicker();
  if(!picker)
    {
    return false;
    }
  // If the object is not contained in the list of the associated active pickers
  // return false
  return (this->Internal->IsObjectLinked(picker, obj));
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkAbstractPicker* picker)
{
  return (picker == this->Internal->SelectPicker());
}

//------------------------------------------------------------------------------
vtkAssemblyPath* vtkPickingManager::
GetAssemblyPath(double X, double Y, double Z,
                vtkAbstractPropPicker* picker,
                vtkRenderer* renderer,
                vtkObject* obj)
{
  if (this->Enabled)
    {
    // Return 0 when the Picker is not selected
    if (!this->Pick(picker, obj))
      {
      return 0;
      }
    }
  else
    {
    picker->Pick(X, Y, Z, renderer);
    }

  return picker->GetPath();
}

//------------------------------------------------------------------------------
int vtkPickingManager::GetNumberOfPickers()
{
  return static_cast<int>(this->Internal->Pickers.size());
}

//------------------------------------------------------------------------------
int vtkPickingManager::GetNumberOfObjectsLinked(vtkAbstractPicker* picker)
{
  if (!picker)
    {
    return 0;
    }

  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  if (it == this->Internal->Pickers.end())
    {
    return 0;
    }

  return static_cast<int>(it->second.size());
}

//------------------------------------------------------------------------------
void vtkPickingManager::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "RenderWindowInteractor: " << this->Interactor << "\n";
  os << indent << "NumberOfPickers: " << this->Internal->Pickers.size() << "\n";

  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    this->Internal->Pickers.begin();

  for(; it != this->Internal->Pickers.end(); ++it)
    {
    os << indent << indent << "Picker: " << it->first.GetPointer() << "\n";
    os << indent << indent << "NumberOfObjectsLinked: " << it->second.size()
       << "\n";
    }
}
<commit_msg>Fix invalid iterator access after erase().<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPickingManager.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

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

  Library: MSVTK

  Copyright (c) Kitware 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.txt

  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.

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

// VTK includes
#include "vtkAbstractPicker.h"
#include "vtkAbstractPropPicker.h"
#include "vtkCamera.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkMath.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPickingManager.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkSmartPointer.h"
#include "vtkTimeStamp.h"

// STL includes
#include <algorithm>
#include <limits>
#include <map>
#include <vector>

//------------------------------------------------------------------------------
vtkStandardNewMacro(vtkPickingManager);

//------------------------------------------------------------------------------
class vtkPickingManager::vtkInternal
{
public:
  vtkInternal(vtkPickingManager* external);
  ~vtkInternal();

  // Callback used to update the current time
  // of the manager when an event occurs in the RenderWindowInteractor.
  // Time is used to know if the cached information is still valid or obsolete.
  static void UpdateTime(vtkObject *caller,
                         unsigned long event,
                         void *clientData,
                         void *callData);

  // Select the best picker based on various criterias such as z-depth,
  // 2D overlay and/or distance to picked point.
  vtkAbstractPicker* SelectPicker();

  // Compute the selection. The current implementation use the distance
  // between the world coordinates of a pick to the camera's ones.
  vtkAbstractPicker* ComputePickerSelection(double X, double Y, double Z,
                                            vtkRenderer* renderer);

  // Check if a given Observator is associated with a given Picker
  bool IsObjectLinked(vtkAbstractPicker* picker, vtkObject* object);

  // Create a new list of associated observers
  void CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object);

  // Instead of a vtkCollection we are using a vector of a vtkSmartPointer
  // containing vtkObject to allow using 0 as a valid value because it is
  // allowed the return a picker event if he is not associated to a specific
  // object.
  // This is related with the capacity when a picker associated with a given
  // object does not manage others object,
  // it will automatically be removed from the list as well.
  typedef std::vector<vtkSmartPointer<vtkObject> > CollectionType;

  // For code clearance and performances during the computation std::map is
  // used instead of a vector of pair. Nevertheless, it makes internally use of
  // vtkSmartPointer and this class does not overload the order operators;
  // therefore to following functor has to be implemented to keep the data
  // structure consistent.
  struct less_smartPtrPicker
  {
    bool operator () (const vtkSmartPointer<vtkAbstractPicker>& first,
                      const vtkSmartPointer<vtkAbstractPicker>& second) const
      {
      return first.GetPointer() < second.GetPointer();
      }
  };

  typedef std::map<vtkSmartPointer<vtkAbstractPicker>,
                   CollectionType, less_smartPtrPicker > PickerObjectsType;

  typedef std::pair<vtkSmartPointer<vtkAbstractPicker>,
                    CollectionType> PickerObjectsPairType;

  // Associate a given vtkObject to a particular picker.
  void LinkPickerObject(const PickerObjectsType::iterator& it,
                        vtkObject* object);

  // Predicate comparing a vtkAbstractPicker*
  // and a vtkSmartPointer<vtkAbstractPicker> using the PickerObjectsType.
  // As we use a vtkSmartPointer, this predicate allows to compare the equality
  // of a pointer on a vtkAbstractPicker with the adress contained in
  // a corresponding vtkSmartPointer.
  struct equal_smartPtrPicker
  {
    equal_smartPtrPicker(vtkAbstractPicker* picker) : Picker(picker) {}

    bool operator () (const PickerObjectsPairType& pickerObjs) const
      {
      return this->Picker == pickerObjs.first.GetPointer();
      }

    vtkAbstractPicker* Picker;
  };

  // Predicate comparing a vtkObject*
  // and a vtkSmartPointer<vtkObject> using the PickerObjectsType.
  // As we use a vtkSmartPointer, this predicate allows to compare the equality
  // of a pointer on a vtkObject with the adress contained in
  // a corresponding vtkSmartPointer.
  struct equal_smartPtrObject
  {
    equal_smartPtrObject(vtkObject* object) : Object(object) {}

    bool operator () (const vtkSmartPointer<vtkObject>& smartObj) const
      {
      return this->Object == smartObj.GetPointer();
      }

    vtkObject* Object;
  };

  PickerObjectsType Pickers;           // Map the picker with the objects
  vtkTimeStamp CurrentInteractionTime; // Time of the last interaction event
  vtkTimeStamp LastPickingTime;        // Time of the last picking process
  vtkSmartPointer<vtkAbstractPicker> LastSelectedPicker;

  // Define callback to keep track of the CurrentTime and the LastPickingTime.
  // The timeStamp is use to avoid repeating the picking process if the
  // vtkWindowInteractor has not been modified, it is a huge optimization
  // avoiding each picker to relaunch the whole mechanisme to determine which
  // picker has been selected at a state of the rendering.
  vtkSmartPointer<vtkCallbackCommand> TimerCallback;

  vtkPickingManager*  External;
};

//------------------------------------------------------------------------------
// vtkInternal methods

//------------------------------------------------------------------------------
vtkPickingManager::vtkInternal::vtkInternal(vtkPickingManager* external)
{
  this->External = external;

  this->TimerCallback = vtkSmartPointer<vtkCallbackCommand>::New();
  this->TimerCallback->SetClientData(this);
  this->TimerCallback->SetCallback(UpdateTime);

}

//------------------------------------------------------------------------------
vtkPickingManager::vtkInternal::~vtkInternal()
{}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::
CreateDefaultCollection(vtkAbstractPicker* picker, vtkObject* object)
{
  CollectionType objects;
  objects.push_back(object);

  this->Pickers.insert(PickerObjectsPairType(picker, objects));
}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::
LinkPickerObject(const PickerObjectsType::iterator& it, vtkObject* object)
{
  CollectionType::iterator itObj = std::find_if(it->second.begin(),
                                                it->second.end(),
                                                equal_smartPtrObject(object));

  if (itObj != it->second.end() && object)
    {
    vtkDebugWithObjectMacro(
      this->External, "vtkPickingtManager::Internal::LinkPickerObject: "
      << "Current object already linked with the given picker.");

    return;
    }

  it->second.push_back(object);
}

//------------------------------------------------------------------------------
bool vtkPickingManager::vtkInternal::
IsObjectLinked(vtkAbstractPicker* picker, vtkObject* obj)
{
  if(!picker || !obj)
    {
    return false;
    }

  PickerObjectsType::iterator itPick = std::find_if(
    this->Pickers.begin(), this->Pickers.end(), equal_smartPtrPicker(picker));
  if(itPick == this->Pickers.end())
    {
    return false;
    }

  CollectionType::iterator itObj = std::find_if(itPick->second.begin(),
                                                itPick->second.end(),
                                                equal_smartPtrObject(obj));
  return (itObj != itPick->second.end());
}

//------------------------------------------------------------------------------
vtkAbstractPicker* vtkPickingManager::vtkInternal::SelectPicker()
{
  if (!this->External->Interactor)
    {
    return 0;
    }
  else if (this->External->GetOptimizeOnInteractorEvents() &&
           this->CurrentInteractionTime.GetMTime() == this->LastPickingTime)
    {
    return this->LastSelectedPicker;
    }

  // Get the event position
  double X = this->External->Interactor->GetEventPosition()[0];
  double Y = this->External->Interactor->GetEventPosition()[1];

  // Get the poked renderer
  vtkRenderer* renderer = this->External->Interactor->FindPokedRenderer(X, Y);
  vtkAbstractPicker* selectedPicker =
    this->ComputePickerSelection(X, Y, 0., renderer);

  // Keep track of the lastet picker choosen & last picking time.
  this->LastSelectedPicker = selectedPicker;
  this->LastPickingTime = this->CurrentInteractionTime;

  return selectedPicker;
}

//------------------------------------------------------------------------------
vtkAbstractPicker* vtkPickingManager::vtkInternal::
ComputePickerSelection(double X, double Y, double Z, vtkRenderer* renderer)
{
  vtkAbstractPicker* closestPicker = 0;
  if (!renderer)
    {
    return closestPicker;
    }

  double* camPos = renderer->GetActiveCamera()->GetPosition();
  double smallestDistance2 = std::numeric_limits<double>::max();

  for(PickerObjectsType::iterator it = this->Pickers.begin();
      it != this->Pickers.end(); ++it)
    {
    int pickResult = it->first->Pick(X, Y, Z, renderer);
    double* pPos = it->first->GetPickPosition();

    if(pickResult > 0) // Keep closest object picked.
      {
      double distance2 = vtkMath::Distance2BetweenPoints(camPos, pPos);

      if(smallestDistance2 > distance2)
        {
        smallestDistance2 = distance2;
        closestPicker = it->first;
        }
      }
    }

  return closestPicker;
}

//------------------------------------------------------------------------------
void vtkPickingManager::vtkInternal::UpdateTime(vtkObject *vtkNotUsed(caller),
                                                unsigned long vtkNotUsed(event),
                                                void *clientData,
                                                void *vtkNotUsed(calldata))
{
  vtkPickingManager::vtkInternal* self =
    reinterpret_cast<vtkPickingManager::vtkInternal*>(clientData);
  if (!self)
    {
    return;
    }

  self->CurrentInteractionTime.Modified();
}

//------------------------------------------------------------------------------
// vtkPickingManager methods

//------------------------------------------------------------------------------
vtkPickingManager::vtkPickingManager()
  : Interactor(0)
  , Enabled(false)
  , OptimizeOnInteractorEvents(true)
  , Internal(0)
{
  this->Internal = new vtkInternal(this);
}

//------------------------------------------------------------------------------
vtkPickingManager::~vtkPickingManager()
{
  this->SetInteractor(0);
  delete this->Internal;
}

//------------------------------------------------------------------------------
void vtkPickingManager::SetInteractor(vtkRenderWindowInteractor* rwi)
{
  if (rwi == this->Interactor)
    {
    return;
    }
  if (this->Interactor)
    {
    this->Interactor->RemoveObserver(this->Internal->TimerCallback);
    }

  this->Interactor = rwi;
  if (this->Interactor)
    {
    this->Interactor->AddObserver(
      vtkCommand::ModifiedEvent, this->Internal->TimerCallback);
    }

  this->Modified();
}

//------------------------------------------------------------------------------
void vtkPickingManager::SetOptimizeOnInteractorEvents(bool optimize)
{
  if (this->OptimizeOnInteractorEvents == optimize)
    {
    return;
    }

  this->OptimizeOnInteractorEvents = optimize;
  this->Modified();
}

//------------------------------------------------------------------------------
void vtkPickingManager::AddPicker(vtkAbstractPicker* picker,
                                  vtkObject* object)
{
  if (!picker)
    {
    return;
    }

  // Linke the object if the picker is already registered
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  if (it != this->Internal->Pickers.end() )
    {
    vtkDebugMacro("vtkPickingtManager::AddPicker: "
      << "Picker already in the manager, the object will be linked");

    this->Internal->LinkPickerObject(it, object);
    return;
    }

  // The picker does not exists in the manager yet.
  // Create the list of associated objects
  this->Internal->CreateDefaultCollection(picker, object);
}

//------------------------------------------------------------------------------
void vtkPickingManager::RemovePicker(vtkAbstractPicker* picker,
                                     vtkObject* object)
{
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  // The Picker does not exist
  if (it == this->Internal->Pickers.end())
    {
    return;
    }

  vtkPickingManager::vtkInternal::CollectionType::iterator itObj =
    std::find_if(it->second.begin(),
                 it->second.end(),
                 vtkPickingManager::vtkInternal::equal_smartPtrObject(object));

  // The object is not associated with the given picker.
  if (itObj == it->second.end())
    {
    return;
    }

  it->second.erase(itObj);

  // Delete the picker when it is not associated with any object anymore.
  if(it->second.size() == 0)
    {
    this->Internal->Pickers.erase(it);
    }
}

//------------------------------------------------------------------------------
void vtkPickingManager::RemoveObject(vtkObject* object)
{
  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    this->Internal->Pickers.begin();

  for(; it != this->Internal->Pickers.end();)
    {
    vtkPickingManager::vtkInternal::CollectionType::iterator itObj =
      std::find_if(it->second.begin(),
                   it->second.end(),
                   vtkPickingManager::vtkInternal::equal_smartPtrObject(object));

    if (itObj != it->second.end())
      {
      it->second.erase(itObj);

      if (it->second.size() == 0)
        {
        vtkPickingManager::vtkInternal::PickerObjectsType::iterator
          toRemove = it;
        it++;
        this->Internal->Pickers.erase(toRemove);
        continue;
        }
      }

    ++it;
    }
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkAbstractPicker* picker, vtkObject* obj)
{
  if (!this->Internal->IsObjectLinked(picker, obj))
    {
    return false;
    }

  return (this->Pick(picker));
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkObject* obj)
{
  vtkAbstractPicker* picker = this->Internal->SelectPicker();
  if(!picker)
    {
    return false;
    }
  // If the object is not contained in the list of the associated active pickers
  // return false
  return (this->Internal->IsObjectLinked(picker, obj));
}

//------------------------------------------------------------------------------
bool vtkPickingManager::Pick(vtkAbstractPicker* picker)
{
  return (picker == this->Internal->SelectPicker());
}

//------------------------------------------------------------------------------
vtkAssemblyPath* vtkPickingManager::
GetAssemblyPath(double X, double Y, double Z,
                vtkAbstractPropPicker* picker,
                vtkRenderer* renderer,
                vtkObject* obj)
{
  if (this->Enabled)
    {
    // Return 0 when the Picker is not selected
    if (!this->Pick(picker, obj))
      {
      return 0;
      }
    }
  else
    {
    picker->Pick(X, Y, Z, renderer);
    }

  return picker->GetPath();
}

//------------------------------------------------------------------------------
int vtkPickingManager::GetNumberOfPickers()
{
  return static_cast<int>(this->Internal->Pickers.size());
}

//------------------------------------------------------------------------------
int vtkPickingManager::GetNumberOfObjectsLinked(vtkAbstractPicker* picker)
{
  if (!picker)
    {
    return 0;
    }

  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    std::find_if( this->Internal->Pickers.begin(),
                  this->Internal->Pickers.end(),
                  vtkPickingManager::vtkInternal::equal_smartPtrPicker(picker));

  if (it == this->Internal->Pickers.end())
    {
    return 0;
    }

  return static_cast<int>(it->second.size());
}

//------------------------------------------------------------------------------
void vtkPickingManager::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);

  os << indent << "RenderWindowInteractor: " << this->Interactor << "\n";
  os << indent << "NumberOfPickers: " << this->Internal->Pickers.size() << "\n";

  vtkPickingManager::vtkInternal::PickerObjectsType::iterator it =
    this->Internal->Pickers.begin();

  for(; it != this->Internal->Pickers.end(); ++it)
    {
    os << indent << indent << "Picker: " << it->first.GetPointer() << "\n";
    os << indent << indent << "NumberOfObjectsLinked: " << it->second.size()
       << "\n";
    }
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkIdentColoredPainter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkIdentColoredPainter.h"

#include "vtkActor.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkConfigure.h"
#include "vtkDataArray.h"
#include "vtkObjectFactory.h"
#include "vtkPainterDeviceAdapter.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolygon.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkTimerLog.h"
#include "vtkTriangle.h"
#include "vtkIdTypeArray.h"

#ifndef VTK_IMPLEMENT_MESA_CXX
#  include "vtkOpenGL.h"
#endif

//-----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkIdentColoredPainter, "1.18");
vtkStandardNewMacro(vtkIdentColoredPainter);

//-----------------------------------------------------------------------------
static inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,
  unsigned long typeflags)
{
  int total_cells = 0;
  total_cells += (typeflags & vtkPainter::VERTS)?
    pd->GetNumberOfVerts() : 0;
  total_cells += (typeflags & vtkPainter::LINES)?
    pd->GetNumberOfLines() : 0;
  total_cells += (typeflags & vtkPainter::POLYS)?
    pd->GetNumberOfPolys() : 0;
  total_cells += (typeflags & vtkPainter::STRIPS)?
    pd->GetNumberOfStrips() : 0;
  return total_cells;
}

//-----------------------------------------------------------------------------
vtkIdentColoredPainter::vtkIdentColoredPainter()
{
  this->ColorMode = COLORBYIDENT;
  this->ResetCurrentId();

  this->ActorIds = NULL;
  this->PropAddrs = NULL;
}

//-----------------------------------------------------------------------------
vtkIdentColoredPainter::~vtkIdentColoredPainter()
{
  if (this->ActorIds != NULL)
    {
    this->ActorIds->Delete();
    this->ActorIds = NULL;
    delete[] this->PropAddrs;
    this->PropAddrs = NULL;
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByConstant(unsigned int constant)
{
  this->ColorMode = COLORBYCONST;
  this->ResetCurrentId();
  this->CurrentIdPlane0 = constant;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByVertex()
{
  this->ColorMode = COLORBYVERTEX;
}

//-----------------------------------------------------------------------------
vtkProp* vtkIdentColoredPainter::GetActorFromId(vtkIdType id)
{
  vtkIdType numIds = this->ActorIds->GetNumberOfTuples();
  for (int i = 0; i < numIds; i++)
    {
    if (this->ActorIds->GetValue(i) == id)
      {
      return this->PropAddrs[i];
      }
    }
  return 0;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)
{
  //free whatever we were given before this
  if (this->ActorIds != NULL)
    {
    this->ActorIds->Delete();
    this->ActorIds = NULL;
    delete[] this->PropAddrs;
    this->PropAddrs = NULL;
    }

  //sanity checking
  if (props == NULL ||
      ids == NULL ||
      (ids->GetNumberOfComponents() != 1) ||
      (ids->GetNumberOfTuples() == 0))
    {
    vtkWarningMacro("Invalid actor-id lookup table supplied.");
    return;
    }

  //copy over the new lookup table
  this->ActorIds = ids;
  this->ActorIds->Register(this);
  this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];
  for (int i = 0; i < ids->GetNumberOfTuples(); i++)
    {
    this->PropAddrs[i] = props[i];
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)
{
  this->ColorMode = COLORBYCONST;
  this->ResetCurrentId();

  vtkIdType maxId = 0;
  int numIds = 0;
  if (this->ActorIds != NULL)
    {
    numIds = this->ActorIds->GetNumberOfTuples();
    for (int i = 0; i< numIds; i++)
      {
      vtkIdType nextId = this->ActorIds->GetValue(i);
      if (actorAddr == this->PropAddrs[i])
        {
        this->CurrentIdPlane0 = nextId + 1;
        return;
        }
      if (nextId > maxId)
        {
        maxId = nextId;
        }
      }
    }

  //we didn't find the actor in the table, make up an ID and add it
  //cerr << "ID not found for actor " << actorAddr
  //     << " using " << maxId+1 << endl;
  vtkIdTypeArray *arr = vtkIdTypeArray::New();
  arr->SetNumberOfComponents(1);
  arr->SetNumberOfTuples(numIds+1);
  vtkProp **SaveProps = new vtkProp*[numIds+1];
  if (this->ActorIds != NULL)
    {
    for (int i = 0; i< numIds; i++)
      {
      arr->SetValue(i, this->ActorIds->GetValue(i));
      SaveProps[i] = this->PropAddrs[i];
      }
    }
  arr->SetValue(numIds, maxId+1);
  SaveProps[numIds] = actorAddr;
  this->MakeActorLookupTable(SaveProps, arr);
  arr->Delete();

  this->CurrentIdPlane0 = maxId+2;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)
{
  this->ColorMode = COLORBYIDENT;
  this->Plane = (plane < 3)?plane:2;
  this->ResetCurrentId();
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ResetCurrentId()
{
  //do not use 0, it is reserved for miss
  this->CurrentIdPlane0 = 1;
  this->CurrentIdPlane1 = 1;
  this->CurrentIdPlane2 = 1;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::IncrementCurrentId()
{
  if (this->ColorMode == COLORBYCONST)
    {
    return;
    }

  //the limits are set up assuming 24 bits total for each for RGB pixel
  //do not use A because the parallel compositing code does not support Alpha
  this->CurrentIdPlane0++;
  if (this->CurrentIdPlane0 >= 0x01000000)
    {
    this->CurrentIdPlane0 = 0x00000001;
    this->CurrentIdPlane1++;
    if (this->CurrentIdPlane1 >= 0x01000000)
      {
      this->CurrentIdPlane1 = 0x00000001;
      this->CurrentIdPlane2++;
      }
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)
{
  unsigned int val = this->CurrentIdPlane0;
  if (this->ColorMode == COLORBYIDENT)
    {
    if (this->Plane == 1)
      {
      val = this->CurrentIdPlane1;
      }
    else if (this->Plane == 2)
      {
      val = this->CurrentIdPlane2;
      }
    }

  //cerr << "Curr Color is "
  //     << this->ColorMode << " "
  //     << this->CurrentIdPlane2 << ":"
  //     << this->CurrentIdPlane1 << ":"
  //     << this->CurrentIdPlane0 << endl;

  RGB[0] = (val & 0x00FF0000)>>16;
  RGB[1] = (val & 0x0000FF00)>>8;
  RGB[2] = (val & 0x000000FF);
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer,
                                            vtkActor* actor,
                                            unsigned long typeflags)
{
  if (typeflags == 0)
    {
    // No primitive to render.
    return;
    }

  vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
    GetPainterDeviceAdapter();

  if (!device)
    {
    vtkErrorMacro("Painter Device Adapter missing!");
    return;
    }

  this->TotalCells =
    vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);

  this->Timer->StartTimer();

  //turn off antialising and lighting so that the colors we draw will be the
  //colors we read back
  int origMultisample = device->QueryMultisampling();
  int origLighting = device->QueryLighting();
  int origBlending = device->QueryBlending();

  device->MakeMultisampling(0);
  device->MakeLighting(0);
  device->MakeBlending(0);

  vtkIdType startCell = 0;

  if (typeflags & vtkPainter::VERTS)
    {
    this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfVerts();

  if (typeflags & vtkPainter::LINES)
    {
    if (this->ColorMode == COLORBYVERTEX)
      {
      //for point selection, draw twice to hide occluded verts
      this->ColorByConstant(0);
      this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,
                      renderer);
      this->ColorByVertex();
      }
    this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfLines();

  if (typeflags & vtkPainter::POLYS)
    {
#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))
    if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
      {
      if (this->ColorMode == COLORBYVERTEX)
        {
        this->ColorByConstant(0);
        this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,
                        renderer);
        this->ColorByVertex();
        }
      this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,
                      renderer);
      }
    else
#endif
      {
      if (this->ColorMode == COLORBYVERTEX)
        {
        this->ColorByConstant(0);
        this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,
                        renderer);
        this->ColorByVertex();
        }
      this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,
                      renderer);
      }
    }
  startCell += this->PolyData->GetNumberOfPolys();

  if (typeflags & vtkPainter::STRIPS)
    {
    if (this->ColorMode == COLORBYVERTEX)
      {
      this->ColorByConstant(4);
      this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,
                      renderer);
      this->ColorByVertex();
      }
    this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfStrips();

  //reset lighting back to the default
  device->MakeBlending(origBlending);
  device->MakeLighting(origLighting);
  device->MakeMultisampling(origMultisample);

  this->Timer->StopTimer();
  this->TimeToDraw = this->Timer->GetElapsedTime();

  // let the superclass pass on the request to delegate painter.
  // Ofcouse, more than likely, this call will never have a delegate,
  // but anyways.
  this->Superclass::RenderInternal(renderer, actor, typeflags);
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,
                                       vtkIdType startCellId,
                                       vtkRenderer *renderer)
{
  if (!this->PolyData)
    {
    vtkWarningMacro("No polydata to render!");
    return;
    }

  if (this->ColorMode == COLORBYVERTEX)
    {
    mode = VTK_POLY_VERTEX;
    vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
      GetPainterDeviceAdapter();
    device->MakeVertexEmphasis(1); //draw verts larger and nearer to be on top
    //of their associated polygons
   }

  vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
    GetPainterDeviceAdapter();

  vtkPoints* p = this->PolyData->GetPoints();
  vtkIdType npts, *pts;
  vtkIdType cellId = startCellId;

  int pointtype = p->GetDataType();
  void* voidpoints = p->GetVoidPointer(0);
  int count = 0;

  unsigned char color[3];
  for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)
    {
    device->BeginPrimitive(mode);

    if (this->ColorMode == COLORBYVERTEX)
      {
      this->ResetCurrentId();
      }
    this->GetCurrentColor(color);
    device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);

    for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)
      {
      vtkIdType pointId = pts[cellpointi];
      if (this->ColorMode == COLORBYVERTEX && cellpointi > 0)
        {
        this->IncrementCurrentId();
        this->GetCurrentColor(color);

        device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);
        }

      device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,
        pointtype, voidpoints, 3*pointId);
      }

    this->IncrementCurrentId();

    device->EndPrimitive();

    cellId++;

    if (count == 10000)
      {
      count = 0;
      // report progress
      this->UpdateProgress(static_cast<double>(cellId - startCellId)/this->TotalCells);
      // Abort render.
      if (renderer->GetRenderWindow()->CheckAbortStatus())
        {
        if (this->ColorMode == COLORBYVERTEX)
          {
          vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
            GetPainterDeviceAdapter();
          device->MakeVertexEmphasis(0);
          }
        return;
        }
      }

    }

  if (this->ColorMode == COLORBYVERTEX)
    {
    vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
      GetPainterDeviceAdapter();
    device->MakeVertexEmphasis(0);
    }

}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<commit_msg>COMP: fix reused declaration warning.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkIdentColoredPainter.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

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

#include "vtkIdentColoredPainter.h"

#include "vtkActor.h"
#include "vtkCellArray.h"
#include "vtkCellData.h"
#include "vtkConfigure.h"
#include "vtkDataArray.h"
#include "vtkObjectFactory.h"
#include "vtkPainterDeviceAdapter.h"
#include "vtkPointData.h"
#include "vtkPolyData.h"
#include "vtkPolygon.h"
#include "vtkProperty.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkTimerLog.h"
#include "vtkTriangle.h"
#include "vtkIdTypeArray.h"

#ifndef VTK_IMPLEMENT_MESA_CXX
#  include "vtkOpenGL.h"
#endif

//-----------------------------------------------------------------------------
vtkCxxRevisionMacro(vtkIdentColoredPainter, "1.19");
vtkStandardNewMacro(vtkIdentColoredPainter);

//-----------------------------------------------------------------------------
static inline int vtkIdentColoredPainterGetTotalCells(vtkPolyData* pd,
  unsigned long typeflags)
{
  int total_cells = 0;
  total_cells += (typeflags & vtkPainter::VERTS)?
    pd->GetNumberOfVerts() : 0;
  total_cells += (typeflags & vtkPainter::LINES)?
    pd->GetNumberOfLines() : 0;
  total_cells += (typeflags & vtkPainter::POLYS)?
    pd->GetNumberOfPolys() : 0;
  total_cells += (typeflags & vtkPainter::STRIPS)?
    pd->GetNumberOfStrips() : 0;
  return total_cells;
}

//-----------------------------------------------------------------------------
vtkIdentColoredPainter::vtkIdentColoredPainter()
{
  this->ColorMode = COLORBYIDENT;
  this->ResetCurrentId();

  this->ActorIds = NULL;
  this->PropAddrs = NULL;
}

//-----------------------------------------------------------------------------
vtkIdentColoredPainter::~vtkIdentColoredPainter()
{
  if (this->ActorIds != NULL)
    {
    this->ActorIds->Delete();
    this->ActorIds = NULL;
    delete[] this->PropAddrs;
    this->PropAddrs = NULL;
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByConstant(unsigned int constant)
{
  this->ColorMode = COLORBYCONST;
  this->ResetCurrentId();
  this->CurrentIdPlane0 = constant;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByVertex()
{
  this->ColorMode = COLORBYVERTEX;
}

//-----------------------------------------------------------------------------
vtkProp* vtkIdentColoredPainter::GetActorFromId(vtkIdType id)
{
  vtkIdType numIds = this->ActorIds->GetNumberOfTuples();
  for (int i = 0; i < numIds; i++)
    {
    if (this->ActorIds->GetValue(i) == id)
      {
      return this->PropAddrs[i];
      }
    }
  return 0;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::MakeActorLookupTable(vtkProp **props, vtkIdTypeArray *ids)
{
  //free whatever we were given before this
  if (this->ActorIds != NULL)
    {
    this->ActorIds->Delete();
    this->ActorIds = NULL;
    delete[] this->PropAddrs;
    this->PropAddrs = NULL;
    }

  //sanity checking
  if (props == NULL ||
      ids == NULL ||
      (ids->GetNumberOfComponents() != 1) ||
      (ids->GetNumberOfTuples() == 0))
    {
    vtkWarningMacro("Invalid actor-id lookup table supplied.");
    return;
    }

  //copy over the new lookup table
  this->ActorIds = ids;
  this->ActorIds->Register(this);
  this->PropAddrs = new vtkProp*[ids->GetNumberOfTuples()];
  for (int i = 0; i < ids->GetNumberOfTuples(); i++)
    {
    this->PropAddrs[i] = props[i];
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByActorId(vtkProp *actorAddr)
{
  this->ColorMode = COLORBYCONST;
  this->ResetCurrentId();

  vtkIdType maxId = 0;
  int numIds = 0;
  if (this->ActorIds != NULL)
    {
    numIds = this->ActorIds->GetNumberOfTuples();
    for (int i = 0; i< numIds; i++)
      {
      vtkIdType nextId = this->ActorIds->GetValue(i);
      if (actorAddr == this->PropAddrs[i])
        {
        this->CurrentIdPlane0 = nextId + 1;
        return;
        }
      if (nextId > maxId)
        {
        maxId = nextId;
        }
      }
    }

  //we didn't find the actor in the table, make up an ID and add it
  //cerr << "ID not found for actor " << actorAddr
  //     << " using " << maxId+1 << endl;
  vtkIdTypeArray *arr = vtkIdTypeArray::New();
  arr->SetNumberOfComponents(1);
  arr->SetNumberOfTuples(numIds+1);
  vtkProp **SaveProps = new vtkProp*[numIds+1];
  if (this->ActorIds != NULL)
    {
    for (int i = 0; i< numIds; i++)
      {
      arr->SetValue(i, this->ActorIds->GetValue(i));
      SaveProps[i] = this->PropAddrs[i];
      }
    }
  arr->SetValue(numIds, maxId+1);
  SaveProps[numIds] = actorAddr;
  this->MakeActorLookupTable(SaveProps, arr);
  arr->Delete();

  this->CurrentIdPlane0 = maxId+2;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ColorByIncreasingIdent(unsigned int plane)
{
  this->ColorMode = COLORBYIDENT;
  this->Plane = (plane < 3)?plane:2;
  this->ResetCurrentId();
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::ResetCurrentId()
{
  //do not use 0, it is reserved for miss
  this->CurrentIdPlane0 = 1;
  this->CurrentIdPlane1 = 1;
  this->CurrentIdPlane2 = 1;
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::IncrementCurrentId()
{
  if (this->ColorMode == COLORBYCONST)
    {
    return;
    }

  //the limits are set up assuming 24 bits total for each for RGB pixel
  //do not use A because the parallel compositing code does not support Alpha
  this->CurrentIdPlane0++;
  if (this->CurrentIdPlane0 >= 0x01000000)
    {
    this->CurrentIdPlane0 = 0x00000001;
    this->CurrentIdPlane1++;
    if (this->CurrentIdPlane1 >= 0x01000000)
      {
      this->CurrentIdPlane1 = 0x00000001;
      this->CurrentIdPlane2++;
      }
    }
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::GetCurrentColor(unsigned char *RGB)
{
  unsigned int val = this->CurrentIdPlane0;
  if (this->ColorMode == COLORBYIDENT)
    {
    if (this->Plane == 1)
      {
      val = this->CurrentIdPlane1;
      }
    else if (this->Plane == 2)
      {
      val = this->CurrentIdPlane2;
      }
    }

  //cerr << "Curr Color is "
  //     << this->ColorMode << " "
  //     << this->CurrentIdPlane2 << ":"
  //     << this->CurrentIdPlane1 << ":"
  //     << this->CurrentIdPlane0 << endl;

  RGB[0] = (val & 0x00FF0000)>>16;
  RGB[1] = (val & 0x0000FF00)>>8;
  RGB[2] = (val & 0x000000FF);
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::RenderInternal(vtkRenderer* renderer,
                                            vtkActor* actor,
                                            unsigned long typeflags)
{
  if (typeflags == 0)
    {
    // No primitive to render.
    return;
    }

  vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
    GetPainterDeviceAdapter();

  if (!device)
    {
    vtkErrorMacro("Painter Device Adapter missing!");
    return;
    }

  this->TotalCells =
    vtkIdentColoredPainterGetTotalCells(this->PolyData, typeflags);

  this->Timer->StartTimer();

  //turn off antialising and lighting so that the colors we draw will be the
  //colors we read back
  int origMultisample = device->QueryMultisampling();
  int origLighting = device->QueryLighting();
  int origBlending = device->QueryBlending();

  device->MakeMultisampling(0);
  device->MakeLighting(0);
  device->MakeBlending(0);

  vtkIdType startCell = 0;

  if (typeflags & vtkPainter::VERTS)
    {
    this->DrawCells(VTK_POLY_VERTEX, this->PolyData->GetVerts(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfVerts();

  if (typeflags & vtkPainter::LINES)
    {
    if (this->ColorMode == COLORBYVERTEX)
      {
      //for point selection, draw twice to hide occluded verts
      this->ColorByConstant(0);
      this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,
                      renderer);
      this->ColorByVertex();
      }
    this->DrawCells(VTK_POLY_LINE, this->PolyData->GetLines(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfLines();

  if (typeflags & vtkPainter::POLYS)
    {
#if defined(__APPLE__) && (defined(VTK_USE_CARBON) || defined(VTK_USE_COCOA))
    if (actor->GetProperty()->GetRepresentation() == VTK_WIREFRAME)
      {
      if (this->ColorMode == COLORBYVERTEX)
        {
        this->ColorByConstant(0);
        this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,
                        renderer);
        this->ColorByVertex();
        }
      this->DrawCells(VTK_TETRA, this->PolyData->GetPolys(), startCell,
                      renderer);
      }
    else
#endif
      {
      if (this->ColorMode == COLORBYVERTEX)
        {
        this->ColorByConstant(0);
        this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,
                        renderer);
        this->ColorByVertex();
        }
      this->DrawCells(VTK_POLYGON, this->PolyData->GetPolys(), startCell,
                      renderer);
      }
    }
  startCell += this->PolyData->GetNumberOfPolys();

  if (typeflags & vtkPainter::STRIPS)
    {
    if (this->ColorMode == COLORBYVERTEX)
      {
      this->ColorByConstant(4);
      this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,
                      renderer);
      this->ColorByVertex();
      }
    this->DrawCells(VTK_TRIANGLE_STRIP, this->PolyData->GetStrips(), startCell,
                    renderer);
    }
  startCell += this->PolyData->GetNumberOfStrips();

  //reset lighting back to the default
  device->MakeBlending(origBlending);
  device->MakeLighting(origLighting);
  device->MakeMultisampling(origMultisample);

  this->Timer->StopTimer();
  this->TimeToDraw = this->Timer->GetElapsedTime();

  // let the superclass pass on the request to delegate painter.
  // Ofcouse, more than likely, this call will never have a delegate,
  // but anyways.
  this->Superclass::RenderInternal(renderer, actor, typeflags);
}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::DrawCells(int mode, vtkCellArray *connectivity,
                                       vtkIdType startCellId,
                                       vtkRenderer *renderer)
{
  if (!this->PolyData)
    {
    vtkWarningMacro("No polydata to render!");
    return;
    }

  if (this->ColorMode == COLORBYVERTEX)
    {
    mode = VTK_POLY_VERTEX;
    vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
      GetPainterDeviceAdapter();
    device->MakeVertexEmphasis(1); //draw verts larger and nearer to be on top
    //of their associated polygons
   }

  vtkPainterDeviceAdapter* device = renderer->GetRenderWindow()->
    GetPainterDeviceAdapter();

  vtkPoints* p = this->PolyData->GetPoints();
  vtkIdType npts, *pts;
  vtkIdType cellId = startCellId;

  int pointtype = p->GetDataType();
  void* voidpoints = p->GetVoidPointer(0);
  int count = 0;

  unsigned char color[3];
  for (connectivity->InitTraversal(); connectivity->GetNextCell(npts, pts); count++)
    {
    device->BeginPrimitive(mode);

    if (this->ColorMode == COLORBYVERTEX)
      {
      this->ResetCurrentId();
      }
    this->GetCurrentColor(color);
    device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);

    for (vtkIdType cellpointi = 0; cellpointi < npts; cellpointi++)
      {
      vtkIdType pointId = pts[cellpointi];
      if (this->ColorMode == COLORBYVERTEX && cellpointi > 0)
        {
        this->IncrementCurrentId();
        this->GetCurrentColor(color);

        device->SendAttribute(vtkCellData::SCALARS, 3, VTK_UNSIGNED_CHAR, color);
        }

      device->SendAttribute(vtkPointData::NUM_ATTRIBUTES, 3,
        pointtype, voidpoints, 3*pointId);
      }

    this->IncrementCurrentId();

    device->EndPrimitive();

    cellId++;

    if (count == 10000)
      {
      count = 0;
      // report progress
      this->UpdateProgress(static_cast<double>(cellId - startCellId)/this->TotalCells);
      // Abort render.
      if (renderer->GetRenderWindow()->CheckAbortStatus())
        {
        if (this->ColorMode == COLORBYVERTEX)
          {
          device->MakeVertexEmphasis(0);
          }
        return;
        }
      }

    }

  if (this->ColorMode == COLORBYVERTEX)
    {
    device->MakeVertexEmphasis(0);
    }

}

//-----------------------------------------------------------------------------
void vtkIdentColoredPainter::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}
<|endoftext|>