text:
#include <ctime>
#include <iostream>
#include <ros/ros.h>
#include <boost/foreach.hpp>
#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <ctime>

#include <pcl/common/common.h>
#include <pcl/console/print.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/PCLPointCloud2.h>
#include <pcl/point_types.h>
#include <pcl/PointIndices.h>
#include <pcl/features/normal_3d.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/features/principal_curvatures.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/pcl_exports.h>
#include <pcl/io/pcd_io.h>
#include <pcl_ros/point_cloud.h>

#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Geometry>

#include <ros/ros.h>
#include <boost/foreach.hpp>

using namespace std;

static ros::Subscriber sub;
static ros::Publisher pub;

void callback(const pcl::PointCloud<pcl::PointXYZ>::ConstPtr& cloud)
{
    printf ("Cloud: width = %d, height = %d\n", cloud->width, cloud->height);
    /*for( auto pt : cloud->points){
  	 printf ("\t(%f, %f, %f)\n", pt.x, pt.y, pt.z);
    }*/

    //normal estimation;
    pcl::search::KdTree<pcl::PointXYZ>::Ptr tree(new pcl::search::KdTree<pcl::PointXYZ>());//create an empty kd_tree
    pcl::PointCloud<pcl::Normal>::Ptr normals(new pcl::PointCloud<pcl::Normal>());//create an empty normal point cloud
    pcl::NormalEstimation<pcl::PointXYZ, pcl::Normal> ne;
    tree->setInputCloud(cloud);
    ne.setInputCloud(cloud);
    ne.setSearchMethod(tree);
    ne.setKSearch (20); //number of search neighborhood points
    ne.compute(*normals); //compute normal and save to normal point cloud

    //neighborhood
    int point_num = cloud->points.size();//number of point cloud
    vector<int>nebor_index;//store index of neighborhood points
    vector<float>nebor_dis;//store distance of neighborhood points
    int nebor_size(20);//number of neighborhood points
    vector<vector<int> > point_nebor;
    point_nebor.resize(point_num, nebor_index);
    for (int i_point = 0; i_point < point_num; i_point++)
    {
        if(tree->nearestKSearch(cloud->points[i_point], nebor_size, nebor_index, nebor_dis))
        {
            //points[i_point]: 20 index of neighborhood point with i_point
            point_nebor[i_point].swap(nebor_index);
            //each points in point_nebor store 20 index of neighborhoood around themselves.
        }
        else
        {
            PCL_ERROR("WARNING:FALSE NEARERTKSEARCH");
        }
    }

    //curvature
    vector<pair<float, int> > point_curvature_index;
    float curvature = 0.0;
    pcl::PrincipalCurvaturesEstimation<pcl::PointXYZ, pcl::Normal, pcl::PrincipalCurvatures> cur;
    pcl::PointCloud<pcl::PrincipalCurvatures>::Ptr curvatures(new pcl::PointCloud<pcl::PrincipalCurvatures>);
    cur.setInputCloud(cloud);
    cur.setInputNormals(normals);
    cur.setSearchMethod(tree);
    //pc.setRadiusSearch(0.05);
    cur.setKSearch(20);
    cur.compute(*curvatures);
    for (size_t i = 0; i < point_num; i++)
    {
        curvature = (*curvatures)[i].pc1 * (*curvatures)[i].pc2;
        //store point curvature and point(float, int)
        point_curvature_index.push_back(make_pair(curvature,i));
    }
    sort(point_curvature_index.begin(), point_curvature_index.end());//sort according curvature
    //cout<<"curvature finished"<<endl;

    //region growing
    float normal_threshold_low = cosf(1.0 / 180.0 * M_PI);//Theta_low
    float normal_threshold_high = cosf(10.0 / 180.0 * M_PI);//Theta_high
    float curvature_threshold = 0.7;//curvature threshold
    int counter_(0);
    int segment_label(0);
    int seed_index_orginal = point_curvature_index[0].second;//selected min curvature point as seed points
    vector<int> point_label;
    vector<int> seg_ave_num;
    point_label.resize(point_num, -1);//(size, initial value)
    while(counter_<point_num)//iterate over all the point cloud
    {
        queue<int> seed;//create a queue
        seed.push(seed_index_orginal);//add to the end of queue
        int counter_1(1);
        point_label[seed_index_orginal] = segment_label;//segment_label is 0
        while (!seed.empty())
        {
            int curr_seed = seed.front();//first element of seed
            seed.pop();//Pop-up the first element
            int K_nebor(0);
            while (K_nebor<nebor_size)//detect curr_seed's surrounding points
            {
                int index_nebor = point_nebor[curr_seed][K_nebor];
                //float g_curvature;
                //g_curvature = (*curvatures)[index_nebor].pc1 * (*curvatures)[index_nebor].pc2;
                if (point_label[index_nebor] != -1)//have selected, skip this point
                {
                    K_nebor++;
                    continue;
                }
                bool is_a_seed = false;
                Eigen::Map<Eigen::Vector3f> vec_curr_point(static_cast<float*>(normals->points[curr_seed].normal));
                Eigen::Map<Eigen::Vector3f> vec_nebor_point (static_cast<float*>(normals->points[index_nebor].normal));
                float dot_normal = fabsf(vec_curr_point.dot(vec_nebor_point));
                if (dot_normal<normal_threshold_high)
                {
                    is_a_seed = false;
                }
                else if(dot_normal>normal_threshold_high&&dot_normal<normal_threshold_low)
                {
                    int Edge_nebor(0);
                    int num_out_high(0);
                    //detect if index_nebor point is Edge point or not
                    while (Edge_nebor<nebor_size)
                    {
                        int Edge_index_nebor = point_nebor[index_nebor][Edge_nebor];
                        Eigen::Map<Eigen::Vector3f> vec_curr_edge_point(static_cast<float*>(normals->points[index_nebor].normal));
                        Eigen::Map<Eigen::Vector3f> vec_edge_point_nebor(static_cast<float*>(normals->points[Edge_index_nebor].normal));
                        float dot_normal_edge = fabsf(vec_curr_edge_point.dot(vec_edge_point_nebor));
                        if (dot_normal_edge<normal_threshold_high)
                        {
                            num_out_high++;//number of the point which out high threhold
                        }
                        Edge_nebor++;
                    }
                    float proportion = num_out_high/nebor_size;
                    if (proportion>0.4)
                    {
                        is_a_seed = false;
                    }
                    /*else if (g_curvature>curvature_threshold)
                    {
		        is_a_seed = false;
		    }*/
                    else
                    {
                        is_a_seed = true;
                    }
                }
                /*else if (g_curvature>curvature_threshold)
                {
		    is_a_seed = false;
		}*/
                else
                {
                    is_a_seed = true;
                }
                if (!is_a_seed)//not a seed point, throw it away
                {
                    K_nebor++;
                    continue;
                }
                point_label[index_nebor] = segment_label;
                counter_1++;
                if (is_a_seed)//is a seed, add to seed queue
                {
                    seed.push(index_nebor);
                }
                K_nebor++;
            }
        }
        segment_label++;//number of segmentation
        counter_ += counter_1;//the number of points which have been detected
        seg_ave_num.push_back(counter_1);//number of points on one plane
        for (int i_seg = 0; i_seg < point_num; i_seg++)
        {
            int index_ = point_curvature_index[i_seg].second;
            if (point_label[index_] == -1)//haven't been detected.
            {
                seed_index_orginal = index_;
                break;
            }
        }
    }

    //summary of segmentation results
    vector<pcl::PointIndices> cluster_;
    pcl::PointIndices segments;
    int seg_num = seg_ave_num.size();//number of all planes
    cluster_.resize(seg_num, segments);
    for(int i_seg = 0; i_seg < seg_num; i_seg++)//iterate over all the planes
    {
        cluster_[i_seg].indices.resize(seg_ave_num[i_seg],0);
    }
    vector<int> counter;
    counter.resize(seg_num, 0);
    for (int i_point = 0; i_point < point_num; i_point++)
    {
        int segment_index = point_label[i_point];//Which plane
        int nebor_idx = counter[segment_index];
        cluster_[segment_index].indices[nebor_idx] = i_point;
        counter[segment_index] += 1;
    }

    //Remove outline points
    vector<pcl::PointIndices> clusters;
    int min_number = 100, max_number = point_num/10;
    for (int i_seg = 0; i_seg < seg_num; i_seg++)//iterate over all the planes
    {
        if (cluster_[i_seg].indices.size() > min_number&&cluster_[i_seg].indices.size() < max_number)
        {
            clusters.push_back(cluster_[i_seg]);
        }
    }

    pcl::PointCloud<pcl::PointXYZ>::Ptr color_point(new pcl::PointCloud<pcl::PointXYZ>);
    //pcl::PointCloud<pcl::PointXYZRGB>::Ptr color_point(new pcl::PointCloud<pcl::PointXYZRGB>);
    //srand(time(nullptr));
    /*vector<unsigned char> color;
    for (int i_segment = 0; i_segment < clusters.size(); i_segment++)
    {
        color.push_back(static_cast<unsigned char>(rand() % 256));
        color.push_back(static_cast<unsigned char>(rand() % 256));
        color.push_back(static_cast<unsigned char>(rand() % 256));
    }
    int color_index(0);*/
    for (int i_seg = 0; i_seg < clusters.size(); i_seg++)
    {
        int clusters_size = clusters[i_seg].indices.size();
        for (int i_idx = 0; i_idx < clusters_size; i_idx++)
        {
            pcl::PointXYZ n_point;
            n_point.x = cloud->points[clusters[i_seg].indices[i_idx]].x;
            n_point.y = cloud->points[clusters[i_seg].indices[i_idx]].y;
            n_point.z = cloud->points[clusters[i_seg].indices[i_idx]].z;
            //n_point.r = color[3 * color_index];
            //n_point.g = color[3 * color_index + 1];
            //n_point.b = color[3 * color_index + 2];
            color_point->push_back(n_point);
        }
        //color_index++;
    }

    pcl::io::savePCDFileASCII("/home/miao/catkin_ws/src/vision_module/src/data/region.pcd", *color_point);

    pub.publish(color_point);

}

int main(int argc, char** argv)
{
  std::cout<<"Init the region growing node:" <<std::endl;
  ros::init(argc, argv, "region_growing");
  ros::NodeHandle nh;
  sub = nh.subscribe<pcl::PointCloud<pcl::PointXYZ>>("removal_outlier", 1000, callback);
  pub = nh.advertise<pcl::PointCloud<pcl::PointXYZ>> ("region_growing", 1000);
  ros::spin();
}


text:
/*
 * Copyright (c) 2011-2018, The DART development contributors
 * All rights reserved.
 *
 * The list of contributors can be found at:
 *   https://github.com/dartsim/dart/blob/master/LICENSE
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * This code incorporates portions of Open Dynamics Engine
 *     (Copyright (c) 2001-2004, Russell L. Smith. All rights
 *     reserved.) and portions of FCL (Copyright (c) 2011, Willow
 *     Garage, Inc. All rights reserved.), which were released under
 *     the same BSD license as below
 *
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef DART_SIMULATION_RECORDING_HPP_
#define DART_SIMULATION_RECORDING_HPP_

#include <vector>

#include <Eigen/Dense>

#include "dart/dynamics/Skeleton.hpp"

namespace dart {

namespace dynamics {
class Skeleton;
}  // namespace dynamics

namespace simulation {

/// \brief class Recording
class Recording
{
public:
  /// \brief Create Recording with a list of skeletons
  explicit Recording(const std::vector<dynamics::SkeletonPtr>& _skeletons);

  /// \brief Create Recording with a list of number of dofs
  explicit Recording(const std::vector<int>& _skelDofs);

  /// \brief Destructor
  virtual ~Recording();

  /// \brief Get number of frames
  int getNumFrames() const;

  /// \brief Get number of skeletons
  int getNumSkeletons() const;

  /// \brief Get number of generalized coordinates of skeleton whoes index is
  /// _skelIdx
  int getNumDofs(int _skelIdx) const;

  /// \brief Get number of contacts at frame number _frameIdx
  int getNumContacts(int _frameIdx) const;

  /// \brief Get skeleton configurations whose index is _skelIdx at frame number
  /// _frameIdx
  Eigen::VectorXd getConfig(int _frameIdx, int _skelIdx) const;

  /// \brief Get _dofIdx-th single configruation of a skeleton whose index is
  /// _skelIdx at frame number _frameIdx
  double getGenCoord(int _frameIdx, int _skelIdx, int _dofIdx) const;

  /// \brief Get contact point whose index is _contactIdx at frame number
  /// _frameIdx
  Eigen::Vector3d getContactPoint(int _frameIdx, int _contactIdx) const;

  /// \brief Get contact force whose index is _contactIdx at frame number
  /// _frameIdx
  Eigen::Vector3d getContactForce(int _frameIdx, int _contactIdx) const;

  /// \brief Clear the saved histories
  void clear();

  /// \brief Add state
  void addState(const Eigen::VectorXd& _state);

  /// \brief Update list for number of generalized coordinates
  void updateNumGenCoords(const std::vector<dynamics::SkeletonPtr>& _skeletons);

private:
  /// \brief Baked states
  std::vector<Eigen::VectorXd> mBakedStates;

  /// \brief Number of generalized coordinates for skeletons
  std::vector<int> mNumGenCoordsForSkeletons;
};

}  // namespace simulation
}  // namespace dart

#endif  // DART_SIMULATION_RECORDING_HPP_

ext: hpp

max_stars_repo_name: neka-nat/dart

max_issues_repo_name: neka-nat/dart

max_forks_repo_name: neka-nat/dart


text:
#include <NTL/LLL.h>

NTL_CLIENT

int main()
{
   mat_ZZ B;
   long s;

#if 1
   cin >> B;
#else
   long i, j;
   long n;
   cerr << "n: ";
   cin >> n;

   long m;
   cerr << "m: ";
   cin >> m;

   long k;
   cerr << "k: ";
   cin >> k;

   B.SetDims(n, m);
   for (i = 1; i <= n; i++)
      for (j = 1; j <= m; j++) {
         RandomLen(B(i,j), k);
         if (RandomBnd(2)) negate(B(i,j), B(i,j));
      }

#endif

   mat_ZZ U, B0, B1, B2;

   B0 = B;

   double t;
   ZZ d;

   B = B0;
   cerr << "LLL_FP...";
   t = GetTime();
   s = LLL_FP(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "LLL_QP...";
   t = GetTime();
   s = LLL_QP(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "LLL_XD...";
   t = GetTime();
   s = LLL_XD(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "LLL_RR...";
   t = GetTime();
   s = LLL_RR(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "G_LLL_FP...";
   t = GetTime();
   s = G_LLL_FP(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "G_LLL_QP...";
   t = GetTime();
   s = G_LLL_QP(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "G_LLL_XD...";
   t = GetTime();
   s = G_LLL_XD(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "G_LLL_RR...";
   t = GetTime();
   s = G_LLL_RR(B, U, 0.99);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");
   LLL(d, B, 90, 100);
   if (B1 != B) Error("bad LLLTest (2)");

   B = B0;
   cerr << "LLL...";
   t = GetTime();
   s = LLL(d, B, U);
   cerr << (GetTime()-t) << "\n";
   mul(B1, U, B0);
   if (B1 != B) Error("bad LLLTest (1)");

   cout << "rank = " << s << "\n";
   cout << "det = " << d << "\n";
   cout << "B = " << B << "\n";
   cout << "U = " << U << "\n";
}

ext: cpp

max_stars_repo_name: vshesh/RUNEtag

max_issues_repo_name: vshesh/RUNEtag

max_forks_repo_name: vshesh/RUNEtag


text:
/******************************************************************************
Copyright (C) 2013 Tomislav Pejsa

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/

#include "AnimationStudioApp.h"
#include "AnimationStudioFrame.h"
#include "ProjectViewWindow.h"
#include "OgreWindow.h"
//#include "NewResourceDialog.h"
#include "DotSceneLoader.h"
#include "zhOgreModelController.h"

#include <boost/filesystem.hpp>
#include <boost/tokenizer.hpp> // TODO: remove this?

AnimationStudioApp* gApp = NULL;

void RenderTimer::Notify()
{
	zh::Animation* cur_anim = gApp->getCurrentAnimation();
	if( cur_anim == NULL || cur_anim->getFrameRate() < 20 )
		Stop();
	else
		gApp->getOgreRoot()->renderOneFrame();
}

AnimationStudioApp::AnimationStudioApp()
: mOgreRoot(NULL), mCam(NULL), mSceneMgr(NULL), mRenderWnd(NULL),
mCurAnim(NULL), mAnimEnabled(true), mTracedJointAnim(NULL)
{
	mRenderTimer = new RenderTimer();
	mFrameTime = 1.f/60.f;
	mParamSkelEditor = new ParamSkeletonEditor();
}

AnimationStudioApp::~AnimationStudioApp()
{
}

AnimationStudioFrame* AnimationStudioApp::getAppFrame() const
{
	return mFrmMain;
}

Camera* AnimationStudioApp::getCamera() const
{
	return mCam;
}

SceneManager* AnimationStudioApp::getSceneManager() const
{
	return mSceneMgr;
}

zh::Skeleton* AnimationStudioApp::selectSkeleton( const string& name )
{
	if( !zhAnimationSystem->hasSkeleton(name) || name == "Environment" )
	{
		// Can't find skeleton by that name
		wxMessageBox( "Unable to find skeleton " + name + ".",
			"Error", wxOK | wxICON_EXCLAMATION );
		return NULL;
	}

	// Reset all motion and environment visualization
	displayJointMarkers( std::set<std::string>(), false );
	traceJointPaths( std::set<std::string>(), false );

	zhAnimationSystem->stopAnimation();
	zhAnimationSystem->setOutputSkeleton(name);
	zh::Skeleton* skel = zhAnimationSystem->getOutputSkeleton();

	mParamSkelEditor->init(skel);
	displayJointMarkers( std::set<std::string>(), false );
	mFrmMain->getOgreWindow()->setRenderSkeleton(skel);
	mFrmMain->refresh();

	return skel;
}

void AnimationStudioApp::removeSkeleton( const string& name )
{
	// TODO: remove skeleton

	// Update window contents
	mFrmMain->refresh();
}

ParamSkeletonEditor* AnimationStudioApp::getParamSkeletonEditor() const
{
	return mParamSkelEditor;
}

zh::Animation* AnimationStudioApp::selectAnimation( const string& animName )
{
	// Write out environment to a file
	zh::Animation* anim = getCurrentAnimation();
	zh::Skeleton* env = zhAnimationSystem->getEnvironment();
	if( anim != NULL && env->getNumBones() >= 2 )
	{
		std::string path = anim->getAnimationSet()->getPath() + ".env";
		std::ofstream ofs(path);
		zh::Skeleton::BoneConstIterator obj_i = env->getBoneConstIterator();
		while( obj_i.hasMore() )
		{
			zh::Bone* obj = obj_i.next();
			if( obj->getName() == "Root" )
				continue;
			zh::Vector3 pos = obj->getWorldPosition();
			ofs << toString<zh::Vector3>(pos) << std::endl;
		}
	}

	// Reset all motion and environment visualization
	displayJointMarkers( std::set<std::string>(), false );
	traceJointPaths( std::set<std::string>(), false );
	deleteAllEnvironmentObjects();

	if( zhAnimationSystem->getOutputSkeleton() == NULL )
	{
		if( zhAnimationSystem->getNumSkeletons() > 0 )
			selectSkeleton( zhAnimationSystem->getSkeletonConstIterator().next()->getName() );
		else
			return NULL;
	}

	zhAnimationSystem->stopAnimation();
	mCurAnim = zhAnimationSystem->getAnimation(animName);
	useConstFrameRate();

	// Position camera so that the whole motion is visible
	float minx, maxx, miny, maxy, minz, maxz;
	mCurAnim->computeAnimationBounds( minx, maxx, miny, maxy, minz, maxz );
	// TODO

	// Load the environment associated with the animation
	std::ifstream ifs( mCurAnim->getAnimationSet()->getPath() + ".env" );
	unsigned short obj_id = 1;
	while( ifs.good() && !ifs.eof() )
	{
		char line[4097];
		ifs.getline( &line[0], 4096 );
		std::string pos_str(line);
		if( pos_str.length() <= 1 )
			break;
		zh::Vector3 pos = fromString<zh::Vector3>(pos_str);
		createEnvironmentObject( toString<unsigned short>(obj_id++), pos );
	}

	return mCurAnim;
}

void AnimationStudioApp::deselectAnimation()
{
	mCurAnim = NULL;
}

zh::Animation* AnimationStudioApp::getCurrentAnimation() const
{
	return mCurAnim;
}

void AnimationStudioApp::displayJointMarkers( const std::set<std::string>& boneNames, bool enable )
{
	zh::Skeleton* skel = zhAnimationSystem->getOutputSkeleton();
	if( skel == NULL )
		return;
	std::set<std::string> bone_names = boneNames;

	if( bone_names.empty() )
	{
		zh::Skeleton::BoneConstIterator bone_i = skel->getBoneConstIterator();
		while( bone_i.hasMore() )
			bone_names.insert( bone_i.next()->getName() );
	}

	if(!enable)
	{
		std::set<std::string> results;
		std::set_difference( mJointsWithMarkers.begin(), mJointsWithMarkers.end(),
			bone_names.begin(), bone_names.end(), std::inserter( results, results.end() ) );
		mJointsWithMarkers = results;

		for( std::set<std::string>::const_iterator jmi = bone_names.begin();
			jmi != bone_names.end(); ++jmi )
			mFrmMain->getOgreWindow()->deletePrettyObject("Marker"+*jmi);
	}
	else
	{
		std::set_union( mJointsWithMarkers.begin(), mJointsWithMarkers.end(),
			bone_names.begin(), bone_names.end(),
			std::inserter( mJointsWithMarkers, mJointsWithMarkers.end() ) );

		// Joint marker points
		std::vector<Ogre::Vector3> pts;
		pts.push_back(Ogre::Vector3(0,0,0));

		for( std::set<std::string>::const_iterator jmi = bone_names.begin();
			jmi != bone_names.end(); ++jmi )
		{
			mFrmMain->getOgreWindow()->createPrettyObject(
				"Marker"+*jmi, Ogre::RenderOperation::OT_POINT_LIST, pts,
				zhSkeleton_MarkerColor, zhSkeleton_MarkerSize, RENDER_QUEUE_OVERLAY, *jmi );
		}
	}
}

void AnimationStudioApp::displayJointMarker( const std::string& boneName, bool enable )
{
	std::set<std::string> bone_names;
	bone_names.insert(boneName);
	displayJointMarkers( bone_names, enable );
}

bool AnimationStudioApp::hasJointMarker( const std::string& boneName ) const
{
	return mJointsWithMarkers.count(boneName) > 0;
}

void AnimationStudioApp::traceJointPaths( const std::set<std::string>& boneNames, bool enable )
{
	zh::Skeleton* skel = zhAnimationSystem->getOutputSkeleton();
	if( skel == NULL )
		return;
	std::set<std::string> bone_names = boneNames;

	if( bone_names.empty() )
	{
		zh::Skeleton::BoneConstIterator bone_i = skel->getBoneConstIterator();
		while( bone_i.hasMore() )
			bone_names.insert( bone_i.next()->getName() );
	}

	if(!enable)
	{
		std::set<std::string> results;
		std::set_difference( mTracedJoints.begin(), mTracedJoints.end(),
			bone_names.begin(), bone_names.end(), std::inserter( results, results.end() ) );
		mTracedJoints = results;
		mTracedJointAnim = NULL;

		for( std::set<std::string>::const_iterator jmi = bone_names.begin();
			jmi != bone_names.end(); ++jmi )
			mFrmMain->getOgreWindow()->deletePrettyObject("Trace"+*jmi);
	}
	else
	{
		if( getCurrentAnimation() == NULL )
			return;
		else
			mTracedJointAnim = getCurrentAnimation();

		std::set_union( mTracedJoints.begin(), mTracedJoints.end(),
			bone_names.begin(), bone_names.end(),
			std::inserter( mTracedJoints, mTracedJoints.end() ) );

		for( std::set<std::string>::const_iterator jmi = bone_names.begin();
			jmi != bone_names.end(); ++jmi )
		{
			std::vector<Ogre::Vector3> path;
			_computeJointTracePath( *jmi, path );

			mFrmMain->getOgreWindow()->createPrettyObject(
				"Trace"+*jmi, Ogre::RenderOperation::OT_LINE_STRIP, path,
				zhSkeleton_TraceColor, zhSkeleton_MarkerSize, RENDER_QUEUE_WORLD_GEOMETRY_2 );
		}
	}
}

void AnimationStudioApp::traceJointPath( const std::string& boneName, bool enable )
{
	std::set<std::string> bone_names;
	bone_names.insert(boneName);
	traceJointPaths( bone_names, enable );
}

bool AnimationStudioApp::hasJointTrace( const std::string& boneName ) const
{
	return mTracedJoints.count(boneName) > 0;
}

zh::Bone* AnimationStudioApp::createEnvironmentObject(
	const std::string& name, const zh::Vector3& pos )
{
	// Create the bone representing the "object"
	zh::Skeleton* env = zhAnimationSystem->getEnvironment();
	unsigned short obj_id = 0;
	while( env->hasBone(obj_id) ) ++obj_id;
	zh::Bone* obj = env->createBone( obj_id, name );
	env->getRoot()->addChild(obj);
	obj->setInitialPosition(pos);
	obj->resetToInitialPose();

	// Show the object in the scene
	std::vector<Ogre::Vector3> pts;
	pts.push_back( zhOgreVector3(pos) );
	mFrmMain->getOgreWindow()->createPrettyObject( "EnvObj"+obj->getName(),
		Ogre::RenderOperation::OT_POINT_LIST, pts,
		zhSkeleton_EnvObjColor, zhSkeleton_MarkerSize );

	return obj;
}

void AnimationStudioApp::deleteEnvironmentObject( const std::string& name )
{
	// Delete the bone representing the "object"
	zh::Skeleton* env = zhAnimationSystem->getEnvironment();
	if( !env->hasBone(name) ) return;
	env->deleteBone(name);

	// Remove object from the scene
	mFrmMain->getOgreWindow()->deletePrettyObject( "EnvObj"+name );
}

void AnimationStudioApp::deleteAllEnvironmentObjects()
{
	zh::Skeleton* env = zhAnimationSystem->getEnvironment();
	zh::Skeleton::BoneIterator obj_i = env->getBoneIterator();
	std::vector<std::string> objnames;
	while( obj_i.hasMore() )
	{
		zh::Bone* obj = obj_i.next();
		if( obj->getName() != "Root" )
			objnames.push_back(obj->getName());
	}

	for( std::vector<std::string>::iterator name_i = objnames.begin();
		name_i != objnames.end(); ++name_i )
		deleteEnvironmentObject(*name_i);
}

void AnimationStudioApp::useConstFrameRate( bool useConstFR )
{
	mRenderTimer->Stop();
	zh::Animation* cur_anim = getCurrentAnimation();
	if(useConstFR)
	{
		if( cur_anim != NULL && cur_anim->getFrameRate() >= 20 )
			mFrameTime = 1.f/cur_anim->getFrameRate();
		else
			mFrameTime = 1.f/60.f;
		mRenderTimer->Start(1000.f*mFrameTime);
	}
}

bool AnimationStudioApp::frameStarted( const FrameEvent& evt )
{
	if( mCurAnim == NULL )
		traceJointPaths( std::set<std::string>(), false ); // disable joint traces when no anim. selected

	if( mAnimEnabled )
	{
		// Update the ZombieHorse system
		zhAnimationSystem->update(evt.timeSinceLastFrame);
	}

	// Apply updated pose to the skeleton in viewport
	mFrmMain->getOgreWindow()->updateRenderSkeletonPose( zhAnimationSystem->getOutputSkeleton() );

	return true;
}

bool AnimationStudioApp::frameEnded( const FrameEvent& evt )
{
	return true;
}

void AnimationStudioApp::resize( unsigned int width, unsigned int height )
{
	if( mRenderWnd )
		mRenderWnd->windowMovedOrResized();
}

int AnimationStudioApp::FilterEvent( wxEvent& evt )
{
	if( evt.GetEventType() == wxEVT_KEY_DOWN )
	{
		int kc = ((wxKeyEvent&)evt).GetKeyCode();
		if( kc == WXK_F9 )
		{
			// Toggle root IK
			_toggleIK( RootIKSolver::ClassId() );
			return true;
		}
		else if( kc == WXK_F10 )
		{
			// Toggle posture IK
			_toggleIK( PostureIKSolver::ClassId() );
			return true;
		}
		else if( kc == WXK_F11 )
		{
			// Toggle limb IK
			_toggleIK( LimbIKSolver::ClassId() );
			return true;
		}
		else if( kc == WXK_F12 )
		{
			// Toggle prediction
			zh::Animation* anim = zhAnimationSystem->getCurrentAnimation();
			if( anim != NULL )
			{
				AnimationNode* node = zhAnimationSystem->getAnimationTree()->getNode( anim->getFullName() );
				AnimationAdaptor* adapt = node->getAdaptor();
				if( node->getAdaptor() != NULL )
				{
					if( adapt->getPredictionWeight() > 0 )
						adapt->setPredictionWeight(0);
					else
						adapt->setPredictionWeight(0.15f);
				}
			}
			return true;
		}
    }

    return -1;
}

bool AnimationStudioApp::OnInit()
{
	gApp = this;

	// create main application window
	mFrmMain = new AnimationStudioFrame( ID_frmMain, "Animation Studio", wxPoint( 0, 0 ),
		wxSize( 1280, 800 ) );
	if( mFrmMain == NULL ) return false;
	mFrmMain->Show();
	wxInitAllImageHandlers();
	SetTopWindow(mFrmMain);

	// initialize OGRE and ZombieHorse
	if( !init( mFrmMain->getOgreWindow() ) )
		return false;

	return true;
}

int AnimationStudioApp::OnExit()
{
	destroyScene();
	if( mOgreRoot != NULL ) delete mOgreRoot;

	return wxApp::OnExit();
}

void AnimationStudioApp::OnIdle( wxIdleEvent& evt )
{
	if( mRenderTimer->IsRunning() )
		// Rendering at constant framerate, skip this
		return;

	mOgreRoot->renderOneFrame();
	evt.RequestMore();
}

bool AnimationStudioApp::init( wxWindow* wnd )
{
	#ifdef _DEBUG
	mOgreRoot = new Root( "plugins_d.cfg", "ogre_d.cfg", "ogre_d.log" );
	#else
	mOgreRoot = new Root( "plugins.cfg", "ogre.cfg", "ogre.log" );
	#endif

	if( !initOgreCore(wnd) ||
		!createSceneManager() ||
		!createCamera() ||
		!createViewports() )
		return false;
	TextureManager::getSingleton().setDefaultNumMipmaps(5);
	if( !loadResourceLocations() ||
		!createFrameListener() ||
		!createScene() ||
		!mFrmMain->getOgreWindow()->init() )
		return false;

	if( !initZombieHorse() )
		return false;

	// Add OGRE resource directories
	mOgreRoot->addResourceLocation( "../../samples/data/OGRE/models", "FileSystem", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
	mOgreRoot->addResourceLocation( "../../samples/data/OGRE/scenes", "FileSystem", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
	mOgreRoot->addResourceLocation( "../../samples/data/OGRE/materials/scripts", "FileSystem", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
	mOgreRoot->addResourceLocation( "../../samples/data/OGRE/materials/programs", "FileSystem", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );
	mOgreRoot->addResourceLocation( "../../samples/data/OGRE/materials/textures", "FileSystem", ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME );

	// Load ZombieHorse resources
	boost::filesystem::recursive_directory_iterator end;
	for( boost::filesystem::recursive_directory_iterator dir("../../samples/data/animations");
		dir != end; ++dir )
	{
		boost::filesystem::directory_entry bdir = (*dir);
		boost::filesystem::path bpath = bdir.path();
		std::string path = bpath.string();
		std::transform( path.begin(), path.end(), path.begin(), ::tolower );
		if( path.substr(path.size()-4) ==  ".bvh" || path.substr(path.size()-4) ==  ".zha" )
			zhAnimationSystem->loadAnimationSet(path);
	}

	// Auto-tag all skeletons and create IK solvers on them
	// TODO: one day we'll have a config file or script that specifies these things
	AnimationSystem::SkeletonIterator skel_i = zhAnimationSystem->getSkeletonIterator();
	while( skel_i.hasMore() )
	{
		zh::Skeleton* skel = skel_i.next();
		// TODO: fix auto-tagging in BVHLoader...
		skel->_removeAllBoneTags();
		if( skel->hasBone("0_Hips") ) skel->getBone("0_Hips")->tag(BT_Root);
		if( skel->hasBone("13_lowerback") ) skel->getBone("13_lowerback")->tag(BT_LowerBack);
		if( skel->hasBone("15_Chest") ) skel->getBone("15_Chest")->tag(BT_Chest);
		if( skel->hasBone("2_LeftHip") ) skel->getBone("2_LeftHip")->tag(BT_LHip);
		if( skel->hasBone("3_LeftKnee") ) skel->getBone("3_LeftKnee")->tag(BT_LKnee);
		if( skel->hasBone("4_LeftAnkle") ) skel->getBone("4_LeftAnkle")->tag(BT_LAnkle);
		if( skel->hasBone("8_RightHip") ) skel->getBone("8_RightHip")->tag(BT_RHip);
		if( skel->hasBone("9_RightKnee") ) skel->getBone("9_RightKnee")->tag(BT_RKnee);
		if( skel->hasBone("10_RightAnkle") ) skel->getBone("10_RightAnkle")->tag(BT_RAnkle);
		if( skel->hasBone("21_LeftShoulder") ) skel->getBone("21_LeftShoulder")->tag(BT_LShoulder);
		if( skel->hasBone("22_LeftElbow") ) skel->getBone("22_LeftElbow")->tag(BT_LElbow);
		if( skel->hasBone("23_LeftWrist") ) skel->getBone("23_LeftWrist")->tag(BT_LWrist);
		if( skel->hasBone("30_RightShoulder") ) skel->getBone("30_RightShoulder")->tag(BT_RShoulder);
		if( skel->hasBone("31_RightElbow") ) skel->getBone("31_RightElbow")->tag(BT_RElbow);
		if( skel->hasBone("32_RightWrist") ) skel->getBone("32_RightWrist")->tag(BT_RWrist);
		if( skel->hasBone("20_LeftCollar") ) skel->getBone("20_LeftCollar")->tag(BT_LCollar);
		if( skel->hasBone("29_RightCollar") ) skel->getBone("29_RightCollar")->tag(BT_RCollar);
		if( skel->hasBone("1_LHipJoint") ) skel->getBone("1_LHipJoint")->tag(BT_LHipJoint);
		if( skel->hasBone("7_RHipJoint") ) skel->getBone("7_RHipJoint")->tag(BT_RHipJoint);
		//
		zhAnimationSystem->createIKSolversOnSkeleton( skel->getName() );
	}

	zh::Skeleton* out_skel = zhAnimationSystem->getOutputSkeleton();
	if( out_skel == NULL )
	{
		// No skeletons or animations to be found
		wxMessageBox( "No animations found in the project directory. This application will now exit.",
			"Warning", wxOK | wxICON_WARNING );
		ExitMainLoop();
	}

	// Create user-editable skeleton and set it as default
	zh::Skeleton* skel = zhAnimationSystem->createSkeleton("TestFigure");
	out_skel->_clone(skel);
	zhAnimationSystem->createIKSolversOnSkeleton( skel->getName() );
	zhAnimationSystem->setOutputSkeleton( skel->getName() );
	mFrmMain->getOgreWindow()->setRenderSkeleton(skel);
	mParamSkelEditor->init(skel);

	// Update window contents
	mFrmMain->refresh();

	return true;
}

bool AnimationStudioApp::initOgreCore( wxWindow* renderWnd  )
{
	if( !mOgreRoot->restoreConfig() && !mOgreRoot->showConfigDialog() )
		return false;

	if( renderWnd == NULL )
	{
		this->mRenderWnd = mOgreRoot->initialise(true);
	}
	else
	{
		this->mRenderWnd = mOgreRoot->initialise(false);
		NameValuePairList params;
		params["externalWindowHandle"] = StringConverter::toString( (int)renderWnd->GetHandle() );
		this->mRenderWnd = mOgreRoot->createRenderWindow( "OGRE render window",
			renderWnd->GetRect().GetWidth(),
			renderWnd->GetRect().GetHeight(), false, &params );
	}

	return true;
}

bool AnimationStudioApp::createSceneManager()
{
	mSceneMgr = mOgreRoot->createSceneManager( ST_GENERIC );

	return true;
}

bool AnimationStudioApp::createCamera()
{
	mCam = mSceneMgr->createCamera( "MainCam" );
	mCam->setPosition( zhCamera_Pos );
	mCam->lookAt( zhCamera_Focus );
	mCam->setNearClipDistance(0.01f);
	mCam->setFarClipDistance(3000.f);
	mCam->setAutoAspectRatio(true);

	return true;
}

bool AnimationStudioApp::createViewports()
{
	Viewport* viewport = mRenderWnd->addViewport( mCam );
	viewport->setBackgroundColour( ColourValue( 0, 0, 0 ) );
	mCam->setAspectRatio(
		Real( viewport->getActualWidth() ) / Real( viewport->getActualHeight() ) );

	return true;
}

bool AnimationStudioApp::createFrameListener()
{
	mOgreRoot->addFrameListener(this);
	mOgreRoot->addFrameListener( mFrmMain->getOgreWindow() );

	return true;
}

bool AnimationStudioApp::loadResourceLocations()
{
	ConfigFile res_cfg;
	res_cfg.load( "resources.cfg" );

	ConfigFile::SectionIterator si = res_cfg.getSectionIterator();
	String sec_name, type_name, arch_name;

	while( si.hasMoreElements() )
	{
		sec_name = si.peekNextKey();
		ConfigFile::SettingsMultiMap* settings = si.getNext();

		for( ConfigFile::SettingsMultiMap::iterator i = settings->begin();
			i != settings->end(); ++i )
		{
			type_name = i->first;
			arch_name = i->second;

			ResourceGroupManager::getSingleton().addResourceLocation(
				arch_name, type_name, sec_name );
		}
	}

	// initialize resource groups (doesn't actually load all the resources)
	ResourceGroupManager::getSingleton().initialiseAllResourceGroups();

	return true;
}

bool AnimationStudioApp::createScene()
{
	mFrmMain->getOgreWindow()->showGround();
	mFrmMain->getOgreWindow()->showSkybox();

	// Setup lighting
	mSceneMgr->setAmbientLight( ColourValue( 0.8f, 0.8f, 0.8f ) );
	Light* sunlight = mSceneMgr->createLight( "Sunlight1" );
	sunlight->setType( Light::LT_DIRECTIONAL );
	sunlight->setDiffuseColour( ColourValue( 1.f, 1.f, 1.f ) );
	sunlight->setSpecularColour( ColourValue( 1.f, 1.f, 1.f ) );
	sunlight->setDirection( Ogre::Vector3( -1.f, 0.f, -1.f ) );
	sunlight = mSceneMgr->createLight( "Sunlight2" );
	sunlight->setType( Light::LT_DIRECTIONAL );
	sunlight->setDiffuseColour( ColourValue( 1.f, 1.f, 1.f ) );
	sunlight->setSpecularColour( ColourValue( 1.f, 1.f, 1.f ) );
	sunlight->setDirection( Ogre::Vector3( -1.f, 0.f, 1.f ) );

	return true;
}

bool AnimationStudioApp::destroyScene()
{
	mSceneMgr->clearScene();

	return true;
}

bool AnimationStudioApp::initZombieHorse()
{
	zhAnimationSystem->init();
	zhAnimationDatabaseSystem->init();

	return true;
}

void AnimationStudioApp::_toggleIK( unsigned long solverClassId )
{
	zh::Skeleton* skel = zhAnimationSystem->getOutputSkeleton();
	if( skel != NULL && skel->getNumIKSolvers() > 0 )
	{
		zh::Skeleton::IKSolverIterator solver_i = skel->getIKSolverIterator();
		while( solver_i.hasMore() )
		{
			IKSolver* solver = solver_i.next();
			if( solver->getClassId() == solverClassId )
				solver->setEnabled( !solver->getEnabled() );
		}
	}
}

void AnimationStudioApp::_computeJointTracePath( const std::string& boneName,
	std::vector<Ogre::Vector3>& path )
{
	zh::Skeleton* skel = zhAnimationSystem->getOutputSkeleton();
	zhAssert( skel != NULL );
	zhAssert( mTracedJointAnim != NULL );

	float dt = 1/60.f;
	for( float t = 0; t <= mTracedJointAnim->getLength(); t += dt )
	{
		skel->resetToInitialPose();
		mTracedJointAnim->apply( skel, t, 1, 1, zh::Animation::EmptyBoneMask );
		zh::Vector3 pt = skel->getBone(boneName)->getWorldPosition();
		path.push_back( zhOgreVector3(pt) );
	}
}

BEGIN_EVENT_TABLE( AnimationStudioApp, wxApp )
	EVT_IDLE( AnimationStudioApp::OnIdle )
END_EVENT_TABLE()

IMPLEMENT_APP(AnimationStudioApp)

max_stars_repo_name: tpejsa/ZombieHorse

max_issues_repo_name: tpejsa/ZombieHorse

max_forks_repo_name: tpejsa/ZombieHorse


text:
#ifndef BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_MAJOR_VERSION_HPP_20101120
#define BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_MAJOR_VERSION_HPP_20101120

// Copyright 2010 Dean Michael Berris.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/cstdint.hpp>

namespace boost { namespace network { namespace http {

struct major_version_directive {
  boost::uint8_t major_version;
  explicit major_version_directive(boost::uint8_t major_version);
  void operator()(request_base &request) const;
};

inline major_version_directive
major_version(boost::uint8_t major_version_) {
  return major_version_directive(major_version_);
}

} /* http */

} /* network */

} /* boost */

#endif /* BOOST_NETWORK_PROTOCOL_HTTP_MESSAGE_DIRECTIVES_MAJOR_VERSION_HPP_20101120 */

max_stars_repo_name: sureandrew/cpp-netlib

max_issues_repo_name: sureandrew/cpp-netlib

max_forks_repo_name: sureandrew/cpp-netlib


text:
#include <limiter.h>
#include <simd.template.h>

#include <deal.II/base/vectorization.h>

using namespace ryujin;
using namespace dealii;

/* Explicitly instantiate all variants: */

template class ryujin::Limiter<1>;
template class ryujin::Limiter<2>;
template class ryujin::Limiter<3>;

template class ryujin::Limiter<1, float>;
template class ryujin::Limiter<2, float>;
template class ryujin::Limiter<3, float>;

template class ryujin::Limiter<1, VectorizedArray<double>>;
template class ryujin::Limiter<2, VectorizedArray<double>>;
template class ryujin::Limiter<3, VectorizedArray<double>>;

template class ryujin::Limiter<1, VectorizedArray<float>>;
template class ryujin::Limiter<2, VectorizedArray<float>>;
template class ryujin::Limiter<3, VectorizedArray<float>>;

int main()
{
  return 0;
}

ext: cc

max_stars_repo_name: Fanxiaotsing/ryujin

max_issues_repo_name: Fanxiaotsing/ryujin

max_forks_repo_name: Fanxiaotsing/ryujin


text:
//          Copyright Camille Gillot 2012 - 2015.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// allow room for some optimizations

#include "mmethod/config.hpp"

#ifndef MMETHOD_ATTRIBUTE_PURE
#if defined(__GNUC__)
#define MMETHOD_ATTRIBUTE_PURE __attribute__((pure))
#else
#define MMETHOD_ATTRIBUTE_PURE
#endif
#endif

#ifndef MMETHOD_ATTRIBUTE_UNUSED
#ifdef BOOST_ATTRIBUTE_UNUSED
#define MMETHOD_ATTRIBUTE_UNUSED BOOST_ATTRIBUTE_UNUSED
#else
#include <boost/static_assert.hpp>
#define MMETHOD_ATTRIBUTE_UNUSED BOOST_STATIC_ASSERT_UNUSED_ATTRIBUTE
#endif
#endif

#ifndef MMETHOD_ATTRIBUTE_ALIGNED
#ifdef __GNUC__
#define MMETHOD_ATTRIBUTE_ALIGNED __attribute__((aligned(2)))
#else
#define MMETHOD_ATTRIBUTE_ALIGNED
#endif
#endif

max_stars_repo_name: cjgillot/rtti

max_issues_repo_name: cjgillot/rtti

max_forks_repo_name: cjgillot/rtti


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

#include <boost/test/unit_test.hpp>
#include "lzasm/arm/arm32/divided_thumb_assembler.hpp"
#include "assembler_test_utilities.hpp"
#include "test_utilities.hpp"

namespace lzasm_unittest
{

using namespace ::lzasm::arm::arm32;

BOOST_AUTO_TEST_SUITE(divided_thumb_assembler_test)

    BOOST_AUTO_TEST_SUITE(push_pop)

        BOOST_AUTO_TEST_SUITE(pop)

            BOOST_AUTO_TEST_CASE(one_register)
            {
                CHECK(pop(r0), H(0xbc01));
                CHECK(pop(pc), H(0xbd00));
            }

            BOOST_AUTO_TEST_CASE(comma_separated_registers)
            {
                CHECK(pop(r0, r2, r4, r6, pc), H(0xbd55));
                CHECK(pop(r1, r3, r5, r7), H(0xbcaa));
            }

            BOOST_AUTO_TEST_CASE(register_ranges)
            {
                CHECK(pop(r0 - r3), H(0xbc0f));
                CHECK(pop(r4 - r7), H(0xbcf0));
                CHECK(pop(r0 - r2, r4 - r6), H(0xbc77));
            }

            BOOST_AUTO_TEST_CASE(comma_separated_registers_and_ranges)
            {
                CHECK(pop(r1, r3, r5 - r7, pc), H(0xbdea));
                CHECK(pop(r0 - r7, pc), H(0xbdff));
            }

        BOOST_AUTO_TEST_SUITE_END()

        BOOST_AUTO_TEST_SUITE(push)

            BOOST_AUTO_TEST_CASE(one_register)
            {
                CHECK(push(r0), H(0xb401));
                CHECK(push(lr), H(0xb500));
            }

            BOOST_AUTO_TEST_CASE(comma_separated_registers)
            {
                CHECK(push(r0, r2, r4, r6, lr), H(0xb555));
                CHECK(push(r1, r3, r5, r7), H(0xb4aa));
            }

            BOOST_AUTO_TEST_CASE(register_ranges)
            {
                CHECK(push(r0 - r3), H(0xb40f));
                CHECK(push(r4 - r7), H(0xb4f0));
                CHECK(push(r0 - r2, r4 - r6), H(0xb477));
            }

            BOOST_AUTO_TEST_CASE(comma_separated_registers_and_ranges)
            {
                CHECK(push(r1, r3, r5 - r7, lr), H(0xb5ea));
                CHECK(push(r0 - r7, lr), H(0xb5ff));
            }

        BOOST_AUTO_TEST_SUITE_END()

    BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

}


text:
#include "i_render.h"
#include "actor_renderer.h"
#include "core/i_position_component.h"
#include "core/i_inventory_component.h"
#include "core/i_health_component.h"
#include "core/i_collision_component.h"
#include "core/i_renderable_component.h"
#include "core/actor.h"
#include "recognizer.h"
#include "shader_manager.h"
#include "input/mouse.h"
#include "engine/engine.h"
#include "engine/activity_system.h"
#include "core/program_state.h"
#include "core/scene.h"
#include "renderable_repo.h"
#include "i_visual_box_multiplier_component.h"
#include "sprite_phase_cache.h"
#include "platform/game_clock.h"
#include "main/window.h"
#include <boost/ref.hpp>
#include "action_renderer_loader_repo.h"

void ActorRenderer::Init()
{
    mVAO.Init();
    mOnActorEvent = EventServer<ActorEvent>::Get().Subscribe( boost::bind( &ActorRenderer::OnActorEvent, this, _1 ) );
    mMouseMoveId = EventServer<WorldMouseMoveEvent>::Get().Subscribe( boost::bind( &ActorRenderer::OnMouseMoveEvent, this, _1 ) );
}

void ActorRenderer::OnActorEvent( ActorEvent const& Evt )
{
    if( Evt.mState == ActorEvent::Added )
    {
        mActionRenderersMap[Evt.mActor->GetGUID()];
    }
    else if ( Evt.mState == ActorEvent::Removed )
    {
        mActionRenderersMap.erase( Evt.mActor->GetGUID() );
    }
}

ActorRenderer::ActorRenderer()
    : mRecognizerRepo( RecognizerRepo::Get() )
    , mActionRendererFactory( ActionRendererFactory::Get() )
    , mPrevSize( 0 )
    , mX(0)
    , mY(0)
    , mTexIndex(0)
    , mSecondaryTexIndex(0)
    , mPosIndex(0)
    , mHeadingIndex(0)
    , mSizeIndex(0)
    , mColorIndex(0)
{
    Init();
}

namespace {
typedef std::vector<glm::vec2> Positions_t;
typedef std::vector<GLfloat> Floats_t;
typedef std::vector<glm::vec4> TexCoords_t;
typedef std::vector<glm::vec4> Colors_t;
typedef ActorRenderer::RenderableSprites_t RenderableSprites_t;
glm::vec2 visMultiplier( Actor const& actor )
{
    Opt<render::IVisualBoxMultiplierComponent> const& vbox = actor.Get<render::IVisualBoxMultiplierComponent>();
    if( vbox.IsValid() )
    {
        return glm::vec2( vbox->GetWidth(), vbox->GetHeight() );
    }
    return glm::vec2( 1.0, 1.0 );
}
bool isVisible( Actor const& actor, std::vector<Camera const*> const& cameras )
{
    Opt<IPositionComponent> const positionC = actor.Get<IPositionComponent>();
    if( !positionC.IsValid() )
    {
        return false;
    }
    Opt<IRenderableComponent> const renderableC = actor.Get<IRenderableComponent>();
    if( !renderableC.IsValid() )
    {
        return false;
    }
    static RenderableRepo& renderables( RenderableRepo::Get() );
    float scale = renderables.GetMaxScale( actor.GetId() );
    Opt<ICollisionComponent> const collisionC = actor.Get<ICollisionComponent>();
    glm::vec2 const& visMulti = visMultiplier( actor );
    float vmult = std::max<float>( visMulti.x, visMulti.y );
    // 2.0 multiplier: safety
    float size = ( collisionC.IsValid() ? collisionC->GetRadius() : 50 ) * scale * 2.0 * vmult;
    for( auto camera : cameras )
    {
        glm::vec4 const& region = camera->VisibleRegion();
        if( region.x < positionC->GetX() + size && region.z > positionC->GetX() - size
            && region.y < positionC->GetY() + size && region.w > positionC->GetY() - size )
        {
            return true;
        }
    }
    return false;
}
bool getNextTextId( RenderableSprites_t::const_iterator& i, RenderableSprites_t::const_iterator e,
                    glm::vec2*& Positions, GLfloat*& Headings,
                    glm::vec4*& TexCoords, glm::vec4*& SecondaryTexCoords,
                    glm::vec4*& MaskTexCoords, glm::vec4*& NormalTexCoords,
                    glm::vec2*& Sizes, glm::vec4*& Colors,
                    std::map<int32_t, std::vector<glm::vec4> >& postprocColors,
                    GLfloat*& ShadowLenScales,
                    size_t& cnt,
                    render::RenderBatch& batch )
{
    static int32_t prevNormalId = -1;
    static int32_t prevsecid = -1;
    if( i == e )
    {
        prevNormalId = -1;
        prevsecid = -1;
        return false;
    }
    batch.TexId = i->Spr->TexId;
    // mask id is by default the tex id ( if no additional alpha masking is necessary )
    batch.MaskId = batch.TexId;
    batch.NormalId = prevNormalId;
    // we don't swap back from a valid sec. tex id to -1
    // so there are less RenderBatch changes in render::count
    batch.SecondaryTexId = prevsecid;
    batch.ShaderId = i->RenderableComp->GetShaderId();
    (*Positions++) = glm::vec2( i->PositionC->GetX(), i->PositionC->GetY() ) + i->RelativePosition;
    (*Headings++) = ( GLfloat )i->PositionC->GetOrientation() + i->RelativeOrientation;
    (*ShadowLenScales++) = (GLfloat)i->RenderableComp->GetShadowLenScale();

    float const radius = (( i->CollisionC != nullptr ? i->CollisionC->GetRadius() : 50 )
                            + i->RelativeRadius) *i->Anim->GetScale();
    auto const size = radius * visMultiplier( *(i->Obj) );
    (*Sizes) = size;
    ++Sizes;

    glm::vec4 secondaryTexCoord(-1,-1,-1,-1);
    SpritePhase const* Spr = nullptr;
    if( !i->AdditionalSprs.empty() )
    {
        Spr = i->AdditionalSprs.front();
        secondaryTexCoord = glm::vec4( Spr->Left, Spr->Right, Spr->Bottom, Spr->Top );
        prevsecid = batch.SecondaryTexId = Spr->TexId;
    }
    (*SecondaryTexCoords++) = secondaryTexCoord;
    auto coords = glm::vec4( i->Spr->Left, i->Spr->Right, i->Spr->Bottom, i->Spr->Top );
    (*TexCoords++) = coords;
    if( i->MaskSpr != nullptr )
    {
        batch.MaskId = i->MaskSpr->TexId;
        coords = glm::vec4( i->MaskSpr->Left, i->MaskSpr->Right, i->MaskSpr->Bottom, i->MaskSpr->Top );
    }
    (*MaskTexCoords++) = coords;
    coords = glm::vec4( -1, -1, -1, -1 );
    if( i->NormalSpr != nullptr )
    {
        prevNormalId = batch.NormalId = i->NormalSpr->TexId;
        coords = glm::vec4( i->NormalSpr->Left, i->NormalSpr->Right, i->NormalSpr->Bottom, i->NormalSpr->Top );
    }
    (*NormalTexCoords++) = coords;
    (*Colors++) = i->Color;
    {   // move to cache
        static render::SpritePhaseCache& cache( render::SpritePhaseCache::Get() );
        cache.Request( *i->Spr, std::max( size.x, size.y ) );
        if( Spr != nullptr )
        {
            cache.Request( *Spr, std::max( size.x, size.y ) );
        }
        if( i->MaskSpr != nullptr )
        {
            cache.Request( *i->MaskSpr, std::max( size.x, size.y ) );
        }
        if( i->NormalSpr != nullptr )
        {
            cache.Request( *i->NormalSpr, std::max( size.x, size.y ) );
        }
    }
    for( auto id : i->RenderableComp->GetPostProcessIds() )
    {
        postprocColors[ id ][cnt] = glm::vec4(1,1,1,1);
    }
    ++i;
    ++cnt;
    return true;
}
}

void ActorRenderer::Prepare( Scene const& , std::vector<Camera const*> const& cameras, double DeltaTime )
{
    static auto activityS = engine::Engine::Get().GetSystem<engine::ActivitySystem>();
    auto const& Lst = activityS->GetActiveActors();
    if( Lst.empty() )
    {
        mRenderableSprites.clear(); // renderable sprites still can contain obsolete sprites, so render nothing instead of invalid object
        mCounts.clear();
        mPostprocessColors.clear();
        return;
    }
    RenderableSprites_t RenderableSprites;
    RenderableSprites.reserve( mRenderableSprites.size() );
    std::set<int32_t> postprocids;
    for( auto i = Lst.begin(), e = Lst.end(); i != e; ++i )
    {
        const Actor& Object = **i;
        if( !isVisible( Object, cameras ) )
        {
            continue;
        }
        auto recogptr = mRecognizerRepo.GetRecognizers( Object.GetId() );
        if( nullptr == recogptr || recogptr->empty() )
        {
            continue;
        }
        Opt<IRenderableComponent> renderableC( Object.Get<IRenderableComponent>() );
        auto const& pp = renderableC->GetPostProcessIds();
        postprocids.insert( pp.begin(), pp.end() );
        auto const& recognizers = *recogptr;
        RecognizerRepo::ExcludedRecognizers_t excluded;

        ActionRenderersMap_t::iterator actionRenderersIt = mActionRenderersMap.find( Object.GetGUID() );
        BOOST_ASSERT( actionRenderersIt != mActionRenderersMap.end() );
        ActionRenderers_t& actionRenderers = actionRenderersIt->second;

        for ( auto recogIt = recognizers.begin(), recogE = recognizers.end(); recogIt != recogE; ++recogIt )
        {
            auto const& recognizer = *recogIt;
            if ( excluded.find( recognizer.GetId() ) == excluded.end()
                 && recognizer.Recognize( Object ) )
            {
                int32_t actionRendererId = recognizer.GetActionRenderer();
                ActionRenderers_t::iterator foundActionRendererIt =
                    std::find_if( actionRenderers.begin(), actionRenderers.end(), FindActionRenderer( actionRendererId ) );
                if ( foundActionRendererIt == actionRenderers.end() )
                {
                    static auto& mActionRendererLoaderRepo( render::ActionRendererLoaderRepo::Get() );
                    std::auto_ptr<ActionRenderer> actionRenderer( mActionRendererFactory( actionRendererId ) );
                    actionRenderer->SetOrder( recognizer.GetOrder() );
                    actionRenderer->Init( Object );
                    auto const& loader = mActionRendererLoaderRepo(Object.GetId(), actionRendererId );
                    actionRenderer = loader.FillProperties( actionRenderer );
                    actionRenderers.insert( actionRenderer );
                }
                auto excludedRecognizers = mRecognizerRepo.GetExcludedRecognizers( recognizer.GetId() );
                if( nullptr != excludedRecognizers )
                {
                    excluded.insert( excludedRecognizers->begin(), excludedRecognizers->end() );
                }
            }
        }
        for ( auto excludedIt = excluded.begin(), excludedE = excluded.end(); excludedIt != excludedE; ++excludedIt )
        {
            auto arIt = std::find_if( actionRenderers.begin(), actionRenderers.end(), FindActionRenderer( *excludedIt ) );
            if( arIt != actionRenderers.end() )
            {
                actionRenderers.erase( arIt );

            }
        }
        for ( auto actionRendererIt = actionRenderers.begin(), actionRendererE = actionRenderers.end(); actionRendererIt != actionRendererE; ++actionRendererIt )
        {
            ActionRenderer& actionRenderer = *actionRendererIt;
            actionRenderer.FillRenderableSprites( Object, *renderableC.Get(), RenderableSprites );
            actionRenderer.Update( DeltaTime );
        }
    }
    std::swap( RenderableSprites, mRenderableSprites );
    size_t CurSize = mRenderableSprites.size();
    if( CurSize == 0 )
    {
        mCounts.clear();
        mPostprocessColors.clear();
        return;
    }

    Positions_t Positions( CurSize );
    Floats_t Headings( CurSize );
    Floats_t ShadowLenScales( CurSize );
    Positions_t Sizes( CurSize );
    TexCoords_t TexCoords( CurSize );
    TexCoords_t SecondaryTexCoords( CurSize );
    TexCoords_t MaskTexCoords( CurSize );
    TexCoords_t NormalTexCoords( CurSize );
    Colors_t Colors( CurSize );
    postprocids.insert( -1 );
    mPostprocessColors.clear();
    for( auto id : postprocids )
    {
        mPostprocessColors[ id ] = Colors_t( CurSize, glm::vec4(0,0,0,1) );
    }

    glm::vec2* posptr = &Positions[0];
    GLfloat* hptr = &Headings[0];
    GLfloat* shadowlenscaleptr = &ShadowLenScales[0];
    glm::vec2* sptr = &Sizes[0];
    glm::vec4* tptr = &TexCoords[0];
    glm::vec4* stptr = &SecondaryTexCoords[0];
    glm::vec4* mtptr = &MaskTexCoords[0];
    glm::vec4* ntptr = &NormalTexCoords[0];
    glm::vec4* cptr = &Colors[0];
    size_t cnt = 0;
    RenderableSprites_t::const_iterator i = mRenderableSprites.begin();
    mCounts = render::count(
        std::bind( &getNextTextId, std::ref( i ), mRenderableSprites.end(),
        std::ref( posptr ), std::ref( hptr ), std::ref( tptr ),
        std::ref( stptr ), std::ref(mtptr), std::ref(ntptr),
        std::ref( sptr ), std::ref( cptr ), std::ref( mPostprocessColors ),
        std::ref( shadowlenscaleptr ),
        std::ref( cnt ),
        std::placeholders::_1 )
    );
    mVAO.Bind();

    if( CurSize > mPrevSize )
    {
        mPrevSize = CurSize;
        size_t TotalSize = CurSize * ( 2 * sizeof( glm::vec4 ) + 2 * sizeof( glm::vec2 ) + 2 * sizeof( GLfloat ) + 4 * sizeof( glm::vec4 ) );
        glBufferData( GL_ARRAY_BUFFER, TotalSize, NULL, GL_DYNAMIC_DRAW );
    }

    size_t CurrentOffset = 0;
    size_t CurrentSize = CurSize * sizeof( glm::vec4 );
    GLuint CurrentAttribIndex = 0;
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &TexCoords[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mTexIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &SecondaryTexCoords[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mSecondaryTexIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec2 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Positions[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mPosIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( GLfloat );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Headings[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mHeadingIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec2 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Sizes[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mSizeIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Colors[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mColorIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &MaskTexCoords[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mMaskTexCoordIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &NormalTexCoords[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mNormalTexCoordIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( GLfloat );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &ShadowLenScales[0] );
    glEnableVertexAttribArray( CurrentAttribIndex );
    mShadowLenScaleIndex = CurrentOffset;
    ++CurrentAttribIndex;

    CurrentOffset += CurrentSize;
    CurrentSize = CurSize * sizeof( glm::vec4 );
    glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &mPostprocessColors[-1][0] );
    // no need to actually upload this, random mem is just fine
    // although it might be faster to just upload everything at prepare time
    glEnableVertexAttribArray( CurrentAttribIndex );
    mPostprocessColorIndex = CurrentOffset;
    mVAO.Unbind();
}

namespace {
void partitionByFilter( render::Counts_t& rv, RenderableSprites_t const& sprites, render::CountByTexId const& part, ActorRenderer::RenderFilter const& filter )
{
    rv.clear();
    size_t idx = part.Start;
    render::CountByTexId* actual = NULL;
    bool match = false;
    IRenderableComponent const* prevRC = nullptr;
    for( auto i = sprites.begin() + part.Start, e = sprites.begin() + part.Start + part.Count; i != e; ++i, ++idx )
    {
        auto const& val = *i;
        if( prevRC != val.RenderableComp )
        {
            match = filter( *val.RenderableComp );
            prevRC = val.RenderableComp;
        }
        if( !match )
        {
            actual = NULL;
        }
        else
        {
            if( NULL == actual )
            {
                rv.push_back( part );
                actual = &rv.back();
                actual->Start = idx;
                actual->Count = 0;
            }
            ++actual->Count;
        }
    }
}
}

void ActorRenderer::Draw( RenderFilter filter, SetupFunction setup, size_t extraInstances )
{
    if( mRenderableSprites.empty() )
    {
        return;
    }
    mVAO.Bind();
    ShaderManager& ShaderMgr( ShaderManager::Get() );
    static int32_t def = AutoId( "sprite2" );
    ShaderMgr.SetDefaultShader( def );
    for( render::Counts_t::const_iterator i = mCounts.begin(), e = mCounts.end(); i != e; ++i )
    {
        render::CountByTexId const& BigPart = *i;
        ShaderMgr.ActivateShader( BigPart.Batch.ShaderId );
        glActiveTexture( GL_TEXTURE0 + 1 );
        glBindTexture( GL_TEXTURE_2D, BigPart.Batch.TexId );
        ShaderMgr.UploadData( "spriteTexture", GLuint( 1 ) );
        if( BigPart.Batch.NormalId != -1 )
        {
            glActiveTexture( GL_TEXTURE0 + 2 );
            glBindTexture( GL_TEXTURE_2D, BigPart.Batch.NormalId );
            ShaderMgr.UploadData( "normalTexture", GLuint( 2 ) );
        }
        if( BigPart.Batch.SecondaryTexId != -1 )
        {
            glActiveTexture( GL_TEXTURE0 + 3 );
            glBindTexture( GL_TEXTURE_2D, BigPart.Batch.SecondaryTexId );
            ShaderMgr.UploadData( "secondarySpriteTexture", GLuint( 3 ) );
        }
        ShaderMgr.UploadData( "time", GLfloat( platform::Clock::Now() ) );
        int w, h;
        static auto Window = engine::Engine::Get().GetSystem<engine::WindowSystem>();
        Window->GetWindowSize( w, h );
        ShaderMgr.UploadData( "resolution", glm::vec2( w, h ) );
        if( setup )
        {
            setup( ShaderMgr );
        }
        render::Counts_t parts;
        partitionByFilter( parts, mRenderableSprites, BigPart, filter );
        for( auto const& Part : parts )
        {
            DrawOnePart( Part, 4 + extraInstances * 4 );
        }
    }
    glActiveTexture( GL_TEXTURE0 );
    mVAO.Unbind();
}

void ActorRenderer::Draw( int32_t postprocid )
{
    if( mRenderableSprites.empty() || mCounts.empty() )
    {
        return;
    }
    auto ppcit = mPostprocessColors.find( postprocid );
    if( ppcit == mPostprocessColors.end() )
    {
        return;
    }
    auto const& ppc = ppcit->second;
    if( ppc.empty() )
    {
        return;
    }
    mVAO.Bind();
    ShaderManager& ShaderMgr( ShaderManager::Get() );
    static int32_t def = AutoId( "postprocessor_select" );
    ShaderMgr.ActivateShader( def );
    glBufferSubData( GL_ARRAY_BUFFER, mPostprocessColorIndex, sizeof(glm::vec4) * ppc.size(), &ppc[0] );
    for( auto const& BigPart : mCounts )
    {
        glActiveTexture( GL_TEXTURE0 + 1 );
        glBindTexture( GL_TEXTURE_2D, BigPart.Batch.MaskId );
        ShaderMgr.UploadData( "spriteTexture", GLuint( 1 ) );
        DrawOnePart( BigPart, 4 );
    }
    glActiveTexture( GL_TEXTURE0 );
    mVAO.Unbind();
}

void ActorRenderer::DrawOnePart( render::CountByTexId const& Part, size_t instances ) const
{
    GLuint CurrentAttribIndex = 0;
    CurrentAttribIndex = 0;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mTexIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mSecondaryTexIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mPosIndex + sizeof( glm::vec2 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 1, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mHeadingIndex + sizeof( GLfloat )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mSizeIndex + sizeof( glm::vec2 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mColorIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mMaskTexCoordIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mNormalTexCoordIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 1, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mShadowLenScaleIndex + sizeof( GLfloat )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    ++CurrentAttribIndex;
    glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( mPostprocessColorIndex + sizeof( glm::vec4 )*Part.Start ) );
    glVertexAttribDivisor( CurrentAttribIndex, 1 );
    glDrawArraysInstanced( GL_TRIANGLE_STRIP, 0, instances, Part.Count );
}

ActorRenderer::~ActorRenderer()
{

}

void ActorRenderer::OnMouseMoveEvent( const WorldMouseMoveEvent& Event )
{
    mX = Event.Pos.x;
    mY = Event.Pos.y;
}


text:
// arbitrary_positional_facade.hpp: a base class of repositional stream facade

// Copyright Takeshi Mouri 2006, 2007.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

// See http://hamigaki.sourceforge.jp/libs/iostreams for library home page.

#ifndef HAMIGAKI_IOSTREAMS_ARBITRARY_POSITIONAL_FACADE_HPP
#define HAMIGAKI_IOSTREAMS_ARBITRARY_POSITIONAL_FACADE_HPP

#include <boost/config.hpp>
#include <boost/iostreams/detail/ios.hpp>
#include <boost/iostreams/positioning.hpp>
#include <boost/iostreams/traits.hpp>
#include <boost/assert.hpp>

namespace boost { namespace iostreams {

template<class Derived, class CharT, std::streamsize MaxBlockSize>
class arbitrary_positional_facade;

class core_access
{
#if defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS)
public:
#else
    template<class Derived, class CharT, std::streamsize MaxBlockSize>
    friend class arbitrary_positional_facade;

    friend struct device_operations;

    template<class Device>
    friend struct filter_operations;
#endif

    template<class RepositionalSource, class CharT>
    static std::streamsize read_blocks(
        RepositionalSource& src, CharT* s, std::streamsize n)
    {
        return src.read_blocks(s, n);
    }

    template<class RepositionalInputFilter, class Source>
    static std::streamsize read_blocks(
        RepositionalInputFilter& filter, Source& src,
        typename boost::iostreams::char_type_of<Source>::type* s,
        std::streamsize n)
    {
        return filter.read_blocks(src, s, n);
    }

    template<class RepositionalSink, class CharT>
    static std::streamsize write_blocks(
        RepositionalSink& sink, const CharT* s, std::streamsize n)
    {
        return sink.write_blocks(s, n);
    }

    template<class RepositionalOutputFilter, class Sink>
    static std::streamsize write_blocks(
        RepositionalOutputFilter& filter, Sink& sink,
        const typename boost::iostreams::char_type_of<Sink>::type* s,
        std::streamsize n)
    {
        return filter.write_blocks(sink, s, n);
    }

    template<class RepositionalSink, class CharT>
    static void close_with_flush(
        RepositionalSink& sink, const CharT* s, std::streamsize n)
    {
        return sink.close_with_flush(s, n);
    }

    template<class RepositionalOutputFilter, class Sink>
    static void close_with_flush(
        RepositionalOutputFilter& filter, Sink& sink,
        const typename boost::iostreams::char_type_of<Sink>::type* s,
        std::streamsize n)
    {
        return filter.close_with_flush(sink, s, n);
    }

    template<class RepositionalDevice>
    static std::streampos seek_blocks(
        RepositionalDevice& dev,
        boost::iostreams::stream_offset off, BOOST_IOS::seekdir way)
    {
        return dev.seek_blocks(off, way);
    }

    struct device_operations
    {
        template<class RepositionalDevice, class CharT>
        std::streamsize read_blocks(
            RepositionalDevice& t, CharT* s, std::streamsize n) const
        {
            return core_access::read_blocks(t, s, n);
        }

        template<class RepositionalDevice, class CharT>
        std::streamsize write_blocks(
            RepositionalDevice& t, const CharT* s, std::streamsize n) const
        {
            return core_access::write_blocks(t, s, n);
        }
    };

    template<class Device>
    struct filter_operations
    {
        typedef typename boost::iostreams::
            char_type_of<Device>::type char_type;

        Device* dev_ptr_;

        explicit filter_operations(Device& dev) : dev_ptr_(&dev) {}

        template<class RepositionalInputFilter>
        std::streamsize read_blocks(
            RepositionalInputFilter& t, char_type* s, std::streamsize n) const
        {
            return core_access::read_blocks(t, *dev_ptr_, s, n);
        }

        template<class RepositionalOutputFilter>
        std::streamsize write_blocks(
            RepositionalOutputFilter& t,
            const char_type* s, std::streamsize n) const
        {
            return core_access::write_blocks(t, *dev_ptr_, s, n);
        }
    };
};

template<class Derived, class CharT, std::streamsize MaxBlockSize>
class arbitrary_positional_facade
{
private:
    typedef CharT char_type;

    Derived& derived()
    {
      return *static_cast<Derived*>(this);
    }

protected:
    typedef arbitrary_positional_facade<
        Derived,CharT,MaxBlockSize> arbitrary_positional_facade_;

    void block_size(std::streamsize n)
    {
        block_size_ = n;
    }

public:
    arbitrary_positional_facade() : block_size_(MaxBlockSize), count_(0)
    {
    }

    explicit arbitrary_positional_facade(std::streamsize block_size)
        : block_size_(block_size), count_(0)
    {
        BOOST_ASSERT(block_size_ <= MaxBlockSize);
    }

    std::streamsize read(char_type* s, std::streamsize n)
    {
        return read_impl(core_access::device_operations(), s, n);
    }

    template<class Source>
    std::streamsize read(Source& src, char_type* s, std::streamsize n)
    {
        return read_impl(core_access::filter_operations<Source>(src), s, n);
    }

    std::streamsize write(const char_type* s, std::streamsize n)
    {
        return write_impl(core_access::device_operations(), s, n);
    }

    template<class Sink>
    std::streamsize write(Sink& sink, const char_type* s, std::streamsize n)
    {
        return write_impl(core_access::filter_operations<Sink>(sink), s, n);
    }

    void close()
    {
        BOOST_ASSERT(count_ < block_size_);
        core_access::close_with_flush(derived(), buffer_, count_);
    }

    template<class Sink>
    void close(Sink& sink)
    {
        BOOST_ASSERT(count_ < block_size_);
        core_access::close_with_flush(derived(), sink, buffer_, count_);
    }

    std::streampos seek(
        boost::iostreams::stream_offset off, BOOST_IOS::seekdir way)
    {
        if (way == BOOST_IOS::beg)
        {
            core_access::seek_blocks(derived(), off/block_size_, way);

            std::streamsize skip =
                static_cast<std::streamsize>(off%block_size_);
            if (skip == 0)
                count_ = 0;
            else
            {
                std::streamsize res =
                    core_access::read_blocks(derived(), buffer_, 1);
                if (res != 1)
                    throw BOOST_IOSTREAMS_FAILURE("bad seek");
                count_ = block_size_ - skip;
            }
            return boost::iostreams::offset_to_position(off);
        }
        else if (way == BOOST_IOS::cur)
        {
            std::streampos pos =
                core_access::seek_blocks(
                    derived(), (off-count_)/block_size_, way);

            std::streamsize skip =
                static_cast<std::streamsize>((off-count_)%block_size_);
            if (skip == 0)
            {
                count_ = 0;

                return boost::iostreams::offset_to_position(
                    boost::iostreams::position_to_offset(pos) * block_size_);
            }
            else
            {
                std::streamsize res =
                    core_access::read_blocks(derived(), buffer_, 1);
                if (res != 1)
                    throw BOOST_IOSTREAMS_FAILURE("bad seek");
                count_ = block_size_ - skip;

                return boost::iostreams::offset_to_position(
                    boost::iostreams::position_to_offset(pos) * block_size_
                    + block_size_-count_);
            }
        }
        else
        {
            std::streampos pos =
                core_access::seek_blocks(
                    derived(), (off-block_size_+1)/block_size_, way);

            count_ =
                static_cast<std::streamsize>((-off)%block_size_);
            if (count_ == 0)
            {
                return boost::iostreams::offset_to_position(
                    boost::iostreams::position_to_offset(pos) * block_size_);
            }
            else
            {
                std::streamsize res =
                    core_access::read_blocks(derived(), buffer_, 1);
                if (res != 1)
                    throw BOOST_IOSTREAMS_FAILURE("bad seek");

                return boost::iostreams::offset_to_position(
                    boost::iostreams::position_to_offset(pos) * block_size_
                    + block_size_-count_);
            }
        }
    }

private:
    char_type buffer_[MaxBlockSize];
    std::streamsize block_size_;
    std::streamsize count_;

    template<class Op>
    std::streamsize read_impl(const Op& op, char_type* s, std::streamsize n)
    {
        std::streamsize total = 0;

        if (count_ != 0)
        {
            std::streamsize amt = (std::min)(n, count_);
            char_type* start = buffer_ + (block_size_ - count_);
            s = std::copy(start, start+amt, s);
            n -= amt;
            count_ -= amt;
            total += amt;
        }

        if (n >= block_size_)
        {
            BOOST_ASSERT(count_ == 0);

            std::streamsize request = n/block_size_;
            std::streamsize res =
                op.read_blocks(derived(), s, request);

            if (res != -1)
            {
                s += res;
                n -= res;
                total += res;
            }

            if (res < request*block_size_)
                return total != 0 ? total : -1;
        }

        if (n != 0)
        {
            BOOST_ASSERT(n < block_size_);
            BOOST_ASSERT(count_ == 0);

            std::streamsize res =
                op.read_blocks(derived(), buffer_, 1);

            if (res > 0)
            {
                s = std::copy(buffer_, buffer_+n, s);
                count_ = block_size_ - n;
                total += n;
            }
        }

        return total != 0 ? total : -1;
    }

    template<class Op>
    std::streamsize write_impl(
        const Op& op, const char_type* s, std::streamsize n)
    {
        std::streamsize total = 0;

        if (count_ != 0)
        {
            std::streamsize amt = (std::min)(n, block_size_-count_);
            std::copy(s, s+amt, buffer_+count_);
            s += amt;
            n -= amt;
            count_ += amt;
            total += amt;

            if (count_ == block_size_)
            {
                op.write_blocks(derived(), buffer_, 1);
                count_ = 0;
            }
        }

        if (n >= block_size_)
        {
            BOOST_ASSERT(count_ == 0);

            std::streamsize request = n/block_size_;
            op.write_blocks(derived(), s, request);

            std::streamsize amt = request*block_size_;
            s += amt;
            n -= amt;
            total += amt;
        }

        if (n != 0)
        {
            BOOST_ASSERT(n < block_size_);
            BOOST_ASSERT(count_ == 0);

            std::copy(s, s+n, buffer_);
            count_ = n;
            total += n;
        }

        return total != 0 ? total : -1;
    }
};

} } // End namespaces iostreams, boost.

#endif // HAMIGAKI_IOSTREAMS_ARBITRARY_POSITIONAL_FACADE_HPP

max_stars_repo_name: austinkeller/pwiz

max_issues_repo_name: austinkeller/pwiz

max_forks_repo_name: austinkeller/pwiz


text:
#pragma once

#include <sys/time.h>
#include <boost/utility.hpp>

class Ticker : boost::noncopyable {
	public:
		Ticker() { reset(); }

		void reset() { gettimeofday(&last_, 0); }

		int tick() {
			gettimeofday(&next_, 0);
			int out = 1000000 * (next_.tv_sec - last_.tv_sec) + (next_.tv_usec - last_.tv_usec);
			last_ = next_;
			return out;
		}

	private:
		timeval last_, next_;
};

max_stars_repo_name: bracket/circles

max_issues_repo_name: bracket/circles

max_forks_repo_name: bracket/circles


text:
/**
 *  @copyright Copyright 2018 The J-PET Framework Authors. All rights reserved.
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may find a copy of the License in the LICENCE file.
 *
 *  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.
 *
 *  @file JPetAdditionalTransformations.h
 */

#include "JPetOptionsGenerator/JPetAdditionalTransformations.h"

#include <boost/any.hpp>

using boost::any_cast;

// cppcheck-suppress unusedFunction
std::pair<std::string, boost::any> setAdditionalRunIdInTheMap(boost::any option)
{
  int run = any_cast<int>(option);
  return std::make_pair("additionalRunID_int", run);
}

max_stars_repo_name: BlurredChoise/j-pet-framework

max_issues_repo_name: BlurredChoise/j-pet-framework

max_forks_repo_name: BlurredChoise/j-pet-framework


text:
/*
 Copyright (C) 2016 Quaternion Risk Management Ltd
 All rights reserved.

 This file is part of ORE, a free-software/open-source library
 for transparent pricing and risk analysis - http://opensourcerisk.org

 ORE is free software: you can redistribute it and/or modify it
 under the terms of the Modified BSD License.  You should have received a
 copy of the license along with this program.
 The license is also available online at <http://opensourcerisk.org>

 This program is distributed on the basis that it will form a useful
 contribution to risk analytics and model standardisation, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 FITNESS FOR A PARTICULAR PURPOSE. See the license for more details.
*/

#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>
#include <ored/marketdata/marketimpl.hpp>
#include <ored/portfolio/builders/swap.hpp>
#include <ored/portfolio/enginedata.hpp>
#include <ored/portfolio/portfolio.hpp>
#include <ored/portfolio/swap.hpp>
#include <ored/utilities/indexparser.hpp>
#include <ored/utilities/log.hpp>
#include <oret/toplevelfixture.hpp>
#include <ql/termstructures/yield/discountcurve.hpp>
#include <ql/time/calendars/target.hpp>
#include <ql/time/calendars/unitedstates.hpp>
#include <ql/time/daycounters/actual360.hpp>

using namespace QuantLib;
using namespace boost::unit_test_framework;
using namespace ore::data;
using std::vector;

namespace {

class TestMarket : public MarketImpl {
public:
    TestMarket() {
        // valuation date
        asof_ = Date(22, Aug, 2016);

        // build vectors with dates and discount factors
        vector<Date> datesEUR = {asof_,
                                 asof_ + 6 * Months,
                                 asof_ + 7 * Months,
                                 asof_ + 8 * Months,
                                 asof_ + 9 * Months,
                                 asof_ + 10 * Months,
                                 asof_ + 11 * Months,
                                 asof_ + 12 * Months,
                                 asof_ + 13 * Months,
                                 asof_ + 14 * Months,
                                 asof_ + 15 * Months,
                                 asof_ + 16 * Months,
                                 asof_ + 17 * Months,
                                 asof_ + 18 * Months,
                                 asof_ + 2 * Years,
                                 asof_ + 3 * Years,
                                 asof_ + 4 * Years,
                                 asof_ + 5 * Years,
                                 asof_ + 6 * Years};
        vector<Date> datesUSD = {asof_,
                                 asof_ + 3 * Months,
                                 asof_ + 4 * Months,
                                 asof_ + 7 * Months,
                                 asof_ + 10 * Months,
                                 asof_ + 13 * Months,
                                 asof_ + 16 * Months,
                                 asof_ + 19 * Months,
                                 asof_ + 2 * Years,
                                 asof_ + 3 * Years,
                                 asof_ + 4 * Years,
                                 asof_ + 5 * Years,
                                 asof_ + 6 * Years};
        vector<DiscountFactor> dfsEUR = {1.0,      1.000972, 1.001138, 1.001309, 1.001452, 1.001663, 1.001826,
                                         1.002005, 1.002196, 1.002369, 1.002554, 1.00275,  1.002918, 1.003114,
                                         1.004134, 1.006005, 1.007114, 1.006773, 1.004282};
        vector<DiscountFactor> dfsUSD = {1.0,      0.997872, 0.997147, 0.99499, 0.992416, 0.989948, 0.987405,
                                         0.984774, 0.980358, 0.96908,  0.95704, 0.944041, 0.93004};

        // build discount
        yieldCurves_[make_tuple(Market::defaultConfiguration, YieldCurveType::Discount, "EUR")] =
            intDiscCurve(datesEUR, dfsEUR, Actual360(), TARGET());
        yieldCurves_[make_tuple(Market::defaultConfiguration, YieldCurveType::Discount, "USD")] =
            intDiscCurve(datesUSD, dfsUSD, Actual360(), UnitedStates());

        // build ibor index
        Handle<IborIndex> hEUR(parseIborIndex("EUR-EURIBOR-6M", intDiscCurve(datesEUR, dfsEUR, Actual360(), TARGET())));
        iborIndices_[make_pair(Market::defaultConfiguration, "EUR-EURIBOR-6M")] = hEUR;

        // add Eurib 6M fixing
        hEUR->addFixing(Date(18, Aug, 2016), -0.00191);
        Handle<IborIndex> hUSD(
            parseIborIndex("USD-LIBOR-3M", intDiscCurve(datesUSD, dfsUSD, Actual360(), UnitedStates())));
        iborIndices_[make_pair(Market::defaultConfiguration, "USD-LIBOR-3M")] = hUSD;

        // add Libor 3M fixing
        hUSD->addFixing(Date(18, Aug, 2016), 0.00811);

        // add fx rates
        fxSpots_[Market::defaultConfiguration].addQuote("EURUSD",
                                                        Handle<Quote>(boost::make_shared<SimpleQuote>(1.1306)));
    }

private:
    Handle<YieldTermStructure> intDiscCurve(vector<Date> dates, vector<DiscountFactor> dfs, DayCounter dc,
                                            Calendar cal) {
        boost::shared_ptr<YieldTermStructure> idc(
            new QuantLib::InterpolatedDiscountCurve<LogLinear>(dates, dfs, dc, cal));
        return Handle<YieldTermStructure>(idc);
    }
};
} // namespace

BOOST_FIXTURE_TEST_SUITE(OREDataTestSuite, ore::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(CcySwapWithResetsTest)

// Ccy Swap with notional resets test, example from Bloomberg
BOOST_AUTO_TEST_CASE(testCcySwapWithResetsPrice) {

    BOOST_TEST_MESSAGE("Testing CcySwapWithResets Price...");

    // Bloomberg CCYswap and CCYswapReset prices (in USD)
    Real npvCCYswap = -349.69;
    Real npvCCYswapReset = 0;

    // build market
    boost::shared_ptr<Market> market = boost::make_shared<TestMarket>();
    Settings::instance().evaluationDate() = market->asofDate();

    // test asof date
    Date today = market->asofDate();
    BOOST_CHECK_EQUAL(today, Date(22, Aug, 2016));

    // Test if EUR discount curve is empty
    Handle<YieldTermStructure> dts = market->discountCurve("EUR");
    QL_REQUIRE(!dts.empty(), "EUR discount curve not found");

    // Test EUR discount(today+3*Years)) against base value
    BOOST_CHECK_CLOSE(market->discountCurve("EUR")->discount(today + 3 * Years), 1.006005, 0.0001);

    // Test USD discount(today+3*Years)) against base value
    BOOST_CHECK_CLOSE(market->discountCurve("USD")->discount(today + 3 * Years), 0.96908, 0.0001);

    // Test EURUSD fx spot object against base value
    BOOST_CHECK_EQUAL(market->fxSpot("EURUSD")->value(), 1.1306);

    // envelope
    Envelope env("CP");

    // Start/End date
    Date startDate = today;
    Date endDate = today + 5 * Years;

    // date 2 string
    std::ostringstream oss;
    oss << io::iso_date(startDate);
    string start(oss.str());
    oss.str("");
    oss.clear();
    oss << io::iso_date(endDate);
    string end(oss.str());

    // Schedules
    string conv = "MF";
    string rule = "Forward";
    ScheduleData scheduleEUR(ScheduleRules(start, end, "6M", "TARGET", conv, conv, rule));
    ScheduleData scheduleUSD(ScheduleRules(start, end, "3M", "US", conv, conv, rule));

    // EUR Leg without and with Notional resets
    bool isPayerEUR = true;
    string indexEUR = "EUR-EURIBOR-6M";
    bool isInArrears = false;
    int days = 2, fxFixingDays = 0;
    vector<Real> spreadEUR(1, 0.000261);
    string dc = "ACT/360";
    vector<Real> notionalEUR(1, 8833141.95);
    string paymentConvention = "F";
    bool notionalInitialXNL = true;
    bool notionalFinalXNL = true;
    bool notionalAmortizingXNL = false;
    string foreignCCY = "USD";
    Real foreignAmount = 10000000;
    string fxIndex = "FX-ECB-EUR-USD";
    auto legdataEUR = boost::make_shared<FloatingLegData>(indexEUR, days, isInArrears, spreadEUR);
    LegData legEUR1(legdataEUR, isPayerEUR, "EUR", scheduleEUR, dc, notionalEUR, vector<string>(), paymentConvention,
                    notionalInitialXNL, notionalFinalXNL, notionalAmortizingXNL, notionalFinalXNL, foreignCCY,
                    foreignAmount, fxIndex, fxFixingDays);
    LegData legEUR2(legdataEUR, isPayerEUR, "EUR", scheduleEUR, dc, notionalEUR, vector<string>(), paymentConvention,
                    notionalInitialXNL, notionalFinalXNL, notionalAmortizingXNL, false, foreignCCY, foreignAmount,
                    fxIndex, fxFixingDays);

    // USD Leg without notional resets
    bool isPayerUSD = false;
    string indexUSD = "USD-LIBOR-3M";
    vector<Real> spreadUSD(1, 0);
    vector<Real> notionalUSD(1, 10000000);
    auto legdataUSD = boost::make_shared<FloatingLegData>(indexUSD, days, isInArrears, spreadUSD);
    LegData legUSD(legdataUSD, isPayerUSD, "USD", scheduleUSD, dc, notionalUSD, vector<string>(), paymentConvention,
                   notionalInitialXNL, notionalFinalXNL, notionalAmortizingXNL);

    // Build swap trades
    boost::shared_ptr<Trade> swap1(new ore::data::Swap(env, legUSD, legEUR1));
    boost::shared_ptr<Trade> swap2(new ore::data::Swap(env, legUSD, legEUR2));

    // engine data and factory
    boost::shared_ptr<EngineData> engineData = boost::make_shared<EngineData>();
    engineData->model("CrossCurrencySwap") = "DiscountedCashflows";
    engineData->engine("CrossCurrencySwap") = "DiscountingCrossCurrencySwapEngine";
    boost::shared_ptr<EngineFactory> engineFactory = boost::make_shared<EngineFactory>(engineData, market);
    engineFactory->registerBuilder(boost::make_shared<CrossCurrencySwapEngineBuilder>());

    // build swaps and portfolio
    boost::shared_ptr<Portfolio> portfolio(new Portfolio());
    swap1->id() = "XCCY_Swap_EUR_USD";
    swap2->id() = "XCCY_Swap_EUR_USD_RESET";

    portfolio->add(swap1);
    portfolio->add(swap2);
    portfolio->build(engineFactory);

    // check CCYswap NPV
    BOOST_TEST_MESSAGE("CcySwap Price = " << swap1->instrument()->NPV() << " " << swap1->npvCurrency()
                                          << ". BBG Price = " << npvCCYswap << " USD");
    // check if difference between ore and bbg NPV does not exceed 250 USD (on 10M notional)
    BOOST_CHECK_CLOSE(std::abs(swap1->instrument()->NPV() - npvCCYswap), 250, 5);

    // check CCYswapReset NPV
    BOOST_TEST_MESSAGE("CcySwapReset Price = " << swap2->instrument()->NPV() << " " << swap2->npvCurrency()
                                               << ". BBG Price = " << npvCCYswapReset << " USD");
    // check if difference between ore and bbg NPV does not exceed 250 USD (on 10M notional)
    BOOST_CHECK_CLOSE(std::abs(swap2->instrument()->NPV() - npvCCYswapReset), 250, 5);

    // check if sum(XNL) on resetting leg is zero
    Real sumXNL = 0;
    const vector<Leg>& legs = swap2->legs();
    for (Size i = 3; i < legs.size(); i++) {
        const QuantLib::Leg& leg = legs[i];
        for (Size j = 0; j < leg.size(); j++) {
            boost::shared_ptr<QuantLib::CashFlow> ptrFlow = leg[j];
            sumXNL += ptrFlow->amount();
        }
    }
    BOOST_CHECK_EQUAL(sumXNL, 0);
}

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: mrslezak/Engine

max_issues_repo_name: mrslezak/Engine

max_forks_repo_name: mrslezak/Engine


text:
/*
// Copyright (c) 2020 Intel Corporation
//
// 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.
*/
#pragma once
#include "node.hpp"

#include <boost/container/flat_map.hpp>
#include <cstdlib>
#include <ctime>
#include <error_messages.hpp>
#include <http_client.hpp>
#include <memory>
#include <utils/json_utils.hpp>
#include <variant>

namespace redfish
{
class Subscription
{
  public:
    std::string id;
    std::string destinationUrl;
    std::string protocol;
    std::string retryPolicy;
    std::string customText;
    std::string eventFormatType;
    std::string subscriptionType;
    std::vector<std::string> registryMsgIds;
    std::vector<std::string> registryPrefixes;
    std::vector<nlohmann::json> httpHeaders; // key-value pair

    Subscription(const Subscription&) = delete;
    Subscription& operator=(const Subscription&) = delete;
    Subscription(Subscription&&) = delete;
    Subscription& operator=(Subscription&&) = delete;

    Subscription(const std::string& inHost, const std::string& inPort,
                 const std::string& inPath, const std::string& inUriProto) :
        host(inHost),
        port(inPort), path(inPath), uriProto(inUriProto)
    {
        conn = std::make_shared<crow::HttpClient>(
            crow::connections::systemBus->get_io_context(), host, port, path);
    }
    ~Subscription()
    {
    }

    void sendEvent(const std::string& msg)
    {
        std::vector<std::pair<std::string, std::string>> reqHeaders;
        for (const auto& header : httpHeaders)
        {
            for (const auto& item : header.items())
            {
                std::string key = item.key();
                std::string val = item.value();
                reqHeaders.emplace_back(std::pair(key, val));
            }
        }
        conn->setHeaders(reqHeaders);
        conn->sendData(msg);
    }

  private:
    std::string host;
    std::string port;
    std::string path;
    std::string uriProto;
    std::shared_ptr<crow::HttpClient> conn;
};

class EventServiceManager
{
  private:
    EventServiceManager(const EventServiceManager&) = delete;
    EventServiceManager& operator=(const EventServiceManager&) = delete;
    EventServiceManager(EventServiceManager&&) = delete;
    EventServiceManager& operator=(EventServiceManager&&) = delete;

    EventServiceManager()
    {
        // TODO: Read the persistent data from store and populate.
        // Populating with default.
        enabled = true;
        retryAttempts = 3;
        retryTimeoutInterval = 30; // seconds
    }

    boost::container::flat_map<std::string, std::shared_ptr<Subscription>>
        subscriptionsMap;

  public:
    bool enabled;
    uint32_t retryAttempts;
    uint32_t retryTimeoutInterval;

    static EventServiceManager& getInstance()
    {
        static EventServiceManager handler;
        return handler;
    }

    void updateSubscriptionData()
    {
        // Persist the config and subscription data.
        // TODO: subscriptionsMap & configData need to be
        // written to Persist store.
        return;
    }

    std::shared_ptr<Subscription> getSubscription(const std::string& id)
    {
        auto obj = subscriptionsMap.find(id);
        if (obj == subscriptionsMap.end())
        {
            BMCWEB_LOG_ERROR << "No subscription exist with ID:" << id;
            return nullptr;
        }
        std::shared_ptr<Subscription> subValue = obj->second;
        return subValue;
    }

    std::string addSubscription(const std::shared_ptr<Subscription> subValue)
    {
        std::srand(static_cast<uint32_t>(std::time(0)));
        std::string id;

        int retry = 3;
        while (retry)
        {
            id = std::to_string(std::rand());
            auto inserted = subscriptionsMap.insert(std::pair(id, subValue));
            if (inserted.second)
            {
                break;
            }
            --retry;
        };

        if (retry <= 0)
        {
            BMCWEB_LOG_ERROR << "Failed to generate random number";
            return std::string("");
        }

        updateSubscriptionData();
        return id;
    }

    bool isSubscriptionExist(const std::string& id)
    {
        auto obj = subscriptionsMap.find(id);
        if (obj == subscriptionsMap.end())
        {
            return false;
        }
        return true;
    }

    void deleteSubscription(const std::string& id)
    {
        auto obj = subscriptionsMap.find(id);
        if (obj != subscriptionsMap.end())
        {
            subscriptionsMap.erase(obj);
            updateSubscriptionData();
        }
    }

    size_t getNumberOfSubscriptions()
    {
        return subscriptionsMap.size();
    }

    std::vector<std::string> getAllIDs()
    {
        std::vector<std::string> idList;
        for (const auto& it : subscriptionsMap)
        {
            idList.emplace_back(it.first);
        }
        return idList;
    }

    bool isDestinationExist(const std::string& destUrl)
    {
        for (const auto& it : subscriptionsMap)
        {
            std::shared_ptr<Subscription> entry = it.second;
            if (entry->destinationUrl == destUrl)
            {
                BMCWEB_LOG_ERROR << "Destination exist already" << destUrl;
                return true;
            }
        }
        return false;
    }
};

} // namespace redfish

max_stars_repo_name: ztai-goog/bmcweb

max_issues_repo_name: ztai-goog/bmcweb

max_forks_repo_name: ztai-goog/bmcweb