<commit_before>/* -------------------------------------------------------------------------- *
 *                         OpenSim:  BushingForce.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): Ajay Seth                                                       *
 *                                                                            *
 * 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 <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Simulation/Model/Model.h>

#include "BushingForce.h"

using namespace std;
using namespace SimTK;
using namespace OpenSim;

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
// Uses default (compiler-generated) destructor, copy constructor, and copy
// assignment operator.

//_____________________________________________________________________________
// Default constructor.
BushingForce::BushingForce()
{
    setNull();
    constructProperties();
}

/* Construct a BusingForce by supplying the Offset frames that the BushingForce
   acts between */
BushingForce::BushingForce(const PhysicalOffsetFrame& frame1,
    const PhysicalOffsetFrame& frame2,
    const SimTK::Vec3& transStiffness,
    const SimTK::Vec3& rotStiffness,
    const SimTK::Vec3& transDamping,
    const SimTK::Vec3& rotDamping)
{
    set_offset_frame1(frame1);
    set_offset_frame2(frame2);
    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

/* Convenience construction that creates the Offsets on the Physical Frames (e.g.
   Bodies that the BushingForce acts between. */
BushingForce::BushingForce(const PhysicalFrame& frame1,
    const SimTK::Vec3& point1,
    const SimTK::Vec3& orientation1,
    const PhysicalFrame& frame2,
    const SimTK::Vec3& point2,
    const SimTK::Vec3& orientation2,
    const SimTK::Vec3& transStiffness,
    const SimTK::Vec3& rotStiffness,
    const SimTK::Vec3& transDamping,
    const SimTK::Vec3& rotDamping)
{
    setNull();
    constructProperties();

    upd_offset_frame1().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame1.getName());
    Rotation rotation1(BodyRotationSequence,
        orientation1[0], XAxis,
        orientation1[1], YAxis,
        orientation1[2], ZAxis);
    upd_offset_frame1().setOffsetTransform(Transform(rotation1, point1));

    upd_offset_frame2().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame2.getName());
    Rotation rotation2(BodyRotationSequence,
        orientation2[0], XAxis,
        orientation2[1], YAxis,
        orientation2[2], ZAxis);
    upd_offset_frame2().setOffsetTransform(Transform(rotation2, point2));

    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

/* Convenience construction that creates the Offsets on the PhysicalFrames (e.g.
   Bodies) that the BushingForce acts between. In this case, PhysicalFrames are
   identified by name. */
BushingForce::BushingForce(const string&    frame1Name,
    const Vec3&      point1,
    const Vec3&      orientation1,
    const string&    frame2Name,
    const Vec3&      point2,
    const Vec3&      orientation2,
    const Vec3&      transStiffness,
    const Vec3&      rotStiffness,
    const Vec3&      transDamping,
    const Vec3&      rotDamping)
{
    setNull();
    constructProperties();

    //upd_frame1().setName(frame1Name + "_offset");
    upd_offset_frame1().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame1Name);
    Rotation rotation1(BodyRotationSequence,
        orientation1[0], XAxis,
        orientation1[1], YAxis,
        orientation1[2], ZAxis);
    upd_offset_frame1().setOffsetTransform(Transform(rotation1, point1));

    //upd_frame2().setName(frame2Name + "_offset");
    upd_offset_frame2().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame2Name);
    Rotation rotation2(BodyRotationSequence,
        orientation2[0], XAxis,
        orientation2[1], YAxis,
        orientation2[2], ZAxis);
    upd_offset_frame2().setOffsetTransform(Transform(rotation2, point2));

    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

//_____________________________________________________________________________
// Set the data members of this BushingForce to their null values.
void BushingForce::setNull()
{
    setAuthors("Ajay Seth");
}

//_____________________________________________________________________________
// Allocate and initialize properties.
void BushingForce::constructProperties()
{
    //Default frames
    PhysicalOffsetFrame frame1;
    PhysicalOffsetFrame frame2;
    frame1.setName("offset_frame1");
    frame2.setName("offset_frame2");

    constructProperty_offset_frame1(frame1);
    constructProperty_offset_frame2(frame2);

    // default bushing material properties
    constructProperty_rotational_stiffness(Vec3(0));
    constructProperty_translational_stiffness(Vec3(0));
    constructProperty_rotational_damping(Vec3(0));
    constructProperty_translational_damping(Vec3(0));
}

void BushingForce::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
    int documentVersion = versionNumber;
    bool converting = false;
    if (documentVersion < XMLDocument::getLatestVersion()){
        if (documentVersion < 30503){
            // replace old properties with latest use of PhysicalOffsetFrames properties
            SimTK::Xml::element_iterator body1Element = aNode.element_begin("body_1");
            SimTK::Xml::element_iterator body2Element = aNode.element_begin("body_2");
            SimTK::Xml::element_iterator locBody1Elt = aNode.element_begin("location_body_1");
            SimTK::Xml::element_iterator orientBody1Elt = aNode.element_begin("orientation_body_1");
            SimTK::Xml::element_iterator locBody2Elt = aNode.element_begin("location_body_2");
            SimTK::Xml::element_iterator orientBody2Elt = aNode.element_begin("orientation_body_2");

            // If default constructed then elements not serialized since they are default
            // values. Check that we have associated elements, then extract their values.
            if (body1Element != aNode.element_end()){
                std::string frame1_name("");
                body1Element->getValueAs<std::string>(frame1_name);
                upd_offset_frame1().updConnector(0).set_connected_to_name(frame1_name);
            }
            if (body2Element != aNode.element_end()){
                std::string frame2_name("");
                body2Element->getValueAs<std::string>(frame2_name);
                upd_offset_frame2().updConnector(0).set_connected_to_name(frame2_name);
            }
            if (locBody1Elt != aNode.element_end()){
                Vec3 location;
                locBody1Elt->getValueAs<Vec3>(location);
                upd_offset_frame1().set_translation(location);
            }
            if (orientBody1Elt != aNode.element_end()){
                Vec3 orientation;
                orientBody1Elt->getValueAs<Vec3>(orientation);
                upd_offset_frame1().set_orientation(orientation);
            }
            if (locBody2Elt != aNode.element_end()){
                Vec3 location;
                locBody2Elt->getValueAs<Vec3>(location);
                upd_offset_frame2().set_translation(location);
            }
            if (orientBody2Elt != aNode.element_end()){
                Vec3 orientation;
                orientBody2Elt->getValueAs<Vec3>(orientation);
                upd_offset_frame2().set_orientation(orientation);
            }
        }
    }
    Super::updateFromXMLNode(aNode, versionNumber);
}

void BushingForce::extendFinalizeFromProperties()
{
    Super::extendFinalizeFromProperties();

    //mark the two PhysicalOffsetFrames as subcomponents
    addComponent(&upd_offset_frame1());
    addComponent(&upd_offset_frame2());
}

// Add underly Simbody elements to the System after subcomponents
void BushingForce::
    extendAddToSystemAfterSubcomponents(SimTK::MultibodySystem& system) const
{
    Super::extendAddToSystemAfterSubcomponents(system);

    const SimTK::Vec3& rotStiffness         = get_rotational_stiffness();
    const SimTK::Vec3& transStiffness       = get_translational_stiffness();
    const SimTK::Vec3& rotDamping           = get_rotational_damping();
    const SimTK::Vec3& transDamping         = get_translational_damping();

    // Get underlying mobilized bodies
    const SimTK::MobilizedBody& b1 = get_offset_frame1().getMobilizedBody();
    const SimTK::MobilizedBody& b2 = get_offset_frame2().getMobilizedBody();

    Vec6 stiffness(rotStiffness[0], rotStiffness[1], rotStiffness[2],
                   transStiffness[0], transStiffness[1], transStiffness[2]);
    Vec6 damping(rotDamping[0], rotDamping[1], rotDamping[2],
                 transDamping[0], transDamping[1], transDamping[2]);

    // Now create a Simbody Force::LinearBushing
    SimTK::Force::LinearBushing simtkForce
        (_model->updForceSubsystem(), b1, get_offset_frame1().getOffsetTransform(),
                                      b2, get_offset_frame2().getOffsetTransform(),
                                      stiffness, damping );

    // Beyond the const Component get the index so we can access the
    // SimTK::Force later.
    BushingForce* mutableThis = const_cast<BushingForce *>(this);
    mutableThis->_index = simtkForce.getForceIndex();
}

//=============================================================================
// SET
//=============================================================================
//_____________________________________________________________________________
// The following methods set properties of the bushing Force.

/* Potential energy is computed by underlying SimTK::Force. */
double BushingForce::computePotentialEnergy(const SimTK::State& s) const
{
    return _model->getForceSubsystem().getForce(_index)
                                      .calcPotentialEnergyContribution(s);
}

//=============================================================================
// Reporting
//=============================================================================
/**
 * Provide names of the quantities (column labels) of the force value(s) reported
 *
 */
OpenSim::Array<std::string> BushingForce::getRecordLabels() const
{
    const string& frame1Name = get_offset_frame1().getName();
    const string& frame2Name = get_offset_frame2().getName();

    OpenSim::Array<std::string> labels("");
    labels.append(getName()+"."+frame1Name+".force.X");
    labels.append(getName()+"."+frame1Name+".force.Y");
    labels.append(getName()+"."+frame1Name+".force.Z");
    labels.append(getName()+"."+frame1Name+".torque.X");
    labels.append(getName()+"."+frame1Name+".torque.Y");
    labels.append(getName()+"."+frame1Name+".torque.Z");
    labels.append(getName()+"."+frame2Name+".force.X");
    labels.append(getName()+"."+frame2Name+".force.Y");
    labels.append(getName()+"."+frame2Name+".force.Z");
    labels.append(getName()+"."+frame2Name+".torque.X");
    labels.append(getName()+"."+frame2Name+".torque.Y");
    labels.append(getName()+"."+frame2Name+".torque.Z");

    return labels;
}
/**
 * Provide the value(s) to be reported that correspond to the labels
 */
OpenSim::Array<double> BushingForce::
getRecordValues(const SimTK::State& state) const
{
    const string& frame1Name = get_offset_frame1().getName();
    const string& frame2Name = get_offset_frame2().getName();

    OpenSim::Array<double> values(1);

    const SimTK::Force::LinearBushing &simtkSpring =
        (SimTK::Force::LinearBushing &)(_model->getForceSubsystem().getForce(_index));

    SimTK::Vector_<SimTK::SpatialVec> bodyForces(0);
    SimTK::Vector_<SimTK::Vec3> particleForces(0);
    SimTK::Vector mobilityForces(0);

    //get the net force added to the system contributed by the bushing
    simtkSpring.calcForceContribution(state, bodyForces, particleForces, mobilityForces);
    SimTK::Vec3 forces = bodyForces(get_offset_frame1().getMobilizedBodyIndex())[1];
    SimTK::Vec3 torques = bodyForces(get_offset_frame1().getMobilizedBodyIndex())[0];
    values.append(3, &forces[0]);
    values.append(3, &torques[0]);

    forces = bodyForces(get_offset_frame2().getMobilizedBodyIndex())[1];
    torques = bodyForces(get_offset_frame2().getMobilizedBodyIndex())[0];

    values.append(3, &forces[0]);
    values.append(3, &torques[0]);

    return values;
}
<commit_msg>BushingForce cleanup unnecessary commented lines<commit_after>/* -------------------------------------------------------------------------- *
 *                         OpenSim:  BushingForce.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): Ajay Seth                                                       *
 *                                                                            *
 * 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 <OpenSim/Simulation/Model/BodySet.h>
#include <OpenSim/Simulation/Model/Model.h>

#include "BushingForce.h"

using namespace std;
using namespace SimTK;
using namespace OpenSim;

//=============================================================================
// CONSTRUCTOR(S) AND DESTRUCTOR
//=============================================================================
// Uses default (compiler-generated) destructor, copy constructor, and copy
// assignment operator.

//_____________________________________________________________________________
// Default constructor.
BushingForce::BushingForce()
{
    setNull();
    constructProperties();
}

/* Construct a BusingForce by supplying the Offset frames that the BushingForce
   acts between */
BushingForce::BushingForce(const PhysicalOffsetFrame& frame1,
    const PhysicalOffsetFrame& frame2,
    const SimTK::Vec3& transStiffness,
    const SimTK::Vec3& rotStiffness,
    const SimTK::Vec3& transDamping,
    const SimTK::Vec3& rotDamping)
{
    set_offset_frame1(frame1);
    set_offset_frame2(frame2);
    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

/* Convenience construction that creates the Offsets on the Physical Frames (e.g.
   Bodies that the BushingForce acts between. */
BushingForce::BushingForce(const PhysicalFrame& frame1,
    const SimTK::Vec3& point1,
    const SimTK::Vec3& orientation1,
    const PhysicalFrame& frame2,
    const SimTK::Vec3& point2,
    const SimTK::Vec3& orientation2,
    const SimTK::Vec3& transStiffness,
    const SimTK::Vec3& rotStiffness,
    const SimTK::Vec3& transDamping,
    const SimTK::Vec3& rotDamping)
{
    setNull();
    constructProperties();

    upd_offset_frame1().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame1.getName());
    Rotation rotation1(BodyRotationSequence,
        orientation1[0], XAxis,
        orientation1[1], YAxis,
        orientation1[2], ZAxis);
    upd_offset_frame1().setOffsetTransform(Transform(rotation1, point1));

    upd_offset_frame2().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame2.getName());
    Rotation rotation2(BodyRotationSequence,
        orientation2[0], XAxis,
        orientation2[1], YAxis,
        orientation2[2], ZAxis);
    upd_offset_frame2().setOffsetTransform(Transform(rotation2, point2));

    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

/* Convenience construction that creates the Offsets on the PhysicalFrames (e.g.
   Bodies) that the BushingForce acts between. In this case, PhysicalFrames are
   identified by name. */
BushingForce::BushingForce(const string&    frame1Name,
    const Vec3&      point1,
    const Vec3&      orientation1,
    const string&    frame2Name,
    const Vec3&      point2,
    const Vec3&      orientation2,
    const Vec3&      transStiffness,
    const Vec3&      rotStiffness,
    const Vec3&      transDamping,
    const Vec3&      rotDamping)
{
    setNull();
    constructProperties();

    upd_offset_frame1().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame1Name);
    Rotation rotation1(BodyRotationSequence,
        orientation1[0], XAxis,
        orientation1[1], YAxis,
        orientation1[2], ZAxis);
    upd_offset_frame1().setOffsetTransform(Transform(rotation1, point1));

    upd_offset_frame2().updConnector<PhysicalFrame>("parent")
        .set_connected_to_name(frame2Name);
    Rotation rotation2(BodyRotationSequence,
        orientation2[0], XAxis,
        orientation2[1], YAxis,
        orientation2[2], ZAxis);
    upd_offset_frame2().setOffsetTransform(Transform(rotation2, point2));

    set_rotational_stiffness(rotStiffness);
    set_translational_stiffness(transStiffness);
    set_rotational_damping(rotDamping);
    set_translational_damping(transDamping);
}

//_____________________________________________________________________________
// Set the data members of this BushingForce to their null values.
void BushingForce::setNull()
{
    setAuthors("Ajay Seth");
}

//_____________________________________________________________________________
// Allocate and initialize properties.
void BushingForce::constructProperties()
{
    //Default frames
    PhysicalOffsetFrame frame1;
    PhysicalOffsetFrame frame2;
    frame1.setName("offset_frame1");
    frame2.setName("offset_frame2");

    constructProperty_offset_frame1(frame1);
    constructProperty_offset_frame2(frame2);

    // default bushing material properties
    constructProperty_rotational_stiffness(Vec3(0));
    constructProperty_translational_stiffness(Vec3(0));
    constructProperty_rotational_damping(Vec3(0));
    constructProperty_translational_damping(Vec3(0));
}

void BushingForce::updateFromXMLNode(SimTK::Xml::Element& aNode, int versionNumber)
{
    int documentVersion = versionNumber;
    bool converting = false;
    if (documentVersion < XMLDocument::getLatestVersion()){
        if (documentVersion < 30503){
            // replace old properties with latest use of PhysicalOffsetFrames properties
            SimTK::Xml::element_iterator body1Element = aNode.element_begin("body_1");
            SimTK::Xml::element_iterator body2Element = aNode.element_begin("body_2");
            SimTK::Xml::element_iterator locBody1Elt = aNode.element_begin("location_body_1");
            SimTK::Xml::element_iterator orientBody1Elt = aNode.element_begin("orientation_body_1");
            SimTK::Xml::element_iterator locBody2Elt = aNode.element_begin("location_body_2");
            SimTK::Xml::element_iterator orientBody2Elt = aNode.element_begin("orientation_body_2");

            // If default constructed then elements not serialized since they are default
            // values. Check that we have associated elements, then extract their values.
            if (body1Element != aNode.element_end()){
                std::string frame1_name("");
                body1Element->getValueAs<std::string>(frame1_name);
                upd_offset_frame1().updConnector(0).set_connected_to_name(frame1_name);
            }
            if (body2Element != aNode.element_end()){
                std::string frame2_name("");
                body2Element->getValueAs<std::string>(frame2_name);
                upd_offset_frame2().updConnector(0).set_connected_to_name(frame2_name);
            }
            if (locBody1Elt != aNode.element_end()){
                Vec3 location;
                locBody1Elt->getValueAs<Vec3>(location);
                upd_offset_frame1().set_translation(location);
            }
            if (orientBody1Elt != aNode.element_end()){
                Vec3 orientation;
                orientBody1Elt->getValueAs<Vec3>(orientation);
                upd_offset_frame1().set_orientation(orientation);
            }
            if (locBody2Elt != aNode.element_end()){
                Vec3 location;
                locBody2Elt->getValueAs<Vec3>(location);
                upd_offset_frame2().set_translation(location);
            }
            if (orientBody2Elt != aNode.element_end()){
                Vec3 orientation;
                orientBody2Elt->getValueAs<Vec3>(orientation);
                upd_offset_frame2().set_orientation(orientation);
            }
        }
    }
    Super::updateFromXMLNode(aNode, versionNumber);
}

void BushingForce::extendFinalizeFromProperties()
{
    Super::extendFinalizeFromProperties();

    //mark the two PhysicalOffsetFrames as subcomponents
    addComponent(&upd_offset_frame1());
    addComponent(&upd_offset_frame2());
}

// Add underly Simbody elements to the System after subcomponents
void BushingForce::
    extendAddToSystemAfterSubcomponents(SimTK::MultibodySystem& system) const
{
    Super::extendAddToSystemAfterSubcomponents(system);

    const SimTK::Vec3& rotStiffness         = get_rotational_stiffness();
    const SimTK::Vec3& transStiffness       = get_translational_stiffness();
    const SimTK::Vec3& rotDamping           = get_rotational_damping();
    const SimTK::Vec3& transDamping         = get_translational_damping();

    // Get underlying mobilized bodies
    const SimTK::MobilizedBody& b1 = get_offset_frame1().getMobilizedBody();
    const SimTK::MobilizedBody& b2 = get_offset_frame2().getMobilizedBody();

    Vec6 stiffness(rotStiffness[0], rotStiffness[1], rotStiffness[2],
                   transStiffness[0], transStiffness[1], transStiffness[2]);
    Vec6 damping(rotDamping[0], rotDamping[1], rotDamping[2],
                 transDamping[0], transDamping[1], transDamping[2]);

    // Now create a Simbody Force::LinearBushing
    SimTK::Force::LinearBushing simtkForce
        (_model->updForceSubsystem(), b1, get_offset_frame1().getOffsetTransform(),
                                      b2, get_offset_frame2().getOffsetTransform(),
                                      stiffness, damping );

    // Beyond the const Component get the index so we can access the
    // SimTK::Force later.
    BushingForce* mutableThis = const_cast<BushingForce *>(this);
    mutableThis->_index = simtkForce.getForceIndex();
}

//=============================================================================
// SET
//=============================================================================
//_____________________________________________________________________________
// The following methods set properties of the bushing Force.

/* Potential energy is computed by underlying SimTK::Force. */
double BushingForce::computePotentialEnergy(const SimTK::State& s) const
{
    return _model->getForceSubsystem().getForce(_index)
                                      .calcPotentialEnergyContribution(s);
}

//=============================================================================
// Reporting
//=============================================================================
/**
 * Provide names of the quantities (column labels) of the force value(s) reported
 *
 */
OpenSim::Array<std::string> BushingForce::getRecordLabels() const
{
    const string& frame1Name = get_offset_frame1().getName();
    const string& frame2Name = get_offset_frame2().getName();

    OpenSim::Array<std::string> labels("");
    labels.append(getName()+"."+frame1Name+".force.X");
    labels.append(getName()+"."+frame1Name+".force.Y");
    labels.append(getName()+"."+frame1Name+".force.Z");
    labels.append(getName()+"."+frame1Name+".torque.X");
    labels.append(getName()+"."+frame1Name+".torque.Y");
    labels.append(getName()+"."+frame1Name+".torque.Z");
    labels.append(getName()+"."+frame2Name+".force.X");
    labels.append(getName()+"."+frame2Name+".force.Y");
    labels.append(getName()+"."+frame2Name+".force.Z");
    labels.append(getName()+"."+frame2Name+".torque.X");
    labels.append(getName()+"."+frame2Name+".torque.Y");
    labels.append(getName()+"."+frame2Name+".torque.Z");

    return labels;
}
/**
 * Provide the value(s) to be reported that correspond to the labels
 */
OpenSim::Array<double> BushingForce::
getRecordValues(const SimTK::State& state) const
{
    const string& frame1Name = get_offset_frame1().getName();
    const string& frame2Name = get_offset_frame2().getName();

    OpenSim::Array<double> values(1);

    const SimTK::Force::LinearBushing &simtkSpring =
        (SimTK::Force::LinearBushing &)(_model->getForceSubsystem().getForce(_index));

    SimTK::Vector_<SimTK::SpatialVec> bodyForces(0);
    SimTK::Vector_<SimTK::Vec3> particleForces(0);
    SimTK::Vector mobilityForces(0);

    //get the net force added to the system contributed by the bushing
    simtkSpring.calcForceContribution(state, bodyForces, particleForces, mobilityForces);
    SimTK::Vec3 forces = bodyForces(get_offset_frame1().getMobilizedBodyIndex())[1];
    SimTK::Vec3 torques = bodyForces(get_offset_frame1().getMobilizedBodyIndex())[0];
    values.append(3, &forces[0]);
    values.append(3, &torques[0]);

    forces = bodyForces(get_offset_frame2().getMobilizedBodyIndex())[1];
    torques = bodyForces(get_offset_frame2().getMobilizedBodyIndex())[0];

    values.append(3, &forces[0]);
    values.append(3, &torques[0]);

    return values;
}
<|endoftext|>


<commit_before>#include <cstdio>

#include "ClimateType.h"
#include "WeatherType.h"
#include "WeatherUtils.h"
#include "WildWorldUtils.h"

#include "components/debug/Debug.h"

DOSUtils::FilenameBuffer WildWorldUtils::generateInfName(ClimateType climateType,
	WeatherType weatherType)
{
	const char climateLetter = [climateType]()
	{
		if (climateType == ClimateType::Temperate)
		{
			return 'T';
		}
		else if (climateType == ClimateType::Desert)
		{
			return 'D';
		}
		else
		{
			return 'M';
		}
	}();

	// Wilderness is "W".
	const char locationLetter = 'W';

	const char weatherLetter = [climateType, weatherType]()
	{
		if (WeatherUtils::isClear(weatherType) || WeatherUtils::isOvercast(weatherType))
		{
			return 'N';
		}
		else if (WeatherUtils::isRain(weatherType))
		{
			return 'R';
		}
		else if (WeatherUtils::isSnow(weatherType))
		{
			// Deserts can't have snow.
			if (climateType != ClimateType::Desert)
			{
				return 'S';
			}
			else
			{
				DebugLogWarning("Deserts do not have snow templates.");
				return 'N';
			}
		}
		else
		{
			// Not sure what this means.
			return 'W';
		}
	}();

	DOSUtils::FilenameBuffer buffer;
	std::snprintf(buffer.data(), buffer.size(), "%C%C%C.INF",
		climateLetter, locationLetter, weatherLetter);

	return buffer;
}
<commit_msg>Added better else case to wild climate type .INF branches.<commit_after>#include <cstdio>

#include "ClimateType.h"
#include "WeatherType.h"
#include "WeatherUtils.h"
#include "WildWorldUtils.h"

#include "components/debug/Debug.h"

DOSUtils::FilenameBuffer WildWorldUtils::generateInfName(ClimateType climateType,
	WeatherType weatherType)
{
	const char climateLetter = [climateType]()
	{
		if (climateType == ClimateType::Temperate)
		{
			return 'T';
		}
		else if (climateType == ClimateType::Desert)
		{
			return 'D';
		}
		else if (climateType == ClimateType::Mountain)
		{
			return 'M';
		}
		else
		{
			DebugUnhandledReturnMsg(char, std::to_string(static_cast<int>(climateType)));
		}
	}();

	// Wilderness is "W".
	const char locationLetter = 'W';

	const char weatherLetter = [climateType, weatherType]()
	{
		if (WeatherUtils::isClear(weatherType) || WeatherUtils::isOvercast(weatherType))
		{
			return 'N';
		}
		else if (WeatherUtils::isRain(weatherType))
		{
			return 'R';
		}
		else if (WeatherUtils::isSnow(weatherType))
		{
			// Deserts can't have snow.
			if (climateType != ClimateType::Desert)
			{
				return 'S';
			}
			else
			{
				DebugLogWarning("Deserts do not have snow templates.");
				return 'N';
			}
		}
		else
		{
			// Not sure what this means.
			return 'W';
		}
	}();

	DOSUtils::FilenameBuffer buffer;
	std::snprintf(buffer.data(), buffer.size(), "%C%C%C.INF",
		climateLetter, locationLetter, weatherLetter);

	return buffer;
}
<|endoftext|>


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

/***********************************************************************************************************************
 * View.cpp
 *
 *  Created on: Dec 6, 2010
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "views/View.h"
#include "Scene.h"
#include "VisualizationManager.h"

namespace Visualization {

View::View(Scene* scene, View *parent) :
	QGraphicsView(scene, parent), hiddenItemCategories_(0)
{
	if ( parent == nullptr )
	{
		setParent(VisualizationManager::instance().getMainWindow());
		VisualizationManager::instance().addTopLevelView(this);
	}
}

View::~View()
{
}

QRectF View::visibleRect()
{
	int h = horizontalScrollBar() ? horizontalScrollBar()->height() : 0;
	int w = verticalScrollBar() ? verticalScrollBar()->width() : 0;
	return mapToScene(viewport()->rect().adjusted(0,0,-w,-h)).boundingRect();
}

Scene* View::scene()
{
	return static_cast<Scene*> (QGraphicsView::scene());
}

void View::paintEvent(QPaintEvent* event)
{
	scene()->setHiddenItemCategories(hiddenItemCategories_);
	QGraphicsView::paintEvent(event);
}

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

/***********************************************************************************************************************
 * View.cpp
 *
 *  Created on: Dec 6, 2010
 *      Author: Dimitar Asenov
 **********************************************************************************************************************/

#include "views/View.h"
#include "Scene.h"
#include "VisualizationManager.h"

namespace Visualization {

View::View(Scene* scene, View *parent) :
	QGraphicsView(scene, parent), hiddenItemCategories_(0)
{
	setOptimizationFlag(DontSavePainterState);
	if ( parent == nullptr )
	{
		setParent(VisualizationManager::instance().getMainWindow());
		VisualizationManager::instance().addTopLevelView(this);
	}
}

View::~View()
{
}

QRectF View::visibleRect()
{
	int h = horizontalScrollBar() ? horizontalScrollBar()->height() : 0;
	int w = verticalScrollBar() ? verticalScrollBar()->width() : 0;
	return mapToScene(viewport()->rect().adjusted(0,0,-w,-h)).boundingRect();
}

Scene* View::scene()
{
	return static_cast<Scene*> (QGraphicsView::scene());
}

void View::paintEvent(QPaintEvent* event)
{
	scene()->setHiddenItemCategories(hiddenItemCategories_);
	QGraphicsView::paintEvent(event);
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2013 Vicente Romero Calero
//
// Distributed under the MIT software license, see the file LICENSE
//
// Author: Vicente Romero <vteromero@gmail.com>

#include "sort-stats.h"

#include <stdio.h>
#include <cmath>

void InitSortStats(SortStats *stats)
{
    stats->array_length = 0;
    stats->iterations = 0;
    stats->comparisons = 0;
    stats->swaps = 0;
    stats->extra_memory = 0;
}

void PrintSortStats(const SortStats& stats)
{
    double one_n = 1.0 / (double)stats.array_length;
    double iter_n = stats.iterations * one_n;
    double comp_n = stats.comparisons * one_n;
    double swaps_n = stats.swaps * one_n;

    double log2n = log2(stats.array_length);
    long long square_n = stats.array_length * stats.array_length;

    printf("\n** Stats **\n\n");
    printf("%-20s%20d\n", "Array length (N):", stats.array_length);
    printf("%-20s%20llu%10.1f*N\n", "Iterations:", stats.iterations, iter_n);
    printf("%-20s%20llu%10.1f*N\n", "Comparisons:", stats.comparisons, comp_n);
    printf("%-20s%20llu%10.1f*N\n", "Swaps:", stats.swaps, swaps_n);
    printf("%-20s%20llu bytes\n", "Extra memory:", stats.extra_memory);
    printf("\nReference metrics:\n");
    printf("    log2(N) = %.1f\n", log2n);
    printf("    N^2 = %lld\n", square_n);
}
<commit_msg>fixed bug when exceeding data type limit<commit_after>// Copyright (c) 2013 Vicente Romero Calero
//
// Distributed under the MIT software license, see the file LICENSE
//
// Author: Vicente Romero <vteromero@gmail.com>

#include "sort-stats.h"

#include <stdio.h>
#include <cmath>

void InitSortStats(SortStats *stats)
{
    stats->array_length = 0;
    stats->iterations = 0;
    stats->comparisons = 0;
    stats->swaps = 0;
    stats->extra_memory = 0;
}

void PrintSortStats(const SortStats& stats)
{
    double one_n = 1.0 / (double)stats.array_length;
    double iter_n = stats.iterations * one_n;
    double comp_n = stats.comparisons * one_n;
    double swaps_n = stats.swaps * one_n;

    double log2n = log2(stats.array_length);
    long long square_n = (long long)stats.array_length * stats.array_length;

    printf("\n** Stats **\n\n");
    printf("%-20s%20d\n", "Array length (N):", stats.array_length);
    printf("%-20s%20llu%10.1f*N\n", "Iterations:", stats.iterations, iter_n);
    printf("%-20s%20llu%10.1f*N\n", "Comparisons:", stats.comparisons, comp_n);
    printf("%-20s%20llu%10.1f*N\n", "Swaps:", stats.swaps, swaps_n);
    printf("%-20s%20llu bytes\n", "Extra memory:", stats.extra_memory);
    printf("\nReference metrics:\n");
    printf("    log2(N) = %.1f\n", log2n);
    printf("    N^2 = %lld\n", square_n);
}
<|endoftext|>


<commit_before>#include "Halide.h"
#include "stubtest.stub.h"

using StubNS1::StubNS2::StubTest;

namespace {

class StubUser : public Halide::Generator<StubUser> {
public:
    GeneratorParam<int32_t> int_arg{ "int_arg", 33 };

    Input<Func> input{ "input", UInt(8), 3 };
    Output<Func> output{"output", UInt(8), 3};

    void generate() {

        // We'll explicit fill in the struct fields by name, just to show
        // it as an option. (Alternately, we could fill it in by using
        // C++11 aggregate-initialization syntax.)
        StubTest::Inputs inputs;
        inputs.input = { input };
        inputs.float_arg = 1.234f;
        inputs.int_arg = { int_arg };

        stub = StubTest(context(), inputs);

        const float kOffset = 2.f;
        output(x, y, c) = cast<uint8_t>(stub.f(x, y, c)[1] + kOffset);
    }

    void schedule() {
        const bool vectorize = true;
        stub.schedule({ vectorize, LoopLevel(output, Var("y")) });
    }

private:
    Var x{"x"}, y{"y"}, c{"c"};
    StubTest stub;
};

// Note that HALIDE_REGISTER_GENERATOR() with just two args is functionally
// identical to the old Halide::RegisterGenerator<> syntax: no stub being defined,
// just AOT usage. (If you try to generate a stub for this class you'll
// fail with an error at generation time.)
HALIDE_REGISTER_GENERATOR(StubUser, "stubuser")

}  // namespace
<commit_msg>Use *this instead of context() in StubUser<commit_after>#include "Halide.h"
#include "stubtest.stub.h"

using StubNS1::StubNS2::StubTest;

namespace {

class StubUser : public Halide::Generator<StubUser> {
public:
    GeneratorParam<int32_t> int_arg{ "int_arg", 33 };

    Input<Func> input{ "input", UInt(8), 3 };
    Output<Func> output{"output", UInt(8), 3};

    void generate() {

        // We'll explicit fill in the struct fields by name, just to show
        // it as an option. (Alternately, we could fill it in by using
        // C++11 aggregate-initialization syntax.)
        StubTest::Inputs inputs;
        inputs.input = { input };
        inputs.float_arg = 1.234f;
        inputs.int_arg = { int_arg };

        stub = StubTest(*this, inputs);

        const float kOffset = 2.f;
        output(x, y, c) = cast<uint8_t>(stub.f(x, y, c)[1] + kOffset);
    }

    void schedule() {
        const bool vectorize = true;
        stub.schedule({ vectorize, LoopLevel(output, Var("y")) });
    }

private:
    Var x{"x"}, y{"y"}, c{"c"};
    StubTest stub;
};

// Note that HALIDE_REGISTER_GENERATOR() with just two args is functionally
// identical to the old Halide::RegisterGenerator<> syntax: no stub being defined,
// just AOT usage. (If you try to generate a stub for this class you'll
// fail with an error at generation time.)
HALIDE_REGISTER_GENERATOR(StubUser, "stubuser")

}  // namespace
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageActorPointPlacer.cxx

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

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

=========================================================================*/
#include "vtkImageActorPointPlacer.h"
#include "vtkObjectFactory.h"
#include "vtkBoundedPlanePointPlacer.h"
#include "vtkPlane.h"
#include "vtkRenderer.h"
#include "vtkImageActor.h"
#include "vtkImageData.h"

vtkCxxRevisionMacro(vtkImageActorPointPlacer, "1.1");
vtkStandardNewMacro(vtkImageActorPointPlacer);

vtkCxxSetObjectMacro(vtkImageActorPointPlacer, ImageActor, vtkImageActor);

//----------------------------------------------------------------------
vtkImageActorPointPlacer::vtkImageActorPointPlacer()
{
  this->Placer = vtkBoundedPlanePointPlacer::New();
  this->ImageActor = NULL;
  this->SavedBounds[0] = 0.0;
  this->SavedBounds[1] = 0.0;
  this->SavedBounds[2] = 0.0;
  this->SavedBounds[3] = 0.0;
  this->SavedBounds[4] = 0.0;
  this->SavedBounds[5] = 0.0;
}

//----------------------------------------------------------------------
vtkImageActorPointPlacer::~vtkImageActorPointPlacer()
{
  this->Placer->Delete();
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren,
                                                    double  displayPos[2],
                                                    double *refWorldPos,
                                                    double  worldPos[3],
                                                    double  worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ComputeWorldPosition( ren, displayPos,
                                             refWorldPos, worldPos,
                                             worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren,
                                                    double displayPos[2],
                                                    double worldPos[3],
                                                    double worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ComputeWorldPosition( ren, displayPos, worldPos, worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ValidateWorldPosition( double worldPos[3],
                                                     double *worldOrient )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ValidateWorldPosition( worldPos, worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ValidateWorldPosition( double worldPos[3] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ValidateWorldPosition( worldPos );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::UpdateWorldPosition( vtkRenderer *ren,
                                                   double worldPos[3],
                                                   double worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->UpdateWorldPosition( ren,
                                            worldPos,
                                            worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::UpdateInternalState()
{
  if ( !this->ImageActor )
    {
    return 0;
    }

  vtkImageData *input;
  input = this->ImageActor->GetInput();
  if ( !input )
    {
    return 0;
    }

  double spacing[3];
  input->GetSpacing(spacing);

  double origin[3];
  input->GetOrigin(origin);

  double bounds[6];
  this->ImageActor->GetBounds(bounds);

  int displayExtent[6];
  this->ImageActor->GetDisplayExtent(displayExtent);

  int axis;
  double position;
  if ( displayExtent[0] == displayExtent[1] )
    {
    axis = vtkBoundedPlanePointPlacer::XAxis;
    position = origin[0] + displayExtent[0]*spacing[0];
    }
  else if ( displayExtent[2] == displayExtent[3] )
    {
    axis = vtkBoundedPlanePointPlacer::YAxis;
    position = origin[1] + displayExtent[2]*spacing[1];
    }
  else if ( displayExtent[4] == displayExtent[5] )
    {
    axis = vtkBoundedPlanePointPlacer::ZAxis;
    position = origin[2] + displayExtent[4]*spacing[2];
    }
  else
    {
    vtkErrorMacro("Incorrect display extent in Image Actor");
    return 0;
    }

  if ( axis != this->Placer->GetProjectionNormal() ||
       position != this->Placer->GetProjectionPosition() ||
       bounds[0] != this->SavedBounds[0] ||
       bounds[1] != this->SavedBounds[1] ||
       bounds[2] != this->SavedBounds[2] ||
       bounds[3] != this->SavedBounds[3] ||
       bounds[4] != this->SavedBounds[4] ||
       bounds[5] != this->SavedBounds[5] )
    {
    this->SavedBounds[0] = bounds[0];
    this->SavedBounds[1] = bounds[1];
    this->SavedBounds[2] = bounds[2];
    this->SavedBounds[3] = bounds[3];
    this->SavedBounds[4] = bounds[4];
    this->SavedBounds[5] = bounds[5];

    this->Placer->SetProjectionNormal(axis);
    this->Placer->SetProjectionPosition(position);

    this->Placer->RemoveAllBoundingPlanes();

    vtkPlane *plane;

    if ( axis != vtkBoundedPlanePointPlacer::XAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 1.0, 0.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( -1.0, 0.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    if ( axis != vtkBoundedPlanePointPlacer::YAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 0.0, 1.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( 0.0, -1.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    if ( axis != vtkBoundedPlanePointPlacer::ZAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 0.0, 0.0, 1.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( 0.0, 0.0, -1.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    this->Modified();
    }

  return 1;
}

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

}

<commit_msg>BUG: fixed leak - needed to set ImageActor to null on delete<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageActorPointPlacer.cxx

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

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

=========================================================================*/
#include "vtkImageActorPointPlacer.h"
#include "vtkObjectFactory.h"
#include "vtkBoundedPlanePointPlacer.h"
#include "vtkPlane.h"
#include "vtkRenderer.h"
#include "vtkImageActor.h"
#include "vtkImageData.h"

vtkCxxRevisionMacro(vtkImageActorPointPlacer, "1.2");
vtkStandardNewMacro(vtkImageActorPointPlacer);

vtkCxxSetObjectMacro(vtkImageActorPointPlacer, ImageActor, vtkImageActor);

//----------------------------------------------------------------------
vtkImageActorPointPlacer::vtkImageActorPointPlacer()
{
  this->Placer = vtkBoundedPlanePointPlacer::New();
  this->ImageActor = NULL;
  this->SavedBounds[0] = 0.0;
  this->SavedBounds[1] = 0.0;
  this->SavedBounds[2] = 0.0;
  this->SavedBounds[3] = 0.0;
  this->SavedBounds[4] = 0.0;
  this->SavedBounds[5] = 0.0;
}

//----------------------------------------------------------------------
vtkImageActorPointPlacer::~vtkImageActorPointPlacer()
{
  this->Placer->Delete();
  this->SetImageActor(NULL);
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren,
                                                    double  displayPos[2],
                                                    double *refWorldPos,
                                                    double  worldPos[3],
                                                    double  worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ComputeWorldPosition( ren, displayPos,
                                             refWorldPos, worldPos,
                                             worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ComputeWorldPosition( vtkRenderer *ren,
                                                    double displayPos[2],
                                                    double worldPos[3],
                                                    double worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ComputeWorldPosition( ren, displayPos, worldPos, worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ValidateWorldPosition( double worldPos[3],
                                                     double *worldOrient )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ValidateWorldPosition( worldPos, worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::ValidateWorldPosition( double worldPos[3] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->ValidateWorldPosition( worldPos );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::UpdateWorldPosition( vtkRenderer *ren,
                                                   double worldPos[3],
                                                   double worldOrient[9] )
{
  if ( !this->UpdateInternalState() )
    {
    return 0;
    }

  return this->Placer->UpdateWorldPosition( ren,
                                            worldPos,
                                            worldOrient );
}

//----------------------------------------------------------------------
int vtkImageActorPointPlacer::UpdateInternalState()
{
  if ( !this->ImageActor )
    {
    return 0;
    }

  vtkImageData *input;
  input = this->ImageActor->GetInput();
  if ( !input )
    {
    return 0;
    }

  double spacing[3];
  input->GetSpacing(spacing);

  double origin[3];
  input->GetOrigin(origin);

  double bounds[6];
  this->ImageActor->GetBounds(bounds);

  int displayExtent[6];
  this->ImageActor->GetDisplayExtent(displayExtent);

  int axis;
  double position;
  if ( displayExtent[0] == displayExtent[1] )
    {
    axis = vtkBoundedPlanePointPlacer::XAxis;
    position = origin[0] + displayExtent[0]*spacing[0];
    }
  else if ( displayExtent[2] == displayExtent[3] )
    {
    axis = vtkBoundedPlanePointPlacer::YAxis;
    position = origin[1] + displayExtent[2]*spacing[1];
    }
  else if ( displayExtent[4] == displayExtent[5] )
    {
    axis = vtkBoundedPlanePointPlacer::ZAxis;
    position = origin[2] + displayExtent[4]*spacing[2];
    }
  else
    {
    vtkErrorMacro("Incorrect display extent in Image Actor");
    return 0;
    }

  if ( axis != this->Placer->GetProjectionNormal() ||
       position != this->Placer->GetProjectionPosition() ||
       bounds[0] != this->SavedBounds[0] ||
       bounds[1] != this->SavedBounds[1] ||
       bounds[2] != this->SavedBounds[2] ||
       bounds[3] != this->SavedBounds[3] ||
       bounds[4] != this->SavedBounds[4] ||
       bounds[5] != this->SavedBounds[5] )
    {
    this->SavedBounds[0] = bounds[0];
    this->SavedBounds[1] = bounds[1];
    this->SavedBounds[2] = bounds[2];
    this->SavedBounds[3] = bounds[3];
    this->SavedBounds[4] = bounds[4];
    this->SavedBounds[5] = bounds[5];

    this->Placer->SetProjectionNormal(axis);
    this->Placer->SetProjectionPosition(position);

    this->Placer->RemoveAllBoundingPlanes();

    vtkPlane *plane;

    if ( axis != vtkBoundedPlanePointPlacer::XAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 1.0, 0.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( -1.0, 0.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    if ( axis != vtkBoundedPlanePointPlacer::YAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 0.0, 1.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( 0.0, -1.0, 0.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    if ( axis != vtkBoundedPlanePointPlacer::ZAxis )
      {
      plane = vtkPlane::New();
      plane->SetOrigin( bounds[0], bounds[2], bounds[4] );
      plane->SetNormal( 0.0, 0.0, 1.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();

      plane = vtkPlane::New();
      plane->SetOrigin( bounds[1], bounds[3], bounds[5] );
      plane->SetNormal( 0.0, 0.0, -1.0 );
      this->Placer->AddBoundingPlane( plane );
      plane->Delete();
      }

    this->Modified();
    }

  return 1;
}

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

}

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// index_performance_test.cpp
//
// Identification: test/index/index_performance_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "common/harness.h"

#include <vector>
#include <thread>

#include "common/logger.h"
#include "common/platform.h"
#include "common/timer.h"
#include "index/index_factory.h"
#include "storage/tuple.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Index Performance Tests
//===--------------------------------------------------------------------===//

class IndexPerformanceTests : public PelotonTest {};

catalog::Schema *key_schema = nullptr;
catalog::Schema *tuple_schema = nullptr;

ItemPointer item0(120, 5);
ItemPointer item1(120, 7);

index::Index *BuildIndex(const bool unique_keys,
                         const IndexType index_type) {
  // Build tuple and key schema
  std::vector<std::vector<std::string>> column_names;
  std::vector<catalog::Column> columns;
  std::vector<catalog::Schema *> schemas;

  catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "A", true);
  catalog::Column column2(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "B", true);
  catalog::Column column3(VALUE_TYPE_DOUBLE, GetTypeSize(VALUE_TYPE_DOUBLE),
                          "C", true);
  catalog::Column column4(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "D", true);

  columns.push_back(column1);
  columns.push_back(column2);

  // INDEX KEY SCHEMA -- {column1, column2}
  std::vector<oid_t> key_attrs = {0, 1};
  key_schema = new catalog::Schema(columns);
  key_schema->SetIndexedColumns(key_attrs);

  columns.push_back(column3);
  columns.push_back(column4);

  // TABLE SCHEMA -- {column1, column2, column3, column4}
  tuple_schema = new catalog::Schema(columns);

  // Build index metadata
  index::IndexMetadata *index_metadata = new index::IndexMetadata(
      "test_index", 125, index_type, INDEX_CONSTRAINT_TYPE_DEFAULT,
      tuple_schema, key_schema, key_attrs, unique_keys);

  // Build index
  index::Index *index = index::IndexFactory::GetInstance(index_metadata);
  EXPECT_TRUE(index != NULL);

  return index;
}

/*
 * InsertTest1() - Tests InsertEntry() performance for each index type
 *
 * This function tests threads inserting on its own consecutive interval
 * without any interleaving with each other.
 *
 * The insert pattern is depicted as follows:
 *
 * |<--- thread 0 --->|<--- thread 1 --->| ... |<--- thread (num_thread - 1) --->|
 *  ^                ^
 * start key       end key
 */
void InsertTest1(index::Index *index,
                 size_t num_thread,
                 size_t num_key,
                 uint64_t thread_id) {
  // To avoid compiler warning
  (void)num_thread;

  // Each thread is responsible for a consecutive range of keys
  // and here is the range: [start_key, end_key)
  size_t start_key = thread_id * num_key;
  size_t end_key = start_key + num_key;

  std::unique_ptr<storage::Tuple> key(new storage::Tuple(key_schema, true));

  // Set the non-indexed column of the key to avoid undefined behaviour
  //key->SetValue(2, ValueFactory::GetDoubleValue(1.11), nullptr);
  //key->SetValue(3, ValueFactory::GetIntegerValue(12345), nullptr);

  for (size_t i = start_key;i < end_key;i++) {
    auto key_value =  ValueFactory::GetIntegerValue(i);

    key->SetValue(0, key_value, nullptr);
    key->SetValue(1, key_value, nullptr);

    auto status = index->InsertEntry(key.get(), item0);
    EXPECT_TRUE(status);
  }

  // Perform garbage collection
  if(index->NeedGC() == true) {
    index->PerformGC();
  }

  return;
}

static void TestIndexPerformance(const IndexType& index_type) {
  std::vector<ItemPointer *> location_ptrs;

  // INDEX
  std::unique_ptr<index::Index> index(BuildIndex(false, index_type));

  // Parallel Test by default 4 Million key

  // Number of threads doing insert or delete
  size_t num_thread = 4;

  // Number of keys inserted by each thread
  size_t num_key = 1024 * 256;

  Timer<> timer;

  std::vector<std::thread> thread_group;

  timer.Start();

  // First two arguments are used for launching tasks
  // All remaining arguments are passed to the thread body
  LaunchParallelTest(num_thread, InsertTest1, index.get(), num_thread, num_key);

  index->ScanAllKeys(location_ptrs);
  EXPECT_EQ(location_ptrs.size(), num_thread * num_key);
  location_ptrs.clear();

  timer.Stop();
  LOG_INFO("Type = %d; Duration = %.2lf", (int)index_type, timer.GetDuration());

  delete tuple_schema;
}

TEST_F(IndexPerformanceTests, MultiThreadedTest) {
  std::vector<IndexType> index_types = {INDEX_TYPE_BTREE, INDEX_TYPE_SKIPLIST, INDEX_TYPE_BWTREE};

  for(auto index_type : index_types) {
    TestIndexPerformance(index_type);
  }

}

}  // End test namespace
}  // End peloton namespace
<commit_msg>Change the place where GC is called in performance test (should be called in single thread environemnt)<commit_after>//===----------------------------------------------------------------------===//
//
//                         Peloton
//
// index_performance_test.cpp
//
// Identification: test/index/index_performance_test.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "gtest/gtest.h"
#include "common/harness.h"

#include <vector>
#include <thread>

#include "common/logger.h"
#include "common/platform.h"
#include "common/timer.h"
#include "index/index_factory.h"
#include "storage/tuple.h"

namespace peloton {
namespace test {

//===--------------------------------------------------------------------===//
// Index Performance Tests
//===--------------------------------------------------------------------===//

class IndexPerformanceTests : public PelotonTest {};

catalog::Schema *key_schema = nullptr;
catalog::Schema *tuple_schema = nullptr;

ItemPointer item0(120, 5);
ItemPointer item1(120, 7);

index::Index *BuildIndex(const bool unique_keys,
                         const IndexType index_type) {
  // Build tuple and key schema
  std::vector<std::vector<std::string>> column_names;
  std::vector<catalog::Column> columns;
  std::vector<catalog::Schema *> schemas;

  catalog::Column column1(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "A", true);
  catalog::Column column2(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "B", true);
  catalog::Column column3(VALUE_TYPE_DOUBLE, GetTypeSize(VALUE_TYPE_DOUBLE),
                          "C", true);
  catalog::Column column4(VALUE_TYPE_INTEGER, GetTypeSize(VALUE_TYPE_INTEGER),
                          "D", true);

  columns.push_back(column1);
  columns.push_back(column2);

  // INDEX KEY SCHEMA -- {column1, column2}
  std::vector<oid_t> key_attrs = {0, 1};
  key_schema = new catalog::Schema(columns);
  key_schema->SetIndexedColumns(key_attrs);

  columns.push_back(column3);
  columns.push_back(column4);

  // TABLE SCHEMA -- {column1, column2, column3, column4}
  tuple_schema = new catalog::Schema(columns);

  // Build index metadata
  index::IndexMetadata *index_metadata = new index::IndexMetadata(
      "test_index", 125, index_type, INDEX_CONSTRAINT_TYPE_DEFAULT,
      tuple_schema, key_schema, key_attrs, unique_keys);

  // Build index
  index::Index *index = index::IndexFactory::GetInstance(index_metadata);
  EXPECT_TRUE(index != NULL);

  return index;
}

/*
 * InsertTest1() - Tests InsertEntry() performance for each index type
 *
 * This function tests threads inserting on its own consecutive interval
 * without any interleaving with each other.
 *
 * The insert pattern is depicted as follows:
 *
 * |<--- thread 0 --->|<--- thread 1 --->| ... |<--- thread (num_thread - 1) --->|
 *  ^                ^
 * start key       end key
 */
void InsertTest1(index::Index *index,
                 size_t num_thread,
                 size_t num_key,
                 uint64_t thread_id) {
  // To avoid compiler warning
  (void)num_thread;

  // Each thread is responsible for a consecutive range of keys
  // and here is the range: [start_key, end_key)
  size_t start_key = thread_id * num_key;
  size_t end_key = start_key + num_key;

  std::unique_ptr<storage::Tuple> key(new storage::Tuple(key_schema, true));

  // Set the non-indexed column of the key to avoid undefined behaviour
  //key->SetValue(2, ValueFactory::GetDoubleValue(1.11), nullptr);
  //key->SetValue(3, ValueFactory::GetIntegerValue(12345), nullptr);

  for (size_t i = start_key;i < end_key;i++) {
    auto key_value =  ValueFactory::GetIntegerValue(i);

    key->SetValue(0, key_value, nullptr);
    key->SetValue(1, key_value, nullptr);

    auto status = index->InsertEntry(key.get(), item0);
    EXPECT_TRUE(status);
  }

  return;
}

static void TestIndexPerformance(const IndexType& index_type) {
  std::vector<ItemPointer *> location_ptrs;

  // INDEX
  std::unique_ptr<index::Index> index(BuildIndex(false, index_type));

  // Parallel Test by default 4 Million key

  // Number of threads doing insert or delete
  size_t num_thread = 4;

  // Number of keys inserted by each thread
  size_t num_key = 1024 * 256;

  Timer<> timer;

  std::vector<std::thread> thread_group;

  timer.Start();

  // First two arguments are used for launching tasks
  // All remaining arguments are passed to the thread body
  LaunchParallelTest(num_thread, InsertTest1, index.get(), num_thread, num_key);

  // Perform garbage collection
  if(index->NeedGC() == true) {
    index->PerformGC();
  }

  index->ScanAllKeys(location_ptrs);
  EXPECT_EQ(location_ptrs.size(), num_thread * num_key);
  location_ptrs.clear();

  timer.Stop();
  LOG_INFO("Type = %d; Duration = %.2lf", (int)index_type, timer.GetDuration());

  delete tuple_schema;
}

TEST_F(IndexPerformanceTests, MultiThreadedTest) {
  std::vector<IndexType> index_types = {INDEX_TYPE_BTREE, INDEX_TYPE_SKIPLIST, INDEX_TYPE_BWTREE};

  for(auto index_type : index_types) {
    TestIndexPerformance(index_type);
  }

}

}  // End test namespace
}  // End peloton namespace
<|endoftext|>


<commit_before><commit_msg>better adc switching<commit_after><|endoftext|>


<commit_before>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).

#include "org/xtreemfs/client.h"
#include "main.h"
using namespace org::xtreemfs::client;

#include "org/xtreemfs/interfaces/constants.h"

#include "yield.h"
#include "yieldfs.h"

#include <vector>
#include <exception>

#ifndef _WIN32
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <unistd.h>
#endif

namespace org
{
  namespace xtreemfs
  {
    namespace client
    {
      class xtfs_mount : public Main
      {
      public:
        xtfs_mount()
          : Main( "xtfs_mount", "mount an XtreemFS volume", "[oncrpc[s]://]<dir host>[:dir port]/<volume name> <mount point>" )
        {
          addOption( XTFS_MOUNT_OPTION_CACHE_METADATA, "--cache-metadata" );
          cache_metadata = false;

          direct_io = false;

          addOption( XTFS_MOUNT_OPTION_FOREGROUND, "-f", "--foreground" );
          foreground = false;

          addOption( XTFS_MOUNT_OPTION_FUSE_OPTION, "-o", NULL, "<fuse_option>" );
        }

      private:
        enum
        {
          XTFS_MOUNT_OPTION_CACHE_METADATA = 10,
          XTFS_MOUNT_OPTION_DIRECT_IO = 11,
          XTFS_MOUNT_OPTION_FOREGROUND = 12,
          XTFS_MOUNT_OPTION_FUSE_OPTION = 13
        };

        bool cache_metadata;
        bool direct_io;
        std::auto_ptr<YIELD::URI> dir_uri;
        bool foreground;
        std::string fuse_o_args;
        std::string mount_point, volume_name;

        // xtfs_bin
        int _main( int argc, char** argv )
        {
          if ( foreground )
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": running in foreground.";
          else
          {
#ifndef _WIN32
            if ( daemon( 1, 0 ) == -1 )
              return errno;
#endif
          }

          YIELD::SEDAStageGroup& main_stage_group = YIELD::SEDAStageGroup::createStageGroup();

          // Create the DIRProxy
          YIELD::auto_Object<DIRProxy> dir_proxy = createProxy<DIRProxy>( *dir_uri.get() );
          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": using DIR URI " << static_cast<const char*>( *dir_uri.get() ) << ".";
          main_stage_group.createStage( *dir_proxy.get() );

          // Create the MRCProxy
          YIELD::URI mrc_uri = dir_proxy.get()->getVolumeURIFromVolumeName( volume_name );
          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": using MRC URI " << static_cast<const char*>( mrc_uri ) << ".";
          YIELD::auto_Object<MRCProxy> mrc_proxy = createProxy<MRCProxy>( mrc_uri );
          main_stage_group.createStage( *mrc_proxy.get() );

          // Create the OSDProxyFactory
          OSDProxyFactory osd_proxy_factory( *dir_proxy.get(), main_stage_group );

          // Start FUSE with an XtreemFS volume
          YIELD::Volume* xtreemfs_volume = new Volume( volume_name, *dir_proxy.get(), *mrc_proxy.get(), osd_proxy_factory );

          // Translate exceptions into errno codes
          xtreemfs_volume = new yieldfs::ExceptionHandlingVolume( *xtreemfs_volume, get_log().incRef() );

          if ( cache_metadata )
          {
            xtreemfs_volume = new yieldfs::StatCachingVolume( YIELD::Object::incRef( *xtreemfs_volume ), get_log().incRef(), 5 );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": caching metadata.";
          }
          if ( get_log_level() >= YIELD::Log::LOG_INFO )
          {
            xtreemfs_volume = new yieldfs::TracingVolume( YIELD::Object::incRef( *xtreemfs_volume ), get_log().incRef() );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": tracing volume operations.";
          }

          uint32_t fuse_flags = yieldfs::FUSE::FUSE_FLAGS_DEFAULT;
          if ( get_log_level() >= YIELD::Log::LOG_INFO )
          {
    	      fuse_flags |= yieldfs::FUSE::FUSE_FLAG_DEBUG;
    	      get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": enabling FUSE debugging.";
          }
          if ( direct_io )
          {
    	      fuse_flags |= yieldfs::FUSE::FUSE_FLAG_DIRECT_IO;
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": enabling FUSE direct I/O.";
          }

          yieldfs::FUSE fuse( xtreemfs_volume->incRef(), get_log().incRef(), fuse_flags );
          int ret;
#ifdef _WIN32
          ret = fuse.main( mount_point.c_str() );
#else
          if ( fuse_o_args.empty() )
            ret = fuse.main( argv[0], mount_point.c_str() );
          else
          {
            std::vector<char*> argvv;
            argvv.push_back( argv[0] );
            argvv.push_back( "-o" );
            argvv.push_back( const_cast<char*>( fuse_o_args.c_str() ) );
            argvv.push_back( NULL );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": passing -o " << fuse_o_args << " to FUSE.";
            struct fuse_args fuse_args_ = FUSE_ARGS_INIT( argvv.size() - 1 , &argvv[0] );
            ret = fuse.main( fuse_args_, mount_point.c_str() );
          }
#endif

          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": shutting down.";
          YIELD::Object::decRef( *xtreemfs_volume );
          YIELD::SEDAStageGroup::destroyStageGroup( main_stage_group ); // Must destroy the stage group before the event handlers go out of scope so the stages aren't holding dead pointers

          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": returning exit code " << ret << ".";

          return ret;
        }

        void parseOption( int id, char* arg )
        {
          switch ( id )
          {
            case XTFS_MOUNT_OPTION_CACHE_METADATA: cache_metadata = true; break;
            case XTFS_MOUNT_OPTION_FOREGROUND: foreground = true; break;

            case XTFS_MOUNT_OPTION_FUSE_OPTION:
            {
              if ( !fuse_o_args.empty() )
                fuse_o_args.append( "," );
              fuse_o_args.append( arg );

              if ( strstr( arg, "direct_io" ) != NULL )
                direct_io = true;
            }
            break;

            default: Main::parseOption( id, arg ); break;
          }
        }

        void parseFiles( int file_count, char** files )
        {
          if ( file_count >= 2 )
          {
            dir_uri = parseURI( files[0] );
            if ( strlen( dir_uri->get_resource() ) > 1 )
            {
              volume_name = dir_uri->get_resource() + 1;
              mount_point = files[1];
              return;
            }
          }

          throw YIELD::Exception( "must specify dir_host/volume name and mount point" );
        }
      };
    };
  };
};

int main( int argc, char** argv )
{
  return xtfs_mount().main( argc, argv );
}
<commit_msg>client: xtfs_mount: experimental file caching<commit_after>// Copyright 2009 Minor Gordon.
// This source comes from the XtreemFS project. It is licensed under the GPLv2 (see COPYING for terms and conditions).

#include "org/xtreemfs/client.h"
#include "main.h"
using namespace org::xtreemfs::client;

#include "org/xtreemfs/interfaces/constants.h"

#include "yield.h"
#include "yieldfs.h"

#include <vector>
#include <exception>

#ifndef _WIN32
#define FUSE_USE_VERSION 26
#include <fuse.h>
#include <unistd.h>
#endif

namespace org
{
  namespace xtreemfs
  {
    namespace client
    {
      class xtfs_mount : public Main
      {
      public:
        xtfs_mount()
          : Main( "xtfs_mount", "mount an XtreemFS volume", "[oncrpc[s]://]<dir host>[:dir port]/<volume name> <mount point>" )
        {
          addOption( XTFS_MOUNT_OPTION_CACHE_FILES, "--cache-files" );
          cache_files = false;

          addOption( XTFS_MOUNT_OPTION_CACHE_METADATA, "--cache-metadata" );
          cache_metadata = false;

          direct_io = false;

          addOption( XTFS_MOUNT_OPTION_FOREGROUND, "-f", "--foreground" );
          foreground = false;

          addOption( XTFS_MOUNT_OPTION_FUSE_OPTION, "-o", NULL, "<fuse_option>" );
        }

      private:
        enum
        {
          XTFS_MOUNT_OPTION_CACHE_FILES = 10,
          XTFS_MOUNT_OPTION_CACHE_METADATA = 11,
          XTFS_MOUNT_OPTION_DIRECT_IO = 12,
          XTFS_MOUNT_OPTION_FOREGROUND = 13,
          XTFS_MOUNT_OPTION_FUSE_OPTION = 14
        };

        bool cache_files, cache_metadata;
        bool direct_io;
        std::auto_ptr<YIELD::URI> dir_uri;
        bool foreground;
        std::string fuse_o_args;
        std::string mount_point, volume_name;

        // xtfs_bin
        int _main( int argc, char** argv )
        {
          if ( foreground )
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": running in foreground.";
          else
          {
#ifndef _WIN32
            if ( daemon( 1, 0 ) == -1 )
              return errno;
#endif
          }

          YIELD::SEDAStageGroup& main_stage_group = YIELD::SEDAStageGroup::createStageGroup();

          // Create the DIRProxy
          YIELD::auto_Object<DIRProxy> dir_proxy = createProxy<DIRProxy>( *dir_uri.get() );
          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": using DIR URI " << static_cast<const char*>( *dir_uri.get() ) << ".";
          main_stage_group.createStage( *dir_proxy.get() );

          // Create the MRCProxy
          YIELD::URI mrc_uri = dir_proxy.get()->getVolumeURIFromVolumeName( volume_name );
          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": using MRC URI " << static_cast<const char*>( mrc_uri ) << ".";
          YIELD::auto_Object<MRCProxy> mrc_proxy = createProxy<MRCProxy>( mrc_uri );
          main_stage_group.createStage( *mrc_proxy.get() );

          // Create the OSDProxyFactory
          OSDProxyFactory osd_proxy_factory( *dir_proxy.get(), main_stage_group );

          // Start FUSE with an XtreemFS volume
          YIELD::Volume* xtreemfs_volume = new Volume( volume_name, *dir_proxy.get(), *mrc_proxy.get(), osd_proxy_factory );

          // Translate exceptions into errno codes
          xtreemfs_volume = new yieldfs::ExceptionHandlingVolume( *xtreemfs_volume, get_log().incRef() );

          if ( cache_files )
          {
            xtreemfs_volume = new yieldfs::FileCachingVolume( YIELD::Object::incRef( *xtreemfs_volume ), get_log().incRef() );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": caching files.";
          }

          if ( cache_metadata )
          {
            xtreemfs_volume = new yieldfs::StatCachingVolume( YIELD::Object::incRef( *xtreemfs_volume ), get_log().incRef(), 5 );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": caching metadata.";
          }

          if ( get_log_level() >= YIELD::Log::LOG_INFO )
          {
            xtreemfs_volume = new yieldfs::TracingVolume( YIELD::Object::incRef( *xtreemfs_volume ), get_log().incRef() );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": tracing volume operations.";
          }

          uint32_t fuse_flags = yieldfs::FUSE::FUSE_FLAGS_DEFAULT;
          if ( get_log_level() >= YIELD::Log::LOG_INFO )
          {
    	      fuse_flags |= yieldfs::FUSE::FUSE_FLAG_DEBUG;
    	      get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": enabling FUSE debugging.";
          }
          if ( direct_io )
          {
    	      fuse_flags |= yieldfs::FUSE::FUSE_FLAG_DIRECT_IO;
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": enabling FUSE direct I/O.";
          }

          yieldfs::FUSE fuse( xtreemfs_volume->incRef(), get_log().incRef(), fuse_flags );
          int ret;
#ifdef _WIN32
          ret = fuse.main( mount_point.c_str() );
#else
          if ( fuse_o_args.empty() )
            ret = fuse.main( argv[0], mount_point.c_str() );
          else
          {
            std::vector<char*> argvv;
            argvv.push_back( argv[0] );
            argvv.push_back( "-o" );
            argvv.push_back( const_cast<char*>( fuse_o_args.c_str() ) );
            argvv.push_back( NULL );
            get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": passing -o " << fuse_o_args << " to FUSE.";
            struct fuse_args fuse_args_ = FUSE_ARGS_INIT( argvv.size() - 1 , &argvv[0] );
            ret = fuse.main( fuse_args_, mount_point.c_str() );
          }
#endif

          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": shutting down.";
          YIELD::Object::decRef( *xtreemfs_volume );
          YIELD::SEDAStageGroup::destroyStageGroup( main_stage_group ); // Must destroy the stage group before the event handlers go out of scope so the stages aren't holding dead pointers

          get_log().getStream( YIELD::Log::LOG_INFO ) << get_program_name() << ": returning exit code " << ret << ".";

          return ret;
        }

        void parseOption( int id, char* arg )
        {
          switch ( id )
          {
            case XTFS_MOUNT_OPTION_CACHE_FILES: cache_files = true; break;
            case XTFS_MOUNT_OPTION_CACHE_METADATA: cache_metadata = true; break;
            case XTFS_MOUNT_OPTION_FOREGROUND: foreground = true; break;

            case XTFS_MOUNT_OPTION_FUSE_OPTION:
            {
              if ( !fuse_o_args.empty() )
                fuse_o_args.append( "," );
              fuse_o_args.append( arg );

              if ( strstr( arg, "direct_io" ) != NULL )
                direct_io = true;
            }
            break;

            default: Main::parseOption( id, arg ); break;
          }
        }

        void parseFiles( int file_count, char** files )
        {
          if ( file_count >= 2 )
          {
            dir_uri = parseURI( files[0] );
            if ( strlen( dir_uri->get_resource() ) > 1 )
            {
              volume_name = dir_uri->get_resource() + 1;
              mount_point = files[1];
              return;
            }
          }

          throw YIELD::Exception( "must specify dir_host/volume name and mount point" );
        }
      };
    };
  };
};

int main( int argc, char** argv )
{
  return xtfs_mount().main( argc, argv );
}
<|endoftext|>


<commit_before><commit_msg>easy implemtation problem<commit_after><|endoftext|>


<commit_before>#include "dcptimezoneconf.h"
#include "dcptimezonedata.h"

#include <QFile>
#include <unicode/timezone.h>
#include <unicode/strenum.h>
#include "dcpicuconversions.h"
// #include <duiconf.h>
#include <QDebug>

DcpTimeZoneConf *DcpTimeZoneConf::sm_Instance = 0;
static const QString zonePath = QString(PREFIX) + "/share/zoneinfo/";
static const QString defaultZoneKey = "system/timezone";

DcpTimeZoneConf* DcpTimeZoneConf::instance()
{
    if (!sm_Instance) {
        sm_Instance = new DcpTimeZoneConf();
    }

    return sm_Instance;
}

DcpTimeZoneConf::~DcpTimeZoneConf()
{
    m_ItemMap.clear();
    sm_Instance = 0;
}

QMultiMap<QString, DcpTimeZoneData*> DcpTimeZoneConf::getMap() const
{
    return m_ItemMap;
}

DcpTimeZoneData DcpTimeZoneConf::defaultTimeZone() const
{
    /* QVariant zoneId;
    QString zone;
    m_Conf->getValue("/system/timezone", zoneId);
    if (zoneId.toString().isEmpty()) {
        zone = "Europe/London";
    } else {
        zone = zoneId.toString();
    }*/
    QString zone = m_Settings.value(defaultZoneKey, "Europe/London").toString();

    DcpTimeZoneData timeZone(zone);
    return timeZone;
}

void DcpTimeZoneConf::setDefaultTimeZone(QString zoneId)
{
    // m_Conf->set("/system/timezone", zoneId);
    QSettings settings("Nokia", "DuiControlPanel");
    m_Settings.setValue(defaultZoneKey, zoneId);
}

void DcpTimeZoneConf::initCountry()
{
    // collect informations from zone.tab
    QFile *file = new QFile(zonePath + "zone.tab");
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QMultiMap<QString, QString> zoneMap;
    while (!file->atEnd()) {
        QString line = file->readLine();
        if (!line.startsWith("#")) {
            QStringList item = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            zoneMap.insert(item.at(0), item.at(2));
        }
    }
    file->close();
    delete file;

    // collect informations from iso3166.tab
    file = new QFile(zonePath + "iso3166.tab");
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while (!file->atEnd()) {
        QString line = file->readLine();
        if (!line.startsWith("#")) {
            QStringList item = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            QMultiMap<QString, QString>::const_iterator iter = zoneMap.find(item.at(0));
            while (iter != zoneMap.end() && iter.key() == item.at(0)) {
                QString country;
                for (int i = 1; i < item.size(); i++) {
                    if (i != item.size() - 1) {
                        country += item.at(i) + " ";
                    } else {
                        country += item.at(i);
                    }
                }

		/* TODO find better slution for long names or file a bug to the
		 * proper component */
                if (country == "South Georgia & the South Sandwich Islands")
                    country = "South Georgia & the South Sandw...";

                m_CountryMap.insert(iter.value(), country);
                ++iter;
            }
        }
    }
    file->close();
    delete file;
}

//! protected constructor
DcpTimeZoneConf::DcpTimeZoneConf()
                :QObject(), m_Settings("Nokia","DuiControlPanel")
{
    // create m_Conf and cache keys under /system
    // m_Conf = new DuiConf();
    // m_Conf->addDir("/system", true);

    // fill up m_CountryMap
    this->initCountry();

    // fill up itemMap
    QMap<int, DcpTimeZoneData*> itemMap;
    QStringList list = this->supportedTimeZones();
    QStringListIterator iter(list);
    int count = 1;
    while (iter.hasNext()) {
        QString item = iter.next();
        if (item.startsWith("Europe") || item.startsWith("America") ||
            item.startsWith("Asia")   || item.startsWith("Australia") ||
            item.startsWith("Indian") || item.startsWith("Africa") ||
            item.startsWith("Pacific") || item.startsWith("Mideast") ||
            item.startsWith("Brazil") || item.startsWith("Atlantic") ||
            item.startsWith("Arctic") || item.startsWith("Antarctica"))
            itemMap[count++] = new DcpTimeZoneData(item);
    }

    // check countries in itemMap and fill up m_ItemMap
    QMapIterator<int, DcpTimeZoneData*> itera(itemMap);
    while (itera.hasNext()) {
        itera.next();
        QMultiMap<QString, QString>::const_iterator it = m_CountryMap.find(itera.value()->timeZone());
        while (it != m_CountryMap.end() && it.key() == itera.value()->timeZone()) {
            itera.value()->setCountry(it.value());
            m_ItemMap.insert(itera.value()->country(), itera.value());
            ++it;
        }
    }
}

QStringList DcpTimeZoneConf::supportedTimeZones()
{
    icu::StringEnumeration *stringEnum = icu::TimeZone::createEnumeration();
    QStringList result;
    UErrorCode status = U_ZERO_ERROR;
    const UnicodeString *next = stringEnum->snext(status);
    while (next != 0) {
        result << unicodeStringToQString(*next);
        next = stringEnum->snext(status);
    }
    delete stringEnum;
    return result;
}

<commit_msg>remove ununsed local object<commit_after>#include "dcptimezoneconf.h"
#include "dcptimezonedata.h"

#include <QFile>
#include <unicode/timezone.h>
#include <unicode/strenum.h>
#include "dcpicuconversions.h"
// #include <duiconf.h>
#include <QDebug>

DcpTimeZoneConf *DcpTimeZoneConf::sm_Instance = 0;
static const QString zonePath = QString(PREFIX) + "/share/zoneinfo/";
static const QString defaultZoneKey = "system/timezone";

DcpTimeZoneConf* DcpTimeZoneConf::instance()
{
    if (!sm_Instance) {
        sm_Instance = new DcpTimeZoneConf();
    }

    return sm_Instance;
}

DcpTimeZoneConf::~DcpTimeZoneConf()
{
    m_ItemMap.clear();
    sm_Instance = 0;
}

QMultiMap<QString, DcpTimeZoneData*> DcpTimeZoneConf::getMap() const
{
    return m_ItemMap;
}

DcpTimeZoneData DcpTimeZoneConf::defaultTimeZone() const
{
    /* QVariant zoneId;
    QString zone;
    m_Conf->getValue("/system/timezone", zoneId);
    if (zoneId.toString().isEmpty()) {
        zone = "Europe/London";
    } else {
        zone = zoneId.toString();
    }*/
    QString zone = m_Settings.value(defaultZoneKey, "Europe/London").toString();

    DcpTimeZoneData timeZone(zone);
    return timeZone;
}

void DcpTimeZoneConf::setDefaultTimeZone(QString zoneId)
{
    // m_Conf->set("/system/timezone", zoneId);
    m_Settings.setValue(defaultZoneKey, zoneId);
}

void DcpTimeZoneConf::initCountry()
{
    // collect informations from zone.tab
    QFile *file = new QFile(zonePath + "zone.tab");
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QMultiMap<QString, QString> zoneMap;
    while (!file->atEnd()) {
        QString line = file->readLine();
        if (!line.startsWith("#")) {
            QStringList item = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            zoneMap.insert(item.at(0), item.at(2));
        }
    }
    file->close();
    delete file;

    // collect informations from iso3166.tab
    file = new QFile(zonePath + "iso3166.tab");
    if (!file->open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    while (!file->atEnd()) {
        QString line = file->readLine();
        if (!line.startsWith("#")) {
            QStringList item = line.split(QRegExp("\\s"), QString::SkipEmptyParts);
            QMultiMap<QString, QString>::const_iterator iter = zoneMap.find(item.at(0));
            while (iter != zoneMap.end() && iter.key() == item.at(0)) {
                QString country;
                for (int i = 1; i < item.size(); i++) {
                    if (i != item.size() - 1) {
                        country += item.at(i) + " ";
                    } else {
                        country += item.at(i);
                    }
                }

		/* TODO find better slution for long names or file a bug to the
		 * proper component */
                if (country == "South Georgia & the South Sandwich Islands")
                    country = "South Georgia & the South Sandw...";

                m_CountryMap.insert(iter.value(), country);
                ++iter;
            }
        }
    }
    file->close();
    delete file;
}

//! protected constructor
DcpTimeZoneConf::DcpTimeZoneConf()
                :QObject(), m_Settings("Nokia","DuiControlPanel")
{
    // create m_Conf and cache keys under /system
    // m_Conf = new DuiConf();
    // m_Conf->addDir("/system", true);

    // fill up m_CountryMap
    this->initCountry();

    // fill up itemMap
    QMap<int, DcpTimeZoneData*> itemMap;
    QStringList list = this->supportedTimeZones();
    QStringListIterator iter(list);
    int count = 1;
    while (iter.hasNext()) {
        QString item = iter.next();
        if (item.startsWith("Europe") || item.startsWith("America") ||
            item.startsWith("Asia")   || item.startsWith("Australia") ||
            item.startsWith("Indian") || item.startsWith("Africa") ||
            item.startsWith("Pacific") || item.startsWith("Mideast") ||
            item.startsWith("Brazil") || item.startsWith("Atlantic") ||
            item.startsWith("Arctic") || item.startsWith("Antarctica"))
            itemMap[count++] = new DcpTimeZoneData(item);
    }

    // check countries in itemMap and fill up m_ItemMap
    QMapIterator<int, DcpTimeZoneData*> itera(itemMap);
    while (itera.hasNext()) {
        itera.next();
        QMultiMap<QString, QString>::const_iterator it = m_CountryMap.find(itera.value()->timeZone());
        while (it != m_CountryMap.end() && it.key() == itera.value()->timeZone()) {
            itera.value()->setCountry(it.value());
            m_ItemMap.insert(itera.value()->country(), itera.value());
            ++it;
        }
    }
}

QStringList DcpTimeZoneConf::supportedTimeZones()
{
    icu::StringEnumeration *stringEnum = icu::TimeZone::createEnumeration();
    QStringList result;
    UErrorCode status = U_ZERO_ERROR;
    const UnicodeString *next = stringEnum->snext(status);
    while (next != 0) {
        result << unicodeStringToQString(*next);
        next = stringEnum->snext(status);
    }
    delete stringEnum;
    return result;
}

<|endoftext|>