<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/dbus/cras_audio_client_stub_impl.h"

namespace chromeos {

CrasAudioClientStubImpl::CrasAudioClientStubImpl() {}

void CrasAudioClientStubImpl::Init(dbus::Bus* bus) {
  VLOG(1) << "CrasAudioClientStubImpl is created";

  // Fake audio output nodes.
  AudioNode node_1;
  node_1.is_input = false;
  node_1.id = 10001;
  node_1.device_name = "Fake Speaker";
  node_1.type = "INTERNAL_SPEAKER";
  node_1.name = "Speaker";
  node_1.active = false;
  node_list_.push_back(node_1);

  AudioNode node_2;
  node_2.is_input = false;
  node_2.id = 10002;
  node_2.device_name = "Fake Headphone";
  node_2.type = "HEADPHONE";
  node_2.name = "Headphone";
  node_2.active = false;
  node_list_.push_back(node_2);
  active_output_node_id_ = node_2.id;

  AudioNode node_3;
  node_3.is_input = false;
  node_3.id = 10003;
  node_3.device_name = "Fake Bluetooth Headphone";
  node_3.type = "BLUETOOTH";
  node_3.name = "Headphone";
  node_3.active = false;
  node_list_.push_back(node_3);

  // Fake audio input ndoes
  AudioNode node_4;
  node_4.is_input = true;
  node_4.id = 10004;
  node_4.device_name = "Fake Internal Mic";
  node_4.type = "INTERNAL_MIC";
  node_4.name = "Internal Mic";
  node_4.active = false;
  node_list_.push_back(node_4);

  AudioNode node_5;
  node_5.is_input = true;
  node_5.id = 10005;
  node_5.device_name = "Fake USB Mic";
  node_5.type = "USB";
  node_5.name = "Mic";
  node_5.active = true;
  node_list_.push_back(node_5);

  active_input_node_id_ = node_5.id;
}

CrasAudioClientStubImpl::~CrasAudioClientStubImpl() {
}

void CrasAudioClientStubImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void CrasAudioClientStubImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

bool CrasAudioClientStubImpl::HasObserver(Observer* observer) {
  return observers_.HasObserver(observer);
}

void CrasAudioClientStubImpl::GetVolumeState(
    const GetVolumeStateCallback& callback) {
  callback.Run(volume_state_, true);
}

void CrasAudioClientStubImpl::GetNodes(const GetNodesCallback& callback,
                                       const ErrorCallback& error_callback) {
  callback.Run(node_list_, true);
}

void CrasAudioClientStubImpl::SetOutputNodeVolume(uint64 node_id,
                                                  int32 volume) {
}

void CrasAudioClientStubImpl::SetOutputUserMute(bool mute_on) {
  volume_state_.output_user_mute = mute_on;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    OutputMuteChanged(volume_state_.output_user_mute));
}

void CrasAudioClientStubImpl::SetInputNodeGain(uint64 node_id,
                                               int32 input_gain) {
}

void CrasAudioClientStubImpl::SetInputMute(bool mute_on) {
  volume_state_.input_mute = mute_on;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    InputMuteChanged(volume_state_.input_mute));
}

void CrasAudioClientStubImpl::SetActiveOutputNode(uint64 node_id) {
  if (active_output_node_id_ == node_id)
    return;

  for (size_t i = 0; i < node_list_.size(); ++i) {
    if (node_list_[i].id == active_output_node_id_)
      node_list_[i].active = false;
    else if (node_list_[i].id == node_id)
      node_list_[i].active = true;
  }
  active_output_node_id_ = node_id;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    ActiveOutputNodeChanged(node_id));
}

void CrasAudioClientStubImpl::SetActiveInputNode(uint64 node_id) {
  if (active_input_node_id_ == node_id)
    return;

  for (size_t i = 0; i < node_list_.size(); ++i) {
    if (node_list_[i].id == active_input_node_id_)
      node_list_[i].active = false;
    else if (node_list_[i].id == node_id)
      node_list_[i].active = true;
  }
  active_input_node_id_ = node_id;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    ActiveInputNodeChanged(node_id));
}

void CrasAudioClientStubImpl::SetAudioDevices(
    const AudioNodeList& audio_nodes) {
  node_list_.clear();
  for (size_t i = 0; i < audio_nodes.size(); ++i)
    node_list_.push_back(audio_nodes[i]);
}

void CrasAudioClientStubImpl::ChangeAudioNodes(const AudioNodeList& new_nodes) {
  SetAudioDevices(new_nodes);
  FOR_EACH_OBSERVER(Observer, observers_, NodesChanged());
}

}  // namespace chromeos
<commit_msg>All cras nodes should be inintialized as non-active in the stub implementation. This fixes the cras warning log issue when running ash_unittests.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chromeos/dbus/cras_audio_client_stub_impl.h"

namespace chromeos {

CrasAudioClientStubImpl::CrasAudioClientStubImpl() {}

void CrasAudioClientStubImpl::Init(dbus::Bus* bus) {
  VLOG(1) << "CrasAudioClientStubImpl is created";

  // Fake audio output nodes.
  AudioNode node_1;
  node_1.is_input = false;
  node_1.id = 10001;
  node_1.device_name = "Fake Speaker";
  node_1.type = "INTERNAL_SPEAKER";
  node_1.name = "Speaker";
  node_list_.push_back(node_1);

  AudioNode node_2;
  node_2.is_input = false;
  node_2.id = 10002;
  node_2.device_name = "Fake Headphone";
  node_2.type = "HEADPHONE";
  node_2.name = "Headphone";
  node_list_.push_back(node_2);

  AudioNode node_3;
  node_3.is_input = false;
  node_3.id = 10003;
  node_3.device_name = "Fake Bluetooth Headphone";
  node_3.type = "BLUETOOTH";
  node_3.name = "Headphone";
  node_list_.push_back(node_3);

  // Fake audio input ndoes
  AudioNode node_4;
  node_4.is_input = true;
  node_4.id = 10004;
  node_4.device_name = "Fake Internal Mic";
  node_4.type = "INTERNAL_MIC";
  node_4.name = "Internal Mic";
  node_list_.push_back(node_4);

  AudioNode node_5;
  node_5.is_input = true;
  node_5.id = 10005;
  node_5.device_name = "Fake USB Mic";
  node_5.type = "USB";
  node_5.name = "Mic";
  node_list_.push_back(node_5);
}

CrasAudioClientStubImpl::~CrasAudioClientStubImpl() {
}

void CrasAudioClientStubImpl::AddObserver(Observer* observer) {
  observers_.AddObserver(observer);
}

void CrasAudioClientStubImpl::RemoveObserver(Observer* observer) {
  observers_.RemoveObserver(observer);
}

bool CrasAudioClientStubImpl::HasObserver(Observer* observer) {
  return observers_.HasObserver(observer);
}

void CrasAudioClientStubImpl::GetVolumeState(
    const GetVolumeStateCallback& callback) {
  callback.Run(volume_state_, true);
}

void CrasAudioClientStubImpl::GetNodes(const GetNodesCallback& callback,
                                       const ErrorCallback& error_callback) {
  callback.Run(node_list_, true);
}

void CrasAudioClientStubImpl::SetOutputNodeVolume(uint64 node_id,
                                                  int32 volume) {
}

void CrasAudioClientStubImpl::SetOutputUserMute(bool mute_on) {
  volume_state_.output_user_mute = mute_on;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    OutputMuteChanged(volume_state_.output_user_mute));
}

void CrasAudioClientStubImpl::SetInputNodeGain(uint64 node_id,
                                               int32 input_gain) {
}

void CrasAudioClientStubImpl::SetInputMute(bool mute_on) {
  volume_state_.input_mute = mute_on;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    InputMuteChanged(volume_state_.input_mute));
}

void CrasAudioClientStubImpl::SetActiveOutputNode(uint64 node_id) {
  if (active_output_node_id_ == node_id)
    return;

  for (size_t i = 0; i < node_list_.size(); ++i) {
    if (node_list_[i].id == active_output_node_id_)
      node_list_[i].active = false;
    else if (node_list_[i].id == node_id)
      node_list_[i].active = true;
  }
  active_output_node_id_ = node_id;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    ActiveOutputNodeChanged(node_id));
}

void CrasAudioClientStubImpl::SetActiveInputNode(uint64 node_id) {
  if (active_input_node_id_ == node_id)
    return;

  for (size_t i = 0; i < node_list_.size(); ++i) {
    if (node_list_[i].id == active_input_node_id_)
      node_list_[i].active = false;
    else if (node_list_[i].id == node_id)
      node_list_[i].active = true;
  }
  active_input_node_id_ = node_id;
  FOR_EACH_OBSERVER(Observer,
                    observers_,
                    ActiveInputNodeChanged(node_id));
}

void CrasAudioClientStubImpl::SetAudioDevices(
    const AudioNodeList& audio_nodes) {
  node_list_.clear();
  for (size_t i = 0; i < audio_nodes.size(); ++i)
    node_list_.push_back(audio_nodes[i]);
}

void CrasAudioClientStubImpl::ChangeAudioNodes(const AudioNodeList& new_nodes) {
  SetAudioDevices(new_nodes);
  FOR_EACH_OBSERVER(Observer, observers_, NodesChanged());
}

}  // namespace chromeos
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ASTNodeEraser.h"

#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ///\brief The class does the actual work of removing a declaration and
  /// resetting the internal structures of the compiler
  ///
  class DeclReverter : public DeclVisitor<DeclReverter, bool> {
  private:
    Sema* m_Sema;

  public:
    DeclReverter(Sema* S): m_Sema(S) {}

    ///\brief Function that contains common actions, done for every removal of
    /// declaration.
    ///
    /// For example: We must uncache the cached include, which brought that
    /// declaration in the AST.
    ///\param[in] D - A declaration.
    ///
    void PreVisitDecl(Decl* D);

    ///\brief If it falls back in the base class just remove the declaration
    /// only from the declaration context.
    /// @param[in] D - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitDecl(Decl* D);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context.
    /// @param[in] ND - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamedDecl(NamedDecl* ND);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] VD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitVarDecl(VarDecl* VD);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] FD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitFunctionDecl(FunctionDecl* FD);

    ///\brief Removes the enumerator and its enumerator constants.
    /// @param[in] ED - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitEnumDecl(EnumDecl* ED);

    ///\brief Removes the namespace.
    /// @param[in] NSD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamespaceDecl(NamespaceDecl* NSD);

    /// @name Helpers
    /// @{

    ///\brief Checks whether the declaration was pushed onto the declaration
    /// chains. Returns
    /// @param[in] ND - The declaration that is being checked
    ///
    ///\returns true if the ND was found in the lookup chain.
    ///
    bool isOnScopeChains(clang::NamedDecl* ND);

    ///\brief Removes given declaration from the chain of redeclarations.
    /// Rebuilds the chain and sets properly first and last redeclaration.
    /// @param[in] R - The redeclarable, its chain to be rebuilt
    ///
    ///\returns the most recent redeclaration in the new chain.
    ///
    template <typename T>
    T* RemoveFromRedeclChain(clang::Redeclarable<T>* R) {
      llvm::SmallVector<T*, 4> PrevDecls;
      T* PrevDecl = 0;

      // [0]=>C [1]=>B [2]=>A ...
      while ((PrevDecl = R->getPreviousDecl())) {
        PrevDecls.push_back(PrevDecl);
        R = PrevDecl;
      }

      if (!PrevDecls.empty()) {
        // Put 0 in the end of the array so that the loop will reset the
        // pointer to latest redeclaration in the chain to itself.
        //
        PrevDecls.push_back(0);

        // 0 <- A <- B <- C
        for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
          PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
        }
      }

      return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();
    }

    /// @}
  };

  void DeclReverter::PreVisitDecl(Decl *D) {
    SourceLocation Loc = D->getLocStart();
    SourceManager& SM = m_Sema->getSourceManager();
    FileManager& FM = SM.getFileManager();
    const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));
    if (OldEntry)
      FM.invalidateCache(OldEntry);

    // Clean up the pending instantiations
    m_Sema->PendingInstantiations.clear();
    m_Sema->PendingLocalImplicitInstantiations.clear();

  }

  // Gives us access to the protected members that we  need.
  class DeclContextExt : public DeclContext {
  public:
    static bool removeIfLast(DeclContext* DC, Decl* D) {
      if (!D->getNextDeclInContext()) {
        // Either last (remove!), or invalid (nothing to remove)
        if (((DeclContextExt*)DC)->LastDecl == D) {
          // Valid. Thus remove.
          DC->removeDecl(D);
          return true;
        }
      }
      else {
        DC->removeDecl(D);
        return true;
      }

      return false;
    }
  };

  bool DeclReverter::VisitDecl(Decl* D) {
    assert(D && "The Decl is null");
    PreVisitDecl(D);

    DeclContext* DC = D->getDeclContext();

    bool ExistsInDC = false;

    for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
         E !=I; ++I) {
      if (*I == D) {
        ExistsInDC = true;
        break;
      }
    }

    bool Successful = DeclContextExt::removeIfLast(DC, D);

    // ExistsInDC && Successful
    // true          false      -> false // In the context but cannot delete
    // false         false      -> true  // Not in the context cannot delete
    // true          true       -> true  // In the context and can delete
    // false         true       -> assert // Not in the context but can delete ?
    assert(!(!ExistsInDC && Successful) && \
           "Not in the context but can delete?!");
    if (ExistsInDC && !Successful)
      return false;
    else { // in release we'd want the assert to fall into true
      m_Sema->getDiagnostics().Reset();
      return true;
    }
  }

  bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
    bool Successful = VisitDecl(ND);

    DeclContext* DC = ND->getDeclContext();

    // If the decl was removed make sure that we fix the lookup
    if (Successful) {
      Scope* S = m_Sema->getScopeForContext(DC);
      if (S)
        S->RemoveDecl(ND);

      if (isOnScopeChains(ND))
        m_Sema->IdResolver.RemoveDecl(ND);

      return true;
    }

    return false;
  }

  bool DeclReverter::VisitVarDecl(VarDecl* VD) {
    bool Successful = VisitNamedDecl(VD);

    DeclContext* DC = VD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      // We need to rewire the list of the redeclarations in order to exclude
      // the reverted one, because it gets found for example by
      // Sema::MergeVarDecl and ends up in the lookup
      //
      if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {

        Pos->second.setOnlyValue(MostRecentVD);
        if (S)
          S->AddDecl(MostRecentVD);
        m_Sema->IdResolver.AddDecl(MostRecentVD);
      }

    return Successful;
  }

  bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
    bool Successful = true;

    DeclContext* DC = FD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Template instantiation of templated function first creates a canonical
    // declaration and after the actual template specialization. For example:
    // template<typename T> T TemplatedF(T t);
    // template<> int TemplatedF(int i) { return i + 1; } creates:
    // 1. Canonical decl: int TemplatedF(int i);
    // 2. int TemplatedF(int i){ return i + 1; }
    //
    // The template specialization is attached to the list of specialization of
    // the templated function.
    // When TemplatedF is looked up it finds the templated function and the
    // lookup is extended by the templated function with its specializations.
    // In the end we don't need to remove the canonical decl because, it
    // doesn't end up in the lookup table.
    //
#if 0
    getSpecializations() now returns a FoldingSetVector which
    does not have an interface for removing nodes...
    class FunctionTemplateDeclExt : public FunctionTemplateDecl {
    public:
      static llvm::FoldingSet<FunctionTemplateSpecializationInfo>&
      getSpecializationsExt(FunctionTemplateDecl* FTD) {
        assert(FTD && "Cannot be null!");
        return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();
      }
    };
#endif

    if (FD->isFunctionTemplateSpecialization()) {
#if 0
      // 1. Remove the canonical decl.
      // TODO: Can the canonical have another DeclContext and Scope, different
      // from the specialization's implementation?
      FunctionDecl* CanFD = FD->getCanonicalDecl();
      FunctionTemplateDecl* FTD
        = FD->getTemplateSpecializationInfo()->getTemplate();
      llvm::FoldingSet<FunctionTemplateSpecializationInfo> &FS
        = FunctionTemplateDeclExt::getSpecializationsExt(FTD);
      FS.RemoveNode(CanFD->getTemplateSpecializationInfo());
#endif
      assert("FunctionTemplateSpecialization not handled yet" && 0);
    }

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.getAsDecl()) {
      Successful = VisitNamedDecl(FD) && Successful;

      Pos = Map->find(FD->getDeclName());
      assert(Pos != Map->end() && "no lookup entry for decl");

      if (Pos->second.isNull()) {
        // When we have template specialization we have to clean up
        if (FD->isFunctionTemplateSpecialization()) {
          while ((FD = FD->getPreviousDecl())) {
            Successful = VisitNamedDecl(FD) && Successful;
          }
          return true;
        }

        // We need to rewire the list of the redeclarations in order to exclude
        // the reverted one, because it gets found for example by
        // Sema::MergeVarDecl and ends up in the lookup
        //
        if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
          Pos->second.setOnlyValue(MostRecentFD);
          if (S)
            S->AddDecl(MostRecentFD);
          m_Sema->IdResolver.AddDecl(MostRecentFD);
        }
      }
    }
    else if (llvm::SmallVector<NamedDecl*, 4>* Decls
             = Pos->second.getAsVector()) {
      for(llvm::SmallVector<NamedDecl*, 4>::iterator I = Decls->begin();
          I != Decls->end(); ++I) {
        if ((*I) == FD) {
          if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
            Successful = VisitNamedDecl(*I) && Successful;
            Decls->insert(I, MostRecentFD);
          }
          else
            Decls->erase(I);
        }
      }
    }

    return Successful;
  }

  bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {
    bool Successful = true;

    for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      assert(I->getDeclName() && "EnumConstantDecl with no name?");
      Successful = VisitNamedDecl(*I) && Successful;
    }

    Successful = VisitNamedDecl(ED) && Successful;

    return Successful;
  }

  bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
    bool Successful = VisitNamedDecl(NSD);

    //DeclContext* DC = NSD->getPrimaryContext();
    DeclContext* DC = NSD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      if (NSD != NSD->getOriginalNamespace()) {
        NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
        Pos->second.setOnlyValue(NewNSD);
        if (S)
          S->AddDecl(NewNSD);
        m_Sema->IdResolver.AddDecl(NewNSD);
      }

    return Successful;
  }

  // See Sema::PushOnScopeChains
  bool DeclReverter::isOnScopeChains(NamedDecl* ND) {

    // Named decls without name shouldn't be in. Eg: struct {int a};
    if (!ND->getDeclName())
      return false;

    // Out-of-line definitions shouldn't be pushed into scope in C++.
    // Out-of-line variable and function definitions shouldn't even in C.
    if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
        !ND->getDeclContext()->getRedeclContext()->Equals(
                        ND->getLexicalDeclContext()->getRedeclContext()))
      return false;

    // Template instantiations should also not be pushed into scope.
    if (isa<FunctionDecl>(ND) &&
        cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
      return false;

    IdentifierResolver::iterator
      IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
      IDRiEnd = m_Sema->IdResolver.end();

    for (; IDRi != IDRiEnd; ++IDRi) {
      if (ND == *IDRi)
        return true;
    }

    // Check if the declaration is template instantiation, which is not in
    // any DeclContext yet, because it came from
    // Sema::PerformPendingInstantiations
    // if (isa<FunctionDecl>(D) &&
    //     cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
    //   return false;ye

    return false;
  }

  ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {
    m_DeclReverter = new DeclReverter(S);
  }

  ASTNodeEraser::~ASTNodeEraser() {
    delete m_DeclReverter;
    m_DeclReverter = 0;
  }

  bool ASTNodeEraser::RevertDecl(Decl* D) {
    return m_DeclReverter->Visit(D);
  }

} // end namespace cling
<commit_msg>Collect the file entries that contained the reverted declaration. Uncache them  when destroying the object. Presumably the reverter is used per transaction so  this is the best place to uncache the files.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Vassil Vassilev <vvasilev@cern.ch>
//------------------------------------------------------------------------------

#include "ASTNodeEraser.h"

#include "clang/AST/Decl.h"
#include "clang/AST/DeclVisitor.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/FileManager.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/Sema.h"

using namespace clang;

namespace cling {

  ///\brief The class does the actual work of removing a declaration and
  /// resetting the internal structures of the compiler
  ///
  class DeclReverter : public DeclVisitor<DeclReverter, bool> {
  private:
    typedef llvm::DenseSet<const FileEntry*> FileEntries;

    ///\brief The Sema object being reverted (contains the AST as well).
    Sema* m_Sema;

    ///\brief Reverted declaration contains a SourceLocation, representing a
    /// place in the file where it was seen. Clang caches that file and even if
    /// a declaration is removed and the file is edited we hit the cached entry.
    /// This ADT keeps track of the files from which the reverted declarations
    /// came from so that in the end they could be removed from clang's cache.
    ///
    FileEntries m_FilesToUncache;

  public:
    DeclReverter(Sema* S): m_Sema(S) {}
    ~DeclReverter();

    ///\brief Function that contains common actions, done for every removal of
    /// declaration.
    ///
    /// For example: We must uncache the cached include, which brought that
    /// declaration in the AST.
    ///\param[in] D - A declaration.
    ///
    void PreVisitDecl(Decl* D);

    ///\brief If it falls back in the base class just remove the declaration
    /// only from the declaration context.
    /// @param[in] D - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitDecl(Decl* D);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context.
    /// @param[in] ND - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamedDecl(NamedDecl* ND);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] VD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitVarDecl(VarDecl* VD);

    ///\brief Removes the declaration from the lookup chains and from the
    /// declaration context and it rebuilds the redeclaration chain.
    /// @param[in] FD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitFunctionDecl(FunctionDecl* FD);

    ///\brief Removes the enumerator and its enumerator constants.
    /// @param[in] ED - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitEnumDecl(EnumDecl* ED);

    ///\brief Removes the namespace.
    /// @param[in] NSD - The declaration to be removed.
    ///
    ///\returns true on success.
    ///
    bool VisitNamespaceDecl(NamespaceDecl* NSD);

    /// @name Helpers
    /// @{

    ///\brief Checks whether the declaration was pushed onto the declaration
    /// chains. Returns
    /// @param[in] ND - The declaration that is being checked
    ///
    ///\returns true if the ND was found in the lookup chain.
    ///
    bool isOnScopeChains(clang::NamedDecl* ND);

    ///\brief Removes given declaration from the chain of redeclarations.
    /// Rebuilds the chain and sets properly first and last redeclaration.
    /// @param[in] R - The redeclarable, its chain to be rebuilt
    ///
    ///\returns the most recent redeclaration in the new chain.
    ///
    template <typename T>
    T* RemoveFromRedeclChain(clang::Redeclarable<T>* R) {
      llvm::SmallVector<T*, 4> PrevDecls;
      T* PrevDecl = 0;

      // [0]=>C [1]=>B [2]=>A ...
      while ((PrevDecl = R->getPreviousDecl())) {
        PrevDecls.push_back(PrevDecl);
        R = PrevDecl;
      }

      if (!PrevDecls.empty()) {
        // Put 0 in the end of the array so that the loop will reset the
        // pointer to latest redeclaration in the chain to itself.
        //
        PrevDecls.push_back(0);

        // 0 <- A <- B <- C
        for(unsigned i = PrevDecls.size() - 1; i > 0; --i) {
          PrevDecls[i-1]->setPreviousDeclaration(PrevDecls[i]);
        }
      }

      return PrevDecls.empty() ? 0 : PrevDecls[0]->getMostRecentDecl();
    }

    /// @}
  };

  void DeclReverter::PreVisitDecl(Decl *D) {
    const SourceLocation Loc = D->getLocStart();
    const SourceManager& SM = m_Sema->getSourceManager();
    const FileEntry* OldEntry = SM.getFileEntryForID(SM.getFileID(Loc));
    if (OldEntry && !m_FilesToUncache.count(OldEntry))
      m_FilesToUncache.insert(OldEntry);

    // Clean up the pending instantiations
    m_Sema->PendingInstantiations.clear();
    m_Sema->PendingLocalImplicitInstantiations.clear();

  }

  // Gives us access to the protected members that we  need.
  class DeclContextExt : public DeclContext {
  public:
    static bool removeIfLast(DeclContext* DC, Decl* D) {
      if (!D->getNextDeclInContext()) {
        // Either last (remove!), or invalid (nothing to remove)
        if (((DeclContextExt*)DC)->LastDecl == D) {
          // Valid. Thus remove.
          DC->removeDecl(D);
          return true;
        }
      }
      else {
        DC->removeDecl(D);
        return true;
      }

      return false;
    }
  };

  bool DeclReverter::VisitDecl(Decl* D) {
    assert(D && "The Decl is null");
    PreVisitDecl(D);

    DeclContext* DC = D->getDeclContext();

    bool ExistsInDC = false;

    for (DeclContext::decl_iterator I = DC->decls_begin(), E = DC->decls_end();
         E !=I; ++I) {
      if (*I == D) {
        ExistsInDC = true;
        break;
      }
    }

    bool Successful = DeclContextExt::removeIfLast(DC, D);

    // ExistsInDC && Successful
    // true          false      -> false // In the context but cannot delete
    // false         false      -> true  // Not in the context cannot delete
    // true          true       -> true  // In the context and can delete
    // false         true       -> assert // Not in the context but can delete ?
    assert(!(!ExistsInDC && Successful) && \
           "Not in the context but can delete?!");
    if (ExistsInDC && !Successful)
      return false;
    else { // in release we'd want the assert to fall into true
      m_Sema->getDiagnostics().Reset();
      return true;
    }
  }

  bool DeclReverter::VisitNamedDecl(NamedDecl* ND) {
    bool Successful = VisitDecl(ND);

    DeclContext* DC = ND->getDeclContext();

    // If the decl was removed make sure that we fix the lookup
    if (Successful) {
      Scope* S = m_Sema->getScopeForContext(DC);
      if (S)
        S->RemoveDecl(ND);

      if (isOnScopeChains(ND))
        m_Sema->IdResolver.RemoveDecl(ND);

      return true;
    }

    return false;
  }

  bool DeclReverter::VisitVarDecl(VarDecl* VD) {
    bool Successful = VisitNamedDecl(VD);

    DeclContext* DC = VD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(VD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      // We need to rewire the list of the redeclarations in order to exclude
      // the reverted one, because it gets found for example by
      // Sema::MergeVarDecl and ends up in the lookup
      //
      if (VarDecl* MostRecentVD = RemoveFromRedeclChain(VD)) {

        Pos->second.setOnlyValue(MostRecentVD);
        if (S)
          S->AddDecl(MostRecentVD);
        m_Sema->IdResolver.AddDecl(MostRecentVD);
      }

    return Successful;
  }

  bool DeclReverter::VisitFunctionDecl(FunctionDecl* FD) {
    bool Successful = true;

    DeclContext* DC = FD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Template instantiation of templated function first creates a canonical
    // declaration and after the actual template specialization. For example:
    // template<typename T> T TemplatedF(T t);
    // template<> int TemplatedF(int i) { return i + 1; } creates:
    // 1. Canonical decl: int TemplatedF(int i);
    // 2. int TemplatedF(int i){ return i + 1; }
    //
    // The template specialization is attached to the list of specialization of
    // the templated function.
    // When TemplatedF is looked up it finds the templated function and the
    // lookup is extended by the templated function with its specializations.
    // In the end we don't need to remove the canonical decl because, it
    // doesn't end up in the lookup table.
    //
#if 0
    getSpecializations() now returns a FoldingSetVector which
    does not have an interface for removing nodes...
    class FunctionTemplateDeclExt : public FunctionTemplateDecl {
    public:
      static llvm::FoldingSet<FunctionTemplateSpecializationInfo>&
      getSpecializationsExt(FunctionTemplateDecl* FTD) {
        assert(FTD && "Cannot be null!");
        return ((FunctionTemplateDeclExt*) FTD)->getSpecializations();
      }
    };
#endif

    if (FD->isFunctionTemplateSpecialization()) {
#if 0
      // 1. Remove the canonical decl.
      // TODO: Can the canonical have another DeclContext and Scope, different
      // from the specialization's implementation?
      FunctionDecl* CanFD = FD->getCanonicalDecl();
      FunctionTemplateDecl* FTD
        = FD->getTemplateSpecializationInfo()->getTemplate();
      llvm::FoldingSet<FunctionTemplateSpecializationInfo> &FS
        = FunctionTemplateDeclExt::getSpecializationsExt(FTD);
      FS.RemoveNode(CanFD->getTemplateSpecializationInfo());
#endif
      assert("FunctionTemplateSpecialization not handled yet" && 0);
    }

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(FD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.getAsDecl()) {
      Successful = VisitNamedDecl(FD) && Successful;

      Pos = Map->find(FD->getDeclName());
      assert(Pos != Map->end() && "no lookup entry for decl");

      if (Pos->second.isNull()) {
        // When we have template specialization we have to clean up
        if (FD->isFunctionTemplateSpecialization()) {
          while ((FD = FD->getPreviousDecl())) {
            Successful = VisitNamedDecl(FD) && Successful;
          }
          return true;
        }

        // We need to rewire the list of the redeclarations in order to exclude
        // the reverted one, because it gets found for example by
        // Sema::MergeVarDecl and ends up in the lookup
        //
        if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
          Pos->second.setOnlyValue(MostRecentFD);
          if (S)
            S->AddDecl(MostRecentFD);
          m_Sema->IdResolver.AddDecl(MostRecentFD);
        }
      }
    }
    else if (llvm::SmallVector<NamedDecl*, 4>* Decls
             = Pos->second.getAsVector()) {
      for(llvm::SmallVector<NamedDecl*, 4>::iterator I = Decls->begin();
          I != Decls->end(); ++I) {
        if ((*I) == FD) {
          if (FunctionDecl* MostRecentFD = RemoveFromRedeclChain(FD)) {
            Successful = VisitNamedDecl(*I) && Successful;
            Decls->insert(I, MostRecentFD);
          }
          else
            Decls->erase(I);
        }
      }
    }

    return Successful;
  }

  bool DeclReverter::VisitEnumDecl(EnumDecl* ED) {
    bool Successful = true;

    for (EnumDecl::enumerator_iterator I = ED->enumerator_begin(),
           E = ED->enumerator_end(); I != E; ++I) {
      assert(I->getDeclName() && "EnumConstantDecl with no name?");
      Successful = VisitNamedDecl(*I) && Successful;
    }

    Successful = VisitNamedDecl(ED) && Successful;

    return Successful;
  }

  bool DeclReverter::VisitNamespaceDecl(NamespaceDecl* NSD) {
    bool Successful = VisitNamedDecl(NSD);

    //DeclContext* DC = NSD->getPrimaryContext();
    DeclContext* DC = NSD->getDeclContext();
    Scope* S = m_Sema->getScopeForContext(DC);

    // Find other decls that the old one has replaced
    StoredDeclsMap *Map = DC->getPrimaryContext()->getLookupPtr();
    if (!Map)
      return false;
    StoredDeclsMap::iterator Pos = Map->find(NSD->getDeclName());
    assert(Pos != Map->end() && "no lookup entry for decl");

    if (Pos->second.isNull())
      if (NSD != NSD->getOriginalNamespace()) {
        NamespaceDecl* NewNSD = NSD->getOriginalNamespace();
        Pos->second.setOnlyValue(NewNSD);
        if (S)
          S->AddDecl(NewNSD);
        m_Sema->IdResolver.AddDecl(NewNSD);
      }

    return Successful;
  }

  // See Sema::PushOnScopeChains
  bool DeclReverter::isOnScopeChains(NamedDecl* ND) {

    // Named decls without name shouldn't be in. Eg: struct {int a};
    if (!ND->getDeclName())
      return false;

    // Out-of-line definitions shouldn't be pushed into scope in C++.
    // Out-of-line variable and function definitions shouldn't even in C.
    if ((isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) && ND->isOutOfLine() &&
        !ND->getDeclContext()->getRedeclContext()->Equals(
                        ND->getLexicalDeclContext()->getRedeclContext()))
      return false;

    // Template instantiations should also not be pushed into scope.
    if (isa<FunctionDecl>(ND) &&
        cast<FunctionDecl>(ND)->isFunctionTemplateSpecialization())
      return false;

    IdentifierResolver::iterator
      IDRi = m_Sema->IdResolver.begin(ND->getDeclName()),
      IDRiEnd = m_Sema->IdResolver.end();

    for (; IDRi != IDRiEnd; ++IDRi) {
      if (ND == *IDRi)
        return true;
    }

    // Check if the declaration is template instantiation, which is not in
    // any DeclContext yet, because it came from
    // Sema::PerformPendingInstantiations
    // if (isa<FunctionDecl>(D) &&
    //     cast<FunctionDecl>(D)->getTemplateInstantiationPattern())
    //   return false;ye

    return false;
  }

  DeclReverter::~DeclReverter() {
    FileManager& FM = m_Sema->getSourceManager().getFileManager();
    for (FileEntries::iterator I = m_FilesToUncache.begin(),
           E = m_FilesToUncache.end(); I != E; ++I) {
      FM.invalidateCache(*I);
    }

    m_Sema = 0;
  }

  ASTNodeEraser::ASTNodeEraser(Sema* S) : m_Sema(S) {
    m_DeclReverter = new DeclReverter(S);
  }

  ASTNodeEraser::~ASTNodeEraser() {
    delete m_DeclReverter;
    m_DeclReverter = 0;
  }

  bool ASTNodeEraser::RevertDecl(Decl* D) {
    return m_DeclReverter->Visit(D);
  }

} // end namespace cling
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: requesttypes.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: hr $ $Date: 2003-03-19 16:19:03 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_REQUESTTYPES_HXX_
#define CONFIGMGR_BACKEND_REQUESTTYPES_HXX_

#ifndef _CONFIGMGR_TREE_VALUENODE_HXX
#include "valuenode.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif

#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif

#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif

namespace configmgr
{
// ---------------------------------------------------------------------------
    namespace backend
    {
// ---------------------------------------------------------------------------
        using configuration::AbsolutePath;
        using configuration::Name;
// ---------------------------------------------------------------------------
      //typedef std::pair<std::auto_ptr<ISubtree>, Name> ComponentData;
        struct ComponentDataStruct
        {
            const std::auto_ptr<ISubtree>& data;
            Name name;
            ComponentDataStruct (const std::auto_ptr<ISubtree>& _data, Name _name)
              : data(_data), name(_name) {}
        };
        typedef struct ComponentDataStruct ComponentData;

        class NodePath
        {
            AbsolutePath m_path;
        public:
            NodePath(AbsolutePath const & _path) : m_path(_path) {};

            AbsolutePath const & location() const { return m_path; }
            AbsolutePath context()          const { return m_path.getParentPath(); }

            bool isEmpty()              const { return m_path.isRoot(); }
            bool isModuleRoot()         const { return m_path.getDepth() == 1; }
            Name getModuleName()        const { return m_path.getModuleName(); }
            rtl::OUString toString()    const { return m_path.toString(); }
        };
// ---------------------------------------------------------------------------
        struct NodeInstance
        {
            typedef std::auto_ptr<ISubtree> Data;

            explicit
            NodeInstance(Data _node, AbsolutePath const & _rootpath)
            : m_node(_node)
            , m_root(_rootpath)
            {
            }

            Data        const & data() const { return m_node; }
            NodePath    const & root() const { return m_root; }

            Data &  mutableData() { return m_node; }
            Data extractData() { return m_node; }
        private:
            Data        m_node;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
        struct TemplateInstance
        {
            typedef std::auto_ptr<INode> Data;

            explicit
            TemplateInstance(Data _node, Name const & _name, Name const & _component)
            : m_node(_node)
            , m_name(_name)
            , m_component(_component)
            {
            }

            Data        const & data() const { return m_node; }
            Name        const & name() const { return m_name; }
            Name        const & component() const { return m_component; }

            Data extractData() { return m_node; }
    private:
            Data m_node;
            Name m_name; // if empty, this is a complete set of component templates
            Name m_component;
        };
// ---------------------------------------------------------------------------
        struct ComponentInstance
        {
            typedef std::auto_ptr<ISubtree> Data;

            explicit
            ComponentInstance(Data _node, Data _template, Name const & _component)
            : m_node(_node)
            , m_template(_template)
            , m_component(_component)
            {
            }

            Data        const & data() const { return m_node; }
            Data        const & templateData() const { return m_template; }
            Name        const & component() const { return m_component; }

            ComponentData  componentTemplateData () const { return ComponentData(m_template,m_component);}
            ComponentData  componentNodeData () const { return ComponentData(m_node,m_component);}
            Data &  mutableData() { return m_node; }
            Data extractData() { return m_node; }
            Data extractTemplateData() { return m_template; }
        private:
            Data        m_node;
            Data        m_template;
            Name        m_component;
        };
// ---------------------------------------------------------------------------
        struct UpdateInstance
        {
            typedef SubtreeChange *         Data;
            typedef SubtreeChange const *   ConstData;

            explicit
            UpdateInstance(Data _update, AbsolutePath const & _rootpath)
            : m_update(_update)
            , m_root(_rootpath)
            {
            }

            UpdateInstance(UpdateInstance & _aModifiableOther)
            : m_update(_aModifiableOther.m_update)
            , m_root(_aModifiableOther.m_root)
            {
            }

            Data                data()       { return m_update; }
            ConstData           data() const { return m_update; }
            NodePath    const & root() const { return m_root; }
        private:
            Data        m_update;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
        struct ConstUpdateInstance
        {
            typedef UpdateInstance::ConstData   Data, ConstData;

            explicit
            ConstUpdateInstance(Data _update, AbsolutePath const & _rootpath)
            : m_update(_update)
            , m_root(_rootpath)
            {
            }

            // conversion
            ConstUpdateInstance(UpdateInstance const & _aModifiable)
            : m_update(_aModifiable.data())
            , m_root(_aModifiable.root())
            {
            }

            Data                data() const { return m_update; }
            NodePath    const & root() const { return m_root; }
        private:
            Data        m_update;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Due to the use of auto_ptr, the XxxInstance classes cannot easily be used as return values
// To return them, they should be wrapped into a ResultHolder

        template <class Instance_>
        class ResultHolder
        {
            struct RCInstance : public salhelper::SimpleReferenceObject
            {
                RCInstance(Instance_ & _instance) : instance(_instance) {}
                Instance_ instance;
            };
            typedef rtl::Reference< RCInstance > InstanceRef;

            InstanceRef m_xInstance;
        public:
            typedef Instance_ Instance;

            explicit
            ResultHolder(Instance & _rInstance)
            : m_xInstance( new RCInstance(_rInstance) )
            {}

            bool isEmpty() const { return !m_xInstance.is(); }

            bool is() const { return m_xInstance.is() && m_xInstance->instance.data().get(); }

            Instance const & instance() const { return  m_xInstance->instance; }

            Instance const & operator *() const { return  instance(); }
            Instance const * operator->() const { return &instance(); }
            Instance & mutableInstance() { return m_xInstance->instance; }

            typename Instance::Data extractDataAndClear()
            {
                typename Instance::Data aData = m_xInstance->instance.extractData();
                this->clear();
                return aData;
            }

            void releaseAndClear()
            {
                typename Instance::Data aData = this->extractDataAndClear();
                aData.release();
            }

            void clear() { m_xInstance.clear(); }
        };
// ---------------------------------------------------------------------------
        typedef ResultHolder< NodeInstance >        NodeResult;
        typedef ResultHolder< TemplateInstance >    TemplateResult;
        typedef ResultHolder< ComponentInstance >   ComponentResult;

// ---------------------------------------------------------------------------
    }
// ---------------------------------------------------------------------------
} // namespace

#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.194); FILE MERGED 2005/09/05 17:04:34 rt 1.7.194.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: requesttypes.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 03:54:19 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CONFIGMGR_BACKEND_REQUESTTYPES_HXX_
#define CONFIGMGR_BACKEND_REQUESTTYPES_HXX_

#ifndef _CONFIGMGR_TREE_VALUENODE_HXX
#include "valuenode.hxx"
#endif
#ifndef CONFIGMGR_TREECHANGELIST_HXX
#include "treechangelist.hxx"
#endif
#ifndef CONFIGMGR_CONFIGPATH_HXX_
#include "configpath.hxx"
#endif

#ifndef _SALHELPER_SIMPLEREFERENCEOBJECT_HXX_
#include <salhelper/simplereferenceobject.hxx>
#endif

#ifndef INCLUDED_MEMORY
#include <memory>
#define INCLUDED_MEMORY
#endif

namespace configmgr
{
// ---------------------------------------------------------------------------
    namespace backend
    {
// ---------------------------------------------------------------------------
        using configuration::AbsolutePath;
        using configuration::Name;
// ---------------------------------------------------------------------------
      //typedef std::pair<std::auto_ptr<ISubtree>, Name> ComponentData;
        struct ComponentDataStruct
        {
            const std::auto_ptr<ISubtree>& data;
            Name name;
            ComponentDataStruct (const std::auto_ptr<ISubtree>& _data, Name _name)
              : data(_data), name(_name) {}
        };
        typedef struct ComponentDataStruct ComponentData;

        class NodePath
        {
            AbsolutePath m_path;
        public:
            NodePath(AbsolutePath const & _path) : m_path(_path) {};

            AbsolutePath const & location() const { return m_path; }
            AbsolutePath context()          const { return m_path.getParentPath(); }

            bool isEmpty()              const { return m_path.isRoot(); }
            bool isModuleRoot()         const { return m_path.getDepth() == 1; }
            Name getModuleName()        const { return m_path.getModuleName(); }
            rtl::OUString toString()    const { return m_path.toString(); }
        };
// ---------------------------------------------------------------------------
        struct NodeInstance
        {
            typedef std::auto_ptr<ISubtree> Data;

            explicit
            NodeInstance(Data _node, AbsolutePath const & _rootpath)
            : m_node(_node)
            , m_root(_rootpath)
            {
            }

            Data        const & data() const { return m_node; }
            NodePath    const & root() const { return m_root; }

            Data &  mutableData() { return m_node; }
            Data extractData() { return m_node; }
        private:
            Data        m_node;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
        struct TemplateInstance
        {
            typedef std::auto_ptr<INode> Data;

            explicit
            TemplateInstance(Data _node, Name const & _name, Name const & _component)
            : m_node(_node)
            , m_name(_name)
            , m_component(_component)
            {
            }

            Data        const & data() const { return m_node; }
            Name        const & name() const { return m_name; }
            Name        const & component() const { return m_component; }

            Data extractData() { return m_node; }
    private:
            Data m_node;
            Name m_name; // if empty, this is a complete set of component templates
            Name m_component;
        };
// ---------------------------------------------------------------------------
        struct ComponentInstance
        {
            typedef std::auto_ptr<ISubtree> Data;

            explicit
            ComponentInstance(Data _node, Data _template, Name const & _component)
            : m_node(_node)
            , m_template(_template)
            , m_component(_component)
            {
            }

            Data        const & data() const { return m_node; }
            Data        const & templateData() const { return m_template; }
            Name        const & component() const { return m_component; }

            ComponentData  componentTemplateData () const { return ComponentData(m_template,m_component);}
            ComponentData  componentNodeData () const { return ComponentData(m_node,m_component);}
            Data &  mutableData() { return m_node; }
            Data extractData() { return m_node; }
            Data extractTemplateData() { return m_template; }
        private:
            Data        m_node;
            Data        m_template;
            Name        m_component;
        };
// ---------------------------------------------------------------------------
        struct UpdateInstance
        {
            typedef SubtreeChange *         Data;
            typedef SubtreeChange const *   ConstData;

            explicit
            UpdateInstance(Data _update, AbsolutePath const & _rootpath)
            : m_update(_update)
            , m_root(_rootpath)
            {
            }

            UpdateInstance(UpdateInstance & _aModifiableOther)
            : m_update(_aModifiableOther.m_update)
            , m_root(_aModifiableOther.m_root)
            {
            }

            Data                data()       { return m_update; }
            ConstData           data() const { return m_update; }
            NodePath    const & root() const { return m_root; }
        private:
            Data        m_update;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
        struct ConstUpdateInstance
        {
            typedef UpdateInstance::ConstData   Data, ConstData;

            explicit
            ConstUpdateInstance(Data _update, AbsolutePath const & _rootpath)
            : m_update(_update)
            , m_root(_rootpath)
            {
            }

            // conversion
            ConstUpdateInstance(UpdateInstance const & _aModifiable)
            : m_update(_aModifiable.data())
            , m_root(_aModifiable.root())
            {
            }

            Data                data() const { return m_update; }
            NodePath    const & root() const { return m_root; }
        private:
            Data        m_update;
            NodePath    m_root;
        };
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Due to the use of auto_ptr, the XxxInstance classes cannot easily be used as return values
// To return them, they should be wrapped into a ResultHolder

        template <class Instance_>
        class ResultHolder
        {
            struct RCInstance : public salhelper::SimpleReferenceObject
            {
                RCInstance(Instance_ & _instance) : instance(_instance) {}
                Instance_ instance;
            };
            typedef rtl::Reference< RCInstance > InstanceRef;

            InstanceRef m_xInstance;
        public:
            typedef Instance_ Instance;

            explicit
            ResultHolder(Instance & _rInstance)
            : m_xInstance( new RCInstance(_rInstance) )
            {}

            bool isEmpty() const { return !m_xInstance.is(); }

            bool is() const { return m_xInstance.is() && m_xInstance->instance.data().get(); }

            Instance const & instance() const { return  m_xInstance->instance; }

            Instance const & operator *() const { return  instance(); }
            Instance const * operator->() const { return &instance(); }
            Instance & mutableInstance() { return m_xInstance->instance; }

            typename Instance::Data extractDataAndClear()
            {
                typename Instance::Data aData = m_xInstance->instance.extractData();
                this->clear();
                return aData;
            }

            void releaseAndClear()
            {
                typename Instance::Data aData = this->extractDataAndClear();
                aData.release();
            }

            void clear() { m_xInstance.clear(); }
        };
// ---------------------------------------------------------------------------
        typedef ResultHolder< NodeInstance >        NodeResult;
        typedef ResultHolder< TemplateInstance >    TemplateResult;
        typedef ResultHolder< ComponentInstance >   ComponentResult;

// ---------------------------------------------------------------------------
    }
// ---------------------------------------------------------------------------
} // namespace

#endif
<|endoftext|>


<commit_before>/**
 * @file /tip-server/src/tip/http/server/connection.cpp
 * @brief
 * @date Jul 8, 2015
 * @author: zmij
 */

#include <tip/http/server/connection.hpp>
#include <tip/http/server/request_handler.hpp>
#include <tip/http/server/remote_address.hpp>
#include <tip/http/server/reply_context.hpp>

#include <tip/http/common/request.hpp>
#include <tip/http/common/response.hpp>
#include <tip/http/common/grammar/response_generate.hpp>

#include <tip/http/version.hpp>

#include <tip/log.hpp>

#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/lexical_cast.hpp>

#include <vector>
#include <functional>
#include <chrono>

namespace tip {
namespace http {
namespace server {

LOCAL_LOGGING_FACILITY(HTTPCONN, TRACE);

const ::std::size_t LOG_MAX_REQUEST_BYTES = 500;

connection::connection(io_service_ptr io_service,
                       request_handler_ptr handler) :
	io_service_(io_service),
	strand_(*io_service),
	socket_(*io_service),
	request_handler_(handler),
	default_headers_{
		{ Server, "tip-http-server/" + tip::VERSION }
	}
{
}

connection::~connection()
{
}

boost::asio::ip::tcp::socket& connection::socket()
{
	return socket_;
}

void
connection::start(endpoint_ptr peer)
{
	local_log() << "Start new connection with " << peer->address();
	peer_ = peer;
	read_request_headers();
}

void
connection::read_request_headers()
{
	boost::asio::async_read_until(socket_, incoming_, "\r\n\r\n",
		strand_.wrap(std::bind(&connection::handle_read_headers,
			shared_from_this(),
			std::placeholders::_1, std::placeholders::_2)));
}

void
connection::handle_read_headers(const boost::system::error_code& e,
								std::size_t)
{
	if (!e) {
		std::istream is(&incoming_);
		request_ptr req = std::make_shared< request >();
		if (req->read_headers(is)) {
			read_request_body(req, req->read_body(is));
		} else {
			// Bad request
			send_error(req, response_status::bad_request);
			local_log(logger::ERROR) << "Error parsing headers";
		}
	} else {
		local_log(logger::DEBUG) << "Error reading request headers: "
				<< e.message();
	}
}

void
connection::read_request_body(request_ptr req, read_result_type res)
{
	using std::placeholders::_1;
	using std::placeholders::_2;
	if (res.result) {
		// success read
		io_service_ptr io = io_service_.lock();
		if (io) {
			req->start_ = boost::posix_time::microsec_clock::local_time();
			reply rep{
				io,
				req,
				strand_.wrap(std::bind(&connection::send_response,
						shared_from_this(), req, std::placeholders::_1)),
				strand_.wrap(std::bind(&connection::send_error,
						shared_from_this(), req, std::placeholders::_1))
			};
			add_context(rep, new remote_address(rep, peer_));
			try {
			request_handler_->handle_request(rep);
			} catch (::std::exception const& e) {
				local_log(logger::ERROR) << "Exception when dispatching request "
						<< req->path << ": " << e.what();
			} catch (...) {
				local_log(logger::ERROR) << "Unknown exception when dispatching request "
						<< req->path;
			}
		} else {
			local_log(logger::WARNING) << "IO service weak pointer is bad";
		}
	} else if (!res.result) {
		// fail read
		local_log(logger::WARNING) << "Failed to read request body";
		send_error(req, response_status::bad_request);
	} else if (res.callback) {
		boost::asio::async_read(socket_, incoming_,
			boost::asio::transfer_at_least(1),
			strand_.wrap( std::bind( &connection::handle_read_body,
				shared_from_this(), _1, _2, req, res.callback) ));
	} else {
		// need more data but no callback
		local_log(logger::WARNING) << "Request read body returned "
				"indeterminate, but provided no callback";
	}
}

void
connection::handle_read_body(const boost::system::error_code& e,
								std::size_t,
								request_ptr req,
								read_callback cb)
{
	if (!e) {
		std::istream is(&incoming_);
		read_request_body(req, cb(is));
	} else {
		local_log(logger::DEBUG) << "Error reading request body: "
				<< e.message();
	}

	// If an error occurs then no new asynchronous operations are started. This
	// means that all shared_ptr references to the connection object will
	// disappear and the object will be destroyed automatically after this
	// handler returns. The connection class's destructor closes the socket.
}

void
connection::send_response(request_ptr req, response_const_ptr resp)
{
	typedef std::vector< boost::asio::const_buffer > output_buffers_type;
	using std::placeholders::_1;
	using std::placeholders::_2;

	{
		auto proc_time = boost::posix_time::microsec_clock::local_time() - req->start_;
		if (proc_time.is_not_a_date_time()) {
			local_log() << req->method << " " << req->path
					<< " " << resp->status << " '" << resp->status_line << "' process time: 00:00:00.0";
		} else {
			local_log() << req->method << " " << req->path
					<< " " << resp->status << " '" << resp->status_line << "' process time: " << proc_time;
		}
	}
	if (is_error(resp->status) && (HTTPCONN_DEFAULT_SEVERITY != logger::OFF)) {
		local_log() << "Request headers:\n" << req->headers_;
		if (!req->body_.empty()) {
			::std::size_t bs = req->body_.size() < LOG_MAX_REQUEST_BYTES ?
					req->body_.size() : LOG_MAX_REQUEST_BYTES;
			::std::string body(req->body_.begin(), req->body_.begin() + bs);
			local_log() << "Request body (max " << LOG_MAX_REQUEST_BYTES << " bytes):\n"
					<< body;
		}
	}

	std::ostream os(&outgoing_);
	os << *resp;
	if (!resp->headers_.count(ContentLength)) {
		header content_length{
			ContentLength,
			boost::lexical_cast<std::string>( resp->body_.size() )
		};
		os << content_length;
	}
	if (!default_headers_.empty()) {
		os << default_headers_;
	}
	os << "\r\n";

	output_buffers_type buffers;
	buffers.push_back(boost::asio::buffer(outgoing_.data()));
	buffers.push_back(boost::asio::buffer(resp->body_));
	boost::asio::async_write(socket_, buffers,
		strand_.wrap(std::bind(&connection::handle_write_response,
			shared_from_this(), _1, _2, resp)));
}

void
connection::send_error(request_ptr req, response_status status)
{
	response_const_ptr resp = response::stock_response(status);
	send_response(req, resp);
}

void
connection::handle_write(const boost::system::error_code& e)
{
	if (!e) {
		// Initiate graceful connection closure.
		boost::system::error_code ignored_ec;
		socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
				ignored_ec);
	}

	// TODO Keep-Alive and timer
	// No new asynchronous operations are started. This means that all shared_ptr
	// references to the connection object will disappear and the object will be
	// destroyed automatically after this handler returns. The connection class's
	// destructor closes the socket.
}

void
connection::handle_write_response(boost::system::error_code const& e,
		size_t, response_const_ptr)
{
	if (!e) {
		// Initiate graceful connection closure.
		boost::system::error_code ignored_ec;
		socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
				ignored_ec);
	}

	// TODO Keep-Alive and timer
	// No new asynchronous operations are started. This means that all shared_ptr
	// references to the connection object will disappear and the object will be
	// destroyed automatically after this handler returns. The connection class's
	// destructor closes the socket.
}

} // namespace server
} // namespace http
}  // namespace tip
<commit_msg>Catch exceptions when trying to parse Content-Length header<commit_after>/**
 * @file /tip-server/src/tip/http/server/connection.cpp
 * @brief
 * @date Jul 8, 2015
 * @author: zmij
 */

#include <tip/http/server/connection.hpp>
#include <tip/http/server/request_handler.hpp>
#include <tip/http/server/remote_address.hpp>
#include <tip/http/server/reply_context.hpp>

#include <tip/http/common/request.hpp>
#include <tip/http/common/response.hpp>
#include <tip/http/common/grammar/response_generate.hpp>

#include <tip/http/version.hpp>

#include <tip/log.hpp>

#include <boost/date_time/posix_time/posix_time_io.hpp>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/lexical_cast.hpp>

#include <vector>
#include <functional>
#include <chrono>

namespace tip {
namespace http {
namespace server {

LOCAL_LOGGING_FACILITY(HTTPCONN, TRACE);

const ::std::size_t LOG_MAX_REQUEST_BYTES = 500;

connection::connection(io_service_ptr io_service,
                       request_handler_ptr handler) :
    io_service_(io_service),
    strand_(*io_service),
    socket_(*io_service),
    request_handler_(handler),
    default_headers_{
        { Server, "tip-http-server/" + tip::VERSION }
    }
{
}

connection::~connection()
{
}

boost::asio::ip::tcp::socket& connection::socket()
{
    return socket_;
}

void
connection::start(endpoint_ptr peer)
{
    local_log() << "Start new connection with " << peer->address();
    peer_ = peer;
    read_request_headers();
}

void
connection::read_request_headers()
{
    boost::asio::async_read_until(socket_, incoming_, "\r\n\r\n",
        strand_.wrap(std::bind(&connection::handle_read_headers,
            shared_from_this(),
            std::placeholders::_1, std::placeholders::_2)));
}

void
connection::handle_read_headers(const boost::system::error_code& e,
                                std::size_t)
{
    if (!e) {
        std::istream is(&incoming_);
        request_ptr req = std::make_shared< request >();
        if (req->read_headers(is)) {
            try {
                read_request_body(req, req->read_body(is));
            } catch (::std::exception const& e) {
                local_log(logger::ERROR) << "Error reading body: " << e.what();
                send_error(req, response_status::bad_request);
            }
        } else {
            // Bad request
            local_log(logger::ERROR) << "Error parsing headers";
            send_error(req, response_status::bad_request);
        }
    } else {
        local_log(logger::DEBUG) << "Error reading request headers: "
                << e.message();
    }
}

void
connection::read_request_body(request_ptr req, read_result_type res)
{
    using std::placeholders::_1;
    using std::placeholders::_2;
    if (res.result) {
        // success read
        io_service_ptr io = io_service_.lock();
        if (io) {
            req->start_ = boost::posix_time::microsec_clock::local_time();
            reply rep{
                io,
                req,
                strand_.wrap(std::bind(&connection::send_response,
                        shared_from_this(), req, std::placeholders::_1)),
                strand_.wrap(std::bind(&connection::send_error,
                        shared_from_this(), req, std::placeholders::_1))
            };
            add_context(rep, new remote_address(rep, peer_));
            try {
            request_handler_->handle_request(rep);
            } catch (::std::exception const& e) {
                local_log(logger::ERROR) << "Exception when dispatching request "
                        << req->path << ": " << e.what();
            } catch (...) {
                local_log(logger::ERROR) << "Unknown exception when dispatching request "
                        << req->path;
            }
        } else {
            local_log(logger::WARNING) << "IO service weak pointer is bad";
        }
    } else if (!res.result) {
        // fail read
        local_log(logger::WARNING) << "Failed to read request body";
        send_error(req, response_status::bad_request);
    } else if (res.callback) {
        boost::asio::async_read(socket_, incoming_,
            boost::asio::transfer_at_least(1),
            strand_.wrap( std::bind( &connection::handle_read_body,
                shared_from_this(), _1, _2, req, res.callback) ));
    } else {
        // need more data but no callback
        local_log(logger::WARNING) << "Request read body returned "
                "indeterminate, but provided no callback";
    }
}

void
connection::handle_read_body(const boost::system::error_code& e,
                                std::size_t,
                                request_ptr req,
                                read_callback cb)
{
    if (!e) {
        std::istream is(&incoming_);
        read_request_body(req, cb(is));
    } else {
        local_log(logger::DEBUG) << "Error reading request body: "
                << e.message();
    }

    // If an error occurs then no new asynchronous operations are started. This
    // means that all shared_ptr references to the connection object will
    // disappear and the object will be destroyed automatically after this
    // handler returns. The connection class's destructor closes the socket.
}

void
connection::send_response(request_ptr req, response_const_ptr resp)
{
    typedef std::vector< boost::asio::const_buffer > output_buffers_type;
    using std::placeholders::_1;
    using std::placeholders::_2;

    {
        auto proc_time = boost::posix_time::microsec_clock::local_time() - req->start_;
        if (proc_time.is_not_a_date_time()) {
            local_log() << req->method << " " << req->path
                    << " " << resp->status << " '" << resp->status_line << "' process time: 00:00:00.0";
        } else {
            local_log() << req->method << " " << req->path
                    << " " << resp->status << " '" << resp->status_line << "' process time: " << proc_time;
        }
    }
    if (is_error(resp->status) && (HTTPCONN_DEFAULT_SEVERITY != logger::OFF)) {
        local_log() << "Request headers:\n" << req->headers_;
        if (!req->body_.empty()) {
            ::std::size_t bs = req->body_.size() < LOG_MAX_REQUEST_BYTES ?
                    req->body_.size() : LOG_MAX_REQUEST_BYTES;
            ::std::string body(req->body_.begin(), req->body_.begin() + bs);
            local_log() << "Request body (max " << LOG_MAX_REQUEST_BYTES << " bytes):\n"
                    << body;
        }
    }

    std::ostream os(&outgoing_);
    os << *resp;
    if (!resp->headers_.count(ContentLength)) {
        header content_length{
            ContentLength,
            boost::lexical_cast<std::string>( resp->body_.size() )
        };
        os << content_length;
    }
    if (!default_headers_.empty()) {
        os << default_headers_;
    }
    os << "\r\n";

    output_buffers_type buffers;
    buffers.push_back(boost::asio::buffer(outgoing_.data()));
    buffers.push_back(boost::asio::buffer(resp->body_));
    boost::asio::async_write(socket_, buffers,
        strand_.wrap(std::bind(&connection::handle_write_response,
            shared_from_this(), _1, _2, resp)));
}

void
connection::send_error(request_ptr req, response_status status)
{
    response_const_ptr resp = response::stock_response(status);
    send_response(req, resp);
}

void
connection::handle_write(const boost::system::error_code& e)
{
    if (!e) {
        // Initiate graceful connection closure.
        boost::system::error_code ignored_ec;
        socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
                ignored_ec);
    }

    // TODO Keep-Alive and timer
    // No new asynchronous operations are started. This means that all shared_ptr
    // references to the connection object will disappear and the object will be
    // destroyed automatically after this handler returns. The connection class's
    // destructor closes the socket.
}

void
connection::handle_write_response(boost::system::error_code const& e,
        size_t, response_const_ptr)
{
    if (!e) {
        // Initiate graceful connection closure.
        boost::system::error_code ignored_ec;
        socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both,
                ignored_ec);
    }

    // TODO Keep-Alive and timer
    // No new asynchronous operations are started. This means that all shared_ptr
    // references to the connection object will disappear and the object will be
    // destroyed automatically after this handler returns. The connection class's
    // destructor closes the socket.
}

} // namespace server
} // namespace http
}  // namespace tip
<|endoftext|>


<commit_before>#include "bikecontroller.h"
// OSG
#include <osg/PositionAttitudeTransform>
#include <osgViewer/View>
//troen
#include "../constants.h"
#include "../view/bikeview.h"
#include "../view/nodefollowcameramanipulator.h"
#include "../model/bikemodel.h"
#include "../controller/fencecontroller.h"
#include "../controller/hudcontroller.h"
#include "../model/physicsworld.h"
#include "../sound/audiomanager.h"

#include "../input/keyboard.h"
#include "../input/gamepad.h"
#include "../input/gamepadps4.h"
#include "../input/ai.h"
#include "../input/pollingdevice.h"
#include "../globals.h"

#include "../resourcepool.h"

using namespace troen;

BikeController::BikeController(
	input::BikeInputState::InputDevice inputDevice,
	btTransform initialTransform,
	osg::Vec3 playerColor,
	ResourcePool *m_resourcePool,
	bool hasGameView) :
AbstractController(),
m_initialTransform(initialTransform),
m_hasGameView(hasGameView),
m_turboInitiated(false),
m_playerColor(playerColor),
m_health(BIKE_DEFAULT_HEALTH),
m_points(0),
m_speed(0),
m_timeOfLastCollision(-1),
m_currentState(BIKESTATE::WAITING),
m_respawnTime(-1),
m_keyboardHandler(nullptr),
m_pollingThread(nullptr)
{
	m_view = std::make_shared<BikeView>(m_playerColor, m_resourcePool);

	m_fenceController = std::make_shared<FenceController>(this, m_playerColor, m_initialTransform);

	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	m_model = std::make_shared<BikeModel>(m_initialTransform, viewNode, m_fenceController, this);

	initializeInput(inputDevice);
}

void BikeController::reset()
{
	if (m_pollingThread != nullptr)
		m_pollingThread->setVibration(false);

	removeAllFences();
	m_health = BIKE_DEFAULT_HEALTH;
	m_points = 0;
	m_timeOfLastCollision = -1;
}

void BikeController::registerCollision(btScalar impulse)
{
	if (impulse > 0) {
		m_timeOfLastCollision = g_currentTime;
	}
}

float BikeController::increaseHealth(float diff)
{
	m_health = clamp(0,BIKE_DEFAULT_HEALTH,m_health + diff);
	return m_health;
}

float BikeController::increasePoints(float diff)
{
	m_points += diff;
	return m_points;
}

BikeController::~BikeController()
{
	if (m_pollingThread != nullptr)
	{
		m_pollingThread->stop();
		m_pollingThread->wait();
	}
}

void BikeController::initializeInput(input::BikeInputState::InputDevice inputDevice)
{
	osg::ref_ptr<input::BikeInputState> bikeInputState = new input::BikeInputState();
	setInputState(bikeInputState);

	switch (inputDevice)
	{
	case input::BikeInputState::KEYBOARD_wasd:
	{
												 m_keyboardHandler = new input::Keyboard(bikeInputState, std::vector<osgGA::GUIEventAdapter::KeySymbol>{
													 osgGA::GUIEventAdapter::KEY_W,
														 osgGA::GUIEventAdapter::KEY_A,
														 osgGA::GUIEventAdapter::KEY_S,
														 osgGA::GUIEventAdapter::KEY_D,
														 osgGA::GUIEventAdapter::KEY_Space,
														 osgGA::GUIEventAdapter::KEY_G
												 });
												 break;
	}
	case input::BikeInputState::KEYBOARD_arrows:
	{
												   m_keyboardHandler = new input::Keyboard(bikeInputState, std::vector<osgGA::GUIEventAdapter::KeySymbol>{
													   osgGA::GUIEventAdapter::KEY_Up,
														   osgGA::GUIEventAdapter::KEY_Left,
														   osgGA::GUIEventAdapter::KEY_Down,
														   osgGA::GUIEventAdapter::KEY_Right,
														   osgGA::GUIEventAdapter::KEY_Control_R,
														   osgGA::GUIEventAdapter::KEY_M,
												   });
												   break;
	}
#ifdef WIN32
	case input::BikeInputState::GAMEPAD:
	{
										   std::shared_ptr<input::Gamepad> gamepad = std::make_shared<input::Gamepad>(bikeInputState);

										   if (gamepad->checkConnection())
										   {
											   std::cout << "[TroenGame::initializeInput] Gamepad connected on port " << gamepad->getPort() << std::endl;
										   }
										   else
										   {
											   std::cout << "[TroenGame::initializeInput] No gamepad connected!" << std::endl;
										   }
										   m_pollingThread = gamepad;
										   m_pollingThread->start();
										   break;
	}
#endif
	case input::BikeInputState::GAMEPADPS4:
	{
											  std::shared_ptr<input::GamepadPS4> gamepad = std::make_shared<input::GamepadPS4>(bikeInputState);

											  if (gamepad->checkConnection())
											  {
												  std::cout << "[TroenGame::initializeInput] PS4 Controller connected" << std::endl;
											  }
											  else
											  {
												  std::cout << "[TroenGame::initializeInput] No PS4 Controller connected!" << std::endl;
											  }
											  m_pollingThread = gamepad;
											  m_pollingThread->start();
											  break;
	}
	case input::BikeInputState::AI:
	{
									  std::shared_ptr<input::AI> ai = std::make_shared<input::AI>(bikeInputState);
									  m_pollingThread = ai;
									  m_pollingThread->start();
									  break;
	}
	default:
		break;
	}
}

osg::ref_ptr<input::Keyboard> BikeController::getKeyboardHandler()
{
	return m_keyboardHandler;
}

bool BikeController::hasKeyboardHandler()
{
	return m_keyboardHandler != nullptr;
}

void BikeController::setInputState(osg::ref_ptr<input::BikeInputState> bikeInputState)
{
	std::static_pointer_cast<BikeModel>(m_model)->setInputState(bikeInputState);
}

void BikeController::attachTrackingCameras(
	osg::ref_ptr<NodeFollowCameraManipulator>& manipulator,
	std::shared_ptr<HUDController>& hudController)
{
	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (viewNode->getChild(0));

	// set the actual node as the track node, not the pat
	manipulator->setTrackNode(pat->getChild(0));
	if (hudController != nullptr)
		hudController->setTrackNode(pat->getChild(0));

	// set camera position
	manipulator->setHomePosition(
		CAMERA_EYE_POSITION, // homeEye
		osg::Vec3f(), // homeCenter
		osg::Z_AXIS, // up
		false
		);
}
void BikeController::attachTrackingCamera(osg::ref_ptr<NodeFollowCameraManipulator>& manipulator)
{
	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (viewNode->getChild(0));

	// set the actual node as the track node, not the pat
	manipulator->setTrackNode(pat->getChild(0));

	// set camera position
	manipulator->setHomePosition(
		CAMERA_EYE_POSITION, // homeEye
		osg::Vec3f(), // homeCenter
		osg::Z_AXIS, // up
		false
		);
}

void BikeController::attachGameView(osg::ref_ptr<osgViewer::View> gameView)
{
	m_gameView = gameView;
}

void BikeController::setFovy(float newFovy)
{
	if (!m_gameView.valid()) return;
	double fovy, aspect, znear, zfar;
	m_gameView->getCamera()->getProjectionMatrixAsPerspective(fovy, aspect, znear, zfar);
	m_gameView->getCamera()->setProjectionMatrixAsPerspective(newFovy, aspect, znear, zfar);
}

float BikeController::getFovy()
{
	if (!m_gameView.valid())
		return 0;
	double fovy, aspect, znear, zfar;
	m_gameView->getCamera()->getProjectionMatrixAsPerspective(fovy, aspect, znear, zfar);
	return fovy;
}

float BikeController::computeFovyDelta(float speed, float currentFovy)
{
	long double timeSinceLastUpdate = std::static_pointer_cast<BikeModel>(m_model)->getTimeSinceLastUpdate();
	long double timeFactor = timeSinceLastUpdate / 16.7f;

	m_speed = speed;

	float fovyFactor = (speed - BIKE_VELOCITY_MIN) / (BIKE_VELOCITY_MAX - BIKE_VELOCITY_MIN);
	fovyFactor = fovyFactor > 0 ? fovyFactor : 0;
	float newFovy = FOVY_INITIAL + interpolate(fovyFactor, InterpolateCubed) * FOVY_ADDITION_MAX;

	const float fovyDampening = 20.f;
	float fovyDelta = (newFovy - currentFovy) / fovyDampening * timeFactor;
	return clamp(-FOVY_DELTA_MAX, FOVY_DELTA_MAX, fovyDelta);
}

float BikeController::getSpeed()
{
	return m_speed;
}

float BikeController::getHealth()
{
	return m_health;
}

float BikeController::getPoints()
{
	return m_points;
}

void BikeController::activateTurbo()
{
	m_turboInitiated = true;
}

float BikeController::getTurboInitiation()
{
	return m_turboInitiated;
}

void BikeController::setState(BIKESTATE newState, double respawnTime /*=-1*/)
{
	m_currentState = newState;
	m_respawnTime = respawnTime;
}

void BikeController::updateModel(long double time)
{
	switch (m_currentState)
	{
	case DRIVING:
	{
		double speed = std::static_pointer_cast<BikeModel>(m_model)->updateState(time);
		increasePoints(speed / 1000);
		updateFov(speed);
		break;
	}
	case RESPAWN:
	{
		std::static_pointer_cast<BikeModel>(m_model)->freeze();
		updateFov(0);
		if (time > m_respawnTime + RESPAWN_DURATION*2.f/3.f)
		{
			//osg::Quat attitude = btToOSGQuat(m_initialTransform.getRotation());
			//std::static_pointer_cast<BikeView>(m_view)->m_pat->setAttitude(attitude);
			moveBikeToPosition(m_initialTransform);
			m_currentState = RESPAWN_PART_2;
		}
		break;
	}
	case RESPAWN_PART_2:
	{
		reset();
		updateFov(0);
		if (time > m_respawnTime + RESPAWN_DURATION)
		{
			m_currentState = DRIVING;
		}
		break;
	}
	case WAITING_FOR_GAMESTART:
	case WAITING:
		break;
	default:
		break;
	}

	// turbo should be only applied in one frame
	if (m_turboInitiated)
		m_turboInitiated = false;

	if (m_pollingThread != nullptr)
	{
		m_pollingThread->setVibration(m_timeOfLastCollision != -1 && g_currentTime - m_timeOfLastCollision < VIBRATION_TIME_MS);
	}

	updateUniforms();

}

osg::ref_ptr<osg::Group> BikeController::getViewNode()
{
	osg::ref_ptr<osg::Group> group = new osg::Group();
	// TODO (dw) try not to disable culling, by resizing the childrens bounding boxes
	group->setCullingActive(false);
	group->addChild(m_fenceController->getViewNode());
	group->addChild(std::static_pointer_cast<BikeView>(m_view)->getNode());
	return group;
};

void BikeController::setPlayerNode(osg::Group* playerNode)
{
	// this is the node which holds the rootNode of the entire scene
	// it is used to expose player specific information to the shaders
	// this is only necessary if a gameView exists for this player

	m_playerNode = playerNode;
	m_timeOfCollisionUniform = new osg::Uniform("timeSinceLastHit", 100000.f);
	m_playerNode->getOrCreateStateSet()->addUniform(m_timeOfCollisionUniform);

}

void BikeController::attachWorld(std::shared_ptr<PhysicsWorld> &world) {
	world->addRigidBodies(getRigidBodies(), COLGROUP_BIKE, COLMASK_BIKE);
	m_fenceController->attachWorld(world);
}

void BikeController::removeAllFences()
{
	m_fenceController->removeAllFences();
}

void BikeController::setLimitFence(bool boolean)
{
	m_fenceLimitActivated = boolean;
}

int BikeController::getFenceLimit() {
	if (m_fenceLimitActivated)
		return getPoints();
	else
		return 0;
}

void BikeController::moveBikeToPosition(btTransform transform)
{
	std::static_pointer_cast<BikeModel>(m_model)->moveBikeToPosition(transform);
	m_fenceController->setLastPosition(transform.getRotation(), transform.getOrigin());
}

osg::ref_ptr<osgViewer::View> BikeController::getGameView()
{
	return m_gameView;
};

void BikeController::updateUniforms()
{
	if (m_hasGameView) {
		m_timeOfCollisionUniform->set((float)g_currentTime - m_timeOfLastCollision);
	}
}

void BikeController::updateFov(double speed)
{
	if (m_gameView.valid()) {
		float currentFovy = getFovy();
		setFovy(currentFovy + computeFovyDelta(speed, currentFovy));
	}
}

BikeController::BIKESTATE BikeController::getState()
{
	return m_currentState;
}

double BikeController::getRespawnTime()
{
	return m_respawnTime;
}<commit_msg>fix on collision after bike "death"<commit_after>#include "bikecontroller.h"
// OSG
#include <osg/PositionAttitudeTransform>
#include <osgViewer/View>
//troen
#include "../constants.h"
#include "../view/bikeview.h"
#include "../view/nodefollowcameramanipulator.h"
#include "../model/bikemodel.h"
#include "../controller/fencecontroller.h"
#include "../controller/hudcontroller.h"
#include "../model/physicsworld.h"
#include "../sound/audiomanager.h"

#include "../input/keyboard.h"
#include "../input/gamepad.h"
#include "../input/gamepadps4.h"
#include "../input/ai.h"
#include "../input/pollingdevice.h"
#include "../globals.h"

#include "../resourcepool.h"

using namespace troen;

BikeController::BikeController(
	input::BikeInputState::InputDevice inputDevice,
	btTransform initialTransform,
	osg::Vec3 playerColor,
	ResourcePool *m_resourcePool,
	bool hasGameView) :
AbstractController(),
m_initialTransform(initialTransform),
m_hasGameView(hasGameView),
m_turboInitiated(false),
m_playerColor(playerColor),
m_health(BIKE_DEFAULT_HEALTH),
m_points(0),
m_speed(0),
m_timeOfLastCollision(-1),
m_currentState(BIKESTATE::WAITING),
m_respawnTime(-1),
m_keyboardHandler(nullptr),
m_pollingThread(nullptr)
{
	m_view = std::make_shared<BikeView>(m_playerColor, m_resourcePool);

	m_fenceController = std::make_shared<FenceController>(this, m_playerColor, m_initialTransform);

	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	m_model = std::make_shared<BikeModel>(m_initialTransform, viewNode, m_fenceController, this);

	initializeInput(inputDevice);
}

void BikeController::reset()
{
	if (m_pollingThread != nullptr)
		m_pollingThread->setVibration(false);

	removeAllFences();
	m_health = BIKE_DEFAULT_HEALTH;
	m_points = 0;
	m_timeOfLastCollision = -1;
}

void BikeController::registerCollision(btScalar impulse)
{
	if (impulse > 0) {
		m_timeOfLastCollision = g_currentTime;
	}
}

float BikeController::increaseHealth(float diff)
{
	m_health = clamp(0,BIKE_DEFAULT_HEALTH,m_health + diff);
	return m_health;
}

float BikeController::increasePoints(float diff)
{
	m_points += diff;
	return m_points;
}

BikeController::~BikeController()
{
	if (m_pollingThread != nullptr)
	{
		m_pollingThread->stop();
		m_pollingThread->wait();
	}
}

void BikeController::initializeInput(input::BikeInputState::InputDevice inputDevice)
{
	osg::ref_ptr<input::BikeInputState> bikeInputState = new input::BikeInputState();
	setInputState(bikeInputState);

	switch (inputDevice)
	{
	case input::BikeInputState::KEYBOARD_wasd:
	{
												 m_keyboardHandler = new input::Keyboard(bikeInputState, std::vector<osgGA::GUIEventAdapter::KeySymbol>{
													 osgGA::GUIEventAdapter::KEY_W,
														 osgGA::GUIEventAdapter::KEY_A,
														 osgGA::GUIEventAdapter::KEY_S,
														 osgGA::GUIEventAdapter::KEY_D,
														 osgGA::GUIEventAdapter::KEY_Space,
														 osgGA::GUIEventAdapter::KEY_G
												 });
												 break;
	}
	case input::BikeInputState::KEYBOARD_arrows:
	{
												   m_keyboardHandler = new input::Keyboard(bikeInputState, std::vector<osgGA::GUIEventAdapter::KeySymbol>{
													   osgGA::GUIEventAdapter::KEY_Up,
														   osgGA::GUIEventAdapter::KEY_Left,
														   osgGA::GUIEventAdapter::KEY_Down,
														   osgGA::GUIEventAdapter::KEY_Right,
														   osgGA::GUIEventAdapter::KEY_Control_R,
														   osgGA::GUIEventAdapter::KEY_M,
												   });
												   break;
	}
#ifdef WIN32
	case input::BikeInputState::GAMEPAD:
	{
										   std::shared_ptr<input::Gamepad> gamepad = std::make_shared<input::Gamepad>(bikeInputState);

										   if (gamepad->checkConnection())
										   {
											   std::cout << "[TroenGame::initializeInput] Gamepad connected on port " << gamepad->getPort() << std::endl;
										   }
										   else
										   {
											   std::cout << "[TroenGame::initializeInput] No gamepad connected!" << std::endl;
										   }
										   m_pollingThread = gamepad;
										   m_pollingThread->start();
										   break;
	}
#endif
	case input::BikeInputState::GAMEPADPS4:
	{
											  std::shared_ptr<input::GamepadPS4> gamepad = std::make_shared<input::GamepadPS4>(bikeInputState);

											  if (gamepad->checkConnection())
											  {
												  std::cout << "[TroenGame::initializeInput] PS4 Controller connected" << std::endl;
											  }
											  else
											  {
												  std::cout << "[TroenGame::initializeInput] No PS4 Controller connected!" << std::endl;
											  }
											  m_pollingThread = gamepad;
											  m_pollingThread->start();
											  break;
	}
	case input::BikeInputState::AI:
	{
									  std::shared_ptr<input::AI> ai = std::make_shared<input::AI>(bikeInputState);
									  m_pollingThread = ai;
									  m_pollingThread->start();
									  break;
	}
	default:
		break;
	}
}

osg::ref_ptr<input::Keyboard> BikeController::getKeyboardHandler()
{
	return m_keyboardHandler;
}

bool BikeController::hasKeyboardHandler()
{
	return m_keyboardHandler != nullptr;
}

void BikeController::setInputState(osg::ref_ptr<input::BikeInputState> bikeInputState)
{
	std::static_pointer_cast<BikeModel>(m_model)->setInputState(bikeInputState);
}

void BikeController::attachTrackingCameras(
	osg::ref_ptr<NodeFollowCameraManipulator>& manipulator,
	std::shared_ptr<HUDController>& hudController)
{
	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (viewNode->getChild(0));

	// set the actual node as the track node, not the pat
	manipulator->setTrackNode(pat->getChild(0));
	if (hudController != nullptr)
		hudController->setTrackNode(pat->getChild(0));

	// set camera position
	manipulator->setHomePosition(
		CAMERA_EYE_POSITION, // homeEye
		osg::Vec3f(), // homeCenter
		osg::Z_AXIS, // up
		false
		);
}
void BikeController::attachTrackingCamera(osg::ref_ptr<NodeFollowCameraManipulator>& manipulator)
{
	osg::ref_ptr<osg::Group> viewNode = std::static_pointer_cast<BikeView>(m_view)->getNode();
	osg::PositionAttitudeTransform* pat = dynamic_cast<osg::PositionAttitudeTransform*> (viewNode->getChild(0));

	// set the actual node as the track node, not the pat
	manipulator->setTrackNode(pat->getChild(0));

	// set camera position
	manipulator->setHomePosition(
		CAMERA_EYE_POSITION, // homeEye
		osg::Vec3f(), // homeCenter
		osg::Z_AXIS, // up
		false
		);
}

void BikeController::attachGameView(osg::ref_ptr<osgViewer::View> gameView)
{
	m_gameView = gameView;
}

void BikeController::setFovy(float newFovy)
{
	if (!m_gameView.valid()) return;
	double fovy, aspect, znear, zfar;
	m_gameView->getCamera()->getProjectionMatrixAsPerspective(fovy, aspect, znear, zfar);
	m_gameView->getCamera()->setProjectionMatrixAsPerspective(newFovy, aspect, znear, zfar);
}

float BikeController::getFovy()
{
	if (!m_gameView.valid())
		return 0;
	double fovy, aspect, znear, zfar;
	m_gameView->getCamera()->getProjectionMatrixAsPerspective(fovy, aspect, znear, zfar);
	return fovy;
}

float BikeController::computeFovyDelta(float speed, float currentFovy)
{
	long double timeSinceLastUpdate = std::static_pointer_cast<BikeModel>(m_model)->getTimeSinceLastUpdate();
	long double timeFactor = timeSinceLastUpdate / 16.7f;

	m_speed = speed;

	float fovyFactor = (speed - BIKE_VELOCITY_MIN) / (BIKE_VELOCITY_MAX - BIKE_VELOCITY_MIN);
	fovyFactor = fovyFactor > 0 ? fovyFactor : 0;
	float newFovy = FOVY_INITIAL + interpolate(fovyFactor, InterpolateCubed) * FOVY_ADDITION_MAX;

	const float fovyDampening = 20.f;
	float fovyDelta = (newFovy - currentFovy) / fovyDampening * timeFactor;
	return clamp(-FOVY_DELTA_MAX, FOVY_DELTA_MAX, fovyDelta);
}

float BikeController::getSpeed()
{
	return m_speed;
}

float BikeController::getHealth()
{
	return m_health;
}

float BikeController::getPoints()
{
	return m_points;
}

void BikeController::activateTurbo()
{
	m_turboInitiated = true;
}

float BikeController::getTurboInitiation()
{
	return m_turboInitiated;
}

void BikeController::setState(BIKESTATE newState, double respawnTime /*=-1*/)
{
	if (m_currentState == newState)
		return;

	m_currentState = newState;
	m_respawnTime = respawnTime;
}

void BikeController::updateModel(long double time)
{
	switch (m_currentState)
	{
	case DRIVING:
	{
		double speed = std::static_pointer_cast<BikeModel>(m_model)->updateState(time);
		increasePoints(speed / 1000);
		updateFov(speed);
		break;
	}
	case RESPAWN:
	{
		std::static_pointer_cast<BikeModel>(m_model)->freeze();
		updateFov(0);
		if (time > m_respawnTime + RESPAWN_DURATION*2.f/3.f)
		{
			//osg::Quat attitude = btToOSGQuat(m_initialTransform.getRotation());
			//std::static_pointer_cast<BikeView>(m_view)->m_pat->setAttitude(attitude);
			moveBikeToPosition(m_initialTransform);
			m_currentState = RESPAWN_PART_2;
		}
		break;
	}
	case RESPAWN_PART_2:
	{
		reset();
		updateFov(0);
		if (time > m_respawnTime + RESPAWN_DURATION)
		{
			m_currentState = DRIVING;
		}
		break;
	}
	case WAITING_FOR_GAMESTART:
	case WAITING:
		break;
	default:
		break;
	}

	// turbo should be only applied in one frame
	if (m_turboInitiated)
		m_turboInitiated = false;

	if (m_pollingThread != nullptr)
	{
		m_pollingThread->setVibration(m_timeOfLastCollision != -1 && g_currentTime - m_timeOfLastCollision < VIBRATION_TIME_MS);
	}

	updateUniforms();

}

osg::ref_ptr<osg::Group> BikeController::getViewNode()
{
	osg::ref_ptr<osg::Group> group = new osg::Group();
	// TODO (dw) try not to disable culling, by resizing the childrens bounding boxes
	group->setCullingActive(false);
	group->addChild(m_fenceController->getViewNode());
	group->addChild(std::static_pointer_cast<BikeView>(m_view)->getNode());
	return group;
};

void BikeController::setPlayerNode(osg::Group* playerNode)
{
	// this is the node which holds the rootNode of the entire scene
	// it is used to expose player specific information to the shaders
	// this is only necessary if a gameView exists for this player

	m_playerNode = playerNode;
	m_timeOfCollisionUniform = new osg::Uniform("timeSinceLastHit", 100000.f);
	m_playerNode->getOrCreateStateSet()->addUniform(m_timeOfCollisionUniform);

}

void BikeController::attachWorld(std::shared_ptr<PhysicsWorld> &world) {
	world->addRigidBodies(getRigidBodies(), COLGROUP_BIKE, COLMASK_BIKE);
	m_fenceController->attachWorld(world);
}

void BikeController::removeAllFences()
{
	m_fenceController->removeAllFences();
}

void BikeController::setLimitFence(bool boolean)
{
	m_fenceLimitActivated = boolean;
}

int BikeController::getFenceLimit() {
	if (m_fenceLimitActivated)
		return getPoints();
	else
		return 0;
}

void BikeController::moveBikeToPosition(btTransform transform)
{
	std::static_pointer_cast<BikeModel>(m_model)->moveBikeToPosition(transform);
	m_fenceController->setLastPosition(transform.getRotation(), transform.getOrigin());
}

osg::ref_ptr<osgViewer::View> BikeController::getGameView()
{
	return m_gameView;
};

void BikeController::updateUniforms()
{
	if (m_hasGameView) {
		m_timeOfCollisionUniform->set((float)g_currentTime - m_timeOfLastCollision);
	}
}

void BikeController::updateFov(double speed)
{
	if (m_gameView.valid()) {
		float currentFovy = getFovy();
		setFovy(currentFovy + computeFovyDelta(speed, currentFovy));
	}
}

BikeController::BIKESTATE BikeController::getState()
{
	return m_currentState;
}

double BikeController::getRespawnTime()
{
	return m_respawnTime;
}<|endoftext|>