<commit_before>/*
	jcom.textslider
	A slider displaying text and value
	By Trond Lossius, Copyright  2008
	Based on jcom.meter~ by Tim Place, 2005

	License: This code is licensed under the terms of the GNU LGPL
	http://www.gnu.org/licenses/lgpl.html
  */

#include "ext.h"
#include "ext_obex.h"
#include "ext_user.h"
#include "ext_common.h"
#include "jpatcher_api.h"	// jpatcher_api.h must come before z_dsp.h (in Jamoma.h)
#include "jgraphics.h"
#include "Jamoma.h"
#include "TTBlue.h"

// Constants
const double kPollIntervalDefault = 150;
const double kPollIntervalMinimum = 50;
const double kPollIntervalMaximum = 5000;
const double kHeightDefault = 13;
const double kHeightMinimum = 1;
const double kHeightMaximum = 400;
const double kWidthDefault = 80;
const double kWidthMinimum = 1;
const double kWidthMaximum = 1200;
const double kOrientationVectical = 1;
const double kOrientationHorizontal = 0;
const double kMinimumChangeForRedraw = 0.00001;

// Instance definition
typedef struct _textslider{
	t_pxjbox	obj;
	char		attrDefeat;			// disable the textslider

	t_jrgba		attrBgColor;		///< Background color
	t_jrgba		attrFgColor;		///< Forground color
	t_jrgba		attrBorderColor;	///< Border color
	t_jrgba		attrTextColor;		///< Text color

	float		attrValue;			///< The slider value
	void		*outlet;			///< Outlet
} t_textslider;

// prototypes
void*		textslider_new(t_symbol *s, long argc, t_atom *argv);
void		textslider_free(t_textslider *x);
t_max_err	textslider_notify(t_textslider *x, t_symbol *s, t_symbol *msg, void *sender, void *data);
void		textslider_assist(t_textslider *x, void *b, long m, long a, char *s);
void		textslider_bang(t_textslider *x);
void		textslider_int(t_textslider *x, long value);
void		textslider_float(t_textslider *x, double value);
void		textslider_paint(t_textslider *x, t_object *view);
void*		textslider_oksize(t_textslider *x, t_rect *newrect);

// globals
static t_class*	s_textslider_class;

// implementation
#if 0
#pragma mark -
#pragma mark Class Definition
#endif 0

int main(void)
{
	t_class *c = class_new("jcom.textslider", (method)textslider_new, (method)textslider_free, sizeof(t_textslider), (method)NULL, A_GIMME, 0L);

	c->c_flags |= CLASS_FLAG_NEWDICTIONARY; // use dictionary constructor
	jbox_initclass(c, 0);

	jamoma_init();
	common_symbols_init();

	class_addmethod(c, (method)textslider_bang,		"bang",			0);
	class_addmethod(c, (method)textslider_int,		"int",			A_LONG, 0);
	class_addmethod(c, (method)textslider_float,	"float",		A_FLOAT, 0);
	class_addmethod(c, (method)textslider_paint,	"paint",		A_CANT, 0);
	class_addmethod(c, (method)textslider_oksize,	"oksize",		A_CANT, 0);
	class_addmethod(c, (method)textslider_bang,		"mousedown",	A_CANT, 0);
	class_addmethod(c, (method)textslider_notify,	"notify",		A_CANT, 0);
	class_addmethod(c, (method)textslider_assist,	"assist",		A_CANT, 0);

	CLASS_ATTR_RGBA(c,						"bgcolor",		0,	t_textslider,	attrBgColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"bgcolor",		0,	"0.7 0.7 0.7 1.0");
	CLASS_ATTR_STYLE(c,						"bgcolor",		0,	"rgba");

	CLASS_ATTR_RGBA(c,						"fgcolor",		0,	t_textslider,	attrFgColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"fgcolor",		0,	"0.95 0.95 0.95 1.0");
	CLASS_ATTR_STYLE(c,						"fgcolor",		0,	"rgba");

	CLASS_ATTR_RGBA(c,						"bordercolor",	0,	t_textslider,	attrBorderColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"bordercolor",	0,	"0.7 0.7 0.7 1.0");
	CLASS_ATTR_STYLE(c,						"bordercolor",	0,	"rgba");

	CLASS_ATTR_RGBA(c,						"textcolor",	0,	t_textslider,	attrTextColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"textcolor",	0,	"0.0 0.0 0.0 1.0");
	CLASS_ATTR_STYLE(c,						"textcolor",	0,	"rgba");

	CLASS_ATTR_DEFAULT(c,					"patching_rect",	0,	"0. 0. 100. 12.");
	CLASS_ATTR_MIN(c,						"patching_size",	0,	"1. 1.");

	class_register(CLASS_BOX, c);
	s_textslider_class = c;
	return 0;
}

#if 0
#pragma mark -
#pragma mark Life Cycle
#endif 0

void *textslider_new(t_symbol *s, long argc, t_atom *argv)
{
	t_textslider*	x;
	t_jbox*		box;
	long		flags;

	t_dictionary *d=NULL;

	if (!(d=object_dictionaryarg(argc,argv)))
		return NULL;

	x = (t_textslider *)object_alloc(s_textslider_class);

	flags = 0
		| JBOX_DRAWFIRSTIN
		| JBOX_NODRAWBOX
		| JBOX_DRAWINLAST
	//	| JBOX_TRANSPARENT
	//	| JBOX_NOGROW
	//	| JBOX_GROWY
		| JBOX_GROWBOTH
	//	| JBOX_HILITE
	//	| JBOX_BACKGROUND
	//	| JBOX_DRAWBACKGROUND
	//	| JBOX_NOFLOATINSPECTOR
	//	| JBOX_TEXTFIELD
	//	| JBOX_MOUSEDRAGDELTA
	//	| JBOX_TEXTFIELD
	;

	box = (t_jbox *)x;
	jbox_new(box, flags, argc, argv);
	x->obj.z_box.b_firstin = (t_object*)x;

	x->outlet = outlet_new(x, 0);

	attr_dictionary_process(x,d);
	jbox_ready((t_jbox *)x);
	return x;
}

void textslider_free(t_textslider *x)
{
	notify_free((t_object *)x);
	jbox_free((t_jbox *)x);
}

#if 0
#pragma mark -
#pragma mark Methods
#endif 0

t_max_err textslider_notify(t_textslider *x, t_symbol *s, t_symbol *msg, void *sender, void *data)
{
	t_symbol*	name;

	if(msg == _sym_attr_modified){
		name = (t_symbol *)object_method((t_object *)data, _sym_getname);
		if(name == _sym_bgcolor)
			jbox_redraw((t_jbox*)x);
	}

	jbox_notify((t_jbox *)x, s, msg, sender, data);
	return MAX_ERR_NONE;
}

// Method for Assistance Messages
void textslider_assist(t_textslider *x, void *b, long msg, long arg, char *dst)
{
	if(msg==1) 						// Inlet
		strcpy(dst, "Input");
	else if(msg==2){ 				// Outlets
		switch(arg){
			case 0: strcpy(dst, "Output"); break;
				//case 1: strcpy(dst, "Attribute Stuff"); break;
 		}
 	}
}

// Method: bang - output current value
void textslider_bang(t_textslider *x)
{
	// jbox_redraw((t_jbox*)x); I don't think it's necsessary to redraw here...
	outlet_float(x->outlet, x->attrValue);
}

void textslider_int(t_textslider *x, long value)
{
	textslider_float(x,(double)value);
}

void textslider_float(t_textslider *x, double value)
{
	x->attrValue = value;
	// TODO: Should it be clipped to range?
	jbox_redraw((t_jbox*)x);
	outlet_float(x->outlet, x->attrValue);

}

#if 0
#pragma mark -
#pragma mark User Interface
#endif 0

void *textslider_oksize(t_textslider *x, t_rect *newrect)
{
	TTClip(newrect->width, kWidthMinimum, kWidthMaximum);
	TTClip(newrect->height, kHeightMinimum, kHeightMaximum);
	return (void*)1;
}

void textslider_paint(t_textslider *x, t_object *view)
{
	t_rect			rect;
	t_jgraphics*	g;
	double			value = TTClip(x->attrValue, 0.0f, 1.0f);
	double			position;
	t_jrgba			c;

	g = (t_jgraphics*) patcherview_get_jgraphics(view);		// obtain graphics context
	jbox_get_rect_for_view((t_object *)x, view, &rect);		// this is the box rectangle -- but we draw relative to 0 0, and thus only care about width & height
	rect.x = 0;
	rect.y = 0;
	position = rect.width * value;

	c = x->attrFgColor;
	jgraphics_set_source_jrgba(g, &c);
	jgraphics_rectangle_fill_fast(g, 0, 0, position, rect.height);

	c = x->attrBgColor;
	jgraphics_set_source_jrgba(g, &c);
	jgraphics_rectangle_fill_fast(g, position, 0, rect.width-position, rect.height);

}

<commit_msg>Adding range attribute to jcom.textslider<commit_after>/*
	jcom.textslider
	A slider displaying text and value
	By Trond Lossius, Copyright  2008
	Based on jcom.meter~ by Tim Place, 2005

	License: This code is licensed under the terms of the GNU LGPL
	http://www.gnu.org/licenses/lgpl.html
  */

#include "ext.h"
#include "ext_obex.h"
#include "ext_user.h"
#include "ext_common.h"
#include "jpatcher_api.h"	// jpatcher_api.h must come before z_dsp.h (in Jamoma.h)
#include "jgraphics.h"
#include "Jamoma.h"
#include "TTBlue.h"

// Constants
const double kPollIntervalDefault = 150;
const double kPollIntervalMinimum = 50;
const double kPollIntervalMaximum = 5000;
const double kHeightDefault = 13;
const double kHeightMinimum = 1;
const double kHeightMaximum = 400;
const double kWidthDefault = 80;
const double kWidthMinimum = 1;
const double kWidthMaximum = 1200;
const double kOrientationVectical = 1;
const double kOrientationHorizontal = 0;
const double kMinimumChangeForRedraw = 0.00001;

// Instance definition
typedef struct _textslider{
	t_pxjbox	obj;
	char		attrDefeat;			// disable the textslider

	t_jrgba		attrBgColor;		///< Background color
	t_jrgba		attrFgColor;		///< Forground color
	t_jrgba		attrBorderColor;	///< Border color
	t_jrgba		attrTextColor;		///< Text color

	float		attrValue;			///< The slider value
	float		attrRange[2];		///< ATTRIBUTE: low, high
	void		*outlet;			///< Outlet
} t_textslider;

// prototypes
void*		textslider_new(t_symbol *s, long argc, t_atom *argv);
void		textslider_free(t_textslider *x);
t_max_err	textslider_notify(t_textslider *x, t_symbol *s, t_symbol *msg, void *sender, void *data);
void		textslider_assist(t_textslider *x, void *b, long m, long a, char *s);
void		textslider_bang(t_textslider *x);
void		textslider_int(t_textslider *x, long value);
void		textslider_float(t_textslider *x, double value);
t_max_err	textslider_getRange(t_textslider *x, void *attr, long *argc, t_atom **argv);
t_max_err	textslider_setRange(t_textslider *x, void *attr, long argc, t_atom *argv);
void		textslider_paint(t_textslider *x, t_object *view);
void*		textslider_oksize(t_textslider *x, t_rect *newrect);

// globals
static t_class*	s_textslider_class;

// implementation
#if 0
#pragma mark -
#pragma mark Class Definition
#endif 0

int main(void)
{
	t_class *c = class_new("jcom.textslider", (method)textslider_new, (method)textslider_free, sizeof(t_textslider), (method)NULL, A_GIMME, 0L);

	c->c_flags |= CLASS_FLAG_NEWDICTIONARY; // use dictionary constructor
	jbox_initclass(c, 0);

	jamoma_init();
	common_symbols_init();

	class_addmethod(c, (method)textslider_bang,		"bang",			0);
	class_addmethod(c, (method)textslider_int,		"int",			A_LONG, 0);
	class_addmethod(c, (method)textslider_float,	"float",		A_FLOAT, 0);
	class_addmethod(c, (method)textslider_paint,	"paint",		A_CANT, 0);
	class_addmethod(c, (method)textslider_oksize,	"oksize",		A_CANT, 0);
	class_addmethod(c, (method)textslider_bang,		"mousedown",	A_CANT, 0);
	class_addmethod(c, (method)textslider_notify,	"notify",		A_CANT, 0);
	class_addmethod(c, (method)textslider_assist,	"assist",		A_CANT, 0);

	CLASS_ATTR_RGBA(c,						"bgcolor",		0,	t_textslider,	attrBgColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"bgcolor",		0,	"0.7 0.7 0.7 1.0");
	CLASS_ATTR_STYLE(c,						"bgcolor",		0,	"rgba");

	CLASS_ATTR_RGBA(c,						"fgcolor",		0,	t_textslider,	attrFgColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"fgcolor",		0,	"0.95 0.95 0.95 1.0");
	CLASS_ATTR_STYLE(c,						"fgcolor",		0,	"rgba");

	CLASS_ATTR_RGBA(c,						"bordercolor",	0,	t_textslider,	attrBorderColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"bordercolor",	0,	"0.7 0.7 0.7 1.0");
	CLASS_ATTR_STYLE(c,						"bordercolor",	0,	"rgba");

	CLASS_ATTR_RGBA(c,						"textcolor",	0,	t_textslider,	attrTextColor);
	CLASS_ATTR_DEFAULTNAME_SAVE_PAINT(c,	"textcolor",	0,	"0.0 0.0 0.0 1.0");
	CLASS_ATTR_STYLE(c,						"textcolor",	0,	"rgba");

	CLASS_ATTR_DEFAULT(c,					"patching_rect",	0,	"0. 0. 100. 12.");
	CLASS_ATTR_MIN(c,						"patching_size",	0,	"1. 1.");

	CLASS_ATTR_FLOAT_ARRAY(c,				"range",		0,	t_textslider,	attrRange, 2);
	CLASS_ATTR_LABEL(c,						"range",		0,	"Range");
	CLASS_ATTR_DEFAULT(c,					"range",		0,	"0.0 1.0");
	CLASS_ATTR_SAVE(c,						"range",		0);
	CLASS_ATTR_ACCESSORS(c,					"range",		textslider_getRange, textslider_setRange);

	class_register(CLASS_BOX, c);
	s_textslider_class = c;
	return 0;
}

#if 0
#pragma mark -
#pragma mark Life Cycle
#endif 0

void *textslider_new(t_symbol *s, long argc, t_atom *argv)
{
	t_textslider*	x;
	t_jbox*		box;
	long		flags;

	t_dictionary *d=NULL;

	if (!(d=object_dictionaryarg(argc,argv)))
		return NULL;

	x = (t_textslider *)object_alloc(s_textslider_class);

	flags = 0
		| JBOX_DRAWFIRSTIN
		| JBOX_NODRAWBOX
		| JBOX_DRAWINLAST
	//	| JBOX_TRANSPARENT
	//	| JBOX_NOGROW
	//	| JBOX_GROWY
		| JBOX_GROWBOTH
	//	| JBOX_HILITE
	//	| JBOX_BACKGROUND
	//	| JBOX_DRAWBACKGROUND
	//	| JBOX_NOFLOATINSPECTOR
	//	| JBOX_TEXTFIELD
	//	| JBOX_MOUSEDRAGDELTA
	//	| JBOX_TEXTFIELD
	;

	box = (t_jbox *)x;
	jbox_new(box, flags, argc, argv);
	x->obj.z_box.b_firstin = (t_object*)x;

	x->outlet = outlet_new(x, 0);
	x->attrRange[0] = 0.;
	x->attrRange[1] = 1.;

	attr_dictionary_process(x,d);
	jbox_ready((t_jbox *)x);
	return x;
}

void textslider_free(t_textslider *x)
{
	notify_free((t_object *)x);
	jbox_free((t_jbox *)x);
}

#if 0
#pragma mark -
#pragma mark Methods
#endif 0

t_max_err textslider_notify(t_textslider *x, t_symbol *s, t_symbol *msg, void *sender, void *data)
{
	t_symbol*	name;

	if(msg == _sym_attr_modified){
		name = (t_symbol *)object_method((t_object *)data, _sym_getname);
		if(name == _sym_bgcolor)
			jbox_redraw((t_jbox*)x);
	}

	jbox_notify((t_jbox *)x, s, msg, sender, data);
	return MAX_ERR_NONE;
}

// Method for Assistance Messages
void textslider_assist(t_textslider *x, void *b, long msg, long arg, char *dst)
{
	if(msg==1) 						// Inlet
		strcpy(dst, "Input");
	else if(msg==2){ 				// Outlets
		switch(arg){
			case 0: strcpy(dst, "Output"); break;
				//case 1: strcpy(dst, "Attribute Stuff"); break;
 		}
 	}
}

// Method: bang - output current value
void textslider_bang(t_textslider *x)
{
	// jbox_redraw((t_jbox*)x); I don't think it's necsessary to redraw here...
	outlet_float(x->outlet, x->attrValue);
}

void textslider_int(t_textslider *x, long value)
{
	textslider_float(x,(double)value);
}

void textslider_float(t_textslider *x, double value)
{
	x->attrValue = value;
	// TODO: Should it be clipped to range?
	jbox_redraw((t_jbox*)x);
	outlet_float(x->outlet, x->attrValue);

}

t_max_err textslider_getRange(t_textslider *x, void *attr, long *argc, t_atom **argv)
{

	*argc = 2;

	//sysmem_ptrsize(*argv)
	// FIXME: This checks if we have memory passed in, good, but how do we know if it is enough memory for 2 atoms? [TAP]
	if (!(*argv)) // otherwise use memory passed in
		*argv = (t_atom *)sysmem_newptr(sizeof(t_atom) * 2);

	atom_setfloat(*argv, x->attrRange[0]);
	atom_setfloat(*argv+1, x->attrRange[1]);

	return MAX_ERR_NONE;
}

t_max_err textslider_setRange(t_textslider *x, void *attr, long argc, t_atom *argv)
{
	if(argc)
		x->attrRange[0] = atom_getfloat(argv+0);
	if(argc > 1)
		x->attrRange[1] = atom_getfloat(argv+1);

	return MAX_ERR_NONE;
}

#if 0
#pragma mark -
#pragma mark User Interface
#endif 0

void *textslider_oksize(t_textslider *x, t_rect *newrect)
{
	TTClip(newrect->width, kWidthMinimum, kWidthMaximum);
	TTClip(newrect->height, kHeightMinimum, kHeightMaximum);
	return (void*)1;
}

void textslider_paint(t_textslider *x, t_object *view)
{
	t_rect			rect;
	t_jgraphics*	g;
	double			value;

	if (x->attrRange[0] == x->attrRange[1])
		value = 0.5;
	else
		value = TTClip( (x->attrValue - x->attrRange[0])/(x->attrRange[1] - x->attrRange[0]), 0.0f, 1.0f);
	double			position;
	t_jrgba			c;

	g = (t_jgraphics*) patcherview_get_jgraphics(view);		// obtain graphics context
	jbox_get_rect_for_view((t_object *)x, view, &rect);		// this is the box rectangle -- but we draw relative to 0 0, and thus only care about width & height
	rect.x = 0;
	rect.y = 0;
	position = rect.width * value;

	c = x->attrFgColor;
	jgraphics_set_source_jrgba(g, &c);
	jgraphics_rectangle_fill_fast(g, 0, 0, position, rect.height);

	c = x->attrBgColor;
	jgraphics_set_source_jrgba(g, &c);
	jgraphics_rectangle_fill_fast(g, position, 0, rect.width-position, rect.height);

}

<|endoftext|>


<commit_before>#include <ork/thread.h>
#include <sys/prctl.h>

namespace ork {

thread::thread(const std::string& name)
    : _name(name)
{
    mState = 0;
}
thread::~thread()
{
    join();
}

void* thread_impl(void* pdat)
{
    thread* pthr = (thread*) pdat;

    //printf( "starting thread<%p:%s>\n", pdat,pthr->_name.c_str() );
    SetCurrentThreadName(pthr->_name.c_str());

    pthr->mLambda();
    //printf( "thread<%p> returned\n", pdat );
    return nullptr;
}
#if defined(USE_SPROC)
void sproc_thread_impl(void* pdat)
{
    thread_impl(pdat);
}
#endif

void thread::start( const ork::void_lambda_t& l )
{
    int istate = mState.fetch_and_increment();
    //printf( "start thread<%p> istate<%d>\n", this, istate );
    if( istate==0 )
    {
        mLambda = l;
        #if defined(USE_PTHREAD)

        //pthread_attr_t attr;
        //int ia = pthread_attr_init(&attr);
        //pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS );
        //pthread_attr_setschedpolicy(&attr, SCHED_RR );
        //pthread_setconcurrency(2);

        pthread_create(&mThreadHandle, nullptr, thread_impl, (void*) this );
        //pthread_create(&mThreadHandle, &attr, thread_impl, (void*) this );
        #elif defined(USE_SPROC)
        mSprocPid = sproc( sproc_thread_impl, PR_SALL, (void*) this );
        printf( "mSprocPid<%d>\n", mSprocPid );
        sysmp(MP_RUNANYWHERE_PID, mSprocPid);
        /*while( int(mState) != 2 )
        {
            usleep(1000);
        }*/
        #endif
    }
}

void thread::join()
{
    if( mState.fetch_and_decrement()==1 )
    {
        #if defined(USE_PTHREAD)
        pthread_join(mThreadHandle,NULL);
        #elif defined(USE_SPROC)
        int status;
        waitpid((pid_t)mSprocPid, &status, 0);
        #endif
    }
    else
    {
        mState.fetch_and_increment();
    }
}

///////////////////////////////////////////////////////////////////////////

void SetCurrentThreadName(const char* threadName)
{
    static const int  kMAX_NAME_LEN = 15;
    char name[kMAX_NAME_LEN+1];
    for( int i=0; i<kMAX_NAME_LEN; i++ ) name[i]=0;
    strncpy(name,threadName,kMAX_NAME_LEN);
    name[kMAX_NAME_LEN]=0;
#if defined(OSX)
    pthread_setname_np(name);
#elif defined(LINUX)
    prctl(PR_SET_NAME,(unsigned long)&name);
#endif
}

}
<commit_msg>fix IX build<commit_after>#include <ork/thread.h>
#if !defined(ORK_OSX)
#include <sys/prctl.h>
#endif

namespace ork {

thread::thread(const std::string& name)
    : _name(name)
{
    mState = 0;
}
thread::~thread()
{
    join();
}

void* thread_impl(void* pdat)
{
    thread* pthr = (thread*) pdat;

    //printf( "starting thread<%p:%s>\n", pdat,pthr->_name.c_str() );
    SetCurrentThreadName(pthr->_name.c_str());

    pthr->mLambda();
    //printf( "thread<%p> returned\n", pdat );
    return nullptr;
}
#if defined(USE_SPROC)
void sproc_thread_impl(void* pdat)
{
    thread_impl(pdat);
}
#endif

void thread::start( const ork::void_lambda_t& l )
{
    int istate = mState.fetch_and_increment();
    //printf( "start thread<%p> istate<%d>\n", this, istate );
    if( istate==0 )
    {
        mLambda = l;
        #if defined(USE_PTHREAD)

        //pthread_attr_t attr;
        //int ia = pthread_attr_init(&attr);
        //pthread_attr_setscope(&attr, PTHREAD_SCOPE_PROCESS );
        //pthread_attr_setschedpolicy(&attr, SCHED_RR );
        //pthread_setconcurrency(2);

        pthread_create(&mThreadHandle, nullptr, thread_impl, (void*) this );
        //pthread_create(&mThreadHandle, &attr, thread_impl, (void*) this );
        #elif defined(USE_SPROC)
        mSprocPid = sproc( sproc_thread_impl, PR_SALL, (void*) this );
        printf( "mSprocPid<%d>\n", mSprocPid );
        sysmp(MP_RUNANYWHERE_PID, mSprocPid);
        /*while( int(mState) != 2 )
        {
            usleep(1000);
        }*/
        #endif
    }
}

void thread::join()
{
    if( mState.fetch_and_decrement()==1 )
    {
        #if defined(USE_PTHREAD)
        pthread_join(mThreadHandle,NULL);
        #elif defined(USE_SPROC)
        int status;
        waitpid((pid_t)mSprocPid, &status, 0);
        #endif
    }
    else
    {
        mState.fetch_and_increment();
    }
}

///////////////////////////////////////////////////////////////////////////

void SetCurrentThreadName(const char* threadName)
{
    static const int  kMAX_NAME_LEN = 15;
    char name[kMAX_NAME_LEN+1];
    for( int i=0; i<kMAX_NAME_LEN; i++ ) name[i]=0;
    strncpy(name,threadName,kMAX_NAME_LEN);
    name[kMAX_NAME_LEN]=0;
#if defined(OSX)
    pthread_setname_np(name);
#elif defined(LINUX)
    prctl(PR_SET_NAME,(unsigned long)&name);
#endif
}

}
<|endoftext|>


<commit_before>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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.
 *
 ***************************************************************/

/*
   This is some wisdom from Cygnus's web page.  If you just try to use
   the "stringify" operator on a preprocessor directive, you'd get
   "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
   is).  That's because the stringify operator is a special case, and
   the preprocessor isn't allowed to expand things that are passed to
   it.  However, by defining two layers of macros, you get the right
   behavior, since the first pass converts:

   xstr(PLATFORM) -> str(Intel Linux)

   and the next pass gives:

   str(Intel Linux) -> "Intel Linux"

   This is exactly what we want, so we use it.  -Derek Wright and Jeff
   Ballard, 12/2/99

   Also, because the NT build system is totally different, we have to
   define the correct platform string right in here. :( -Derek 12/3/99
*/

#define xstr(s) str(s)
#define str(s) #s

#if defined(WIN32)
#define PLATFORM INTEL-WINNT50
#endif

/* Via configure, one may have specified a particular buildid string to use
	in the version string. So honor that request here. */
#if defined(BUILDID)
#define BUILDIDSTR " BuildID: " xstr(BUILDID)
#else
#define BUILDIDSTR ""
#endif

/* Here is the version string - update before a public release */
/* --- IMPORTANT!  THE FORMAT OF THE VERSION STRING IS VERY STRICT
   BECAUSE IT IS PARSED AT RUNTIME.  DO NOT ALTER THE FORMAT OR ENTER
   ANYTHING EXTRA BEFORE THE DATE.  IF YOU WISH TO ADD EXTRA INFORMATION,
   DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER.
   EXAMPLES:
       $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK]
	   $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!]
   Any questions?  See Todd or Derek.  Note: if you mess it up, DaemonCore
   will EXCEPT at startup time.
*/

static char* CondorVersionString = "$CondorVersion: 7.1.0 " __DATE__ BUILDIDSTR " $";

/* Here is the platform string.  You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";

extern "C" {

const char*
CondorVersion( void )
{
	return CondorVersionString;
}

const char*
CondorPlatform( void )
{
	return CondorPlatformString;
}

} /* extern "C" */

<commit_msg>Updating version to 7.1.1 pre-release.<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * 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.
 *
 ***************************************************************/

/*
   This is some wisdom from Cygnus's web page.  If you just try to use
   the "stringify" operator on a preprocessor directive, you'd get
   "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
   is).  That's because the stringify operator is a special case, and
   the preprocessor isn't allowed to expand things that are passed to
   it.  However, by defining two layers of macros, you get the right
   behavior, since the first pass converts:

   xstr(PLATFORM) -> str(Intel Linux)

   and the next pass gives:

   str(Intel Linux) -> "Intel Linux"

   This is exactly what we want, so we use it.  -Derek Wright and Jeff
   Ballard, 12/2/99

   Also, because the NT build system is totally different, we have to
   define the correct platform string right in here. :( -Derek 12/3/99
*/

#define xstr(s) str(s)
#define str(s) #s

#if defined(WIN32)
#define PLATFORM INTEL-WINNT50
#endif

/* Via configure, one may have specified a particular buildid string to use
	in the version string. So honor that request here. */
#if defined(BUILDID)
#define BUILDIDSTR " BuildID: " xstr(BUILDID)
#else
#define BUILDIDSTR ""
#endif

/* Here is the version string - update before a public release */
/* --- IMPORTANT!  THE FORMAT OF THE VERSION STRING IS VERY STRICT
   BECAUSE IT IS PARSED AT RUNTIME.  DO NOT ALTER THE FORMAT OR ENTER
   ANYTHING EXTRA BEFORE THE DATE.  IF YOU WISH TO ADD EXTRA INFORMATION,
   DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER.
   EXAMPLES:
       $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK]
	   $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!]
   Any questions?  See Todd or Derek.  Note: if you mess it up, DaemonCore
   will EXCEPT at startup time.
*/

static char* CondorVersionString = "$CondorVersion: 7.1.1 " __DATE__ BUILDIDSTR " PRE-RELEASE-UWCS $";

/* Here is the platform string.  You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";

extern "C" {

const char*
CondorVersion( void )
{
	return CondorVersionString;
}

const char*
CondorPlatform( void )
{
	return CondorPlatformString;
}

} /* extern "C" */

<|endoftext|>


<commit_before>/**
 * @copyright
 * ====================================================================
 *    Licensed to the Apache Software Foundation (ASF) under one
 *    or more contributor license agreements.  See the NOTICE file
 *    distributed with this work for additional information
 *    regarding copyright ownership.  The ASF licenses this file
 *    to you 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.
 * ====================================================================
 * @endcopyright
 *
 * @file Outputer.cpp
 * @brief Implementation of the class Outputer
 */

#include "Outputer.h"
#include "JNIUtil.h"
#include "JNIByteArray.h"

/**
 * Create an Outputer object.
 * @param jthis the Java object to be stored
 */
Outputer::Outputer(jobject jthis)
{
  m_jthis = jthis;
}

/**
 * Destroy an Inputer object.
 */
Outputer::~Outputer()
{
  // The m_jthis does not need to be destroyed, because it is the
  // passed in parameter to the Java method.
}

/**
 * Create a svn_stream_t structure for this object.  This will be used
 * as an output stream by Subversion.
 * @param pool  the pool, from which the structure is allocated
 * @return the output stream
 */
svn_stream_t *Outputer::getStream(const SVN::Pool &pool)
{
  // Create a stream with this as the baton and set the write and
  // close functions.
  svn_stream_t *ret = svn_stream_create(this, pool.pool());
  svn_stream_set_write(ret, Outputer::write);
  svn_stream_set_close(ret, Outputer::close);
  return ret;
}

/**
 * Implements svn_write_fn_t to write data out from Subversion.
 * @param baton     an Outputer object for the callback
 * @param buffer    the buffer for the write data
 * @param len       on input the buffer len, on output the number of written
 *                  bytes
 * @return a subversion error or SVN_NO_ERROR
 */
svn_error_t *Outputer::write(void *baton, const char *buffer, apr_size_t *len)
{
  JNIEnv *env = JNIUtil::getEnv();

  // An object of our class is passed in as the baton.
  Outputer *that = (Outputer*)baton;

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/IOutput");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "write", "([B)I");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // convert the data to a Java byte array
  jbyteArray data = JNIUtil::makeJByteArray((const signed char*)buffer,
                                            *len);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // write the data
  jint written = env->CallIntMethod(that->m_jthis, mid, data);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // return the number of bytes written
  *len = written;

  return SVN_NO_ERROR;
}

/**
 * Implements svn_close_fn_t to close the output stream.
 * @param baton     an Outputer object for the callback
 * @return a subversion error or SVN_NO_ERROR
 */
svn_error_t *Outputer::close(void *baton)
{
  JNIEnv *env = JNIUtil::getEnv();

  // An object of our class is passed in as the baton
  Outputer *that = (Outputer*)baton;

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/IOutput");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "close", "()V");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // Call the Java object, to close the stream.
  env->CallVoidMethod(that->m_jthis, mid);
  // No need to check for exception here because we return anyway.

  return SVN_NO_ERROR;
}
<commit_msg>* subversion/bindings/javahl/native/Outputer.cpp   (write): Add a call to DeleteLocalRef() to prevent a leaking local     reference.<commit_after>/**
 * @copyright
 * ====================================================================
 *    Licensed to the Apache Software Foundation (ASF) under one
 *    or more contributor license agreements.  See the NOTICE file
 *    distributed with this work for additional information
 *    regarding copyright ownership.  The ASF licenses this file
 *    to you 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.
 * ====================================================================
 * @endcopyright
 *
 * @file Outputer.cpp
 * @brief Implementation of the class Outputer
 */

#include "Outputer.h"
#include "JNIUtil.h"
#include "JNIByteArray.h"

/**
 * Create an Outputer object.
 * @param jthis the Java object to be stored
 */
Outputer::Outputer(jobject jthis)
{
  m_jthis = jthis;
}

/**
 * Destroy an Inputer object.
 */
Outputer::~Outputer()
{
  // The m_jthis does not need to be destroyed, because it is the
  // passed in parameter to the Java method.
}

/**
 * Create a svn_stream_t structure for this object.  This will be used
 * as an output stream by Subversion.
 * @param pool  the pool, from which the structure is allocated
 * @return the output stream
 */
svn_stream_t *Outputer::getStream(const SVN::Pool &pool)
{
  // Create a stream with this as the baton and set the write and
  // close functions.
  svn_stream_t *ret = svn_stream_create(this, pool.pool());
  svn_stream_set_write(ret, Outputer::write);
  svn_stream_set_close(ret, Outputer::close);
  return ret;
}

/**
 * Implements svn_write_fn_t to write data out from Subversion.
 * @param baton     an Outputer object for the callback
 * @param buffer    the buffer for the write data
 * @param len       on input the buffer len, on output the number of written
 *                  bytes
 * @return a subversion error or SVN_NO_ERROR
 */
svn_error_t *Outputer::write(void *baton, const char *buffer, apr_size_t *len)
{
  JNIEnv *env = JNIUtil::getEnv();

  // An object of our class is passed in as the baton.
  Outputer *that = (Outputer*)baton;

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/IOutput");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "write", "([B)I");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // convert the data to a Java byte array
  jbyteArray data = JNIUtil::makeJByteArray((const signed char*)buffer,
                                            *len);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // write the data
  jint written = env->CallIntMethod(that->m_jthis, mid, data);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  env->DeleteLocalRef(data);
  if (JNIUtil::isJavaExceptionThrown())
    return SVN_NO_ERROR;

  // return the number of bytes written
  *len = written;

  return SVN_NO_ERROR;
}

/**
 * Implements svn_close_fn_t to close the output stream.
 * @param baton     an Outputer object for the callback
 * @return a subversion error or SVN_NO_ERROR
 */
svn_error_t *Outputer::close(void *baton)
{
  JNIEnv *env = JNIUtil::getEnv();

  // An object of our class is passed in as the baton
  Outputer *that = (Outputer*)baton;

  // The method id will not change during the time this library is
  // loaded, so it can be cached.
  static jmethodID mid = 0;
  if (mid == 0)
    {
      jclass clazz = env->FindClass(JAVA_PACKAGE"/IOutput");
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;

      mid = env->GetMethodID(clazz, "close", "()V");
      if (JNIUtil::isJavaExceptionThrown() || mid == 0)
        return SVN_NO_ERROR;

      env->DeleteLocalRef(clazz);
      if (JNIUtil::isJavaExceptionThrown())
        return SVN_NO_ERROR;
    }

  // Call the Java object, to close the stream.
  env->CallVoidMethod(that->m_jthis, mid);
  // No need to check for exception here because we return anyway.

  return SVN_NO_ERROR;
}
<|endoftext|>


<commit_before>/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorFilter.h"
#include "SkColorSpaceXform.h"
#include "SkColorSpaceXformCanvas.h"
#include "SkGradientShader.h"
#include "SkImage_Base.h"
#include "SkMakeUnique.h"
#include "SkNoDrawCanvas.h"
#include "SkSurface.h"
#include "SkTLazy.h"

class SkColorSpaceXformCanvas : public SkNoDrawCanvas {
public:
    SkColorSpaceXformCanvas(SkCanvas* target,
                            sk_sp<SkColorSpace> targetCS)
        : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))
        , fTarget(target)
        , fTargetCS(std::move(targetCS)) {

        fFromSRGB = SkColorSpaceXform::New(SkColorSpace::MakeSRGB().get(), fTargetCS.get());
    }

    sk_sp<const SkImage> xform(const SkImage* img) const {
        return as_IB(img)->makeColorSpace(fTargetCS);
    }

    void xform(SkColor* xformed, const SkColor* srgb, int n) const {
        SkAssertResult(fFromSRGB->apply(SkColorSpaceXform::kBGRA_8888_ColorFormat, xformed,
                                        SkColorSpaceXform::kBGRA_8888_ColorFormat, srgb,
                                        n, kUnpremul_SkAlphaType));
    }

    SkColor xform(SkColor srgb) const {
        SkColor xformed;
        this->xform(&xformed, &srgb, 1);
        return xformed;
    }

    // TODO: Is this introspection going to be enough, or do we need a new SkShader method?
    sk_sp<SkShader> xform(const SkShader* shader) const {
        SkColor color;
        if (shader->isConstant() && shader->asLuminanceColor(&color)) {
            return SkShader::MakeColorShader(this->xform(color));
        }

        SkShader::TileMode xy[2];
        SkMatrix local;
        if (auto img = shader->isAImage(&local, xy)) {
            return this->xform(img)->makeShader(xy[0], xy[1], &local);
        }

        SkShader::ComposeRec compose;
        if (shader->asACompose(&compose)) {
            auto A = this->xform(compose.fShaderA),
                 B = this->xform(compose.fShaderB);
            if (A && B) {
                return SkShader::MakeComposeShader(std::move(A), std::move(B), compose.fBlendMode);
            }
        }

        SkShader::GradientInfo gradient;
        sk_bzero(&gradient, sizeof(gradient));
        if (auto type = shader->asAGradient(&gradient)) {
            SkSTArray<8, SkColor>  colors(gradient.fColorCount);
            SkSTArray<8, SkScalar>    pos(gradient.fColorCount);

            gradient.fColors       = colors.begin();
            gradient.fColorOffsets =    pos.begin();
            shader->asAGradient(&gradient);

            SkSTArray<8, SkColor> xformed(gradient.fColorCount);
            this->xform(xformed.begin(), gradient.fColors, gradient.fColorCount);

            switch (type) {
                case SkShader::kNone_GradientType:
                case SkShader::kColor_GradientType:
                    SkASSERT(false);  // Should be unreachable.
                    break;

                case SkShader::kLinear_GradientType:
                    return SkGradientShader::MakeLinear(gradient.fPoint,
                                                        xformed.begin(),
                                                        gradient.fColorOffsets,
                                                        gradient.fColorCount,
                                                        gradient.fTileMode,
                                                        gradient.fGradientFlags,
                                                        &shader->getLocalMatrix());
                case SkShader::kRadial_GradientType:  break;  // TODO
                case SkShader::kSweep_GradientType:   break;  // TODO
                case SkShader::kConical_GradientType: break;  // TODO
            }
        }

        return nullptr;
    }

    const SkPaint& xform(const SkPaint& paint, SkTLazy<SkPaint>* lazy) const {
        const SkPaint* result = &paint;
        auto get_lazy = [&] {
            if (!lazy->isValid()) {
                lazy->init(paint);
                result = lazy->get();
            }
            return lazy->get();
        };

        // All SkColorSpaces have the same black point.
        if (paint.getColor() & 0xffffff) {
            get_lazy()->setColor(this->xform(paint.getColor()));
        }

        if (auto shader = paint.getShader()) {
            if (auto replacement = this->xform(shader)) {
                get_lazy()->setShader(std::move(replacement));
            }
        }

        // As far as I know, SkModeColorFilter is the only color filter that holds a color.
        if (auto cf = paint.getColorFilter()) {
            SkColor color;
            SkBlendMode mode;
            if (cf->asColorMode(&color, &mode)) {
                get_lazy()->setColorFilter(SkColorFilter::MakeModeFilter(this->xform(color), mode));
            }
        }

        // TODO:
        //    - image filters?

        return *result;
    }

    const SkPaint* xform(const SkPaint* paint, SkTLazy<SkPaint>* lazy) const {
        return paint ? &this->xform(*paint, lazy) : nullptr;
    }

    void onDrawPaint(const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPaint(this->xform(paint, &lazy));
    }

    void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRect(rect, this->xform(paint, &lazy));
    }
    void onDrawOval(const SkRect& oval, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawOval(oval, this->xform(paint, &lazy));
    }
    void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRRect(rrect, this->xform(paint, &lazy));
    }
    void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawDRRect(outer, inner, this->xform(paint, &lazy));
    }
    void onDrawPath(const SkPath& path, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPath(path, this->xform(paint, &lazy));
    }
    void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,
                   const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawArc(oval, start, sweep, useCenter, this->xform(paint, &lazy));
    }
    void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRegion(region, this->xform(paint, &lazy));
    }
    void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],
                     SkBlendMode mode, const SkPaint& paint) override {
        SkColor xformed[4];
        if (colors) {
            this->xform(xformed, colors, 4);
            colors = xformed;
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawPatch(cubics, colors, texs, mode, this->xform(paint, &lazy));
    }
    void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,
                      const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPoints(mode, count, pts, this->xform(paint, &lazy));
    }
    void onDrawVertices(VertexMode vmode, int count,
                        const SkPoint* verts, const SkPoint* texs, const SkColor* colors,
                        SkBlendMode mode,
                        const uint16_t* indices, int indexCount, const SkPaint& paint) override {
        SkSTArray<8, SkColor> xformed;
        if (colors) {
            xformed.reset(count);
            this->xform(xformed.begin(), colors, count);
            colors = xformed.begin();
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawVertices(vmode, count, verts, texs, colors, mode, indices, indexCount,
                              this->xform(paint, &lazy));
    }

    void onDrawText(const void* ptr, size_t len,
                    SkScalar x, SkScalar y,
                    const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawText(ptr, len, x, y, this->xform(paint, &lazy));
    }
    void onDrawPosText(const void* ptr, size_t len,
                       const SkPoint* xys,
                       const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPosText(ptr, len, xys, this->xform(paint, &lazy));
    }
    void onDrawPosTextH(const void* ptr, size_t len,
                        const SkScalar* xs, SkScalar y,
                        const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPosTextH(ptr, len, xs, y, this->xform(paint, &lazy));
    }
    void onDrawTextOnPath(const void* ptr, size_t len,
                          const SkPath& path, const SkMatrix* matrix,
                          const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextOnPath(ptr, len, path, matrix, this->xform(paint, &lazy));
    }
    void onDrawTextRSXform(const void* ptr, size_t len,
                           const SkRSXform* xforms, const SkRect* cull,
                           const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextRSXform(ptr, len, xforms, cull, this->xform(paint, &lazy));
    }
    void onDrawTextBlob(const SkTextBlob* blob,
                        SkScalar x, SkScalar y,
                        const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextBlob(blob, x, y, this->xform(paint, &lazy));
    }

    void onDrawImage(const SkImage* img,
                     SkScalar l, SkScalar t,
                     const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImage(this->xform(img).get(),
                           l, t,
                           this->xform(paint, &lazy));
    }
    void onDrawImageRect(const SkImage* img,
                         const SkRect* src, const SkRect& dst,
                         const SkPaint* paint, SrcRectConstraint constraint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageRect(this->xform(img).get(),
                               src ? *src : dst, dst,
                               this->xform(paint, &lazy), constraint);
    }
    void onDrawImageNine(const SkImage* img,
                         const SkIRect& center, const SkRect& dst,
                         const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageNine(this->xform(img).get(),
                               center, dst,
                               this->xform(paint, &lazy));
    }
    void onDrawImageLattice(const SkImage* img,
                            const Lattice& lattice, const SkRect& dst,
                            const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageLattice(this->xform(img).get(),
                                  lattice, dst,
                                  this->xform(paint, &lazy));
    }
    void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,
                     const SkColor* colors, int count, SkBlendMode mode,
                     const SkRect* cull, const SkPaint* paint) override {
        SkSTArray<8, SkColor> xformed;
        if (colors) {
            xformed.reset(count);
            this->xform(xformed.begin(), colors, count);
            colors = xformed.begin();
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawAtlas(this->xform(atlas).get(), xforms, tex, colors, count, mode, cull,
                           this->xform(paint, &lazy));
    }

    void onDrawBitmap(const SkBitmap& bitmap,
                      SkScalar l, SkScalar t,
                      const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImage(image.get(), l, t, paint);
        }
    }
    void onDrawBitmapRect(const SkBitmap& bitmap,
                          const SkRect* src, const SkRect& dst,
                          const SkPaint* paint, SrcRectConstraint constraint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageRect(image.get(), src, dst, paint, constraint);
        }
    }
    void onDrawBitmapNine(const SkBitmap& bitmap,
                          const SkIRect& center, const SkRect& dst,
                          const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageNine(image.get(), center, dst, paint);
        }
    }
    void onDrawBitmapLattice(const SkBitmap& bitmap,
                             const Lattice& lattice, const SkRect& dst,
                             const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageLattice(image.get(), lattice, dst, paint);
        }
    }

    // TODO: May not be ideal to unfurl pictures.
    void onDrawPicture(const SkPicture* pic,
                       const SkMatrix* matrix,
                       const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        SkCanvas::onDrawPicture(pic, matrix, this->xform(paint, &lazy));
    }
    void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
        SkTLazy<SkPaint> lazy;
        SkCanvas::onDrawDrawable(drawable, matrix);
    }

    SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {
        SkTLazy<SkPaint> lazy;
        fTarget->saveLayer({
            rec.fBounds,
            this->xform(rec.fPaint, &lazy),
            rec.fBackdrop,  // TODO: this is an image filter
            rec.fSaveLayerFlags,
        });
        return kNoLayer_SaveLayerStrategy;
    }

    // Everything from here on should be uninteresting strictly proxied state-change calls.
    void willSave()    override { fTarget->save(); }
    void willRestore() override { fTarget->restore(); }

    void didConcat   (const SkMatrix& m) override { fTarget->concat   (m); }
    void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }

    void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipRect(clip, op, style);
    }
    void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipRRect(clip, op, style);
    }
    void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipPath(clip, op, style);
    }
    void onClipRegion(const SkRegion& clip, SkClipOp op) override {
        fTarget->clipRegion(clip, op);
    }

    void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {
        fTarget->drawAnnotation(rect, key, val);
    }

    sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {
        return fTarget->makeSurface(info, &props);
    }

private:
    SkCanvas*                          fTarget;
    sk_sp<SkColorSpace>                fTargetCS;
    std::unique_ptr<SkColorSpaceXform> fFromSRGB;
};

std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target,
                                                        sk_sp<SkColorSpace> targetCS) {
    return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(targetCS));
}
<commit_msg>Support all gradient types in SkColorSpaceXformCanvas.<commit_after>/*
 * Copyright 2017 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "SkColorFilter.h"
#include "SkColorSpaceXform.h"
#include "SkColorSpaceXformCanvas.h"
#include "SkGradientShader.h"
#include "SkImage_Base.h"
#include "SkMakeUnique.h"
#include "SkNoDrawCanvas.h"
#include "SkSurface.h"
#include "SkTLazy.h"

class SkColorSpaceXformCanvas : public SkNoDrawCanvas {
public:
    SkColorSpaceXformCanvas(SkCanvas* target,
                            sk_sp<SkColorSpace> targetCS)
        : SkNoDrawCanvas(SkIRect::MakeSize(target->getBaseLayerSize()))
        , fTarget(target)
        , fTargetCS(std::move(targetCS)) {

        fFromSRGB = SkColorSpaceXform::New(SkColorSpace::MakeSRGB().get(), fTargetCS.get());
    }

    sk_sp<const SkImage> xform(const SkImage* img) const {
        return as_IB(img)->makeColorSpace(fTargetCS);
    }

    void xform(SkColor* xformed, const SkColor* srgb, int n) const {
        SkAssertResult(fFromSRGB->apply(SkColorSpaceXform::kBGRA_8888_ColorFormat, xformed,
                                        SkColorSpaceXform::kBGRA_8888_ColorFormat, srgb,
                                        n, kUnpremul_SkAlphaType));
    }

    SkColor xform(SkColor srgb) const {
        SkColor xformed;
        this->xform(&xformed, &srgb, 1);
        return xformed;
    }

    // TODO: Is this introspection going to be enough, or do we need a new SkShader method?
    sk_sp<SkShader> xform(const SkShader* shader) const {
        SkColor color;
        if (shader->isConstant() && shader->asLuminanceColor(&color)) {
            return SkShader::MakeColorShader(this->xform(color));
        }

        SkShader::TileMode xy[2];
        SkMatrix local;
        if (auto img = shader->isAImage(&local, xy)) {
            return this->xform(img)->makeShader(xy[0], xy[1], &local);
        }

        SkShader::ComposeRec compose;
        if (shader->asACompose(&compose)) {
            auto A = this->xform(compose.fShaderA),
                 B = this->xform(compose.fShaderB);
            if (A && B) {
                return SkShader::MakeComposeShader(std::move(A), std::move(B), compose.fBlendMode);
            }
        }

        SkShader::GradientInfo gradient;
        sk_bzero(&gradient, sizeof(gradient));
        if (auto type = shader->asAGradient(&gradient)) {
            SkSTArray<8, SkColor>  colors(gradient.fColorCount);
            SkSTArray<8, SkScalar>    pos(gradient.fColorCount);

            gradient.fColors       = colors.begin();
            gradient.fColorOffsets =    pos.begin();
            shader->asAGradient(&gradient);

            SkSTArray<8, SkColor> xformed(gradient.fColorCount);
            this->xform(xformed.begin(), gradient.fColors, gradient.fColorCount);

            switch (type) {
                case SkShader::kNone_GradientType:
                case SkShader::kColor_GradientType:
                    SkASSERT(false);  // Should be unreachable.
                    break;

                case SkShader::kLinear_GradientType:
                    return SkGradientShader::MakeLinear(gradient.fPoint,
                                                        xformed.begin(),
                                                        gradient.fColorOffsets,
                                                        gradient.fColorCount,
                                                        gradient.fTileMode,
                                                        gradient.fGradientFlags,
                                                        &shader->getLocalMatrix());
                case SkShader::kRadial_GradientType:
                    return SkGradientShader::MakeRadial(gradient.fPoint[0],
                                                        gradient.fRadius[0],
                                                        xformed.begin(),
                                                        gradient.fColorOffsets,
                                                        gradient.fColorCount,
                                                        gradient.fTileMode,
                                                        gradient.fGradientFlags,
                                                        &shader->getLocalMatrix());
                case SkShader::kSweep_GradientType:
                    return SkGradientShader::MakeSweep(gradient.fPoint[0].fX,
                                                       gradient.fPoint[0].fY,
                                                       xformed.begin(),
                                                       gradient.fColorOffsets,
                                                       gradient.fColorCount,
                                                       gradient.fGradientFlags,
                                                       &shader->getLocalMatrix());
                case SkShader::kConical_GradientType:
                    return SkGradientShader::MakeTwoPointConical(gradient.fPoint[0],
                                                                 gradient.fRadius[0],
                                                                 gradient.fPoint[1],
                                                                 gradient.fRadius[1],
                                                                 xformed.begin(),
                                                                 gradient.fColorOffsets,
                                                                 gradient.fColorCount,
                                                                 gradient.fTileMode,
                                                                 gradient.fGradientFlags,
                                                                 &shader->getLocalMatrix());
            }
        }

        return nullptr;
    }

    const SkPaint& xform(const SkPaint& paint, SkTLazy<SkPaint>* lazy) const {
        const SkPaint* result = &paint;
        auto get_lazy = [&] {
            if (!lazy->isValid()) {
                lazy->init(paint);
                result = lazy->get();
            }
            return lazy->get();
        };

        // All SkColorSpaces have the same black point.
        if (paint.getColor() & 0xffffff) {
            get_lazy()->setColor(this->xform(paint.getColor()));
        }

        if (auto shader = paint.getShader()) {
            if (auto replacement = this->xform(shader)) {
                get_lazy()->setShader(std::move(replacement));
            }
        }

        // As far as I know, SkModeColorFilter is the only color filter that holds a color.
        if (auto cf = paint.getColorFilter()) {
            SkColor color;
            SkBlendMode mode;
            if (cf->asColorMode(&color, &mode)) {
                get_lazy()->setColorFilter(SkColorFilter::MakeModeFilter(this->xform(color), mode));
            }
        }

        // TODO:
        //    - image filters?

        return *result;
    }

    const SkPaint* xform(const SkPaint* paint, SkTLazy<SkPaint>* lazy) const {
        return paint ? &this->xform(*paint, lazy) : nullptr;
    }

    void onDrawPaint(const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPaint(this->xform(paint, &lazy));
    }

    void onDrawRect(const SkRect& rect, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRect(rect, this->xform(paint, &lazy));
    }
    void onDrawOval(const SkRect& oval, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawOval(oval, this->xform(paint, &lazy));
    }
    void onDrawRRect(const SkRRect& rrect, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRRect(rrect, this->xform(paint, &lazy));
    }
    void onDrawDRRect(const SkRRect& outer, const SkRRect& inner, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawDRRect(outer, inner, this->xform(paint, &lazy));
    }
    void onDrawPath(const SkPath& path, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPath(path, this->xform(paint, &lazy));
    }
    void onDrawArc(const SkRect& oval, SkScalar start, SkScalar sweep, bool useCenter,
                   const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawArc(oval, start, sweep, useCenter, this->xform(paint, &lazy));
    }
    void onDrawRegion(const SkRegion& region, const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawRegion(region, this->xform(paint, &lazy));
    }
    void onDrawPatch(const SkPoint cubics[12], const SkColor colors[4], const SkPoint texs[4],
                     SkBlendMode mode, const SkPaint& paint) override {
        SkColor xformed[4];
        if (colors) {
            this->xform(xformed, colors, 4);
            colors = xformed;
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawPatch(cubics, colors, texs, mode, this->xform(paint, &lazy));
    }
    void onDrawPoints(PointMode mode, size_t count, const SkPoint* pts,
                      const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPoints(mode, count, pts, this->xform(paint, &lazy));
    }
    void onDrawVertices(VertexMode vmode, int count,
                        const SkPoint* verts, const SkPoint* texs, const SkColor* colors,
                        SkBlendMode mode,
                        const uint16_t* indices, int indexCount, const SkPaint& paint) override {
        SkSTArray<8, SkColor> xformed;
        if (colors) {
            xformed.reset(count);
            this->xform(xformed.begin(), colors, count);
            colors = xformed.begin();
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawVertices(vmode, count, verts, texs, colors, mode, indices, indexCount,
                              this->xform(paint, &lazy));
    }

    void onDrawText(const void* ptr, size_t len,
                    SkScalar x, SkScalar y,
                    const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawText(ptr, len, x, y, this->xform(paint, &lazy));
    }
    void onDrawPosText(const void* ptr, size_t len,
                       const SkPoint* xys,
                       const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPosText(ptr, len, xys, this->xform(paint, &lazy));
    }
    void onDrawPosTextH(const void* ptr, size_t len,
                        const SkScalar* xs, SkScalar y,
                        const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawPosTextH(ptr, len, xs, y, this->xform(paint, &lazy));
    }
    void onDrawTextOnPath(const void* ptr, size_t len,
                          const SkPath& path, const SkMatrix* matrix,
                          const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextOnPath(ptr, len, path, matrix, this->xform(paint, &lazy));
    }
    void onDrawTextRSXform(const void* ptr, size_t len,
                           const SkRSXform* xforms, const SkRect* cull,
                           const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextRSXform(ptr, len, xforms, cull, this->xform(paint, &lazy));
    }
    void onDrawTextBlob(const SkTextBlob* blob,
                        SkScalar x, SkScalar y,
                        const SkPaint& paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawTextBlob(blob, x, y, this->xform(paint, &lazy));
    }

    void onDrawImage(const SkImage* img,
                     SkScalar l, SkScalar t,
                     const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImage(this->xform(img).get(),
                           l, t,
                           this->xform(paint, &lazy));
    }
    void onDrawImageRect(const SkImage* img,
                         const SkRect* src, const SkRect& dst,
                         const SkPaint* paint, SrcRectConstraint constraint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageRect(this->xform(img).get(),
                               src ? *src : dst, dst,
                               this->xform(paint, &lazy), constraint);
    }
    void onDrawImageNine(const SkImage* img,
                         const SkIRect& center, const SkRect& dst,
                         const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageNine(this->xform(img).get(),
                               center, dst,
                               this->xform(paint, &lazy));
    }
    void onDrawImageLattice(const SkImage* img,
                            const Lattice& lattice, const SkRect& dst,
                            const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        fTarget->drawImageLattice(this->xform(img).get(),
                                  lattice, dst,
                                  this->xform(paint, &lazy));
    }
    void onDrawAtlas(const SkImage* atlas, const SkRSXform* xforms, const SkRect* tex,
                     const SkColor* colors, int count, SkBlendMode mode,
                     const SkRect* cull, const SkPaint* paint) override {
        SkSTArray<8, SkColor> xformed;
        if (colors) {
            xformed.reset(count);
            this->xform(xformed.begin(), colors, count);
            colors = xformed.begin();
        }

        SkTLazy<SkPaint> lazy;
        fTarget->drawAtlas(this->xform(atlas).get(), xforms, tex, colors, count, mode, cull,
                           this->xform(paint, &lazy));
    }

    void onDrawBitmap(const SkBitmap& bitmap,
                      SkScalar l, SkScalar t,
                      const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImage(image.get(), l, t, paint);
        }
    }
    void onDrawBitmapRect(const SkBitmap& bitmap,
                          const SkRect* src, const SkRect& dst,
                          const SkPaint* paint, SrcRectConstraint constraint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageRect(image.get(), src, dst, paint, constraint);
        }
    }
    void onDrawBitmapNine(const SkBitmap& bitmap,
                          const SkIRect& center, const SkRect& dst,
                          const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageNine(image.get(), center, dst, paint);
        }
    }
    void onDrawBitmapLattice(const SkBitmap& bitmap,
                             const Lattice& lattice, const SkRect& dst,
                             const SkPaint* paint) override {
        if (auto image = SkImage::MakeFromBitmap(bitmap)) {
            this->onDrawImageLattice(image.get(), lattice, dst, paint);
        }
    }

    // TODO: May not be ideal to unfurl pictures.
    void onDrawPicture(const SkPicture* pic,
                       const SkMatrix* matrix,
                       const SkPaint* paint) override {
        SkTLazy<SkPaint> lazy;
        SkCanvas::onDrawPicture(pic, matrix, this->xform(paint, &lazy));
    }
    void onDrawDrawable(SkDrawable* drawable, const SkMatrix* matrix) override {
        SkTLazy<SkPaint> lazy;
        SkCanvas::onDrawDrawable(drawable, matrix);
    }

    SaveLayerStrategy getSaveLayerStrategy(const SaveLayerRec& rec) override {
        SkTLazy<SkPaint> lazy;
        fTarget->saveLayer({
            rec.fBounds,
            this->xform(rec.fPaint, &lazy),
            rec.fBackdrop,  // TODO: this is an image filter
            rec.fSaveLayerFlags,
        });
        return kNoLayer_SaveLayerStrategy;
    }

    // Everything from here on should be uninteresting strictly proxied state-change calls.
    void willSave()    override { fTarget->save(); }
    void willRestore() override { fTarget->restore(); }

    void didConcat   (const SkMatrix& m) override { fTarget->concat   (m); }
    void didSetMatrix(const SkMatrix& m) override { fTarget->setMatrix(m); }

    void onClipRect(const SkRect& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipRect(clip, op, style);
    }
    void onClipRRect(const SkRRect& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipRRect(clip, op, style);
    }
    void onClipPath(const SkPath& clip, SkClipOp op, ClipEdgeStyle style) override {
        fTarget->clipPath(clip, op, style);
    }
    void onClipRegion(const SkRegion& clip, SkClipOp op) override {
        fTarget->clipRegion(clip, op);
    }

    void onDrawAnnotation(const SkRect& rect, const char* key, SkData* val) override {
        fTarget->drawAnnotation(rect, key, val);
    }

    sk_sp<SkSurface> onNewSurface(const SkImageInfo& info, const SkSurfaceProps& props) override {
        return fTarget->makeSurface(info, &props);
    }

private:
    SkCanvas*                          fTarget;
    sk_sp<SkColorSpace>                fTargetCS;
    std::unique_ptr<SkColorSpaceXform> fFromSRGB;
};

std::unique_ptr<SkCanvas> SkCreateColorSpaceXformCanvas(SkCanvas* target,
                                                        sk_sp<SkColorSpace> targetCS) {
    return skstd::make_unique<SkColorSpaceXformCanvas>(target, std::move(targetCS));
}
<|endoftext|>


<commit_before>// LineSegment.cpp

#include "LineSegment.h"
#include "Triangle.h"
#include <wx/debug.h>

LineSegment::LineSegment( void )
{
	vertex[0].set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
	vertex[1].set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
}

LineSegment::LineSegment( const c3ga::vectorE3GA& vertex0, const c3ga::vectorE3GA& vertex1 )
{
	vertex[0] = vertex0;
	vertex[1] = vertex1;
}

/*virtual*/ LineSegment::~LineSegment( void )
{
}

bool LineSegment::TessellateTriangle( const Triangle& triangle, TriangleList& tessellatedTriangleList ) const
{
	VectorArray edgeHitArray;

	for( int i = 0; i < 3; i++ )
	{
		int j = ( i + 1 ) % 3;
		LineSegment edge;
		edge.vertex[0] = triangle.vertex[i].point;
		edge.vertex[1] = triangle.vertex[j].point;

		c3ga::vectorE3GA intersectionPoint;
		if( CalculateIntersectionWith( edge, intersectionPoint, false, true ) )
			edgeHitArray.push_back( intersectionPoint );
	}

	if( edgeHitArray.size() <= 1 )
		return false;

	wxASSERT( edgeHitArray.size() == 2 );
	if( edgeHitArray.size() != 2 )
		return false;

	LineSegment chord;
	chord.vertex[0] = *edgeHitArray.begin();
	chord.vertex[1] = edgeHitArray.back();

	if( !( chord.ContainsPoint( vertex[0] ) || chord.ContainsPoint( vertex[1] ) ||
		ContainsPoint( chord.vertex[0] ) || ContainsPoint( chord.vertex[1] ) ) )
	{
		return false;
	}

	// Get vertex list in CCW order.
	VectorArray vertexArray;	// TODO: May want to replace this with std::list< Triangle::Vertex >.

	for( int i = 0; i < 3; i++ )
	{
		int j = ( i + 1 ) % 3;
		LineSegment edge;
		edge.vertex[0] = triangle.vertex[i].point;
		edge.vertex[1] = triangle.vertex[j].point;

		vertexArray.push_back( edge.vertex[0] );

		// There may be duplicate vertices put on the list, but that's okay.
		for( int k = 0; k < 2; k++ )
			if( edge.ContainsPoint( chord.vertex[k] ) )
				vertexArray.push_back( chord.vertex[k] );	// TODO: New UVs may be as easy as lerps along edges.
	}

	wxASSERT( vertexArray.size() >= 5 );

	c3ga::vectorE3GA center( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
	for( int i = 0; i < vertexArray.size(); i++ )
		center += vertexArray[i];

	center = center * ( 1.0 / double( vertexArray.size() ) );

	double smallestDistance = 0.0;
	int bestVertex = -1;
	for( int i = 0; i < vertexArray.size(); i++ )
	{
		double distance = c3ga::norm( center - vertexArray[i] );
		if( bestVertex == -1 || distance < smallestDistance )
		{
			smallestDistance = distance;
			bestVertex = i;
		}
	}

	// This is not necessarily the best tessellation, but it should work.
	for( int i = 0; i < vertexArray.size() - 2; i++ )
	{
		Triangle* triangle = new Triangle();
		triangle->vertex[0].point = vertexArray[ bestVertex ];
		triangle->vertex[1].point = vertexArray[ ( bestVertex + i + 1 ) % vertexArray.size() ];
		triangle->vertex[2].point = vertexArray[ ( bestVertex + i + 2 ) % vertexArray.size() ];
		if( triangle->IsDegenerate() )
			delete triangle;
		else
			tessellatedTriangleList.push_back( triangle );
	}

	return true;
}

double LineSegment::CalculateOrthogonalDistanceToLine( const c3ga::vectorE3GA& point ) const
{
	c3ga::vectorE3GA normal = c3ga::unit( vertex[1] - vertex[0] );
	c3ga::vectorE3GA vector = point - vertex[0];
	double distance = c3ga::norm( c3ga::lc( normal, c3ga::op( vector, normal ) ) );
	return distance;
}

bool LineSegment::CalculateIntersectionWith( const LineSegment& lineSegment, c3ga::vectorE3GA& intersectionPoint, bool mustHitThis, bool mustHitGiven ) const
{
	c3ga::bivectorE3GA bivector = CalculateLineVector() ^ lineSegment.CalculateLineVector();
	if( bivector.get_e1_e2() == 0.0 )
		return false;		// The line segments are parallel.  They either intersect not at all, in a single point, or an infinite number of points; we don't care?

	c3ga::vectorE3GA vector = bivector * c3ga::I3;
	intersectionPoint.set_e1( vector.get_e1() / vector.get_e3() );
	intersectionPoint.set_e2( vector.get_e2() / vector.get_e3() );
	intersectionPoint.set_e3( 0.0 );

	if( mustHitThis && !ContainsPoint( intersectionPoint ) )
		return false;

	if( mustHitGiven && !lineSegment.ContainsPoint( intersectionPoint ) )
		return false;

	return true;
}

c3ga::vectorE3GA LineSegment::CalculateLineVector( void ) const
{
	c3ga::vectorE3GA vector = vertex[1] - vertex[0];
	c3ga::vectorE3GA normal( c3ga::vectorE3GA::coord_e1_e2_e3, -vector.get_e2(), vector.get_e1(), 0.0 );
	normal = c3ga::unit( normal );
	double dot = c3ga::lc( vertex[0], normal );
	vector = normal - c3ga::vectorE3GA( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, dot );
	return vector;
}

bool LineSegment::ContainsPoint( const c3ga::vectorE3GA& point, double eps /*= 1e-7*/ ) const
{
	double totalLength = c3ga::norm( point - vertex[0] ) + c3ga::norm( vertex[1] - point );
	double length = CalculateLength();
	if( fabs( totalLength - length ) < eps )
		return true;
	return false;
}

bool LineSegment::PointOnLine( const c3ga::vectorE3GA& point, double eps /*= 1e-7*/ ) const
{
	c3ga::vectorE3GA vector = CalculateLineVector();
	c3ga::vectorE3GA homogenizedPoint = point;
	homogenizedPoint.set_e3( 1.0 );
	double dot = c3ga::lc( homogenizedPoint, vector );
	if( fabs( dot ) < eps )
		return true;
	return false;
}

double LineSegment::CalculateLength( void ) const
{
	return c3ga::norm( vertex[1] - vertex[0] );
}

// LineSegment.cpp<commit_msg>small fix<commit_after>// LineSegment.cpp

#include "LineSegment.h"
#include "Triangle.h"
#include <wx/debug.h>

LineSegment::LineSegment( void )
{
	vertex[0].set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
	vertex[1].set( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
}

LineSegment::LineSegment( const c3ga::vectorE3GA& vertex0, const c3ga::vectorE3GA& vertex1 )
{
	vertex[0] = vertex0;
	vertex[1] = vertex1;
}

/*virtual*/ LineSegment::~LineSegment( void )
{
}

bool LineSegment::TessellateTriangle( const Triangle& triangle, TriangleList& tessellatedTriangleList ) const
{
	VectorArray edgeHitArray;

	for( int i = 0; i < 3; i++ )
	{
		int j = ( i + 1 ) % 3;
		LineSegment edge;
		edge.vertex[0] = triangle.vertex[i].point;
		edge.vertex[1] = triangle.vertex[j].point;

		c3ga::vectorE3GA intersectionPoint;
		if( CalculateIntersectionWith( edge, intersectionPoint, false, true ) )
			edgeHitArray.push_back( intersectionPoint );
	}

	// 0 hits -- we don't cut the triangle.
	// 1 hit -- we're tangent and so don't cut.
	// 2 hits -- we may cut the triangle.
	// 3 hits -- we're tangential here too.
	if( edgeHitArray.size() != 2 )
		return false;

	LineSegment chord;
	chord.vertex[0] = *edgeHitArray.begin();
	chord.vertex[1] = edgeHitArray.back();

	if( !( chord.ContainsPoint( vertex[0] ) || chord.ContainsPoint( vertex[1] ) ||
		ContainsPoint( chord.vertex[0] ) || ContainsPoint( chord.vertex[1] ) ) )
	{
		return false;
	}

	// Get vertex list in CCW order.
	VectorArray vertexArray;	// TODO: May want to replace this with std::list< Triangle::Vertex >.

	for( int i = 0; i < 3; i++ )
	{
		int j = ( i + 1 ) % 3;
		LineSegment edge;
		edge.vertex[0] = triangle.vertex[i].point;
		edge.vertex[1] = triangle.vertex[j].point;

		vertexArray.push_back( edge.vertex[0] );

		// There may be duplicate vertices put on the list, but that's okay.
		for( int k = 0; k < 2; k++ )
			if( edge.ContainsPoint( chord.vertex[k] ) )
				vertexArray.push_back( chord.vertex[k] );	// TODO: New UVs may be as easy as lerps along edges.
	}

	wxASSERT( vertexArray.size() >= 5 );

	c3ga::vectorE3GA center( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, 0.0 );
	for( int i = 0; i < vertexArray.size(); i++ )
		center += vertexArray[i];

	center = center * ( 1.0 / double( vertexArray.size() ) );

	double smallestDistance = 0.0;
	int bestVertex = -1;
	for( int i = 0; i < vertexArray.size(); i++ )
	{
		double distance = c3ga::norm( center - vertexArray[i] );
		if( bestVertex == -1 || distance < smallestDistance )
		{
			smallestDistance = distance;
			bestVertex = i;
		}
	}

	// This is not necessarily the best tessellation, but it should work.
	// I can conceive a recursive way of doing this, but I'm not sure what that gains us.
	for( int i = 0; i < vertexArray.size() - 2; i++ )
	{
		Triangle* triangle = new Triangle();
		triangle->vertex[0].point = vertexArray[ bestVertex ];
		triangle->vertex[1].point = vertexArray[ ( bestVertex + i + 1 ) % vertexArray.size() ];
		triangle->vertex[2].point = vertexArray[ ( bestVertex + i + 2 ) % vertexArray.size() ];
		if( triangle->IsDegenerate() )
			delete triangle;
		else
			tessellatedTriangleList.push_back( triangle );
	}

	return true;
}

double LineSegment::CalculateOrthogonalDistanceToLine( const c3ga::vectorE3GA& point ) const
{
	c3ga::vectorE3GA normal = c3ga::unit( vertex[1] - vertex[0] );
	c3ga::vectorE3GA vector = point - vertex[0];
	double distance = c3ga::norm( c3ga::lc( normal, c3ga::op( vector, normal ) ) );
	return distance;
}

bool LineSegment::CalculateIntersectionWith( const LineSegment& lineSegment, c3ga::vectorE3GA& intersectionPoint, bool mustHitThis, bool mustHitGiven ) const
{
	c3ga::bivectorE3GA bivector = CalculateLineVector() ^ lineSegment.CalculateLineVector();
	if( bivector.get_e1_e2() == 0.0 )
		return false;		// The line segments are parallel.  They either intersect not at all, in a single point, or an infinite number of points; we don't care?

	c3ga::vectorE3GA vector = bivector * c3ga::I3;
	intersectionPoint.set_e1( vector.get_e1() / vector.get_e3() );
	intersectionPoint.set_e2( vector.get_e2() / vector.get_e3() );
	intersectionPoint.set_e3( 0.0 );

	if( mustHitThis && !ContainsPoint( intersectionPoint ) )
		return false;

	if( mustHitGiven && !lineSegment.ContainsPoint( intersectionPoint ) )
		return false;

	return true;
}

c3ga::vectorE3GA LineSegment::CalculateLineVector( void ) const
{
	c3ga::vectorE3GA vector = vertex[1] - vertex[0];
	c3ga::vectorE3GA normal( c3ga::vectorE3GA::coord_e1_e2_e3, -vector.get_e2(), vector.get_e1(), 0.0 );
	normal = c3ga::unit( normal );
	double dot = c3ga::lc( vertex[0], normal );
	vector = normal - c3ga::vectorE3GA( c3ga::vectorE3GA::coord_e1_e2_e3, 0.0, 0.0, dot );
	return vector;
}

bool LineSegment::ContainsPoint( const c3ga::vectorE3GA& point, double eps /*= 1e-7*/ ) const
{
	double totalLength = c3ga::norm( point - vertex[0] ) + c3ga::norm( vertex[1] - point );
	double length = CalculateLength();
	if( fabs( totalLength - length ) < eps )
		return true;
	return false;
}

bool LineSegment::PointOnLine( const c3ga::vectorE3GA& point, double eps /*= 1e-7*/ ) const
{
	c3ga::vectorE3GA vector = CalculateLineVector();
	c3ga::vectorE3GA homogenizedPoint = point;
	homogenizedPoint.set_e3( 1.0 );
	double dot = c3ga::lc( homogenizedPoint, vector );
	if( fabs( dot ) < eps )
		return true;
	return false;
}

double LineSegment::CalculateLength( void ) const
{
	return c3ga::norm( vertex[1] - vertex[0] );
}

// LineSegment.cpp<|endoftext|>


<commit_before>/*
 * @author: jstuder
 *
 */
//from arduino #include <Servo.h>

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>

// Open the Maestro's virtual COM port.
//const char * device = "\\\\.\\USBSER000";  // Windows, "\\\\.\\COM6" also works
const char * device = "/dev/ttyACM0";  // Linux
//const char * device = "/dev/cu.usbmodem00034567";  // Mac OS X

//the servo to counter the pitch of the drone
int pitch = 0;
int roll = 1;
const int PARALLEL = 50; //45 allows for 30 degrees of + and - with ease
const int PERPENDICULAR = PARALLEL + 90;

//A constant to control the speed of angle change, lower is faster
const int SPEED = 10;

// Gets the position of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
int maestroGetPosition(int serialControl, unsigned char channel)
{
  unsigned char command[] = {0x90, channel};
  if(write(serialControl, command, sizeof(command)) == -1)
  {
    perror("error writing");
    return -1;
  }

  unsigned char response[2];
  if(read(serialControl,response,2) != 2)
  {
    perror("error reading");
    return -1;
  }

  return response[0] + 256*response[1];
}

// Sets the target of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
// The units of 'target' are quarter-microseconds.
int maestroSetTarget(int serialControl, unsigned char channel, unsigned short target)
{
  unsigned char command[] = {0x84, channel, target & 0x7F, target >> 7 & 0x7F};
  if (write(serialControl, command, sizeof(command)) == -1)
  {
    perror("error writing");
    return -1;
  }
  return 0;
}

/*
 * @parameters
 *  int angle -> the angle you want to go to
 *  int speed -> the sleep between a move of 1 degree (lower is faster)
 */
void goToAngle(int pitchAngle, int rollAngle, int speed);

/*
 * @parameters
 * bool isPLL -> true if gimbal needs to be parallel to the ground, false if it
 *               needs to be perpendicular
 * int xAdj -> pass a positive or negative value to adjust the left-right axis of the gimbal
 *             (modifies servo2)
 * int yAdj -> pass a positive or negative value to adjust the forward-backward axis of the gimbal
 *             (modifies pitch)
 */
void mntn(int isPLL, int rAdj, int pAdj);

void setup()
{
  if (serialControl == -1)
  {
    perror(device);
    return 1;
  }

  #ifdef _WIN32
    _setmode(serialControl, _O_BINARY);
  #else
    struct termios options;
    tcgetattr(serialControl, &options);
    options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IXON | IXOFF);
    options.c_oflag &= ~(ONLCR | OCRNL);
    options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tcsetattr(serialControl, TCSANOW, &options);
  #endif

  goToAngle(50, 40, SPEED); //sets the gimbal to parallel as default

}

int sig_handler(int signo)
{
  if (signo == SIGUSR1)
  {
    return 1;
  }
}

void main()
{
  //used to track parallel or perpendicular
  static int isParallel = 1;

  int serialControl = open(device, O_RDWR | O_NOCTTY);

  if (Serial.available())
  {
    //allows yChange to default to the previous value. If input is invalid the gimbal doesn't move.
    int pChange = maestroGetPosition(serialControl, pitch);
    int rChange = maestroGetPosition(serialControl, roll);

    //if SIGUSR1 is sent, allows the gimbal to switch orientation
    if (sig_handler(SIGUSR1) == 1)
    {
      if (isParallel == 1)
        isParallel = 0;
      else
        isParallel = 1;
      pChange = 0;
      rChange = 0;
    }
    else
      mntn(isParallel, rChange, pChange);
  }
}

void mntn(int isPLL, int rAdj, int pAdj)
{
  //sets the new angle equal to the change from the old angle
  //runs if the gimbal needs to be parallel to the ground
  rAdj += 40;
  if (isPLL == 1)
  {
    pAdj += PARALLEL;
    goToAngle(pAdj, rAdj, SPEED);
  }
  else
  {
    pAdj += PERPENDICULAR;
    goToAngle(pAdj, rAdj, SPEED);
  }
}

void goToAngle(int pitchAngle, int rollAngle, int speed)
{
  int currentPAngle = maestroGetPosition(serialControl, pitch);
  int currentRAngle = maestroGetPosition(serialControl, roll);
  if(pitchAngle > currentPAngle)
  {
    for (int i = currentPAngle; i < pitchAngle; i++)
    {
      maestroSetTarget(serialControl, pitch, i);
      sleep(speed);
    }
  }
  else
  {
    for (int i = currentPAngle; i > pitchAngle; i--)
    {
      maestroSetTarget(serialControl, pitch, i);
      sleep(speed);
    }
  }

  if(rollAngle > currentRAngle)
  {
    for (int i = currentRAngle; i < rollAngle; i++)
    {
      maestroSetTarget(serialControl, roll, i);
      sleep(speed);
    }
  }
  else
  {
    for (int i = currentRAngle; i > rollAngle; i--)
    {
      maestroSetTarget(serialControl, roll, i);
      sleep(speed);
    }
  }
}

<commit_msg>Update gimbal.cpp<commit_after>/*
 * @author: jstuder
 *
 */
//from arduino #include <Servo.h>

#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <termios.h>

// Open the Maestro's virtual COM port.
//const char * device = "\\\\.\\USBSER000";  // Windows, "\\\\.\\COM6" also works
const char * device = "/dev/ttyACM0";  // Linux
//const char * device = "/dev/cu.usbmodem00034567";  // Mac OS X

//the servo to counter the pitch of the drone
int pitch = 0;
int roll = 1;
const int PARALLEL = 50; //45 allows for 30 degrees of + and - with ease
const int PERPENDICULAR = PARALLEL + 90;

//A constant to control the speed of angle change, lower is faster
const int SPEED = 10;

// Gets the position of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
int maestroGetPosition(int fd, unsigned char channel)
{
  unsigned char command[] = {0x90, channel};
  if(write(fd, command, sizeof(command)) == -1)
  {
    perror("error writing");
    return -1;
  }

  unsigned char response[2];
  if(read(fd,response,2) != 2)
  {
    perror("error reading");
    return -1;
  }

  return response[0] + 256*response[1];
}

// Sets the target of a Maestro channel.
// See the "Serial Servo Commands" section of the user's guide.
// The units of 'target' are quarter-microseconds.
int maestroSetTarget(int serialControl, unsigned char channel, unsigned short target)
{
  unsigned char command[] = {0x84, channel, target & 0x7F, target >> 7 & 0x7F};
  if (write(serialControl, command, sizeof(command)) == -1)
  {
    perror("error writing");
    return -1;
  }
  return 0;
}

/*
 * @parameters
 *  int angle -> the angle you want to go to
 *  int speed -> the sleep between a move of 1 degree (lower is faster)
 */
void goToAngle(int pitchAngle, int rollAngle, int speed);

/*
 * @parameters
 * bool isPLL -> true if gimbal needs to be parallel to the ground, false if it
 *               needs to be perpendicular
 * int xAdj -> pass a positive or negative value to adjust the left-right axis of the gimbal
 *             (modifies servo2)
 * int yAdj -> pass a positive or negative value to adjust the forward-backward axis of the gimbal
 *             (modifies pitch)
 */
void mntn(int isPLL, int rAdj, int pAdj);

void setup()
{
  if (serialControl == -1)
  {
    perror(device);
    return 1;
  }

  #ifdef _WIN32
    _setmode(serialControl, _O_BINARY);
  #else
    struct termios options;
    tcgetattr(serialControl, &options);
    options.c_iflag &= ~(INLCR | IGNCR | ICRNL | IXON | IXOFF);
    options.c_oflag &= ~(ONLCR | OCRNL);
    options.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tcsetattr(serialControl, TCSANOW, &options);
  #endif

  goToAngle(50, 40, SPEED); //sets the gimbal to parallel as default

}

int sig_handler(int signo)
{
  if (signo == SIGUSR1)
  {
    return 1;
  }
}

void main()
{
  //used to track parallel or perpendicular
  static int isParallel = 1;

  int serialControl = open(device, O_RDWR | O_NOCTTY);

  if (Serial.available())
  {
    //allows yChange to default to the previous value. If input is invalid the gimbal doesn't move.
    int pChange = maestroGetPosition(serialControl, pitch);
    int rChange = maestroGetPosition(serialControl, roll);

    //if SIGUSR1 is sent, allows the gimbal to switch orientation
    if (sig_handler(SIGUSR1) == 1)
    {
      if (isParallel == 1)
        isParallel = 0;
      else
        isParallel = 1;
      pChange = 0;
      rChange = 0;
    }
    else
      mntn(isParallel, rChange, pChange);
  }
}

void mntn(int isPLL, int rAdj, int pAdj)
{
  //sets the new angle equal to the change from the old angle
  //runs if the gimbal needs to be parallel to the ground
  rAdj += 40;
  if (isPLL == 1)
  {
    pAdj += PARALLEL;
    goToAngle(pAdj, rAdj, SPEED);
  }
  else
  {
    pAdj += PERPENDICULAR;
    goToAngle(pAdj, rAdj, SPEED);
  }
}

void goToAngle(int pitchAngle, int rollAngle, int speed)
{
  int currentPAngle = maestroGetPosition(serialControl, pitch);
  int currentRAngle = maestroGetPosition(serialControl, roll);
  if(pitchAngle > currentPAngle)
  {
    for (int i = currentPAngle; i < pitchAngle; i++)
    {
      maestroSetTarget(serialControl, pitch, i);
      sleep(speed);
    }
  }
  else
  {
    for (int i = currentPAngle; i > pitchAngle; i--)
    {
      maestroSetTarget(serialControl, pitch, i);
      sleep(speed);
    }
  }

  if(rollAngle > currentRAngle)
  {
    for (int i = currentRAngle; i < rollAngle; i++)
    {
      maestroSetTarget(serialControl, roll, i);
      sleep(speed);
    }
  }
  else
  {
    for (int i = currentRAngle; i > rollAngle; i--)
    {
      maestroSetTarget(serialControl, roll, i);
      sleep(speed);
    }
  }
}

<|endoftext|>


<commit_before>
#include "lcio.h"

#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"

#include "UTIL/LCStdHepRdrNew.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <memory>

// using namespace std ;
using namespace lcio ;

/** Simple test program to demonstrate reading of binary .stdhep generator files.
 *  Writes MCParticle collections to the outputfile stdhepjob.slcio.
 */

int main(int argc, char** argv ){

  if(argc < 4) {

     std::cout << " usage: stdhepjob infile.stdhep outfile.slcio maxEvt " <<  std::endl
	       << "   infile.stdhep    - input file name "  <<  std::endl
	       << "   outfile.slcio    - ouput file name "  <<  std::endl
	       << "   maxEvt           - max number of events to read [-1: all]"  <<  std::endl  ;

    return 1;
  }

  std::string inFile  = argv[1] ;
  std::string outFile = argv[2] ;
  int maxEvt = std::atoi( argv[3] ) ;

  std::cout << "==================================================== " << std::endl
	    << " stdhepjob : " << std::endl  ;

  // Open an instance of the StdHep Reader with the given filename
  LCStdHepRdrNew rdr( inFile.c_str()  ) ;

  std::cout << " opened file : " << inFile << std::endl ;

  rdr.printHeader() ;

  // create sio writer
  std::auto_ptr<LCWriter> lcWrt( LCFactory::getInstance()->createLCWriter() ) ;

  lcWrt->open( outFile )  ;

  std::auto_ptr<LCRunHeaderImpl> runHdr(  new LCRunHeaderImpl ) ;

  runHdr->setRunNumber( 0 ) ;

  std::string detName("Unknown")  ;
  runHdr->setDetectorName( detName ) ;

  std::stringstream description ;

  description << " file generated with LCIO stdhepjob from "  << inFile  ;

  runHdr->setDescription( description.str()  ) ;

  lcWrt->writeRunHeader( runHdr.get()  ) ;

  int count = 0;

  try {

    while( maxEvt < 0  || count < maxEvt ){

      std::auto_ptr<LCEventImpl> evt( new LCEventImpl() ) ;

      evt->setRunNumber(  0   ) ;
      evt->setEventNumber( count ) ;
      evt->setDetectorName( detName ) ;

      // read the next stdhep event and add an MCParticle collection to the event
      rdr.updateNextEvent( evt.get()  , "MCParticle" ) ;

      lcWrt->writeEvent( evt.get()  ) ;

      ++count ;

    } // evt loop
  }

  catch( IO::EndOfDataException& e ) {
  }

  std::cout << "  converted " << count << " events - written to LCIO " << outFile  << std::endl ;

  std::cout << "==================================================== "
	    << std::endl << std::endl ;

  lcWrt->close() ;

  return 0 ;

}

<commit_msg>replace auto_ptr with unique_ptr in sthepjob_new<commit_after>
#include "lcio.h"

#include "IO/LCWriter.h"
#include "EVENT/LCIO.h"
#include "IMPL/LCEventImpl.h"
#include "IMPL/LCRunHeaderImpl.h"

#include "UTIL/LCStdHepRdrNew.h"

#include <cstdlib>
#include <iostream>
#include <sstream>
#include <memory>

// using namespace std ;
using namespace lcio ;

/** Simple test program to demonstrate reading of binary .stdhep generator files.
 *  Writes MCParticle collections to the outputfile stdhepjob.slcio.
 */

int main(int argc, char** argv ){

  if(argc < 4) {

     std::cout << " usage: stdhepjob infile.stdhep outfile.slcio maxEvt " <<  std::endl
	       << "   infile.stdhep    - input file name "  <<  std::endl
	       << "   outfile.slcio    - ouput file name "  <<  std::endl
	       << "   maxEvt           - max number of events to read [-1: all]"  <<  std::endl  ;

    return 1;
  }

  std::string inFile  = argv[1] ;
  std::string outFile = argv[2] ;
  int maxEvt = std::atoi( argv[3] ) ;

  std::cout << "==================================================== " << std::endl
	    << " stdhepjob : " << std::endl  ;

  // Open an instance of the StdHep Reader with the given filename
  LCStdHepRdrNew rdr( inFile.c_str()  ) ;

  std::cout << " opened file : " << inFile << std::endl ;

  rdr.printHeader() ;

  // create sio writer
  std::unique_ptr<LCWriter> lcWrt( LCFactory::getInstance()->createLCWriter() ) ;

  lcWrt->open( outFile )  ;

  std::unique_ptr<LCRunHeaderImpl> runHdr(  new LCRunHeaderImpl ) ;

  runHdr->setRunNumber( 0 ) ;

  std::string detName("Unknown")  ;
  runHdr->setDetectorName( detName ) ;

  std::stringstream description ;

  description << " file generated with LCIO stdhepjob from "  << inFile  ;

  runHdr->setDescription( description.str()  ) ;

  lcWrt->writeRunHeader( runHdr.get()  ) ;

  int count = 0;

  try {

    while( maxEvt < 0  || count < maxEvt ){

      std::unique_ptr<LCEventImpl> evt( new LCEventImpl() ) ;

      evt->setRunNumber(  0   ) ;
      evt->setEventNumber( count ) ;
      evt->setDetectorName( detName ) ;

      // read the next stdhep event and add an MCParticle collection to the event
      rdr.updateNextEvent( evt.get()  , "MCParticle" ) ;

      lcWrt->writeEvent( evt.get()  ) ;

      ++count ;

    } // evt loop
  }

  catch( IO::EndOfDataException& e ) {
  }

  std::cout << "  converted " << count << " events - written to LCIO " << outFile  << std::endl ;

  std::cout << "==================================================== "
	    << std::endl << std::endl ;

  lcWrt->close() ;

  return 0 ;

}

<|endoftext|>