<commit_before>#include <igl/circulation.h>
#include <igl/collapse_edge.h>
#include <igl/edge_flaps.h>
#include <igl/read_triangle_mesh.h>
#include <igl/Viewer/viewer.h>
#include <Eigen/Core>
#include <iostream>
#include <set>

int main(int argc, char * argv[])
{
  using namespace std;
  using namespace Eigen;
  using namespace igl;
  cout<<"Usage: ./progressive_hulls [filename.(off|obj|ply)]"<<endl;
  cout<<"  [space]  toggle animation."<<endl;
  cout<<"  'r'  reset."<<endl;
  // Load a closed manifold mesh
  string filename("../shared/fertility.off");
  if(argc>=2)
  {
    filename = argv[1];
  }
  MatrixXd V,OV;
  MatrixXi F,OF;
  read_triangle_mesh(filename,OV,OF);

  igl::viewer::Viewer viewer;

  // Prepare array-based edge data structures and priority queue
  VectorXi EMAP;
  MatrixXi E,EF,EI;
  typedef std::set<std::pair<double,int> > PriorityQueue;
  PriorityQueue Q;
  std::vector<PriorityQueue::iterator > Qit;
  // If an edge were collapsed, we'd collapse it to these points:
  MatrixXd C;
  int num_collapsed;

  // Function for computing cost of collapsing edge (lenght) and placement
  // (midpoint)
  const auto & shortest_edge_and_midpoint = [](
    const int e,
    const Eigen::MatrixXd & V,
    const Eigen::MatrixXi & /*F*/,
    const Eigen::MatrixXi & E,
    const Eigen::VectorXi & /*EMAP*/,
    const Eigen::MatrixXi & /*EF*/,
    const Eigen::MatrixXi & /*EI*/,
    double & cost,
    RowVectorXd & p)
  {
    cost = (V.row(E(e,0))-V.row(E(e,1))).norm();
    p = 0.5*(V.row(E(e,0))+V.row(E(e,1)));
  };

  // Function to reset original mesh and data structures
  const auto & reset = [&]()
  {
    F = OF;
    V = OV;
    edge_flaps(F,E,EMAP,EF,EI);
    Qit.resize(E.rows());

    C.resize(E.rows(),V.cols());
    VectorXd costs(E.rows());
    for(int e = 0;e<E.rows();e++)
    {
      double cost = e;
      RowVectorXd p(1,3);
      shortest_edge_and_midpoint(e,V,F,E,EMAP,EF,EI,cost,p);
      C.row(e) = p;
      Qit[e] = Q.insert(std::pair<double,int>(cost,e)).first;
    }
    num_collapsed = 0;
    viewer.data.clear();
    viewer.data.set_mesh(V,F);
    viewer.data.set_face_based(true);
  };

  const auto &pre_draw = [&](igl::viewer::Viewer & viewer)->bool
  {
    // If animating then collapse 10% of edges
    if(viewer.core.is_animating && !Q.empty())
    {
      bool something_collapsed = false;
      // collapse edge
      const int max_iter = std::ceil(0.01*Q.size());
      for(int j = 0;j<max_iter;j++)
      {
        if(!collapse_edge(shortest_edge_and_midpoint,V,F,E,EMAP,EF,EI,Q,Qit,C))
        {
          break;
        }
        something_collapsed = true;
        num_collapsed++;
      }

      if(something_collapsed)
      {
        viewer.data.clear();
        viewer.data.set_mesh(V,F);
        viewer.data.set_face_based(true);
      }
    }
    return false;
  };

  const auto &key_down =
    [&](igl::viewer::Viewer &viewer,unsigned char key,int mod)->bool
  {
    switch(key)
    {
      case ' ':
        viewer.core.is_animating ^= 1;
        break;
      case 'R':
      case 'r':
        reset();
        break;
      default:
        return false;
    }
    return true;
  };

  reset();
  viewer.core.is_animating = true;
  viewer.callback_key_down = key_down;
  viewer.callback_pre_draw = pre_draw;
  return viewer.launch();
}
<commit_msg>fixed wrong include in 701<commit_after>#include <igl/circulation.h>
#include <igl/collapse_edge.h>
#include <igl/edge_flaps.h>
#include <igl/read_triangle_mesh.h>
#include <igl/viewer/Viewer.h>
#include <Eigen/Core>
#include <iostream>
#include <set>

int main(int argc, char * argv[])
{
  using namespace std;
  using namespace Eigen;
  using namespace igl;
  cout<<"Usage: ./progressive_hulls [filename.(off|obj|ply)]"<<endl;
  cout<<"  [space]  toggle animation."<<endl;
  cout<<"  'r'  reset."<<endl;
  // Load a closed manifold mesh
  string filename("../shared/fertility.off");
  if(argc>=2)
  {
    filename = argv[1];
  }
  MatrixXd V,OV;
  MatrixXi F,OF;
  read_triangle_mesh(filename,OV,OF);

  igl::viewer::Viewer viewer;

  // Prepare array-based edge data structures and priority queue
  VectorXi EMAP;
  MatrixXi E,EF,EI;
  typedef std::set<std::pair<double,int> > PriorityQueue;
  PriorityQueue Q;
  std::vector<PriorityQueue::iterator > Qit;
  // If an edge were collapsed, we'd collapse it to these points:
  MatrixXd C;
  int num_collapsed;

  // Function for computing cost of collapsing edge (lenght) and placement
  // (midpoint)
  const auto & shortest_edge_and_midpoint = [](
    const int e,
    const Eigen::MatrixXd & V,
    const Eigen::MatrixXi & /*F*/,
    const Eigen::MatrixXi & E,
    const Eigen::VectorXi & /*EMAP*/,
    const Eigen::MatrixXi & /*EF*/,
    const Eigen::MatrixXi & /*EI*/,
    double & cost,
    RowVectorXd & p)
  {
    cost = (V.row(E(e,0))-V.row(E(e,1))).norm();
    p = 0.5*(V.row(E(e,0))+V.row(E(e,1)));
  };

  // Function to reset original mesh and data structures
  const auto & reset = [&]()
  {
    F = OF;
    V = OV;
    edge_flaps(F,E,EMAP,EF,EI);
    Qit.resize(E.rows());

    C.resize(E.rows(),V.cols());
    VectorXd costs(E.rows());
    for(int e = 0;e<E.rows();e++)
    {
      double cost = e;
      RowVectorXd p(1,3);
      shortest_edge_and_midpoint(e,V,F,E,EMAP,EF,EI,cost,p);
      C.row(e) = p;
      Qit[e] = Q.insert(std::pair<double,int>(cost,e)).first;
    }
    num_collapsed = 0;
    viewer.data.clear();
    viewer.data.set_mesh(V,F);
    viewer.data.set_face_based(true);
  };

  const auto &pre_draw = [&](igl::viewer::Viewer & viewer)->bool
  {
    // If animating then collapse 10% of edges
    if(viewer.core.is_animating && !Q.empty())
    {
      bool something_collapsed = false;
      // collapse edge
      const int max_iter = std::ceil(0.01*Q.size());
      for(int j = 0;j<max_iter;j++)
      {
        if(!collapse_edge(shortest_edge_and_midpoint,V,F,E,EMAP,EF,EI,Q,Qit,C))
        {
          break;
        }
        something_collapsed = true;
        num_collapsed++;
      }

      if(something_collapsed)
      {
        viewer.data.clear();
        viewer.data.set_mesh(V,F);
        viewer.data.set_face_based(true);
      }
    }
    return false;
  };

  const auto &key_down =
    [&](igl::viewer::Viewer &viewer,unsigned char key,int mod)->bool
  {
    switch(key)
    {
      case ' ':
        viewer.core.is_animating ^= 1;
        break;
      case 'R':
      case 'r':
        reset();
        break;
      default:
        return false;
    }
    return true;
  };

  reset();
  viewer.core.is_animating = true;
  viewer.callback_key_down = key_down;
  viewer.callback_pre_draw = pre_draw;
  return viewer.launch();
}
<|endoftext|>


<commit_before>af508b0f-4b02-11e5-9ac4-28cfe9171a43<commit_msg>This'll fix that<commit_after>af5e1128-4b02-11e5-8d98-28cfe9171a43<|endoftext|>


<commit_before>class CfgVehicles {
	class Logic;
	class Module_F: Logic {
		class ArgumentsBaseUnits {
			class Units;
		};
		class ModuleDescription {
			class AnyBrain;
		};
	};

	class thingX;

	class HEHU_MF_Module: Module_F
	{
		scope = 0;
		author = "Magnus Bergmark";
		category = "HEHU_MF_Modules";
	};

	class HEHU_MF_ModuleCQBSpawner: HEHU_MF_Module
	{
		displayName = "CQB Spawner";
		author = "Magnus Bergmark";
		scope = 2;
		function = "HEHU_MF_fnc_moduleCQBSpawner";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 1;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 0;

		isTriggerActivated = 0;
		isDisposable = 1;

		class Arguments
		{
			// Module specific arguments
			class NumberOfUnits
  			{
				displayName = "Number of units";
				description = "0 means choose from global config / script variable.";
				typeName = "NUMBER";
				defaultValue = "0";
			};
			class UnitAlertness
  			{
				displayName = "Unit alertness";
				typeName = "NUMBER";
				class values
				{
					class UseDefault		{name = "Use global config"; value = -1; default = 1;};
					class StandStill		{name = "Stand still"; value = 0;};
					class RespondThreats	{name = "Respond to threats"; value = 1;};
					class SomePatrol		{name = "Some will patrol"; value = 2;};
					class MostPatrol		{name = "Most will patrol"; value = 3;};
					class AllPatrol			{name = "Everyone patrols"; value = 4;};
				};
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Spawns units in random building positions.";
			sync[] = {"LocationArea_F", "LocationBase_F"};

			class LocationArea_F
			{
				description[] = { // Multi-line descriptions are supported
					"CQB area, with independent unit combinations and positions.",
					"Positions will be of building positions of buildings inside the triggers."
				};
				position = 0; // Position is taken into effect
				direction = 0; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
				sync[] = {"EmptyDetector", "AnyAI"};
			};

			class LocationBase_F
			{
				description[] = { // Multi-line descriptions are supported
					"CQB area, with independent unit combinations and positions.",
					"Positions will be of random places in the triggers."
				};
				position = 0; // Position is taken into effect
				direction = 0; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
				sync[] = {"EmptyDetector", "AnyAI"};
			};

			class EmptyDetector
			{
				description[] = {
					"Trigger areas",
					"Buildings inside the areas will be candidates for unit placements."
				};
				position = 1; // Position is taken into effect
				direction = 1; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
			};
		};
	};

	class HEHU_MF_ModuleTargetCounter: HEHU_MF_Module
	{
		displayName = "Target counter";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleTargetCounter";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 0;
		isDisposable = 1;

		class Arguments: ArgumentsBaseUnits
		{
			class Units: Units {};

			// Module specific arguments
			class Precision
  			{
				displayName = "Precision";
				description = "How accurate the counter will be.";
				typeName = "NUMBER";
				class values
				{
					class Exact		{name = "Exact (number of enemies)"; value = 1; default = 1};
					class Inexact	{name = "Inexact (few, many, etc.)"; value = 2;};
					class Unhelpful	{name = "Unhelpful (enemies left, no enemies left)"; value = 3;};
				};
			};
			class RefreshInterval
  			{
				displayName = "Refresh interval";
				typeName = "NUMBER";
				class values
				{
					class 100ms	{name = "100ms"; value = 0.1;};
					class 1s	{name = "1s"; value = 1;};
					class 2s	{name = "2s"; value = 2; default = 1};
					class 3s	{name = "3s"; value = 3;};
					class 4s	{name = "4s"; value = 4;};
					class 5s	{name = "5s"; value = 5;};
				};
			};
			class AutoHide
  			{
				displayName = "Stop when no enemies left";
				description = "Should target counter disappear when no enemies are left?";
				typeName = "BOOL";
				defaultValue = false;
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Shows number of enemies left to synchronized (or all) players.";
			sync[] = {"AnyPlayer"};
		};
	};

	class HEHU_MF_ModuleUnitLocator: HEHU_MF_Module
	{
		displayName = "Unit locator";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleUnitLocator";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 1;
		isDisposable = 0;

		class Arguments: ArgumentsBaseUnits
		{
			class Units: Units {};

			// Module specific arguments
			class Precision
  			{
				displayName = "Precision";
				description = "How precise should the locator be.";
				typeName = "NUMBER";
				class values
				{
					/*
						Note that the value is the RADIUS of the circle; "20m" precision sounds
						like 20m DIAMETER so value is half that of the description says.
						"I know you precision within 20 meters" sound like +- 10 meters, as the
						search span is 20 meters.
					*/
					class Exact          {name = "Exact"; value = 0;};
					class Accurate       {name = "Accurate (5m)"; value = 2.5; default = 1};
					class Inaccurate     {name = "Inaccurate (20m)"; value = 10;};
					class VeryInaccurate {name = "Very inaccurate (50m)"; value = 25;};
					class WayOff         {name = "Way off (500m)"; value = 250;};
				};
			};
			class RefreshInterval
  			{
				displayName = "Refresh interval";
				typeName = "NUMBER";
				class values
				{
					class 250ms	{name = "250ms"; value = 0.25;};
					class 500ms	{name = "500ms"; value = 0.5;};
					class 1s	{name = "1s"; value = 1;};
					class 2s	{name = "2s"; value = 2; default = 1};
					class 3s	{name = "3s"; value = 3;};
					class 4s	{name = "4s"; value = 4;};
					class 5s	{name = "5s"; value = 5;};
				};
			};

			class NumberOfUnits
  			{
				displayName = "Maximum units alive";
				description = "Only display after this amount of units are alive. (Counts all selected unit types; enter 0 for Always)";
				typeName = "NUMBER";
				defaultValue = 2;
			};

			class LocatorType
  			{
				displayName = "Type";
				description = "How should the enemies be located?";
				typeName = "NUMBER";
				class values
				{
					class Markers {name = "Markers"; value = 1; default = 1};
					// TODO: Add more locator types
				};
			};

			class LocateUnits
  			{
				displayName = "Units to locate";
				description = "What kinds of units should be located?";
				typeName = "NUMBER";
				class values
				{
					class NonPlayers {name = "Non-players"; value = 1;};
					class Players    {name = "Players"; value = 2;};
					class Enemies    {name = "Enemies"; value = 3; default = 1};
					class Civilians  {name = "Civilians"; value = 4;};
					class West       {name = "BLUFOR"; value = 5;};
					class East       {name = "OPFOR"; value = 6;};
					class Ind        {name = "Idenpendent"; value = 7;};
					class Everyone   {name = "Everyone"; value = 8;};
				};
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Shows alive units to synchronized (or all) players.";
			sync[] = {"AnyPlayer"};
		};
	};

	class HEHU_MF_ModuleAutomaticEndGame: HEHU_MF_Module
	{
		displayName = "Automatic end game";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleAutomaticEndGame";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 1;
		isDisposable = 1;

		class ModuleDescription: ModuleDescription
		{
			description = "Ends the mission when all enemies are dead (and optional triggers are activated).";
			sync[] = {};
		};
	};

	class HEHU_MF_ArsenalBox: thingX
	{
		// Don't inherit from a real ammo box to remove the vanilla inventory from them.
		// You can only interact with this box as a Virtual Arsenal object.
		//
		// class thingX;
		//   class ReammoBox_F;
		//      class Box_NATO_Wps_F;
		//
		// TODO: Make it possible to sling load this box, or make a variant that is.

		vehicleclass = "Ammo";  // ReammoBox_F
		animated = 0;           // ReammoBox_F
		accuracy = 0.2;         // ReammoBox_F
		icon = "iconCrateWpns"; // Box_NATO_Wps_F
		mapsize = 1.81;         // Box_NATO_Wps_F
		model = "\A3\weapons_F\AmmoBoxes\WpnsBox_F"; // Box_NATO_Wps_F

		displayName = "HEHU Ammo box";
		author = "Magnus Bergmark";
		scope = 2;
		class Eventhandlers
		{
			init = "[""AmmoboxInit"",[(_this select 0), true]] spawn BIS_fnc_arsenal;";
		};
	};
};
<commit_msg>Fix Zero Divisor error<commit_after>class CfgVehicles {
	class Logic;
	class Module_F: Logic {
		class ArgumentsBaseUnits {
			class Units;
		};
		class ModuleDescription {
			class AnyBrain;
		};
	};

	class thingX;

	class HEHU_MF_Module: Module_F
	{
		scope = 0;
		author = "Magnus Bergmark";
		category = "HEHU_MF_Modules";
	};

	class HEHU_MF_ModuleCQBSpawner: HEHU_MF_Module
	{
		displayName = "CQB Spawner";
		author = "Magnus Bergmark";
		scope = 2;
		function = "HEHU_MF_fnc_moduleCQBSpawner";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 1;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 0;

		isTriggerActivated = 0;
		isDisposable = 0;

		class Arguments
		{
			// Module specific arguments
			class NumberOfUnits
  			{
				displayName = "Number of units";
				description = "0 means choose from global config / script variable.";
				typeName = "NUMBER";
				defaultValue = "0";
			};
			class UnitAlertness
  			{
				displayName = "Unit alertness";
				typeName = "NUMBER";
				class values
				{
					class UseDefault		{name = "Use global config"; value = -1; default = 1;};
					class StandStill		{name = "Stand still"; value = 0;};
					class RespondThreats	{name = "Respond to threats"; value = 1;};
					class SomePatrol		{name = "Some will patrol"; value = 2;};
					class MostPatrol		{name = "Most will patrol"; value = 3;};
					class AllPatrol			{name = "Everyone patrols"; value = 4;};
				};
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Spawns units in random building positions.";
			sync[] = {"LocationArea_F", "LocationBase_F"};

			class LocationArea_F
			{
				description[] = { // Multi-line descriptions are supported
					"CQB area, with independent unit combinations and positions.",
					"Positions will be of building positions of buildings inside the triggers."
				};
				position = 0; // Position is taken into effect
				direction = 0; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
				sync[] = {"EmptyDetector", "AnyAI"};
			};

			class LocationBase_F
			{
				description[] = { // Multi-line descriptions are supported
					"CQB area, with independent unit combinations and positions.",
					"Positions will be of random places in the triggers."
				};
				position = 0; // Position is taken into effect
				direction = 0; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
				sync[] = {"EmptyDetector", "AnyAI"};
			};

			class EmptyDetector
			{
				description[] = {
					"Trigger areas",
					"Buildings inside the areas will be candidates for unit placements."
				};
				position = 1; // Position is taken into effect
				direction = 1; // Direction is taken into effect
				optional = 0; // Synced entity is optional
				duplicate = 1; // Multiple entities of this type can be synced
			};
		};
	};

	class HEHU_MF_ModuleTargetCounter: HEHU_MF_Module
	{
		displayName = "Target counter";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleTargetCounter";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 0;
		isDisposable = 0;

		class Arguments: ArgumentsBaseUnits
		{
			class Units: Units {};

			// Module specific arguments
			class Precision
  			{
				displayName = "Precision";
				description = "How accurate the counter will be.";
				typeName = "NUMBER";
				class values
				{
					class Exact		{name = "Exact (number of enemies)"; value = 1; default = 1};
					class Inexact	{name = "Inexact (few, many, etc.)"; value = 2;};
					class Unhelpful	{name = "Unhelpful (enemies left, no enemies left)"; value = 3;};
				};
			};
			class RefreshInterval
  			{
				displayName = "Refresh interval";
				typeName = "NUMBER";
				class values
				{
					class 100ms	{name = "100ms"; value = 0.1;};
					class 1s	{name = "1s"; value = 1;};
					class 2s	{name = "2s"; value = 2; default = 1};
					class 3s	{name = "3s"; value = 3;};
					class 4s	{name = "4s"; value = 4;};
					class 5s	{name = "5s"; value = 5;};
				};
			};
			class AutoHide
  			{
				displayName = "Stop when no enemies left";
				description = "Should target counter disappear when no enemies are left?";
				typeName = "BOOL";
				defaultValue = false;
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Shows number of enemies left to synchronized (or all) players.";
			sync[] = {"AnyPlayer"};
		};
	};

	class HEHU_MF_ModuleUnitLocator: HEHU_MF_Module
	{
		displayName = "Unit locator";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleUnitLocator";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 1;
		isDisposable = 0;

		class Arguments: ArgumentsBaseUnits
		{
			class Units: Units {};

			// Module specific arguments
			class Precision
  			{
				displayName = "Precision";
				description = "How precise should the locator be.";
				typeName = "NUMBER";
				class values
				{
					/*
						Note that the value is the RADIUS of the circle; "20m" precision sounds
						like 20m DIAMETER so value is half that of the description says.
						"I know you precision within 20 meters" sound like +- 10 meters, as the
						search span is 20 meters.
					*/
					class Exact          {name = "Exact"; value = 0;};
					class Accurate       {name = "Accurate (5m)"; value = 2.5; default = 1};
					class Inaccurate     {name = "Inaccurate (20m)"; value = 10;};
					class VeryInaccurate {name = "Very inaccurate (50m)"; value = 25;};
					class WayOff         {name = "Way off (500m)"; value = 250;};
				};
			};
			class RefreshInterval
  			{
				displayName = "Refresh interval";
				typeName = "NUMBER";
				class values
				{
					class 250ms	{name = "250ms"; value = 0.25;};
					class 500ms	{name = "500ms"; value = 0.5;};
					class 1s	{name = "1s"; value = 1;};
					class 2s	{name = "2s"; value = 2; default = 1};
					class 3s	{name = "3s"; value = 3;};
					class 4s	{name = "4s"; value = 4;};
					class 5s	{name = "5s"; value = 5;};
				};
			};

			class NumberOfUnits
  			{
				displayName = "Maximum units alive";
				description = "Only display after this amount of units are alive. (Counts all selected unit types; enter 0 for Always)";
				typeName = "NUMBER";
				defaultValue = 2;
			};

			class LocatorType
  			{
				displayName = "Type";
				description = "How should the enemies be located?";
				typeName = "NUMBER";
				class values
				{
					class Markers {name = "Markers"; value = 1; default = 1};
					// TODO: Add more locator types
				};
			};

			class LocateUnits
  			{
				displayName = "Units to locate";
				description = "What kinds of units should be located?";
				typeName = "NUMBER";
				class values
				{
					class NonPlayers {name = "Non-players"; value = 1;};
					class Players    {name = "Players"; value = 2;};
					class Enemies    {name = "Enemies"; value = 3; default = 1};
					class Civilians  {name = "Civilians"; value = 4;};
					class West       {name = "BLUFOR"; value = 5;};
					class East       {name = "OPFOR"; value = 6;};
					class Ind        {name = "Idenpendent"; value = 7;};
					class Everyone   {name = "Everyone"; value = 8;};
				};
			};
		};

		class ModuleDescription: ModuleDescription
		{
			description = "Shows alive units to synchronized (or all) players.";
			sync[] = {"AnyPlayer"};
		};
	};

	class HEHU_MF_ModuleAutomaticEndGame: HEHU_MF_Module
	{
		displayName = "Automatic end game";
		author = "Magnus Bergmark";
		scope = 2;

		function = "HEHU_MF_fnc_moduleAutomaticEndGame";
		// Execution priority, modules with lower number are executed first. 0 is used when the attribute is undefined
		functionPriority = 100;

		// 0 for server only execution, 1 for remote execution on all clients upon mission start, 2 for persistent execution
		isGlobal = 2;

		isTriggerActivated = 1;
		isDisposable = 0;

		class ModuleDescription: ModuleDescription
		{
			description = "Ends the mission when all enemies are dead (and optional triggers are activated).";
			sync[] = {};
		};
	};

	class HEHU_MF_ArsenalBox: thingX
	{
		// Don't inherit from a real ammo box to remove the vanilla inventory from them.
		// You can only interact with this box as a Virtual Arsenal object.
		//
		// class thingX;
		//   class ReammoBox_F;
		//      class Box_NATO_Wps_F;
		//
		// TODO: Make it possible to sling load this box, or make a variant that is.

		vehicleclass = "Ammo";  // ReammoBox_F
		animated = 0;           // ReammoBox_F
		accuracy = 0.2;         // ReammoBox_F
		icon = "iconCrateWpns"; // Box_NATO_Wps_F
		mapsize = 1.81;         // Box_NATO_Wps_F
		model = "\A3\weapons_F\AmmoBoxes\WpnsBox_F"; // Box_NATO_Wps_F

		displayName = "HEHU Ammo box";
		author = "Magnus Bergmark";
		scope = 2;
		class Eventhandlers
		{
			init = "[""AmmoboxInit"",[(_this select 0), true]] spawn BIS_fnc_arsenal;";
		};
	};
};
<|endoftext|>


<commit_before>/*
 * DelayTestProbe.cpp
 *
 *  Created on: October 1, 2013
 *      Author: wchavez
 */

#include "DelayTestProbe.hpp"
#include <include/pv_arch.h>
#include <layers/HyPerLayer.hpp>
#include <string.h>
#include <assert.h>

namespace PV {

DelayTestProbe::DelayTestProbe(const char * filename, HyPerLayer * layer, const char * msg)
: StatsProbe(filename, layer, msg)
{
}

DelayTestProbe::DelayTestProbe(HyPerLayer * layer, const char * msg)
: StatsProbe(layer, msg)
{
}

DelayTestProbe::~DelayTestProbe() {}

int DelayTestProbe::outputState(double timed)
{
	int status = StatsProbe::outputState(timed);
#ifdef PV_USE_MPI
   InterColComm * icComm = getTargetLayer()->getParent()->icCommunicator();
   const int rcvProc = 0;
   if( icComm->commRank() != rcvProc ) {
      return 0;
   }
#endif // PV_USE_MPI
   const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   const int rows = getTargetLayer()->getParent()->icCommunicator()->numCommRows();
   const int cols = getTargetLayer()->getParent()->icCommunicator()->numCommColumns();

      int nx = loc->nx;
      int ny = loc->ny;
      int nf = loc->nf;

      assert((avg == timed/nf)&&(avg == double(nnz)/((nx*rows)*(ny*cols)*nf)));

      return status;
}

} /* namespace PV */
<commit_msg>Changed assertions to match Movie layer update. (Line 52: timed-1 instead of timed)<commit_after>/*
 * DelayTestProbe.cpp
 *
 *  Created on: October 1, 2013
 *      Author: wchavez
 */

#include "DelayTestProbe.hpp"
#include <include/pv_arch.h>
#include <layers/HyPerLayer.hpp>
#include <string.h>
#include <assert.h>

namespace PV {

DelayTestProbe::DelayTestProbe(const char * filename, HyPerLayer * layer, const char * msg)
: StatsProbe(filename, layer, msg)
{
}

DelayTestProbe::DelayTestProbe(HyPerLayer * layer, const char * msg)
: StatsProbe(layer, msg)
{
}

DelayTestProbe::~DelayTestProbe() {}

int DelayTestProbe::outputState(double timed)
{
	int status = StatsProbe::outputState(timed);
#ifdef PV_USE_MPI
   InterColComm * icComm = getTargetLayer()->getParent()->icCommunicator();
   const int rcvProc = 0;
   if( icComm->commRank() != rcvProc ) {
      return 0;
   }
#endif // PV_USE_MPI
   const PVLayerLoc * loc = getTargetLayer()->getLayerLoc();
   const int rows = getTargetLayer()->getParent()->icCommunicator()->numCommRows();
   const int cols = getTargetLayer()->getParent()->icCommunicator()->numCommColumns();

      int nx = loc->nx;
      int ny = loc->ny;
      int nf = loc->nf;

    if (timed==0) {
        assert((avg == (timed)/nf)&&(avg == double(nnz)/((nx*rows)*(ny*cols)*nf)));
    }

    else {
        assert((avg == (timed-1)/nf)&&(avg == double(nnz)/((nx*rows)*(ny*cols)*nf)));
    }
      return status;
}

} /* namespace PV */
<|endoftext|>


<commit_before>c3dabcfa-4b02-11e5-b1b2-28cfe9171a43<commit_msg>I'm done<commit_after>c3e7979c-4b02-11e5-9645-28cfe9171a43<|endoftext|>


<commit_before>72b72521-ad5c-11e7-9a12-ac87a332f658<commit_msg>Fixed that one bug<commit_after>732dd6c2-ad5c-11e7-b662-ac87a332f658<|endoftext|>


<commit_before>a69342a3-4b02-11e5-9c0c-28cfe9171a43<commit_msg>No longer crashes if X<commit_after>a6a372f8-4b02-11e5-98d1-28cfe9171a43<|endoftext|>


<commit_before>7901d50a-2749-11e6-8a83-e0f84713e7b8<commit_msg>add file<commit_after>7910a833-2749-11e6-8d31-e0f84713e7b8<|endoftext|>


<commit_before>753f811c-2749-11e6-86fe-e0f84713e7b8<commit_msg>my cat is cute<commit_after>754fc4fa-2749-11e6-be65-e0f84713e7b8<|endoftext|>


<commit_before>/*********************************************************************
 * jacobian_cpp.cpp
 *
 * Copyright (c) 2017, ISCI / National Chiao Tung University (NCTU)
 *
 * Author: Howard Chen (s880367@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **********************************************************************/

#include <iostream>
#include <eigen3/Eigen/Dense>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <math.h>
#include <vector>
#include "tm_kinematics/include/tm_kinematics/tm_kin.h"
#include <unistd.h>
#include <sys/time.h>

#define D1 0.1451
#define D2 0
#define D3 0
#define D4 -0.1222
#define D5 0.106
#define D6 0.1144

#define A1 0
#define A2 0.329
#define A3 0.3115
#define A4 0
#define A5 0
#define A6 0

#define ALPHA1 -90
#define ALPHA2 0
#define ALPHA3 0
#define ALPHA4 90
#define ALPHA5 90
#define ALPHA6 0

#define PI 3.141592654
#define DEG2RAD 0.01745329252
#define RAD2DEG 57.29577951

using namespace std;

void help()
{
    printf("\n");
	printf("* PLease enter the argument in the following format : \n");
	printf("* option : IJ = inverse jacobian\n");
	printf("*          IK = inverse kinematics\n");
	printf("*          FJ = forward jacobian\n");
	printf("*          FK = forward kinematics\n");
	printf("*          FJG = forward jacobian with gripper\n");
	printf("*          FKG = forward kinematics with gripper\n");
	printf("* IJ: ./tm_jacobian IJ q1 q2 q3 q4 q5 q6 x' y' z' a' b' c' \n");
	printf("* IK: ./tm_jacobian IK x y z a b c\n");
	printf("* FJ: ./tm_jacobian FJ q1 q2 q3 q4 q5 q6 qd1 qd2 qd3 qd4 qd5 qd6 \n");
	printf("* FK: ./tm_jacobian FK q1 q2 q3 q4 q5 q6 \n");
	printf("* Input  dim: joint(radius), cartesian(m)\n");
	printf("* Output dim: joint(radius), cartesian(m)\n");
	printf("\n");
}

int main(int argc, char const *argv[])
{
	double *q_inv, *q_forward, *T;

	q_inv = new double[48];
	q_forward = new double[6];
	T = new double[16];

	Eigen::Matrix<float, 6, 1> jointspd = Eigen::Matrix<float, 6, 1>::Zero();
	Eigen::Matrix<float, 6, 1> effspd = Eigen::Matrix<float, 6, 1>::Zero();
	Eigen::Matrix<float, 6, 1> q_AfterHomeOffset, q_BeforeHomeOffset;
	Eigen::Matrix<float, 6, 1> home;

	home << 0, -PI*0.5, 0, PI*0.5, 0, 0;
/*
	double *q_test = new double [2];
	q_test[0] = 45*DEG2RAD;
	q_test[1] = 45*DEG2RAD;

	tm_jacobian::Forward_Kinematics_3(q_test, T);
	cout << ">>>> forward T" << endl;
	tm_jacobian::printMatrix(T,4,16);

	delete [] q_test;
*/

	if(strncmp(argv[1],"--help",6) == 0)
	{
		help();
		return 0;
	}

	q_BeforeHomeOffset << 	strtod(argv[2],NULL),
							strtod(argv[3],NULL),
							strtod(argv[4],NULL),
							strtod(argv[5],NULL),
							strtod(argv[6],NULL),
							strtod(argv[7],NULL);

	q_AfterHomeOffset = q_BeforeHomeOffset + home;

	if(strncmp(argv[1],"IJ",2) == 0) // inverse jacobian
	{
		effspd << 			strtod(argv[8],NULL),
							strtod(argv[9],NULL),
							strtod(argv[10],NULL),
							strtod(argv[11],NULL),
							strtod(argv[12],NULL),
							strtod(argv[13],NULL);

		Eigen::Matrix<float, 6, 6> Inverse_Jacobian = tm_jacobian::Inverse_Jacobian(q_AfterHomeOffset);
		jointspd = Inverse_Jacobian*effspd;
		cout << ">>>> Inverse jacobian" << endl;
		tm_jacobian::printMatrix(Inverse_Jacobian);

		cout << ">>>> joint speed" << endl;
		tm_jacobian::printMatrix(jointspd);
	}
	else if(strncmp(argv[1],"IK",2) == 0)    // inverse kinematics
	{
		Eigen::Matrix<float, 6, 1>CartesianPosition = q_BeforeHomeOffset;
		Eigen::Matrix<float, 4, 4> T_;
	    Eigen::AngleAxisf rollAngle (CartesianPosition(3), Eigen::Vector3f::UnitZ());
	    Eigen::AngleAxisf yawAngle  (CartesianPosition(4), Eigen::Vector3f::UnitY());
	    Eigen::AngleAxisf pitchAngle(CartesianPosition(5), Eigen::Vector3f::UnitX());
	    Eigen::Quaternion<float> quaternion_matrix = rollAngle * yawAngle * pitchAngle;
	    Eigen::Matrix<float,3,3> RotationMatrix    = quaternion_matrix.matrix();
	    int num_sol;

	    T_ <<   0., 0., 0., CartesianPosition(0),
	            0., 0., 0., CartesianPosition(1),
	            0., 0., 0., CartesianPosition(2),
	            0., 0., 0., 1.;
	    T_.block<3,3>(0,0) = RotationMatrix.block<3,3>(0,0);

	    if(strncmp(argv[1],"IKG",3) == 0)
	    {
		    Eigen::Matrix<float,4,4> T67, T06;
			T67 <<  1, 0, 0, 0,
					0, 1, 0, 0,
					0, 0, 1, 0.235,
					0, 0, 0, 1;

			T06 = T_*T67.inverse();
		    tm_jacobian::Matrix2DoubleArray(T06,T);
		   	num_sol =  tm_kinematics::inverse(T, q_inv);
		   	cout << ">>>> T07 " << endl;
	    	tm_jacobian::printMatrix(T_);
		}
		else
		{
			tm_jacobian::Matrix2DoubleArray(T_,T);
			num_sol =  tm_kinematics::inverse(T, q_inv);
		}

	    cout << ">>>> T06 " << endl;
	    tm_jacobian::printMatrix(T,4,16);
	    cout << ">>>> inverse q number of sols T06 : " << num_sol << endl;
		tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
	}
	else if(strncmp(argv[1],"FJ",2) == 0)    // forward jacobian
	{
		if(strncmp(argv[1],"FJG",3) == 0)
		{
			Eigen::Matrix<double, 6, 1> JointVelocity    = Eigen::Matrix<double, 6, 1>::Zero();
			Eigen::Matrix<double, 6, 1> EFFVelocity      = Eigen::Matrix<double, 6, 1>::Zero();
			Eigen::Matrix<double, 6, 6> Jacobian_gripper = tm_jacobian::Forward_Jacobian_gripper(q_AfterHomeOffset);
			JointVelocity << 	strtod(argv[8],NULL),
								strtod(argv[9],NULL),
								strtod(argv[10],NULL),
								strtod(argv[11],NULL),
								strtod(argv[12],NULL),
								strtod(argv[13],NULL);
			EFFVelocity = Jacobian_gripper*JointVelocity;

			cout << ">>>> jacobian" << endl;
			tm_jacobian::printMatrixd(Jacobian_gripper);
			cout << ">>>> effspd speed" << endl;
			tm_jacobian::printMatrixd(EFFVelocity);
		}
		else
		{
			jointspd << 		strtod(argv[8],NULL),
								strtod(argv[9],NULL),
								strtod(argv[10],NULL),
								strtod(argv[11],NULL),
								strtod(argv[12],NULL),
								strtod(argv[13],NULL);

			Eigen::Matrix<float, 6, 6> Jacobian = tm_jacobian::Forward_Jacobian(q_AfterHomeOffset);
			effspd = Jacobian*jointspd;
			cout << ">>>> jacobian" << endl;
			tm_jacobian::printMatrix(Jacobian);

			cout << ">>>> effspd speed" << endl;
			tm_jacobian::printMatrix(effspd);
		}
	}
	else if(strncmp(argv[1],"FK",2) == 0)    // forward kinematics
	{
		if(strncmp(argv[1],"FKG",3) == 0)
		{
			Eigen::Matrix<double,4,4> T07, T67, T06;
			T67 <<  1, 0, 0, 0,
					0, 1, 0, 0,
					0, 0, 1, 0.235,
					0, 0, 0, 1;

			tm_jacobian::Matrix2DoubleArray(q_BeforeHomeOffset, q_forward);
			tm_jacobian::Forward_Kinematics_gripper(q_forward,T);

			for (int i = 0; i < 4; ++i)
				for (int j = 0; j < 4; ++j)
					T07(i,j) = T[4*i+j];

			T06 = T07*T67.inverse();

			for (int i = 0; i < 4; ++i)
				for (int j = 0; j < 4; ++j)
					T[4*i+j] = T06(i,j);

			int num_sol = tm_kinematics::inverse(T, q_inv, q_forward);

			cout << ">>>> T07 " << endl;
	    	tm_jacobian::printMatrixd(T07);
	    	cout << ">>>> T06 " << endl;
	    	tm_jacobian::printMatrixd(T06);
			cout << ">>>> inverse q number of sols for T06 : " << num_sol << endl;
			tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
		}
		else
		{
			tm_jacobian::Matrix2DoubleArray(q_BeforeHomeOffset, q_forward);
			tm_kinematics::forward(q_forward, T);
			int num_sol = tm_kinematics::inverse(T, q_inv, q_forward);

			cout << ">>>> T06" << endl;
			tm_jacobian::printMatrix(T,4,16);
			cout << ">>>> inverse q number of sols : " << num_sol << endl;
			tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
		}
	}
	else if(strncmp(argv[1],"TT",2) == 0)
	{
		double *q_test = new double [3];
		q_test[0] = 0;
		q_test[1] = 0;
		q_test[2] = 0;

		tm_jacobian::Forward_Kinematics_3(q_test, T);
		cout << ">>>> forward T" << endl;
		tm_jacobian::printMatrix(T,4,16);

		delete [] q_test;

	}

	delete [] T;
	delete [] q_inv;
	delete [] q_forward;
	return 0;
}
<commit_msg>change IK input format<commit_after>/*********************************************************************
 * jacobian_cpp.cpp
 *
 * Copyright (c) 2017, ISCI / National Chiao Tung University (NCTU)
 *
 * Author: Howard Chen (s880367@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 **********************************************************************/

#include <iostream>
#include <eigen3/Eigen/Dense>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <math.h>
#include <vector>
#include "tm_kinematics/include/tm_kinematics/tm_kin.h"
#include <unistd.h>
#include <sys/time.h>

#define D1 0.1451
#define D2 0
#define D3 0
#define D4 -0.1222
#define D5 0.106
#define D6 0.1144

#define A1 0
#define A2 0.329
#define A3 0.3115
#define A4 0
#define A5 0
#define A6 0

#define ALPHA1 -90
#define ALPHA2 0
#define ALPHA3 0
#define ALPHA4 90
#define ALPHA5 90
#define ALPHA6 0

#define PI 3.141592654
#define DEG2RAD 0.01745329252
#define RAD2DEG 57.29577951

using namespace std;

void help()
{
    printf("\n");
	printf("* PLease enter the argument in the following format : \n");
	printf("* option : IJ = inverse jacobian\n");
	printf("*          IK = inverse kinematics\n");
	printf("*          FJ = forward jacobian\n");
	printf("*          FK = forward kinematics\n");
	printf("*          FJG = forward jacobian with gripper\n");
	printf("*          FKG = forward kinematics with gripper\n");
	printf("* IJ: ./tm_jacobian IJ q1 q2 q3 q4 q5 q6 x' y' z' a' b' c' \n");
	printf("* IK: ./tm_jacobian IK x y z rz ry rx\n");
	printf("* FJ: ./tm_jacobian FJ q1 q2 q3 q4 q5 q6 qd1 qd2 qd3 qd4 qd5 qd6 \n");
	printf("* FK: ./tm_jacobian FK q1 q2 q3 q4 q5 q6 \n");
	printf("* Input  dim: joint(radius), cartesian(m)\n");
	printf("* Output dim: joint(radius), cartesian(m)\n");
	printf("\n");
}

int main(int argc, char const *argv[])
{
	double *q_inv, *q_forward, *T;

	q_inv = new double[48];
	q_forward = new double[6];
	T = new double[16];

	Eigen::Matrix<float, 6, 1> jointspd = Eigen::Matrix<float, 6, 1>::Zero();
	Eigen::Matrix<float, 6, 1> effspd = Eigen::Matrix<float, 6, 1>::Zero();
	Eigen::Matrix<float, 6, 1> q_AfterHomeOffset, q_BeforeHomeOffset;
	Eigen::Matrix<float, 6, 1> home;

	home << 0, -PI*0.5, 0, PI*0.5, 0, 0;
/*
	double *q_test = new double [2];
	q_test[0] = 45*DEG2RAD;
	q_test[1] = 45*DEG2RAD;

	tm_jacobian::Forward_Kinematics_3(q_test, T);
	cout << ">>>> forward T" << endl;
	tm_jacobian::printMatrix(T,4,16);

	delete [] q_test;
*/

	if(strncmp(argv[1],"--help",6) == 0)
	{
		help();
		return 0;
	}

	q_BeforeHomeOffset << 	strtod(argv[2],NULL),
							strtod(argv[3],NULL),
							strtod(argv[4],NULL),
							strtod(argv[5],NULL),
							strtod(argv[6],NULL),
							strtod(argv[7],NULL);

	q_AfterHomeOffset = q_BeforeHomeOffset + home;

	if(strncmp(argv[1],"IJ",2) == 0) // inverse jacobian
	{
		effspd << 			strtod(argv[8],NULL),
							strtod(argv[9],NULL),
							strtod(argv[10],NULL),
							strtod(argv[11],NULL),
							strtod(argv[12],NULL),
							strtod(argv[13],NULL);

		Eigen::Matrix<float, 6, 6> Inverse_Jacobian = tm_jacobian::Inverse_Jacobian(q_AfterHomeOffset);
		jointspd = Inverse_Jacobian*effspd;
		cout << ">>>> Inverse jacobian" << endl;
		tm_jacobian::printMatrix(Inverse_Jacobian);

		cout << ">>>> joint speed" << endl;
		tm_jacobian::printMatrix(jointspd);
	}
	else if(strncmp(argv[1],"IK",2) == 0)    // inverse kinematics
	{
		Eigen::Matrix<float, 6, 1>CartesianPosition = q_BeforeHomeOffset;
		Eigen::Matrix<float, 4, 4> T_;
	    Eigen::AngleAxisf rollAngle (CartesianPosition(3), Eigen::Vector3f::UnitZ());
	    Eigen::AngleAxisf yawAngle  (CartesianPosition(4), Eigen::Vector3f::UnitY());
	    Eigen::AngleAxisf pitchAngle(CartesianPosition(5), Eigen::Vector3f::UnitX());
	    Eigen::Quaternion<float> quaternion_matrix = rollAngle * yawAngle * pitchAngle;
	    Eigen::Matrix<float,3,3> RotationMatrix    = quaternion_matrix.matrix();
	    int num_sol;

	    T_ <<   0., 0., 0., CartesianPosition(0),
	            0., 0., 0., CartesianPosition(1),
	            0., 0., 0., CartesianPosition(2),
	            0., 0., 0., 1.;
	    T_.block<3,3>(0,0) = RotationMatrix.block<3,3>(0,0);

	    if(strncmp(argv[1],"IKG",3) == 0)
	    {
		    Eigen::Matrix<float,4,4> T67, T06;
			T67 <<  1, 0, 0, 0,
					0, 1, 0, 0,
					0, 0, 1, 0.235,
					0, 0, 0, 1;

			T06 = T_*T67.inverse();
		    tm_jacobian::Matrix2DoubleArray(T06,T);
		   	num_sol =  tm_kinematics::inverse(T, q_inv);
		   	cout << ">>>> T07 " << endl;
	    	tm_jacobian::printMatrix(T_);
		}
		else
		{
			tm_jacobian::Matrix2DoubleArray(T_,T);
			num_sol =  tm_kinematics::inverse(T, q_inv);
		}

	    cout << ">>>> T06 " << endl;
	    tm_jacobian::printMatrix(T,4,16);
	    cout << ">>>> inverse q number of sols T06 : " << num_sol << endl;
		tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
	}
	else if(strncmp(argv[1],"FJ",2) == 0)    // forward jacobian
	{
		if(strncmp(argv[1],"FJG",3) == 0)
		{
			Eigen::Matrix<double, 6, 1> JointVelocity    = Eigen::Matrix<double, 6, 1>::Zero();
			Eigen::Matrix<double, 6, 1> EFFVelocity      = Eigen::Matrix<double, 6, 1>::Zero();
			Eigen::Matrix<double, 6, 6> Jacobian_gripper = tm_jacobian::Forward_Jacobian_gripper(q_AfterHomeOffset);
			JointVelocity << 	strtod(argv[8],NULL),
								strtod(argv[9],NULL),
								strtod(argv[10],NULL),
								strtod(argv[11],NULL),
								strtod(argv[12],NULL),
								strtod(argv[13],NULL);
			EFFVelocity = Jacobian_gripper*JointVelocity;

			cout << ">>>> jacobian" << endl;
			tm_jacobian::printMatrixd(Jacobian_gripper);
			cout << ">>>> effspd speed" << endl;
			tm_jacobian::printMatrixd(EFFVelocity);
		}
		else
		{
			jointspd << 		strtod(argv[8],NULL),
								strtod(argv[9],NULL),
								strtod(argv[10],NULL),
								strtod(argv[11],NULL),
								strtod(argv[12],NULL),
								strtod(argv[13],NULL);

			Eigen::Matrix<float, 6, 6> Jacobian = tm_jacobian::Forward_Jacobian(q_AfterHomeOffset);
			effspd = Jacobian*jointspd;
			cout << ">>>> jacobian" << endl;
			tm_jacobian::printMatrix(Jacobian);

			cout << ">>>> effspd speed" << endl;
			tm_jacobian::printMatrix(effspd);
		}
	}
	else if(strncmp(argv[1],"FK",2) == 0)    // forward kinematics
	{
		if(strncmp(argv[1],"FKG",3) == 0)
		{
			Eigen::Matrix<double,4,4> T07, T67, T06;
			T67 <<  1, 0, 0, 0,
					0, 1, 0, 0,
					0, 0, 1, 0.235,
					0, 0, 0, 1;

			tm_jacobian::Matrix2DoubleArray(q_BeforeHomeOffset, q_forward);
			tm_jacobian::Forward_Kinematics_gripper(q_forward,T);

			for (int i = 0; i < 4; ++i)
				for (int j = 0; j < 4; ++j)
					T07(i,j) = T[4*i+j];

			T06 = T07*T67.inverse();

			for (int i = 0; i < 4; ++i)
				for (int j = 0; j < 4; ++j)
					T[4*i+j] = T06(i,j);

			int num_sol = tm_kinematics::inverse(T, q_inv, q_forward);

			cout << ">>>> T07 " << endl;
	    	tm_jacobian::printMatrixd(T07);
	    	cout << ">>>> T06 " << endl;
	    	tm_jacobian::printMatrixd(T06);
			cout << ">>>> inverse q number of sols for T06 : " << num_sol << endl;
			tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
		}
		else
		{
			tm_jacobian::Matrix2DoubleArray(q_BeforeHomeOffset, q_forward);
			tm_kinematics::forward(q_forward, T);
			int num_sol = tm_kinematics::inverse(T, q_inv, q_forward);

			cout << ">>>> T06" << endl;
			tm_jacobian::printMatrix(T,4,16);
			cout << ">>>> inverse q number of sols : " << num_sol << endl;
			tm_jacobian::printMatrix(q_inv, 6, 6*(num_sol));
		}
	}
	else if(strncmp(argv[1],"TT",2) == 0)
	{
		double *q_test = new double [3];
		q_test[0] = 0;
		q_test[1] = 0;
		q_test[2] = 0;

		tm_jacobian::Forward_Kinematics_3(q_test, T);
		cout << ">>>> forward T" << endl;
		tm_jacobian::printMatrix(T,4,16);

		delete [] q_test;

	}

	delete [] T;
	delete [] q_inv;
	delete [] q_forward;
	return 0;
}
<|endoftext|>


<commit_before>f6c1dff3-2747-11e6-8e02-e0f84713e7b8<commit_msg>Nope, didn't work, now it does<commit_after>f6d1fa0f-2747-11e6-a28d-e0f84713e7b8<|endoftext|>


<commit_before>da2ca56e-ad5a-11e7-8db3-ac87a332f658<commit_msg>Bug fixes and performance improvements<commit_after>dac120e8-ad5a-11e7-a1f6-ac87a332f658<|endoftext|>


<commit_before>d8ddd382-4b02-11e5-922b-28cfe9171a43<commit_msg>I'm done<commit_after>d8ea5451-4b02-11e5-a9e9-28cfe9171a43<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AdabasStatDlg.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 07:03:54 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
DBG_NAME(OAdabasStatPageDlg)
//========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        DBG_CTOR(OAdabasStatPageDlg,NULL);

        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setDataSourceOrName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ResId(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);

        DBG_DTOR(OAdabasStatPageDlg,NULL);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<commit_msg>INTEGRATION: CWS residcleanup (1.10.80); FILE MERGED 2007/02/26 22:58:45 pl 1.10.80.1: #i74635# no more ResMgr default<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: AdabasStatDlg.cxx,v $
 *
 *  $Revision: 1.11 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 07:55:00 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_dbaccess.hxx"

#ifndef DBAUI_ADABASSTATDLG_HXX
#include "AdabasStatDlg.hxx"
#endif
#ifndef DBAUI_ADABASSTATDLG_HRC
#include "AdabasStatDlg.hrc"
#endif
#ifndef _DBU_DLG_HRC_
#include "dbu_dlg.hrc"
#endif
#ifndef _DBAUI_MODULE_DBU_HXX_
#include "moduledbu.hxx"
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef _SFXSTRITEM_HXX
#include <svtools/stritem.hxx>
#endif
#ifndef _SFXENUMITEM_HXX
#include <svtools/eitem.hxx>
#endif
#ifndef _SFXINTITEM_HXX
#include <svtools/intitem.hxx>
#endif
#ifndef _VCL_STDTEXT_HXX
#include <vcl/stdtext.hxx>
#endif
#ifndef _SV_MSGBOX_HXX
#include <vcl/msgbox.hxx>
#endif
#ifndef _DBAUI_DATASOURCEITEMS_HXX_
#include "dsitems.hxx"
#endif
#ifndef DBAUI_DRIVERSETTINGS_HXX
#include "DriverSettings.hxx"
#endif
#ifndef _DBAUI_DBADMINIMPL_HXX_
#include "DbAdminImpl.hxx"
#endif
#ifndef _DBAUI_PROPERTYSETITEM_HXX_
#include "propertysetitem.hxx"
#endif
#ifndef _DBAUI_ADMINPAGES_HXX_
#include "adminpages.hxx"
#endif
//.........................................................................
namespace dbaui
{
//.........................................................................
    using namespace ::com::sun::star::uno;
    using namespace ::com::sun::star::beans;
    using namespace ::com::sun::star::lang;
    using namespace ::com::sun::star::sdbc;

    //========================================================================
    //= OAdabasStatPageDlg
DBG_NAME(OAdabasStatPageDlg)
//========================================================================
    OAdabasStatPageDlg::OAdabasStatPageDlg(Window* _pParent
                                            , SfxItemSet* _pItems
                                            ,const Reference< XMultiServiceFactory >& _rxORB
                                            ,const ::com::sun::star::uno::Any& _aDataSourceName)
        :SfxTabDialog(_pParent, ModuleRes(DLG_DATABASE_ADABASADMIN), _pItems)
    {
        DBG_CTOR(OAdabasStatPageDlg,NULL);

        m_pImpl = ::std::auto_ptr<ODbDataSourceAdministrationHelper>(new ODbDataSourceAdministrationHelper(_rxORB,_pParent,this));
        m_pImpl->setDataSourceOrName(_aDataSourceName);
        Reference< XPropertySet > xDatasource = m_pImpl->getCurrentDataSource();
        m_pImpl->translateProperties(xDatasource, *GetInputSetImpl());
        SetInputSet(GetInputSetImpl());
        // propagate this set as our new input set and reset the example set
        delete pExampleSet;
        pExampleSet = new SfxItemSet(*GetInputSetImpl());

        DATASOURCE_TYPE eType = m_pImpl->getDatasourceType(*GetInputSetImpl());

        switch ( eType )
        {
            case DST_ADABAS:
                AddTabPage(TAB_PAG_ADABAS_SETTINGS, String(ModuleRes(STR_PAGETITLE_ADABAS_STATISTIC)), ODriversSettings::CreateAdabas,0, sal_False, 1);
                break;
            default:
                OSL_ENSURE(0,"Not supported for other types thasn adabas!");
                break;
        }

        // remove the reset button - it's meaning is much too ambiguous in this dialog
        RemoveResetButton();
        FreeResource();
    }

    // -----------------------------------------------------------------------
    OAdabasStatPageDlg::~OAdabasStatPageDlg()
    {
        SetInputSet(NULL);
        DELETEZ(pExampleSet);

        DBG_DTOR(OAdabasStatPageDlg,NULL);
    }
    // -----------------------------------------------------------------------
    short OAdabasStatPageDlg::Execute()
    {
        short nRet = SfxTabDialog::Execute();
        if ( nRet == RET_OK )
        {
            pExampleSet->Put(*GetOutputItemSet());
            m_pImpl->saveChanges(*pExampleSet);
        }
        return nRet;
    }
    //-------------------------------------------------------------------------
    void OAdabasStatPageDlg::PageCreated(USHORT _nId, SfxTabPage& _rPage)
    {
        // register ourself as modified listener
        static_cast<OGenericAdministrationPage&>(_rPage).SetServiceFactory(m_pImpl->getORB());
        static_cast<OGenericAdministrationPage&>(_rPage).SetAdminDialog(this,this);

        AdjustLayout();
        Window *pWin = GetViewWindow();
        if(pWin)
            pWin->Invalidate();

        SfxTabDialog::PageCreated(_nId, _rPage);
    }
    // -----------------------------------------------------------------------------
    const SfxItemSet* OAdabasStatPageDlg::getOutputSet() const
    {
        return GetExampleSet();
    }
    // -----------------------------------------------------------------------------
    SfxItemSet* OAdabasStatPageDlg::getWriteOutputSet()
    {
        return pExampleSet;
    }
    // -----------------------------------------------------------------------------
    ::std::pair< Reference<XConnection>,sal_Bool> OAdabasStatPageDlg::createConnection()
    {
        return m_pImpl->createConnection();
    }
    // -----------------------------------------------------------------------------
    Reference< XMultiServiceFactory > OAdabasStatPageDlg::getORB()
    {
        return m_pImpl->getORB();
    }
    // -----------------------------------------------------------------------------
    Reference< XDriver > OAdabasStatPageDlg::getDriver()
    {
        return m_pImpl->getDriver();
    }
    // -----------------------------------------------------------------------------
    DATASOURCE_TYPE OAdabasStatPageDlg::getDatasourceType(const SfxItemSet& _rSet) const
    {
        return m_pImpl->getDatasourceType(_rSet);
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::clearPassword()
    {
        m_pImpl->clearPassword();
    }
    // -----------------------------------------------------------------------------
    void OAdabasStatPageDlg::setTitle(const ::rtl::OUString& _sTitle)
    {
        SetText(_sTitle);
    }
    //-------------------------------------------------------------------------
    sal_Bool OAdabasStatPageDlg::saveDatasource()
    {
        return PrepareLeaveCurrentPage();
    }
//.........................................................................
}   // namespace dbaui
//.........................................................................
<|endoftext|>


<commit_before><commit_msg>Remove unused variables (#16070)<commit_after><|endoftext|>


<commit_before>#ifndef ENTT_SIGNAL_EMITTER_HPP
#define ENTT_SIGNAL_EMITTER_HPP

#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"

namespace entt {

/**
 * @brief General purpose event emitter.
 *
 * The emitter class template follows the CRTP idiom. To create a custom emitter
 * type, derived classes must inherit directly from the base class as:
 *
 * @code{.cpp}
 * struct my_emitter: emitter<my_emitter> {
 *     // ...
 * }
 * @endcode
 *
 * Pools for the type of events are created internally on the fly. It's not
 * required to specify in advance the full list of accepted types.

 * Moreover, whenever an event is published, an emitter provides the listeners
 * with a reference to itself along with a const reference to the event.
 * Therefore listeners have an handy way to work with it without incurring in
 * the need of capturing a reference to the emitter.
 *
 * @tparam Derived Actual type of emitter that extends the class template.
 */
template<typename Derived>
class emitter {
    struct basic_pool {
        virtual ~basic_pool() = default;
        virtual bool empty() const ENTT_NOEXCEPT = 0;
        virtual void clear() ENTT_NOEXCEPT = 0;
    };

    template<typename Event>
    struct pool_handler final: basic_pool {
        using listener_type = std::function<void(const Event &, Derived &)>;
        using element_type = std::pair<bool, listener_type>;
        using container_type = std::list<element_type>;
        using connection_type = typename container_type::iterator;

        bool empty() const ENTT_NOEXCEPT override {
            auto pred = [](auto &&element) { return element.first; };

            return std::all_of(once_list.cbegin(), once_list.cend(), pred) &&
                    std::all_of(on_list.cbegin(), on_list.cend(), pred);
        }

        void clear() ENTT_NOEXCEPT override {
            if(publishing) {
                for(auto &&element: once_list) {
                    element.first = true;
                }

                for(auto &&element: on_list) {
                    element.first = true;
                }
            } else {
                once_list.clear();
                on_list.clear();
            }
        }

        connection_type once(listener_type listener) {
            return once_list.emplace(once_list.cend(), false, std::move(listener));
        }

        connection_type on(listener_type listener) {
            return on_list.emplace(on_list.cend(), false, std::move(listener));
        }

        void erase(connection_type conn) {
            conn->first = true;

            if(!publishing) {
                auto pred = [](auto &&element) { return element.first; };
                once_list.remove_if(pred);
                on_list.remove_if(pred);
            }
        }

        void publish(const Event &event, Derived &ref) {
            container_type swap_list;
            once_list.swap(swap_list);

            publishing = true;

            for(auto &&element: on_list) {
                element.first ? void() : element.second(event, ref);
            }

            for(auto &&element: swap_list) {
                element.first ? void() : element.second(event, ref);
            }

            publishing = false;

            on_list.remove_if([](auto &&element) { return element.first; });
        }

    private:
        bool publishing{false};
        container_type once_list{};
        container_type on_list{};
    };

    template<typename Event>
    const pool_handler<Event> & assure() const {
        static_assert(std::is_same_v<Event, std::decay_t<Event>>);
        const auto index = type_index<Event>::value();

        if(!(index < pools.size())) {
            pools.resize(index+1);
        }

        if(!pools[index]) {
            pools[index].reset(new pool_handler<Event>{});
        }

        return static_cast<pool_handler<Event> &>(*pools[index]);
    }

    template<typename Event>
    pool_handler<Event> & assure() {
        return const_cast<pool_handler<Event> &>(std::as_const(*this).template assure<Event>());
    }

public:
    /** @brief Type of listeners accepted for the given event. */
    template<typename Event>
    using listener = typename pool_handler<Event>::listener_type;

    /**
     * @brief Generic connection type for events.
     *
     * Type of the connection object returned by the event emitter whenever a
     * listener for the given type is registered.

     * It can be used to break connections still in use.
     *
     * @tparam Event Type of event for which the connection is created.
     */
    template<typename Event>
    struct connection: private pool_handler<Event>::connection_type {
        /** @brief Event emitters are friend classes of connections. */
        friend class emitter;

        /*! @brief Default constructor. */
        connection() = default;

        /**
         * @brief Creates a connection that wraps its underlying instance.
         * @param conn A connection object to wrap.
         */
        connection(typename pool_handler<Event>::connection_type conn)
            : pool_handler<Event>::connection_type{std::move(conn)}
        {}
    };

    /*! @brief Default constructor. */
    emitter() = default;

    /*! @brief Default destructor. */
    virtual ~emitter() {
        static_assert(std::is_base_of_v<emitter<Derived>, Derived>);
    }

    /*! @brief Default move constructor. */
    emitter(emitter &&) = default;

    /*! @brief Default move assignment operator. @return This emitter. */
    emitter & operator=(emitter &&) = default;

    /**
     * @brief Emits the given event.
     *
     * All the listeners registered for the specific event type are invoked with
     * the given event. The event type must either have a proper constructor for
     * the arguments provided or be an aggregate type.
     *
     * @tparam Event Type of event to publish.
     * @tparam Args Types of arguments to use to construct the event.
     * @param args Parameters to use to initialize the event.
     */
    template<typename Event, typename... Args>
    void publish(Args &&... args) {
        assure<Event>().publish(Event{std::forward<Args>(args)...}, *static_cast<Derived *>(this));
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * more than once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param instance The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    connection<Event> on(listener<Event> instance) {
        return assure<Event>().on(std::move(instance));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * only once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param instance The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    connection<Event> once(listener<Event> instance) {
        return assure<Event>().once(std::move(instance));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     *
     * Do not use twice the same connection to disconnect a listener, it results
     * in undefined behavior. Once used, discard the connection object.
     *
     * @tparam Event Type of event of the connection.
     * @param conn A valid connection.
     */
    template<typename Event>
    void erase(connection<Event> conn) {
        assure<Event>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     *
     * All the connections previously returned for the given event are
     * invalidated. Using them results in undefined behavior.
     *
     * @tparam Event Type of event to reset.
     */
    template<typename Event>
    void clear() {
        assure<Event>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     *
     * All the connections previously returned are invalidated. Using them
     * results in undefined behavior.
     */
    void clear() ENTT_NOEXCEPT {
        for(auto &&cpool: pools) {
            if(cpool) {
                cpool->clear();
            }
        }
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @tparam Event Type of event to test.
     * @return True if there are no listeners registered, false otherwise.
     */
    template<typename Event>
    bool empty() const {
        return assure<Event>().empty();
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered, false otherwise.
     */
    bool empty() const ENTT_NOEXCEPT {
        return std::all_of(pools.cbegin(), pools.cend(), [](auto &&cpool) {
            return !cpool || cpool->empty();
        });
    }

private:
    mutable std::vector<std::unique_ptr<basic_pool>> pools{};
};

}

#endif
<commit_msg>emitter: reintroduced type_id for the internal pool<commit_after>#ifndef ENTT_SIGNAL_EMITTER_HPP
#define ENTT_SIGNAL_EMITTER_HPP

#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <type_traits>
#include <utility>
#include <vector>
#include "../config/config.h"
#include "../core/fwd.hpp"
#include "../core/type_info.hpp"

namespace entt {

/**
 * @brief General purpose event emitter.
 *
 * The emitter class template follows the CRTP idiom. To create a custom emitter
 * type, derived classes must inherit directly from the base class as:
 *
 * @code{.cpp}
 * struct my_emitter: emitter<my_emitter> {
 *     // ...
 * }
 * @endcode
 *
 * Pools for the type of events are created internally on the fly. It's not
 * required to specify in advance the full list of accepted types.

 * Moreover, whenever an event is published, an emitter provides the listeners
 * with a reference to itself along with a const reference to the event.
 * Therefore listeners have an handy way to work with it without incurring in
 * the need of capturing a reference to the emitter.
 *
 * @tparam Derived Actual type of emitter that extends the class template.
 */
template<typename Derived>
class emitter {
    struct basic_pool {
        virtual ~basic_pool() = default;
        virtual bool empty() const ENTT_NOEXCEPT = 0;
        virtual void clear() ENTT_NOEXCEPT = 0;
        virtual id_type type_id() const ENTT_NOEXCEPT = 0;
    };

    template<typename Event>
    struct pool_handler final: basic_pool {
        using listener_type = std::function<void(const Event &, Derived &)>;
        using element_type = std::pair<bool, listener_type>;
        using container_type = std::list<element_type>;
        using connection_type = typename container_type::iterator;

        bool empty() const ENTT_NOEXCEPT override {
            auto pred = [](auto &&element) { return element.first; };

            return std::all_of(once_list.cbegin(), once_list.cend(), pred) &&
                    std::all_of(on_list.cbegin(), on_list.cend(), pred);
        }

        void clear() ENTT_NOEXCEPT override {
            if(publishing) {
                for(auto &&element: once_list) {
                    element.first = true;
                }

                for(auto &&element: on_list) {
                    element.first = true;
                }
            } else {
                once_list.clear();
                on_list.clear();
            }
        }

        connection_type once(listener_type listener) {
            return once_list.emplace(once_list.cend(), false, std::move(listener));
        }

        connection_type on(listener_type listener) {
            return on_list.emplace(on_list.cend(), false, std::move(listener));
        }

        void erase(connection_type conn) {
            conn->first = true;

            if(!publishing) {
                auto pred = [](auto &&element) { return element.first; };
                once_list.remove_if(pred);
                on_list.remove_if(pred);
            }
        }

        void publish(const Event &event, Derived &ref) {
            container_type swap_list;
            once_list.swap(swap_list);

            publishing = true;

            for(auto &&element: on_list) {
                element.first ? void() : element.second(event, ref);
            }

            for(auto &&element: swap_list) {
                element.first ? void() : element.second(event, ref);
            }

            publishing = false;

            on_list.remove_if([](auto &&element) { return element.first; });
        }

        id_type type_id() const ENTT_NOEXCEPT override {
            return type_info<Event>::id();
        }

    private:
        bool publishing{false};
        container_type once_list{};
        container_type on_list{};
    };

    template<typename Event>
    const pool_handler<Event> & assure() const {
        static_assert(std::is_same_v<Event, std::decay_t<Event>>);
        const auto index = type_index<Event>::value();

        if(!(index < pools.size())) {
            pools.resize(index+1);
        }

        if(!pools[index]) {
            pools[index].reset(new pool_handler<Event>{});
        }

        return static_cast<pool_handler<Event> &>(*pools[index]);
    }

    template<typename Event>
    pool_handler<Event> & assure() {
        return const_cast<pool_handler<Event> &>(std::as_const(*this).template assure<Event>());
    }

public:
    /** @brief Type of listeners accepted for the given event. */
    template<typename Event>
    using listener = typename pool_handler<Event>::listener_type;

    /**
     * @brief Generic connection type for events.
     *
     * Type of the connection object returned by the event emitter whenever a
     * listener for the given type is registered.

     * It can be used to break connections still in use.
     *
     * @tparam Event Type of event for which the connection is created.
     */
    template<typename Event>
    struct connection: private pool_handler<Event>::connection_type {
        /** @brief Event emitters are friend classes of connections. */
        friend class emitter;

        /*! @brief Default constructor. */
        connection() = default;

        /**
         * @brief Creates a connection that wraps its underlying instance.
         * @param conn A connection object to wrap.
         */
        connection(typename pool_handler<Event>::connection_type conn)
            : pool_handler<Event>::connection_type{std::move(conn)}
        {}
    };

    /*! @brief Default constructor. */
    emitter() = default;

    /*! @brief Default destructor. */
    virtual ~emitter() {
        static_assert(std::is_base_of_v<emitter<Derived>, Derived>);
    }

    /*! @brief Default move constructor. */
    emitter(emitter &&) = default;

    /*! @brief Default move assignment operator. @return This emitter. */
    emitter & operator=(emitter &&) = default;

    /**
     * @brief Emits the given event.
     *
     * All the listeners registered for the specific event type are invoked with
     * the given event. The event type must either have a proper constructor for
     * the arguments provided or be an aggregate type.
     *
     * @tparam Event Type of event to publish.
     * @tparam Args Types of arguments to use to construct the event.
     * @param args Parameters to use to initialize the event.
     */
    template<typename Event, typename... Args>
    void publish(Args &&... args) {
        assure<Event>().publish(Event{std::forward<Args>(args)...}, *static_cast<Derived *>(this));
    }

    /**
     * @brief Registers a long-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * more than once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param instance The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    connection<Event> on(listener<Event> instance) {
        return assure<Event>().on(std::move(instance));
    }

    /**
     * @brief Registers a short-lived listener with the event emitter.
     *
     * This method can be used to register a listener designed to be invoked
     * only once for the given event type.

     * The connection returned by the method can be freely discarded. It's meant
     * to be used later to disconnect the listener if required.
     *
     * The listener is as a callable object that can be moved and the type of
     * which is `void(const Event &, Derived &)`.
     *
     * @note
     * Whenever an event is emitted, the emitter provides the listener with a
     * reference to the derived class. Listeners don't have to capture those
     * instances for later uses.
     *
     * @tparam Event Type of event to which to connect the listener.
     * @param instance The listener to register.
     * @return Connection object that can be used to disconnect the listener.
     */
    template<typename Event>
    connection<Event> once(listener<Event> instance) {
        return assure<Event>().once(std::move(instance));
    }

    /**
     * @brief Disconnects a listener from the event emitter.
     *
     * Do not use twice the same connection to disconnect a listener, it results
     * in undefined behavior. Once used, discard the connection object.
     *
     * @tparam Event Type of event of the connection.
     * @param conn A valid connection.
     */
    template<typename Event>
    void erase(connection<Event> conn) {
        assure<Event>().erase(std::move(conn));
    }

    /**
     * @brief Disconnects all the listeners for the given event type.
     *
     * All the connections previously returned for the given event are
     * invalidated. Using them results in undefined behavior.
     *
     * @tparam Event Type of event to reset.
     */
    template<typename Event>
    void clear() {
        assure<Event>().clear();
    }

    /**
     * @brief Disconnects all the listeners.
     *
     * All the connections previously returned are invalidated. Using them
     * results in undefined behavior.
     */
    void clear() ENTT_NOEXCEPT {
        for(auto &&cpool: pools) {
            if(cpool) {
                cpool->clear();
            }
        }
    }

    /**
     * @brief Checks if there are listeners registered for the specific event.
     * @tparam Event Type of event to test.
     * @return True if there are no listeners registered, false otherwise.
     */
    template<typename Event>
    bool empty() const {
        return assure<Event>().empty();
    }

    /**
     * @brief Checks if there are listeners registered with the event emitter.
     * @return True if there are no listeners registered, false otherwise.
     */
    bool empty() const ENTT_NOEXCEPT {
        return std::all_of(pools.cbegin(), pools.cend(), [](auto &&cpool) {
            return !cpool || cpool->empty();
        });
    }

private:
    mutable std::vector<std::unique_ptr<basic_pool>> pools{};
};

}

#endif
<|endoftext|>


<commit_before>30bd6557-ad5b-11e7-a88f-ac87a332f658<commit_msg>more bug fix<commit_after>313264dc-ad5b-11e7-b101-ac87a332f658<|endoftext|>


<commit_before>/*
 * libcpu: i386_decoder.cpp
 */

#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#include <llvm/MC/MCInstrInfo.h>
#include <llvm/MC/MCRegisterInfo.h>
#include <llvm/MC/MCSubtargetInfo.h>
#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/MemoryObject.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/raw_ostream.h>

#include "i386_arch.h"

extern "C"
{
	 void LLVMInitializeX86Disassembler();
}

static const MCDisassembler *DisAsm = NULL;
static MCInstPrinter *InstPrinter = NULL;

/*
// A subclass of LLVM's MemoryObject that wraps a pointer as an unbounded array
// of bytes.
//
// When we have an MCDisassembler object, we'll point it into this MemoryObject
// to decode an instruction.
*/
namespace {
	class DirectMemoryObject : public MemoryObject {
	private:
		const uint8_t *Bytes;
	public:
		DirectMemoryObject(const uint8_t *bytes) : Bytes(bytes) {}

		uint64_t getBase() const { return 0; }
		uint64_t getExtent() const { return 0; }

		int readByte(uint64_t Addr, uint8_t *Byte) const {
			*Byte = Bytes[Addr];
			return 0;
		}
	};
}

/*
// Initializes our global disassembler and printer.
// Largely ripped out of llvm-mc.
*/
static void InitializeGlobals()
{
	// Initialize the X86 disassembler
	LLVMInitializeX86Disassembler();

	// We need to make a target triple for i386
	Triple triple(sys::getDefaultTargetTriple());
	triple.setArch(Triple::getArchTypeForLLVMName("x86"));

	// Look up this target in LLVM's registry
	std::string Err;
	const Target *T = TargetRegistry::lookupTarget(triple.getTriple(), Err);
	if (!T)
	{
		errs() << "Failed to get target for " << triple.getTriple() << "\n";
		abort();
	}

	OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(triple.getTriple()));
	if (!AsmInfo) {
		errs() << "Failed to get target for target\n";
		abort();
	}

	OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(triple.getTriple(), "", ""));
	if (!STI) {
		errs() << "Failed to get subtarget for target\n";
		abort();
	}

	DisAsm = T->createMCDisassembler(*STI);
	if (!DisAsm) {
		errs() << "Failed to get disassembler for target\n";
		abort();
	}

	OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(triple.getTriple()));
	if (!MRI) {
		errs() << "Failed to get register info for target\n";
		abort();
	}

	OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
	if (!MII) {
		errs() << "Failed to get instruction info for target\n";
		abort();
	}

	int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
	InstPrinter = T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo,
		                                 *MII, *MRI, *STI);
	if (!InstPrinter) {
		errs() << "Failed to get instruction printer for target\n";
		abort();
	}
}

/*
// Vends a shared MCDisassembler object.
*/
static const MCDisassembler *GetDisassembler()
{
	if (!DisAsm)
		InitializeGlobals();

	return DisAsm;
}

/*
// Vends a shared MCInstPrinter object.
*/
static MCInstPrinter *GetInstPrinter()
{
	if (!InstPrinter)
		InitializeGlobals();

	return InstPrinter;
}

/*
// Decodes one instruction from the buffer.
*/
MCInst DecodeInstruction(cpu_t *cpu, addr_t pc, uint64_t *_size)
{
	uint64_t size = 0;
	uint64_t index = pc;
	MCInst insn;

	// Decode the instruction
	DirectMemoryObject memoryObject(cpu->RAM);

	MCDisassembler::DecodeStatus S;
    S = GetDisassembler()->getInstruction(insn, size, memoryObject, index,
                                          nulls(), nulls());

	switch (S)
	{
		case MCDisassembler::Fail:
			errs() << "Warning: Invalid instruction encoding\n";
			if (size == 0)
				size = 1;
			break;

		case MCDisassembler::SoftFail:
			errs() << "Warning: Potentially undefined instruction encoding\n";
			// Fall through

		case MCDisassembler::Success:
			break;
	}

	if (_size)
		*_size = size;

	return insn;
}

/*
// Returns a human-readable version of the instruction.
*/
std::string DisasmInstruction(MCInst insn)
{
	std::string output;
	raw_string_ostream sos(output);
	GetInstPrinter()->printInst(&insn, sos, "");
	return sos.str();
}

int arch_i386_disasm_instr(cpu_t *cpu, addr_t pc, char *line, unsigned int max_line)
{
	uint64_t size;
	MCInst insn = DecodeInstruction(cpu, pc, &size);
	strlcpy(line, DisasmInstruction(insn).c_str(), max_line);
	return size;
}<commit_msg>Add the correct #import for this function.<commit_after>/*
 * libcpu: i386_decoder.cpp
 */

#include <llvm/MC/MCAsmInfo.h>
#include <llvm/MC/MCDisassembler.h>
#include <llvm/MC/MCInst.h>
#include <llvm/MC/MCInstPrinter.h>
#include <llvm/MC/MCInstrInfo.h>
#include <llvm/MC/MCRegisterInfo.h>
#include <llvm/MC/MCSubtargetInfo.h>
#include <llvm/ADT/OwningPtr.h>
#include <llvm/ADT/Triple.h>
#include <llvm/Support/MemoryObject.h>
#include <llvm/Support/Host.h>
#include <llvm/Support/TargetRegistry.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>

#include "i386_arch.h"

static const MCDisassembler *DisAsm = NULL;
static MCInstPrinter *InstPrinter = NULL;

/*
// A subclass of LLVM's MemoryObject that wraps a pointer as an unbounded array
// of bytes.
//
// When we have an MCDisassembler object, we'll point it into this MemoryObject
// to decode an instruction.
*/
namespace {
	class DirectMemoryObject : public MemoryObject {
	private:
		const uint8_t *Bytes;
	public:
		DirectMemoryObject(const uint8_t *bytes) : Bytes(bytes) {}

		uint64_t getBase() const { return 0; }
		uint64_t getExtent() const { return 0; }

		int readByte(uint64_t Addr, uint8_t *Byte) const {
			*Byte = Bytes[Addr];
			return 0;
		}
	};
}

/*
// Initializes our global disassembler and printer.
// Largely ripped out of llvm-mc.
*/
static void InitializeGlobals()
{
	// Initialize the X86 disassembler
	LLVMInitializeX86Disassembler();

	// We need to make a target triple for i386
	Triple triple(sys::getDefaultTargetTriple());
	triple.setArch(Triple::getArchTypeForLLVMName("x86"));

	// Look up this target in LLVM's registry
	std::string Err;
	const Target *T = TargetRegistry::lookupTarget(triple.getTriple(), Err);
	if (!T)
	{
		errs() << "Failed to get target for " << triple.getTriple() << "\n";
		abort();
	}

	OwningPtr<const MCAsmInfo> AsmInfo(T->createMCAsmInfo(triple.getTriple()));
	if (!AsmInfo) {
		errs() << "Failed to get target for target\n";
		abort();
	}

	OwningPtr<const MCSubtargetInfo> STI(T->createMCSubtargetInfo(triple.getTriple(), "", ""));
	if (!STI) {
		errs() << "Failed to get subtarget for target\n";
		abort();
	}

	DisAsm = T->createMCDisassembler(*STI);
	if (!DisAsm) {
		errs() << "Failed to get disassembler for target\n";
		abort();
	}

	OwningPtr<const MCRegisterInfo> MRI(T->createMCRegInfo(triple.getTriple()));
	if (!MRI) {
		errs() << "Failed to get register info for target\n";
		abort();
	}

	OwningPtr<const MCInstrInfo> MII(T->createMCInstrInfo());
	if (!MII) {
		errs() << "Failed to get instruction info for target\n";
		abort();
	}

	int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
	InstPrinter = T->createMCInstPrinter(AsmPrinterVariant, *AsmInfo,
		                                 *MII, *MRI, *STI);
	if (!InstPrinter) {
		errs() << "Failed to get instruction printer for target\n";
		abort();
	}
}

/*
// Vends a shared MCDisassembler object.
*/
static const MCDisassembler *GetDisassembler()
{
	if (!DisAsm)
		InitializeGlobals();

	return DisAsm;
}

/*
// Vends a shared MCInstPrinter object.
*/
static MCInstPrinter *GetInstPrinter()
{
	if (!InstPrinter)
		InitializeGlobals();

	return InstPrinter;
}

/*
// Decodes one instruction from the buffer.
*/
MCInst DecodeInstruction(cpu_t *cpu, addr_t pc, uint64_t *_size)
{
	uint64_t size = 0;
	uint64_t index = pc;
	MCInst insn;

	// Decode the instruction
	DirectMemoryObject memoryObject(cpu->RAM);

	MCDisassembler::DecodeStatus S;
    S = GetDisassembler()->getInstruction(insn, size, memoryObject, index,
                                          nulls(), nulls());

	switch (S)
	{
		case MCDisassembler::Fail:
			errs() << "Warning: Invalid instruction encoding\n";
			if (size == 0)
				size = 1;
			break;

		case MCDisassembler::SoftFail:
			errs() << "Warning: Potentially undefined instruction encoding\n";
			// Fall through

		case MCDisassembler::Success:
			break;
	}

	if (_size)
		*_size = size;

	return insn;
}

/*
// Returns a human-readable version of the instruction.
*/
std::string DisasmInstruction(MCInst insn)
{
	std::string output;
	raw_string_ostream sos(output);
	GetInstPrinter()->printInst(&insn, sos, "");
	return sos.str();
}

int arch_i386_disasm_instr(cpu_t *cpu, addr_t pc, char *line, unsigned int max_line)
{
	uint64_t size;
	MCInst insn = DecodeInstruction(cpu, pc, &size);
	strlcpy(line, DisasmInstruction(insn).c_str(), max_line);
	return size;
}
<|endoftext|>


<commit_before>6f91b42b-4b02-11e5-8db3-28cfe9171a43<commit_msg>oh my, I hate charles<commit_after>6f9e93c0-4b02-11e5-bd32-28cfe9171a43<|endoftext|>