<commit_before>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "../FileOnlyProfilingConnection.hpp"

#include <ProfilingService.hpp>
#include <Runtime.hpp>
#include <Filesystem.hpp>

#include <boost/core/ignore_unused.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/test/unit_test.hpp>

#include <cstdio>
#include <fstream>
#include <sstream>
#include <sys/stat.h>

using namespace armnn::profiling;
using namespace armnn;

using namespace std::chrono_literals;

class FileOnlyHelperService : public ProfilingService
{
    public:
    // Wait for a notification from the send thread
    bool WaitForPacketsSent(uint32_t timeout = 1000)
    {
        return ProfilingService::WaitForPacketSent(ProfilingService::Instance(), timeout);
    }
};

BOOST_AUTO_TEST_SUITE(FileOnlyProfilingDecoratorTests)

BOOST_AUTO_TEST_CASE(DumpOutgoingValidFileEndToEnd)
{
    // Create a temporary file name.
    boost::filesystem::path tempPath = boost::filesystem::temp_directory_path();
    boost::filesystem::path tempFile = boost::filesystem::unique_path();
    tempPath                         = tempPath / tempFile;
    armnn::Runtime::CreationOptions::ExternalProfilingOptions options;
    options.m_EnableProfiling     = true;
    options.m_FileOnly            = true;
    options.m_IncomingCaptureFile = "";
    options.m_OutgoingCaptureFile = tempPath.string();
    options.m_CapturePeriod       = 100;

    FileOnlyHelperService helper;

    // Enable the profiling service
    ProfilingService& profilingService = ProfilingService::Instance();
    profilingService.ResetExternalProfilingOptions(options, true);
    // Bring the profiling service to the "WaitingForAck" state
    profilingService.Update();
    profilingService.Update();

    BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::WaitingForAck);

    profilingService.Update();
    // First packet sent will be the SendStreamMetaDataPacket, it's possible though unlikely that it will be sent twice
    // The second or possibly third packet will be the CounterDirectoryPacket which means the
    // ConnectionAcknowledgedCommandHandler has set the state to active
    uint32_t packetCount = 0;
    while(profilingService.GetCurrentState() != ProfilingState::Active && packetCount < 3)
    {
        if(!helper.WaitForPacketsSent())
        {
            BOOST_FAIL("Timeout waiting for packets");
        }
        packetCount++;
    }

    BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::Active);
    // Minimum test here is to check that the file was created.
    BOOST_CHECK(boost::filesystem::exists(tempPath.c_str()) == true);

    // Increment a counter.
    BOOST_CHECK(profilingService.IsCounterRegistered(0) == true);
    profilingService.IncrementCounterValue(0);
    BOOST_CHECK(profilingService.GetCounterValue(0) > 0);

    // At this point the profiling service is active and we've activated all the counters. Waiting a collection
    // period should be enough to have some data in the file.

    // Wait for 1 collection period plus a bit of overhead..
    helper.WaitForPacketsSent();

    // In order to flush the files we need to gracefully close the profiling service.
    options.m_EnableProfiling = false;
    profilingService.ResetExternalProfilingOptions(options, true);

    // The output file size should be greater than 0.
    BOOST_CHECK(armnnUtils::Filesystem::GetFileSize(tempPath.string().c_str()) > 0);

    // Delete the tmp file.
    BOOST_CHECK(armnnUtils::Filesystem::Remove(tempPath.string().c_str()));
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>IVGCVSW-4171 Temporarily disable DumpOutgoingValidFileEndToEnd unit test<commit_after>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "../FileOnlyProfilingConnection.hpp"

#include <ProfilingService.hpp>
#include <Runtime.hpp>
#include <Filesystem.hpp>

#include <boost/core/ignore_unused.hpp>
#include <boost/filesystem.hpp>
#include <boost/numeric/conversion/cast.hpp>
#include <boost/test/unit_test.hpp>

#include <cstdio>
#include <fstream>
#include <sstream>
#include <sys/stat.h>

using namespace armnn::profiling;
using namespace armnn;

using namespace std::chrono_literals;

class FileOnlyHelperService : public ProfilingService
{
    public:
    // Wait for a notification from the send thread
    bool WaitForPacketsSent(uint32_t timeout = 1000)
    {
        return ProfilingService::WaitForPacketSent(ProfilingService::Instance(), timeout);
    }
};

BOOST_AUTO_TEST_SUITE(FileOnlyProfilingDecoratorTests)

BOOST_AUTO_TEST_CASE(DumpOutgoingValidFileEndToEnd, * boost::unit_test::disabled())
{
    // Create a temporary file name.
    boost::filesystem::path tempPath = boost::filesystem::temp_directory_path();
    boost::filesystem::path tempFile = boost::filesystem::unique_path();
    tempPath                         = tempPath / tempFile;
    armnn::Runtime::CreationOptions::ExternalProfilingOptions options;
    options.m_EnableProfiling     = true;
    options.m_FileOnly            = true;
    options.m_IncomingCaptureFile = "";
    options.m_OutgoingCaptureFile = tempPath.string();
    options.m_CapturePeriod       = 100;

    FileOnlyHelperService helper;

    // Enable the profiling service
    ProfilingService& profilingService = ProfilingService::Instance();
    profilingService.ResetExternalProfilingOptions(options, true);
    // Bring the profiling service to the "WaitingForAck" state
    profilingService.Update();
    profilingService.Update();

    BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::WaitingForAck);

    profilingService.Update();
    // First packet sent will be the SendStreamMetaDataPacket, it's possible though unlikely that it will be sent twice
    // The second or possibly third packet will be the CounterDirectoryPacket which means the
    // ConnectionAcknowledgedCommandHandler has set the state to active
    uint32_t packetCount = 0;
    while(profilingService.GetCurrentState() != ProfilingState::Active && packetCount < 3)
    {
        if(!helper.WaitForPacketsSent())
        {
            BOOST_FAIL("Timeout waiting for packets");
        }
        packetCount++;
    }

    BOOST_CHECK(profilingService.GetCurrentState() == ProfilingState::Active);
    // Minimum test here is to check that the file was created.
    BOOST_CHECK(boost::filesystem::exists(tempPath.c_str()) == true);

    // Increment a counter.
    BOOST_CHECK(profilingService.IsCounterRegistered(0) == true);
    profilingService.IncrementCounterValue(0);
    BOOST_CHECK(profilingService.GetCounterValue(0) > 0);

    // At this point the profiling service is active and we've activated all the counters. Waiting a collection
    // period should be enough to have some data in the file.

    // Wait for 1 collection period plus a bit of overhead..
    helper.WaitForPacketsSent();

    // In order to flush the files we need to gracefully close the profiling service.
    options.m_EnableProfiling = false;
    profilingService.ResetExternalProfilingOptions(options, true);

    // The output file size should be greater than 0.
    BOOST_CHECK(armnnUtils::Filesystem::GetFileSize(tempPath.string().c_str()) > 0);

    // Delete the tmp file.
    BOOST_CHECK(armnnUtils::Filesystem::Remove(tempPath.string().c_str()));
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   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 <Modules/Legacy/Fields/SplitFieldByConnectedRegion.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Scalar.h>
#include <Core/Datatypes/SparseRowMatrix.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

ModuleLookupInfo SplitFieldByConnectedRegion::staticInfo_("SplitFieldByConnectedRegion", "NewField", "SCIRun");

SplitFieldByConnectedRegion::SplitFieldByConnectedRegion()
  : Module(staticInfo_)
{
  INITIALIZE_PORT(InputField);
  INITIALIZE_PORT(OutputField1);
}

void SplitFieldByConnectedRegion::setStateDefaults()
{
/*
  setStateBoolFromAlgo(Parameters::NoInnerBoundary);
  setStateBoolFromAlgo(Parameters::DisconnectBoundaries); */
}

void SplitFieldByConnectedRegion::execute()
{
  // Define local handles of data objects:
/*  auto ifield = getRequiredInput(InputField);
  auto elemLink = getOptionalInput(ElemLink);
  auto minValue = getOptionalInput(MinValue);
  auto maxValue = getOptionalInput(MaxValue);

 if (needToExecute())
  {
    update_state(Executing);

    if (minValue && *minValue)
    {
      double minrange = (*minValue)->value();
      get_state()->setValue(Parameters::MinRange, minrange);
      get_state()->setValue(Parameters::Domain, minrange);  //??
    }
    if (maxValue && *maxValue)
    {
      double maxrange = (*maxValue)->value();
      get_state()->setValue(Parameters::MaxRange, maxrange);
    }

    auto state = get_state();

    setAlgoIntFromState(Parameters::MinRange);
    setAlgoIntFromState(Parameters::MaxRange);
    setAlgoIntFromState(Parameters::Domain);
    setAlgoBoolFromState(Parameters::UseRange);
    setAlgoBoolFromState(Parameters::AddOuterBoundary);
    setAlgoBoolFromState(Parameters::InnerBoundaryOnly);
    setAlgoBoolFromState(Parameters::NoInnerBoundary);
    setAlgoBoolFromState(Parameters::DisconnectBoundaries);

    if (!state->getValue(Parameters::UseRange).getBool())
    {
      int guiValue = state->getValue(Parameters::Domain).getInt();
      algo().set(Parameters::UseRange, true);
      algo().set(Parameters::MinRange, guiValue);
      algo().set(Parameters::MaxRange, guiValue);
    }

    auto output = algo().run_generic(make_input((InputField, ifield)(ElemLink, optionalAlgoInput(elemLink))));
    */
  if (needToExecute())
  {
   update_state(Executing);
   AlgorithmOutput output;
   sendOutputFromAlgorithm(OutputField1, output);
  }
}

#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER

#include <Core/Algorithms/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Datatypes/Bundle.h>
#include <Core/Datatypes/Field.h>

#include <Dataflow/Network/Ports/FieldPort.h>
#include <Dataflow/Network/Ports/BundlePort.h>
#include <Dataflow/Network/Module.h>

#include <sstream>

namespace ModelCreation {

using namespace SCIRun;

class SplitFieldByConnectedRegion : public Module {
  public:
    SplitFieldByConnectedRegion(GuiContext*);
    ~SplitFieldByConnectedRegion() {}
    virtual void execute();

  private:
    GuiInt    gui_sort_by_size_;
    GuiDouble gui_sort_ascending_;
    SCIRunAlgo::SplitByConnectedRegionAlgo algo_;
};

DECLARE_MAKER(SplitFieldByConnectedRegion)
SplitFieldByConnectedRegion::SplitFieldByConnectedRegion(GuiContext* ctx)
  : Module("SplitFieldByConnectedRegion", ctx, Source, "NewField", "SCIRun"),
    gui_sort_by_size_(get_ctx()->subVar("sort-by-size"),0),
    gui_sort_ascending_(get_ctx()->subVar("sort-ascending"),0)
{
  algo_.set_progress_reporter(this);
}

void SplitFieldByConnectedRegion::execute()
{
  // Define local handles of data objects:
  FieldHandle input;
  BundleHandle boutput;
  std::vector<FieldHandle> output;
  FieldHandle nofield = 0;

  // Get the new input data:
  get_input_handle("Field",input,true);

  // Only reexecute if the input changed. SCIRun uses simple scheduling
  // that executes every module downstream even if no data has changed:
  if (inputs_changed_  || !oport_cached("All Fields") || !oport_cached("Field1")
    || !oport_cached("Field2") || !oport_cached("Field3") || !oport_cached("Field4")
    || !oport_cached("Field5") || !oport_cached("Field6") || !oport_cached("Field7")
    || !oport_cached("Field8") || gui_sort_by_size_.changed()
    || gui_sort_ascending_.changed())
  {
    update_state(Executing);

    algo_.set_bool("sort_by_size",gui_sort_by_size_.get());
    algo_.set_bool("sort_ascending",gui_sort_ascending_.get());

    if(!(algo_.run(input,output))) return;

    boutput = new Bundle;
    for (size_t j=0; j< output.size(); j++)
    {
      std::ostringstream oss;
      oss << "Field" << j;
      boutput->setField(oss.str(),output[j]);
    }

    send_output_handle("All Fields",boutput);
    if (output.size() > 0) send_output_handle("Field1",output[0]);
    else send_output_handle("Field1",nofield);
    if (output.size() > 1) send_output_handle("Field2",output[1]);
    else send_output_handle("Field2",nofield);
    if (output.size() > 2) send_output_handle("Field3",output[2]);
    else send_output_handle("Field3",nofield);
    if (output.size() > 3) send_output_handle("Field4",output[3]);
    else send_output_handle("Field4",nofield);
    if (output.size() > 4) send_output_handle("Field5",output[4]);
    else send_output_handle("Field5",nofield);
    if (output.size() > 5) send_output_handle("Field6",output[5]);
    else send_output_handle("Field6",nofield);
    if (output.size() > 6) send_output_handle("Field7",output[6]);
    else send_output_handle("Field7",nofield);
    if (output.size() > 7) send_output_handle("Field8",output[7]);
    else send_output_handle("Field8",nofield);
  }
}

} // End namespace ModelCreation
 #endif

<commit_msg>intermediate commit<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

   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 <Modules/Legacy/Fields/SplitFieldByConnectedRegion.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Scalar.h>
#include <Core/Datatypes/SparseRowMatrix.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Core::Algorithms;
using namespace SCIRun::Core::Algorithms::Fields;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

ModuleLookupInfo SplitFieldByConnectedRegion::staticInfo_("SplitFieldByConnectedRegion", "NewField", "SCIRun");

SplitFieldByConnectedRegion::SplitFieldByConnectedRegion()
  : Module(staticInfo_)
{
  INITIALIZE_PORT(InputField);
  INITIALIZE_PORT(OutputField1);
}

void SplitFieldByConnectedRegion::setStateDefaults()
{
/*
  setStateBoolFromAlgo(Parameters::NoInnerBoundary);
  setStateBoolFromAlgo(Parameters::DisconnectBoundaries); */
}

void SplitFieldByConnectedRegion::execute()
{

/*  auto ifield = getRequiredInput(InputField);
  auto elemLink = getOptionalInput(ElemLink);
  auto minValue = getOptionalInput(MinValue);
  auto maxValue = getOptionalInput(MaxValue);

 if (needToExecute())
  {
    update_state(Executing);

    if (minValue && *minValue)
    {
      double minrange = (*minValue)->value();
      get_state()->setValue(Parameters::MinRange, minrange);
      get_state()->setValue(Parameters::Domain, minrange);  //??
    }
    if (maxValue && *maxValue)
    {
      double maxrange = (*maxValue)->value();
      get_state()->setValue(Parameters::MaxRange, maxrange);
    }

    auto state = get_state();

    setAlgoIntFromState(Parameters::MinRange);
    setAlgoIntFromState(Parameters::MaxRange);
    setAlgoIntFromState(Parameters::Domain);
    setAlgoBoolFromState(Parameters::UseRange);
    setAlgoBoolFromState(Parameters::AddOuterBoundary);
    setAlgoBoolFromState(Parameters::InnerBoundaryOnly);
    setAlgoBoolFromState(Parameters::NoInnerBoundary);
    setAlgoBoolFromState(Parameters::DisconnectBoundaries);

    if (!state->getValue(Parameters::UseRange).getBool())
    {
      int guiValue = state->getValue(Parameters::Domain).getInt();
      algo().set(Parameters::UseRange, true);
      algo().set(Parameters::MinRange, guiValue);
      algo().set(Parameters::MaxRange, guiValue);
    }

    auto output = algo().run_generic(make_input((InputField, ifield)(ElemLink, optionalAlgoInput(elemLink))));
    */
  if (needToExecute())
  {
   update_state(Executing);
   AlgorithmOutput output;
   sendOutputFromAlgorithm(OutputField1, output);
  }
}

#ifdef SCIRUN4_CODE_TO_BE_ENABLED_LATER

#include <Core/Algorithms/Fields/MeshDerivatives/SplitByConnectedRegion.h>
#include <Core/Datatypes/Bundle.h>
#include <Core/Datatypes/Field.h>

#include <Dataflow/Network/Ports/FieldPort.h>
#include <Dataflow/Network/Ports/BundlePort.h>
#include <Dataflow/Network/Module.h>

#include <sstream>

namespace ModelCreation {

using namespace SCIRun;

class SplitFieldByConnectedRegion : public Module {
  public:
    SplitFieldByConnectedRegion(GuiContext*);
    ~SplitFieldByConnectedRegion() {}
    virtual void execute();

  private:
    GuiInt    gui_sort_by_size_;
    GuiDouble gui_sort_ascending_;
    SCIRunAlgo::SplitByConnectedRegionAlgo algo_;
};

DECLARE_MAKER(SplitFieldByConnectedRegion)
SplitFieldByConnectedRegion::SplitFieldByConnectedRegion(GuiContext* ctx)
  : Module("SplitFieldByConnectedRegion", ctx, Source, "NewField", "SCIRun"),
    gui_sort_by_size_(get_ctx()->subVar("sort-by-size"),0),
    gui_sort_ascending_(get_ctx()->subVar("sort-ascending"),0)
{
  algo_.set_progress_reporter(this);
}

void SplitFieldByConnectedRegion::execute()
{
  // Define local handles of data objects:
  FieldHandle input;
  BundleHandle boutput;
  std::vector<FieldHandle> output;
  FieldHandle nofield = 0;

  // Get the new input data:
  get_input_handle("Field",input,true);

  // Only reexecute if the input changed. SCIRun uses simple scheduling
  // that executes every module downstream even if no data has changed:
  if (inputs_changed_  || !oport_cached("All Fields") || !oport_cached("Field1")
    || !oport_cached("Field2") || !oport_cached("Field3") || !oport_cached("Field4")
    || !oport_cached("Field5") || !oport_cached("Field6") || !oport_cached("Field7")
    || !oport_cached("Field8") || gui_sort_by_size_.changed()
    || gui_sort_ascending_.changed())
  {
    update_state(Executing);

    algo_.set_bool("sort_by_size",gui_sort_by_size_.get());
    algo_.set_bool("sort_ascending",gui_sort_ascending_.get());

    if(!(algo_.run(input,output))) return;

    boutput = new Bundle;
    for (size_t j=0; j< output.size(); j++)
    {
      std::ostringstream oss;
      oss << "Field" << j;
      boutput->setField(oss.str(),output[j]);
    }

    send_output_handle("All Fields",boutput);
    if (output.size() > 0) send_output_handle("Field1",output[0]);
    else send_output_handle("Field1",nofield);
    if (output.size() > 1) send_output_handle("Field2",output[1]);
    else send_output_handle("Field2",nofield);
    if (output.size() > 2) send_output_handle("Field3",output[2]);
    else send_output_handle("Field3",nofield);
    if (output.size() > 3) send_output_handle("Field4",output[3]);
    else send_output_handle("Field4",nofield);
    if (output.size() > 4) send_output_handle("Field5",output[4]);
    else send_output_handle("Field5",nofield);
    if (output.size() > 5) send_output_handle("Field6",output[5]);
    else send_output_handle("Field6",nofield);
    if (output.size() > 6) send_output_handle("Field7",output[6]);
    else send_output_handle("Field7",nofield);
    if (output.size() > 7) send_output_handle("Field8",output[7]);
    else send_output_handle("Field8",nofield);
  }
}

} // End namespace ModelCreation
 #endif

<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "PoiRingController.h"
#include "InteriorsFloorModel.h"
#include "InteriorsModel.h"
#include "InteriorId.h"
#include "TtyHandler.h"
#include "CameraHelpers.h"
#include "RenderCamera.h"
#include "IRayPicker.h"
#include "PoiRingView.h"
#include "RenderContext.h"
#include "MathFunc.h"
#include "MathsHelpers.h"
#include "IMyPinCreationInitiationViewModel.h"
#include "IMyPinCreationModel.h"
#include "EarthConstants.h"
#include "TerrainHeightProvider.h"
#include "TransformHelpers.h"
#include "VectorMath.h"
#include "InteriorController.h"

#include "InteriorHeightHelpers.h"
#include "ScreenProperties.h"

namespace ExampleApp
{
    namespace MyPinCreation
    {
        namespace PoiRing
        {
            namespace SdkModel
            {
                namespace
                {

                    float CalculateAltitudeBasedSphereOuterScale(float altitude)
                    {
                        const float minAltitude = 50.f;
                        const float maxAltitude = 1500.f;
                        const float lowAltitudeScale = 0.05f;
                        const float highAltitudeScale = 1.0f;
                        float t = Eegeo::Math::Clamp01((altitude - minAltitude)/(maxAltitude-minAltitude));
                        return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);
                    }

                    float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)
                    {
                        const float minAltitude = 100.f;
                        const float maxAltitude = 18000.f;
                        const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;
                        const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;
                        return lowAltitudeSphereScale + (((altitude - minAltitude)/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));
                    }

                    bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)
                    {
                        const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();
                        const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();

                        for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)
                        {
                            const Eegeo::Geometry::Plane& p = frustum.planes[i];
                            double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;

                            if (signedDist < -radius)
                            {
                                return false;
                            }
                        }

                        return true;
                    }
                }

                PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,
                                                     PoiRingView& poiRingView,
                                                     Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,
                                                     Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,
                                                     Eegeo::Resources::Interiors::InteriorController& interiorController,
                                                     Eegeo::Rendering::ScreenProperties& screenProperties)
                    : m_myPinCreationModel(myPinCreationModel)
                    , m_poiRingView(poiRingView)
                    , m_scaleInterpolationParam(0.f)
                    , m_easeDurationInSeconds(1.2f)
                    , m_environmentFlatteningService(environmentFlatteningService)
                    , m_terrainHeightProvider(terrainHeightProvider)
                    , m_iconPosition(Eegeo::dv3::Zero())
                    , m_iconSize(0.0f)
                    , m_ringRadius(0.0f)
                    , m_interiorController(interiorController)
                    , m_screenProperties(screenProperties)
                {

                }

                void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)
                {
                    const bool showingInterior = m_interiorController.InteriorIsVisible();
                    float interiorDownScale = showingInterior ? 0.5f : 1.0f;
                    const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));
                    const float outerRingRadiusInMeters = 120.f * interiorDownScale;
                    const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);
                    const float transitionScale = CalculateTransitionScale(dt);
                    m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;

                    const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);

                    m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);

                    if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)
                    {
                        m_scaleInterpolationParam = 0.f;
                    }

                    if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)
                    {
                        m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);
                    }

                    if(m_myPinCreationModel.NeedsTerrainHeight())
                    {
                        float terrainHeight;
                        if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))
                        {
                            m_myPinCreationModel.SetTerrainHeight(terrainHeight);
                        }
                    }

                    if(m_myPinCreationModel.GetCreationStage() == Ring)
                    {
                        m_myPinCreationModel.SetInterior(showingInterior);
                        if(showingInterior)
                        {
                            const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;
                            bool success = m_interiorController.TryGetCurrentModel(pModel);
                            if(success)
                            {
                                const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();
                                m_myPinCreationModel.SetBuildingId(buildingId);
                            }

                            m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());
                            float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());
                            const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();
                            m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);
                        }
                        else
                        {
                            m_myPinCreationModel.SetHeightAboveTerrain(0);
                        }
                    }

                    Eegeo::m44 sphereTransformMatrix;
                    sphereTransformMatrix.Scale(m_ringRadius);

                    Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());

                    Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();
                    sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));

                    m_poiRingView.SetRingTransforms(sphereTransformMatrix);

                    float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);
                    m_poiRingView.SetInnerSphereScale(altitudeBasedScale);

                    Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();
                    Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(
                                                  unflattenedIconPosition,
                                                  m_environmentFlatteningService.GetCurrentScale());

                    const float assetSize = 75.f;
                    const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) / (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;

                    m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);
                    m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);

                    m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;
                }

                float PoiRingController::CalculateTransitionScale(float dt)
                {
                    float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;
                    delta /= m_easeDurationInSeconds;
                    m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);
                    return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);
                }

                void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const
                {
                    out_positionEcef = m_iconPosition;
                    out_sizeMeters = m_iconSize;
                }

                void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const
                {
                    out_sphereCenterEcef = m_myPinCreationModel.GetPosition();
                    out_sphereRadius = m_ringRadius;
                }
            }
        }
    }
}
<commit_msg>Fix for https://bugs.eegeo.com/browse/MPLY-6031 - mitigate error in PinCreationModel, where PoiRingController SetHeightAboveTerrain causes refresh of position with invalid cached height. Must go back and fix PinCreationModel internals. Discussed with TJ and FM, buddy: MB.<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "PoiRingController.h"
#include "InteriorsFloorModel.h"
#include "InteriorsModel.h"
#include "InteriorId.h"
#include "TtyHandler.h"
#include "CameraHelpers.h"
#include "RenderCamera.h"
#include "IRayPicker.h"
#include "PoiRingView.h"
#include "RenderContext.h"
#include "MathFunc.h"
#include "MathsHelpers.h"
#include "IMyPinCreationInitiationViewModel.h"
#include "IMyPinCreationModel.h"
#include "EarthConstants.h"
#include "TerrainHeightProvider.h"
#include "TransformHelpers.h"
#include "VectorMath.h"
#include "InteriorController.h"

#include "InteriorHeightHelpers.h"
#include "ScreenProperties.h"

namespace ExampleApp
{
    namespace MyPinCreation
    {
        namespace PoiRing
        {
            namespace SdkModel
            {
                namespace
                {

                    float CalculateAltitudeBasedSphereOuterScale(float altitude)
                    {
                        const float minAltitude = 50.f;
                        const float maxAltitude = 1500.f;
                        const float lowAltitudeScale = 0.05f;
                        const float highAltitudeScale = 1.0f;
                        float t = Eegeo::Math::Clamp01((altitude - minAltitude)/(maxAltitude-minAltitude));
                        return Eegeo::Math::Lerp(lowAltitudeScale, highAltitudeScale, t);
                    }

                    float CalculateAltitudeBasedSphereScale(float altitude, float outerRingRadiusInMeters)
                    {
                        const float minAltitude = 100.f;
                        const float maxAltitude = 18000.f;
                        const float lowAltitudeSphereScale = outerRingRadiusInMeters - 0.5f;
                        const float highAltitudeSphereScale = outerRingRadiusInMeters - 100.f;
                        return lowAltitudeSphereScale + (((altitude - minAltitude)/maxAltitude) * (highAltitudeSphereScale - lowAltitudeSphereScale));
                    }

                    bool RingIsOnScreen(const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& position, float radius)
                    {
                        const Eegeo::Geometry::Frustum& frustum = renderCamera.GetFrustum();
                        const Eegeo::dv3 cameraRelativePosition = position - renderCamera.GetEcefLocation();

                        for (int i = 0; i < Eegeo::Geometry::Frustum::PLANES_COUNT; ++i)
                        {
                            const Eegeo::Geometry::Plane& p = frustum.planes[i];
                            double signedDist = p.a * cameraRelativePosition.GetX() + p.b * cameraRelativePosition.GetY() + p.c * cameraRelativePosition.GetZ() + p.d;

                            if (signedDist < -radius)
                            {
                                return false;
                            }
                        }

                        return true;
                    }
                }

                PoiRingController::PoiRingController(MyPinCreation::SdkModel::IMyPinCreationModel& myPinCreationModel,
                                                     PoiRingView& poiRingView,
                                                     Eegeo::Rendering::EnvironmentFlatteningService& environmentFlatteningService,
                                                     Eegeo::Resources::Terrain::Heights::TerrainHeightProvider& terrainHeightProvider,
                                                     Eegeo::Resources::Interiors::InteriorController& interiorController,
                                                     Eegeo::Rendering::ScreenProperties& screenProperties)
                    : m_myPinCreationModel(myPinCreationModel)
                    , m_poiRingView(poiRingView)
                    , m_scaleInterpolationParam(0.f)
                    , m_easeDurationInSeconds(1.2f)
                    , m_environmentFlatteningService(environmentFlatteningService)
                    , m_terrainHeightProvider(terrainHeightProvider)
                    , m_iconPosition(Eegeo::dv3::Zero())
                    , m_iconSize(0.0f)
                    , m_ringRadius(0.0f)
                    , m_interiorController(interiorController)
                    , m_screenProperties(screenProperties)
                {

                }

                void PoiRingController::Update(float dt, const Eegeo::Camera::RenderCamera& renderCamera, const Eegeo::dv3& cameraEcefInterestPoint)
                {
                    const bool showingInterior = m_interiorController.InteriorIsVisible();
                    float interiorDownScale = showingInterior ? 0.5f : 1.0f;
                    const float altitude = (float)(renderCamera.GetAltitude() - (m_myPinCreationModel.GetPosition().Length() - Eegeo::Space::EarthConstants::Radius));
                    const float outerRingRadiusInMeters = 120.f * interiorDownScale;
                    const float altitudeScale = CalculateAltitudeBasedSphereOuterScale(altitude);
                    const float transitionScale = CalculateTransitionScale(dt);
                    m_ringRadius = outerRingRadiusInMeters * altitudeScale * transitionScale;

                    const bool ringIsOnScreen = RingIsOnScreen(renderCamera, m_myPinCreationModel.GetPosition(), m_ringRadius);

                    m_poiRingView.SetShouldRenderRing(m_scaleInterpolationParam > 0.f && ringIsOnScreen);

                    if (m_myPinCreationModel.GetCreationStage() == Inactive && !ringIsOnScreen)
                    {
                        m_scaleInterpolationParam = 0.f;
                    }

                    if (m_scaleInterpolationParam < 0.01f && m_myPinCreationModel.GetCreationStage() != Details)
                    {
                        m_myPinCreationModel.SetPosition(cameraEcefInterestPoint);
                    }

                    if(m_myPinCreationModel.NeedsTerrainHeight())
                    {
                        float terrainHeight;
                        if(m_terrainHeightProvider.TryGetHeight(m_myPinCreationModel.GetPosition(), 11, terrainHeight))
                        {
                            m_myPinCreationModel.SetTerrainHeight(terrainHeight);
                        }
                    }

                    if(m_myPinCreationModel.GetCreationStage() == Ring)
                    {
                        m_myPinCreationModel.SetInterior(showingInterior);
                        if(showingInterior)
                        {
                            const Eegeo::Resources::Interiors::InteriorsModel *pModel = NULL;
                            bool success = m_interiorController.TryGetCurrentModel(pModel);
                            if(success)
                            {
                                const Eegeo::Resources::Interiors::InteriorId& buildingId = pModel->GetId();
                                m_myPinCreationModel.SetBuildingId(buildingId);
                            }

                            m_myPinCreationModel.SetFloor(m_interiorController.GetCurrentFloorIndex());
                            float floorHeightAboveSeaLevel = Helpers::InteriorHeightHelpers::GetFloorHeightAboveSeaLevel(*pModel, m_interiorController.GetCurrentFloorIndex());
                            const float floorHeightAboveTerrain = floorHeightAboveSeaLevel - m_myPinCreationModel.GetTerrainHeight();
                            m_myPinCreationModel.SetHeightAboveTerrain(floorHeightAboveTerrain);
                        }
                    }

                    Eegeo::m44 sphereTransformMatrix;
                    sphereTransformMatrix.Scale(m_ringRadius);

                    Eegeo::dv3 scaledPoint = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(m_myPinCreationModel.GetPosition(), m_environmentFlatteningService.GetCurrentScale());

                    Eegeo::dv3 cameraRelativePosition = scaledPoint - renderCamera.GetEcefLocation();
                    sphereTransformMatrix.SetRow(3, Eegeo::v4(cameraRelativePosition.ToSingle(), 1.f));

                    m_poiRingView.SetRingTransforms(sphereTransformMatrix);

                    float altitudeBasedScale = CalculateAltitudeBasedSphereScale(altitude, m_ringRadius);
                    m_poiRingView.SetInnerSphereScale(altitudeBasedScale);

                    Eegeo::dv3 unflattenedIconPosition = m_myPinCreationModel.GetPosition();
                    Eegeo::dv3 iconPosition = Eegeo::Rendering::EnvironmentFlatteningService::GetScaledPointEcef(
                                                  unflattenedIconPosition,
                                                  m_environmentFlatteningService.GetCurrentScale());

                    const float assetSize = 75.f;
                    const float iconScale = Eegeo::Helpers::TransformHelpers::ComputeModelScaleForConstantScreenSizeWithVerticalFoV(renderCamera, iconPosition) / (m_screenProperties.GetScreenHeight()* 0.5f)*m_screenProperties.GetPixelScale() * assetSize;

                    m_iconSize = Eegeo::Max(iconScale * transitionScale, 0.0f);
                    m_poiRingView.AddIconSprite(renderCamera, iconPosition, m_iconSize);

                    m_iconPosition = iconPosition + (Eegeo::dv3)renderCamera.GetModelMatrix().GetRow(1) * m_iconSize * 0.5f;
                }

                float PoiRingController::CalculateTransitionScale(float dt)
                {
                    float delta = m_myPinCreationModel.GetCreationStage() == Ring ? dt : -dt;
                    delta /= m_easeDurationInSeconds;
                    m_scaleInterpolationParam = Eegeo::Clamp(m_scaleInterpolationParam + delta, 0.f, 1.f);
                    return Eegeo::Helpers::MathsHelpers::PennerElasticEaseInOut(0.f, 1.f, m_scaleInterpolationParam);
                }

                void PoiRingController::GetIconPositionAndSize(Eegeo::dv3& out_positionEcef, float& out_sizeMeters) const
                {
                    out_positionEcef = m_iconPosition;
                    out_sizeMeters = m_iconSize;
                }

                void PoiRingController::GetSpherePositionAndRadius(Eegeo::dv3& out_sphereCenterEcef, float& out_sphereRadius) const
                {
                    out_sphereCenterEcef = m_myPinCreationModel.GetPosition();
                    out_sphereRadius = m_ringRadius;
                }
            }
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2008, Google Inc.
// 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 Google Inc. 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
// 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 "config.h"

#include "webkit/glue/npruntime_util.h"

// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "third_party/npapi/bindings/c/c_utility.h"
using KJS::Bindings::PrivateIdentifier;
#endif

#include "base/pickle.h"

namespace webkit_glue {

bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
  PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);

  // If the identifier was null, then we just send a numeric 0.  This is to
  // support cases where the other end doesn't care about the NPIdentifier
  // being serialized, so the bogus value of 0 is really inconsequential.
  PrivateIdentifier null_id;
  if (!priv) {
    priv = &null_id;
    priv->isString = false;
    priv->value.number = 0;
  }

  if (!pickle->WriteBool(priv->isString))
    return false;
  if (priv->isString) {
    // Write the null byte for efficiency on the other end.
    return pickle->WriteData(
        priv->value.string, strlen(priv->value.string) + 1);
  }
  return pickle->WriteInt(priv->value.number);
}

bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
                             NPIdentifier* identifier) {
  bool is_string;
  if (!pickle.ReadBool(pickle_iter, &is_string))
    return false;

  if (is_string) {
    const char* data;
    int data_len;
    if (!pickle.ReadData(pickle_iter, &data, &data_len))
      return false;
    DCHECK_EQ(data_len, strlen(data) + 1);
    *identifier = NPN_GetStringIdentifier(data);
  } else {
    int number;
    if (!pickle.ReadInt(pickle_iter, &number))
      return false;
    *identifier = NPN_GetIntIdentifier(number);
  }
  return true;
}

}  // namespace webkit_glue
<commit_msg>Revert my change for c_utility so that the JSC build will compile<commit_after>// Copyright 2008, Google Inc.
// 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 Google Inc. 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
// 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 "config.h"

#include "webkit/glue/npruntime_util.h"

// Import the definition of PrivateIdentifier
#if USE(V8_BINDING)
#include "webkit/port/bindings/v8/np_v8object.h"
#elif USE(JAVASCRIPTCORE_BINDINGS)
#include "bindings/c/c_utility.h"
using KJS::Bindings::PrivateIdentifier;
#endif

#include "base/pickle.h"

namespace webkit_glue {

bool SerializeNPIdentifier(NPIdentifier identifier, Pickle* pickle) {
  PrivateIdentifier* priv = static_cast<PrivateIdentifier*>(identifier);

  // If the identifier was null, then we just send a numeric 0.  This is to
  // support cases where the other end doesn't care about the NPIdentifier
  // being serialized, so the bogus value of 0 is really inconsequential.
  PrivateIdentifier null_id;
  if (!priv) {
    priv = &null_id;
    priv->isString = false;
    priv->value.number = 0;
  }

  if (!pickle->WriteBool(priv->isString))
    return false;
  if (priv->isString) {
    // Write the null byte for efficiency on the other end.
    return pickle->WriteData(
        priv->value.string, strlen(priv->value.string) + 1);
  }
  return pickle->WriteInt(priv->value.number);
}

bool DeserializeNPIdentifier(const Pickle& pickle, void** pickle_iter,
                             NPIdentifier* identifier) {
  bool is_string;
  if (!pickle.ReadBool(pickle_iter, &is_string))
    return false;

  if (is_string) {
    const char* data;
    int data_len;
    if (!pickle.ReadData(pickle_iter, &data, &data_len))
      return false;
    DCHECK_EQ(data_len, strlen(data) + 1);
    *identifier = NPN_GetStringIdentifier(data);
  } else {
    int number;
    if (!pickle.ReadInt(pickle_iter, &number))
      return false;
    *identifier = NPN_GetIntIdentifier(number);
  }
  return true;
}

}  // namespace webkit_glue
<|endoftext|>


<commit_before>/*
* blinkyBlocksSimulator.cpp
*
*  Created on: 23 mars 2013
*      Author: dom
*/

#include <iostream>
#include "blinkyBlocksSimulator.h"
#include <string.h>
#include "trace.h"

using namespace std;

namespace BlinkyBlocks {

BlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL;

BlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) {
	OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator constructor" << "\033[0m" << endl;

	int currentID = 1;
	BlinkyBlocksWorld *world = NULL;
	buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;

	TiXmlNode *node = xmlDoc->FirstChild("world");
	if (node) {
		TiXmlElement* worldElement = node->ToElement();
		const char *attr= worldElement->Attribute("gridsize");
		int lx,ly,lz;
		if (attr) {
			string str=attr;
			int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
			lx = atoi(str.substr(0,pos1).c_str());
			ly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
			lz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
			OUTPUT << "grid size : " << lx << " x " << ly << " x " << lz << endl;
		} else {
			OUTPUT << "WARNING No grid size in XML file" << endl;
		}
		attr=worldElement->Attribute("windowSize");
		if (attr) {
			string str=attr;
	 		int pos = str.find_first_of(',');
			GlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str());
			GlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
			GlutContext::screenWidth = GlutContext::initialScreenWidth;
			GlutContext::screenHeight = GlutContext::initialScreenHeight;
		}

		createWorld(lx, ly, lz, argc, argv);
		world = getWorld();
		world->loadTextures("../../simulatorCore/blinkyBlocksTextures");

	} else {
		ERRPUT << "ERROR : NO world in XML file" << endl;
		exit(1);
	}

	createScheduler();

	// loading the camera parameters
	TiXmlNode *nodeConfig = node->FirstChild("camera");
	if (nodeConfig) {
		TiXmlElement* cameraElement = nodeConfig->ToElement();
		const char *attr=cameraElement->Attribute("target");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			Vecteur target;
			target.pt[0] = atof(str.substr(0,pos1).c_str());
			target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			world->getCamera()->setTarget(target);
		}
		attr=cameraElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			float az,ele,dist;
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			world->getCamera()->setDirection(az,ele);
			world->getCamera()->setDistance(dist);
		}
		attr=cameraElement->Attribute("angle");
		if (attr) {
			float angle = atof(attr);
			world->getCamera()->setAngle(angle);
		}
		double def_near=1,def_far=1500;
		attr=cameraElement->Attribute("near");
		if (attr) {
			def_near = atof(attr);
		}
		attr=cameraElement->Attribute("far");
		if (attr) {
			def_far = atof(attr);
		}
		world->getCamera()->setNearFar(def_near,def_far);
	}

	// loading the spotlight parameters
	nodeConfig = node->FirstChild("spotlight");
	if (nodeConfig) {
		Vecteur target;
		float az=0,ele=60,dist=1000,angle=50;
		TiXmlElement* lightElement = nodeConfig->ToElement();
		const char *attr=lightElement->Attribute("target");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			target.pt[0] = atof(str.substr(0,pos1).c_str());
			target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("angle");
		if (attr) {
			angle = atof(attr);
		}
		float farplane=2.0*dist*tan(angle*M_PI/180.0);
		world->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane);

	}

	// loading the blocks
	TiXmlNode *nodeBlock = node->FirstChild("blockList");
	if (nodeBlock) {
		Color defaultColor = DARKGREY;
		TiXmlElement* element = nodeBlock->ToElement();
		const char *attr= element->Attribute("color");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			defaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0;
			defaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0;
			defaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0;
		}
		attr= element->Attribute("blocksize");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			float siz[3];
			siz[0] = atof(str.substr(0,pos1).c_str());
			siz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			siz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			OUTPUT << "blocksize =" << siz[0] <<"," << siz[1] <<"," << siz[2]<< endl;
			world->setBlocksSize(siz);
		}

		/* Reading a blinkyblock */
		OUTPUT << "default color :" << defaultColor << endl;
		nodeBlock = nodeBlock->FirstChild("block");
		Vecteur position;
		Color color;
		while (nodeBlock) {
			element = nodeBlock->ToElement();
			color=defaultColor;
			attr = element->Attribute("color");
			if (attr) {
				string str(attr);
				int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
				 color.set(atof(str.substr(0,pos1).c_str())/255.0,
                         atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0,
                         atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0);
				OUTPUT << "color :" << color << endl;
			}
			attr = element->Attribute("position");
			if (attr) {
				string str(attr);
				int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
				position.pt[0] = atoi(str.substr(0,pos1).c_str());
				position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
				position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
				OUTPUT << "position : " << position << endl;
			}
			world->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color);
			nodeBlock = nodeBlock->NextSibling("block");
		} // end while (nodeBlock)
	} else { // end if(nodeBlock)
		ERRPUT << "no Block List" << endl;
	}

	// loading the scenario
	TiXmlNode *nodeScenario = node->FirstChild("scenario");
	if (nodeScenario) {
		bool autostart=false;
		TiXmlElement* element = nodeScenario->ToElement();
		const char *attr= element->Attribute("autostart");
		if (attr) {
			string str(attr);
			autostart=(str=="True" || str=="true");
		}
		OUTPUT << "SCENARIO: Autostart=" << autostart << endl;
		/* Reading an event */
		nodeScenario = nodeScenario->FirstChild("event");
		float eventTime =0.0;
		int eventBlockId=-1;
		while (nodeScenario) {
			element = nodeScenario->ToElement();
			attr = element->Attribute("time");
			if (attr) {
				eventTime = atof(attr);
			}
			attr = element->Attribute("type");
			if (attr) {
				string strAttr(attr);
				if (strAttr=="tap") {
					attr = element->Attribute("id");
					eventBlockId=-1;
					if (attr) {
						eventBlockId=atoi(attr);
					}
					if (eventBlockId==-1) {
						ERRPUT << "SCENARIO:No id for tap event" << endl;
					} else {
						OUTPUT << "SCENARIO: tap(" << eventTime << "," << eventBlockId << ")" << endl;
						world->addScenarioEvent(new ScenarioTappEvent(eventTime,eventBlockId));
					}
				} else if (strAttr=="debug") {
					attr = element->Attribute("id");
					bool open=true;
					if (attr) {
						string str(attr);
						open = (str=="true" || str=="True");
					}
					OUTPUT << "SCENARIO: debug(" << eventTime << "," << open << ")" << endl;
					world->addScenarioEvent(new ScenarioDebugEvent(eventTime,open));
				} else if (strAttr=="selectBlock") {
					attr = element->Attribute("id");
					eventBlockId=-1;
					if (attr) {
						eventBlockId=atoi(attr);
					}
					OUTPUT << "SCENARIO: selectBlock(" << eventTime << "," << eventBlockId << ")" << endl;
					world->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId));
				} else if (strAttr=="addBlock") {
					attr = element->Attribute("position");
					if (attr) {
						string str(attr);
						int pos1 = str.find_first_of(','),
						pos2 = str.find_last_of(',');
						Vecteur position;
						position.pt[0] = atoi(str.substr(0,pos1).c_str());
						position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
						position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
						OUTPUT << "SCENARIO: addBlock(" << eventTime << "," << position << ")" << endl;
						world->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position));
					} else {
						ERRPUT << "SCENARIO: No position for addBlock event" << endl;
					}

				} else {
					ERRPUT << "SCENARIO: event '" << attr << "': unknown !" << endl;
				}

			} else {
				ERRPUT << "SCENARIO: no Event type " << endl;
			}
			nodeScenario = nodeScenario->NextSibling("event");
		} // while(nodeScenario)
	}
	world->linkBlocks();

	//getScheduler()->sem_schedulerStart->post();
	getScheduler()->setState(Scheduler::NOTSTARTED);

	GlutContext::mainLoop();

}

BlinkyBlocksSimulator::~BlinkyBlocksSimulator() {
	OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator destructor" << "\033[0m" <<endl;
}

void BlinkyBlocksSimulator::createSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) {
	simulator =  new BlinkyBlocksSimulator(argc, argv, blinkyBlocksBlockCodeBuildingFunction);
}

void BlinkyBlocksSimulator::deleteSimulator() {
	delete((BlinkyBlocksSimulator*)simulator);
}

} // BlinkyBlocks namespace
<commit_msg>Add some comment reminders to BB files to mark locations needing to be checked for conflicts<commit_after>/*
* blinkyBlocksSimulator.cpp
*
*  Created on: 23 mars 2013
*      Author: dom
*/

#include <iostream>
#include "blinkyBlocksSimulator.h"
#include <string.h>
#include "trace.h"

using namespace std;

namespace BlinkyBlocks {

BlinkyBlocksBlockCode*(* BlinkyBlocksSimulator::buildNewBlockCode)(BlinkyBlocksBlock*)=NULL;

BlinkyBlocksSimulator::BlinkyBlocksSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) : BaseSimulator::Simulator(argc, argv) {
	OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator constructor" << "\033[0m" << endl;

	int currentID = 1;
	BlinkyBlocksWorld *world = NULL;
	buildNewBlockCode = blinkyBlocksBlockCodeBuildingFunction;

    // PThy: Reading the command line may be needed at this time to enable debugging.

	TiXmlNode *node = xmlDoc->FirstChild("world");
    if (node) {
		TiXmlElement* worldElement = node->ToElement();
		const char *attr= worldElement->Attribute("gridsize");
		int lx,ly,lz;
		if (attr) {
			string str=attr;
			int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
			lx = atoi(str.substr(0,pos1).c_str());
			ly = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
			lz = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
			OUTPUT << "grid size : " << lx << " x " << ly << " x " << lz << endl;
		} else {
			OUTPUT << "WARNING No grid size in XML file" << endl;
		}
		attr=worldElement->Attribute("windowSize");
		if (attr) {
			string str=attr;
	 		int pos = str.find_first_of(',');
			GlutContext::initialScreenWidth = atoi(str.substr(0,pos).c_str());
			GlutContext::initialScreenHeight = atoi(str.substr(pos+1,str.length()-pos-1).c_str());
			GlutContext::screenWidth = GlutContext::initialScreenWidth;
			GlutContext::screenHeight = GlutContext::initialScreenHeight;
		}

		createWorld(lx, ly, lz, argc, argv);
		world = getWorld();
		world->loadTextures("../../simulatorCore/blinkyBlocksTextures");

	} else {
		ERRPUT << "ERROR : NO world in XML file" << endl;
		exit(1);
	}

	createScheduler();

    // Pthy: Not sure if we should be keeping that debugging part, perhaps it has to be located somewhere else now that MeldInterpreter has been embedded into VSim
//    if(debugging) {
//		createDebugger();
//	}

	// loading the camera parameters
	TiXmlNode *nodeConfig = node->FirstChild("camera");
	if (nodeConfig) {
		TiXmlElement* cameraElement = nodeConfig->ToElement();
		const char *attr=cameraElement->Attribute("target");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			Vecteur target;
			target.pt[0] = atof(str.substr(0,pos1).c_str());
			target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			world->getCamera()->setTarget(target);
		}
		attr=cameraElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			float az,ele,dist;
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			world->getCamera()->setDirection(az,ele);
			world->getCamera()->setDistance(dist);
		}
		attr=cameraElement->Attribute("angle");
		if (attr) {
			float angle = atof(attr);
			world->getCamera()->setAngle(angle);
		}
		double def_near=1,def_far=1500;
		attr=cameraElement->Attribute("near");
		if (attr) {
			def_near = atof(attr);
		}
		attr=cameraElement->Attribute("far");
		if (attr) {
			def_far = atof(attr);
		}
		world->getCamera()->setNearFar(def_near,def_far);
	}

	// loading the spotlight parameters
	nodeConfig = node->FirstChild("spotlight");
	if (nodeConfig) {
		Vecteur target;
		float az=0,ele=60,dist=1000,angle=50;
		TiXmlElement* lightElement = nodeConfig->ToElement();
		const char *attr=lightElement->Attribute("target");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			target.pt[0] = atof(str.substr(0,pos1).c_str());
			target.pt[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			target.pt[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("directionSpherical");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			az = -90.0+atof(str.substr(0,pos1).c_str());
			ele = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			dist = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
		}
		attr=lightElement->Attribute("angle");
		if (attr) {
			angle = atof(attr);
		}
		float farplane=2.0*dist*tan(angle*M_PI/180.0);
		world->getCamera()->setLightParameters(target,az,ele,dist,angle,10.0,farplane);

	}

	// loading the blocks
	TiXmlNode *nodeBlock = node->FirstChild("blockList");
	if (nodeBlock) {
		Color defaultColor = DARKGREY;
		TiXmlElement* element = nodeBlock->ToElement();
		const char *attr= element->Attribute("color");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			defaultColor.rgba[0] = atof(str.substr(0,pos1).c_str())/255.0;
			defaultColor.rgba[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0;
			defaultColor.rgba[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0;
		}
		attr= element->Attribute("blocksize");
		if (attr) {
			string str(attr);
			int pos1 = str.find_first_of(','),
			pos2 = str.find_last_of(',');
			float siz[3];
			siz[0] = atof(str.substr(0,pos1).c_str());
			siz[1] = atof(str.substr(pos1+1,pos2-pos1-1).c_str());
			siz[2] = atof(str.substr(pos2+1,str.length()-pos1-1).c_str());
			OUTPUT << "blocksize =" << siz[0] <<"," << siz[1] <<"," << siz[2]<< endl;
			world->setBlocksSize(siz);
		}

		/* Reading a blinkyblock */
		OUTPUT << "default color :" << defaultColor << endl;
		nodeBlock = nodeBlock->FirstChild("block");
		Vecteur position;
		Color color;
		while (nodeBlock) {
			element = nodeBlock->ToElement();
			color=defaultColor;
			attr = element->Attribute("color");
			if (attr) {
				string str(attr);
				int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
				 color.set(atof(str.substr(0,pos1).c_str())/255.0,
                         atof(str.substr(pos1+1,pos2-pos1-1).c_str())/255.0,
                         atof(str.substr(pos2+1,str.length()-pos1-1).c_str())/255.0);
				OUTPUT << "color :" << color << endl;
			}
			attr = element->Attribute("position");
			if (attr) {
				string str(attr);
				int pos1 = str.find_first_of(','),
				pos2 = str.find_last_of(',');
				position.pt[0] = atoi(str.substr(0,pos1).c_str());
				position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
				position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
				OUTPUT << "position : " << position << endl;
			}
			world->addBlock(currentID++, BlinkyBlocksSimulator::buildNewBlockCode, position, color);
			nodeBlock = nodeBlock->NextSibling("block");
		} // end while (nodeBlock)
	} else { // end if(nodeBlock)
		ERRPUT << "no Block List" << endl;
	}

	// loading the scenario
	TiXmlNode *nodeScenario = node->FirstChild("scenario");
	if (nodeScenario) {
		bool autostart=false;
		TiXmlElement* element = nodeScenario->ToElement();
		const char *attr= element->Attribute("autostart");
		if (attr) {
			string str(attr);
			autostart=(str=="True" || str=="true");
		}
		OUTPUT << "SCENARIO: Autostart=" << autostart << endl;
		/* Reading an event */
		nodeScenario = nodeScenario->FirstChild("event");
		float eventTime =0.0;
		int eventBlockId=-1;
		while (nodeScenario) {
			element = nodeScenario->ToElement();
			attr = element->Attribute("time");
			if (attr) {
				eventTime = atof(attr);
			}
			attr = element->Attribute("type");
			if (attr) {
				string strAttr(attr);
				if (strAttr=="tap") {
					attr = element->Attribute("id");
					eventBlockId=-1;
					if (attr) {
						eventBlockId=atoi(attr);
					}
					if (eventBlockId==-1) {
						ERRPUT << "SCENARIO:No id for tap event" << endl;
					} else {
						OUTPUT << "SCENARIO: tap(" << eventTime << "," << eventBlockId << ")" << endl;
						world->addScenarioEvent(new ScenarioTappEvent(eventTime,eventBlockId));
					}
				} else if (strAttr=="debug") {
					attr = element->Attribute("id");
					bool open=true;
					if (attr) {
						string str(attr);
						open = (str=="true" || str=="True");
					}
					OUTPUT << "SCENARIO: debug(" << eventTime << "," << open << ")" << endl;
					world->addScenarioEvent(new ScenarioDebugEvent(eventTime,open));
				} else if (strAttr=="selectBlock") {
					attr = element->Attribute("id");
					eventBlockId=-1;
					if (attr) {
						eventBlockId=atoi(attr);
					}
					OUTPUT << "SCENARIO: selectBlock(" << eventTime << "," << eventBlockId << ")" << endl;
					world->addScenarioEvent(new ScenarioSelectBlockEvent(eventTime,eventBlockId));
				} else if (strAttr=="addBlock") {
					attr = element->Attribute("position");
					if (attr) {
						string str(attr);
						int pos1 = str.find_first_of(','),
						pos2 = str.find_last_of(',');
						Vecteur position;
						position.pt[0] = atoi(str.substr(0,pos1).c_str());
						position.pt[1] = atoi(str.substr(pos1+1,pos2-pos1-1).c_str());
						position.pt[2] = atoi(str.substr(pos2+1,str.length()-pos1-1).c_str());
						OUTPUT << "SCENARIO: addBlock(" << eventTime << "," << position << ")" << endl;
						world->addScenarioEvent(new ScenarioAddBlockEvent(eventTime,position));
					} else {
						ERRPUT << "SCENARIO: No position for addBlock event" << endl;
					}

				} else {
					ERRPUT << "SCENARIO: event '" << attr << "': unknown !" << endl;
				}

			} else {
				ERRPUT << "SCENARIO: no Event type " << endl;
			}
			nodeScenario = nodeScenario->NextSibling("event");
		} // while(nodeScenario)
	}
	world->linkBlocks();

	//getScheduler()->sem_schedulerStart->post();
	getScheduler()->setState(Scheduler::NOTSTARTED);

	GlutContext::mainLoop();

}

BlinkyBlocksSimulator::~BlinkyBlocksSimulator() {
	OUTPUT << "\033[1;34m" << "BlinkyBlocksSimulator destructor" << "\033[0m" <<endl;
}

void BlinkyBlocksSimulator::createSimulator(int argc, char *argv[], BlinkyBlocksBlockCode *(*blinkyBlocksBlockCodeBuildingFunction)(BlinkyBlocksBlock*)) {
	simulator =  new BlinkyBlocksSimulator(argc, argv, blinkyBlocksBlockCodeBuildingFunction);
}

void BlinkyBlocksSimulator::deleteSimulator() {
	delete((BlinkyBlocksSimulator*)simulator);
}

} // BlinkyBlocks namespace
<|endoftext|>


<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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.
==============================================================================*/

#include "tensorflow/core/tpu/tpu_embedding_optimization_parameters_utils.h"
#include "tensorflow/core/lib/core/errors.h"

namespace tensorflow {
namespace tpu {

string GetOptimizationAlgorithmName(OptimizationAlgorithm alg) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      return "Adagrad";
    case OptimizationAlgorithm::kStochasticGradientDescent:
      return "StochasticGradientDescent";
    case OptimizationAlgorithm::kFtrl:
      return "FTRL";
    case OptimizationAlgorithm::kAdam:
      return "ADAM";
    case OptimizationAlgorithm::kMomentum:
      return "Momentum";
    case OptimizationAlgorithm::kRmsProp:
      return "RMSProp";
    case OptimizationAlgorithm::kCenteredRmsProp:
      return "CenteredRMSProp";
    case OptimizationAlgorithm::kMdlAdagradLight:
      return "MDLAdagradLight";
    case OptimizationAlgorithm::kAdadelta:
      return "Adadelta";
    case OptimizationAlgorithm::kProximalAdagrad:
      return "ProximalAdagrad";
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return "*** Not set ***";
  }
}

string GetOptimizationAlgorithmFriendlyName(OptimizationAlgorithm alg) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      return "Adagrad";
    case OptimizationAlgorithm::kStochasticGradientDescent:
      return "stochastic gradient descent";
    case OptimizationAlgorithm::kFtrl:
      return "FTRL";
    case OptimizationAlgorithm::kAdam:
      return "ADAM";
    case OptimizationAlgorithm::kMomentum:
      return "Momentum";
    case OptimizationAlgorithm::kRmsProp:
      return "RMSProp";
    case OptimizationAlgorithm::kCenteredRmsProp:
      return "centered RMSProp";
    case OptimizationAlgorithm::kMdlAdagradLight:
      return "MDL Adagrad Light";
    case OptimizationAlgorithm::kAdadelta:
      return "Adadelta";
    case OptimizationAlgorithm::kProximalAdagrad:
      return "proximal Adagrad";
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return "unknown (not specified)";
  }
}

// Returns the number of optimization parameter vectors used by the optimization
// algorithm, excluding the weights themselves and assuming no gradient
// accumulation.
Status GetBaseAuxiliaryParameterCount(OptimizationAlgorithm alg, int* count) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::kStochasticGradientDescent:
      *count = 0;
      return Status::OK();
    case OptimizationAlgorithm::kFtrl:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kAdam:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kMomentum:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::kRmsProp:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kCenteredRmsProp:
      *count = 3;
      return Status::OK();
    case OptimizationAlgorithm::kMdlAdagradLight:
      *count = 3;
      return Status::OK();
    case OptimizationAlgorithm::kAdadelta:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kProximalAdagrad:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return errors::InvalidArgument("No optimization algorithm specified");
  }
}

Status GetGradientAccumulationSupport(OptimizationAlgorithm alg,
                                      GradientAccumulationSupport* support) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      *support = GradientAccumulationSupport::kSupported;
      return Status::OK();
    case OptimizationAlgorithm::kStochasticGradientDescent:
      *support = GradientAccumulationSupport::kUnnecessary;
      return Status::OK();
    default: {
      int auxiliary_parameter_count;
      TF_RETURN_IF_ERROR(
          GetBaseAuxiliaryParameterCount(alg, &auxiliary_parameter_count));
      *support = auxiliary_parameter_count + 1 <= kMaxAuxiliaryParameterCount
                     ? GradientAccumulationSupport::kSupported
                     : GradientAccumulationSupport::kNotSupported;
      return Status::OK();
    }
  }
}
namespace {
// Make a normal state variable specification. Please refer to
// //tensorflow/core/protobuf/tpu/optimization_parameters.proto
// (StateVariableSpecification message) for instructions on how to set the
// padding_initial_value field.
StateVariableSpecification MakeStandardStateVariableSpecification(
    const string& name, double padding_initial_value) {
  StateVariableSpecification result;
  result.set_name(name);
  result.mutable_user_defined()->set_padding_initial_value(
      padding_initial_value);
  return result;
}
}  // namespace

Status GetOptimizationAlgorithmStateVariables(
    OptimizationAlgorithm alg, bool use_gradient_accumulation,
    std::vector<StateVariableSpecification>* state_variables) {
  // The first parameter set is always the weights themselves.
  state_variables->push_back(
      MakeStandardStateVariableSpecification("parameters", 0.0));
  // The order of the returned parameters needs to match the offsets used by
  // the algorithm implementations in test_util.cc and
  // address_handler_program_creator.cc.
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      break;
    }
    case OptimizationAlgorithm::kStochasticGradientDescent: {
      // None.
      break;
    }
    case OptimizationAlgorithm::kFtrl: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("linears", 0.0));
      break;
    }
    case OptimizationAlgorithm::kAdam: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("momenta", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("velocities", 0.0));
      break;
    }
    case OptimizationAlgorithm::kMomentum: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("momenta", 0.0));
      break;
    }
    case OptimizationAlgorithm::kRmsProp: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("ms", 1.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mom", 0.0));
      break;
    }
    case OptimizationAlgorithm::kCenteredRmsProp: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("ms", 1.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mom", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mg", 0.0));
      break;
    }
    case OptimizationAlgorithm::kMdlAdagradLight: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("weights", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("benefits", 0.0));
      break;
    }
    case OptimizationAlgorithm::kAdadelta: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("updates", 0.0));
      break;
    }
    case OptimizationAlgorithm::kProximalAdagrad: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      break;
    }
    case OptimizationAlgorithm::PARAMETERS_NOT_SET: {
      return errors::InvalidArgument("No optimization algorithm specified");
    }
  }
  // This needs to be last so that the save/restore ops do not need to know
  // about gradient accumulation.
  if (use_gradient_accumulation) {
    StateVariableSpecification gradient_acc;
    gradient_acc.set_name("gradient_accumulators");
    gradient_acc.mutable_fill_with_constant()->set_initial_value(
        kGradientAccumulatorInitialValue);
    state_variables->push_back(std::move(gradient_acc));
  }
  if (state_variables->size() > kMaxAuxiliaryParameterCount + 1) {
    return errors::InvalidArgument(
        "Optimization algorithm", GetOptimizationAlgorithmName(alg),
        "does not support gradient accumulation because it "
        "already has too many other accumulators");
  }
  return Status::OK();
}  // namespace tpu

std::vector<OptimizationAlgorithm> GetOptimizationAlgorithms() {
  return {
      OptimizationAlgorithm::kAdagrad,
      OptimizationAlgorithm::kStochasticGradientDescent,
      OptimizationAlgorithm::kFtrl,
      OptimizationAlgorithm::kAdam,
      OptimizationAlgorithm::kMomentum,
      OptimizationAlgorithm::kRmsProp,
      OptimizationAlgorithm::kCenteredRmsProp,
      OptimizationAlgorithm::kMdlAdagradLight,
      OptimizationAlgorithm::kAdadelta,
      OptimizationAlgorithm::kProximalAdagrad,
  };
}

}  // namespace tpu
}  // namespace tensorflow
<commit_msg>Fixed the warning in the file<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.

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.
==============================================================================*/

#include "tensorflow/core/tpu/tpu_embedding_optimization_parameters_utils.h"
#include "tensorflow/core/lib/core/errors.h"

namespace tensorflow {
namespace tpu {

string GetOptimizationAlgorithmName(OptimizationAlgorithm alg) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      return "Adagrad";
    case OptimizationAlgorithm::kStochasticGradientDescent:
      return "StochasticGradientDescent";
    case OptimizationAlgorithm::kFtrl:
      return "FTRL";
    case OptimizationAlgorithm::kAdam:
      return "ADAM";
    case OptimizationAlgorithm::kMomentum:
      return "Momentum";
    case OptimizationAlgorithm::kRmsProp:
      return "RMSProp";
    case OptimizationAlgorithm::kCenteredRmsProp:
      return "CenteredRMSProp";
    case OptimizationAlgorithm::kMdlAdagradLight:
      return "MDLAdagradLight";
    case OptimizationAlgorithm::kAdadelta:
      return "Adadelta";
    case OptimizationAlgorithm::kProximalAdagrad:
      return "ProximalAdagrad";
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return "*** Not set ***";
  }
  return "*** Not set ***";
}

string GetOptimizationAlgorithmFriendlyName(OptimizationAlgorithm alg) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      return "Adagrad";
    case OptimizationAlgorithm::kStochasticGradientDescent:
      return "stochastic gradient descent";
    case OptimizationAlgorithm::kFtrl:
      return "FTRL";
    case OptimizationAlgorithm::kAdam:
      return "ADAM";
    case OptimizationAlgorithm::kMomentum:
      return "Momentum";
    case OptimizationAlgorithm::kRmsProp:
      return "RMSProp";
    case OptimizationAlgorithm::kCenteredRmsProp:
      return "centered RMSProp";
    case OptimizationAlgorithm::kMdlAdagradLight:
      return "MDL Adagrad Light";
    case OptimizationAlgorithm::kAdadelta:
      return "Adadelta";
    case OptimizationAlgorithm::kProximalAdagrad:
      return "proximal Adagrad";
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return "unknown (not specified)";
  }
  return "unknown (not specified)";
}

// Returns the number of optimization parameter vectors used by the optimization
// algorithm, excluding the weights themselves and assuming no gradient
// accumulation.
Status GetBaseAuxiliaryParameterCount(OptimizationAlgorithm alg, int* count) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::kStochasticGradientDescent:
      *count = 0;
      return Status::OK();
    case OptimizationAlgorithm::kFtrl:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kAdam:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kMomentum:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::kRmsProp:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kCenteredRmsProp:
      *count = 3;
      return Status::OK();
    case OptimizationAlgorithm::kMdlAdagradLight:
      *count = 3;
      return Status::OK();
    case OptimizationAlgorithm::kAdadelta:
      *count = 2;
      return Status::OK();
    case OptimizationAlgorithm::kProximalAdagrad:
      *count = 1;
      return Status::OK();
    case OptimizationAlgorithm::PARAMETERS_NOT_SET:
      return errors::InvalidArgument("No optimization algorithm specified");
  }
  return errors::InvalidArgument("No optimization algorithm specified");
}

Status GetGradientAccumulationSupport(OptimizationAlgorithm alg,
                                      GradientAccumulationSupport* support) {
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad:
      *support = GradientAccumulationSupport::kSupported;
      return Status::OK();
    case OptimizationAlgorithm::kStochasticGradientDescent:
      *support = GradientAccumulationSupport::kUnnecessary;
      return Status::OK();
    default: {
      int auxiliary_parameter_count;
      TF_RETURN_IF_ERROR(
          GetBaseAuxiliaryParameterCount(alg, &auxiliary_parameter_count));
      *support = auxiliary_parameter_count + 1 <= kMaxAuxiliaryParameterCount
                     ? GradientAccumulationSupport::kSupported
                     : GradientAccumulationSupport::kNotSupported;
      return Status::OK();
    }
  }
}
namespace {
// Make a normal state variable specification. Please refer to
// //tensorflow/core/protobuf/tpu/optimization_parameters.proto
// (StateVariableSpecification message) for instructions on how to set the
// padding_initial_value field.
StateVariableSpecification MakeStandardStateVariableSpecification(
    const string& name, double padding_initial_value) {
  StateVariableSpecification result;
  result.set_name(name);
  result.mutable_user_defined()->set_padding_initial_value(
      padding_initial_value);
  return result;
}
}  // namespace

Status GetOptimizationAlgorithmStateVariables(
    OptimizationAlgorithm alg, bool use_gradient_accumulation,
    std::vector<StateVariableSpecification>* state_variables) {
  // The first parameter set is always the weights themselves.
  state_variables->push_back(
      MakeStandardStateVariableSpecification("parameters", 0.0));
  // The order of the returned parameters needs to match the offsets used by
  // the algorithm implementations in test_util.cc and
  // address_handler_program_creator.cc.
  switch (alg) {
    case OptimizationAlgorithm::kAdagrad: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      break;
    }
    case OptimizationAlgorithm::kStochasticGradientDescent: {
      // None.
      break;
    }
    case OptimizationAlgorithm::kFtrl: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("linears", 0.0));
      break;
    }
    case OptimizationAlgorithm::kAdam: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("momenta", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("velocities", 0.0));
      break;
    }
    case OptimizationAlgorithm::kMomentum: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("momenta", 0.0));
      break;
    }
    case OptimizationAlgorithm::kRmsProp: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("ms", 1.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mom", 0.0));
      break;
    }
    case OptimizationAlgorithm::kCenteredRmsProp: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("ms", 1.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mom", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("mg", 0.0));
      break;
    }
    case OptimizationAlgorithm::kMdlAdagradLight: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("weights", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("benefits", 0.0));
      break;
    }
    case OptimizationAlgorithm::kAdadelta: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.0));
      state_variables->push_back(
          MakeStandardStateVariableSpecification("updates", 0.0));
      break;
    }
    case OptimizationAlgorithm::kProximalAdagrad: {
      state_variables->push_back(
          MakeStandardStateVariableSpecification("accumulators", 0.1));
      break;
    }
    case OptimizationAlgorithm::PARAMETERS_NOT_SET: {
      return errors::InvalidArgument("No optimization algorithm specified");
    }
  }
  // This needs to be last so that the save/restore ops do not need to know
  // about gradient accumulation.
  if (use_gradient_accumulation) {
    StateVariableSpecification gradient_acc;
    gradient_acc.set_name("gradient_accumulators");
    gradient_acc.mutable_fill_with_constant()->set_initial_value(
        kGradientAccumulatorInitialValue);
    state_variables->push_back(std::move(gradient_acc));
  }
  if (state_variables->size() > kMaxAuxiliaryParameterCount + 1) {
    return errors::InvalidArgument(
        "Optimization algorithm", GetOptimizationAlgorithmName(alg),
        "does not support gradient accumulation because it "
        "already has too many other accumulators");
  }
  return Status::OK();
}  // namespace tpu

std::vector<OptimizationAlgorithm> GetOptimizationAlgorithms() {
  return {
      OptimizationAlgorithm::kAdagrad,
      OptimizationAlgorithm::kStochasticGradientDescent,
      OptimizationAlgorithm::kFtrl,
      OptimizationAlgorithm::kAdam,
      OptimizationAlgorithm::kMomentum,
      OptimizationAlgorithm::kRmsProp,
      OptimizationAlgorithm::kCenteredRmsProp,
      OptimizationAlgorithm::kMdlAdagradLight,
      OptimizationAlgorithm::kAdadelta,
      OptimizationAlgorithm::kProximalAdagrad,
  };
}

}  // namespace tpu
}  // namespace tensorflow
<|endoftext|>


<commit_before>#include "stan/math/functions/rising_factorial.hpp"
#include <gtest/gtest.h>

TEST(MathFunctions, rising_factorial) {
  using stan::math::rising_factorial;

  EXPECT_FLOAT_EQ(120, rising_factorial(4.0,3));
  EXPECT_FLOAT_EQ(360, rising_factorial(3.0,4));
  EXPECT_THROW(rising_factorial(-1, 4),std::domain_error);
}
<commit_msg>added NaN test for rising_factorial<commit_after>#include <stan/math/functions/rising_factorial.hpp>
#include <boost/math/special_functions/fpclassify.hpp>
#include <gtest/gtest.h>

TEST(MathFunctions, rising_factorial) {
  using stan::math::rising_factorial;

  EXPECT_FLOAT_EQ(120, rising_factorial(4.0,3));
  EXPECT_FLOAT_EQ(360, rising_factorial(3.0,4));
  EXPECT_THROW(rising_factorial(-1, 4),std::domain_error);
}

TEST(MathFunctions, rising_factorial_nan) {
  double nan = std::numeric_limits<double>::quiet_NaN();

  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::rising_factorial(4.0, nan));
  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::rising_factorial(nan, 3.0));
  EXPECT_PRED1(boost::math::isnan<double>,
               stan::math::rising_factorial(nan, nan));
}
<|endoftext|>