<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
//
// Demo code about how to impose 3D position and/or 3D rotation to a rigid body
// with functions of time
//
// =============================================================================

#include "chrono/physics/ChBodyEasy.h"
#include "chrono/physics/ChLinkMotorRotationSpeed.h"
#include "chrono/physics/ChLinkTrajectory.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/geometry/ChLineBspline.h"

#include "chrono_irrlicht/ChIrrApp.h"

#include "chrono/motion_functions/ChFunctionPosition_line.h"
#include "chrono/motion_functions/ChFunctionPosition_XYZfunctions.h"
#include "chrono/motion_functions/ChFunctionPosition_setpoint.h"
#include "chrono/motion_functions/ChFunctionRotation_spline.h"
#include "chrono/motion_functions/ChFunctionRotation_ABCfunctions.h"
#include "chrono/motion_functions/ChFunctionRotation_setpoint.h"
#include "chrono/motion_functions/ChFunctionRotation_axis.h"

#include "chrono/physics/ChLinkMotionImposed.h"

// Use the namespace of Chrono
using namespace chrono;
using namespace chrono::geometry;
using namespace chrono::irrlicht;

// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;

int main(int argc, char* argv[]) {
    GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";

    // Create a Chrono::Engine physical system
    ChSystemNSC mphysicalSystem;

	// Create a floor. This is an absolute fixed reference that we will use as
	// a reference for imposing position and rotations of moved bodies.

    auto mfloor = chrono_types::make_shared<ChBodyEasyBox>(3, 0.2, 3, 1000, false, false); // no collide, not shown
    mfloor->SetBodyFixed(true);
    mphysicalSystem.Add(mfloor);

	//
	// EXAMPLE 1
	//
	// In this example we impose position and rotation of a body shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a triplet of X,Y,Z ChFunction objects
	// rotation:  use a fixed axis of rotation and an angle(time) function defined via a ChFunction

	// Create the object to move
    auto mmoved_1 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_1);
    mmoved_1->SetPos(ChVector<>(-0.5, 0, 0));

	// Create a position function p(t) from three x,y,z distinct ChFunction objects,
	// in this case two sine functions on y and z, whereas x remains constant 0 by default.
	auto f_xyz = chrono_types::make_shared<ChFunctionPosition_XYZfunctions>();
	f_xyz->SetFunctionY(chrono_types::make_shared<ChFunction_Sine>(0,0.5,0.5));
	f_xyz->SetFunctionZ(chrono_types::make_shared<ChFunction_Sine>(0,0.5,0.5)); // phase freq ampl

	// Create a rotation function q(t) from a angle(time) rotation with fixed axis:
	auto f_rot_axis = chrono_types::make_shared<ChFunctionRotation_axis>();
	f_rot_axis->SetFunctionAngle(chrono_types::make_shared<ChFunction_Sine>(0,0.15,chrono::CH_C_PI)); // phase freq ampl
	f_rot_axis->SetAxis(ChVector<>(1,1,1).GetNormalized());

	// Create the constraint to impose motion and rotation.
	// Note that the constraint acts by imposing the motion and rotation between
	// frame1 of Body1 (the impose_1 body in this case) and frame2 of Body2 (the floor
	// fixed reference in this case, but it could also be another moving object).
	// We initially set both frame1 and frame2 in the same absolute position, btw in the
	// main reference of the moved mesh, by setting it during the Initialize() method.
	auto impose_1 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_1);
	impose_1->Initialize(mmoved_1, mfloor, ChFrame<>(mmoved_1->GetPos()));
	impose_1->SetPositionFunction(f_xyz);
	impose_1->SetRotationFunction(f_rot_axis);

	//
	// EXAMPLE 2
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a Bspline
	// rotation:  use a quaternion spline.

	// Create the object to move
    auto mmoved_2 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_2);
    mmoved_2->SetPos(ChVector<>(0.5, 0, 0));

	// Create a spline geometry:
    auto mspline = chrono_types::make_shared<ChLineBspline>(
		3,												// spline order
		std::vector<ChVector<>> {						// std::vector with ChVector<> controlpoints
										{  0, 0, 0 },	  // btw.better start from zero displacement if creating frame1&2 in same pos at Initialize()
										{ .3, 0, 0 },
										{ .5, .2, 0 },
										{ .6, .3, 0 },
										{ .5, .5, .1 },
										{  0, .5, .1 }
								}
	);

	// Create a line motion that uses the 3D ChLineBspline above (but in SetLine() you
	// might use also other ChLine objects such as a ChLinePath, a ChLineArc, etc.)
	auto f_line = chrono_types::make_shared<ChFunctionPosition_line>();
	f_line->SetLine(mspline);
	// Note that all ChLine will be evaluated in a 0..1 range, this means that at s=0
	// one gets the start of the line, at s=1 one gets the end. For slower motion, one
	// can use SetSpaceFunction(), here ramping a linear abscissa motion but at 1/5 of the default speed:
	f_line->SetSpaceFunction( chrono_types::make_shared<ChFunction_Ramp>(0, 0.2) );

	// Create a spline rotation interpolation based on quaternion splines.
	// Note that if order=1, the quaternion spline boils down to a simple SLERP interpolation
	auto f_rotspline = chrono_types::make_shared<ChFunctionRotation_spline>(
		1,															// spline order
		std::vector<ChQuaternion<> >{								// std::vector with ChQuaternion<> rot.controlpoints
										{ 1, 0, 0, 0 },
										{ 0, 0, 1, 0 },
										Q_from_AngZ(1.2),
										{ 1, 0, 0, 0 }
									}
	);
	// Optional: avoid default linear evaluation of spline, here use a sigma ramp:
	f_rotspline->SetSpaceFunction( chrono_types::make_shared<ChFunction_Sigma>(1, 0, 4) ); // amp,start,end

	// Create the constraint to impose motion and rotation:
	auto impose_2 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_2);
	impose_2->Initialize(mmoved_2, mfloor, ChFrame<>(mmoved_2->GetPos()));
	impose_2->SetPositionFunction(f_line);
	impose_2->SetRotationFunction(f_rotspline);

    // btw: do you want to visualize the position spline? do this:
    auto mglyphasset = chrono_types::make_shared<ChLineShape>();
    mglyphasset->SetLineGeometry(mspline);
    impose_2->AddAsset(mglyphasset);

	//
	// EXAMPLE 3
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a continuous setpoint (FOH first order hold), ie. a sin(t) set in simulation loop
	// rotation:  use a continuous setpoint (FOH first order hold).

	// Create the object to move
    auto mmoved_3 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_3);
    mmoved_3->SetPos(ChVector<>(1.5, 0, 0));

	// Create the position function: use ChFunctionPosition_setpoint as a proxy to an external continuous setpoint
	auto f_pos_setpoint = chrono_types::make_shared<ChFunctionPosition_setpoint>();

	// Create the rotation function: use ChFunctionPosition_setpoint as a proxy to an external continuous setpoint
	auto f_rot_setpoint = chrono_types::make_shared<ChFunctionRotation_setpoint>();

	// Create the constraint to impose motion and rotation:
	auto impose_3 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_3);
	impose_3->Initialize(mmoved_3, mfloor, ChFrame<>(mmoved_3->GetPos()));
	impose_3->SetPositionFunction(f_pos_setpoint);
	impose_3->SetRotationFunction(f_rot_setpoint);

	//
	// EXAMPLE 4
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  [nothing]
	// rotation:  use three angle functions of time, ie. three ChFunction objects

	// Create the object to move
    auto mmoved_4 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_4);
    mmoved_4->SetPos(ChVector<>(2.5, 0, 0));

	// Create the rotation function: use 3 distinct A,B,C functions of time to set Eulero or Cardano or Rxyz angles:
	auto f_abc_angles = chrono_types::make_shared<ChFunctionRotation_ABCfunctions>();
	f_abc_angles->SetAngleset(AngleSet::RXYZ);
	f_abc_angles->SetFunctionAngleA( chrono_types::make_shared<ChFunction_Sine>(0,2,0.3) ); // phase freq ampl
	f_abc_angles->SetFunctionAngleB( chrono_types::make_shared<ChFunction_Ramp>(0,0.2) ); // a0, da/dt

	// Create the constraint to impose motion and rotation:
	auto impose_4 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_4);
	impose_4->Initialize(mmoved_4, mfloor, ChFrame<>(mmoved_4->GetPos()));
	impose_4->SetRotationFunction(f_abc_angles);

	//
	// VISUALIZATION
	//

	// Create the Irrlicht visualization (open the Irrlicht device,
    // bind a simple user interface, etc. etc.)
    ChIrrApp application(&mphysicalSystem, L"Imposing rotation and position to bodies", core::dimension2d<u32>(800, 600), false, true);

    // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
    application.AddTypicalLogo();
    application.AddTypicalSky();
    application.AddTypicalLights();
    application.AddTypicalCamera(core::vector3df(0, 2, -3));

    // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
    // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes.
    // If you need a finer control on which item really needs a visualization proxy in
    // Irrlicht, just use application.AssetBind(myitem); on a per-item basis.

    application.AssetBindAll();

    // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
    // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!

    application.AssetUpdateAll();

    //
    // THE SOFT-REAL-TIME CYCLE
    //

    application.SetTimestep(0.01);
    application.SetTryRealtime(true);

    while (application.GetDevice()->run()) {
        application.BeginScene();

        application.DrawAll();

        application.DoStep();

		double t = application.GetSystem()->GetChTime();

		if (application.GetSystem()->GetStepcount() % 10 == 0) {
			f_pos_setpoint->SetSetpoint(0.2*ChVector<>(cos(t*12), sin(t*12), 0), t);
			f_rot_setpoint->SetSetpoint(Q_from_AngAxis(t*0.5, VECT_Z), t );
			//GetLog() << "set p = " << f_setpoint->Get_p(t).y() << " at t=" << t  << "\n";
		}
		//GetLog() << "p = " << f_setpoint->Get_p(t).y() << "  p_ds = " << f_setpoint->Get_p_ds(t).y() << "   p_dsds= " << f_setpoint->Get_p_dsds(t).y() << "\n";

        application.EndScene();
    }

    return 0;
}<commit_msg>Test also periodic splines, and periodic rotation interpolation via quaternions splines.<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
//
// Demo code about how to impose 3D position and/or 3D rotation to a rigid body
// with functions of time
//
// =============================================================================

#include "chrono/physics/ChBodyEasy.h"
#include "chrono/physics/ChLinkMotorRotationSpeed.h"
#include "chrono/physics/ChLinkTrajectory.h"
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/geometry/ChLineBspline.h"

#include "chrono_irrlicht/ChIrrApp.h"

#include "chrono/motion_functions/ChFunctionPosition_line.h"
#include "chrono/motion_functions/ChFunctionPosition_XYZfunctions.h"
#include "chrono/motion_functions/ChFunctionPosition_setpoint.h"
#include "chrono/motion_functions/ChFunctionRotation_spline.h"
#include "chrono/motion_functions/ChFunctionRotation_ABCfunctions.h"
#include "chrono/motion_functions/ChFunctionRotation_setpoint.h"
#include "chrono/motion_functions/ChFunctionRotation_axis.h"

#include "chrono/physics/ChLinkMotionImposed.h"

// Use the namespace of Chrono
using namespace chrono;
using namespace chrono::geometry;
using namespace chrono::irrlicht;

// Use the main namespaces of Irrlicht
using namespace irr;
using namespace irr::core;
using namespace irr::scene;
using namespace irr::video;
using namespace irr::io;
using namespace irr::gui;

int main(int argc, char* argv[]) {
    GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";

    // Create a Chrono::Engine physical system
    ChSystemNSC mphysicalSystem;

	// Create a floor. This is an absolute fixed reference that we will use as
	// a reference for imposing position and rotations of moved bodies.

    auto mfloor = chrono_types::make_shared<ChBodyEasyBox>(3, 0.2, 3, 1000, false, false); // no collide, not shown
    mfloor->SetBodyFixed(true);
    mphysicalSystem.Add(mfloor);

	//
	// EXAMPLE 1
	//
	// In this example we impose position and rotation of a body shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a triplet of X,Y,Z ChFunction objects
	// rotation:  use a fixed axis of rotation and an angle(time) function defined via a ChFunction

	// Create the object to move
    auto mmoved_1 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_1);
    mmoved_1->SetPos(ChVector<>(-0.5, 0, 0));

	// Create a position function p(t) from three x,y,z distinct ChFunction objects,
	// in this case two sine functions on y and z, whereas x remains constant 0 by default.
	auto f_xyz = chrono_types::make_shared<ChFunctionPosition_XYZfunctions>();
	f_xyz->SetFunctionY(chrono_types::make_shared<ChFunction_Sine>(0,0.5,0.5));
	f_xyz->SetFunctionZ(chrono_types::make_shared<ChFunction_Sine>(0,0.5,0.5)); // phase freq ampl

	// Create a rotation function q(t) from a angle(time) rotation with fixed axis:
	auto f_rot_axis = chrono_types::make_shared<ChFunctionRotation_axis>();
	f_rot_axis->SetFunctionAngle(chrono_types::make_shared<ChFunction_Sine>(0,0.15,chrono::CH_C_PI)); // phase freq ampl
	f_rot_axis->SetAxis(ChVector<>(1,1,1).GetNormalized());

	// Create the constraint to impose motion and rotation.
	// Note that the constraint acts by imposing the motion and rotation between
	// frame1 of Body1 (the impose_1 body in this case) and frame2 of Body2 (the floor
	// fixed reference in this case, but it could also be another moving object).
	// We initially set both frame1 and frame2 in the same absolute position, btw in the
	// main reference of the moved mesh, by setting it during the Initialize() method.
	auto impose_1 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_1);
	impose_1->Initialize(mmoved_1, mfloor, ChFrame<>(mmoved_1->GetPos()));
	impose_1->SetPositionFunction(f_xyz);
	impose_1->SetRotationFunction(f_rot_axis);

	//
	// EXAMPLE 2
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a Bspline
	// rotation:  use a quaternion spline.

	// Create the object to move
    auto mmoved_2 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_2);
    mmoved_2->SetPos(ChVector<>(0.5, 0, 0));

	// Create a spline geometry:
    auto mspline = chrono_types::make_shared<ChLineBspline>(
		3,												// spline order
		std::vector<ChVector<>> {						// std::vector with ChVector<> controlpoints
										{  0, 0, 0 },	  // btw.better start from zero displacement if creating frame1&2 in same pos at Initialize()
										{ .3, 0, 0 },
										{ .5, .2, 0 },
										{ .6, .3, 0 },
										{ .5, .5, .1 },
										{  0, .5, .1 }
								}
	);
	mspline->SetClosed(true);

	// Create a line motion that uses the 3D ChLineBspline above (but in SetLine() you
	// might use also other ChLine objects such as a ChLinePath, a ChLineArc, etc.)
	auto f_line = chrono_types::make_shared<ChFunctionPosition_line>();
	f_line->SetLine(mspline);
	// Note that all ChLine will be evaluated in a s=0..1 range, this means that at s=0
	// one gets the start of the line, at s=1 one gets the end. For slower motion, one
	// can use SetSpaceFunction(), here ramping a linear abscissa motion but at 1/5 of the default speed
	// i.e.a linear map s=0.2*t between absyssa s and time t
	f_line->SetSpaceFunction( chrono_types::make_shared<ChFunction_Ramp>(0, 0.2) );

	// Create a spline rotation interpolation based on quaternion splines.
	// Note that if order=1, the quaternion spline boils down to a simple SLERP interpolation
	auto f_rotspline = chrono_types::make_shared<ChFunctionRotation_spline>(
		1,															// spline order
		std::vector<ChQuaternion<> >{								// std::vector with ChQuaternion<> rot.controlpoints
										{ 1, 0, 0, 0 },
										{ 0, 0, 1, 0 },
										Q_from_AngZ(1.2),
										{ 0, 1, 0, 0 }
									}
	);
	// This will make the rotation spline evaluation periodic, otherwise by default it extrapolates if beyond s=1
	f_rotspline->SetClosed(true);
	// Make the rotation spline evaluation 1/5 slower using a linear map s=0.2*t between absyssa s and time t
	f_rotspline->SetSpaceFunction( chrono_types::make_shared<ChFunction_Ramp>(0, 0.2) );
	// Another example to test: use a sigma function between s and t:
	// f_rotspline->SetSpaceFunction( chrono_types::make_shared<ChFunction_Sigma>(1, 0, 4) ); // amp,start,end

	// Create the constraint to impose motion and rotation:
	auto impose_2 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_2);
	impose_2->Initialize(mmoved_2, mfloor, ChFrame<>(mmoved_2->GetPos()));
	impose_2->SetPositionFunction(f_line);
	impose_2->SetRotationFunction(f_rotspline);

    // btw: do you want to visualize the position spline? do this:
    auto mglyphasset = chrono_types::make_shared<ChLineShape>();
    mglyphasset->SetLineGeometry(mspline);
    impose_2->AddAsset(mglyphasset);

	// Btw for periodic closed splines, the 1st contr point is not exactly the start of spline,
	// so better move the sample object exactly to beginning:
	mmoved_2->SetPos(f_line->Get_p(0) >> impose_2->GetFrame2() >> impose_2->GetBody2()->GetCoord());

	//
	// EXAMPLE 3
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  use a continuous setpoint (FOH first order hold), ie. a sin(t) set in simulation loop
	// rotation:  use a continuous setpoint (FOH first order hold).

	// Create the object to move
    auto mmoved_3 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_3);
    mmoved_3->SetPos(ChVector<>(1.5, 0, 0));

	// Create the position function: use ChFunctionPosition_setpoint as a proxy to an external continuous setpoint
	auto f_pos_setpoint = chrono_types::make_shared<ChFunctionPosition_setpoint>();

	// Create the rotation function: use ChFunctionPosition_setpoint as a proxy to an external continuous setpoint
	auto f_rot_setpoint = chrono_types::make_shared<ChFunctionRotation_setpoint>();

	// Create the constraint to impose motion and rotation:
	auto impose_3 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_3);
	impose_3->Initialize(mmoved_3, mfloor, ChFrame<>(mmoved_3->GetPos()));
	impose_3->SetPositionFunction(f_pos_setpoint);
	impose_3->SetRotationFunction(f_rot_setpoint);

	//
	// EXAMPLE 4
	//
	//
	// In this example we impose position and rotation of a shape respect to absolute reference,
	// using the following methods:
	//
	// position:  [nothing]
	// rotation:  use three angle functions of time, ie. three ChFunction objects

	// Create the object to move
    auto mmoved_4 = chrono_types::make_shared<ChBodyEasyMesh>(GetChronoDataFile("support.obj"),1000); // mesh file, density
	mphysicalSystem.Add(mmoved_4);
    mmoved_4->SetPos(ChVector<>(2.5, 0, 0));

	// Create the rotation function: use 3 distinct A,B,C functions of time to set Eulero or Cardano or Rxyz angles:
	auto f_abc_angles = chrono_types::make_shared<ChFunctionRotation_ABCfunctions>();
	f_abc_angles->SetAngleset(AngleSet::RXYZ);
	f_abc_angles->SetFunctionAngleA( chrono_types::make_shared<ChFunction_Sine>(0,2,0.3) ); // phase freq ampl
	f_abc_angles->SetFunctionAngleB( chrono_types::make_shared<ChFunction_Ramp>(0,0.2) ); // a0, da/dt

	// Create the constraint to impose motion and rotation:
	auto impose_4 = chrono_types::make_shared<ChLinkMotionImposed>();
	mphysicalSystem.Add(impose_4);
	impose_4->Initialize(mmoved_4, mfloor, ChFrame<>(mmoved_4->GetPos()));
	impose_4->SetRotationFunction(f_abc_angles);

	//
	// VISUALIZATION
	//

	// Create the Irrlicht visualization (open the Irrlicht device,
    // bind a simple user interface, etc. etc.)
    ChIrrApp application(&mphysicalSystem, L"Imposing rotation and position to bodies", core::dimension2d<u32>(800, 600), false, true);

    // Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:
    application.AddTypicalLogo();
    application.AddTypicalSky();
    application.AddTypicalLights();
    application.AddTypicalCamera(core::vector3df(0, 2, -3));

    // ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items
    // in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes.
    // If you need a finer control on which item really needs a visualization proxy in
    // Irrlicht, just use application.AssetBind(myitem); on a per-item basis.

    application.AssetBindAll();

    // ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets
    // that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!

    application.AssetUpdateAll();

    //
    // THE SOFT-REAL-TIME CYCLE
    //

    application.SetTimestep(0.01);
    application.SetTryRealtime(true);

    while (application.GetDevice()->run()) {
        application.BeginScene();

        application.DrawAll();

        application.DoStep();

		double t = application.GetSystem()->GetChTime();

		if (application.GetSystem()->GetStepcount() % 10 == 0) {
			f_pos_setpoint->SetSetpoint(0.2*ChVector<>(cos(t*12), sin(t*12), 0), t);
			f_rot_setpoint->SetSetpoint(Q_from_AngAxis(t*0.5, VECT_Z), t );
			//GetLog() << "set p = " << f_setpoint->Get_p(t).y() << " at t=" << t  << "\n";
		}
		//GetLog() << "p = " << f_setpoint->Get_p(t).y() << "  p_ds = " << f_setpoint->Get_p_ds(t).y() << "   p_dsds= " << f_setpoint->Get_p_dsds(t).y() << "\n";

        application.EndScene();
    }

    return 0;
}<|endoftext|>


<commit_before>#ifndef SILICIUM_THREAD_HPP
#define SILICIUM_THREAD_HPP

#include <silicium/observer.hpp>
#include <silicium/override.hpp>
#include <silicium/config.hpp>
#include <silicium/exchange.hpp>
#include <silicium/yield_context.hpp>
#include <future>
#include <boost/thread/future.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>

namespace Si
{
	namespace detail
	{
		template <class ThreadingAPI>
		struct event : private observer<nothing>
		{
			template <class NothingObservable>
			void block(NothingObservable &&blocked_on)
			{
				assert(!got_something);
				blocked_on.async_get_one(*this);
				typename ThreadingAPI::unique_lock lock(got_something_mutex);
				while (!got_something)
				{
					got_something_set.wait(lock);
				}
				got_something = false;
			}

		private:

			typename ThreadingAPI::mutex got_something_mutex;
			typename ThreadingAPI::condition_variable got_something_set;
			bool got_something = false;

			virtual void got_element(nothing) SILICIUM_OVERRIDE
			{
				wake_get_one();
			}

			virtual void ended() SILICIUM_OVERRIDE
			{
				wake_get_one();
			}

			void wake_get_one()
			{
				typename ThreadingAPI::unique_lock lock(got_something_mutex);
				got_something = true;
				got_something_set.notify_one();
			}
		};
	}

	template <class Element, class ThreadingAPI>
	struct thread_observable
	{
		typedef Element element_type;

		thread_observable()
		{
		}

		template <class Action>
		explicit thread_observable(Action &&action)
			: state(Si::make_unique<state_type>(std::forward<Action>(action)))
		{
		}

#if !SILICIUM_COMPILER_GENERATES_MOVES
		thread_observable(thread_observable &&other) BOOST_NOEXCEPT
			: state(std::move(other.state))
		{
		}

		thread_observable &operator = (thread_observable &&other) BOOST_NOEXCEPT
		{
			state = std::move(other.state);
			return *this;
		}
#endif

		void wait()
		{
			return state->wait();
		}

		void async_get_one(observer<element_type> &receiver)
		{
			return state->async_get_one(receiver);
		}

	private:

		struct state_type : private detail::yield_context_impl<Element>
		{
			template <class Action>
			explicit state_type(Action &&action)
			{
				worker = ThreadingAPI::launch_async([action, this]() mutable
				{
					yield_context<Element> yield(*this);
					(std::forward<Action>(action))(yield);

					typename ThreadingAPI::unique_lock lock(receiver_mutex);
					if (receiver)
					{
						Si::exchange(receiver, nullptr)->ended();
					}
					else
					{
						has_ended = true;
					}
				});
			}

			void async_get_one(observer<Element> &new_receiver)
			{
				typename ThreadingAPI::unique_lock lock(receiver_mutex);
				assert(!receiver);
				if (ready_result)
				{
					Element result = std::move(*ready_result);
					ready_result = boost::none;
					receiver_ready.notify_one();
					lock.unlock();
					new_receiver.got_element(std::move(result));
				}
				else
				{
					if (has_ended)
					{
						return new_receiver.ended();
					}
					receiver = &new_receiver;
					receiver_ready.notify_one();
				}
			}

			void cancel()
			{
				throw std::logic_error("to do");
			}

			void wait()
			{
				worker.get();
			}

		private:

			typename ThreadingAPI::template future<void> worker;
			typename ThreadingAPI::mutex receiver_mutex;
			observer<Element> *receiver = nullptr;
			boost::optional<Element> ready_result;
			typename ThreadingAPI::condition_variable receiver_ready;
			bool has_ended = false;

			detail::event<ThreadingAPI> got_something;

			virtual void push_result(Element result) SILICIUM_OVERRIDE
			{
				typename ThreadingAPI::unique_lock lock(receiver_mutex);
				while (ready_result && !receiver)
				{
					receiver_ready.wait(lock);
				}
				if (receiver)
				{
					auto * const receiver_ = Si::exchange(receiver, nullptr);
					lock.unlock();
					receiver_->got_element(std::move(result));
				}
				else
				{
					ready_result = std::move(result);
				}
			}

			virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE
			{
				got_something.block(target);
			}
		};

		std::unique_ptr<state_type> state;
	};

	template <class Element, class ThreadingAPI, class Action>
	auto make_thread(Action &&action) -> thread_observable<Element, ThreadingAPI>
	{
		return thread_observable<Element, ThreadingAPI>(std::forward<Action>(action));
	}
}

#endif
<commit_msg>release a mutex before notifying about the end of a thread to avoid a crash on destruction<commit_after>#ifndef SILICIUM_THREAD_HPP
#define SILICIUM_THREAD_HPP

#include <silicium/observer.hpp>
#include <silicium/override.hpp>
#include <silicium/config.hpp>
#include <silicium/exchange.hpp>
#include <silicium/yield_context.hpp>
#include <future>
#include <boost/thread/future.hpp>
#include <boost/optional.hpp>
#include <boost/concept_check.hpp>

namespace Si
{
	namespace detail
	{
		template <class ThreadingAPI>
		struct event : private observer<nothing>
		{
			template <class NothingObservable>
			void block(NothingObservable &&blocked_on)
			{
				assert(!got_something);
				blocked_on.async_get_one(*this);
				typename ThreadingAPI::unique_lock lock(got_something_mutex);
				while (!got_something)
				{
					got_something_set.wait(lock);
				}
				got_something = false;
			}

		private:

			typename ThreadingAPI::mutex got_something_mutex;
			typename ThreadingAPI::condition_variable got_something_set;
			bool got_something = false;

			virtual void got_element(nothing) SILICIUM_OVERRIDE
			{
				wake_get_one();
			}

			virtual void ended() SILICIUM_OVERRIDE
			{
				wake_get_one();
			}

			void wake_get_one()
			{
				typename ThreadingAPI::unique_lock lock(got_something_mutex);
				got_something = true;
				got_something_set.notify_one();
			}
		};
	}

	template <class Element, class ThreadingAPI>
	struct thread_observable
	{
		typedef Element element_type;

		thread_observable()
		{
		}

		template <class Action>
		explicit thread_observable(Action &&action)
			: state(Si::make_unique<state_type>(std::forward<Action>(action)))
		{
		}

#if !SILICIUM_COMPILER_GENERATES_MOVES
		thread_observable(thread_observable &&other) BOOST_NOEXCEPT
			: state(std::move(other.state))
		{
		}

		thread_observable &operator = (thread_observable &&other) BOOST_NOEXCEPT
		{
			state = std::move(other.state);
			return *this;
		}
#endif

		void wait()
		{
			return state->wait();
		}

		void async_get_one(observer<element_type> &receiver)
		{
			return state->async_get_one(receiver);
		}

	private:

		struct state_type : private detail::yield_context_impl<Element>
		{
			template <class Action>
			explicit state_type(Action &&action)
			{
				worker = ThreadingAPI::launch_async([action, this]() mutable
				{
					yield_context<Element> yield(*this);
					(std::forward<Action>(action))(yield);

					typename ThreadingAPI::unique_lock lock(receiver_mutex);
					if (receiver)
					{
						auto receiver_ = Si::exchange(receiver, nullptr);
						lock.unlock();
						receiver_->ended();
					}
					else
					{
						has_ended = true;
					}
				});
			}

			void async_get_one(observer<Element> &new_receiver)
			{
				typename ThreadingAPI::unique_lock lock(receiver_mutex);
				assert(!receiver);
				if (ready_result)
				{
					Element result = std::move(*ready_result);
					ready_result = boost::none;
					receiver_ready.notify_one();
					lock.unlock();
					new_receiver.got_element(std::move(result));
				}
				else
				{
					if (has_ended)
					{
						return new_receiver.ended();
					}
					receiver = &new_receiver;
					receiver_ready.notify_one();
				}
			}

			void cancel()
			{
				throw std::logic_error("to do");
			}

			void wait()
			{
				worker.get();
			}

		private:

			typename ThreadingAPI::template future<void> worker;
			typename ThreadingAPI::mutex receiver_mutex;
			observer<Element> *receiver = nullptr;
			boost::optional<Element> ready_result;
			typename ThreadingAPI::condition_variable receiver_ready;
			bool has_ended = false;

			detail::event<ThreadingAPI> got_something;

			virtual void push_result(Element result) SILICIUM_OVERRIDE
			{
				typename ThreadingAPI::unique_lock lock(receiver_mutex);
				while (ready_result && !receiver)
				{
					receiver_ready.wait(lock);
				}
				if (receiver)
				{
					auto * const receiver_ = Si::exchange(receiver, nullptr);
					lock.unlock();
					receiver_->got_element(std::move(result));
				}
				else
				{
					ready_result = std::move(result);
				}
			}

			virtual void get_one(observable<nothing> &target) SILICIUM_OVERRIDE
			{
				got_something.block(target);
			}
		};

		std::unique_ptr<state_type> state;
	};

	template <class Element, class ThreadingAPI, class Action>
	auto make_thread(Action &&action) -> thread_observable<Element, ThreadingAPI>
	{
		return thread_observable<Element, ThreadingAPI>(std::forward<Action>(action));
	}
}

#endif
<|endoftext|>


<commit_before>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef DG_DIAGNOSE
#include "diagnose/dg.h"
#endif

#include "n_srm.h"
#include "srm2api.h"
#include "srm_soap27.h"

#include "constants.h"
#include "i18.h"
#include "sysdep.h"             /* BOOL, STD_BUF, ... */

#include "free.h"               /* FREE(), DELETE() */
#include "str.h"		/* dq_param() */

#include <iostream>             /* std::string, cout, endl, ... */
#include <sstream>              /* ostringstream */

using namespace std;

/*
 * srmGetPermission request constuctor
 */
srmGetPermission::srmGetPermission()
{
  init();
}

/*
 * Initialise srmGetPermission request
 */
void
srmGetPermission::init()
{
  /* request (parser/API) */

  /* response (parser) */
  permissionArray = NULL;
}

/*
 * srmGetPermission request copy constuctor
 */
srmGetPermission::srmGetPermission(Node &node)
{
  init();
  Node::init(node);
}

/*
 * srmGetPermission request destructor
 */
srmGetPermission::~srmGetPermission()
{
  DM_DBG_I;

  /* request (parser/API) */
  DELETE_VEC(SURL);
  DELETE_VEC(storageSystemInfo.key);
  DELETE_VEC(storageSystemInfo.value);

  /* response (parser) */
  DELETE(permissionArray);

  DM_DBG_O;
}

/*
 * Free process-related structures.
 */
void
srmGetPermission::finish(Process *proc)
{
  DM_DBG_I;

  FREE_SRM_RET(GetPermission);
}

int
srmGetPermission::exec(Process *proc)
{
#define EVAL_VEC_STR_GP(vec) vec = proc->eval_vec_str(srmGetPermission::vec)
  DM_DBG_I;

  std::vector <std::string *> SURL;
  tStorageSystemInfo storageSystemInfo;

  EVAL_VEC_STR_GP(SURL);
  EVAL_VEC_STR_GP(storageSystemInfo.key);
  EVAL_VEC_STR_GP(storageSystemInfo.value);

#ifdef SRM2_CALL
  NEW_SRM_RET(GetPermission);

  GetPermission(
    soap,
    EVAL2CSTR(srm_endpoint),
    EVAL2CSTR(authorizationID),
    SURL,
    storageSystemInfo,
    resp
  );
#endif

  DELETE_VEC(SURL);
  DELETE_VEC(storageSystemInfo.key);
  DELETE_VEC(storageSystemInfo.value);

  /* matching */
  if(!resp || !resp->srmGetPermissionResponse) {
    DM_LOG(DM_N(1), "no SRM response\n");
    RETURN(ERR_ERR);
  }

  /* arrayOfPathDetails */
  EAT_MATCH(permissionArray, arrayOfFilePermissionToString(proc, FALSE, FALSE).c_str());

  RETURN(matchReturnStatus(resp->srmGetPermissionResponse->returnStatus, proc));
#undef EVAL_VEC_STR_GP
}

std::string
srmGetPermission::toString(Process *proc)
{
#define EVAL_VEC_STR_GP(vec) EVAL_VEC_STR(srmGetPermission,vec)
  DM_DBG_I;

  GET_SRM_RESP(GetPermission);
  BOOL quote = TRUE;
  std::stringstream ss;

  std::vector <std::string *> SURL;
  tStorageSystemInfo_ storageSystemInfo;

  EVAL_VEC_STR_GP(SURL);
  EVAL_VEC_STR_GP(storageSystemInfo.key);
  EVAL_VEC_STR_GP(storageSystemInfo.value);

  /* request */
  SS_SRM("srmGetPermission");
  SS_P_DQ(authorizationID);
  SS_VEC_DEL(SURL);
  SS_VEC_DEL(storageSystemInfo.key);
  SS_VEC_DEL(storageSystemInfo.value);

  /* response (parser) */
  SS_P_DQ(permissionArray);
  SS_P_DQ(returnStatus.explanation);
  SS_P_DQ(returnStatus.statusCode);

  /* response (API) */
  if(!resp || !resp->srmGetPermissionResponse) RETURN(ss.str());

  ss << arrayOfFilePermissionToString(proc, TRUE, quote);

  SS_P_SRM_RETSTAT(resp->srmGetPermissionResponse);

  RETURN(ss.str());
#undef EVAL_VEC_STR_GP
}

std::string
srmGetPermission::arrayOfFilePermissionToString(Process *proc, BOOL space, BOOL quote) const
{
  DM_DBG_I;

  GET_SRM_RESP(GetPermission);
  std::stringstream ss;

  if(!resp || !resp->srmGetPermissionResponse) RETURN(ss.str());

  if(resp->srmGetPermissionResponse->arrayOfPermissionReturns) {
    std::vector<srm__TPermissionReturn *> v = resp->srmGetPermissionResponse->arrayOfPermissionReturns->permissionArray;
    BOOL print_space = FALSE;
    DM_DBG(DM_N(3), "v.size() = %u\n", v.size());
    for(uint u = 0; u < v.size(); u++) {
      SS_P_VEC_PAR(surl);
      SS_P_VEC_SRM_RETSTAT(status);
      SS_P_VEC_DPAR(owner);
      SS_P_VEC_DPAR_SOAP(PermissionMode,ownerPermission);

      DM_DBG(DM_N(3), "v[u]->arrayOfUserPermissions=%p\n", v[u]->arrayOfUserPermissions);
      if(v[u] && v[u]->arrayOfUserPermissions) {
        for(uint j = 0; v[u]->arrayOfUserPermissions->userPermissionArray.size(); j++) {
          if(!v[u]->arrayOfUserPermissions->userPermissionArray[j]) continue;
          SS_VEC_SPACE;
          ss << "userID" << u << ":" << j << "=" << v[u]->arrayOfUserPermissions->userPermissionArray[j]->userID;
          ss << "mode"   << u << ":" << j << "=" << getTPermissionMode(v[u]->arrayOfUserPermissions->userPermissionArray[j]->mode);
        }
      }
      DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions=%p\n", v[u]->arrayOfGroupPermissions);
      DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions=%p\n", resp->srmGetPermissionResponse->arrayOfPermissionReturns->permissionArray[u]->arrayOfGroupPermissions);

#if 0 // TODO: investigate, DPM may return unitialised values which crash the client?
      if(v[u] && v[u]->arrayOfGroupPermissions) {
        DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions->groupPermissionArray.size()=%u\n", v[u]->arrayOfGroupPermissions->groupPermissionArray.size());
        for(uint j = 0; v[u]->arrayOfGroupPermissions->groupPermissionArray.size(); j++) {
          if(!(v[u]->arrayOfGroupPermissions->groupPermissionArray[j])) continue;
          SS_VEC_SPACE;
          DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions->groupPermissionArray[j]=%p\n", (v[u]->arrayOfGroupPermissions->groupPermissionArray[j]));
          ss << "groupID" << u << ":" << j << "=" << v[u]->arrayOfGroupPermissions->groupPermissionArray[j]->groupID;
          ss << "mode"   << u << ":" << j << "=" << getTPermissionMode(v[u]->arrayOfGroupPermissions->groupPermissionArray[j]->mode);
        }
      }
#endif
      DM_DBG(DM_N(3), "v[u]->otherPermission=%p", v[u]->otherPermission);
      SS_P_VEC_DPAR_SOAP(PermissionMode,otherPermission);
    }
  }

  RETURN(ss.str());
}
<commit_msg>*** empty log message ***<commit_after>#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#ifdef DG_DIAGNOSE
#include "diagnose/dg.h"
#endif

#include "n_srm.h"
#include "srm2api.h"
#include "srm_soap27.h"

#include "constants.h"
#include "i18.h"
#include "sysdep.h"             /* BOOL, STD_BUF, ... */

#include "free.h"               /* FREE(), DELETE() */
#include "str.h"		/* dq_param() */

#include <iostream>             /* std::string, cout, endl, ... */
#include <sstream>              /* ostringstream */

using namespace std;

/*
 * srmGetPermission request constuctor
 */
srmGetPermission::srmGetPermission()
{
  init();
}

/*
 * Initialise srmGetPermission request
 */
void
srmGetPermission::init()
{
  /* request (parser/API) */

  /* response (parser) */
  permissionArray = NULL;
}

/*
 * srmGetPermission request copy constuctor
 */
srmGetPermission::srmGetPermission(Node &node)
{
  init();
  Node::init(node);
}

/*
 * srmGetPermission request destructor
 */
srmGetPermission::~srmGetPermission()
{
  DM_DBG_I;

  /* request (parser/API) */
  DELETE_VEC(SURL);
  DELETE_VEC(storageSystemInfo.key);
  DELETE_VEC(storageSystemInfo.value);

  /* response (parser) */
  DELETE(permissionArray);

  DM_DBG_O;
}

/*
 * Free process-related structures.
 */
void
srmGetPermission::finish(Process *proc)
{
  DM_DBG_I;

  FREE_SRM_RET(GetPermission);
}

int
srmGetPermission::exec(Process *proc)
{
#define EVAL_VEC_STR_GP(vec) vec = proc->eval_vec_str(srmGetPermission::vec)
  DM_DBG_I;

  std::vector <std::string *> SURL;
  tStorageSystemInfo storageSystemInfo;

  EVAL_VEC_STR_GP(SURL);
  EVAL_VEC_STR_GP(storageSystemInfo.key);
  EVAL_VEC_STR_GP(storageSystemInfo.value);

#ifdef SRM2_CALL
  NEW_SRM_RET(GetPermission);

  GetPermission(
    soap,
    EVAL2CSTR(srm_endpoint),
    EVAL2CSTR(authorizationID),
    SURL,
    storageSystemInfo,
    resp
  );
#endif

  DELETE_VEC(SURL);
  DELETE_VEC(storageSystemInfo.key);
  DELETE_VEC(storageSystemInfo.value);

  /* matching */
  if(!resp || !resp->srmGetPermissionResponse) {
    DM_LOG(DM_N(1), "no SRM response\n");
    RETURN(ERR_ERR);
  }

  /* arrayOfPathDetails */
  EAT_MATCH(permissionArray, arrayOfFilePermissionToString(proc, FALSE, FALSE).c_str());

  RETURN(matchReturnStatus(resp->srmGetPermissionResponse->returnStatus, proc));
#undef EVAL_VEC_STR_GP
}

std::string
srmGetPermission::toString(Process *proc)
{
#define EVAL_VEC_STR_GP(vec) EVAL_VEC_STR(srmGetPermission,vec)
  DM_DBG_I;

  GET_SRM_RESP(GetPermission);
  BOOL quote = TRUE;
  std::stringstream ss;

  std::vector <std::string *> SURL;
  tStorageSystemInfo_ storageSystemInfo;

  EVAL_VEC_STR_GP(SURL);
  EVAL_VEC_STR_GP(storageSystemInfo.key);
  EVAL_VEC_STR_GP(storageSystemInfo.value);

  /* request */
  SS_SRM("srmGetPermission");
  SS_P_DQ(authorizationID);
  SS_VEC_DEL(SURL);
  SS_VEC_DEL(storageSystemInfo.key);
  SS_VEC_DEL(storageSystemInfo.value);

  /* response (parser) */
  SS_P_DQ(permissionArray);
  SS_P_DQ(returnStatus.explanation);
  SS_P_DQ(returnStatus.statusCode);

  /* response (API) */
  if(!resp || !resp->srmGetPermissionResponse) RETURN(ss.str());

  ss << arrayOfFilePermissionToString(proc, TRUE, quote);

  SS_P_SRM_RETSTAT(resp->srmGetPermissionResponse);

  RETURN(ss.str());
#undef EVAL_VEC_STR_GP
}

std::string
srmGetPermission::arrayOfFilePermissionToString(Process *proc, BOOL space, BOOL quote) const
{
  DM_DBG_I;

  GET_SRM_RESP(GetPermission);
  std::stringstream ss;

  if(!resp || !resp->srmGetPermissionResponse) RETURN(ss.str());

  if(resp->srmGetPermissionResponse->arrayOfPermissionReturns) {
    std::vector<srm__TPermissionReturn *> v = resp->srmGetPermissionResponse->arrayOfPermissionReturns->permissionArray;
    BOOL print_space = FALSE;
    DM_DBG(DM_N(3), "v.size() = %u\n", v.size());
    for(uint u = 0; u < v.size(); u++) {
      SS_P_VEC_PAR(surl);
      SS_P_VEC_SRM_RETSTAT(status);
      SS_P_VEC_DPAR(owner);
      SS_P_VEC_DPAR_SOAP(PermissionMode,ownerPermission);

      DM_DBG(DM_N(3), "v[u]->arrayOfUserPermissions=%p\n", v[u]->arrayOfUserPermissions);
      if(v[u] && v[u]->arrayOfUserPermissions) {
        for(uint j = 0; v[u]->arrayOfUserPermissions->userPermissionArray.size() < j; j++) {
          if(!v[u]->arrayOfUserPermissions->userPermissionArray[j]) continue;
          SS_VEC_SPACE;
          ss << "userID" << u << ":" << j << "=" << v[u]->arrayOfUserPermissions->userPermissionArray[j]->userID;
          ss << "mode"   << u << ":" << j << "=" << getTPermissionMode(v[u]->arrayOfUserPermissions->userPermissionArray[j]->mode);
        }
      }
      DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions=%p\n", v[u]->arrayOfGroupPermissions);
      DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions=%p\n", resp->srmGetPermissionResponse->arrayOfPermissionReturns->permissionArray[u]->arrayOfGroupPermissions);

#if 1 // TODO: investigate, DPM may return unitialised values which crash the client?
      if(v[u] && v[u]->arrayOfGroupPermissions) {
        DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions->groupPermissionArray.size()=%u\n", v[u]->arrayOfGroupPermissions->groupPermissionArray.size());
        for(uint j = 0; v[u]->arrayOfGroupPermissions->groupPermissionArray.size() < j; j++) {
          if(!(v[u]->arrayOfGroupPermissions->groupPermissionArray[j])) continue;
          SS_VEC_SPACE;
          DM_DBG(DM_N(3), "v[u]->arrayOfGroupPermissions->groupPermissionArray[j]=%p\n", (v[u]->arrayOfGroupPermissions->groupPermissionArray[j]));
          ss << "groupID" << u << ":" << j << "=" << v[u]->arrayOfGroupPermissions->groupPermissionArray[j]->groupID;
          ss << "mode"   << u << ":" << j << "=" << getTPermissionMode(v[u]->arrayOfGroupPermissions->groupPermissionArray[j]->mode);
        }
      }
#endif
      DM_DBG(DM_N(3), "v[u]->otherPermission=%p", v[u]->otherPermission);
      SS_P_VEC_DPAR_SOAP(PermissionMode,otherPermission);
    }
  }

  RETURN(ss.str());
}
<|endoftext|>


<commit_before>#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_mixer.h"

// SDL_main doesn't seem to work with VS2015
#undef main

// Oh god a global. Sue me.
int scale = 2;

void ChangeColorTo(SDL_Surface* surface, Uint32 color) {
    if (surface->format->BytesPerPixel != 4) exit(5);

    for (int x = 0; x < surface->w; x++) for (int y = 0; y < surface->h; y++)
    {
        Uint8* pixel_addr = (Uint8*)surface->pixels + y * surface->pitch + x * 4;
        Uint32 pixel = *((Uint32*)pixel_addr);

        if (pixel != 0x00000000)
            *(Uint32 *)pixel_addr = color;
    }
}

struct Textures {
    SDL_Texture* background;
    SDL_Texture* sword_tex;
};

struct Musics {
    Mix_Music* ominous;
};

enum Controls { UP, DOWN, LEFT, RIGHT };

enum Actions { UP, DOWN, LEFT, RIGHT, NONE };

struct Player {
    SDL_Texture* tex;
    int cell_x, cell_y;
    int frame;

    const int ground_level = 2;

    Player(SDL_Renderer* rend, SDL_Surface* surface, Uint32 color) {
        if (color != 0) ChangeColorTo(surface, color);
        tex = SDL_CreateTextureFromSurface(rend, surface);
        frame = 0;
    }

    ~Player() {
        SDL_DestroyTexture(tex);
    }

    void render(SDL_Renderer* renderer) {
        SDL_Rect src;
        src.x = frame * 45;
        src.y = 0;
        src.w = 45;
        src.h = 45;

        SDL_Rect dest;
        dest.x = cell_x * 45 * scale;
        dest.y = (17 + cell_y * 45) * scale;
        dest.w = 45 * scale;
        dest.h = 45 * scale;

        SDL_RenderCopy(renderer, tex, &src, &dest);
    }
};

#define pressed(ctl) (controls[ctl] && !last_controls[ctl])

#ifdef _WIN32
int WinMain(HINSTANCE hinst, HINSTANCE prev, LPSTR cmdline, int cmdshow) {
#else
int main() {
#endif
    // =============== SDL and asset stuff ==================
    SDL_Window* window;
    int window_width = 720, window_height = 512;
    SDL_Renderer* renderer;
    SDL_Surface* player_surface;
    SDL_Surface* temp_surface;
    Textures tex;
    Musics music;
    bool last_controls[4];
    bool controls[4];

    // ================== Initialize things ====================
    if (!SDL_Init(SDL_INIT_AUDIO) == -1) { exit(1); }
    if (Mix_Init(MIX_INIT_OGG) & MIX_INIT_OGG != MIX_INIT_OGG) { exit(2); }

    window = SDL_CreateWindow(
        "A Duel With the Devil",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        window_width, window_height, 0
    );
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 165, 226, 216, 255);

    memset(&last_controls, 0, sizeof(last_controls));
    memset(&controls, 0, sizeof(controls));

    // =================== Load Some Assets ===================
    player_surface = IMG_Load("assets/player.png");

    temp_surface = IMG_Load("assets/mountaintop.png");
    tex.background = SDL_CreateTextureFromSurface(renderer, temp_surface);
    SDL_Rect bg_rect;
    bg_rect.x = 0; bg_rect.y = 0; bg_rect.w = window_width; bg_rect.h = window_height;
    SDL_FreeSurface(temp_surface);

    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2048) == -1)
        exit(3);
    music.ominous = Mix_LoadMUS("assets/music/ominous.ogg");
    if (!music.ominous) {
        char shit[100];
        sprintf(shit, "Problem loading music: %s\n", Mix_GetError());
        OutputDebugString(shit);
    }
    else
        Mix_PlayMusic(music.ominous, -1);

    // ====================== Initialize Player ======================
    Player player(renderer, player_surface, 0);
    player.cell_x = 1;
    player.cell_y = 1;

    // ============ Stuff for game loop management ===============
    SDL_Event event;
    Uint64 milliseconds_per_tick = 1000 / SDL_GetPerformanceFrequency();
    int key_count;
    const Uint8* keys = SDL_GetKeyboardState(&key_count);

    while (true) {
        // ============= Frame Setup =================
        Uint64 frame_start = SDL_GetPerformanceCounter();

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT: exit(0); break;
            }
        }

        controls[UP]    = keys[SDL_SCANCODE_UP]    || keys[SDL_SCANCODE_W];
        controls[DOWN]  = keys[SDL_SCANCODE_DOWN]  || keys[SDL_SCANCODE_S];
        controls[LEFT]  = keys[SDL_SCANCODE_LEFT]  || keys[SDL_SCANCODE_A];
        controls[RIGHT] = keys[SDL_SCANCODE_RIGHT] || keys[SDL_SCANCODE_D];

        // ================= Game Logic ===================
        if (pressed(RIGHT)) player.cell_x += 1;
        if (pressed(LEFT)) player.cell_x -= 1;
        if (pressed(UP)) player.cell_y -= 1;
        if (pressed(DOWN)) player.cell_y += 1;

        // ====================== Render ========================
        SDL_RenderClear(renderer);

        SDL_RenderCopy(renderer, tex.background, NULL, NULL);
        player.render(renderer);

        SDL_RenderPresent(renderer);

        memcpy(&last_controls, &controls, sizeof(controls));

        // ======================= Cap Framerate =====================
        Uint64 frame_end = SDL_GetPerformanceCounter();
        Uint64 frame_ms = (frame_end - frame_start) * milliseconds_per_tick;

        if (frame_ms < 17)
            SDL_Delay(17 - frame_ms);
    }

	return 0;
}<commit_msg>unbreak enums<commit_after>#ifdef _WIN32
#include <Windows.h>
#endif

#include <stdio.h>
#include "SDL/SDL.h"
#include "SDL/SDL_image.h"
#include "SDL/SDL_mixer.h"

// SDL_main doesn't seem to work with VS2015
#undef main

// Oh god a global. Sue me.
int scale = 2;

void ChangeColorTo(SDL_Surface* surface, Uint32 color) {
    if (surface->format->BytesPerPixel != 4) exit(5);

    for (int x = 0; x < surface->w; x++) for (int y = 0; y < surface->h; y++)
    {
        Uint8* pixel_addr = (Uint8*)surface->pixels + y * surface->pitch + x * 4;
        Uint32 pixel = *((Uint32*)pixel_addr);

        if (pixel != 0x00000000)
            *(Uint32 *)pixel_addr = color;
    }
}

struct Textures {
    SDL_Texture* background;
    SDL_Texture* sword_tex;
};

struct Musics {
    Mix_Music* ominous;
};

enum Controls { UP, DOWN, LEFT, RIGHT };

enum Actions { GO_UP, GO_DOWN, GO_LEFT, GO_RIGHT, NONE };

struct Player {
    SDL_Texture* tex;
    int cell_x, cell_y;
    int frame;

    const int ground_level = 2;

    Player(SDL_Renderer* rend, SDL_Surface* surface, Uint32 color) {
        if (color != 0) ChangeColorTo(surface, color);
        tex = SDL_CreateTextureFromSurface(rend, surface);
        frame = 0;
    }

    ~Player() {
        SDL_DestroyTexture(tex);
    }

    void render(SDL_Renderer* renderer) {
        SDL_Rect src;
        src.x = frame * 45;
        src.y = 0;
        src.w = 45;
        src.h = 45;

        SDL_Rect dest;
        dest.x = cell_x * 45 * scale;
        dest.y = (17 + cell_y * 45) * scale;
        dest.w = 45 * scale;
        dest.h = 45 * scale;

        SDL_RenderCopy(renderer, tex, &src, &dest);
    }
};

#define pressed(ctl) (controls[ctl] && !last_controls[ctl])

#ifdef _WIN32
int WinMain(HINSTANCE hinst, HINSTANCE prev, LPSTR cmdline, int cmdshow) {
#else
int main() {
#endif
    // =============== SDL and asset stuff ==================
    SDL_Window* window;
    int window_width = 720, window_height = 512;
    SDL_Renderer* renderer;
    SDL_Surface* player_surface;
    SDL_Surface* temp_surface;
    Textures tex;
    Musics music;
    bool last_controls[4];
    bool controls[4];

    // ================== Initialize things ====================
    if (!SDL_Init(SDL_INIT_AUDIO) == -1) { exit(1); }
    if (Mix_Init(MIX_INIT_OGG) & MIX_INIT_OGG != MIX_INIT_OGG) { exit(2); }

    window = SDL_CreateWindow(
        "A Duel With the Devil",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
        window_width, window_height, 0
    );
    renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
    SDL_SetRenderDrawColor(renderer, 165, 226, 216, 255);

    memset(&last_controls, 0, sizeof(last_controls));
    memset(&controls, 0, sizeof(controls));

    // =================== Load Some Assets ===================
    player_surface = IMG_Load("assets/player.png");

    temp_surface = IMG_Load("assets/mountaintop.png");
    tex.background = SDL_CreateTextureFromSurface(renderer, temp_surface);
    SDL_Rect bg_rect;
    bg_rect.x = 0; bg_rect.y = 0; bg_rect.w = window_width; bg_rect.h = window_height;
    SDL_FreeSurface(temp_surface);

    if (Mix_OpenAudio(MIX_DEFAULT_FREQUENCY, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 2048) == -1)
        exit(3);
    music.ominous = Mix_LoadMUS("assets/music/ominous.ogg");
    if (!music.ominous) {
        char shit[100];
        sprintf(shit, "Problem loading music: %s\n", Mix_GetError());
        OutputDebugString(shit);
    }
    else
        Mix_PlayMusic(music.ominous, -1);

    // ====================== Initialize Player ======================
    Player player(renderer, player_surface, 0);
    player.cell_x = 1;
    player.cell_y = 1;

    // ============ Stuff for game loop management ===============
    SDL_Event event;
    Uint64 milliseconds_per_tick = 1000 / SDL_GetPerformanceFrequency();
    int key_count;
    const Uint8* keys = SDL_GetKeyboardState(&key_count);

    while (true) {
        // ============= Frame Setup =================
        Uint64 frame_start = SDL_GetPerformanceCounter();

        while (SDL_PollEvent(&event)) {
            switch (event.type) {
            case SDL_QUIT: exit(0); break;
            }
        }

        controls[UP]    = keys[SDL_SCANCODE_UP]    || keys[SDL_SCANCODE_W];
        controls[DOWN]  = keys[SDL_SCANCODE_DOWN]  || keys[SDL_SCANCODE_S];
        controls[LEFT]  = keys[SDL_SCANCODE_LEFT]  || keys[SDL_SCANCODE_A];
        controls[RIGHT] = keys[SDL_SCANCODE_RIGHT] || keys[SDL_SCANCODE_D];

        // ================= Game Logic ===================
        if (pressed(RIGHT)) player.cell_x += 1;
        if (pressed(LEFT)) player.cell_x -= 1;
        if (pressed(UP)) player.cell_y -= 1;
        if (pressed(DOWN)) player.cell_y += 1;

        // ====================== Render ========================
        SDL_RenderClear(renderer);

        SDL_RenderCopy(renderer, tex.background, NULL, NULL);
        player.render(renderer);

        SDL_RenderPresent(renderer);

        memcpy(&last_controls, &controls, sizeof(controls));

        // ======================= Cap Framerate =====================
        Uint64 frame_end = SDL_GetPerformanceCounter();
        Uint64 frame_ms = (frame_end - frame_start) * milliseconds_per_tick;

        if (frame_ms < 17)
            SDL_Delay(17 - frame_ms);
    }

	return 0;
}<|endoftext|>


<commit_before>/* ---------------------------------------------------------------------
 *
 * Copyright (C) 2009 - 2015 by the deal.II authors
 *
 * This file is part of the deal.II library.
 *
 * The deal.II library is free software; you can use it, 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.
 * The full text of the license can be found in the file LICENSE at
 * the top level of the deal.II distribution.
 *
 * ---------------------------------------------------------------------

 *
 * Author: Luca Heltai, Cataldo Manigrasso, 2009
 */

#include "driver.h"

int main (int argc, char *argv[])
{
  try
    {
      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);

      Driver<3> driver;

      ParameterAcceptor::initialize("parmaeter_bem.prm","used_parmaeter_bem.prm");

      driver.run();

    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<commit_msg>corrected the parameter file name<commit_after>/* ---------------------------------------------------------------------
 *
 * Copyright (C) 2009 - 2015 by the deal.II authors
 *
 * This file is part of the deal.II library.
 *
 * The deal.II library is free software; you can use it, 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.
 * The full text of the license can be found in the file LICENSE at
 * the top level of the deal.II distribution.
 *
 * ---------------------------------------------------------------------

 *
 * Author: Luca Heltai, Cataldo Manigrasso, 2009
 */

#include "driver.h"

int main (int argc, char *argv[])
{
  try
    {
      Utilities::MPI::MPI_InitFinalize mpi_initialization(argc, argv, 1);

      Driver<3> driver;

      ParameterAcceptor::initialize("parameter_bem.prm","used_parameter_bem.prm");

      driver.run();

    }
  catch (std::exception &exc)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Exception on processing: " << std::endl
                << exc.what() << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;

      return 1;
    }
  catch (...)
    {
      std::cerr << std::endl << std::endl
                << "----------------------------------------------------"
                << std::endl;
      std::cerr << "Unknown exception!" << std::endl
                << "Aborting!" << std::endl
                << "----------------------------------------------------"
                << std::endl;
      return 1;
    }

  return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "qtquickapp.h"
#include "html5app.h"
#include <QtCore>

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

static bool writeFile(const QByteArray &data, const QString &targetFile)
{
    const QFileInfo fileInfo(targetFile);
    QDir().mkpath(fileInfo.absolutePath());
    QFile file(fileInfo.absoluteFilePath());
    file.open(QIODevice::WriteOnly);
    Q_ASSERT(file.isOpen());
    return file.write(data) != -1;
}

bool QtQuickApp::generateFiles(QString *errorMessage) const
{
    return     writeFile(generateFile(QtQuickAppGeneratedFileInfo::MainCppFile, errorMessage), path(MainCpp))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppProFile, errorMessage), path(AppPro))
            && (m_mainQmlMode != ModeImport ? true : writeFile(generateFile(QtQuickAppGeneratedFileInfo::MainQmlFile, errorMessage), path(MainQml)))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerPriFile, errorMessage), path(AppViewerPri))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerCppFile, errorMessage), path(AppViewerCpp))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerHFile, errorMessage), path(AppViewerH))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::SymbianSvgIconFile, errorMessage), path(SymbianSvgIcon))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::MaemoPngIconFile, errorMessage), path(MaemoPngIcon))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::DesktopFile, errorMessage), path(Desktop));
}

bool Html5App::generateFiles(QString *errorMessage) const
{
    return     writeFile(generateFile(Html5AppGeneratedFileInfo::MainCppFile, errorMessage), path(MainCpp))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppProFile, errorMessage), path(AppPro))
            && (mainHtmlMode() != ModeGenerate ? true : writeFile(generateFile(Html5AppGeneratedFileInfo::MainHtmlFile, errorMessage), path(MainHtml)))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerPriFile, errorMessage), path(AppViewerPri))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerCppFile, errorMessage), path(AppViewerCpp))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerHFile, errorMessage), path(AppViewerH))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::SymbianSvgIconFile, errorMessage), path(SymbianSvgIcon))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::MaemoPngIconFile, errorMessage), path(MaemoPngIcon))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::DesktopFile, errorMessage), path(Desktop));
}

QString AbstractMobileApp::templatesRoot()
{
    return QLatin1String("../../../share/qtcreator/templates/");
}
<commit_msg>Fix the main .qml gile generation in the manual test.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "qtquickapp.h"
#include "html5app.h"
#include <QtCore>

using namespace Qt4ProjectManager;
using namespace Qt4ProjectManager::Internal;

static bool writeFile(const QByteArray &data, const QString &targetFile)
{
    const QFileInfo fileInfo(targetFile);
    QDir().mkpath(fileInfo.absolutePath());
    QFile file(fileInfo.absoluteFilePath());
    file.open(QIODevice::WriteOnly);
    Q_ASSERT(file.isOpen());
    return file.write(data) != -1;
}

bool QtQuickApp::generateFiles(QString *errorMessage) const
{
    return     writeFile(generateFile(QtQuickAppGeneratedFileInfo::MainCppFile, errorMessage), path(MainCpp))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppProFile, errorMessage), path(AppPro))
            && (m_mainQmlMode == ModeImport ? true : writeFile(generateFile(QtQuickAppGeneratedFileInfo::MainQmlFile, errorMessage), path(MainQml)))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerPriFile, errorMessage), path(AppViewerPri))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerCppFile, errorMessage), path(AppViewerCpp))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::AppViewerHFile, errorMessage), path(AppViewerH))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::SymbianSvgIconFile, errorMessage), path(SymbianSvgIcon))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::MaemoPngIconFile, errorMessage), path(MaemoPngIcon))
            && writeFile(generateFile(QtQuickAppGeneratedFileInfo::DesktopFile, errorMessage), path(Desktop));
}

bool Html5App::generateFiles(QString *errorMessage) const
{
    return     writeFile(generateFile(Html5AppGeneratedFileInfo::MainCppFile, errorMessage), path(MainCpp))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppProFile, errorMessage), path(AppPro))
            && (mainHtmlMode() != ModeGenerate ? true : writeFile(generateFile(Html5AppGeneratedFileInfo::MainHtmlFile, errorMessage), path(MainHtml)))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerPriFile, errorMessage), path(AppViewerPri))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerCppFile, errorMessage), path(AppViewerCpp))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::AppViewerHFile, errorMessage), path(AppViewerH))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::SymbianSvgIconFile, errorMessage), path(SymbianSvgIcon))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::MaemoPngIconFile, errorMessage), path(MaemoPngIcon))
            && writeFile(generateFile(Html5AppGeneratedFileInfo::DesktopFile, errorMessage), path(Desktop));
}

QString AbstractMobileApp::templatesRoot()
{
    return QLatin1String("../../../share/qtcreator/templates/");
}
<|endoftext|>


<commit_before><commit_msg>lambda start<commit_after><|endoftext|>


<commit_before>#include <fstream>
#include <iostream>

#include <glob.h>   // TODO

#include <pdal/StageFactory.hpp>

#include <entwine/third/arbiter/arbiter.hpp>
#include <entwine/reader/query.hpp>
#include <entwine/reader/reader.hpp>
#include <entwine/third/json/json.hpp>
#include <entwine/tree/clipper.hpp>
#include <entwine/types/bbox.hpp>
#include <entwine/types/schema.hpp>
#include <entwine/types/structure.hpp>
#include <entwine/util/executor.hpp>

#include "read-queries/entwine.hpp"
#include "read-queries/unindexed.hpp"
#include "util/buffer-pool.hpp"

#include "session.hpp"

namespace
{
    // TODO Put this somewhere else - platform dependent code.
    std::vector<std::string> resolve(
            const std::vector<std::string>& dirs,
            const std::string& name)
    {
        glob_t buffer;
        for (std::size_t i(0); i < dirs.size(); ++i)
        {
            auto flags(GLOB_NOSORT | GLOB_TILDE);
            if (i) flags |= GLOB_APPEND;

            glob((dirs[i] + "/" + name + ".*").c_str(), flags, 0, &buffer);
        }

        std::vector<std::string> results;
        for (std::size_t i(0); i < buffer.gl_pathc; ++i)
        {
            results.push_back(buffer.gl_pathv[i]);
        }

        globfree(&buffer);

        return results;
    }
}

Session::Session(
        pdal::StageFactory& stageFactory,
        std::mutex& factoryMutex)
    : m_stageFactory(stageFactory)
    , m_factoryMutex(factoryMutex)
    , m_initOnce()
    , m_source()
    , m_entwine()
{ }

Session::~Session()
{ }

bool Session::initialize(
        const std::string& name,
        std::vector<std::string> paths,
        std::shared_ptr<arbiter::Arbiter> arbiter,
        std::shared_ptr<entwine::Cache> cache)
{
    m_initOnce.ensure([this, &name, &paths, cache, arbiter]()
    {
        paths.push_back("s3://");

        std::cout << "Discovering " << name << std::endl;

        if (resolveIndex(name, paths, *arbiter, cache))
        {
            std::cout << "\tIndex for " << name << " found" << std::endl;

            Json::Value json;
            const std::size_t numPoints(m_entwine->numPoints());
            const std::size_t numDimensions(
                    m_entwine->structure().dimensions());

            json["type"] = (numDimensions == 2 ? "quadtree" : "octree");
            json["numPoints"] = static_cast<Json::UInt64>(numPoints);
            json["schema"] = m_entwine->schema().toJson();
            json["bounds"] = m_entwine->bbox().toJson()["bounds"];
            json["srs"] = m_entwine->srs();

            m_info = json.toStyledString();
        }
        else if (resolveSource(name, paths))
        {
            std::cout << "\tSource for " << name << " found" << std::endl;
            const std::size_t numPoints(m_source->numPoints());

            Json::Value json;
            json["type"] = "unindexed";
            json["numPoints"] = static_cast<Json::UInt64>(numPoints);
            json["schema"] = m_source->schema().toJson();
            json["bounds"] = m_source->bbox().toJson()["bounds"];
            json["srs"] = m_source->srs();

            m_info = json.toStyledString();
        }
        else
        {
            std::cout << "\tBacking for " << name << " NOT found" << std::endl;
        }
    });

    return sourced() || indexed();
}

std::string Session::info() const
{
    check();
    return m_info;
}

std::shared_ptr<ReadQuery> Session::query(
        const entwine::Schema& schema,
        const bool compress)
{
    if (sourced())
    {
        return std::shared_ptr<ReadQuery>(
                new UnindexedReadQuery(
                    schema,
                    compress,
                    *m_source));
    }
    else
    {
        throw WrongQueryType();
    }
}

std::shared_ptr<ReadQuery> Session::query(
        const entwine::Schema& schema,
        const bool compress,
        const entwine::BBox& bbox,
        const std::size_t depthBegin,
        const std::size_t depthEnd)
{
    if (indexed())
    {
        return std::shared_ptr<ReadQuery>(
                new EntwineReadQuery(
                    schema,
                    compress,
                    m_entwine->query(
                        schema,
                        bbox.exists() ? bbox : m_entwine->bbox(),
                        depthBegin,
                        depthEnd)));
    }
    else
    {
        throw WrongQueryType();
    }
}

const entwine::Schema& Session::schema() const
{
    check();

    if (indexed()) return m_entwine->schema();
    else return m_source->schema();
}

bool Session::resolveIndex(
        const std::string& name,
        const std::vector<std::string>& paths,
        arbiter::Arbiter& arbiter,
        std::shared_ptr<entwine::Cache> cache)
{
    for (std::string path : paths)
    {
        try
        {
            if (path.size() && path.back() != '/') path.push_back('/');
            arbiter::Endpoint endpoint(arbiter.getEndpoint(path + name));
            m_entwine.reset(new entwine::Reader(endpoint, arbiter, *cache));
        }
        catch (...)
        {
            m_entwine.reset(0);
        }

        std::cout << "\tTried resolving index at " << path << ": ";
        if (m_entwine)
        {
            std::cout << "SUCCESS" << std::endl;
            break;
        }
        else
        {
            std::cout << "fail" << std::endl;
        }
    }

    return indexed();
}

bool Session::resolveSource(
        const std::string& name,
        const std::vector<std::string>& paths)
{
    const auto sources(resolve(paths, name));

    if (sources.size() > 1)
    {
        std::cout << "\tFound competing unindexed sources for " << name <<
            std::endl;
    }

    if (sources.size())
    {
        std::size_t i(0);

        while (!m_source && i < sources.size())
        {
            const std::string path(sources[i++]);

            std::unique_lock<std::mutex> lock(m_factoryMutex);
            const std::string driver(
                    m_stageFactory.inferReaderDriver(path));
            lock.unlock();

            if (driver.size())
            {
                try
                {
                    m_source.reset(
                            new SourceManager(
                                m_stageFactory,
                                m_factoryMutex,
                                path,
                                driver));
                }
                catch (...)
                {
                    m_source.reset(0);
                }
            }

            std::cout << "\tTried resolving unindexed at " << path << ": ";
            if (m_source) std::cout << "SUCCESS" << std::endl;
            else std::cout << "failed" << std::endl;
        }
    }

    return sourced();
}

<commit_msg>Return correct tree type string.<commit_after>#include <fstream>
#include <iostream>

#include <glob.h>   // TODO

#include <pdal/StageFactory.hpp>

#include <entwine/third/arbiter/arbiter.hpp>
#include <entwine/reader/query.hpp>
#include <entwine/reader/reader.hpp>
#include <entwine/third/json/json.hpp>
#include <entwine/tree/clipper.hpp>
#include <entwine/types/bbox.hpp>
#include <entwine/types/schema.hpp>
#include <entwine/types/structure.hpp>
#include <entwine/util/executor.hpp>

#include "read-queries/entwine.hpp"
#include "read-queries/unindexed.hpp"
#include "util/buffer-pool.hpp"

#include "session.hpp"

namespace
{
    // TODO Put this somewhere else - platform dependent code.
    std::vector<std::string> resolve(
            const std::vector<std::string>& dirs,
            const std::string& name)
    {
        glob_t buffer;
        for (std::size_t i(0); i < dirs.size(); ++i)
        {
            auto flags(GLOB_NOSORT | GLOB_TILDE);
            if (i) flags |= GLOB_APPEND;

            glob((dirs[i] + "/" + name + ".*").c_str(), flags, 0, &buffer);
        }

        std::vector<std::string> results;
        for (std::size_t i(0); i < buffer.gl_pathc; ++i)
        {
            results.push_back(buffer.gl_pathv[i]);
        }

        globfree(&buffer);

        return results;
    }

    std::string getTypeString(const entwine::Structure& structure)
    {
        if (structure.dimensions() == 2)
        {
            if (structure.tubular()) return "hybrid";
            else return "quadtree";
        }
        else if (structure.dimensions() == 3 && !structure.tubular())
        {
            return "octree";
        }
        else
        {
            throw std::runtime_error("Invalid structure");
        }
    }
}

Session::Session(
        pdal::StageFactory& stageFactory,
        std::mutex& factoryMutex)
    : m_stageFactory(stageFactory)
    , m_factoryMutex(factoryMutex)
    , m_initOnce()
    , m_source()
    , m_entwine()
{ }

Session::~Session()
{ }

bool Session::initialize(
        const std::string& name,
        std::vector<std::string> paths,
        std::shared_ptr<arbiter::Arbiter> arbiter,
        std::shared_ptr<entwine::Cache> cache)
{
    m_initOnce.ensure([this, &name, &paths, cache, arbiter]()
    {
        paths.push_back("s3://");

        std::cout << "Discovering " << name << std::endl;

        if (resolveIndex(name, paths, *arbiter, cache))
        {
            std::cout << "\tIndex for " << name << " found" << std::endl;

            Json::Value json;
            const std::size_t numPoints(m_entwine->numPoints());

            json["type"] = getTypeString(m_entwine->structure());
            json["numPoints"] = static_cast<Json::UInt64>(numPoints);
            json["schema"] = m_entwine->schema().toJson();
            json["bounds"] = m_entwine->bbox().toJson()["bounds"];
            json["srs"] = m_entwine->srs();

            m_info = json.toStyledString();
        }
        else if (resolveSource(name, paths))
        {
            std::cout << "\tSource for " << name << " found" << std::endl;
            const std::size_t numPoints(m_source->numPoints());

            Json::Value json;
            json["type"] = "unindexed";
            json["numPoints"] = static_cast<Json::UInt64>(numPoints);
            json["schema"] = m_source->schema().toJson();
            json["bounds"] = m_source->bbox().toJson()["bounds"];
            json["srs"] = m_source->srs();

            m_info = json.toStyledString();
        }
        else
        {
            std::cout << "\tBacking for " << name << " NOT found" << std::endl;
        }
    });

    return sourced() || indexed();
}

std::string Session::info() const
{
    check();
    return m_info;
}

std::shared_ptr<ReadQuery> Session::query(
        const entwine::Schema& schema,
        const bool compress)
{
    if (sourced())
    {
        return std::shared_ptr<ReadQuery>(
                new UnindexedReadQuery(
                    schema,
                    compress,
                    *m_source));
    }
    else
    {
        throw WrongQueryType();
    }
}

std::shared_ptr<ReadQuery> Session::query(
        const entwine::Schema& schema,
        const bool compress,
        const entwine::BBox& bbox,
        const std::size_t depthBegin,
        const std::size_t depthEnd)
{
    if (indexed())
    {
        return std::shared_ptr<ReadQuery>(
                new EntwineReadQuery(
                    schema,
                    compress,
                    m_entwine->query(
                        schema,
                        bbox.exists() ? bbox : m_entwine->bbox(),
                        depthBegin,
                        depthEnd)));
    }
    else
    {
        throw WrongQueryType();
    }
}

const entwine::Schema& Session::schema() const
{
    check();

    if (indexed()) return m_entwine->schema();
    else return m_source->schema();
}

bool Session::resolveIndex(
        const std::string& name,
        const std::vector<std::string>& paths,
        arbiter::Arbiter& arbiter,
        std::shared_ptr<entwine::Cache> cache)
{
    for (std::string path : paths)
    {
        try
        {
            if (path.size() && path.back() != '/') path.push_back('/');
            arbiter::Endpoint endpoint(arbiter.getEndpoint(path + name));
            m_entwine.reset(new entwine::Reader(endpoint, arbiter, *cache));
        }
        catch (...)
        {
            m_entwine.reset(0);
        }

        std::cout << "\tTried resolving index at " << path << ": ";
        if (m_entwine)
        {
            std::cout << "SUCCESS" << std::endl;
            break;
        }
        else
        {
            std::cout << "fail" << std::endl;
        }
    }

    return indexed();
}

bool Session::resolveSource(
        const std::string& name,
        const std::vector<std::string>& paths)
{
    const auto sources(resolve(paths, name));

    if (sources.size() > 1)
    {
        std::cout << "\tFound competing unindexed sources for " << name <<
            std::endl;
    }

    if (sources.size())
    {
        std::size_t i(0);

        while (!m_source && i < sources.size())
        {
            const std::string path(sources[i++]);

            std::unique_lock<std::mutex> lock(m_factoryMutex);
            const std::string driver(
                    m_stageFactory.inferReaderDriver(path));
            lock.unlock();

            if (driver.size())
            {
                try
                {
                    m_source.reset(
                            new SourceManager(
                                m_stageFactory,
                                m_factoryMutex,
                                path,
                                driver));
                }
                catch (...)
                {
                    m_source.reset(0);
                }
            }

            std::cout << "\tTried resolving unindexed at " << path << ": ";
            if (m_source) std::cout << "SUCCESS" << std::endl;
            else std::cout << "failed" << std::endl;
        }
    }

    return sourced();
}

<|endoftext|>


<commit_before>#include "LinearEllipticPDE.hpp"

double f1(Point const & point) {
	return point.x() * point.x();
}

double f2(Point const & point) {
	return point.y() * point.y();
}

int main() {
	// laplace
	ConstTensor I(3, 0.);
	I(0, 0) = I(1, 1) = I(2, 2) = 1.;
	LinearEllipticPDE LaplacesEquation3D(I, 0., zeroFunc);
	std::cout << "div(D grad u) = f, D:" << '\n';
	LaplacesEquation3D.diffusionTensor().save(std::cout);
	std::cout << "f(0, 0, 0): " << LaplacesEquation3D.forceTerm(Point()) << std::endl;
	// my problem example
	Tensor D(2);
	//D.load(std::cin);
	D(0, 0) = f1;
	D(1, 1) = f2;
	D(0, 1) = zeroFunc;
	NonLinearEllipticPDE MyEqn2D(D, f1, zeroFunc);
	Point dummy(1., 2.);
	std::cout << "Coeff of u_{xx}, u_{yy} etc. at (1, 2):" << '\n';
	MyEqn2D.diffusionTensor(dummy).save(std::cout);
	std::cout << "gamma(1, 2): " << MyEqn2D.gamma(dummy) << '\n'
			  << "f(1, 2): " << MyEqn2D.forceTerm(dummy) << std::endl;
	return 0;
}<commit_msg>Add example of creating BC for Laplaces eqn<commit_after>#include "LinearEllipticPDE.hpp"
#include "BC.hpp"

double g(Point const & point) { // u = g on Г
	return point.x() * point.y();
}

int main() {
	// Laplace's eqn on the plane
	ConstTensor I(2, 0.);
	I(0, 0) = I(1, 1) = 1.;
	LinearEllipticPDE LaplacesEquation2D(I, 0., zeroFunc);
	BC myBC(g); // simple Dirichlet problem
	std::cout << "u(2, 3) = " << myBC.dirichlet(Point(2., 3.)) << std::endl;
	return 0;
}<|endoftext|>


<commit_before>#include "medViewContainerFiltering.h"

//TODO: synchronize views

class medViewContainerFilteringPrivate
{
public:
    medViewContainerCustom* inputViewContainer;
    medViewContainerCustom* outputViewContainer;
    dtkAbstractData * inputData;
    dtkAbstractView * inputView;
    dtkAbstractView * outputView;
};

medViewContainerFiltering::medViewContainerFiltering(QWidget * parent):
        medViewContainerCustom(parent), d3(new medViewContainerFilteringPrivate)
{
    split(1, 2);

    d3->inputViewContainer = children()[0];
    d3->outputViewContainer = children()[1];

    //Set cues for the user:
    d3->inputViewContainer->setInfo(tr("Input"));
    d3->outputViewContainer->setInfo(tr("Result of filtering ..."));

    d3->inputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->inputViewContainer->setAcceptDrops(false);
    d3->inputViewContainer->update();

    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->outputViewContainer->setAcceptDrops(false);
    d3->outputViewContainer->update();

    d3->inputData = NULL;
}

medViewContainerFiltering::~medViewContainerFiltering()
{
    delete d3;
    d3 = NULL;
}

void medViewContainerFiltering::updateInput(dtkAbstractData *data)
{
    if(!data)
        return;

//  d3->views[0]->unlink(d3->views[1]);

    d3->inputView->setData(data,0);
    d3->inputView->reset();
    d3->inputView->update();

//  d3->views[0]->link(d3->views[1]);

    d3->inputViewContainer->setView(d3->inputView);
    d3->inputViewContainer->update();

    if(data != d3->inputData )
    {
//    d3->outputView->clear();
//    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    qDebug() << "OK here";
    d3->outputViewContainer->clear();
    d3->outputViewContainer = children()[1];
    d3->outputViewContainer->setInfo(tr("Result of filtering ..."));
    d3->outputViewContainer->update();
    }
}

void medViewContainerFiltering::updateOutput(dtkAbstractData *data)
{
    if(!data)
        return;

//    d3->outputView->clear();
    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->outputView->setData(data,0);
    d3->outputView->reset();
    d3->outputView->update();

    d3->outputViewContainer->setView(d3->outputView);
    d3->outputViewContainer->update();

//    d3->views[1]->link(d3->views[0]);
}
<commit_msg>fixed bug about refreshing views<commit_after>#include "medViewContainerFiltering.h"

//TODO: synchronize views

class medViewContainerFilteringPrivate
{
public:
    medViewContainerCustom* inputViewContainer;
    medViewContainerCustom* outputViewContainer;
    dtkAbstractData * inputData;
    dtkAbstractView * inputView;
    dtkAbstractView * outputView;
};

medViewContainerFiltering::medViewContainerFiltering(QWidget * parent):
        medViewContainerCustom(parent), d3(new medViewContainerFilteringPrivate)
{
    split(1, 2);

    d3->inputViewContainer = children()[0];
    d3->outputViewContainer = children()[1];

    //Set cues for the user:
    d3->inputViewContainer->setInfo(tr("Input to be filtered"));
    d3->outputViewContainer->setInfo(tr("Result of filtering"));

    d3->inputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->inputViewContainer->setAcceptDrops(false);
    d3->inputViewContainer->update();

    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->outputViewContainer->setAcceptDrops(false);
    d3->outputViewContainer->update();

    d3->inputData = NULL;
}

medViewContainerFiltering::~medViewContainerFiltering()
{
    delete d3;
    d3 = NULL;
}

void medViewContainerFiltering::updateInput(dtkAbstractData *data)
{
    if(!data)
        return;

//  d3->views[0]->unlink(d3->views[1]);

    d3->inputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->inputView->setData(data,0);
    d3->inputView->reset();
    d3->inputView->update();

//  d3->views[0]->link(d3->views[1]);

    d3->inputViewContainer->clear();
    d3->inputViewContainer = children()[0];
    d3->inputViewContainer->setInfo(tr("Input to be filtered"));
    d3->inputViewContainer->update();
    d3->inputViewContainer->setView(d3->inputView);
    d3->inputViewContainer->update();

    if(data != d3->inputData )
    {
//    d3->outputView->clear();
//    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->outputViewContainer->clear();
    d3->outputViewContainer = children()[1];
    d3->outputViewContainer->setInfo(tr("Result of filtering"));
    d3->outputViewContainer->update();
    }
}

void medViewContainerFiltering::updateOutput(dtkAbstractData *data)
{
    if(!data)
        return;

//    d3->outputView->clear();
    d3->outputView = dtkAbstractViewFactory::instance()->create("v3dView");
    d3->outputView->setData(data,0);
    d3->outputView->reset();
    d3->outputView->update();

    d3->outputViewContainer->setView(d3->outputView);
    d3->outputViewContainer->update();

//    d3->views[1]->link(d3->views[0]);
}
<|endoftext|>


<commit_before>#pragma once

#include "boost_defs.hpp"

#include "cf_utility.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <boost/optional.hpp>
#include <cstdint>
#include <pqrs/osx/iokit_types.hpp>
#include <string>
#include <vector>

namespace krbn {
class iokit_utility final {
public:
  static boost::optional<std::string> find_string_property(io_service_t service, CFStringRef _Nonnull key) {
    if (!service) {
      return boost::none;
    }

    if (auto property = IORegistryEntrySearchCFProperty(service,
                                                        kIOServicePlane,
                                                        key,
                                                        kCFAllocatorDefault,
                                                        kIORegistryIterateRecursively | kIORegistryIterateParents)) {
      auto value = cf_utility::to_string(property);
      CFRelease(property);
      return value;
    }

    return boost::none;
  }

  static boost::optional<std::string> find_manufacturer(io_service_t service) {
    return find_string_property(service, CFSTR(kIOHIDManufacturerKey));
  }

  static boost::optional<std::string> find_product(io_service_t service) {
    return find_string_property(service, CFSTR(kIOHIDProductKey));
  }

  static boost::optional<std::string> find_serial_number(io_service_t service) {
    return find_string_property(service, CFSTR(kIOHIDSerialNumberKey));
  }

  static boost::optional<long> find_long_property(IOHIDDeviceRef _Nonnull device, CFStringRef _Nonnull key) {
    auto property = IOHIDDeviceGetProperty(device, key);
    if (!property) {
      return boost::none;
    }

    if (CFNumberGetTypeID() != CFGetTypeID(property)) {
      return boost::none;
    }

    long value = 0;
    if (!CFNumberGetValue(static_cast<CFNumberRef>(property), kCFNumberLongType, &value)) {
      return boost::none;
    }

    return value;
  }

  static boost::optional<std::string> find_string_property(IOHIDDeviceRef _Nonnull device, CFStringRef _Nonnull key) {
    auto property = IOHIDDeviceGetProperty(device, key);
    return cf_utility::to_string(property);
  }

  static boost::optional<long> find_max_input_report_size(IOHIDDeviceRef _Nonnull device) {
    return find_long_property(device, CFSTR(kIOHIDMaxInputReportSizeKey));
  }

  static vendor_id find_vendor_id(IOHIDDeviceRef _Nonnull device) {
    if (auto value = find_long_property(device, CFSTR(kIOHIDVendorIDKey))) {
      return static_cast<vendor_id>(*value);
    }
    return vendor_id(0);
  }

  static product_id find_product_id(IOHIDDeviceRef _Nonnull device) {
    if (auto value = find_long_property(device, CFSTR(kIOHIDProductIDKey))) {
      return static_cast<product_id>(*value);
    }
    return product_id(0);
  }

  static boost::optional<location_id> find_location_id(IOHIDDeviceRef _Nonnull device) {
    if (auto value = find_long_property(device, CFSTR(kIOHIDLocationIDKey))) {
      return static_cast<location_id>(*value);
    }
    return boost::none;
  }

  static boost::optional<std::string> find_manufacturer(IOHIDDeviceRef _Nonnull device) {
    return find_string_property(device, CFSTR(kIOHIDManufacturerKey));
  }

  static boost::optional<std::string> find_product(IOHIDDeviceRef _Nonnull device) {
    return find_string_property(device, CFSTR(kIOHIDProductKey));
  }

  static boost::optional<std::string> find_serial_number(IOHIDDeviceRef _Nonnull device) {
    return find_string_property(device, CFSTR(kIOHIDSerialNumberKey));
  }

  static boost::optional<std::string> find_transport(IOHIDDeviceRef _Nonnull device) {
    return find_string_property(device, CFSTR(kIOHIDTransportKey));
  }

  static bool is_keyboard(IOHIDDeviceRef _Nonnull device) {
    return IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard);
  }

  static bool is_pointing_device(IOHIDDeviceRef _Nonnull device) {
    return IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Pointer) ||
           IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse);
  }

  static bool is_karabiner_virtual_hid_device(IOHIDDeviceRef _Nonnull device) {
    if (auto manufacturer = find_manufacturer(device)) {
      if (*manufacturer == "pqrs.org") {
        return true;
      }
    }

    return false;
  }

  static void log_matching_device(pqrs::osx::iokit_registry_entry_id registry_entry_id,
                                  IOHIDDeviceRef _Nonnull device) {
    logger::get_logger().info("matching device:");
    logger::get_logger().info("  registry_entry_id: {0}", type_safe::get(registry_entry_id));

    if (auto manufacturer = find_manufacturer(device)) {
      logger::get_logger().info("  manufacturer: {0}", *manufacturer);
    }
    if (auto product = find_product(device)) {
      logger::get_logger().info("  product: {0}", *product);
    }
    logger::get_logger().info("  vendor_id: {0}", static_cast<uint32_t>(find_vendor_id(device)));
    logger::get_logger().info("  product_id: {0}", static_cast<uint32_t>(find_product_id(device)));
    if (auto location_id = find_location_id(device)) {
      logger::get_logger().info("  location_id: {0:#x}", static_cast<uint32_t>(*location_id));
    }
    if (auto serial_number = find_serial_number(device)) {
      logger::get_logger().info("  serial_number: {0}", *serial_number);
    }
    logger::get_logger().info("  is_keyboard: {0}", is_keyboard(device));
    logger::get_logger().info("  is_pointing_device: {0}", is_pointing_device(device));
  }
};
} // namespace krbn
<commit_msg>remove unused methods<commit_after>#pragma once

#include "cf_utility.hpp"
#include "logger.hpp"
#include "types.hpp"
#include <IOKit/IOKitLib.h>
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDKeys.h>
#include <cstdint>
#include <pqrs/osx/iokit_hid_device.hpp>
#include <pqrs/string.hpp>
#include <string>
#include <vector>

namespace krbn {
class iokit_utility final {
public:
  static bool is_keyboard(IOHIDDeviceRef _Nonnull device) {
    if (device) {
      return IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Keyboard);
    }
    return false;
  }

  static bool is_pointing_device(IOHIDDeviceRef _Nonnull device) {
    if (device) {
      return IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Pointer) ||
             IOHIDDeviceConformsTo(device, kHIDPage_GenericDesktop, kHIDUsage_GD_Mouse);
    }
    return false;
  }

  static bool is_karabiner_virtual_hid_device(IOHIDDeviceRef _Nonnull device) {
    pqrs::osx::iokit_hid_device hid_device(device);

    if (auto manufacturer = hid_device.find_manufacturer()) {
      if (*manufacturer == "pqrs.org") {
        return true;
      }
    }

    return false;
  }

  static std::string make_device_name_for_log(device_id device_id,
                                              IOHIDDeviceRef _Nonnull device) {
    std::stringstream stream;
    pqrs::osx::iokit_hid_device hid_device(device);

    if (auto product_name = hid_device.find_product()) {
      stream << pqrs::string::trim_copy(*product_name);
    } else {
      if (auto vendor_id = hid_device.find_vendor_id()) {
        if (auto product_id = hid_device.find_product_id()) {
          stream << std::hex
                 << "(vendor_id:0x" << type_safe::get(*vendor_id)
                 << ", product_id:0x" << type_safe::get(*product_id)
                 << ")"
                 << std::dec;
        }
      }
    }

    stream << " (device_id:" << type_safe::get(device_id) << ")";
    return stream.str();
  }

  static void log_matching_device(pqrs::osx::iokit_registry_entry_id registry_entry_id,
                                  IOHIDDeviceRef _Nonnull device) {
    pqrs::osx::iokit_hid_device hid_device(device);

    logger::get_logger().info("matching device:");
    logger::get_logger().info("  registry_entry_id: {0}", type_safe::get(registry_entry_id));

    if (auto manufacturer = hid_device.find_manufacturer()) {
      logger::get_logger().info("  manufacturer: {0}", *manufacturer);
    }
    if (auto product = hid_device.find_product()) {
      logger::get_logger().info("  product: {0}", *product);
    }
    if (auto vendor_id = hid_device.find_vendor_id()) {
      logger::get_logger().info("  vendor_id: {0}", type_safe::get(*vendor_id));
    }
    if (auto product_id = hid_device.find_product_id()) {
      logger::get_logger().info("  product_id: {0}", type_safe::get(*product_id));
    }
    if (auto location_id = hid_device.find_location_id()) {
      logger::get_logger().info("  location_id: {0:#x}", type_safe::get(*location_id));
    }
    if (auto serial_number = hid_device.find_serial_number()) {
      logger::get_logger().info("  serial_number: {0}", *serial_number);
    }
    logger::get_logger().info("  is_keyboard: {0}", is_keyboard(device));
    logger::get_logger().info("  is_pointing_device: {0}", is_pointing_device(device));
  }
};
} // namespace krbn
<|endoftext|>