<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/interaction/events/event.h>
#include <inviwo/core/properties/property.h>
#include <inviwo/core/properties/eventproperty.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/properties/propertyowner.h>
#include <inviwo/core/io/serialization/ivwserializable.h>
#include <inviwo/core/io/serialization/versionconverter.h>

namespace inviwo {

PropertyOwner::PropertyOwner()
    : PropertyOwnerObservable()
    , invalidationLevel_(VALID) {
}

PropertyOwner::PropertyOwner(const PropertyOwner& rhs)
    : PropertyOwnerObservable()
    , invalidationLevel_(rhs.invalidationLevel_) {
}

PropertyOwner& PropertyOwner::operator=(const PropertyOwner& that) {
    if (this != &that) {
        invalidationLevel_ = that.invalidationLevel_;
        properties_.clear();
    }
    return *this;
}

PropertyOwner::~PropertyOwner() {
    properties_.clear();
}

void PropertyOwner::addProperty(Property* property) {
    ivwAssert(getPropertyByIdentifier(property->getIdentifier()) == nullptr,
              "Property already exist");
    notifyObserversWillAddProperty(property, properties_.size());
    properties_.push_back(property);
    property->setOwner(this);
    if (dynamic_cast<EventProperty*>(property)) {
        eventProperties_.push_back(static_cast<EventProperty*>(property));
    }
    if (dynamic_cast<CompositeProperty*>(property)) {
        compositeProperties_.push_back(static_cast<CompositeProperty*>(property));
    }
    notifyObserversDidAddProperty(property, properties_.size()-1);
}

void PropertyOwner::addProperty(Property& property) {
    addProperty(&property);
}

Property* PropertyOwner::removeProperty(const std::string& identifier) {
    std::vector<Property*>::iterator it =
        std::find_if(properties_.begin(), properties_.end(), property_has_identifier(identifier));
    return removeProperty(it);;
}

Property* PropertyOwner::removeProperty(Property* property) {
    std::vector<Property*>::iterator it =
        std::find(properties_.begin(), properties_.end(), property);
    return removeProperty(it);
}

Property* PropertyOwner::removeProperty(Property& property) {
    return removeProperty(&property);
}

Property* PropertyOwner::removeProperty(std::vector<Property*>::iterator it) {
    Property* prop = nullptr;
    if (it != properties_.end()) {
        prop = *it;
        size_t index = std::distance(properties_.begin(), it);
        notifyObserversWillRemoveProperty(prop, index);

        std::vector<EventProperty*>::iterator
            eit = std::find(eventProperties_.begin(),eventProperties_.end(), *it);
        if (eit != eventProperties_.end()) eventProperties_.erase(eit);

        std::vector<CompositeProperty*>::iterator
            cit = std::find(compositeProperties_.begin(),compositeProperties_.end(), *it);
        if (cit != compositeProperties_.end()) compositeProperties_.erase(cit);

        properties_.erase(it);
        notifyObserversDidRemoveProperty(prop, index);
    }
    return prop;
}

Property* PropertyOwner::getPropertyByIdentifier(const std::string& identifier,
                                                 bool recursiveSearch) const {
    for (auto& elem : properties_) {
        if (elem->getIdentifier() == identifier) return elem;
    }
    if (recursiveSearch) {
        for (auto p : compositeProperties_) {
            if (p) return p;
        }
    }
    return nullptr;
}

Property* PropertyOwner::getPropertyByPath(const std::vector<std::string>& path) const {
    Property* property = getPropertyByIdentifier(path[0]);
    if (property) {
        size_t i = 1;
        while (path.size() > i) {
            CompositeProperty* comp = dynamic_cast<CompositeProperty*>(property);
            if (comp) {
                property = comp->getPropertyByIdentifier(path[i]);
                if (!property) return nullptr;
            } else {
                return nullptr;
            }
            ++i;
        }
        return property;
    }
    return nullptr;
}

void PropertyOwner::setValid() {
    for (auto& elem : properties_) elem->setPropertyModified(false);

    invalidationLevel_ = VALID;
}

void PropertyOwner::invalidate(InvalidationLevel invalidationLevel,
                               Property* modifiedProperty) {
    IVW_UNUSED_PARAM(modifiedProperty);
    invalidationLevel_ = std::max(invalidationLevel_, invalidationLevel);
}

void PropertyOwner::serialize(IvwSerializer& s) const {
    std::map<std::string, Property*> propertyMap;

    for (const auto& elem : properties_) propertyMap[(elem)->getIdentifier()] = elem;

    s.serialize("Properties", propertyMap, "Property");
}

void PropertyOwner::deserialize(IvwDeserializer& d) {
    /* 1) Vector deserialization does not allow
    *     specification of comparison attribute string.
    *  2) But Map deserialization does allow
    *     specification of comparision attribute string.
    *     (eg. "identifier" in this case).
    *  3) Hence map deserialization is preferred here.
    *  4) TODO: Vector can be made to behave like Map.
    *           But then it necessitates passing of two extra arguments.
    *           And they are list of attribute values, comparison attribute string.
    *           eg., list of identifier for each property and "identifier"
    *
    */

    NodeVersionConverter<PropertyOwner> tvc(this, &PropertyOwner::findPropsForComposites);
    d.convertVersion(&tvc);

    std::map<std::string, Property*> propertyMap;

    for (std::vector<Property*>::const_iterator it = properties_.begin(); it != properties_.end(); ++it)
        propertyMap[(*it)->getIdentifier()] = *it;

    d.deserialize("Properties", propertyMap, "Property", "identifier");
}

bool PropertyOwner::findPropsForComposites(TxElement* node) {
    std::vector<const CompositeProperty*> props;
    for (std::vector<Property*>::const_iterator it = properties_.begin(); it != properties_.end(); ++it) {
        CompositeProperty* cp = dynamic_cast<CompositeProperty*>(*it);
        if(cp){
            props.push_back(cp);
        }
    }
    return util::xmlFindMatchingSubPropertiesForComposites(node, props);
}

void PropertyOwner::setAllPropertiesCurrentStateAsDefault(){
    for (auto& elem : properties_) (elem)->setCurrentStateAsDefault();
}

void PropertyOwner::resetAllPoperties(){
    for (auto& elem : properties_) (elem)->resetToDefaultState();
}

bool PropertyOwner::property_has_identifier::operator () (const Property* p) {
    return p->getIdentifier() == id_;
}

std::string PropertyOwner::invalidationLevelToString(InvalidationLevel level) {
    switch (level) {
        case VALID: return "Valid";
        case INVALID_OUTPUT: return "Invalid output";
        case INVALID_RESOURCES: return "Invalid resources";
        default: return "Unknown";
    }
}

std::vector<std::string> PropertyOwner::getPath() const {
    return std::vector<std::string>();
}

void PropertyOwner::invokeInteractionEvent(Event* event) {
    for (auto& elem : eventProperties_) {
        if ((elem)->getEvent()->matching(event)) {
            (elem)->getAction()->invoke(event);
            if (event->hasBeenUsed()) return;
        }
    }
    for (auto& elem : compositeProperties_) {
        (elem)->invokeInteractionEvent(event);
        if (event->hasBeenUsed()) return;
    }
}

} // namespace
<commit_msg>PropertyOwner: Refactor bugfix<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2012-2015 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <inviwo/core/interaction/events/event.h>
#include <inviwo/core/properties/property.h>
#include <inviwo/core/properties/eventproperty.h>
#include <inviwo/core/properties/compositeproperty.h>
#include <inviwo/core/properties/propertyowner.h>
#include <inviwo/core/io/serialization/ivwserializable.h>
#include <inviwo/core/io/serialization/versionconverter.h>

namespace inviwo {

PropertyOwner::PropertyOwner()
    : PropertyOwnerObservable()
    , invalidationLevel_(VALID) {
}

PropertyOwner::PropertyOwner(const PropertyOwner& rhs)
    : PropertyOwnerObservable()
    , invalidationLevel_(rhs.invalidationLevel_) {
}

PropertyOwner& PropertyOwner::operator=(const PropertyOwner& that) {
    if (this != &that) {
        invalidationLevel_ = that.invalidationLevel_;
        properties_.clear();
    }
    return *this;
}

PropertyOwner::~PropertyOwner() {
    properties_.clear();
}

void PropertyOwner::addProperty(Property* property) {
    ivwAssert(getPropertyByIdentifier(property->getIdentifier()) == nullptr,
              "Property already exist");
    notifyObserversWillAddProperty(property, properties_.size());
    properties_.push_back(property);
    property->setOwner(this);
    if (dynamic_cast<EventProperty*>(property)) {
        eventProperties_.push_back(static_cast<EventProperty*>(property));
    }
    if (dynamic_cast<CompositeProperty*>(property)) {
        compositeProperties_.push_back(static_cast<CompositeProperty*>(property));
    }
    notifyObserversDidAddProperty(property, properties_.size()-1);
}

void PropertyOwner::addProperty(Property& property) {
    addProperty(&property);
}

Property* PropertyOwner::removeProperty(const std::string& identifier) {
    std::vector<Property*>::iterator it =
        std::find_if(properties_.begin(), properties_.end(), property_has_identifier(identifier));
    return removeProperty(it);;
}

Property* PropertyOwner::removeProperty(Property* property) {
    std::vector<Property*>::iterator it =
        std::find(properties_.begin(), properties_.end(), property);
    return removeProperty(it);
}

Property* PropertyOwner::removeProperty(Property& property) {
    return removeProperty(&property);
}

Property* PropertyOwner::removeProperty(std::vector<Property*>::iterator it) {
    Property* prop = nullptr;
    if (it != properties_.end()) {
        prop = *it;
        size_t index = std::distance(properties_.begin(), it);
        notifyObserversWillRemoveProperty(prop, index);

        std::vector<EventProperty*>::iterator
            eit = std::find(eventProperties_.begin(),eventProperties_.end(), *it);
        if (eit != eventProperties_.end()) eventProperties_.erase(eit);

        std::vector<CompositeProperty*>::iterator
            cit = std::find(compositeProperties_.begin(),compositeProperties_.end(), *it);
        if (cit != compositeProperties_.end()) compositeProperties_.erase(cit);

        properties_.erase(it);
        notifyObserversDidRemoveProperty(prop, index);
    }
    return prop;
}

Property* PropertyOwner::getPropertyByIdentifier(const std::string& identifier,
                                                 bool recursiveSearch) const {
    for (auto& property : properties_) {
        if (property->getIdentifier() == identifier) return property;
    }
    if (recursiveSearch) {
        for (auto compositeProperty : compositeProperties_) {
            Property* p = compositeProperty->getPropertyByIdentifier(identifier, true);
            if (p) return p;
        }
    }
    return nullptr;
}

Property* PropertyOwner::getPropertyByPath(const std::vector<std::string>& path) const {
    Property* property = getPropertyByIdentifier(path[0]);
    if (property) {
        size_t i = 1;
        while (path.size() > i) {
            CompositeProperty* comp = dynamic_cast<CompositeProperty*>(property);
            if (comp) {
                property = comp->getPropertyByIdentifier(path[i]);
                if (!property) return nullptr;
            } else {
                return nullptr;
            }
            ++i;
        }
        return property;
    }
    return nullptr;
}

void PropertyOwner::setValid() {
    for (auto& elem : properties_) elem->setPropertyModified(false);

    invalidationLevel_ = VALID;
}

void PropertyOwner::invalidate(InvalidationLevel invalidationLevel,
                               Property* modifiedProperty) {
    IVW_UNUSED_PARAM(modifiedProperty);
    invalidationLevel_ = std::max(invalidationLevel_, invalidationLevel);
}

void PropertyOwner::serialize(IvwSerializer& s) const {
    std::map<std::string, Property*> propertyMap;

    for (const auto& elem : properties_) propertyMap[(elem)->getIdentifier()] = elem;

    s.serialize("Properties", propertyMap, "Property");
}

void PropertyOwner::deserialize(IvwDeserializer& d) {
    /* 1) Vector deserialization does not allow
    *     specification of comparison attribute string.
    *  2) But Map deserialization does allow
    *     specification of comparision attribute string.
    *     (eg. "identifier" in this case).
    *  3) Hence map deserialization is preferred here.
    *  4) TODO: Vector can be made to behave like Map.
    *           But then it necessitates passing of two extra arguments.
    *           And they are list of attribute values, comparison attribute string.
    *           eg., list of identifier for each property and "identifier"
    *
    */

    NodeVersionConverter<PropertyOwner> tvc(this, &PropertyOwner::findPropsForComposites);
    d.convertVersion(&tvc);

    std::map<std::string, Property*> propertyMap;

    for (std::vector<Property*>::const_iterator it = properties_.begin(); it != properties_.end(); ++it)
        propertyMap[(*it)->getIdentifier()] = *it;

    d.deserialize("Properties", propertyMap, "Property", "identifier");
}

bool PropertyOwner::findPropsForComposites(TxElement* node) {
    std::vector<const CompositeProperty*> props;
    for (std::vector<Property*>::const_iterator it = properties_.begin(); it != properties_.end(); ++it) {
        CompositeProperty* cp = dynamic_cast<CompositeProperty*>(*it);
        if(cp){
            props.push_back(cp);
        }
    }
    return util::xmlFindMatchingSubPropertiesForComposites(node, props);
}

void PropertyOwner::setAllPropertiesCurrentStateAsDefault(){
    for (auto& elem : properties_) (elem)->setCurrentStateAsDefault();
}

void PropertyOwner::resetAllPoperties(){
    for (auto& elem : properties_) (elem)->resetToDefaultState();
}

bool PropertyOwner::property_has_identifier::operator () (const Property* p) {
    return p->getIdentifier() == id_;
}

std::string PropertyOwner::invalidationLevelToString(InvalidationLevel level) {
    switch (level) {
        case VALID: return "Valid";
        case INVALID_OUTPUT: return "Invalid output";
        case INVALID_RESOURCES: return "Invalid resources";
        default: return "Unknown";
    }
}

std::vector<std::string> PropertyOwner::getPath() const {
    return std::vector<std::string>();
}

void PropertyOwner::invokeInteractionEvent(Event* event) {
    for (auto& elem : eventProperties_) {
        if ((elem)->getEvent()->matching(event)) {
            (elem)->getAction()->invoke(event);
            if (event->hasBeenUsed()) return;
        }
    }
    for (auto& elem : compositeProperties_) {
        (elem)->invokeInteractionEvent(event);
        if (event->hasBeenUsed()) return;
    }
}

} // namespace
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

#ifndef CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP
#define CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP

#include "utilities/globalDefinitions.hpp"
#include "utilities/macros.hpp"

// Sets the default values for platform dependent flags used by the client compiler.
// (see c1_globals.hpp)

#ifndef TIERED
define_pd_global(bool, BackgroundCompilation,        true );
define_pd_global(bool, CICompileOSR,                 true );
define_pd_global(bool, InlineIntrinsics,             true );
define_pd_global(bool, PreferInterpreterNativeStubs, false);
define_pd_global(bool, ProfileTraps,                 false);
define_pd_global(bool, UseOnStackReplacement,        true );
define_pd_global(bool, TieredCompilation,            false);
define_pd_global(intx, CompileThreshold,             1000 ); // Design center runs on 1.3.1
define_pd_global(intx, BackEdgeThreshold,            100000);

define_pd_global(intx, OnStackReplacePercentage,     1400 );
define_pd_global(bool, UseTLAB,                      true );
define_pd_global(bool, ProfileInterpreter,           false);
define_pd_global(intx, FreqInlineSize,               325  );
define_pd_global(bool, ResizeTLAB,                   true );
define_pd_global(intx, ReservedCodeCacheSize,        32*M );
define_pd_global(intx, CodeCacheExpansionSize,       32*K );
define_pd_global(uintx, CodeCacheMinBlockLength,     1);
define_pd_global(uintx, CodeCacheMinimumUseSpace,    400*K);
define_pd_global(uintx, MetaspaceSize,               12*M );
define_pd_global(bool, NeverActAsServerClassMachine, true );
define_pd_global(intx, NewSizeThreadIncrease,        16*K );
define_pd_global(uint64_t,MaxRAM,                    1ULL*G);
define_pd_global(intx, InitialCodeCacheSize,         160*K);
#endif // !TIERED

define_pd_global(bool, UseTypeProfile,               false);
define_pd_global(bool, RoundFPResults,               false);

define_pd_global(bool, LIRFillDelaySlots,            true );
define_pd_global(bool, OptimizeSinglePrecision,      false);
define_pd_global(bool, CSEArrayLength,               true );
define_pd_global(bool, TwoOperandLIRForm,            false);

define_pd_global(intx, SafepointPollOffset,          0    );

#endif // CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP
<commit_msg>sparc: fix client vm build<commit_after>/*
 * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 *
 */

#ifndef CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP
#define CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP

#include "utilities/globalDefinitions.hpp"
#include "utilities/macros.hpp"

// Sets the default values for platform dependent flags used by the client compiler.
// (see c1_globals.hpp)

#ifndef TIERED
define_pd_global(bool, BackgroundCompilation,        true );
define_pd_global(bool, CICompileOSR,                 true );
define_pd_global(bool, InlineIntrinsics,             true );
define_pd_global(bool, PreferInterpreterNativeStubs, false);
define_pd_global(bool, ProfileTraps,                 false);
define_pd_global(bool, UseOnStackReplacement,        true );
define_pd_global(bool, TieredCompilation,            false);
define_pd_global(intx, CompileThreshold,             1000 ); // Design center runs on 1.3.1
define_pd_global(intx, BackEdgeThreshold,            100000);

define_pd_global(intx, OnStackReplacePercentage,     1400 );
define_pd_global(bool, UseTLAB,                      true );
define_pd_global(bool, ProfileInterpreter,           false);
define_pd_global(intx, FreqInlineSize,               325  );
define_pd_global(bool, ResizeTLAB,                   true );
define_pd_global(intx, ReservedCodeCacheSize,        32*M );
define_pd_global(intx, CodeCacheExpansionSize,       32*K );
define_pd_global(uintx, CodeCacheMinBlockLength,     1);
define_pd_global(uintx, CodeCacheMinimumUseSpace,    400*K);
define_pd_global(uintx, MetaspaceSize,               12*M );
define_pd_global(bool, NeverActAsServerClassMachine, true );
define_pd_global(intx, NewSizeThreadIncrease,        16*K );
define_pd_global(uint64_t,MaxRAM,                    1ULL*G);
define_pd_global(intx, InitialCodeCacheSize,         160*K);
define_pd_global(intx, TypeProfileWidth,             0);
define_pd_global(intx, MethodProfileWidth,           0);
#endif // !TIERED

define_pd_global(bool, UseTypeProfile,               false);
define_pd_global(bool, RoundFPResults,               false);

define_pd_global(bool, LIRFillDelaySlots,            true );
define_pd_global(bool, OptimizeSinglePrecision,      false);
define_pd_global(bool, CSEArrayLength,               true );
define_pd_global(bool, TwoOperandLIRForm,            false);

define_pd_global(intx, SafepointPollOffset,          0    );

#endif // CPU_SPARC_VM_C1_GLOBALS_SPARC_HPP
<|endoftext|>


<commit_before>#define BOOST_TEST_MODULE TestGeom
#include <boost/test/included/unit_test.hpp>
#include "db.h"
#include "helper.cpp"
#include <iostream>
using namespace odb;

BOOST_AUTO_TEST_SUITE( test_suite )

BOOST_AUTO_TEST_CASE( test_oct )
{
    Oct* oct = new Oct;
    oct->init(Point(0,0),Point(400,400),40);
    BOOST_TEST((oct->getCenterHigh() == Point(400,400)));
    BOOST_TEST((oct->getCenterLow() == Point(0,0)));
    BOOST_TEST(oct->getWidth()==40);
    BOOST_TEST(oct->xMin()==-20);
    BOOST_TEST(oct->xMax()==420);
    BOOST_TEST(oct->yMin()==-20);
    BOOST_TEST(oct->yMax()==420);
    BOOST_TEST(oct->dx()==440);
    BOOST_TEST(oct->dy()==440);

    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::RIGHT);
    oct->init(Point(0,0),Point(-400,400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::LEFT);
    oct->init(Point(0,0),Point(-400,-400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::RIGHT);
    oct->init(Point(0,0),Point(400,-400),40);
    BOOST_TEST(oct->getDir() == Oct::OCT_DIR::LEFT);
}
BOOST_AUTO_TEST_CASE( test_sbox_shapes )
{
    Oct oct(Point(0,0),Point(400,400),40);
    BOOST_TEST(oct.xMin()==-20);
    BOOST_TEST(oct.xMax()==420);
    BOOST_TEST(oct.yMin()==-20);
    BOOST_TEST(oct.yMax()==420);
    BOOST_TEST(oct.dx()==440);
    BOOST_TEST(oct.dy()==440);
    //OCT POINTS
    std::vector<Point> points = oct.getPoints();
    BOOST_TEST(points.size()==9);
    BOOST_TEST((points[0] == Point(-9,-20)));
    BOOST_TEST((points[1] == Point(9,-20)));
    BOOST_TEST((points[2] == Point(420,391)));
    BOOST_TEST((points[3] == Point(420,409)));
    BOOST_TEST((points[4] == Point(409,420)));
    BOOST_TEST((points[5] == Point(391,420)));
    BOOST_TEST((points[6] == Point(-20,9)));
    BOOST_TEST((points[7] == Point(-20,-9)));
    BOOST_TEST((points[8] == Point(-9,-20)));

    //RECT
    Rect rect(Point(0,0),Point(400,400));
    BOOST_TEST(rect.xMin()==0);
    BOOST_TEST(rect.xMax()==400);
    BOOST_TEST(rect.yMin()==0);
    BOOST_TEST(rect.yMax()==400);
    BOOST_TEST(rect.dx()==400);
    BOOST_TEST(rect.dy()==400);
    //RECT POINTS
    points = rect.getPoints();
    BOOST_TEST(points.size()==5);
    BOOST_TEST((points[0] == Point(0,0)));
    BOOST_TEST((points[1] == Point(400,0)));
    BOOST_TEST((points[2] == Point(400,400)));
    BOOST_TEST((points[3] == Point(0,400)));
    BOOST_TEST((points[4] == Point(0,0)));

}
BOOST_AUTO_TEST_CASE( test_rect_merge )
{
    Rect rect(Point(0,0),Point(100,50));
    Oct oct(Point(100,50),Point(200,200),80);
    rect.merge(oct);
    BOOST_TEST(rect.xMin()==0);
    BOOST_TEST(rect.xMax()==240);
    BOOST_TEST(rect.yMin()==0);
    BOOST_TEST(rect.yMax()==240);
    BOOST_TEST(rect.dx()==240);
    BOOST_TEST(rect.dy()==240);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>odb: fix mem leak in unit test (Coverity CID 1436528)<commit_after>#define BOOST_TEST_MODULE TestGeom
#include <boost/test/included/unit_test.hpp>
#include "db.h"
#include "helper.cpp"
#include <iostream>
using namespace odb;

BOOST_AUTO_TEST_SUITE( test_suite )

BOOST_AUTO_TEST_CASE( test_oct )
{
    Oct oct;
    oct.init(Point(0,0),Point(400,400),40);
    BOOST_TEST((oct.getCenterHigh() == Point(400,400)));
    BOOST_TEST((oct.getCenterLow() == Point(0,0)));
    BOOST_TEST(oct.getWidth()==40);
    BOOST_TEST(oct.xMin()==-20);
    BOOST_TEST(oct.xMax()==420);
    BOOST_TEST(oct.yMin()==-20);
    BOOST_TEST(oct.yMax()==420);
    BOOST_TEST(oct.dx()==440);
    BOOST_TEST(oct.dy()==440);

    BOOST_TEST(oct.getDir() == Oct::OCT_DIR::RIGHT);
    oct.init(Point(0,0),Point(-400,400),40);
    BOOST_TEST(oct.getDir() == Oct::OCT_DIR::LEFT);
    oct.init(Point(0,0),Point(-400,-400),40);
    BOOST_TEST(oct.getDir() == Oct::OCT_DIR::RIGHT);
    oct.init(Point(0,0),Point(400,-400),40);
    BOOST_TEST(oct.getDir() == Oct::OCT_DIR::LEFT);
}
BOOST_AUTO_TEST_CASE( test_sbox_shapes )
{
    Oct oct(Point(0,0),Point(400,400),40);
    BOOST_TEST(oct.xMin()==-20);
    BOOST_TEST(oct.xMax()==420);
    BOOST_TEST(oct.yMin()==-20);
    BOOST_TEST(oct.yMax()==420);
    BOOST_TEST(oct.dx()==440);
    BOOST_TEST(oct.dy()==440);
    //OCT POINTS
    std::vector<Point> points = oct.getPoints();
    BOOST_TEST(points.size()==9);
    BOOST_TEST((points[0] == Point(-9,-20)));
    BOOST_TEST((points[1] == Point(9,-20)));
    BOOST_TEST((points[2] == Point(420,391)));
    BOOST_TEST((points[3] == Point(420,409)));
    BOOST_TEST((points[4] == Point(409,420)));
    BOOST_TEST((points[5] == Point(391,420)));
    BOOST_TEST((points[6] == Point(-20,9)));
    BOOST_TEST((points[7] == Point(-20,-9)));
    BOOST_TEST((points[8] == Point(-9,-20)));

    //RECT
    Rect rect(Point(0,0),Point(400,400));
    BOOST_TEST(rect.xMin()==0);
    BOOST_TEST(rect.xMax()==400);
    BOOST_TEST(rect.yMin()==0);
    BOOST_TEST(rect.yMax()==400);
    BOOST_TEST(rect.dx()==400);
    BOOST_TEST(rect.dy()==400);
    //RECT POINTS
    points = rect.getPoints();
    BOOST_TEST(points.size()==5);
    BOOST_TEST((points[0] == Point(0,0)));
    BOOST_TEST((points[1] == Point(400,0)));
    BOOST_TEST((points[2] == Point(400,400)));
    BOOST_TEST((points[3] == Point(0,400)));
    BOOST_TEST((points[4] == Point(0,0)));

}
BOOST_AUTO_TEST_CASE( test_rect_merge )
{
    Rect rect(Point(0,0),Point(100,50));
    Oct oct(Point(100,50),Point(200,200),80);
    rect.merge(oct);
    BOOST_TEST(rect.xMin()==0);
    BOOST_TEST(rect.xMax()==240);
    BOOST_TEST(rect.yMin()==0);
    BOOST_TEST(rect.yMax()==240);
    BOOST_TEST(rect.dx()==240);
    BOOST_TEST(rect.dy()==240);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "stroke.h"
#include "prefdb.h"
#include <math.h>
#include <iterator>
#include <functional>

#define eps 0.000001

using namespace std;

inline bool close(double x, double y) {
	double diff = x - y;
	if (diff < 0)
		diff = -diff;
	return diff < eps;
}

int get_default_button() { return prefs.button.get().button; }

inline double sqr(double x) { return x*x; };

void update_triple(RTriple e, float x, float y, Time t) {
	e->x = x;
	e->y = y;
	e->t = t;
}

RTriple create_triple(float x, float y, Time t) {
	RTriple e(new Triple);
	update_triple(e, x, y, t);
	return e;
}

struct f : public std::unary_function<RTriple, Stroke::Point> {
	Stroke::Point operator()(RTriple e) {
		Stroke::Point p = { e->x, e->y, e->t };
		return p;
	}
};

Stroke::Stroke(PreStroke &s, int trigger_, int button_, bool timeout_) :
	trigger(trigger_), button(button_), timeout(timeout_)
{
	if (s.valid()) {
		std::transform(s.begin(), s.end(), std::back_inserter(points), f());
		normalize();
	}
}

void Stroke::normalize() {
	if (0) {
		double first = points.front().time;
		double length = points.back().time - first;
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			i->time -= first;
			i->time /= length;
		}
	} else {
		double total = 0;
		double lastx = 0;
		double lasty = 0;
		bool first = true;
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			if (first) {
				i->time = 0;
				lastx = i->x;
				lasty = i->y;
				first = false;
				continue;
			}
			total += hypot(i->x-lastx, i->y-lasty);
			i->time = total;
			lastx = i->x;
			lasty = i->y;
		}
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			i->time /= total;
		}
	}

	double minX=0, minY=0, maxX=0, maxY=0;
	bool first = true;
	for (vector<Point>::iterator i = points.begin(); i!=points.end();i++) {
		if (first) {
			minX = i->x;
			maxX = i->x;
			minY = i->y;
			maxY = i->y;
			first = false;
		} else {
			if (i->x < minX) minX = i->x;
			if (i->x > maxX) maxX = i->x;
			if (i->y < minY) minY = i->y;
			if (i->y > maxY) maxY = i->y;
		}
	}
	double scaleX = maxX - minX;
	double scaleY = maxY - minY;
	double scale = (scaleX > scaleY) ? scaleX : scaleY;
	if (scale < 0.001) scale = 1;
	for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
	   i->x = (i->x-(minX+maxX)/2)/scale + 0.5;
	   i->y = (i->y-(minY+maxY)/2)/scale + 0.5;
	}
}

void Stroke::print() const {
	printf("button: %d\n", button);
	for (vector<Point>::const_iterator i = points.begin(); i != points.end(); i++) {
		printf("pt: (%f, %f) at %f\n", i->x, i->y, i->time);
	}
}

double Stroke::length() const {
	double length = 0;
	bool first = true;
	double lastx = 0;
	double lasty = 0;
	for (vector<Point>::const_iterator i = points.begin(); i != points.end(); i++) {
		if (first) {
			lastx = i->x;
			lasty = i->y;
			first = false;
			continue;
		}
		length += hypot(i->x-lastx, i->y-lasty);
		lastx = i->x;
		lasty = i->y;
	}
	return length;
}

/********* Iterators **********/
struct Pt {
	double x; double y;
};

struct PtPair {
	double t;
	Pt a;
	Pt b;
};

class Stroke::RefineIterator {
	vector<Point>::const_iterator i, i_end, j, j_end;
public:
	RefineIterator(RStroke a, RStroke b) :
		i(a->points.begin()), i_end(a->points.end()), j(b->points.begin()), j_end(b->points.end()) {}
	double operator++(int) {
		if (close(i->time, j->time)) {
			double current = (i->time + j->time)/2;
			i++; j++;
			return current;
		}
		if (i->time < j->time) {
			double current = i->time;
			i++;
			return current;
		} else {
			double current = j->time;
			j++;
			return current;
		}
	}
	operator bool() {
		return i != i_end && j != j_end;
	}
};

class Stroke::InterpolateIterator {
	RefineIterator &t;
	vector<Point>::const_iterator j, j_end;
	const Point *a, *b; // The current line segment goes from a to b
	Pt current;
public:
	InterpolateIterator(RefineIterator &t_, RStroke &in) :
		t(t_),
		j(in->points.begin()),
		j_end(in->points.end()),
		a(0), b(0)
	{}
	operator bool() { return t; }
	Pt operator++(int) {
		double now = t++;
		while (j != j_end && (!a || b->time < now)) {
			a = b;
			b = &(*j);
			j++;
		}
		double delta = b->time - a->time;
		if (delta < eps) {
			current.x = b->x;
			current.y = b->y;
		} else {
			double k = (now - a->time) / delta;
			current.x = a->x + (b->x - a->x) * k;
			current.y = a->y + (b->y - a->y) * k;
		}
		return current;
	}
};

class Stroke::RIIterator {
	// There is more potential for optimization here
	RefineIterator t;
	RefineIterator ti;
	RefineIterator tj;
	InterpolateIterator i, j;
	PtPair p;
public:
	RIIterator(RStroke a, RStroke b) :
		t(a, b),
		ti(a, b),
		tj(a, b),
		i(ti, a),
		j(tj, b)
	{}
	operator bool() { return t; }
	PtPair operator++(int) {
		p.t = t++;
		p.a = i++;
		p.b = j++;
		return p;
	}
};

class Stroke::DiffIntegral : public EasyIterator<Point> {
	RIIterator i;
	double a_length, b_length;
public:
	DiffIntegral(RStroke a, RStroke b) : i(a, b), a_length(a->length()), b_length(b->length()) {}
	inline virtual const Point operator++(int) {
		PtPair ps = i++;
		Point p;
		p.x = ps.a.x/a_length - ps.b.x/b_length;
		p.y = ps.a.y/a_length - ps.b.y/b_length;
		p.time = ps.t;
		return p;
	}
	inline virtual operator bool() { return i; }
};

class Stroke::StrokeIntegral : public EasyIterator<Point> {
	vector<Point>::const_iterator i, i_end;
public:
	StrokeIntegral(const Stroke& s) : i(s.points.begin()), i_end(s.points.end()) {}
	inline virtual const Point operator++(int) { return *(i++); }
	inline virtual operator bool() { return i != i_end; }
};

/******** (Iterators) *********/

Integral Stroke::diff_integral(RStroke a, RStroke b) {
	DiffIntegral di(a, b);
	return integral(di);
}

Integral Stroke::integral() const{
	StrokeIntegral si(*this);
	return integral(si);
}

Integral Stroke::integral(EasyIterator<Point>& i) {
	Integral sum = {{{0,0},{0,0}},{{0,0},{0,0}}};
	Point a;
	Point b = i++;
	while (i) {
		a = b;
		b = i++;
		double delta = b.time - a.time;
		if (delta < eps)
			continue;
#define INT_II(l, c) delta * (c + l) / 2
		sum.i.i.x += INT_II(a.x, b.x);
		sum.i.i.y += INT_II(a.y, b.y);
#undef INT_II
#define INT_IS(l, c) delta * (c*(c+l)+l*l) / 3
		sum.i.s.x += INT_IS(a.x, b.x);
		sum.i.s.y += INT_IS(a.y, b.y);
#undef INT_IS
		sum.d.i.x += b.x - a.x;
		sum.d.i.y += b.y - a.y;
#define INT_DS(l, c) sqr(c-l)/delta
		sum.d.s.x += INT_DS(a.x, b.x);
		sum.d.s.y += INT_DS(a.y, b.y);
#undef INT_DS
	}
	return sum;
}

void Stroke::integral2(RStroke a, RStroke b, double &int_x, double &int_y, double &int_dx, double &int_dy) {
	PtPair cur = { 0, {0,0}, {0,0} };
	PtPair last = { 0, {0,0}, {0,0} };
	int_x = 0; int_y = 0; int_dx = 0; int_dy = 0;

	for (RIIterator i(a, b); i;) {
		last = cur;
		cur  = i++;
		double delta = cur.t - last.t;
		int_x += delta*(2*cur.a.x*cur.b.x+2*last.a.x*last.b.x+cur.a.x*last.b.x+cur.b.x*last.a.x)/6;
		int_y += delta*(2*cur.a.y*cur.b.y+2*last.a.y*last.b.y+cur.a.y*last.b.y+cur.b.y*last.a.y)/6;
		if (delta < eps)
			continue;
		int_dx += (cur.a.x-last.a.x)*(cur.b.x-last.b.x)/delta;
		int_dy += (cur.a.y-last.a.y)*(cur.b.y-last.b.y)/delta;
	}
}

bool Stroke::compare(RStroke a_, RStroke b_, double &score) {
	if (!a_ || !b_)
		return -2;
	if (!a_->timeout != !b_->timeout)
		return -2;
	if (a_->button != b_->button)
		if (!(a_->button == b_->trigger && b_->button == a_->trigger))
			return -2;
	if (a_->size() == 0 || b_->size() == 0) {
		if (a_->size() == 0 && b_->size() == 0)
			return 1;
		else
			return -2;
	}
	double ab_x, ab_y, dab_x, dab_y;
	integral2(a_, b_, ab_x, ab_y, dab_x, dab_y);
	Integral a = a_->integral();
	Integral b = b_->integral();
	double A = (a.i.s.x - sqr(a.i.i.x)) + (a.i.s.y - sqr(a.i.i.y));
	double B = (b.i.s.x - sqr(b.i.i.x)) + (b.i.s.y - sqr(b.i.i.y));
	double C = (ab_x - a.i.i.x * b.i.i.x) + (ab_y - a.i.i.y * b.i.i.y);
	double X = a.d.s.x + a.d.s.y;
	double Y = b.d.s.x + b.d.s.y;
	double Z = dab_x + dab_y;

	double p = prefs.p.get();
	double q = 1 - p;
	score = (q*C/A+p*Z/X)/sqrt(q*B/A+p*Y/X);
	if (a_->timeout)
		return score > 0.8;
	else
		return score > 0.7;
}

Glib::RefPtr<Gdk::Pixbuf> Stroke::draw(int size) const {
	if (size != STROKE_SIZE)
		return draw_(size);
	if (pb)
		return pb;
	pb = draw_(size);
	return pb;
}

Glib::RefPtr<Gdk::Pixbuf> Stroke::pbEmpty;

Glib::RefPtr<Gdk::Pixbuf> Stroke::drawEmpty(int size) {
	if (size != STROKE_SIZE)
		return drawEmpty_(size);
	if (pbEmpty)
		return pbEmpty;
	pbEmpty = drawEmpty_(size);
	return pbEmpty;
}

RStroke Stroke::trefoil() {
	PreStroke s;
	const int n = 80;
	const double pi = 3.141592653589793238462643;
	for (int i = 0; i<=n; i++) {
		double phi = pi*(-4.0*i/n)-2.7;
		double r = exp(1.0 + sin(6.0*pi*i/n)) + 2.0;
		s.add(create_triple(r*cos(phi), r*sin(phi), i));
	}
	return Stroke::create(s, 0, 0, false);
}
<commit_msg>increase threshold for timeout gestures<commit_after>/*
 * Copyright (c) 2008, Thomas Jaeger <ThJaeger@gmail.com>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
 * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
 * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include "stroke.h"
#include "prefdb.h"
#include <math.h>
#include <iterator>
#include <functional>

#define eps 0.000001

using namespace std;

inline bool close(double x, double y) {
	double diff = x - y;
	if (diff < 0)
		diff = -diff;
	return diff < eps;
}

int get_default_button() { return prefs.button.get().button; }

inline double sqr(double x) { return x*x; };

void update_triple(RTriple e, float x, float y, Time t) {
	e->x = x;
	e->y = y;
	e->t = t;
}

RTriple create_triple(float x, float y, Time t) {
	RTriple e(new Triple);
	update_triple(e, x, y, t);
	return e;
}

struct f : public std::unary_function<RTriple, Stroke::Point> {
	Stroke::Point operator()(RTriple e) {
		Stroke::Point p = { e->x, e->y, e->t };
		return p;
	}
};

Stroke::Stroke(PreStroke &s, int trigger_, int button_, bool timeout_) :
	trigger(trigger_), button(button_), timeout(timeout_)
{
	if (s.valid()) {
		std::transform(s.begin(), s.end(), std::back_inserter(points), f());
		normalize();
	}
}

void Stroke::normalize() {
	if (0) {
		double first = points.front().time;
		double length = points.back().time - first;
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			i->time -= first;
			i->time /= length;
		}
	} else {
		double total = 0;
		double lastx = 0;
		double lasty = 0;
		bool first = true;
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			if (first) {
				i->time = 0;
				lastx = i->x;
				lasty = i->y;
				first = false;
				continue;
			}
			total += hypot(i->x-lastx, i->y-lasty);
			i->time = total;
			lastx = i->x;
			lasty = i->y;
		}
		for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
			i->time /= total;
		}
	}

	double minX=0, minY=0, maxX=0, maxY=0;
	bool first = true;
	for (vector<Point>::iterator i = points.begin(); i!=points.end();i++) {
		if (first) {
			minX = i->x;
			maxX = i->x;
			minY = i->y;
			maxY = i->y;
			first = false;
		} else {
			if (i->x < minX) minX = i->x;
			if (i->x > maxX) maxX = i->x;
			if (i->y < minY) minY = i->y;
			if (i->y > maxY) maxY = i->y;
		}
	}
	double scaleX = maxX - minX;
	double scaleY = maxY - minY;
	double scale = (scaleX > scaleY) ? scaleX : scaleY;
	if (scale < 0.001) scale = 1;
	for (vector<Point>::iterator i = points.begin(); i != points.end(); i++) {
	   i->x = (i->x-(minX+maxX)/2)/scale + 0.5;
	   i->y = (i->y-(minY+maxY)/2)/scale + 0.5;
	}
}

void Stroke::print() const {
	printf("button: %d\n", button);
	for (vector<Point>::const_iterator i = points.begin(); i != points.end(); i++) {
		printf("pt: (%f, %f) at %f\n", i->x, i->y, i->time);
	}
}

double Stroke::length() const {
	double length = 0;
	bool first = true;
	double lastx = 0;
	double lasty = 0;
	for (vector<Point>::const_iterator i = points.begin(); i != points.end(); i++) {
		if (first) {
			lastx = i->x;
			lasty = i->y;
			first = false;
			continue;
		}
		length += hypot(i->x-lastx, i->y-lasty);
		lastx = i->x;
		lasty = i->y;
	}
	return length;
}

/********* Iterators **********/
struct Pt {
	double x; double y;
};

struct PtPair {
	double t;
	Pt a;
	Pt b;
};

class Stroke::RefineIterator {
	vector<Point>::const_iterator i, i_end, j, j_end;
public:
	RefineIterator(RStroke a, RStroke b) :
		i(a->points.begin()), i_end(a->points.end()), j(b->points.begin()), j_end(b->points.end()) {}
	double operator++(int) {
		if (close(i->time, j->time)) {
			double current = (i->time + j->time)/2;
			i++; j++;
			return current;
		}
		if (i->time < j->time) {
			double current = i->time;
			i++;
			return current;
		} else {
			double current = j->time;
			j++;
			return current;
		}
	}
	operator bool() {
		return i != i_end && j != j_end;
	}
};

class Stroke::InterpolateIterator {
	RefineIterator &t;
	vector<Point>::const_iterator j, j_end;
	const Point *a, *b; // The current line segment goes from a to b
	Pt current;
public:
	InterpolateIterator(RefineIterator &t_, RStroke &in) :
		t(t_),
		j(in->points.begin()),
		j_end(in->points.end()),
		a(0), b(0)
	{}
	operator bool() { return t; }
	Pt operator++(int) {
		double now = t++;
		while (j != j_end && (!a || b->time < now)) {
			a = b;
			b = &(*j);
			j++;
		}
		double delta = b->time - a->time;
		if (delta < eps) {
			current.x = b->x;
			current.y = b->y;
		} else {
			double k = (now - a->time) / delta;
			current.x = a->x + (b->x - a->x) * k;
			current.y = a->y + (b->y - a->y) * k;
		}
		return current;
	}
};

class Stroke::RIIterator {
	// There is more potential for optimization here
	RefineIterator t;
	RefineIterator ti;
	RefineIterator tj;
	InterpolateIterator i, j;
	PtPair p;
public:
	RIIterator(RStroke a, RStroke b) :
		t(a, b),
		ti(a, b),
		tj(a, b),
		i(ti, a),
		j(tj, b)
	{}
	operator bool() { return t; }
	PtPair operator++(int) {
		p.t = t++;
		p.a = i++;
		p.b = j++;
		return p;
	}
};

class Stroke::DiffIntegral : public EasyIterator<Point> {
	RIIterator i;
	double a_length, b_length;
public:
	DiffIntegral(RStroke a, RStroke b) : i(a, b), a_length(a->length()), b_length(b->length()) {}
	inline virtual const Point operator++(int) {
		PtPair ps = i++;
		Point p;
		p.x = ps.a.x/a_length - ps.b.x/b_length;
		p.y = ps.a.y/a_length - ps.b.y/b_length;
		p.time = ps.t;
		return p;
	}
	inline virtual operator bool() { return i; }
};

class Stroke::StrokeIntegral : public EasyIterator<Point> {
	vector<Point>::const_iterator i, i_end;
public:
	StrokeIntegral(const Stroke& s) : i(s.points.begin()), i_end(s.points.end()) {}
	inline virtual const Point operator++(int) { return *(i++); }
	inline virtual operator bool() { return i != i_end; }
};

/******** (Iterators) *********/

Integral Stroke::diff_integral(RStroke a, RStroke b) {
	DiffIntegral di(a, b);
	return integral(di);
}

Integral Stroke::integral() const{
	StrokeIntegral si(*this);
	return integral(si);
}

Integral Stroke::integral(EasyIterator<Point>& i) {
	Integral sum = {{{0,0},{0,0}},{{0,0},{0,0}}};
	Point a;
	Point b = i++;
	while (i) {
		a = b;
		b = i++;
		double delta = b.time - a.time;
		if (delta < eps)
			continue;
#define INT_II(l, c) delta * (c + l) / 2
		sum.i.i.x += INT_II(a.x, b.x);
		sum.i.i.y += INT_II(a.y, b.y);
#undef INT_II
#define INT_IS(l, c) delta * (c*(c+l)+l*l) / 3
		sum.i.s.x += INT_IS(a.x, b.x);
		sum.i.s.y += INT_IS(a.y, b.y);
#undef INT_IS
		sum.d.i.x += b.x - a.x;
		sum.d.i.y += b.y - a.y;
#define INT_DS(l, c) sqr(c-l)/delta
		sum.d.s.x += INT_DS(a.x, b.x);
		sum.d.s.y += INT_DS(a.y, b.y);
#undef INT_DS
	}
	return sum;
}

void Stroke::integral2(RStroke a, RStroke b, double &int_x, double &int_y, double &int_dx, double &int_dy) {
	PtPair cur = { 0, {0,0}, {0,0} };
	PtPair last = { 0, {0,0}, {0,0} };
	int_x = 0; int_y = 0; int_dx = 0; int_dy = 0;

	for (RIIterator i(a, b); i;) {
		last = cur;
		cur  = i++;
		double delta = cur.t - last.t;
		int_x += delta*(2*cur.a.x*cur.b.x+2*last.a.x*last.b.x+cur.a.x*last.b.x+cur.b.x*last.a.x)/6;
		int_y += delta*(2*cur.a.y*cur.b.y+2*last.a.y*last.b.y+cur.a.y*last.b.y+cur.b.y*last.a.y)/6;
		if (delta < eps)
			continue;
		int_dx += (cur.a.x-last.a.x)*(cur.b.x-last.b.x)/delta;
		int_dy += (cur.a.y-last.a.y)*(cur.b.y-last.b.y)/delta;
	}
}

bool Stroke::compare(RStroke a_, RStroke b_, double &score) {
	if (!a_ || !b_)
		return -2;
	if (!a_->timeout != !b_->timeout)
		return -2;
	if (a_->button != b_->button)
		if (!(a_->button == b_->trigger && b_->button == a_->trigger))
			return -2;
	if (a_->size() == 0 || b_->size() == 0) {
		if (a_->size() == 0 && b_->size() == 0)
			return 1;
		else
			return -2;
	}
	double ab_x, ab_y, dab_x, dab_y;
	integral2(a_, b_, ab_x, ab_y, dab_x, dab_y);
	Integral a = a_->integral();
	Integral b = b_->integral();
	double A = (a.i.s.x - sqr(a.i.i.x)) + (a.i.s.y - sqr(a.i.i.y));
	double B = (b.i.s.x - sqr(b.i.i.x)) + (b.i.s.y - sqr(b.i.i.y));
	double C = (ab_x - a.i.i.x * b.i.i.x) + (ab_y - a.i.i.y * b.i.i.y);
	double X = a.d.s.x + a.d.s.y;
	double Y = b.d.s.x + b.d.s.y;
	double Z = dab_x + dab_y;

	double p = prefs.p.get();
	double q = 1 - p;
	score = (q*C/A+p*Z/X)/sqrt(q*B/A+p*Y/X);
	if (a_->timeout)
		return score > 0.85;
	else
		return score > 0.7;
}

Glib::RefPtr<Gdk::Pixbuf> Stroke::draw(int size) const {
	if (size != STROKE_SIZE)
		return draw_(size);
	if (pb)
		return pb;
	pb = draw_(size);
	return pb;
}

Glib::RefPtr<Gdk::Pixbuf> Stroke::pbEmpty;

Glib::RefPtr<Gdk::Pixbuf> Stroke::drawEmpty(int size) {
	if (size != STROKE_SIZE)
		return drawEmpty_(size);
	if (pbEmpty)
		return pbEmpty;
	pbEmpty = drawEmpty_(size);
	return pbEmpty;
}

RStroke Stroke::trefoil() {
	PreStroke s;
	const int n = 80;
	const double pi = 3.141592653589793238462643;
	for (int i = 0; i<=n; i++) {
		double phi = pi*(-4.0*i/n)-2.7;
		double r = exp(1.0 + sin(6.0*pi*i/n)) + 2.0;
		s.add(create_triple(r*cos(phi), r*sin(phi), i));
	}
	return Stroke::create(s, 0, 0, false);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

using namespace std;

struct Input {
	int r, c, l, h;
	vector<vector<bool>> tomatoes;
};

struct Slice {
	int r1, c1, r2, c2;
};

struct Output {
	vector<Slice> slices;
};

void solveSimple(Input& input, Output& output) {
	//TODO add code here
}

void solveDP(Input& input, Output& output) {
	//TODO add code here
}

int main() {
	ios::sync_with_stdio(false);

	//read input
	Input input;
	cin >> input.r >> input.c >> input.l >> input.h;
	for(int i = 0; i < input.r; i++) {
		vector<bool> row(input.c);
		for(int j = 0; j < input.c; j++) {
			char cell;
			cin >> cell;
			row[j] = cell == 'T';
		}
		input.tomatoes.push_back(row);
		//TODO do we read line breaks?
	}

	//solve problem
	Output output;
	solve(input, output);

	//print output
	cout << output.slices.size() << endl;

};
<commit_msg>add algorithm switch<commit_after>#include <iostream>
#include <string>
#include <vector>

using namespace std;

//util classes
struct Input {
	int r, c, l, h;
	vector<vector<bool>> tomatoes;
};

struct Slice {
	int r1, c1, r2, c2;
};

struct Output {
	vector<Slice> slices;
};

void solveSimple(Input& input, Output& output) {
	//TODO add code here
}

void solveDP(Input& input, Output& output) {
	//TODO add code here
}

//input/output code
int main(int argc, char* argv[]) {
	ios::sync_with_stdio(false);

	//read input
	Input input;
	cin >> input.r >> input.c >> input.l >> input.h;
	for(int i = 0; i < input.r; i++) {
		vector<bool> row(input.c);
		for(int j = 0; j < input.c; j++) {
			char cell;
			cin >> cell;
			row[j] = cell == 'T';
		}
		input.tomatoes.push_back(row);
		//TODO do we read line breaks?
	}

	//read command line args
	string algorithm = "simple";
	if(argc > 2) {
		algorithm = argv[1];
	}

	//solve problem
	Output output;
	if(algorithm == "simple") {
		solveSimple(input, output);
	}
	else if(algorithm == "dp") {
		solveDP(input, output);
	}
	else {
		cerr << "unknown algorithm " << algorithm << endl;
		return 1;
	}

	//print output
	cout << output.slices.size() << endl;
	for(Slice slice: output.slices) {
		cout << slice.r1 << ' ' << slice.c1 << ' ' << slice.r2 << ' ' << slice.c2 << endl;
	}
};
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <string>
#include "lru.h"
#include <chrono>
#include <future>
#include <random>

using namespace std;
using namespace ::testing;

TEST(LruTest,AddTest) {
  LruCache<int,string> cache(50, std::chrono::milliseconds(0));
  cache.add(5,"some");
  auto a = cache.get(5);
  ASSERT_TRUE((bool)a);
  ASSERT_STREQ(a->c_str(), "some");
}

TEST(LruTest,WithoutAdditionTest) {
  LruCache<int,string> cache(50, std::chrono::milliseconds(0));
  ASSERT_FALSE(cache.get(5));
}

TEST(LruTest,EvictTest) {
  LruCache<int,string> cache(2, std::chrono::milliseconds(0));
  cache.add(1,"apple");
  cache.add(2,"bee");
  cache.add(3,"cat");
  ASSERT_FALSE(cache.get(1));
  ASSERT_STREQ(cache.get(2)->c_str(), "bee");
  ASSERT_STREQ(cache.get(3)->c_str(), "cat");
}

const std::string getRandomString(const int stringLength) {
  std::uniform_int_distribution<int> d(30, 126);
  std::random_device rd1; // uses RDRND or /dev/urandom
  std::string retString(' ',stringLength);
  for (int i = 0; i < stringLength; i++) {
     *(const_cast<char*>(retString.data())) = static_cast<char>(d(rd1));
  }
  return retString;
}

typedef std::vector<std::pair<int,std::string> > DATA_VECTOR;
typedef std::vector<std::pair<int,std::string> >* DATA_VECTOR_PTR;
typedef std::unique_ptr<DATA_VECTOR> DATA_VECTOR_UNIQUE_PTR;

void insertToCache(LruCache<int,std::string>* cache, DATA_VECTOR* dataVector) {
  DATA_VECTOR_UNIQUE_PTR autoReleaser(dataVector); //take ownership
  for(auto& dataItem : *dataVector) {
    cache->add(dataItem.first,dataItem.second);
  }
}

void setupDataVectors( DATA_VECTOR_PTR* dataVectors, int numDataPoints, int numberOfThreads) {
  std::uniform_int_distribution<int> d(0, numDataPoints * 10);
  std::random_device rd1; // uses RDRND or /dev/urandom

  for (int i = 0; i < numberOfThreads; i++) {
    dataVectors[i] = new DATA_VECTOR();
    for (int j = 0; j < numDataPoints; j++) {
      dataVectors[i]->push_back(std::make_pair(d(rd1), getRandomString(15)));
    }
  }
}

void waitForInsertions(LruCache<int,std::string>& cache, DATA_VECTOR_PTR* dataVectors, int numberOfThreads) {
  std::vector<std::future<void> > futures;
  for (int i = 0; i < numberOfThreads; i++) {
    futures.push_back(std::async( std::bind(insertToCache, &cache, dataVectors[i])));
  }
  for (auto& future : futures) {
    future.wait();
  }
}

const std::chrono::microseconds getTimingForInsertTest(const int cacheSize,
    const int numDataPoints, const int numberOfThreads = 5) {
  LruCache<int,std::string> cache(cacheSize, std::chrono::milliseconds(0));
  //auto numOfReads = 500;
  //auto fractionInCache = 0.5;
  auto dataVectors = new DATA_VECTOR_PTR[numberOfThreads];
  setupDataVectors(dataVectors, numDataPoints, numberOfThreads);

  auto t1 = std::chrono::high_resolution_clock::now();
  waitForInsertions(cache, dataVectors, numberOfThreads);
  auto t2 = std::chrono::high_resolution_clock::now();

  return std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1);
}

TEST(LruTest,AddTimingTest) {
  std::chrono::microseconds durationForTest = getTimingForInsertTest(500,500,5);
  std::cout << "Random Add Test took "
    << durationForTest.count()
    << " microseconds\n";
}

int main(int argc, char* argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<commit_msg>refactored tests and got rid of manual new<commit_after>#include <gtest/gtest.h>
#include <string>
#include "lru.h"
#include <chrono>
#include <future>
#include <random>

using namespace std;
using namespace ::testing;

typedef LruCache<int,std::string> LruTestCache;
typedef std::vector<std::chrono::microseconds> TimingVector;

TEST(LruTest,AddTest) {
  LruTestCache cache(50, std::chrono::milliseconds(0));
  cache.add(5,"some");
  auto a = cache.get(5);
  ASSERT_TRUE((bool)a);
  ASSERT_STREQ(a->c_str(), "some");
}

TEST(LruTest,WithoutAdditionTest) {
  LruTestCache cache(50, std::chrono::milliseconds(0));
  ASSERT_FALSE(cache.get(5));
}

TEST(LruTest,EvictTest) {
  LruTestCache cache(2, std::chrono::milliseconds(0));
  cache.add(1,"apple");
  cache.add(2,"bee");
  cache.add(3,"cat");
  ASSERT_FALSE(cache.get(1));
  ASSERT_STREQ(cache.get(2)->c_str(), "bee");
  ASSERT_STREQ(cache.get(3)->c_str(), "cat");
}

const std::string getRandomString(const int stringLength) {
  std::uniform_int_distribution<int> d(30, 126);
  std::random_device rd1; // uses RDRND or /dev/urandom
  std::string retString(' ',stringLength);
  for (int i = 0; i < stringLength; i++) {
     *(const_cast<char*>(retString.data())) = static_cast<char>(d(rd1));
  }
  return retString;
}

typedef std::vector<std::pair<int,std::string> > DATA_VECTOR;
typedef std::vector<DATA_VECTOR> DATA_VECTOR_LIST;
typedef std::unique_ptr<DATA_VECTOR> DATA_VECTOR_UNIQUE_PTR;

void insertToCache(LruTestCache& cache, DATA_VECTOR& dataVector) {
  for(auto& dataItem : dataVector) {
    cache.add(dataItem.first,dataItem.second);
  }
}

void setupDataVectors(DATA_VECTOR_LIST& dataVectors, int numDataPoints,
    int numberOfThreads) {
  std::uniform_int_distribution<int> d(0, numDataPoints * 10);
  std::random_device rd1; // uses RDRND or /dev/urandom

  for (int i = 0; i < numberOfThreads; i++) {
    for (int j = 0; j < numDataPoints; j++) {
      dataVectors[i].push_back(std::make_pair(d(rd1), getRandomString(15)));
    }
  }
}

void waitForInsertions(LruTestCache& cache, const DATA_VECTOR_LIST& dataVectors,
    int numberOfThreads) {
  std::vector<std::future<void> > futures;
  for (int i = 0; i < numberOfThreads; i++) {
    futures.push_back(std::async(std::bind(insertToCache, std::ref(cache), dataVectors[i])));
  }
  for (auto& future : futures) {
    future.wait();
  }
}

void readPercentageOfData(LruCache<int, std::string>& cache, const DATA_VECTOR& dataVector,
    int numDataPoints, double percentageToRead) {
  std::uniform_int_distribution<int> indexDist(0, dataVector.size());
  std::random_device rd1;
  for (int i = static_cast<int>(dataVector.size() * percentageToRead);
      i > 0; i-- ) {
      cache.get(dataVector[indexDist(rd1)].first);
  }
  std::uniform_int_distribution<int> dataDist(numDataPoints * 10, numDataPoints * 12);
  for (int i = static_cast<int>(dataVector.size() * percentageToRead);
      i > 0; i-- ) {
      cache.get(dataVector[dataDist(rd1)].first);
  }
}

const TimingVector getTimingForInsertTest(const int cacheSize,
    const int numDataPoints, const int numberOfThreads = 5) {
  LruTestCache cache(cacheSize, std::chrono::milliseconds(0));
  //auto numOfReads = 500;
  auto fractionInCache = 0.5;
  DATA_VECTOR_LIST dataVectors(numberOfThreads);
  setupDataVectors(dataVectors, numDataPoints, numberOfThreads);

  auto t1 = std::chrono::high_resolution_clock::now();
  waitForInsertions(cache, dataVectors, numberOfThreads);
  auto t2 = std::chrono::high_resolution_clock::now();
  readPercentageOfData(cache,dataVectors[0],numDataPoints,fractionInCache);
  auto t3 = std::chrono::high_resolution_clock::now();

  return { std::chrono::duration_cast<std::chrono::microseconds>(t2 - t1),
           std::chrono::duration_cast<std::chrono::microseconds>(t3 - t2),};
}

TEST(LruTest,AddTimingTest) {
  TimingVector durationsForTest = getTimingForInsertTest(500,500,5);
  std::cout << "Random Add Test took "
    << durationsForTest[0].count()
    << " microseconds\n";
}

int main(int argc, char* argv[]) {
  testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}
<|endoftext|>


<commit_before>//#include <lambda_p_llvm_test/tests.h>
//#include <lambda_p_repl_test/tests.h>
//#include <lambda_p_io_test/tests.h>
#include <lambda_p_test/tests.h>
//#include <lambda_p_script_test/tests.h>
//#include <lambda_p_script_io_test/tests.h>

#include <llvm/Target/TargetSelect.h>

#include <iostream>

using namespace lambda_p_test;

int main ()
{
    llvm::InitializeNativeTarget ();
	{
		lambda_p_test::tests test;
		test.run ();
	}
	//{
	//	lambda_p_io_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_script_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_script_io_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_llvm_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_repl_test::tests test;
	//	test.run ();
	//}

	for (size_t i (0); i < 1000; ++i)
	{
		std::wcout << L'-';
	}
	return 0;
}<commit_msg>Turning on tests.<commit_after>//#include <lambda_p_llvm_test/tests.h>
//#include <lambda_p_repl_test/tests.h>
#include <lambda_p_io_test/tests.h>
#include <lambda_p_test/tests.h>
//#include <lambda_p_script_test/tests.h>
//#include <lambda_p_script_io_test/tests.h>

#include <llvm/Target/TargetSelect.h>

#include <iostream>

using namespace lambda_p_test;

int main ()
{
    llvm::InitializeNativeTarget ();
	{
		lambda_p_test::tests test;
		test.run ();
	}
	{
		lambda_p_io_test::tests test;
		test.run ();
	}
	//{
	//	lambda_p_script_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_script_io_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_llvm_test::tests test;
	//	test.run ();
	//}
	//{
	//	lambda_p_repl_test::tests test;
	//	test.run ();
	//}

	for (size_t i (0); i < 1000; ++i)
	{
		std::wcout << L'-';
	}
	return 0;
}<|endoftext|>


<commit_before><commit_msg>i965/cfg: Handle no-idom case in cfg_t::dump_domtree().<commit_after><|endoftext|>


<commit_before>//  The MIT License (MIT)
//
//  Copyright (c) 2017 Tag Games Limited
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#ifdef CS_TARGETPLATFORM_RPI

#include <ChilliSource/Core/Base/DeviceInfo.h>
#include <ChilliSource/Core/Base/ScreenInfo.h>
#include <ChilliSource/Core/Base/SystemInfo.h>
#include <ChilliSource/Core/String/StringUtils.h>

#include <CSBackend/Platform/RPi/Core/Base/Screen.h>
#include <CSBackend/Platform/RPi/Core/Base/SystemInfoFactory.h>
#include <CSBackend/Rendering/OpenGL/Base/RenderInfoFactory.h>

#include <algorithm>
#include <vector>

namespace CSBackend
{
    namespace RPi
    {
        //--------------------------------------------------------------------------------
        ChilliSource::SystemInfoCUPtr SystemInfoFactory::CreateSystemInfo() noexcept
        {
            // Create DeviceInfo.
            ChilliSource::DeviceInfo deviceInfo(k_deviceModel, k_deviceModelType, k_deviceManufacturer, k_deviceUdid, GetLocale(), ParseLanguageFromLocale(GetLocale()), GetOSVersion(), GetNumberOfCPUCores());

            // Create ScreenInfo.
            ChilliSource::ScreenInfo screenInfo(GetScreenResolution(), 1.0f, 1.0f, GetSupportedResolutions());

			//Create RenderInfo
			ChilliSource::RenderInfo renderInfo = OpenGL::RenderInfoFactory::CreateRenderInfo();

            // Create SystemInfo.
            ChilliSource::SystemInfoUPtr systemInfo(new ChilliSource::SystemInfo(deviceInfo, screenInfo, renderInfo, ""));

            return std::move(systemInfo);
        }

    }
}

#endif
<commit_msg>Another blind commit, this time for system info<commit_after>//  The MIT License (MIT)
//
//  Copyright (c) 2017 Tag Games Limited
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#ifdef CS_TARGETPLATFORM_RPI

#include <ChilliSource/Core/Base/DeviceInfo.h>
#include <ChilliSource/Core/Base/ScreenInfo.h>
#include <ChilliSource/Core/Base/SystemInfo.h>
#include <ChilliSource/Core/String/StringUtils.h>

#include <CSBackend/Platform/RPi/Core/Base/Screen.h>
#include <CSBackend/Platform/RPi/Core/Base/SystemInfoFactory.h>
#include <CSBackend/Rendering/OpenGL/Base/RenderInfoFactory.h>

#include <sys/sysinfo.h>
#include <sys/utsname.h>

#include <algorithm>
#include <vector>

namespace CSBackend
{
    namespace RPi
    {
        namespace
        {
            const std::string k_deviceModel = "Raspberry Pi";
            const std::string k_deviceManufacturer = "Raspberry Pi Foundation";
            const std::string k_defaultLocale = "en_US";
            const std::string k_deviceUdid = "FAKE ID";

            /// Returns the language portion of a locale code.
            ///
            /// @param locale
            ///     The local code to parse
            ///
            /// @return The language code.
            ///
            std::string ParseLanguageFromLocale(const std::string& locale) noexcept
            {
                std::vector<std::string> localeBrokenUp = ChilliSource::StringUtils::Split(locale, "_", 0);

                if (localeBrokenUp.size() > 0)
                {
                    return localeBrokenUp[0];
                }
                else
                {
                    return k_defaultLocale;
                }
            }
        }

        //--------------------------------------------------------------------------------
        ChilliSource::SystemInfoCUPtr SystemInfoFactory::CreateSystemInfo() noexcept
        {
            utsname info;
            uname(&info);

            std::string osVersion(info.version);
            std::string machineType(info.machine);
            std::locale globalLocale; //Creating with the default constructor will set it to the global locale

            // Create DeviceInfo.
            ChilliSource::DeviceInfo deviceInfo(k_deviceModel, machineType, k_deviceManufacturer, k_deviceUdid, globalLocale.name(), ParseLanguageFromLocale(globalLocale.name()), osVersion, get_nprocs());

            // Create ScreenInfo.
            ChilliSource::ScreenInfo screenInfo(GetScreenResolution(), 1.0f, 1.0f, GetSupportedResolutions());

			//Create RenderInfo
			ChilliSource::RenderInfo renderInfo = OpenGL::RenderInfoFactory::CreateRenderInfo();

            // Create SystemInfo.
            ChilliSource::SystemInfoUPtr systemInfo(new ChilliSource::SystemInfo(deviceInfo, screenInfo, renderInfo, ""));

            return std::move(systemInfo);
        }

    }
}

#endif
<|endoftext|>


<commit_before>/*
 * transition_qtblend.cpp -- Qt composite transition
 * Copyright (c) 2016 Jean-Baptiste Mardelle <jb@kdenlive.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "common.h"
#include <framework/mlt.h>
#include <stdio.h>
#include <string.h>
#include <QImage>
#include <QPainter>
#include <QTransform>

static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
	int error = 0;
	mlt_frame b_frame = mlt_frame_pop_frame( a_frame );
	mlt_properties b_properties = MLT_FRAME_PROPERTIES( b_frame );
	mlt_properties properties = MLT_FRAME_PROPERTIES( a_frame );
	mlt_transition transition = MLT_TRANSITION( mlt_frame_pop_service( a_frame ) );
	mlt_properties transition_properties = MLT_TRANSITION_PROPERTIES( transition );

	uint8_t *b_image = NULL;
	bool hasAlpha = false;
	double opacity = 1.0;
	QTransform transform;
	// reference rect
	mlt_rect rect;

	// Determine length
	mlt_position length = mlt_transition_get_length( transition );
	// Get current position
	mlt_position position =  mlt_transition_get_position( transition, a_frame );

	// Obtain the normalised width and height from the a_frame
	mlt_profile profile = mlt_service_profile( MLT_TRANSITION_SERVICE( transition ) );
	int normalised_width = profile->width;
	int normalised_height = profile->height;
	double consumer_ar = mlt_profile_sar( profile );
	int b_width = mlt_properties_get_int( b_properties, "meta.media.width" );
	int b_height = mlt_properties_get_int( b_properties, "meta.media.height" );
	if ( b_height == 0 )
	{
		b_width = normalised_width;
		b_height = normalised_height;
	}
	double b_ar = mlt_frame_get_aspect_ratio( b_frame );
	double b_dar = b_ar * b_width / b_height;
	rect.w = -1;
	rect.h = -1;
	bool consumerScaling = false;

	// Check transform
	if ( mlt_properties_get( transition_properties, "rect" ) )
	{
		rect = mlt_properties_anim_get_rect( transition_properties, "rect", position, length );
		if (mlt_properties_get(transition_properties, "rect") && ::strchr(mlt_properties_get(transition_properties, "rect"), '%')) {
			rect.x *= normalised_width;
			rect.y *= normalised_height;
			rect.w *= normalised_width;
			rect.h *= normalised_height;
		}
		double scale = mlt_profile_scale_width(profile, *width);
		if ( scale != 1.0 ) {
			consumerScaling = true;
		}
		rect.x *= scale;
		rect.w *= scale;
		scale = mlt_profile_scale_height(profile, *height);
		if ( !consumerScaling && scale != 1.0 ) {
			consumerScaling = true;
		}
		rect.y *= scale;
		rect.h *= scale;
		transform.translate(rect.x, rect.y);
		opacity = rect.o;
	}

	double output_ar = mlt_profile_sar( profile );
	if ( mlt_frame_get_aspect_ratio( b_frame ) == 0 )
	{
		mlt_frame_set_aspect_ratio( b_frame, output_ar );
	}

	if ( mlt_properties_get( transition_properties, "rotation" ) )
	{
		double angle = mlt_properties_anim_get_double( transition_properties, "rotation", position, length );
		if (angle != 0.0) {
			if ( mlt_properties_get_int( transition_properties, "rotate_center" ) )
			{
				transform.translate( rect.w / 2.0, rect.h / 2.0 );
				transform.rotate( angle );
				transform.translate( -rect.w / 2.0, -rect.h / 2.0 );
			}
			else
			{
				transform.rotate( angle );
			}
			hasAlpha = true;
		}
	}

	// This is not a field-aware transform.
	mlt_properties_set_int( b_properties, "consumer_deinterlace", 1 );

	// Suppress padding and aspect normalization.
	char *interps = mlt_properties_get( properties, "rescale.interp" );
	if ( interps )
		interps = strdup( interps );

	if ( error )
	{
		return error;
	}

	// Adjust if consumer is scaling
	if ( consumerScaling )
	{
		// Scale request of b frame image to consumer scale maintaining its aspect ratio.
		b_height = *height;
		b_width = b_height * b_dar / b_ar;
	}

	if ( rect.w != -1 )
	{
		if ( mlt_properties_get_int( transition_properties, "distort" ) && b_width != 0 && b_height != 0 )
		{
			transform.scale( rect.w / b_width, rect.h / b_height );
		}
		else
		{
			// Determine scale with respect to aspect ratio.
			double geometry_dar = rect.w * consumer_ar / rect.h;
			double scale;
			if ( b_dar > geometry_dar )
			{
				scale = rect.w / b_width;
			}
			else
			{
				scale = rect.h / b_height * b_ar;
			}

			transform.translate((rect.w - (b_width * scale)) / 2.0, (rect.h - (b_height * scale)) / 2.0);
			transform.scale( scale, scale );
		}

		if ( opacity < 1 || rect.x > 0 || rect.y > 0 || (rect.x + rect.w < *width ) || (rect.y + rect.w < *height ) )
		{
			// we will process operations on top frame, so also process b_frame
			hasAlpha = true;
		}
	}
	else
	{
		// No transform, request profile sized image
		if (b_dar != mlt_profile_dar( profile ) )
		{
			// Activate transparency if the clips don't have the same aspect ratio
			hasAlpha = true;
		}
		// resize to consumer request
		b_width = *width;
		b_height = *height;
	}
	if ( !hasAlpha && ( mlt_properties_get_int( transition_properties, "compositing" ) != 0 || b_width < *width || b_height < *height ) )
	{
		hasAlpha = true;
	}

	// Check if we have transparency
	if ( !hasAlpha )
	{
		// fetch image
		mlt_image_format fmt = mlt_image_none;
		error = mlt_frame_get_image( b_frame, &b_image, &fmt, width, height, 1 );
		*format = fmt;
		if ( *format == mlt_image_rgb24a || mlt_frame_get_alpha( b_frame ) )
		{
			hasAlpha = true;
		}
	}
	if ( !hasAlpha )
	{
		// Prepare output image
		*image = b_image;
		mlt_frame_replace_image( a_frame, b_image, *format, *width, *height );
		free( interps );
		return 0;
	}
	// Get RGBA image to process
	*format = mlt_image_rgb24a;
	error = mlt_frame_get_image( b_frame, &b_image, format, &b_width, &b_height, writable );

	// Get bottom frame
	uint8_t *a_image = NULL;
	error = mlt_frame_get_image( a_frame, &a_image, format, width, height, 1 );
	if (error)
	{
		free( interps );
		return error;
	}
	// Prepare output image
	int image_size = mlt_image_format_size( *format, *width, *height, NULL );
	*image = (uint8_t *) mlt_pool_alloc( image_size );

	// Copy bottom frame in output
	memcpy( *image, a_image, image_size );

	bool hqPainting = false;
	if ( interps )
	{
		if ( strcmp( interps, "bilinear" ) == 0 || strcmp( interps, "bicubic" ) == 0 )
		{
			hqPainting = true;
		}
	}

	// convert bottom mlt image to qimage
	QImage bottomImg;
	convert_mlt_to_qimage_rgba( *image, &bottomImg, *width, *height );

	// convert top mlt image to qimage
	QImage topImg;
	convert_mlt_to_qimage_rgba( b_image, &topImg, b_width, b_height );

	// setup Qt drawing
	QPainter painter( &bottomImg );
	painter.setCompositionMode( ( QPainter::CompositionMode ) mlt_properties_get_int( transition_properties, "compositing" ) );
	painter.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform, hqPainting );
	painter.setTransform(transform);
	painter.setOpacity(opacity);

	// Composite top frame
	painter.drawImage(0, 0, topImg);

	// finish Qt drawing
	painter.end();
	convert_qimage_to_mlt_rgba( &bottomImg, *image, *width, *height );
	mlt_frame_set_image( a_frame, *image, image_size, mlt_pool_release);
	free( interps );
	return error;
}

static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame )
{
	mlt_frame_push_service( a_frame, transition );
	mlt_frame_push_frame( a_frame, b_frame );
	mlt_frame_push_get_image( a_frame, get_image );
	return a_frame;
}

extern "C" {

mlt_transition transition_qtblend_init( mlt_profile profile, mlt_service_type type, const char *id, void *arg )
{
	mlt_transition transition = mlt_transition_new();

	if ( transition )
	{
		mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition );

		if ( !createQApplicationIfNeeded( MLT_TRANSITION_SERVICE(transition) ) )
		{
			mlt_transition_close( transition );
			return NULL;
		}
		transition->process = process;
		mlt_properties_set_int( properties, "_transition_type", 1 ); // video only
		mlt_properties_set( properties, "rect", (char *) arg );
		mlt_properties_set_int( properties, "compositing", 0 );
		mlt_properties_set_int( properties, "distort", 0 );
		mlt_properties_set_int( properties, "rotate_center", 0 );
	}

	return transition;
}

} // extern "C"
<commit_msg>Revert qtblend optimization (caused crash when resizing)<commit_after>/*
 * transition_qtblend.cpp -- Qt composite transition
 * Copyright (c) 2016 Jean-Baptiste Mardelle <jb@kdenlive.org>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "common.h"
#include <framework/mlt.h>
#include <stdio.h>
#include <string.h>
#include <QImage>
#include <QPainter>
#include <QTransform>

static int get_image( mlt_frame a_frame, uint8_t **image, mlt_image_format *format, int *width, int *height, int writable )
{
	int error = 0;
	mlt_frame b_frame = mlt_frame_pop_frame( a_frame );
	mlt_properties b_properties = MLT_FRAME_PROPERTIES( b_frame );
	mlt_properties properties = MLT_FRAME_PROPERTIES( a_frame );
	mlt_transition transition = MLT_TRANSITION( mlt_frame_pop_service( a_frame ) );
	mlt_properties transition_properties = MLT_TRANSITION_PROPERTIES( transition );

	uint8_t *b_image = NULL;
	bool hasAlpha = false;
	double opacity = 1.0;
	QTransform transform;
	// reference rect
	mlt_rect rect;

	// Determine length
	mlt_position length = mlt_transition_get_length( transition );
	// Get current position
	mlt_position position =  mlt_transition_get_position( transition, a_frame );

	// Obtain the normalised width and height from the a_frame
	mlt_profile profile = mlt_service_profile( MLT_TRANSITION_SERVICE( transition ) );
	int normalised_width = profile->width;
	int normalised_height = profile->height;
	double consumer_ar = mlt_profile_sar( profile );
	int b_width = mlt_properties_get_int( b_properties, "meta.media.width" );
	int b_height = mlt_properties_get_int( b_properties, "meta.media.height" );
	if ( b_height == 0 )
	{
		b_width = normalised_width;
		b_height = normalised_height;
	}
	double b_ar = mlt_frame_get_aspect_ratio( b_frame );
	double b_dar = b_ar * b_width / b_height;
	rect.w = -1;
	rect.h = -1;
	bool consumerScaling = false;

	// Check transform
	if ( mlt_properties_get( transition_properties, "rect" ) )
	{
		rect = mlt_properties_anim_get_rect( transition_properties, "rect", position, length );
		if (mlt_properties_get(transition_properties, "rect") && ::strchr(mlt_properties_get(transition_properties, "rect"), '%')) {
			rect.x *= normalised_width;
			rect.y *= normalised_height;
			rect.w *= normalised_width;
			rect.h *= normalised_height;
		}
		double scale = mlt_profile_scale_width(profile, *width);
		if ( scale != 1.0 ) {
			consumerScaling = true;
		}
		rect.x *= scale;
		rect.w *= scale;
		scale = mlt_profile_scale_height(profile, *height);
		if ( !consumerScaling && scale != 1.0 ) {
			consumerScaling = true;
		}
		rect.y *= scale;
		rect.h *= scale;
		transform.translate(rect.x, rect.y);
		opacity = rect.o;
	}

	double output_ar = mlt_profile_sar( profile );
	if ( mlt_frame_get_aspect_ratio( b_frame ) == 0 )
	{
		mlt_frame_set_aspect_ratio( b_frame, output_ar );
	}

	if ( mlt_properties_get( transition_properties, "rotation" ) )
	{
		double angle = mlt_properties_anim_get_double( transition_properties, "rotation", position, length );
		if (angle != 0.0) {
			if ( mlt_properties_get_int( transition_properties, "rotate_center" ) )
			{
				transform.translate( rect.w / 2.0, rect.h / 2.0 );
				transform.rotate( angle );
				transform.translate( -rect.w / 2.0, -rect.h / 2.0 );
			}
			else
			{
				transform.rotate( angle );
			}
			hasAlpha = true;
		}
	}

	// This is not a field-aware transform.
	mlt_properties_set_int( b_properties, "consumer_deinterlace", 1 );

	// Suppress padding and aspect normalization.
	char *interps = mlt_properties_get( properties, "rescale.interp" );
	if ( interps )
		interps = strdup( interps );

	if ( error )
	{
		return error;
	}

	// Adjust if consumer is scaling
	if ( consumerScaling )
	{
		// Scale request of b frame image to consumer scale maintaining its aspect ratio.
		b_height = *height;
		b_width = b_height * b_dar / b_ar;
	}

	if ( rect.w != -1 )
	{
		if ( mlt_properties_get_int( transition_properties, "distort" ) && b_width != 0 && b_height != 0 )
		{
			transform.scale( rect.w / b_width, rect.h / b_height );
		}
		else
		{
			// Determine scale with respect to aspect ratio.
			double geometry_dar = rect.w * consumer_ar / rect.h;
			double scale;
			if ( b_dar > geometry_dar )
			{
				scale = rect.w / b_width;
			}
			else
			{
				scale = rect.h / b_height * b_ar;
			}

			transform.translate((rect.w - (b_width * scale)) / 2.0, (rect.h - (b_height * scale)) / 2.0);
			transform.scale( scale, scale );
		}

		if ( opacity < 1 || rect.x > 0 || rect.y > 0 || (rect.x + rect.w < *width ) || (rect.y + rect.w < *height ) )
		{
			// we will process operations on top frame, so also process b_frame
			hasAlpha = true;
		}
	}
	else
	{
		// No transform, request profile sized image
		if (b_dar != mlt_profile_dar( profile ) )
		{
			// Activate transparency if the clips don't have the same aspect ratio
			hasAlpha = true;
		}
		// resize to consumer request
		b_width = *width;
		b_height = *height;
	}
	if ( !hasAlpha && ( mlt_properties_get_int( transition_properties, "compositing" ) != 0 || b_width < *width || b_height < *height ) )
	{
		hasAlpha = true;
	}

	// Check if we have transparency
	if ( !hasAlpha )
	{
		// fetch image
		error = mlt_frame_get_image( b_frame, &b_image, format, width, height, 1 );
		if ( *format == mlt_image_rgb24a || mlt_frame_get_alpha( b_frame ) )
		{
			hasAlpha = true;
		}
	}
	if ( !hasAlpha )
	{
		// Prepare output image
		*image = b_image;
		mlt_frame_replace_image( a_frame, b_image, *format, *width, *height );
		free( interps );
		return 0;
	}
	// Get RGBA image to process
	*format = mlt_image_rgb24a;
	error = mlt_frame_get_image( b_frame, &b_image, format, &b_width, &b_height, writable );

	// Get bottom frame
	uint8_t *a_image = NULL;
	error = mlt_frame_get_image( a_frame, &a_image, format, width, height, 1 );
	if (error)
	{
		free( interps );
		return error;
	}
	// Prepare output image
	int image_size = mlt_image_format_size( *format, *width, *height, NULL );
	*image = (uint8_t *) mlt_pool_alloc( image_size );

	// Copy bottom frame in output
	memcpy( *image, a_image, image_size );

	bool hqPainting = false;
	if ( interps )
	{
		if ( strcmp( interps, "bilinear" ) == 0 || strcmp( interps, "bicubic" ) == 0 )
		{
			hqPainting = true;
		}
	}

	// convert bottom mlt image to qimage
	QImage bottomImg;
	convert_mlt_to_qimage_rgba( *image, &bottomImg, *width, *height );

	// convert top mlt image to qimage
	QImage topImg;
	convert_mlt_to_qimage_rgba( b_image, &topImg, b_width, b_height );

	// setup Qt drawing
	QPainter painter( &bottomImg );
	painter.setCompositionMode( ( QPainter::CompositionMode ) mlt_properties_get_int( transition_properties, "compositing" ) );
	painter.setRenderHints( QPainter::Antialiasing | QPainter::SmoothPixmapTransform, hqPainting );
	painter.setTransform(transform);
	painter.setOpacity(opacity);

	// Composite top frame
	painter.drawImage(0, 0, topImg);

	// finish Qt drawing
	painter.end();
	convert_qimage_to_mlt_rgba( &bottomImg, *image, *width, *height );
	mlt_frame_set_image( a_frame, *image, image_size, mlt_pool_release);
	free( interps );
	return error;
}

static mlt_frame process( mlt_transition transition, mlt_frame a_frame, mlt_frame b_frame )
{
	mlt_frame_push_service( a_frame, transition );
	mlt_frame_push_frame( a_frame, b_frame );
	mlt_frame_push_get_image( a_frame, get_image );
	return a_frame;
}

extern "C" {

mlt_transition transition_qtblend_init( mlt_profile profile, mlt_service_type type, const char *id, void *arg )
{
	mlt_transition transition = mlt_transition_new();

	if ( transition )
	{
		mlt_properties properties = MLT_TRANSITION_PROPERTIES( transition );

		if ( !createQApplicationIfNeeded( MLT_TRANSITION_SERVICE(transition) ) )
		{
			mlt_transition_close( transition );
			return NULL;
		}
		transition->process = process;
		mlt_properties_set_int( properties, "_transition_type", 1 ); // video only
		mlt_properties_set( properties, "rect", (char *) arg );
		mlt_properties_set_int( properties, "compositing", 0 );
		mlt_properties_set_int( properties, "distort", 0 );
		mlt_properties_set_int( properties, "rotate_center", 0 );
	}

	return transition;
}

} // extern "C"
<|endoftext|>


<commit_before>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <string>

#include <fmi4cpp/fmi4cpp.hpp>
#include <fmi4cpp/common/logger.hpp>

using namespace std;
using namespace fmi4cpp::fmi2;

namespace logger = fmi4cpp::logger;

const double stop = 0.01;
const double stepSize = 1E-3;

const string fmuPath = "../resources/fmus/2.0/cs/20sim/4.6.4.8004/"
                       "ControlledTemperature/ControlledTemperature.fmu";

int main() {

    fmi2Fmu fmu(fmuPath);
    auto cs_fmu = fmu.asCoSimulationFmu();
    auto md = cs_fmu->getModelDescription();

    auto var = md->modelVariables->getByValueReference(47).asReal();
    logger::info("Name={}, start={}", var.name(), var.start().value_or(0));

    auto slave1 = cs_fmu->newInstance();
    auto slave2 = cs_fmu->newInstance();

    logger::info("modelIdentifier={}", slave1->getModelDescription()->modelIdentifier);

    slave1->setupExperiment();
    slave1->enterInitializationMode();
    slave1->exitInitializationMode();

    slave2->setupExperiment();
    slave2->enterInitializationMode();
    slave2->exitInitializationMode();

    vector<fmi2Real> ref(2);
    vector<fmi2ValueReference> vr = {md->getVariableByName("Temperature_Reference").valueReference,
                                     md->getVariableByName("Temperature_Room").valueReference};

    double t = 0;
    while ((t = slave1->getSimulationTime()) <= stop) {

        if (!slave1->doStep(stepSize)) { break; }
        if (!slave1->readReal(vr, ref)) { break; }
        logger::info("t={}, Temperature_Reference={}, Temperature_Room={}", t, ref[0], ref[1]);

    }

    logger::info("FMU '{}' terminated with success: {}", fmu.modelName(), (slave1->terminate() == 1 ? "true" : "false"));
    logger::info("FMU '{}' terminated with success: {}", fmu.modelName(), (slave2->terminate() == 1 ? "true" : "false"));

    return 0;

}<commit_msg>fix logging<commit_after>/*
 * The MIT License
 *
 * Copyright 2017-2018 Norwegian University of Technology
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING  FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

#include <string>

#include <fmi4cpp/fmi4cpp.hpp>
#include <fmi4cpp/common/logger.hpp>

using namespace std;
using namespace fmi4cpp::fmi2;

namespace logger = fmi4cpp::logger;

const double stop = 0.01;
const double stepSize = 1E-3;

const string fmuPath = "../resources/fmus/2.0/cs/20sim/4.6.4.8004/"
                       "ControlledTemperature/ControlledTemperature.fmu";

int main() {

    fmi2Fmu fmu(fmuPath);
    auto cs_fmu = fmu.asCoSimulationFmu();
    auto md = cs_fmu->getModelDescription();

    auto var = md->modelVariables->getByValueReference(47).asReal();
    logger::info("Name={}, start={}", var.name(), var.start().value_or(0));

    auto slave1 = cs_fmu->newInstance();
    auto slave2 = cs_fmu->newInstance();

    logger::info("modelIdentifier={}", slave1->getModelDescription()->modelIdentifier.data());

    slave1->setupExperiment();
    slave1->enterInitializationMode();
    slave1->exitInitializationMode();

    slave2->setupExperiment();
    slave2->enterInitializationMode();
    slave2->exitInitializationMode();

    vector<fmi2Real> ref(2);
    vector<fmi2ValueReference> vr = {md->getVariableByName("Temperature_Reference").valueReference,
                                     md->getVariableByName("Temperature_Room").valueReference};

    double t = 0;
    while ((t = slave1->getSimulationTime()) <= stop) {

        if (!slave1->doStep(stepSize)) { break; }
        if (!slave1->readReal(vr, ref)) { break; }
        logger::info("t={}, Temperature_Reference={}, Temperature_Room={}", t, ref[0], ref[1]);

    }

    logger::info("FMU '{}' terminated with success: {}", fmu.modelName(), (slave1->terminate() == 1 ? "true" : "false"));
    logger::info("FMU '{}' terminated with success: {}", fmu.modelName(), (slave2->terminate() == 1 ? "true" : "false"));

    return 0;

}<|endoftext|>