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

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkTestingMacros.h"

#include "mitkSceneIO.h"

#include "mitkStandaloneDataStorage.h"
#include "mitkStandardFileLocations.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkCoreObjectFactory.h"
#include "mitkBaseData.h"
#include "mitkImage.h"
#include "mitkSurface.h"

class SceneIOTestClass
{
  public:

/// returns full path to a test file
static std::string LocateFile(const std::string& filename)
{
  mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance();
  MITK_TEST_CONDITION_REQUIRED(locator.IsNotNull(),"Instantiating StandardFileLocations")
  return locator->FindFile(filename.c_str(), "Core/Code/Testing/Data");
}

static mitk::BaseData::Pointer LoadBaseData(const std::string& filename)
{
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    factory->SetFileName( filename );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'");
    }

    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    return node->GetData();
  }
  catch ( itk::ExceptionObject & e )
  {
    MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what());
  }
}

static mitk::Image::Pointer LoadImage(const std::string& filename)
{
  mitk::BaseData::Pointer basedata = LoadBaseData( filename );
  mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(basedata.GetPointer());
  if(image.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "Test image '" << filename << "' was not loaded as an mitk::Image");
  }
  return image;
}

static mitk::Surface::Pointer LoadSurface(const std::string& filename)
{
  mitk::BaseData::Pointer basedata = LoadBaseData( filename );
  mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(basedata.GetPointer());
  if(surface.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "Test surface '" << filename << "' was not loaded as an mitk::Surface");
  }
  return surface;
}

static void FillStorage(mitk::DataStorage* storage)
{
  mitk::Image::Pointer image = LoadImage( LocateFile("Pic3D.pic.gz") );
  MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image Pic3D.pic.gz");

  image->SetProperty("image type", mitk::StringProperty::New("test image") );
  image->SetProperty("greetings", mitk::StringProperty::New("to mom") );

  mitk::DataTreeNode::Pointer imagenode = mitk::DataTreeNode::New();
  imagenode->SetData( image );
  imagenode->SetName( "Pic3D" );
  storage->Add( imagenode );

  mitk::Surface::Pointer surface = LoadSurface( LocateFile("binary.stl") );
  MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface binary.stl");

  surface->SetProperty("surface type", mitk::StringProperty::New("test surface") );
  surface->SetProperty("greetings", mitk::StringProperty::New("to dad") );

  mitk::DataTreeNode::Pointer surfacenode = mitk::DataTreeNode::New();
  surfacenode->SetData( surface );
  surfacenode->SetName( "binary" );
  storage->Add( surfacenode );
}

}; // end test helper class

int mitkSceneIOTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("SceneIO")

  itk::ObjectFactoryBase::RegisterFactory(mitk::CoreObjectFactory::New());

  mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New();
  MITK_TEST_CONDITION_REQUIRED(sceneIO.IsNotNull(),"SceneIO instantiation")

  mitk::DataStorage::Pointer storage = mitk::StandaloneDataStorage::New().GetPointer();
  MITK_TEST_CONDITION_REQUIRED(storage.IsNotNull(),"StandaloneDataStorage instantiation");

  SceneIOTestClass::FillStorage(storage);

  MITK_TEST_CONDITION_REQUIRED( sceneIO->SaveScene( storage->GetAll(), storage, "scene.zip" ),
                                "Saving scene file" );

  mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes();
  if (failedNodes.IsNotNull())
  {
    MITK_TEST_OUTPUT( << "The following nodes could not be serialized:");
    for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin();
          iter != failedNodes->end();
          ++iter )
    {
      MITK_TEST_OUTPUT_NO_ENDL( << " - ");
      if ( mitk::BaseData* data =(*iter)->GetData() )
      {
        MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass());
      }
      else
      {
        MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)");
      }

      MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'");
      // \TODO: should we fail the test case if failed properties exist?
    }
  }

  mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties();
  if (failedProperties.IsNotNull())
  {
    std::cout << "The following properties could not be serialized:" << std::endl;
    const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap();
    for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin();
          iter != propmap->end();
          ++iter )
    {
      MITK_TEST_OUTPUT( << " - " << iter->second.first->GetNameOfClass() << " associated to key '" << iter->first << "'");
      // \TODO: should we fail the test case if failed properties exist?
    }
  }
  MITK_TEST_END()
}
<commit_msg>ENH (#2185): add a PointSet for SceneSerialization. FIX: write scene to TEMP directory, not to binary directory.<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile: mitkPropertyManager.cpp,v $
Language:  C++
Date:      $Date$
Version:   $Revision: 1.12 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

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

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

#include "mitkTestingMacros.h"

#include "mitkSceneIO.h"

#include "mitkStandaloneDataStorage.h"
#include "mitkStandardFileLocations.h"
#include "mitkDataTreeNodeFactory.h"
#include "mitkCoreObjectFactory.h"
#include "mitkBaseData.h"
#include "mitkImage.h"
#include "mitkSurface.h"
#include "mitkPointSet.h"
#include "Poco/File.h"
#include "Poco/TemporaryFile.h"

class SceneIOTestClass
{
  public:

/// returns full path to a test file
static std::string LocateFile(const std::string& filename)
{
  mitk::StandardFileLocations::Pointer locator = mitk::StandardFileLocations::GetInstance();
  MITK_TEST_CONDITION_REQUIRED(locator.IsNotNull(),"Instantiating StandardFileLocations")
  return locator->FindFile(filename.c_str(), "Core/Code/Testing/Data");
}

static mitk::BaseData::Pointer LoadBaseData(const std::string& filename)
{
  mitk::DataTreeNodeFactory::Pointer factory = mitk::DataTreeNodeFactory::New();
  try
  {
    factory->SetFileName( filename );
    factory->Update();

    if(factory->GetNumberOfOutputs()<1)
    {
      MITK_TEST_FAILED_MSG(<< "Could not find test data '" << filename << "'");
    }

    mitk::DataTreeNode::Pointer node = factory->GetOutput( 0 );
    return node->GetData();
  }
  catch ( itk::ExceptionObject & e )
  {
    MITK_TEST_FAILED_MSG(<< "Failed loading test data '" << filename << "': " << e.what());
  }
}

static mitk::Image::Pointer LoadImage(const std::string& filename)
{
  mitk::BaseData::Pointer basedata = LoadBaseData( filename );
  mitk::Image::Pointer image = dynamic_cast<mitk::Image*>(basedata.GetPointer());
  if(image.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "Test image '" << filename << "' was not loaded as an mitk::Image");
  }
  return image;
}

static mitk::Surface::Pointer LoadSurface(const std::string& filename)
{
  mitk::BaseData::Pointer basedata = LoadBaseData( filename );
  mitk::Surface::Pointer surface = dynamic_cast<mitk::Surface*>(basedata.GetPointer());
  if(surface.IsNull())
  {
    MITK_TEST_FAILED_MSG(<< "Test surface '" << filename << "' was not loaded as an mitk::Surface");
  }
  return surface;
}

static mitk::PointSet::Pointer CreatePointSet()
{

  mitk::PointSet::Pointer ps = mitk::PointSet::New();
  mitk::PointSet::PointType p;
  mitk::FillVector3D(p, 1.1, -2.22, 33.33);
  ps->SetPoint(0, p);
  mitk::FillVector3D(p, 100.1, -200.22, 3300.33);
  ps->SetPoint(1, p);
  mitk::FillVector3D(p, 2.0, -3.0, 22.22);
  ps->SetPoint(2, p, mitk::PTCORNER); // add point spec
  //mitk::FillVector3D(p, -2.0, -2.0, -2.22);
  //ps->SetPoint(0, p, 1); // ID 0 in timestep 1
  //mitk::FillVector3D(p, -1.0, -1.0, -11.22);
  //ps->SetPoint(1, p, 1); // ID 1 in timestep 1
  //mitk::FillVector3D(p, 1000.0, 1000.0, 1122.22);
  //ps->SetPoint(11, p, mitk::PTCORNER, 2); // ID 11, point spec, timestep 2
  //return ps;
}

static void FillStorage(mitk::DataStorage* storage)
{
  mitk::Image::Pointer image = LoadImage( LocateFile("Pic3D.pic.gz") );
  MITK_TEST_CONDITION_REQUIRED(image.IsNotNull(),"Loading test image Pic3D.pic.gz");

  image->SetProperty("image type", mitk::StringProperty::New("test image") );
  image->SetProperty("greetings", mitk::StringProperty::New("to mom") );

  mitk::DataTreeNode::Pointer imagenode = mitk::DataTreeNode::New();
  imagenode->SetData( image );
  imagenode->SetName( "Pic3D" );
  storage->Add( imagenode );

  mitk::Surface::Pointer surface = LoadSurface( LocateFile("binary.stl") );
  MITK_TEST_CONDITION_REQUIRED(surface.IsNotNull(),"Loading test surface binary.stl");

  surface->SetProperty("surface type", mitk::StringProperty::New("test surface") );
  surface->SetProperty("greetings", mitk::StringProperty::New("to dad") );

  mitk::DataTreeNode::Pointer surfacenode = mitk::DataTreeNode::New();
  surfacenode->SetData( surface );
  surfacenode->SetName( "binary" );
  storage->Add( surfacenode );

  mitk::PointSet::Pointer ps = CreatePointSet();
  mitk::DataTreeNode::Pointer psenode = mitk::DataTreeNode::New();
  surfacenode->SetData( ps );
  surfacenode->SetName( "points" );
  storage->Add( psenode );

}

}; // end test helper class

int mitkSceneIOTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("SceneIO")

  itk::ObjectFactoryBase::RegisterFactory(mitk::CoreObjectFactory::New());

  mitk::SceneIO::Pointer sceneIO = mitk::SceneIO::New();
  MITK_TEST_CONDITION_REQUIRED(sceneIO.IsNotNull(),"SceneIO instantiation")

  mitk::DataStorage::Pointer storage = mitk::StandaloneDataStorage::New().GetPointer();
  MITK_TEST_CONDITION_REQUIRED(storage.IsNotNull(),"StandaloneDataStorage instantiation");

  SceneIOTestClass::FillStorage(storage);

  std::string  sceneFileName = Poco::Path::temp() + /*Poco::Path::separator() +*/ "scene.zip";
  MITK_TEST_CONDITION_REQUIRED( sceneIO->SaveScene( storage->GetAll(), storage, sceneFileName), "Saving scene file '" << sceneFileName << "'");

  mitk::SceneIO::FailedBaseDataListType::ConstPointer failedNodes = sceneIO->GetFailedNodes();
  if (failedNodes.IsNotNull())
  {
    MITK_TEST_OUTPUT( << "The following nodes could not be serialized:");
    for ( mitk::SceneIO::FailedBaseDataListType::const_iterator iter = failedNodes->begin();
          iter != failedNodes->end();
          ++iter )
    {
      MITK_TEST_OUTPUT_NO_ENDL( << " - ");
      if ( mitk::BaseData* data =(*iter)->GetData() )
      {
        MITK_TEST_OUTPUT_NO_ENDL( << data->GetNameOfClass());
      }
      else
      {
        MITK_TEST_OUTPUT_NO_ENDL( << "(NULL)");
      }

      MITK_TEST_OUTPUT( << " contained in node '" << (*iter)->GetName() << "'");
      // \TODO: should we fail the test case if failed properties exist?
    }
  }

  mitk::PropertyList::ConstPointer failedProperties = sceneIO->GetFailedProperties();
  if (failedProperties.IsNotNull())
  {
    std::cout << "The following properties could not be serialized:" << std::endl;
    const mitk::PropertyList::PropertyMap* propmap = failedProperties->GetMap();
    for ( mitk::PropertyList::PropertyMap::const_iterator iter = propmap->begin();
          iter != propmap->end();
          ++iter )
    {
      MITK_TEST_OUTPUT( << " - " << iter->second.first->GetNameOfClass() << " associated to key '" << iter->first << "'");
      // \TODO: should we fail the test case if failed properties exist?
    }
  }
  MITK_TEST_END()
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <spv_utils.h>
#include <cstdint>

int main() {
  // Read spv binary module from a file
  std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary |
                         std::ios::ate | std::ios::in);
  if (spv_file.is_open()) {
    std::streampos size = spv_file.tellg();

    spv_file.seekg(0, std::ios::beg);
    char *data = new char[size];
    spv_file.read(data, size);
    spv_file.close();

    // Parse the module
    sut::OpcodeStream stream(data, size);
    for (auto &i : stream) {
      if (i.GetOpcode() == spv::Op::OpCapability) {
        uint32_t instruction = 0xDEADBEEF;
        i.InsertAfter(&instruction, 1U);
        i.Remove();
      }
    }
    std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream();

    delete[] data;
    data = nullptr;
  }

  return 0;
};
<commit_msg>Add longer instruction test to sample<commit_after>#include <iostream>
#include <fstream>
#include <spv_utils.h>
#include <cstdint>

int main() {
  // Read spv binary module from a file
  std::ifstream spv_file("../sample_spv_modules/test.frag.spv", std::ios::binary |
                         std::ios::ate | std::ios::in);
  if (spv_file.is_open()) {
    std::streampos size = spv_file.tellg();

    spv_file.seekg(0, std::ios::beg);
    char *data = new char[size];
    spv_file.read(data, size);
    spv_file.close();

    // Parse the module
    sut::OpcodeStream stream(data, size);
    for (auto &i : stream) {
      if (i.GetOpcode() == spv::Op::OpCapability) {
        uint32_t instruction = 0xDEADBEEF;
        std::vector<uint32_t> longer_instruction = {
          0xFFFFEEEE,
          0xFFFFDDDD,
          0xFFFFFFFF,
          0xDEADBEEF
        };
        uint32_t instruction2 = 0xDEADBEEF;
        i.InsertBefore(longer_instruction.data(), longer_instruction.size());
        i.InsertAfter(&instruction, 1U);
        i.Remove();
      }
    }
    std::vector<uint32_t> filtered_stream = stream.EmitFilteredStream();

    delete[] data;
    data = nullptr;
  }

  return 0;
};
<|endoftext|>


<commit_before>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004 darkbits                              Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_KEYLISTENER_HPP
#define GCN_KEYLISTENER_HPP

#include <string>

#include "guichan/key.hpp"
#include "guichan/platform.hpp"

namespace gcn
{
  /**
   * A KeyListener listens for key events on a widget. When a
   * widget recives a key event, the corresponding function
   * in all its key listeners will be called. Only focused
   * widgets will generate key events.
   *
   * None of the functions in this class does anything at all,
   * it is up to you to overload them.
   *
   * @see Widget::addKeyListener
   */
  class DECLSPEC KeyListener
  {
  public:

    /**
     * Destructor
     */
    virtual ~KeyListener() { }

    /**
     * This function is called if a key is pressed when
     * the widget has keyboard focus.
     *
     * If a key is held down the widget will generate multiple
     * key presses.
     *
     * @param key the key pressed
     * @see Key
     */
    virtual void keyPress(const Key& key) { }

    /**
     * This function is called if a key is released when
     * the widget has keyboard focus.
     *
     * @param key the key released
     * @see Key
     */
    virtual void keyRelease(const Key& key) { }

  }; // end KeyListener

} // end gcn

#endif // end GCN_KEYLISTENER_HPP
<commit_msg>KeyListeners constructor is now protected. You should not be able to make an instance of KeyListener.<commit_after>/*      _______   __   __   __   ______   __   __   _______   __   __
 *     / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___  /\ /  |\/ /\
 *    / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
 *   / / /__   / / // / // / // / /    / ___  / // ___  / // /| ' / /
 *  / /_// /\ / /_// / // / // /_/_   / / // / // /\_/ / // / |  / /
 * /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
 * \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
 *
 * Copyright (c) 2004 darkbits                              Js_./
 * Per Larsson a.k.a finalman                          _RqZ{a<^_aa
 * Olof Naessn a.k.a jansem/yakslem                _asww7!uY`>  )\a//
 *                                                 _Qhm`] _f "'c  1!5m
 * Visit: http://guichan.darkbits.org             )Qk<P ` _: :+' .'  "{[
 *                                               .)j(] .d_/ '-(  P .   S
 * License: (BSD)                                <Td/Z <fP"5(\"??"\a.  .L
 * Redistribution and use in source and          _dV>ws?a-?'      ._/L  #'
 * binary forms, with or without                 )4d[#7r, .   '     )d`)[
 * modification, are permitted provided         _Q-5'5W..j/?'   -?!\)cam'
 * that the following conditions are met:       j<<WP+k/);.        _W=j f
 * 1. Redistributions of source code must       .$%w\/]Q  . ."'  .  mj$
 *    retain the above copyright notice,        ]E.pYY(Q]>.   a     J@\
 *    this list of conditions and the           j(]1u<sE"L,. .   ./^ ]{a
 *    following disclaimer.                     4'_uomm\.  )L);-4     (3=
 * 2. Redistributions in binary form must        )_]X{Z('a_"a7'<a"a,  ]"[
 *    reproduce the above copyright notice,       #}<]m7`Za??4,P-"'7. ).m
 *    this list of conditions and the            ]d2e)Q(<Q(  ?94   b-  LQ/
 *    following disclaimer in the                <B!</]C)d_, '(<' .f. =C+m
 *    documentation and/or other materials      .Z!=J ]e []('-4f _ ) -.)m]'
 *    provided with the distribution.          .w[5]' _[ /.)_-"+?   _/ <W"
 * 3. Neither the name of Guichan nor the      :$we` _! + _/ .        j?
 *    names of its contributors may be used     =3)= _f  (_yQmWW$#(    "
 *    to endorse or promote products derived     -   W,  sQQQQmZQ#Wwa]..
 *    from this software without specific        (js, \[QQW$QWW#?!V"".
 *    prior written permission.                    ]y:.<\..          .
 *                                                 -]n w/ '         [.
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT       )/ )/           !
 * HOLDERS AND CONTRIBUTORS "AS IS" AND ANY         <  (; sac    ,    '
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING,               ]^ .-  %
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF            c <   r
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR            aga<  <La
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE          5%  )P'-3L
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR        _bQf` y`..)a
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,          ,J?4P'.P"_(\?d'.,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES               _Pa,)!f/<[]/  ?"
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT      _2-..:. .r+_,.. .
 * OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,     ?a.<%"'  " -'.a_ _,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)                     ^
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef GCN_KEYLISTENER_HPP
#define GCN_KEYLISTENER_HPP

#include <string>

#include "guichan/key.hpp"
#include "guichan/platform.hpp"

namespace gcn
{
  /**
   * A KeyListener listens for key events on a widget. When a
   * widget recives a key event, the corresponding function
   * in all its key listeners will be called. Only focused
   * widgets will generate key events.
   *
   * None of the functions in this class does anything at all,
   * it is up to you to overload them.
   *
   * @see Widget::addKeyListener
   */
  class DECLSPEC KeyListener
  {
  public:

    /**
     * Destructor
     */
    virtual ~KeyListener() { }

    /**
     * This function is called if a key is pressed when
     * the widget has keyboard focus.
     *
     * If a key is held down the widget will generate multiple
     * key presses.
     *
     * @param key the key pressed
     * @see Key
     */
    virtual void keyPress(const Key& key) { }

    /**
     * This function is called if a key is released when
     * the widget has keyboard focus.
     *
     * @param key the key released
     * @see Key
     */
    virtual void keyRelease(const Key& key) { }

	protected:
		/**
		 * Constructor.
		 *
		 * You should not be able to make an instance of KeyListener,
		 * therefore its constructor is protected.
		 */
		KeyListener() { }

  }; // end KeyListener

} // end gcn

#endif // end GCN_KEYLISTENER_HPP
<|endoftext|>


<commit_before>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "base_swg_server.h"

#include "swganh/logger.h"
#include "swganh/network/soe/session.h"

using namespace swganh::network;

using std::move;

BaseSwgServer::BaseSwgServer(
    boost::asio::io_service& io_service)
    : swganh::network::soe::Server(io_service)
{}

void BaseSwgServer::HandleMessage(
    const std::shared_ptr<swganh::network::soe::Session>& connection,
    swganh::ByteBuffer message)
{
    uint32_t message_type = message.peekAt<uint32_t>(message.read_position() + sizeof(uint16_t));

    auto find_iter = message_handlers_.find(message_type);
    if (find_iter == message_handlers_.end())
    {
        DLOG(warning) << "Received an unidentified message: " << std::hex << message_type;
        return;
    }

    try
    {
        LOG_NET << "HandleMessage: "  << std::hex << message_type << " Client -> Server \n" << message;
        find_iter->second(connection, move(message));
    }
    catch(std::exception& e)
    {
        LOG(error) << e.what();
    }
}

void BaseSwgServer::RegisterMessageHandler(
    swganh::HashString handler_id,
    SwgMessageHandler&& handler)
{
    if (HasHandler(handler_id))
    {
        throw HandlerAlreadyDefined("Requested registration of handler that has already been defined.");
    }

    message_handlers_.insert(make_pair(handler_id, move(handler)));
}

bool BaseSwgServer::HasHandler(swganh::HashString handler_id)
{
    return (message_handlers_.find(handler_id) != message_handlers_.end());
}
<commit_msg>Removing network logging here<commit_after>// This file is part of SWGANH which is released under the MIT license.
// See file LICENSE or go to http://swganh.com/LICENSE

#include "base_swg_server.h"

#include "swganh/logger.h"
#include "swganh/network/soe/session.h"

using namespace swganh::network;

using std::move;

BaseSwgServer::BaseSwgServer(
    boost::asio::io_service& io_service)
    : swganh::network::soe::Server(io_service)
{}

void BaseSwgServer::HandleMessage(
    const std::shared_ptr<swganh::network::soe::Session>& connection,
    swganh::ByteBuffer message)
{
    uint32_t message_type = message.peekAt<uint32_t>(message.read_position() + sizeof(uint16_t));

    auto find_iter = message_handlers_.find(message_type);
    if (find_iter == message_handlers_.end())
    {
        DLOG(warning) << "Received an unidentified message: " << std::hex << message_type;
        return;
    }

    try
    {
        find_iter->second(connection, move(message));
    }
    catch(std::exception& e)
    {
        LOG(error) << e.what();
    }
}

void BaseSwgServer::RegisterMessageHandler(
    swganh::HashString handler_id,
    SwgMessageHandler&& handler)
{
    if (HasHandler(handler_id))
    {
        throw HandlerAlreadyDefined("Requested registration of handler that has already been defined.");
    }

    message_handlers_.insert(make_pair(handler_id, move(handler)));
}

bool BaseSwgServer::HasHandler(swganh::HashString handler_id)
{
    return (message_handlers_.find(handler_id) != message_handlers_.end());
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                    OpenSim:  TugOfWar1_CreateModel.cpp                     *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 * Author(s): Jeffrey A. Reinbolt, Ayman Habib, Ajay Seth, Jack Middleton,    *
 *            Samuel R. Hamner                                                *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim application that provides its own
 *  main() routine.  This application is a forward simulation of tug-of-war between two
 *  muscles pulling on a block.
 */

// Author:  Jeff Reinbolt, Ayman Habib, Ajay Seth, Jack Middleton, Samuel Hamner

//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>

using namespace OpenSim;
using namespace SimTK;

//______________________________________________________________________________
/**
 * First exercise: create a model that does nothing.
 */
int main()
{
    try {
        // Create an OpenSim model and set its name
        Model osimModel;
        osimModel.setName("tugOfWar");
    }
    catch (OpenSim::Exception ex)
    {
        std::cout << ex.getMessage() << std::endl;
        return 1;
    }
    catch (std::exception ex)
    {
        std::cout << ex.what() << std::endl;
        return 1;
    }
    catch (...)
    {
        std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
        return 1;
    }

    std::cout << "OpenSim example completed successfully.\n";
    std::cin.get();
    return 0;
}
<commit_msg>Catch exceptions by reference. See, e.g., https://stackoverflow.com/questions/2522299/c-catch-blocks-catch-exception-by-value-or-reference. [ci skip]<commit_after>/* -------------------------------------------------------------------------- *
 *                    OpenSim:  TugOfWar1_CreateModel.cpp                     *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2017 Stanford University and the Authors                *
 * Author(s): Jeffrey A. Reinbolt, Ayman Habib, Ajay Seth, Jack Middleton,    *
 *            Samuel R. Hamner                                                *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

/*
 *  Below is an example of an OpenSim application that provides its own
 *  main() routine.  This application is a forward simulation of tug-of-war between two
 *  muscles pulling on a block.
 */

// Author:  Jeff Reinbolt, Ayman Habib, Ajay Seth, Jack Middleton, Samuel Hamner

//==============================================================================
//==============================================================================
#include <OpenSim/OpenSim.h>

using namespace OpenSim;
using namespace SimTK;

//______________________________________________________________________________
/**
 * First exercise: create a model that does nothing.
 */
int main()
{
    try {
        // Create an OpenSim model and set its name
        Model osimModel;
        osimModel.setName("tugOfWar");
    }
    catch (const OpenSim::Exception& ex)
    {
        std::cout << ex.getMessage() << std::endl;
        return 1;
    }
    catch (const std::exception& ex)
    {
        std::cout << ex.what() << std::endl;
        return 1;
    }
    catch (...)
    {
        std::cout << "UNRECOGNIZED EXCEPTION" << std::endl;
        return 1;
    }

    std::cout << "OpenSim example completed successfully.\n";
    std::cin.get();
    return 0;
}
<|endoftext|>


<commit_before>/* -------------------------------------------------------------------------- *
 *                     OpenSim:  LiuThelen2003Muscle.cpp                      *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Peter Loan, Darryl G. Thelen                                    *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied    *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "LiuThelen2003Muscle.h"
#include <OpenSim/Common/SimmMacros.h>

//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;

// States 0 and 1 are defined in the base class, Thelen2003Muscle.
const int LiuThelen2003Muscle::STATE_ACTIVE_MOTOR_UNITS = 2;
const int LiuThelen2003Muscle::STATE_FATIGUED_MOTOR_UNITS = 3;

//=============================================================================
//=============================================================================
/**
 * A Thelen2003Muscle that includes two states for modeling fatigue and
 * recovery of muscle fibers. The equations for these states are based
 * on the following paper:
 * Liu, Jing Z., Brown, Robert, Yue, Guang H., "A Dynamical Model of Muscle
 * Activation, Fatigue, and Recovery," Biophysical Journal, Vol. 82, Issue 5,
 * pp. 2344-2359, 2002.
 *
 * @author Peter Loan (based on Thelen2003Muscle by Darryl Thelen)
 * @version 1.0
 */

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
 * Default constructor.
 */
LiuThelen2003Muscle::LiuThelen2003Muscle()
{
	setNull();
	constructProperties();
}

//_____________________________________________________________________________
/**
 * Constructor.
 */
LiuThelen2003Muscle::LiuThelen2003Muscle
   (const std::string &aName, double aMaxIsometricForce,
	double aOptimalFiberLength, double aTendonSlackLength,
	double aPennationAngle, double aFatigueFactor,
	double aRecoveryFactor)
:   Super(aName, aMaxIsometricForce, aOptimalFiberLength, aTendonSlackLength,
          aPennationAngle)
{
	setNull();
	constructProperties();
	setFatigueFactor(aFatigueFactor);
	setRecoveryFactor(aRecoveryFactor);
}

//=============================================================================
// CONSTRUCTION METHODS
//=============================================================================
//_____________________________________________________________________________
/**
 * Set the data members of this LiuThelen2003Muscle to their null values.
 */
void LiuThelen2003Muscle::setNull()
{
   _defaultActiveMotorUnits = 0.0;
   _defaultFatiguedMotorUnits = 0.0;
}

//_____________________________________________________________________________
/**
 * Construct and initialize properties.
 *
 * Properties should be given a meaningful name and an informative comment.
 * The name you give each property is the tag that will be used in the XML
 * file. The comment will appear before the property in the XML file.
 * In addition, the comments are used for tool tips in the OpenSim GUI.
 *
 * All properties are added to the property set. Once added, they can be
 * read in and written to files.
*/
void LiuThelen2003Muscle::constructProperties()
{
    constructProperty_fatigue_factor(0.0);
    constructProperty_recovery_factor(0.0);
}

//_____________________________________________________________________________
void LiuThelen2003Muscle::addToSystem(SimTK::MultibodySystem& system) const
{
	Super::addToSystem(system);

	addStateVariable("active_motor_units");
	addStateVariable("fatigued_motor_units");
	addCacheVariable("active_motor_units_deriv", 0.0, SimTK::Stage::Dynamics);
	addCacheVariable("fatigued_motor_units_deriv", 0.0, SimTK::Stage::Dynamics);
}

void LiuThelen2003Muscle::equilibrate(SimTK::State& state) const
{
	// Reasonable initial activation value
	setActivation(state, 0.01);
	setFiberLength(state, getOptimalFiberLength());
	setActiveMotorUnits(state, 0.0);
	setFatiguedMotorUnits(state, 0.0);
	_model->getMultibodySystem().realize(state, SimTK::Stage::Velocity);

	// Compute isometric force to get starting value of _fiberLength.
	computeEquilibrium(state);
}

//=============================================================================
// GET
//=============================================================================

//-----------------------------------------------------------------------------
// MAXIMUM ISOMETRIC FORCE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
 * Set the maximum isometric force that the fibers can generate.
 *
 * @param aMaxIsometricForce The maximum isometric force that the fibers can generate.
 * @return Whether the maximum isometric force was successfully changed.
 */
bool LiuThelen2003Muscle::setFatigueFactor(double aFatigueFactor)
{
	set_fatigue_factor(aFatigueFactor);
	return true;
}

//-----------------------------------------------------------------------------
// OPTIMAL FIBER LENGTH
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
 * Set the optimal length of the muscle fibers.
 *
 * @param aOptimalFiberLength The optimal length of the muscle fibers.
 * @return Whether the optimal length was successfully changed.
 */
bool LiuThelen2003Muscle::setRecoveryFactor(double aRecoveryFactor)
{
	set_recovery_factor(aRecoveryFactor);
	return true;
}

double LiuThelen2003Muscle::getDefaultActiveMotorUnits() const
{
	return _defaultActiveMotorUnits;
}

void LiuThelen2003Muscle::setDefaultActiveMotorUnits(double activeMotorUnits) {
    _defaultActiveMotorUnits = activeMotorUnits;
}

double LiuThelen2003Muscle::getDefaultFatiguedMotorUnits() const
{
	return _defaultFatiguedMotorUnits;
}

void LiuThelen2003Muscle::setDefaultFatiguedMotorUnits(double fatiguedMotorUnits) {
    _defaultFatiguedMotorUnits = fatiguedMotorUnits;
}

//=============================================================================
// COMPUTATION
//=============================================================================
//_____________________________________________________________________________
/**
 * Compute the derivatives of the muscle states.
 *
 * @param s  system state
 */
SimTK::Vector LiuThelen2003Muscle::
computeStateVariableDerivatives(const SimTK::State& s) const
{
	Array<string> names = getStateVariableNames();
	cout << "State names: " << names << endl;

	SimTK::Vector derivs = Super::computeStateVariableDerivatives(s);
	derivs.resizeKeep(4);
    if (!isDisabled(s)) {
	    derivs[2] = getActiveMotorUnitsDeriv(s);
	    derivs[3] = getFatiguedMotorUnitsDeriv(s);
    } else
        derivs[2] = derivs[3] = 0;

	derivs.dump("State values:");
	cout << endl;

	return derivs;
}

//_____________________________________________________________________________
/**
 * Compute the equilibrium states.  This method computes a fiber length
 * for the muscle that is consistent with the muscle's activation level.
 */
void LiuThelen2003Muscle::computeEquilibrium(SimTK::State& s) const
{
	computeIsometricForce(s, getActivation(s));
}

//_____________________________________________________________________________
/**
 * Compute the actuation for the muscle. This function assumes
 * that computeDerivatives has already been called.
 */
double LiuThelen2003Muscle::computeActuation(const SimTK::State& s) const
{
	double tendonForce;
	double normState[4], normStateDeriv[4], norm_tendon_length, ca;
	double norm_muscle_tendon_length, pennation_angle;

	const double maxIsometricForce = get_max_isometric_force();
    const double optimalFiberLength = get_optimal_fiber_length();
	const double tendonSlackLength = get_tendon_slack_length();
	const double pennationAngleAtOptimal = get_pennation_angle_at_optimal();
	const double activationTimeConstant = get_activation_time_constant();
	const double deactivationTimeConstant = get_deactivation_time_constant();
	const double vmax = get_Vmax();
	const double vmax0 = get_Vmax0();

	// Normalize the muscle states.
	normState[STATE_ACTIVATION] = getActivation(s);
	normState[STATE_FIBER_LENGTH] = getFiberLength(s) / optimalFiberLength;
	normState[STATE_ACTIVE_MOTOR_UNITS] = getActiveMotorUnits(s);
	normState[STATE_FATIGUED_MOTOR_UNITS] = getFatiguedMotorUnits(s);

	// Maximum contraction velocity is an activation scaled value.
	double Vmax = vmax;
	if (normState[STATE_ACTIVATION]<1.0)
		Vmax = vmax0 + normState[STATE_ACTIVATION]*(Vmax-vmax0);
	Vmax = Vmax*optimalFiberLength;

	// Compute normalized muscle state derivatives.
	if (getExcitation(s) >= normState[STATE_ACTIVATION])
      normStateDeriv[STATE_ACTIVATION] = (getExcitation(s) - normState[STATE_ACTIVATION]) / activationTimeConstant;
	else
      normStateDeriv[STATE_ACTIVATION] = (getExcitation(s) - normState[STATE_ACTIVATION]) / deactivationTimeConstant;

	pennation_angle = calcPennation( normState[STATE_FIBER_LENGTH], 1.0, pennationAngleAtOptimal);
	ca = cos(pennation_angle);

	norm_muscle_tendon_length = getLength(s) / optimalFiberLength;
	norm_tendon_length = norm_muscle_tendon_length - normState[STATE_FIBER_LENGTH] * ca;

	tendonForce = calcTendonForce(s,norm_tendon_length);
	setPassiveForce(s, calcPassiveForce(s,normState[STATE_FIBER_LENGTH]));
	double activeForce = calcActiveForce(s,normState[STATE_FIBER_LENGTH]);

	// If pennation equals 90 degrees, fiber length equals muscle width and fiber
	// velocity goes to zero.  Pennation will stay at 90 until tendon starts to
	// pull, then "stiff tendon" approximation is used to calculate approximate
	// fiber velocity.
	if (EQUAL_WITHIN_ERROR(ca, 0.0))
	{
      if (EQUAL_WITHIN_ERROR(tendonForce, 0.0))
      {
         normStateDeriv[STATE_FIBER_LENGTH] = 0.0;
		}
		else
		{
         double h = norm_muscle_tendon_length - tendonSlackLength;
         double w = optimalFiberLength * sin(pennationAngleAtOptimal);
         double new_fiber_length = sqrt(h*h + w*w) / optimalFiberLength;
			double new_pennation_angle = calcPennation( new_fiber_length, 1.0, pennationAngleAtOptimal);
         double new_ca = cos(new_pennation_angle);
         normStateDeriv[STATE_FIBER_LENGTH] = getSpeed(s) / (Vmax * new_ca);
		}
	}
	else
	{
      double velocity_dependent_force = tendonForce / ca - getPassiveForce(s);
      normStateDeriv[STATE_FIBER_LENGTH] = calcFiberVelocity(s, getActiveMotorUnits(s), activeForce, velocity_dependent_force);
	}

	normStateDeriv[STATE_ACTIVE_MOTOR_UNITS] = normStateDeriv[STATE_ACTIVATION] - getFatigueFactor() * getActiveMotorUnits(s) + getRecoveryFactor() * getFatiguedMotorUnits(s);
	normStateDeriv[STATE_FATIGUED_MOTOR_UNITS]  = getFatigueFactor() * getActiveMotorUnits(s) - getRecoveryFactor() * getFatiguedMotorUnits(s);

	// Un-normalize the muscle state derivatives and forces.
	// Note: Do not need to Un-Normalize activation dynamics equation since activation, deactivation parameters
	// specified in muscle file are now independent of time scale
	setActivationDeriv(s, normStateDeriv[STATE_ACTIVATION]) ;
	setFiberLengthDeriv(s, normStateDeriv[STATE_FIBER_LENGTH] * Vmax );
	setActiveMotorUnitsDeriv(s, normStateDeriv[STATE_ACTIVE_MOTOR_UNITS]);
	setFatiguedMotorUnitsDeriv(s, normStateDeriv[STATE_FATIGUED_MOTOR_UNITS]);

	tendonForce = tendonForce *  maxIsometricForce;
	setForce( s, tendonForce );
	setTendonForce( s, tendonForce );
	setPassiveForce( s, getPassiveForce(s) * maxIsometricForce);

	return tendonForce;
}

//_____________________________________________________________________________
/**
 * Find the force produced by an actuator (the musculotendon unit), assuming
 * static equilibrium. Using the total muscle-tendon length, it finds the
 * fiber and tendon lengths so that the forces in each match. This routine
 * takes pennation angle into account, so its definition of static equilibrium
 * is when tendon_force = fiber_force * cos(pennation_angle). This funcion
 * will modify the object's values for _length, _fiberLength, _activeForce,
 * and _passiveForce.
 *
 * @param aActivation Activation of the muscle.
 * @return The isometric force in the muscle.
 */
double LiuThelen2003Muscle::
computeIsometricForce(SimTK::State& s, double aActivation) const
{
	const double optimalFiberLength = get_optimal_fiber_length();
	const double fatigueFactor = get_fatigue_factor();
	const double recoveryFactor = get_recovery_factor();

    if (optimalFiberLength < ROUNDOFF_ERROR) {
       return 0.0;
    }

	// This muscle model includes two fatigue states, so this function assumes
	// that t=infinity in order to compute the [steady-state] isometric force.
	// When t=infinity, the number of active motor units is independent of the
	// activation level (JPL: as long as activation > _recoveryFactor /
	// (_fatigueFactor + _recoveryFactor), I think). So the passed-in activation
	// is not used in this function (unless the fatigue and recovery factors are
	// both zero which means there is no fatigue).
	if ((fatigueFactor + recoveryFactor > 0.0) && (aActivation >= recoveryFactor / (fatigueFactor + recoveryFactor))) {
		setActiveMotorUnits(s, recoveryFactor / (fatigueFactor + recoveryFactor));
		setFatiguedMotorUnits(s, fatigueFactor / (fatigueFactor + recoveryFactor));
	} else {
		setActiveMotorUnits(s, aActivation);
		setFatiguedMotorUnits(s, 0.0);
	}

	aActivation = getActiveMotorUnits(s);

	// Now you can call the base class's function with the steady-state activation
	return Super::computeIsometricForce(s, aActivation);
}

<commit_msg>Removed debugging lines I added for checking state variable names and derivs order. <commit_after>/* -------------------------------------------------------------------------- *
 *                     OpenSim:  LiuThelen2003Muscle.cpp                      *
 * -------------------------------------------------------------------------- *
 * The OpenSim API is a toolkit for musculoskeletal modeling and simulation.  *
 * See http://opensim.stanford.edu and the NOTICE file for more information.  *
 * OpenSim is developed at Stanford University and supported by the US        *
 * National Institutes of Health (U54 GM072970, R24 HD065690) and by DARPA    *
 * through the Warrior Web program.                                           *
 *                                                                            *
 * Copyright (c) 2005-2012 Stanford University and the Authors                *
 * Author(s): Peter Loan, Darryl G. Thelen                                    *
 *                                                                            *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may    *
 * not use this file except in compliance with the License. You may obtain a  *
 * copy of the License at http://www.apache.org/licenses/LICENSE-2.0.         *
 *                                                                            *
 * Unless required by applicable law or agreed to in writing, software        *
 * distributed under the License is distributed on an "AS IS" BASIS,          *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied    *
 * See the License for the specific language governing permissions and        *
 * limitations under the License.                                             *
 * -------------------------------------------------------------------------- */

//=============================================================================
// INCLUDES
//=============================================================================
#include "LiuThelen2003Muscle.h"
#include <OpenSim/Common/SimmMacros.h>

//=============================================================================
// STATICS
//=============================================================================
using namespace std;
using namespace OpenSim;

// States 0 and 1 are defined in the base class, Thelen2003Muscle.
const int LiuThelen2003Muscle::STATE_ACTIVE_MOTOR_UNITS = 2;
const int LiuThelen2003Muscle::STATE_FATIGUED_MOTOR_UNITS = 3;

//=============================================================================
//=============================================================================
/**
 * A Thelen2003Muscle that includes two states for modeling fatigue and
 * recovery of muscle fibers. The equations for these states are based
 * on the following paper:
 * Liu, Jing Z., Brown, Robert, Yue, Guang H., "A Dynamical Model of Muscle
 * Activation, Fatigue, and Recovery," Biophysical Journal, Vol. 82, Issue 5,
 * pp. 2344-2359, 2002.
 *
 * @author Peter Loan (based on Thelen2003Muscle by Darryl Thelen)
 * @version 1.0
 */

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
//_____________________________________________________________________________
/**
 * Default constructor.
 */
LiuThelen2003Muscle::LiuThelen2003Muscle()
{
	setNull();
	constructProperties();
}

//_____________________________________________________________________________
/**
 * Constructor.
 */
LiuThelen2003Muscle::LiuThelen2003Muscle
   (const std::string &aName, double aMaxIsometricForce,
	double aOptimalFiberLength, double aTendonSlackLength,
	double aPennationAngle, double aFatigueFactor,
	double aRecoveryFactor)
:   Super(aName, aMaxIsometricForce, aOptimalFiberLength, aTendonSlackLength,
          aPennationAngle)
{
	setNull();
	constructProperties();
	setFatigueFactor(aFatigueFactor);
	setRecoveryFactor(aRecoveryFactor);
}

//=============================================================================
// CONSTRUCTION METHODS
//=============================================================================
//_____________________________________________________________________________
/**
 * Set the data members of this LiuThelen2003Muscle to their null values.
 */
void LiuThelen2003Muscle::setNull()
{
   _defaultActiveMotorUnits = 0.0;
   _defaultFatiguedMotorUnits = 0.0;
}

//_____________________________________________________________________________
/**
 * Construct and initialize properties.
 *
 * Properties should be given a meaningful name and an informative comment.
 * The name you give each property is the tag that will be used in the XML
 * file. The comment will appear before the property in the XML file.
 * In addition, the comments are used for tool tips in the OpenSim GUI.
 *
 * All properties are added to the property set. Once added, they can be
 * read in and written to files.
*/
void LiuThelen2003Muscle::constructProperties()
{
    constructProperty_fatigue_factor(0.0);
    constructProperty_recovery_factor(0.0);
}

//_____________________________________________________________________________
void LiuThelen2003Muscle::addToSystem(SimTK::MultibodySystem& system) const
{
	Super::addToSystem(system);

	addStateVariable("active_motor_units");
	addStateVariable("fatigued_motor_units");
	addCacheVariable("active_motor_units_deriv", 0.0, SimTK::Stage::Dynamics);
	addCacheVariable("fatigued_motor_units_deriv", 0.0, SimTK::Stage::Dynamics);
}

void LiuThelen2003Muscle::equilibrate(SimTK::State& state) const
{
	// Reasonable initial activation value
	setActivation(state, 0.01);
	setFiberLength(state, getOptimalFiberLength());
	setActiveMotorUnits(state, 0.0);
	setFatiguedMotorUnits(state, 0.0);
	_model->getMultibodySystem().realize(state, SimTK::Stage::Velocity);

	// Compute isometric force to get starting value of _fiberLength.
	computeEquilibrium(state);
}

//=============================================================================
// GET
//=============================================================================

//-----------------------------------------------------------------------------
// MAXIMUM ISOMETRIC FORCE
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
 * Set the maximum isometric force that the fibers can generate.
 *
 * @param aMaxIsometricForce The maximum isometric force that the fibers can generate.
 * @return Whether the maximum isometric force was successfully changed.
 */
bool LiuThelen2003Muscle::setFatigueFactor(double aFatigueFactor)
{
	set_fatigue_factor(aFatigueFactor);
	return true;
}

//-----------------------------------------------------------------------------
// OPTIMAL FIBER LENGTH
//-----------------------------------------------------------------------------
//_____________________________________________________________________________
/**
 * Set the optimal length of the muscle fibers.
 *
 * @param aOptimalFiberLength The optimal length of the muscle fibers.
 * @return Whether the optimal length was successfully changed.
 */
bool LiuThelen2003Muscle::setRecoveryFactor(double aRecoveryFactor)
{
	set_recovery_factor(aRecoveryFactor);
	return true;
}

double LiuThelen2003Muscle::getDefaultActiveMotorUnits() const
{
	return _defaultActiveMotorUnits;
}

void LiuThelen2003Muscle::setDefaultActiveMotorUnits(double activeMotorUnits) {
    _defaultActiveMotorUnits = activeMotorUnits;
}

double LiuThelen2003Muscle::getDefaultFatiguedMotorUnits() const
{
	return _defaultFatiguedMotorUnits;
}

void LiuThelen2003Muscle::setDefaultFatiguedMotorUnits(double fatiguedMotorUnits) {
    _defaultFatiguedMotorUnits = fatiguedMotorUnits;
}

//=============================================================================
// COMPUTATION
//=============================================================================
//_____________________________________________________________________________
/**
 * Compute the derivatives of the muscle states.
 *
 * @param s  system state
 */
SimTK::Vector LiuThelen2003Muscle::
computeStateVariableDerivatives(const SimTK::State& s) const
{
	SimTK::Vector derivs = Super::computeStateVariableDerivatives(s);
	derivs.resizeKeep(4);
    if (!isDisabled(s)) {
	    derivs[2] = getActiveMotorUnitsDeriv(s);
	    derivs[3] = getFatiguedMotorUnitsDeriv(s);
    } else
        derivs[2] = derivs[3] = 0;

	return derivs;
}

//_____________________________________________________________________________
/**
 * Compute the equilibrium states.  This method computes a fiber length
 * for the muscle that is consistent with the muscle's activation level.
 */
void LiuThelen2003Muscle::computeEquilibrium(SimTK::State& s) const
{
	computeIsometricForce(s, getActivation(s));
}

//_____________________________________________________________________________
/**
 * Compute the actuation for the muscle. This function assumes
 * that computeDerivatives has already been called.
 */
double LiuThelen2003Muscle::computeActuation(const SimTK::State& s) const
{
	double tendonForce;
	double normState[4], normStateDeriv[4], norm_tendon_length, ca;
	double norm_muscle_tendon_length, pennation_angle;

	const double maxIsometricForce = get_max_isometric_force();
    const double optimalFiberLength = get_optimal_fiber_length();
	const double tendonSlackLength = get_tendon_slack_length();
	const double pennationAngleAtOptimal = get_pennation_angle_at_optimal();
	const double activationTimeConstant = get_activation_time_constant();
	const double deactivationTimeConstant = get_deactivation_time_constant();
	const double vmax = get_Vmax();
	const double vmax0 = get_Vmax0();

	// Normalize the muscle states.
	normState[STATE_ACTIVATION] = getActivation(s);
	normState[STATE_FIBER_LENGTH] = getFiberLength(s) / optimalFiberLength;
	normState[STATE_ACTIVE_MOTOR_UNITS] = getActiveMotorUnits(s);
	normState[STATE_FATIGUED_MOTOR_UNITS] = getFatiguedMotorUnits(s);

	// Maximum contraction velocity is an activation scaled value.
	double Vmax = vmax;
	if (normState[STATE_ACTIVATION]<1.0)
		Vmax = vmax0 + normState[STATE_ACTIVATION]*(Vmax-vmax0);
	Vmax = Vmax*optimalFiberLength;

	// Compute normalized muscle state derivatives.
	if (getExcitation(s) >= normState[STATE_ACTIVATION])
      normStateDeriv[STATE_ACTIVATION] = (getExcitation(s) - normState[STATE_ACTIVATION]) / activationTimeConstant;
	else
      normStateDeriv[STATE_ACTIVATION] = (getExcitation(s) - normState[STATE_ACTIVATION]) / deactivationTimeConstant;

	pennation_angle = calcPennation( normState[STATE_FIBER_LENGTH], 1.0, pennationAngleAtOptimal);
	ca = cos(pennation_angle);

	norm_muscle_tendon_length = getLength(s) / optimalFiberLength;
	norm_tendon_length = norm_muscle_tendon_length - normState[STATE_FIBER_LENGTH] * ca;

	tendonForce = calcTendonForce(s,norm_tendon_length);
	setPassiveForce(s, calcPassiveForce(s,normState[STATE_FIBER_LENGTH]));
	double activeForce = calcActiveForce(s,normState[STATE_FIBER_LENGTH]);

	// If pennation equals 90 degrees, fiber length equals muscle width and fiber
	// velocity goes to zero.  Pennation will stay at 90 until tendon starts to
	// pull, then "stiff tendon" approximation is used to calculate approximate
	// fiber velocity.
	if (EQUAL_WITHIN_ERROR(ca, 0.0))
	{
      if (EQUAL_WITHIN_ERROR(tendonForce, 0.0))
      {
         normStateDeriv[STATE_FIBER_LENGTH] = 0.0;
		}
		else
		{
         double h = norm_muscle_tendon_length - tendonSlackLength;
         double w = optimalFiberLength * sin(pennationAngleAtOptimal);
         double new_fiber_length = sqrt(h*h + w*w) / optimalFiberLength;
			double new_pennation_angle = calcPennation( new_fiber_length, 1.0, pennationAngleAtOptimal);
         double new_ca = cos(new_pennation_angle);
         normStateDeriv[STATE_FIBER_LENGTH] = getSpeed(s) / (Vmax * new_ca);
		}
	}
	else
	{
      double velocity_dependent_force = tendonForce / ca - getPassiveForce(s);
      normStateDeriv[STATE_FIBER_LENGTH] = calcFiberVelocity(s, getActiveMotorUnits(s), activeForce, velocity_dependent_force);
	}

	normStateDeriv[STATE_ACTIVE_MOTOR_UNITS] = normStateDeriv[STATE_ACTIVATION] - getFatigueFactor() * getActiveMotorUnits(s) + getRecoveryFactor() * getFatiguedMotorUnits(s);
	normStateDeriv[STATE_FATIGUED_MOTOR_UNITS]  = getFatigueFactor() * getActiveMotorUnits(s) - getRecoveryFactor() * getFatiguedMotorUnits(s);

	// Un-normalize the muscle state derivatives and forces.
	// Note: Do not need to Un-Normalize activation dynamics equation since activation, deactivation parameters
	// specified in muscle file are now independent of time scale
	setActivationDeriv(s, normStateDeriv[STATE_ACTIVATION]) ;
	setFiberLengthDeriv(s, normStateDeriv[STATE_FIBER_LENGTH] * Vmax );
	setActiveMotorUnitsDeriv(s, normStateDeriv[STATE_ACTIVE_MOTOR_UNITS]);
	setFatiguedMotorUnitsDeriv(s, normStateDeriv[STATE_FATIGUED_MOTOR_UNITS]);

	tendonForce = tendonForce *  maxIsometricForce;
	setForce( s, tendonForce );
	setTendonForce( s, tendonForce );
	setPassiveForce( s, getPassiveForce(s) * maxIsometricForce);

	return tendonForce;
}

//_____________________________________________________________________________
/**
 * Find the force produced by an actuator (the musculotendon unit), assuming
 * static equilibrium. Using the total muscle-tendon length, it finds the
 * fiber and tendon lengths so that the forces in each match. This routine
 * takes pennation angle into account, so its definition of static equilibrium
 * is when tendon_force = fiber_force * cos(pennation_angle). This funcion
 * will modify the object's values for _length, _fiberLength, _activeForce,
 * and _passiveForce.
 *
 * @param aActivation Activation of the muscle.
 * @return The isometric force in the muscle.
 */
double LiuThelen2003Muscle::
computeIsometricForce(SimTK::State& s, double aActivation) const
{
	const double optimalFiberLength = get_optimal_fiber_length();
	const double fatigueFactor = get_fatigue_factor();
	const double recoveryFactor = get_recovery_factor();

    if (optimalFiberLength < ROUNDOFF_ERROR) {
       return 0.0;
    }

	// This muscle model includes two fatigue states, so this function assumes
	// that t=infinity in order to compute the [steady-state] isometric force.
	// When t=infinity, the number of active motor units is independent of the
	// activation level (JPL: as long as activation > _recoveryFactor /
	// (_fatigueFactor + _recoveryFactor), I think). So the passed-in activation
	// is not used in this function (unless the fatigue and recovery factors are
	// both zero which means there is no fatigue).
	if ((fatigueFactor + recoveryFactor > 0.0) && (aActivation >= recoveryFactor / (fatigueFactor + recoveryFactor))) {
		setActiveMotorUnits(s, recoveryFactor / (fatigueFactor + recoveryFactor));
		setFatiguedMotorUnits(s, fatigueFactor / (fatigueFactor + recoveryFactor));
	} else {
		setActiveMotorUnits(s, aActivation);
		setFatiguedMotorUnits(s, 0.0);
	}

	aActivation = getActiveMotorUnits(s);

	// Now you can call the base class's function with the steady-state activation
	return Super::computeIsometricForce(s, aActivation);
}

<|endoftext|>


<commit_before>#include <iostream>

class MyClass
{
	public:

		MyClass(int value) : m_fixedValue(value), m_nonFixedValue(value) {}

		int m_nonFixedValue;

		const int m_fixedValue;

		static const int m_fixedStaticValue;

		void printMe() const
		{
			std::cout << "  non fixed value: " << m_nonFixedValue << std::endl;
			std::cout << "  fixed value: " << m_fixedValue << std::endl;
			std::cout << "  static fixed value: " << m_fixedStaticValue << std::endl;
			std::cout << std::endl;
		}
};

const int MyClass::m_fixedStaticValue = 9;

int main()
{
	const MyClass myInstance(9);

	std::cout << "const_cast on member variable of const object " << std::endl;
	const_cast<int&>(myInstance.m_nonFixedValue) = 7;
	myInstance.printMe();

	std::cout << "const_cast on const member variable of const object " << std::endl;
	const_cast<int&>(myInstance.m_fixedValue) = 7;
	myInstance.printMe();

	std::cout << "const_cast on const static class variable" << std::endl;
	const_cast<int&>(MyClass::m_fixedStaticValue) = 7;
	myInstance.printMe();
}

<commit_msg>Added a comment<commit_after>#include <iostream>

class MyClass
{
	public:

		MyClass(int value) : m_fixedValue(value), m_nonFixedValue(value) {}

		int m_nonFixedValue;

		const int m_fixedValue;

		static const int m_fixedStaticValue;

		void printMe() const
		{
			std::cout << "  non fixed value: " << m_nonFixedValue << std::endl;
			std::cout << "  fixed value: " << m_fixedValue << std::endl;
			std::cout << "  static fixed value: " << m_fixedStaticValue << std::endl;
			std::cout << std::endl;
		}
};

const int MyClass::m_fixedStaticValue = 9;

int main()
{
	const MyClass myInstance(9);

	// Any of the following const-cast and set operations can cause a crash

	std::cout << "const_cast on member variable of const object " << std::endl;
	const_cast<int&>(myInstance.m_nonFixedValue) = 7;
	myInstance.printMe();

	std::cout << "const_cast on const member variable of const object " << std::endl;
	const_cast<int&>(myInstance.m_fixedValue) = 7;
	myInstance.printMe();

	std::cout << "const_cast on const static class variable" << std::endl;
	const_cast<int&>(MyClass::m_fixedStaticValue) = 7;
	myInstance.printMe();
}

<|endoftext|>


<commit_before>/*
 * dialer - MeeGo Voice Call Manager
 * Copyright (c) 2010, 2011, Nokia Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

#include <QDebug>

#include "managerproxy.h"
#include "resourceproxy.h"

using namespace ResourcePolicy;

static ResourceProxy *gResource = 0;

void ResourceProxy::acquireAnswerResource(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    dialedNumber.clear();

    if (stateCall == Released)
        resourceSetCall->acquire();
    else
        emit answerResourceAcquired();
}

void ResourceProxy::acquireDialResource(const QString number)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    dialedNumber = number;

    if (stateCall == Released)
	resourceSetCall->acquire();
    else
	emit dialResourceAcquired(number);
}

void ResourceProxy::acquireIncomingResource(CallItem *call)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    if (stateRingtone == Released) {
        incomingCall = call;
	resourceSetRingtone->acquire();
    } else
	emit incomingResourceAcquired(call);
}

void ResourceProxy::releaseResources(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    if (stateRingtone == Acquired)
	resourceSetRingtone->release();

    if (stateCall == Acquired)
	resourceSetCall->release();
}

// Private slots connected to Resource library signals
void ResourceProxy::acquireHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Acquired;

    if (incomingCall)
        emit incomingResourceAcquired(incomingCall);
}

void ResourceProxy::lostHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    if (incomingCall)
	emit incomingResourceLost(incomingCall);

    incomingCall = NULL;
}

void ResourceProxy::deniedHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    if (incomingCall)
	emit incomingResourceDenied(incomingCall);

    incomingCall = NULL;
}

void ResourceProxy::releaseHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    incomingCall = NULL;
}

void ResourceProxy::acquireHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Acquired;

    if (dialedNumber.isEmpty())
        emit answerResourceAcquired();
    else
        emit dialResourceAcquired(dialedNumber);
}

void ResourceProxy::lostHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;

    emit callResourceLost();
}

void ResourceProxy::deniedHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;

    if (dialedNumber.isEmpty())
        emit answerResourceDenied();
    else
	emit dialResourceDenied();
}

void ResourceProxy::releaseHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;
}

ResourceProxy::ResourceProxy(QObject *parent) : QObject(parent)
{
    ResourcePolicy::AudioResource *audioResourceRingtone;
    ResourcePolicy::AudioResource *audioResourceCall;

    qDebug("ResourceProxy::%s", __func__);

    if (gResource)
	qFatal("ResourceProxy: There can be only one!");

    // Ringtone resource set
    resourceSetRingtone = new ResourceSet("ringtone", this);
    resourceSetRingtone->setAutoRelease();
    resourceSetRingtone->setAlwaysReply();

    audioResourceRingtone = new ResourcePolicy::AudioResource("ringtone");
    audioResourceRingtone->setProcessID(QCoreApplication::applicationPid());
    audioResourceRingtone->setStreamTag("media.name", "*");

    resourceSetRingtone->addResourceObject(audioResourceRingtone);

    connect(resourceSetRingtone,
	    SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this,
	    SLOT(acquireHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(lostResources()), this,
	    SLOT(lostHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(resourcesReleased()), this,
	    SLOT(releaseHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(resourcesDenied()), this,
	    SLOT(deniedHandlerRingtone()));

    // Call resource set
    resourceSetCall = new ResourceSet("call", this);
    resourceSetCall->setAutoRelease();
    resourceSetCall->setAlwaysReply();

    audioResourceCall = new ResourcePolicy::AudioResource("call");
    audioResourceCall->setProcessID(QCoreApplication::applicationPid());
    audioResourceCall->setStreamTag("media.name", "*");

    resourceSetCall->addResourceObject(audioResourceCall);

    connect(resourceSetCall,
	    SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this,
	    SLOT(acquireHandlerCall()));
    connect(resourceSetCall,
	    SIGNAL(lostResources()), this,
	    SLOT(lostHandlerCall()));
    connect(resourceSetCall,
	    SIGNAL(resourcesReleased()), this,
	    SLOT(releaseHandlerCall()));
    connect(resourceSetCall,
	    SIGNAL(resourcesDenied()), this,
	    SLOT(deniedHandlerCall()));

    // Resource proxy internals
    stateCall     = Released;
    stateRingtone = Released;

    dialedNumber.clear();
    incomingCall = NULL;

    gResource = this;
}

ResourceProxy::~ResourceProxy(void)
{
    qDebug("ResourceProxy::%s", __func__);

    if (gResource)
        resourceSetRingtone->release();

    dialedNumber.clear();
    incomingCall = NULL;

    gResource = 0;
}

ResourceProxy* ResourceProxy::instance(void)
{
    qDebug("ResourceProxy::%s", __func__);

    if (!gResource)
	gResource = new ResourceProxy();

    return gResource;
}
<commit_msg>Changed: Workaround lack of ringtone stream name<commit_after>/*
 * dialer - MeeGo Voice Call Manager
 * Copyright (c) 2010, 2011, Nokia Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */

#include <QDebug>

#include "managerproxy.h"
#include "resourceproxy.h"

using namespace ResourcePolicy;

static ResourceProxy *gResource = 0;

void ResourceProxy::acquireAnswerResource(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    dialedNumber.clear();

    if (stateCall == Released)
        resourceSetCall->acquire();
    else
        emit answerResourceAcquired();
}

void ResourceProxy::acquireDialResource(const QString number)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    dialedNumber = number;

    if (stateCall == Released)
	resourceSetCall->acquire();
    else
	emit dialResourceAcquired(number);
}

void ResourceProxy::acquireIncomingResource(CallItem *call)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    if (stateRingtone == Released) {
        incomingCall = call;
	resourceSetRingtone->acquire();
    } else
	emit incomingResourceAcquired(call);
}

void ResourceProxy::releaseResources(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    if (stateRingtone == Acquired)
	resourceSetRingtone->release();

    if (stateCall == Acquired)
	resourceSetCall->release();
}

// Private slots connected to Resource library signals
void ResourceProxy::acquireHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Acquired;

    if (incomingCall)
        emit incomingResourceAcquired(incomingCall);
}

void ResourceProxy::lostHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    if (incomingCall)
	emit incomingResourceLost(incomingCall);

    incomingCall = NULL;
}

void ResourceProxy::deniedHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    if (incomingCall)
	emit incomingResourceDenied(incomingCall);

    incomingCall = NULL;
}

void ResourceProxy::releaseHandlerRingtone(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateRingtone = Released;

    incomingCall = NULL;
}

void ResourceProxy::acquireHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Acquired;

    if (dialedNumber.isEmpty())
        emit answerResourceAcquired();
    else
        emit dialResourceAcquired(dialedNumber);
}

void ResourceProxy::lostHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;

    emit callResourceLost();
}

void ResourceProxy::deniedHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;

    if (dialedNumber.isEmpty())
        emit answerResourceDenied();
    else
	emit dialResourceDenied();
}

void ResourceProxy::releaseHandlerCall(void)
{
    qDebug("ResourceProxy::%s state == %d %d", __func__, stateCall, stateRingtone);

    stateCall = Released;
}

ResourceProxy::ResourceProxy(QObject *parent) : QObject(parent)
{
    ResourcePolicy::AudioResource *audioResourceRingtone;
    ResourcePolicy::AudioResource *audioResourceCall;

    qDebug("ResourceProxy::%s", __func__);

    if (gResource)
	qFatal("ResourceProxy: There can be only one!");

    // Call resource set
    resourceSetCall = new ResourceSet("call", this);
    resourceSetCall->setAutoRelease();
    resourceSetCall->setAlwaysReply();

    audioResourceCall = new ResourcePolicy::AudioResource("call");
    audioResourceCall->setProcessID(QCoreApplication::applicationPid());
    audioResourceCall->setStreamTag("media.name", "*");

    resourceSetCall->addResourceObject(audioResourceCall);

    connect(resourceSetCall,
            SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this,
            SLOT(acquireHandlerCall()));
    connect(resourceSetCall,
            SIGNAL(lostResources()), this,
            SLOT(lostHandlerCall()));
    connect(resourceSetCall,
            SIGNAL(resourcesReleased()), this,
            SLOT(releaseHandlerCall()));
    connect(resourceSetCall,
            SIGNAL(resourcesDenied()), this,
            SLOT(deniedHandlerCall()));

    // Ringtone resource set
    resourceSetRingtone = new ResourceSet("ringtone", this);
    resourceSetRingtone->setAutoRelease();
    resourceSetRingtone->setAlwaysReply();

    audioResourceRingtone = new ResourcePolicy::AudioResource("ringtone");
    audioResourceRingtone->setProcessID(QCoreApplication::applicationPid());
    audioResourceRingtone->setStreamTag("media.name", "*");

    resourceSetRingtone->addResourceObject(audioResourceRingtone);

    connect(resourceSetRingtone,
	    SIGNAL(resourcesGranted(const QList<ResourcePolicy::ResourceType>&)), this,
	    SLOT(acquireHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(lostResources()), this,
	    SLOT(lostHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(resourcesReleased()), this,
	    SLOT(releaseHandlerRingtone()));
    connect(resourceSetRingtone,
	    SIGNAL(resourcesDenied()), this,
	    SLOT(deniedHandlerRingtone()));

    // Resource proxy internals
    stateCall     = Released;
    stateRingtone = Released;

    dialedNumber.clear();
    incomingCall = NULL;

    gResource = this;
}

ResourceProxy::~ResourceProxy(void)
{
    qDebug("ResourceProxy::%s", __func__);

    if (gResource)
        resourceSetRingtone->release();

    dialedNumber.clear();
    incomingCall = NULL;

    gResource = 0;
}

ResourceProxy* ResourceProxy::instance(void)
{
    qDebug("ResourceProxy::%s", __func__);

    if (!gResource)
	gResource = new ResourceProxy();

    return gResource;
}
<|endoftext|>


<commit_before>#include "nova_renderer/rhi/rhi_types.hpp"

namespace nova::renderer::rhi {
    bool ResourceBindingDescription::operator==(const ResourceBindingDescription& other) {
        return set == other.set && binding == other.binding && count == other.count && type == other.type;
    }

    bool ResourceBindingDescription::operator!=(const ResourceBindingDescription& other) { return !(*this == other); }

    ResourceBarrier::ResourceBarrier() {}

    DescriptorResourceInfo::DescriptorResourceInfo() {}

    uint32_t PipelineInterface::get_num_descriptors_of_type(const DescriptorType type) const {
        uint32_t num_descriptors = 0;
        bindings.each_value([&](const ResourceBindingDescription& description) {
            if(description.type == type) {
                num_descriptors++;
            }
        });

        return num_descriptors;
    }

    ShaderStage operator|=(const ShaderStage lhs, const ShaderStage rhs) {
        return static_cast<ShaderStage>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
    }

    bool is_depth_format(const PixelFormat format) {
        switch(format) {
            case PixelFormat::Rgba8:
                [[fallthrough]];
            case PixelFormat::Rgba16F:
                [[fallthrough]];
            case PixelFormat::Rgba32F:
                return false;

            case PixelFormat::Depth32:
                [[fallthrough]];
            case PixelFormat::Depth24Stencil8:
                return true;

            default:
                return false;
        }
    }

    uint32_t get_byte_size(const VertexFieldFormat format) {
        switch(format) {
            case VertexFieldFormat::Uint:
                return 4;

            case VertexFieldFormat::Float2:
                return 8;

            case VertexFieldFormat::Float3:
                return 12;

            case VertexFieldFormat::Float4:
                return 16;

            default:
                return 16;
        }
    }
} // namespace nova::renderer::rhi
<commit_msg>[rhi] Use = default<commit_after>#include "nova_renderer/rhi/rhi_types.hpp"

namespace nova::renderer::rhi {
    bool ResourceBindingDescription::operator==(const ResourceBindingDescription& other) {
        return set == other.set && binding == other.binding && count == other.count && type == other.type;
    }

    bool ResourceBindingDescription::operator!=(const ResourceBindingDescription& other) { return !(*this == other); }

    ResourceBarrier::ResourceBarrier() = default;

    DescriptorResourceInfo::DescriptorResourceInfo() = default;

    uint32_t PipelineInterface::get_num_descriptors_of_type(const DescriptorType type) const {
        uint32_t num_descriptors = 0;
        bindings.each_value([&](const ResourceBindingDescription& description) {
            if(description.type == type) {
                num_descriptors++;
            }
        });

        return num_descriptors;
    }

    ShaderStage operator|=(const ShaderStage lhs, const ShaderStage rhs) {
        return static_cast<ShaderStage>(static_cast<uint32_t>(lhs) | static_cast<uint32_t>(rhs));
    }

    bool is_depth_format(const PixelFormat format) {
        switch(format) {
            case PixelFormat::Rgba8:
                [[fallthrough]];
            case PixelFormat::Rgba16F:
                [[fallthrough]];
            case PixelFormat::Rgba32F:
                return false;

            case PixelFormat::Depth32:
                [[fallthrough]];
            case PixelFormat::Depth24Stencil8:
                return true;

            default:
                return false;
        }
    }

    uint32_t get_byte_size(const VertexFieldFormat format) {
        switch(format) {
            case VertexFieldFormat::Uint:
                return 4;

            case VertexFieldFormat::Float2:
                return 8;

            case VertexFieldFormat::Float3:
                return 12;

            case VertexFieldFormat::Float4:
                return 16;

            default:
                return 16;
        }
    }
} // namespace nova::renderer::rhi
<|endoftext|>