<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    paraTkAppInit.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
/*
 * tkAppInit.c --
 *
 *      Provides a default version of the Tcl_AppInit procedure for
 *      use in wish and similar Tk-based applications.
 *
 * Copyright (c) 1993 The Regents of the University of California.
 * Copyright (c) 1994 Sun Microsystems, Inc.
 *
 * See the file "license.terms" for information on usage and redistribution
 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
 */

#include "vtkSystemIncludes.h"
#include "vtkToolkits.h"
#include "vtkMPIController.h"
#include "tk.h"

/*
 *----------------------------------------------------------------------
 *
 * main --
 *
 *      This is the main program for the application.
 *
 * Results:
 *      None: Tk_Main never returns here, so this procedure never
 *      returns either.
 *
 * Side effects:
 *      Whatever the application does.
 *
 *----------------------------------------------------------------------
 */
int
main(int argc, char **argv)
{
  ios::sync_with_stdio();
  vtkMPIController* controller = vtkMPIController::New();
  controller->Initialize(&argc, &argv);
  vtkMultiProcessController::SetGlobalController(controller);
  Tk_Main(argc, argv, Tcl_AppInit);
  controller->Delete();
  return 0;                     /* Needed only to prevent compiler warning. */
}

/*
 *----------------------------------------------------------------------
 *
 * Tcl_AppInit --
 *
 *      This procedure performs application-specific initialization.
 *      Most applications, especially those that incorporate additional
 *      packages, will have their own version of this procedure.
 *
 * Results:
 *      Returns a standard Tcl completion code, and leaves an error
 *      message in interp->result if an error occurs.
 *
 * Side effects:
 *      Depends on the startup script.
 *
 *----------------------------------------------------------------------
 */

extern "C" int Vtkcommontcl_Init(Tcl_Interp *interp);
extern "C" int Vtkfilteringtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkimagingtcl_Init(Tcl_Interp *interp);
extern "C" int Vtkgraphicstcl_Init(Tcl_Interp *interp);
extern "C" int Vtkiotcl_Init(Tcl_Interp *interp);

#ifdef VTK_USE_RENDERING
extern "C" int Vtkrenderingtcl_Init(Tcl_Interp *interp);
#ifdef VTK_USE_TKWIDGET
extern "C" int Vtktkrenderwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimageviewerwidget_Init(Tcl_Interp *interp);
extern "C" int Vtktkimagewindowwidget_Init(Tcl_Interp *interp);
#endif
#endif

#ifdef VTK_USE_PATENTED
extern "C" int Vtkpatentedtcl_Init(Tcl_Interp *interp);
#endif

#ifdef VTK_USE_HYBRID
extern "C" int Vtkhybridtcl_Init(Tcl_Interp *interp);
#endif

#ifdef VTK_USE_PARALLEL
extern "C" int Vtkparalleltcl_Init(Tcl_Interp *interp);
#endif

int Tcl_AppInit(Tcl_Interp *interp)
{
  if (Tcl_Init(interp) == TCL_ERROR) {
  return TCL_ERROR;
  }
  if (Tk_Init(interp) == TCL_ERROR) {
  return TCL_ERROR;
  }

  /* init the core vtk stuff */
  if (Vtkcommontcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtkfilteringtcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtkimagingtcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtkgraphicstcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtkiotcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }

#ifdef VTK_USE_RENDERING
  if (Vtkrenderingtcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
#ifdef VTK_USE_TKWIDGET
  if (Vtktkrenderwidget_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtktkimagewindowwidget_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
  if (Vtktkimageviewerwidget_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
#endif
#endif

#ifdef VTK_USE_PATENTED
  if (Vtkpatentedtcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
#endif

#ifdef VTK_USE_HYBRID
  if (Vtkhybridtcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
#endif

#ifdef VTK_USE_PARALLEL
  if (Vtkparalleltcl_Init(interp) == TCL_ERROR)
    {
    return TCL_ERROR;
    }
#endif

  /*
   * Specify a user-specific startup file to invoke if the application
   * is run interactively.  Typically the startup file is "~/.apprc"
   * where "app" is the name of the application.  If this line is deleted
   * then no user-specific startup file will be run under any conditions.
   */

#if (((TK_MAJOR_VERSION == 4)&&(TK_MINOR_VERSION >= 1))||((TK_MAJOR_VERSION == 8)&&(TK_MINOR_VERSION >= 0)))
  Tcl_SetVar(interp,
             (char *) "tcl_rcFileName",
             (char *) "~/.vtkrc",
             TCL_GLOBAL_ONLY);
#else
    tcl_RcFileName = (char *) "~/.vtkrc";
#endif
    return TCL_OK;
}

<commit_msg>ENH: Removing old file.  This functionality is now provided in Wrapping/Tcl/vtkParaTkAppInit.cxx.<commit_after><|endoftext|>


<commit_before>#include "Sound.hpp"

#include <iostream>

ppSound::ppSound(const char *name, ppFormat* audioFormat, int track, ppRandomizer* randomizer) : ppGenericSound(name){
	this->randomizer = randomizer;
	this->SetTrack(track);
	this->audioFormat = audioFormat;
	this->bufferSize = audioFormat->GetSampleRate()*2;
	this->nextReadPosition = 0;
	this->startReadPosition = 0;
	this->totalBufferProcessed = 0;
	alGenBuffers(2, this->bufferSet);
	alGenSources(1, &this->sourceID);
	this->SetPlayOrder(ppSoundPlayOrder::LOOP);
}

ppSound::~ppSound(){
	ppGenericSound::~ppGenericSound();
	alDeleteSources(1, &this->sourceID);
    alDeleteBuffers(2, this->bufferSet);
}

void ppSound::SetTrack(int track){
	if(track<1){
		#ifdef PPDEBUG
			throw std::runtime_error("Track number must be 1 or greater. (" + audioFormat->GetFileName() + ")");
		#else
			std::cout << "Track number must be 1 or greater. (" << audioFormat->GetFileName() << ")" << std::endl;
		#endif
		return;
	}
	this->track = track-1;
	this->loadingTrack = this->track;
}

void ppSound::SetPlayOrder(ppSoundPlayOrder playOrder){
	this->playOrder = playOrder;
	this->trackList.clear();
	if(this->playOrder == ppSoundPlayOrder::LOOP || this->playOrder == ppSoundPlayOrder::RANDOM){
		this->trackList.push_back(this->track);
	}else if(this->playOrder == ppSoundPlayOrder::SHUFFLE){
		std::list<int> sequencelist;
		for(int i=0;i<this->audioFormat->GetTotalTrack();i++){
			sequencelist.push_back((this->track+i)%this->audioFormat->GetTotalTrack());
		}
		while(!sequencelist.empty()){
			auto numit = sequencelist.begin();
			advance(numit, this->randomizer->NextInt(sequencelist.size()));
			this->trackList.push_back((this->track+(*numit))%this->audioFormat->GetTotalTrack());
			sequencelist.erase(numit);
		}
	}else if(this->playOrder == ppSoundPlayOrder::SEQUENCE){
		for(int i=0;i<this->audioFormat->GetTotalTrack();i++){
			this->trackList.push_back((this->track+i)%this->audioFormat->GetTotalTrack());
		}
	}
	this->GetNextTrack();
	this->track = this->loadingTrack;
}

ppSoundPlayOrder ppSound::GetPlayOrder(){
	return this->playOrder;
}

void ppSound::GetNextTrack(){
	if(this->track!=this->loadingTrack){
		return;
	}
	this->loadingTrack = this->trackList.front();
	this->trackList.pop_front();
	if(this->playOrder == ppSoundPlayOrder::RANDOM){
		this->loadingTrack = this->randomizer->NextInt(this->audioFormat->GetTotalTrack());
	}
	this->trackList.push_back(this->loadingTrack);
}

int ppSound::GetTotalBuffer(bool countCurrent){
	int bufferSize = this->bufferSize*this->audioFormat->GetTotalTrack();
	int totalBuffer = this->GetPositionLength()/bufferSize;
	if(countCurrent && this->GetPositionLength()%bufferSize > 0){
		totalBuffer++;
	}
	return totalBuffer;
}

void ppSound::SetClipStart(Sint64 clipping){
	clipping = this->audioFormat->RelativePosition(clipping);
	ppClippable::SetClipStart(clipping);
	this->nextReadPosition = this->clipStart;
}

void ppSound::SetClipEnd(Sint64 clipping){
	clipping = this->audioFormat->RelativePosition(clipping);
	ppClippable::SetClipEnd(clipping);
}

void ppSound::Preload(){
	// this->GetNextTrack();
	this->Stop();
	alSourceUnqueueBuffers(this->sourceID, 2, this->bufferSet);

	char *bufferData = new char[this->bufferSize];
	int totalBuffer = 0;
	while(totalBuffer<2){
		Sint64 sizeLeft = this->audioFormat->RelativePosition(this->GetPositionLength())-this->nextReadPosition+this->clipStart;
		if(this->bufferSize < sizeLeft){
			sizeLeft = this->bufferSize;
		}
		Sint64 size = this->audioFormat->Read(bufferData, this->nextReadPosition, sizeLeft, this->loadingTrack);
		this->nextReadPosition += size;
		alBufferData(this->bufferSet[totalBuffer], this->audioFormat->GetFormat(), bufferData, size, this->audioFormat->GetSampleRate());
		totalBuffer++;
		if(size<this->bufferSize){
			this->GetNextTrack();
			this->nextReadPosition = this->clipStart;
		}
	}
	delete[] bufferData;

	alSourceQueueBuffers(this->sourceID, 2, this->bufferSet);

	this->preload = true;
}

void ppSound::Update(){
	ppGenericSound::Update();
	ALint processedBuffer;
	alGetSourcei(this->sourceID, AL_BUFFERS_PROCESSED, &processedBuffer);
	char *bufferData = new char[this->bufferSize];
	while(processedBuffer>0 && !this->IsStop()){
		processedBuffer--;
		this->totalBufferProcessed++;
		ALuint bufferID;
		alSourceUnqueueBuffers(this->sourceID, 1, &bufferID);

		Sint64 sizeLeft = this->audioFormat->RelativePosition(this->GetPositionLength())-this->nextReadPosition+this->clipStart;
		if(this->bufferSize < sizeLeft){
			sizeLeft = this->bufferSize;
		}
		Sint64 size = this->audioFormat->Read(bufferData, this->nextReadPosition, sizeLeft, this->loadingTrack);
		this->nextReadPosition += size;
		alBufferData(bufferID, this->audioFormat->GetFormat(), bufferData, size, this->audioFormat->GetSampleRate());
		alSourceQueueBuffers(this->sourceID, 1, &bufferID);
		if(size<this->bufferSize){
			if(!this->IsAutoLoop() || this->loop == 0){
				break;
			}
			this->GetNextTrack();
			this->nextReadPosition = this->clipStart;
		}
	}
	if(this->GetCurrentPosition()>=this->GetPositionLength()||this->totalBufferProcessed>=this->GetTotalBuffer(true)){
		this->track = this->loadingTrack;
		if(this->loop == 0){
			this->nextReadPosition = this->clipStart;
			this->Stop();
		}else if(loop > 0){
			this->loop--;
		}
		this->totalBufferProcessed = 0;
		this->startReadPosition = 0;
		if(!this->IsAutoLoop()){
			this->Stop();
		}
	}
	delete[] bufferData;
}

void ppSound::StopDecay(bool decay){
	if(!this->isPlaying){
		return;
	}
	ppGenericSound::StopDecay(decay);
	alSourceStop(this->sourceID);
	alSourceUnqueueBuffers(this->sourceID, 2, this->bufferSet);

	this->track = this->loadingTrack;
	this->nextReadPosition = this->clipStart;
	this->totalBufferProcessed = 0;
	this->startReadPosition = 0;
	this->preload = false;
}

void ppSound::Play(){
	ALint sourceState;
	alGetSourcei(this->sourceID, AL_SOURCE_STATE, &sourceState);
	if(sourceState==AL_PLAYING){
		return;
	}
	if(!this->IsPause() && !this->preload){
		this->Preload();
	}
	ppGenericSound::Play();
	alSourcePlay(this->sourceID);
}

void ppSound::Pause(){
	if(this->IsPause()){
		return;
	}
	ppGenericSound::Pause();
	alSourcePause(this->sourceID);
}

void ppSound::Seek(Sint64 position){
	this->startReadPosition = position;
	this->nextReadPosition = this->clipStart+position;
	this->totalBufferProcessed = 0;
	this->Preload();
}

void ppSound::Seek(float time){
	this->Seek(this->audioFormat->RelativePosition(this->audioFormat->TimeToPosition(time)));
}

void ppSound::SetVolume(float volume){
	ppGenericSound::SetVolume(volume);
	alSourcef(this->sourceID, AL_GAIN, this->volume);
}

void ppSound::SetSpeed(float speed){
	ppGenericSound::SetSpeed(speed);
	alSourcef(this->sourceID, AL_PITCH, this->speed);
}

Sint64 ppSound::GetCurrentPosition(){
	int pos;
	alGetSourcei(this->sourceID, AL_BYTE_OFFSET, &pos);
	return this->audioFormat->ActualPosition(((this->totalBufferProcessed*this->bufferSize))+pos+this->startReadPosition);
}

Sint64 ppSound::GetPositionLength(){
	return this->audioFormat->GetPositionLength()-this->audioFormat->ActualPosition(this->clipStart+this->clipEnd);
}

float ppSound::GetCurrentTime(){
	return this->audioFormat->PositionToTime(this->GetCurrentPosition());
}

float ppSound::GetTotalTime(){
	return this->audioFormat->PositionToTime(this->GetPositionLength());
}

int ppSound::GetTrack(){
	return this->track+1;
}

ALuint ppSound::GetSourceID(){
	return this->sourceID;
}

void ppSound::Render(SDL_Renderer* renderer){
	ppControl::Render(renderer);
	if(!this->visible){
		return;
	}
	//Border
	glBegin(GL_LINE_LOOP);
	{
		glColor3f(1, 1, 1);
		glVertex3f(this->x, this->y, 0);
		glVertex3f(this->x+this->width, this->y, 0);
		glVertex3f(this->x+this->width, this->y+this->height, 0);
		glVertex3f(this->x, this->y+this->height, 0);
	}
	glEnd();
	//Playing Cursor
	glBegin(GL_LINES);
	{
		glColor3f(0.7f, 0.7f, 1);
		int offset = this->GetCurrentTime()*(this->width-2)/this->GetTotalTime();
		glVertex3f(this->x+offset, this->y+1, 0);
		glVertex3f(this->x+offset, this->y+this->height, 0);
	}
	glEnd();
	//Skipped position
	int skippedWidth = this->audioFormat->ActualPosition(this->startReadPosition)*(this->width-2)/this->GetPositionLength();
	glBegin(GL_QUADS);
	{
		glColor4f(1, 0.8f, 0.8f, 0.5f);
		glVertex3f(this->x, this->y+1, 0);
		glVertex3f(this->x+skippedWidth, this->y+1, 0);
		glVertex3f(this->x+skippedWidth, this->y+this->height, 0);
		glVertex3f(this->x, this->y+this->height, 0);
	}
	glEnd();
	//Total processed buffer
	glBegin(GL_QUADS);
	{
		glColor4f(0.8f, 0.8f, 1, 0.5f);
		int width = this->audioFormat->ActualPosition(this->totalBufferProcessed*this->bufferSize)*(this->width-2)/this->GetPositionLength();
		glVertex3f(this->x+skippedWidth, this->y+1, 0);
		glVertex3f(this->x+skippedWidth+width, this->y+1, 0);
		glVertex3f(this->x+skippedWidth+width, this->y+this->height, 0);
		glVertex3f(this->x+skippedWidth, this->y+this->height, 0);
	}
	glEnd();
	//Next read position
	glBegin(GL_LINE_STRIP);
	{
		glColor3f(1, 1, 1);
		int offset = this->audioFormat->ActualPosition(this->nextReadPosition-this->clipStart)*(this->width-2)/this->GetPositionLength();
		glVertex3f(this->x+offset-3, this->y+4, 0);
		glVertex3f(this->x+offset, this->y+1, 0);
		glVertex3f(this->x+offset+3, this->y+4, 0);
	}
	glEnd();
}

void ppSound::Update(ppInput* input){
	ppControl::Update(input);
}

ppControlType ppSound::GetType(){
	return ppControlType::SOUND_CONTROL;
}
<commit_msg>Fix sound did not random on autoloop<commit_after>#include "Sound.hpp"

#include <iostream>

ppSound::ppSound(const char *name, ppFormat* audioFormat, int track, ppRandomizer* randomizer) : ppGenericSound(name){
	this->randomizer = randomizer;
	this->SetTrack(track);
	this->audioFormat = audioFormat;
	this->bufferSize = audioFormat->GetSampleRate()*2;
	this->nextReadPosition = 0;
	this->startReadPosition = 0;
	this->totalBufferProcessed = 0;
	alGenBuffers(2, this->bufferSet);
	alGenSources(1, &this->sourceID);
	this->SetPlayOrder(ppSoundPlayOrder::LOOP);
}

ppSound::~ppSound(){
	ppGenericSound::~ppGenericSound();
	alDeleteSources(1, &this->sourceID);
    alDeleteBuffers(2, this->bufferSet);
}

void ppSound::SetTrack(int track){
	if(track<1){
		#ifdef PPDEBUG
			throw std::runtime_error("Track number must be 1 or greater. (" + audioFormat->GetFileName() + ")");
		#else
			std::cout << "Track number must be 1 or greater. (" << audioFormat->GetFileName() << ")" << std::endl;
		#endif
		return;
	}
	this->track = track-1;
	this->loadingTrack = this->track;
}

void ppSound::SetPlayOrder(ppSoundPlayOrder playOrder){
	this->playOrder = playOrder;
	this->trackList.clear();
	if(this->playOrder == ppSoundPlayOrder::LOOP || this->playOrder == ppSoundPlayOrder::RANDOM){
		this->trackList.push_back(this->track);
	}else if(this->playOrder == ppSoundPlayOrder::SHUFFLE){
		std::list<int> sequencelist;
		for(int i=0;i<this->audioFormat->GetTotalTrack();i++){
			sequencelist.push_back((this->track+i)%this->audioFormat->GetTotalTrack());
		}
		while(!sequencelist.empty()){
			auto numit = sequencelist.begin();
			advance(numit, this->randomizer->NextInt(sequencelist.size()));
			this->trackList.push_back((this->track+(*numit))%this->audioFormat->GetTotalTrack());
			sequencelist.erase(numit);
		}
	}else if(this->playOrder == ppSoundPlayOrder::SEQUENCE){
		for(int i=0;i<this->audioFormat->GetTotalTrack();i++){
			this->trackList.push_back((this->track+i)%this->audioFormat->GetTotalTrack());
		}
	}
	this->GetNextTrack();
	this->track = this->loadingTrack;
}

ppSoundPlayOrder ppSound::GetPlayOrder(){
	return this->playOrder;
}

void ppSound::GetNextTrack(){
	if(this->track!=this->loadingTrack){
		return;
	}
	this->loadingTrack = this->trackList.front();
	this->trackList.pop_front();
	if(this->playOrder == ppSoundPlayOrder::RANDOM){
		this->loadingTrack = this->randomizer->NextInt(this->audioFormat->GetTotalTrack());
	}
	this->trackList.push_back(this->loadingTrack);
}

int ppSound::GetTotalBuffer(bool countCurrent){
	int bufferSize = this->bufferSize*this->audioFormat->GetTotalTrack();
	int totalBuffer = this->GetPositionLength()/bufferSize;
	if(countCurrent && this->GetPositionLength()%bufferSize > 0){
		totalBuffer++;
	}
	return totalBuffer;
}

void ppSound::SetClipStart(Sint64 clipping){
	clipping = this->audioFormat->RelativePosition(clipping);
	ppClippable::SetClipStart(clipping);
	this->nextReadPosition = this->clipStart;
}

void ppSound::SetClipEnd(Sint64 clipping){
	clipping = this->audioFormat->RelativePosition(clipping);
	ppClippable::SetClipEnd(clipping);
}

void ppSound::Preload(){
	// this->GetNextTrack();
	this->Stop();
	alSourceUnqueueBuffers(this->sourceID, 2, this->bufferSet);

	char *bufferData = new char[this->bufferSize];
	int totalBuffer = 0;
	while(totalBuffer<2){
		Sint64 sizeLeft = this->audioFormat->RelativePosition(this->GetPositionLength())-this->nextReadPosition+this->clipStart;
		if(this->bufferSize < sizeLeft){
			sizeLeft = this->bufferSize;
		}
		Sint64 size = this->audioFormat->Read(bufferData, this->nextReadPosition, sizeLeft, this->loadingTrack);
		this->nextReadPosition += size;
		alBufferData(this->bufferSet[totalBuffer], this->audioFormat->GetFormat(), bufferData, size, this->audioFormat->GetSampleRate());
		totalBuffer++;
		if(size<this->bufferSize){
			this->GetNextTrack();
			this->nextReadPosition = this->clipStart;
		}
	}
	delete[] bufferData;

	alSourceQueueBuffers(this->sourceID, 2, this->bufferSet);

	this->preload = true;
}

void ppSound::Update(){
	ppGenericSound::Update();
	ALint processedBuffer;
	alGetSourcei(this->sourceID, AL_BUFFERS_PROCESSED, &processedBuffer);
	char *bufferData = new char[this->bufferSize];
	while(processedBuffer>0 && !this->IsStop()){
		processedBuffer--;
		this->totalBufferProcessed++;
		ALuint bufferID;
		alSourceUnqueueBuffers(this->sourceID, 1, &bufferID);

		Sint64 sizeLeft = this->audioFormat->RelativePosition(this->GetPositionLength())-this->nextReadPosition+this->clipStart;
		if(this->bufferSize < sizeLeft){
			sizeLeft = this->bufferSize;
		}
		Sint64 size = this->audioFormat->Read(bufferData, this->nextReadPosition, sizeLeft, this->loadingTrack);
		this->nextReadPosition += size;
		alBufferData(bufferID, this->audioFormat->GetFormat(), bufferData, size, this->audioFormat->GetSampleRate());
		alSourceQueueBuffers(this->sourceID, 1, &bufferID);
		if(size<this->bufferSize){
			this->GetNextTrack();
			if(!this->IsAutoLoop() || this->loop == 0){
				break;
			}
			this->nextReadPosition = this->clipStart;
		}
	}
	if(this->GetCurrentPosition()>=this->GetPositionLength()||this->totalBufferProcessed>=this->GetTotalBuffer(true)){
		this->track = this->loadingTrack;
		if(this->loop == 0){
			this->nextReadPosition = this->clipStart;
			this->Stop();
		}else if(loop > 0){
			this->loop--;
		}
		this->totalBufferProcessed = 0;
		this->startReadPosition = 0;
		if(!this->IsAutoLoop()){
			this->Stop();
		}
	}
	delete[] bufferData;
}

void ppSound::StopDecay(bool decay){
	if(!this->isPlaying){
		return;
	}
	ppGenericSound::StopDecay(decay);
	alSourceStop(this->sourceID);
	alSourceUnqueueBuffers(this->sourceID, 2, this->bufferSet);

	this->track = this->loadingTrack;
	this->nextReadPosition = this->clipStart;
	this->totalBufferProcessed = 0;
	this->startReadPosition = 0;
	this->preload = false;
}

void ppSound::Play(){
	ALint sourceState;
	alGetSourcei(this->sourceID, AL_SOURCE_STATE, &sourceState);
	if(sourceState==AL_PLAYING){
		return;
	}
	if(!this->IsPause() && !this->preload){
		this->Preload();
	}
	ppGenericSound::Play();
	alSourcePlay(this->sourceID);
}

void ppSound::Pause(){
	if(this->IsPause()){
		return;
	}
	ppGenericSound::Pause();
	alSourcePause(this->sourceID);
}

void ppSound::Seek(Sint64 position){
	this->startReadPosition = position;
	this->nextReadPosition = this->clipStart+position;
	this->totalBufferProcessed = 0;
	this->Preload();
}

void ppSound::Seek(float time){
	this->Seek(this->audioFormat->RelativePosition(this->audioFormat->TimeToPosition(time)));
}

void ppSound::SetVolume(float volume){
	ppGenericSound::SetVolume(volume);
	alSourcef(this->sourceID, AL_GAIN, this->volume);
}

void ppSound::SetSpeed(float speed){
	ppGenericSound::SetSpeed(speed);
	alSourcef(this->sourceID, AL_PITCH, this->speed);
}

Sint64 ppSound::GetCurrentPosition(){
	int pos;
	alGetSourcei(this->sourceID, AL_BYTE_OFFSET, &pos);
	return this->audioFormat->ActualPosition(((this->totalBufferProcessed*this->bufferSize))+pos+this->startReadPosition);
}

Sint64 ppSound::GetPositionLength(){
	return this->audioFormat->GetPositionLength()-this->audioFormat->ActualPosition(this->clipStart+this->clipEnd);
}

float ppSound::GetCurrentTime(){
	return this->audioFormat->PositionToTime(this->GetCurrentPosition());
}

float ppSound::GetTotalTime(){
	return this->audioFormat->PositionToTime(this->GetPositionLength());
}

int ppSound::GetTrack(){
	return this->track+1;
}

ALuint ppSound::GetSourceID(){
	return this->sourceID;
}

void ppSound::Render(SDL_Renderer* renderer){
	ppControl::Render(renderer);
	if(!this->visible){
		return;
	}
	//Border
	glBegin(GL_LINE_LOOP);
	{
		glColor3f(1, 1, 1);
		glVertex3f(this->x, this->y, 0);
		glVertex3f(this->x+this->width, this->y, 0);
		glVertex3f(this->x+this->width, this->y+this->height, 0);
		glVertex3f(this->x, this->y+this->height, 0);
	}
	glEnd();
	//Playing Cursor
	glBegin(GL_LINES);
	{
		glColor3f(0.7f, 0.7f, 1);
		int offset = this->GetCurrentTime()*(this->width-2)/this->GetTotalTime();
		glVertex3f(this->x+offset, this->y+1, 0);
		glVertex3f(this->x+offset, this->y+this->height, 0);
	}
	glEnd();
	//Skipped position
	int skippedWidth = this->audioFormat->ActualPosition(this->startReadPosition)*(this->width-2)/this->GetPositionLength();
	glBegin(GL_QUADS);
	{
		glColor4f(1, 0.8f, 0.8f, 0.5f);
		glVertex3f(this->x, this->y+1, 0);
		glVertex3f(this->x+skippedWidth, this->y+1, 0);
		glVertex3f(this->x+skippedWidth, this->y+this->height, 0);
		glVertex3f(this->x, this->y+this->height, 0);
	}
	glEnd();
	//Total processed buffer
	glBegin(GL_QUADS);
	{
		glColor4f(0.8f, 0.8f, 1, 0.5f);
		int width = this->audioFormat->ActualPosition(this->totalBufferProcessed*this->bufferSize)*(this->width-2)/this->GetPositionLength();
		glVertex3f(this->x+skippedWidth, this->y+1, 0);
		glVertex3f(this->x+skippedWidth+width, this->y+1, 0);
		glVertex3f(this->x+skippedWidth+width, this->y+this->height, 0);
		glVertex3f(this->x+skippedWidth, this->y+this->height, 0);
	}
	glEnd();
	//Next read position
	glBegin(GL_LINE_STRIP);
	{
		glColor3f(1, 1, 1);
		int offset = this->audioFormat->ActualPosition(this->nextReadPosition-this->clipStart)*(this->width-2)/this->GetPositionLength();
		glVertex3f(this->x+offset-3, this->y+4, 0);
		glVertex3f(this->x+offset, this->y+1, 0);
		glVertex3f(this->x+offset+3, this->y+4, 0);
	}
	glEnd();
}

void ppSound::Update(ppInput* input){
	ppControl::Update(input);
}

ppControlType ppSound::GetType(){
	return ppControlType::SOUND_CONTROL;
}
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2010 Eduard Burtescu
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <usb/Usb.h>
#include <usb/UsbDevice.h>
#include <usb/UsbHub.h>
#include <processor/Processor.h>
#include <utilities/PointerGuard.h>

#define delay(n) do{Semaphore semWAIT(0);semWAIT.acquire(1, 0, n*1000);}while(0)

ssize_t UsbDevice::doSync(UsbDevice::Endpoint *pEndpoint, UsbPid pid, uintptr_t pBuffer, size_t nBytes)
{
    if(!pEndpoint)
    {
        ERROR("USB: UsbDevice::doSync called with invalid endpoint");
        return -1;
    }

    UsbHub *pParentHub = dynamic_cast<UsbHub*>(m_pParent);
    if(!pParentHub)
    {
        ERROR("USB: Orphaned UsbDevice!");
        return -1;
    }

    UsbEndpoint endpointInfo(m_nAddress, m_nPort, pEndpoint->nEndpoint, m_Speed, pEndpoint->nMaxPacketSize);
    uintptr_t nTransaction = pParentHub->createTransaction(endpointInfo);
    if(nTransaction == static_cast<uintptr_t>(-1))
    {
        ERROR("UsbDevice: couldn't get a valid transaction to work with from the parent hub");
        return -1;
    }

    pParentHub->addTransferToTransaction(nTransaction, pEndpoint->bDataToggle, pid, pBuffer, nBytes);
    /*if(nBytes > pEndpoint->nMaxPacketSize)
    {
        for(size_t i=0;i<nBytes;)
        {
            ssize_t nResult = pParentHub->doSync(endpointInfo, UsbPidIn, pBuffer+i, (nBytes-i)<pEndpoint->nMaxPacketSize?(nBytes-i):pEndpoint->nMaxPacketSize);
            if(nResult < 0)
                return nResult;
            i += nResult;
            pEndpoint->bDataToggle = !pEndpoint->bDataToggle;
        }
        return nBytes;
    }*/

    //ssize_t nResult = pParentHub->doSync(endpointInfo, nPid, pBuffer, nBytes);
    ssize_t nResult = pParentHub->doSync(nTransaction);
    pEndpoint->bDataToggle = !pEndpoint->bDataToggle;
    return nResult;
}

ssize_t UsbDevice::syncSetup(Setup *setup)
{
    return doSync(m_pEndpoints[0], UsbPidSetup, reinterpret_cast<uintptr_t>(setup), sizeof(Setup));
}

ssize_t UsbDevice::syncIn(uint8_t nEndpoint, uintptr_t pBuffer, size_t nBytes)
{
    return doSync(m_pEndpoints[nEndpoint], UsbPidIn, pBuffer, nBytes);
}

ssize_t UsbDevice::syncOut(uint8_t nEndpoint, uintptr_t pBuffer, size_t nBytes)
{
    return doSync(m_pEndpoints[nEndpoint], UsbPidOut, pBuffer, nBytes);
}

ssize_t UsbDevice::controlRequest(uint8_t nRequestType, uint8_t nRequest, uint16_t nValue, uint16_t nIndex, uint16_t nLength, uintptr_t pBuffer)
{
    // Setup structure - holds request details
    Setup *pSetup = new Setup(nRequestType, nRequest, nValue, nIndex, nLength);
    PointerGuard<Setup> guard(pSetup);

    UsbHub *pParentHub = dynamic_cast<UsbHub*>(m_pParent);
    if(!pParentHub)
    {
        ERROR("USB: Orphaned UsbDevice!");
        return -1;
    }

    UsbEndpoint endpointInfo(m_nAddress, m_nPort, 0, m_Speed, 64);

    uintptr_t nTransaction = pParentHub->createTransaction(endpointInfo);
    if(nTransaction == static_cast<uintptr_t>(-1))
    {
        ERROR("UsbDevice: couldn't get a valid transaction to work with from the parent hub");
        return -1;
    }

    // Setup Transfer - handles the SETUP phase of the transfer
    pParentHub->addTransferToTransaction(nTransaction, false, UsbPidSetup, reinterpret_cast<uintptr_t>(pSetup), sizeof(Setup));

    // Data Transfer - handles data transfer
    if(nLength)
        pParentHub->addTransferToTransaction(nTransaction, true, nRequestType & 0x80 ? UsbPidIn : UsbPidOut, pBuffer, nLength);

    // Handshake Transfer - IN when we send data to the device, OUT when we receive. Zero-length.
    pParentHub->addTransferToTransaction(nTransaction, true, nRequestType & 0x80 ? UsbPidOut : UsbPidIn, 0, 0);

    // Wait for the transaction to complete, return result
    return pParentHub->doSync(nTransaction);
}

int16_t UsbDevice::status()
{
    uint16_t nStatus;
    ssize_t nResult = controlRequest(0x80, 0, 0, 0, 2, reinterpret_cast<uintptr_t>(&nStatus));
    if(nResult < 0)
        return nResult;
    return nStatus;
}

bool UsbDevice::assignAddress(uint8_t nAddress)
{
    if(controlRequest(0, 5, nAddress, 0) < 0)
        return false;
    m_nAddress = nAddress;
    return true;
}

bool UsbDevice::useConfiguration(uint8_t nConfig)
{
    m_pConfiguration = m_pDescriptor->pConfigurations[nConfig];
    return !controlRequest(0, 9, m_pConfiguration->pDescriptor->nConfig, 0);
}

bool UsbDevice::useInterface(uint8_t nInterface)
{
    m_pInterface = m_pConfiguration->pInterfaces[nInterface];
    // Gathering endpoints
    for(size_t i = 0;i<m_pInterface->pEndpoints.count();i++)
    {
        Endpoint *pEndpoint = m_pInterface->pEndpoints[i];
        if(!m_pEndpoints[pEndpoint->nEndpoint])
            m_pEndpoints[pEndpoint->nEndpoint] = pEndpoint;
        else
        {
            // Found a multiple-purpose endpoint
            Endpoint *pOldEndpoint = m_pEndpoints[pEndpoint->nEndpoint];
            Endpoint *pNewEndpoint = new Endpoint(pOldEndpoint);
            // In case our previous endpoint was obtained from two endpoints,
            // delete it. Strange, but can happen
            if(!pOldEndpoint->pDescriptor)
                delete pOldEndpoint;
            pNewEndpoint->bIn = pNewEndpoint->bIn || pEndpoint->bIn;
            pNewEndpoint->bOut = pNewEndpoint->bOut || pEndpoint->bOut;
            pNewEndpoint->nMaxPacketSize = pNewEndpoint->nMaxPacketSize < pEndpoint->nMaxPacketSize?pNewEndpoint->nMaxPacketSize:pEndpoint->nMaxPacketSize;
            m_pEndpoints[pEndpoint->nEndpoint] = pNewEndpoint;
        }
    }
    return true;
    //return !controlRequest(0, 9, m_pConfiguration->pDescriptor->nConfig, 0);
}

void *UsbDevice::getDescriptor(uint8_t nDescriptor, uint8_t nSubDescriptor, uint16_t nBytes, uint8_t requestType)
{
    uint8_t *pBuffer = new uint8_t[nBytes];
    uint16_t nIndex = requestType & RequestRecipient::Interface?m_pInterface->pDescriptor->nInterface:0;

    /// \todo Proper language ID handling!
    if(nDescriptor == 3)
        nIndex = 0x0409; // English (US)

    if(controlRequest(0x80|requestType, 6, nDescriptor<<8|nSubDescriptor, nIndex, nBytes, reinterpret_cast<uintptr_t>(pBuffer)) < 0)
    {
        delete [] pBuffer;
        return 0;
    }
    return pBuffer;
}

uint8_t UsbDevice::getDescriptorLength(uint8_t nDescriptor, uint8_t nSubDescriptor, uint8_t requestType)
{
    uint8_t pLength;
    uint16_t nIndex = requestType & RequestRecipient::Interface?m_pInterface->pDescriptor->nInterface:0;

    /// \todo Proper language ID handling
    if(nDescriptor == 3)
        nIndex = 0x0409; // English (US)

    if(controlRequest(0x80|requestType, 6, nDescriptor<<8|nSubDescriptor, nIndex, 1, reinterpret_cast<uintptr_t>(&pLength)) < 0)
        return 0;
    return pLength;
}

char *UsbDevice::getString(uint8_t nString)
{
    if(!nString)
    {
        char *pString = new char[1];
        pString[0] = '\0';
        return pString;
    }

    // Get string information!
    uint8_t infoLength = getDescriptorLength(3, 0);
    char *pData = static_cast<char*>(getDescriptor(3, 0, infoLength));
    for(uint8_t i = 0; i < infoLength; i++)
    {
        NOTICE("pData[" << Dec << i << Hex << "] = " << static_cast<uint32_t>(pData[i]));
    }

    uint8_t descriptorLength = getDescriptorLength(3, nString);
    char *pBuffer = static_cast<char*>(getDescriptor(3, nString, descriptorLength));
    if(pBuffer)
    {
        size_t nStrLength = (descriptorLength - 2) / 2;
        char *pString = new char[nStrLength+1];
        for(size_t i=0;i<nStrLength;i++)
            pString[i] = pBuffer[2+i*2];
        pString[nStrLength] = 0;
        delete pBuffer;
        return pString;
    }
    return 0;
}

void UsbDevice::populateDescriptors()
{
    m_pDescriptor = new DeviceDescriptor(getDescriptor(1, 0, getDescriptorLength(1, 0)));
	if(!m_pDescriptor)
		return; /// \todo Better error handling

	// Debug dump of the device descriptor
	DEBUG_LOG("USB version: " << Dec << (m_pDescriptor->pDescriptor->nBcdUsbRelease >> 8) << "." << (m_pDescriptor->pDescriptor->nBcdUsbRelease & 0xFF) << ".");
	DEBUG_LOG("Device class/subclass/protocol: " << m_pDescriptor->pDescriptor->nClass << "/" << m_pDescriptor->pDescriptor->nSubclass << "/" << m_pDescriptor->pDescriptor->nProtocol);
	DEBUG_LOG("Maximum control packet size is " << Dec << m_pDescriptor->pDescriptor->nMaxPacketSize << Hex << " bytes.");
	DEBUG_LOG("Vendor and product IDs: " << m_pDescriptor->pDescriptor->nVendorId << ":" << m_pDescriptor->pDescriptor->nProductId << ".");
	DEBUG_LOG("Device version: " << Dec << (m_pDescriptor->pDescriptor->nBcdDeviceRelease >> 8) << "." << (m_pDescriptor->pDescriptor->nBcdDeviceRelease & 0xFF) << ".");
	DEBUG_LOG("Device has " << Dec << m_pDescriptor->pDescriptor->nConfigurations << Hex << " configurations");

	if(m_pDescriptor->pDescriptor->nVendorString)
	    m_pDescriptor->sVendor = getString(m_pDescriptor->pDescriptor->nVendorString);
	else
		m_pDescriptor->sVendor = "";
	if(m_pDescriptor->pDescriptor->nProductString)
		m_pDescriptor->sProduct = getString(m_pDescriptor->pDescriptor->nProductString);
	else
		m_pDescriptor->sProduct = "";
	if(m_pDescriptor->pDescriptor->nSerialString)
		m_pDescriptor->sSerial = getString(m_pDescriptor->pDescriptor->nSerialString);
	else
		m_pDescriptor->sSerial = "";
    for(size_t i = 0;i < m_pDescriptor->pDescriptor->nConfigurations;i++)
    {
        uint16_t *pPartialConfig = static_cast<uint16_t*>(getDescriptor(2, i, 4));
        uint16_t configLength = pPartialConfig[1];
        delete pPartialConfig;
        ConfigDescriptor *pConfig = new ConfigDescriptor(getDescriptor(2, i, configLength), configLength);
        pConfig->sString = getString(pConfig->pDescriptor->nString);
        for(size_t j = 0;j < pConfig->pInterfaces.count();j++)
        {
            Interface *pInterface = pConfig->pInterfaces[j];
            pInterface->sString = getString(pInterface->pDescriptor->nString);
        }
        m_pDescriptor->pConfigurations.pushBack(pConfig);
    }
}
<commit_msg>Fix tabs in UsbDevice.cc<commit_after>/*
 * Copyright (c) 2010 Eduard Burtescu
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <usb/Usb.h>
#include <usb/UsbDevice.h>
#include <usb/UsbHub.h>
#include <processor/Processor.h>
#include <utilities/PointerGuard.h>

#define delay(n) do{Semaphore semWAIT(0);semWAIT.acquire(1, 0, n*1000);}while(0)

ssize_t UsbDevice::doSync(UsbDevice::Endpoint *pEndpoint, UsbPid pid, uintptr_t pBuffer, size_t nBytes)
{
    if(!pEndpoint)
    {
        ERROR("USB: UsbDevice::doSync called with invalid endpoint");
        return -1;
    }

    UsbHub *pParentHub = dynamic_cast<UsbHub*>(m_pParent);
    if(!pParentHub)
    {
        ERROR("USB: Orphaned UsbDevice!");
        return -1;
    }

    UsbEndpoint endpointInfo(m_nAddress, m_nPort, pEndpoint->nEndpoint, m_Speed, pEndpoint->nMaxPacketSize);
    uintptr_t nTransaction = pParentHub->createTransaction(endpointInfo);
    if(nTransaction == static_cast<uintptr_t>(-1))
    {
        ERROR("UsbDevice: couldn't get a valid transaction to work with from the parent hub");
        return -1;
    }

    pParentHub->addTransferToTransaction(nTransaction, pEndpoint->bDataToggle, pid, pBuffer, nBytes);
    /*if(nBytes > pEndpoint->nMaxPacketSize)
    {
        for(size_t i=0;i<nBytes;)
        {
            ssize_t nResult = pParentHub->doSync(endpointInfo, UsbPidIn, pBuffer+i, (nBytes-i)<pEndpoint->nMaxPacketSize?(nBytes-i):pEndpoint->nMaxPacketSize);
            if(nResult < 0)
                return nResult;
            i += nResult;
            pEndpoint->bDataToggle = !pEndpoint->bDataToggle;
        }
        return nBytes;
    }*/

    //ssize_t nResult = pParentHub->doSync(endpointInfo, nPid, pBuffer, nBytes);
    ssize_t nResult = pParentHub->doSync(nTransaction);
    pEndpoint->bDataToggle = !pEndpoint->bDataToggle;
    return nResult;
}

ssize_t UsbDevice::syncSetup(Setup *setup)
{
    return doSync(m_pEndpoints[0], UsbPidSetup, reinterpret_cast<uintptr_t>(setup), sizeof(Setup));
}

ssize_t UsbDevice::syncIn(uint8_t nEndpoint, uintptr_t pBuffer, size_t nBytes)
{
    return doSync(m_pEndpoints[nEndpoint], UsbPidIn, pBuffer, nBytes);
}

ssize_t UsbDevice::syncOut(uint8_t nEndpoint, uintptr_t pBuffer, size_t nBytes)
{
    return doSync(m_pEndpoints[nEndpoint], UsbPidOut, pBuffer, nBytes);
}

ssize_t UsbDevice::controlRequest(uint8_t nRequestType, uint8_t nRequest, uint16_t nValue, uint16_t nIndex, uint16_t nLength, uintptr_t pBuffer)
{
    // Setup structure - holds request details
    Setup *pSetup = new Setup(nRequestType, nRequest, nValue, nIndex, nLength);
    PointerGuard<Setup> guard(pSetup);

    UsbHub *pParentHub = dynamic_cast<UsbHub*>(m_pParent);
    if(!pParentHub)
    {
        ERROR("USB: Orphaned UsbDevice!");
        return -1;
    }

    UsbEndpoint endpointInfo(m_nAddress, m_nPort, 0, m_Speed, 64);

    uintptr_t nTransaction = pParentHub->createTransaction(endpointInfo);
    if(nTransaction == static_cast<uintptr_t>(-1))
    {
        ERROR("UsbDevice: couldn't get a valid transaction to work with from the parent hub");
        return -1;
    }

    // Setup Transfer - handles the SETUP phase of the transfer
    pParentHub->addTransferToTransaction(nTransaction, false, UsbPidSetup, reinterpret_cast<uintptr_t>(pSetup), sizeof(Setup));

    // Data Transfer - handles data transfer
    if(nLength)
        pParentHub->addTransferToTransaction(nTransaction, true, nRequestType & 0x80 ? UsbPidIn : UsbPidOut, pBuffer, nLength);

    // Handshake Transfer - IN when we send data to the device, OUT when we receive. Zero-length.
    pParentHub->addTransferToTransaction(nTransaction, true, nRequestType & 0x80 ? UsbPidOut : UsbPidIn, 0, 0);

    // Wait for the transaction to complete, return result
    return pParentHub->doSync(nTransaction);
}

int16_t UsbDevice::status()
{
    uint16_t nStatus;
    ssize_t nResult = controlRequest(0x80, 0, 0, 0, 2, reinterpret_cast<uintptr_t>(&nStatus));
    if(nResult < 0)
        return nResult;
    return nStatus;
}

bool UsbDevice::assignAddress(uint8_t nAddress)
{
    if(controlRequest(0, 5, nAddress, 0) < 0)
        return false;
    m_nAddress = nAddress;
    return true;
}

bool UsbDevice::useConfiguration(uint8_t nConfig)
{
    m_pConfiguration = m_pDescriptor->pConfigurations[nConfig];
    return !controlRequest(0, 9, m_pConfiguration->pDescriptor->nConfig, 0);
}

bool UsbDevice::useInterface(uint8_t nInterface)
{
    m_pInterface = m_pConfiguration->pInterfaces[nInterface];
    // Gathering endpoints
    for(size_t i = 0;i<m_pInterface->pEndpoints.count();i++)
    {
        Endpoint *pEndpoint = m_pInterface->pEndpoints[i];
        if(!m_pEndpoints[pEndpoint->nEndpoint])
            m_pEndpoints[pEndpoint->nEndpoint] = pEndpoint;
        else
        {
            // Found a multiple-purpose endpoint
            Endpoint *pOldEndpoint = m_pEndpoints[pEndpoint->nEndpoint];
            Endpoint *pNewEndpoint = new Endpoint(pOldEndpoint);
            // In case our previous endpoint was obtained from two endpoints,
            // delete it. Strange, but can happen
            if(!pOldEndpoint->pDescriptor)
                delete pOldEndpoint;
            pNewEndpoint->bIn = pNewEndpoint->bIn || pEndpoint->bIn;
            pNewEndpoint->bOut = pNewEndpoint->bOut || pEndpoint->bOut;
            pNewEndpoint->nMaxPacketSize = pNewEndpoint->nMaxPacketSize < pEndpoint->nMaxPacketSize?pNewEndpoint->nMaxPacketSize:pEndpoint->nMaxPacketSize;
            m_pEndpoints[pEndpoint->nEndpoint] = pNewEndpoint;
        }
    }
    return true;
    //return !controlRequest(0, 9, m_pConfiguration->pDescriptor->nConfig, 0);
}

void *UsbDevice::getDescriptor(uint8_t nDescriptor, uint8_t nSubDescriptor, uint16_t nBytes, uint8_t requestType)
{
    uint8_t *pBuffer = new uint8_t[nBytes];
    uint16_t nIndex = requestType & RequestRecipient::Interface?m_pInterface->pDescriptor->nInterface:0;

    /// \todo Proper language ID handling!
    if(nDescriptor == 3)
        nIndex = 0x0409; // English (US)

    if(controlRequest(0x80|requestType, 6, nDescriptor<<8|nSubDescriptor, nIndex, nBytes, reinterpret_cast<uintptr_t>(pBuffer)) < 0)
    {
        delete [] pBuffer;
        return 0;
    }
    return pBuffer;
}

uint8_t UsbDevice::getDescriptorLength(uint8_t nDescriptor, uint8_t nSubDescriptor, uint8_t requestType)
{
    uint8_t pLength;
    uint16_t nIndex = requestType & RequestRecipient::Interface?m_pInterface->pDescriptor->nInterface:0;

    /// \todo Proper language ID handling
    if(nDescriptor == 3)
        nIndex = 0x0409; // English (US)

    if(controlRequest(0x80|requestType, 6, nDescriptor<<8|nSubDescriptor, nIndex, 1, reinterpret_cast<uintptr_t>(&pLength)) < 0)
        return 0;
    return pLength;
}

char *UsbDevice::getString(uint8_t nString)
{
    if(!nString)
    {
        char *pString = new char[1];
        pString[0] = '\0';
        return pString;
    }

    // Get string information!
    uint8_t infoLength = getDescriptorLength(3, 0);
    char *pData = static_cast<char*>(getDescriptor(3, 0, infoLength));
    for(uint8_t i = 0; i < infoLength; i++)
    {
        NOTICE("pData[" << Dec << i << Hex << "] = " << static_cast<uint32_t>(pData[i]));
    }

    uint8_t descriptorLength = getDescriptorLength(3, nString);
    char *pBuffer = static_cast<char*>(getDescriptor(3, nString, descriptorLength));
    if(pBuffer)
    {
        size_t nStrLength = (descriptorLength - 2) / 2;
        char *pString = new char[nStrLength+1];
        for(size_t i=0;i<nStrLength;i++)
            pString[i] = pBuffer[2+i*2];
        pString[nStrLength] = 0;
        delete pBuffer;
        return pString;
    }
    return 0;
}

void UsbDevice::populateDescriptors()
{
    m_pDescriptor = new DeviceDescriptor(getDescriptor(1, 0, getDescriptorLength(1, 0)));
    if(!m_pDescriptor)
        return; /// \todo Better error handling

    // Debug dump of the device descriptor
    DEBUG_LOG("USB version: " << Dec << (m_pDescriptor->pDescriptor->nBcdUsbRelease >> 8) << "." << (m_pDescriptor->pDescriptor->nBcdUsbRelease & 0xFF) << ".");
    DEBUG_LOG("Device class/subclass/protocol: " << m_pDescriptor->pDescriptor->nClass << "/" << m_pDescriptor->pDescriptor->nSubclass << "/" << m_pDescriptor->pDescriptor->nProtocol);
    DEBUG_LOG("Maximum control packet size is " << Dec << m_pDescriptor->pDescriptor->nMaxPacketSize << Hex << " bytes.");
    DEBUG_LOG("Vendor and product IDs: " << m_pDescriptor->pDescriptor->nVendorId << ":" << m_pDescriptor->pDescriptor->nProductId << ".");
    DEBUG_LOG("Device version: " << Dec << (m_pDescriptor->pDescriptor->nBcdDeviceRelease >> 8) << "." << (m_pDescriptor->pDescriptor->nBcdDeviceRelease & 0xFF) << ".");
    DEBUG_LOG("Device has " << Dec << m_pDescriptor->pDescriptor->nConfigurations << Hex << " configurations");

    if(m_pDescriptor->pDescriptor->nVendorString)
        m_pDescriptor->sVendor = getString(m_pDescriptor->pDescriptor->nVendorString);
    else
        m_pDescriptor->sVendor = "";
    if(m_pDescriptor->pDescriptor->nProductString)
        m_pDescriptor->sProduct = getString(m_pDescriptor->pDescriptor->nProductString);
    else
        m_pDescriptor->sProduct = "";
    if(m_pDescriptor->pDescriptor->nSerialString)
        m_pDescriptor->sSerial = getString(m_pDescriptor->pDescriptor->nSerialString);
    else
        m_pDescriptor->sSerial = "";
    for(size_t i = 0;i < m_pDescriptor->pDescriptor->nConfigurations;i++)
    {
        uint16_t *pPartialConfig = static_cast<uint16_t*>(getDescriptor(2, i, 4));
        uint16_t configLength = pPartialConfig[1];
        delete pPartialConfig;
        ConfigDescriptor *pConfig = new ConfigDescriptor(getDescriptor(2, i, configLength), configLength);
        pConfig->sString = getString(pConfig->pDescriptor->nString);
        for(size_t j = 0;j < pConfig->pInterfaces.count();j++)
        {
            Interface *pInterface = pConfig->pInterfaces[j];
            pInterface->sString = getString(pInterface->pDescriptor->nString);
        }
        m_pDescriptor->pConfigurations.pushBack(pConfig);
    }
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "profilewidget.h"
#include "profilecontainer.h"
#include "dcpprofile.h"

#include <QGraphicsLinearLayout>
#include <MContainer>
#include <MLabel>
#include <QVariant>
#include <MGConfItem>

#undef DEBUG
#include "../debug.h"

const QString switchEnabledKey =
    "/meegotouch/settings/profileapplet/switch_enabled";

ProfileWidget::ProfileWidget (
        ProfileDataInterface *api,
        QGraphicsWidget      *parent) :
    DcpWidget (parent),
    m_ProfileIf (api)
{
    SYS_DEBUG ("");

    MGConfItem switchEnabled(switchEnabledKey);
    m_switchEnabled = true; /*switchEnabled.value (false).toBool ();*/

    initWidget ();
}

ProfileWidget::~ProfileWidget ()
{
}

void
ProfileWidget::initWidget ()
{
    // catch profile If actions
    connect (m_ProfileIf, SIGNAL(vibrationValue(int, bool)),
             SLOT(setVibration(int, bool)));

    // get init values
    initProfiles ();

    // widgets're initialized, connect to
    // backends profile-changed signal
    connect (m_ProfileIf, SIGNAL (currentProfile (int)),
             SLOT (profileChanged (int)));
}

void
ProfileWidget::initProfiles ()
{
    QList<ProfileDataInterface::ProfileData> l = m_ProfileIf->getProfilesData();

    QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout (Qt::Vertical);
    QGraphicsLinearLayout *vibraLayout = new QGraphicsLinearLayout (Qt::Vertical);

    SYS_DEBUG ("We have %d profiles.", l.count());
    mainLayout->setContentsMargins (0., 0., 0., 0.);
    mainLayout->setSpacing (0.);
    vibraLayout->setContentsMargins (0., 0., 0., 0.);
    vibraLayout->setSpacing (0.);

    MContainer *headerContainer = new MContainer;
    headerContainer->setHeaderVisible (false);
    headerContainer->setStyleName ("CommonLargeHeaderPanelInverted");

    QGraphicsLinearLayout *headerLayout =
        new QGraphicsLinearLayout (Qt::Horizontal);
    headerLayout->setContentsMargins (0., 0., 0., 0.);

    MLabel *titleLabel = new MLabel;
    //% "Profile"
    titleLabel->setText (qtTrId ("qtn_prof_profile"));
    titleLabel->setStyleName ("CommonLargeHeaderInverted");
    headerLayout->addItem (titleLabel);

    headerLayout->addStretch ();

    MLabel *vibraLabel = new MLabel;
    //% "Vibration"
    vibraLabel->setText (qtTrId ("qtn_prof_vibration"));
    vibraLabel->setStyleName ("CommonGroupHeaderLightInverted");
    vibraLabel->setAlignment (Qt::AlignBottom | Qt::AlignRight);
    headerLayout->addItem (vibraLabel);

    headerContainer->centralWidget ()->setLayout (headerLayout);

    mainLayout->addItem (headerContainer);

    MContainer *listContainer = new MContainer;
    listContainer->setHeaderVisible (false);
    listContainer->setStyleName ("CommonPanelInverted");
    listContainer->setContentsMargins (0., 0., 0., 0.);

    // create profile containers
    for (int i = 0; i < l.count(); ++i) {
        ProfileDataInterface::ProfileData d = l.at(i);
        ProfileContainer* cont = new ProfileContainer(
            d.profileId,
            d.profileName,
            d.vibrationEnabled);
        // For testability driver: set some object name...
        cont->setObjectName (ProfileDataInterface::mapId (d.profileId));
        cont->setIconId(m_ProfileIf->mapId2StatusIconId(d.profileId));

        connect (cont, SIGNAL (toggled (bool)), SLOT (vibrationChanged (bool)));

        if (m_switchEnabled)

        m_Containers.insert(d.profileId, cont);
        vibraLayout->addItem(cont);

        if (m_switchEnabled)
        {
            /*
             * If profile switching is enabled, connect the clicked signal,
             * and select the profile
             */
            cont->setSelected (d.profileId == m_ProfileIf->getCurrentProfile ());
            connect (cont, SIGNAL (clicked ()), SLOT (selectionChanged ()));
        }
    }
    listContainer->centralWidget ()->setLayout (vibraLayout);

    /*
     * mainLayout
     */
    mainLayout->addItem (listContainer);
    mainLayout->addStretch ();

    setLayout (mainLayout);
}

void
ProfileWidget::vibrationChanged (
        bool enabled)
{
    //NOTE: MButton->isChecked() method returns the state before the
    // press at this point
    ProfileContainer *profile =
        static_cast<ProfileContainer*> (this->sender ());

    SYS_DEBUG ("valuechanged for %s: %d",
               SYS_STR (profile->text ()), index);

    m_ProfileIf->setVibration (profile->id (), enabled);
}

void
ProfileWidget::selectionChanged ()
{
    /*
     * INFO: this slot is called only when profile-switiching
     * feature is set to 'true'
     */
    ProfileContainer *profile =
        static_cast<ProfileContainer*> (this->sender ());

    /* deselect all */
    foreach (ProfileContainer *cont, m_Containers)
        cont->setSelected (false);
    /* and select the current */
    profile->setSelected (true);

    m_ProfileIf->setProfile (profile->id ());
}

void
ProfileWidget::profileChanged (int id)
{
    /*
     * No-op if profile-switching feature is disabled...
     */
    if (m_switchEnabled == false)
        return;

    /*
     * this function called when the profile is changed
     * in an other process
     * [eg.: status-indicator-menu profile selection dialog]
     */

    /* deselect all */
    foreach (ProfileContainer *cont, m_Containers)
        cont->setSelected (false);

    /* and select the current */
    m_Containers.value(id)->setSelected (true);
}

void
ProfileWidget::setVibration (
        int profileId,
        bool enabled)
{
    SYS_DEBUG ("set vibration for profile: %d, enabled: %s",
               profileId, SYS_BOOL (enabled));

    ProfileContainer *cont = m_Containers.value (profileId);

    if (cont)
        cont->setChecked (enabled);

}

void
ProfileWidget::retranslateUi ()
{
    SYS_DEBUG ("");

    // Re-load the profiles-data [with the new translations]
    QList<ProfileDataInterface::ProfileData> l = m_ProfileIf->getProfilesData();

    for (int i = 0; i < l.count(); ++i) {
        ProfileDataInterface::ProfileData d = l.at (i);

        // Update the containers title field
        m_Containers.value (d.profileId)->setText (d.profileName);
    }
}

<commit_msg>Changes: disable the profile-switching-by default<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of meegotouch-controlpanelapplets.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include "profilewidget.h"
#include "profilecontainer.h"
#include "dcpprofile.h"

#include <QGraphicsLinearLayout>
#include <MContainer>
#include <MLabel>
#include <QVariant>
#include <MGConfItem>

#undef DEBUG
#include "../debug.h"

const QString switchEnabledKey =
    "/meegotouch/settings/profileapplet/switch_enabled";

ProfileWidget::ProfileWidget (
        ProfileDataInterface *api,
        QGraphicsWidget      *parent) :
    DcpWidget (parent),
    m_ProfileIf (api)
{
    SYS_DEBUG ("");

    MGConfItem switchEnabled(switchEnabledKey);
    switchEnabled.value (false).toBool ();

    initWidget ();
}

ProfileWidget::~ProfileWidget ()
{
}

void
ProfileWidget::initWidget ()
{
    // catch profile If actions
    connect (m_ProfileIf, SIGNAL(vibrationValue(int, bool)),
             SLOT(setVibration(int, bool)));

    // get init values
    initProfiles ();

    // widgets're initialized, connect to
    // backends profile-changed signal
    connect (m_ProfileIf, SIGNAL (currentProfile (int)),
             SLOT (profileChanged (int)));
}

void
ProfileWidget::initProfiles ()
{
    QList<ProfileDataInterface::ProfileData> l = m_ProfileIf->getProfilesData();

    QGraphicsLinearLayout *mainLayout = new QGraphicsLinearLayout (Qt::Vertical);
    QGraphicsLinearLayout *vibraLayout = new QGraphicsLinearLayout (Qt::Vertical);

    SYS_DEBUG ("We have %d profiles.", l.count());
    mainLayout->setContentsMargins (0., 0., 0., 0.);
    mainLayout->setSpacing (0.);
    vibraLayout->setContentsMargins (0., 0., 0., 0.);
    vibraLayout->setSpacing (0.);

    MContainer *headerContainer = new MContainer;
    headerContainer->setHeaderVisible (false);
    headerContainer->setStyleName ("CommonLargeHeaderPanelInverted");

    QGraphicsLinearLayout *headerLayout =
        new QGraphicsLinearLayout (Qt::Horizontal);
    headerLayout->setContentsMargins (0., 0., 0., 0.);

    MLabel *titleLabel = new MLabel;
    //% "Profile"
    titleLabel->setText (qtTrId ("qtn_prof_profile"));
    titleLabel->setStyleName ("CommonLargeHeaderInverted");
    headerLayout->addItem (titleLabel);

    headerLayout->addStretch ();

    MLabel *vibraLabel = new MLabel;
    //% "Vibration"
    vibraLabel->setText (qtTrId ("qtn_prof_vibration"));
    vibraLabel->setStyleName ("CommonGroupHeaderLightInverted");
    vibraLabel->setAlignment (Qt::AlignBottom | Qt::AlignRight);
    headerLayout->addItem (vibraLabel);

    headerContainer->centralWidget ()->setLayout (headerLayout);

    mainLayout->addItem (headerContainer);

    MContainer *listContainer = new MContainer;
    listContainer->setHeaderVisible (false);
    listContainer->setStyleName ("CommonPanelInverted");
    listContainer->setContentsMargins (0., 0., 0., 0.);

    // create profile containers
    for (int i = 0; i < l.count(); ++i) {
        ProfileDataInterface::ProfileData d = l.at(i);
        ProfileContainer* cont = new ProfileContainer(
            d.profileId,
            d.profileName,
            d.vibrationEnabled);
        // For testability driver: set some object name...
        cont->setObjectName (ProfileDataInterface::mapId (d.profileId));
        cont->setIconId(m_ProfileIf->mapId2StatusIconId(d.profileId));

        connect (cont, SIGNAL (toggled (bool)), SLOT (vibrationChanged (bool)));

        if (m_switchEnabled)

        m_Containers.insert(d.profileId, cont);
        vibraLayout->addItem(cont);

        if (m_switchEnabled)
        {
            /*
             * If profile switching is enabled, connect the clicked signal,
             * and select the profile
             */
            cont->setSelected (d.profileId == m_ProfileIf->getCurrentProfile ());
            connect (cont, SIGNAL (clicked ()), SLOT (selectionChanged ()));
        }
    }
    listContainer->centralWidget ()->setLayout (vibraLayout);

    /*
     * mainLayout
     */
    mainLayout->addItem (listContainer);
    mainLayout->addStretch ();

    setLayout (mainLayout);
}

void
ProfileWidget::vibrationChanged (
        bool enabled)
{
    //NOTE: MButton->isChecked() method returns the state before the
    // press at this point
    ProfileContainer *profile =
        static_cast<ProfileContainer*> (this->sender ());

    SYS_DEBUG ("valuechanged for %s: %d",
               SYS_STR (profile->text ()), index);

    m_ProfileIf->setVibration (profile->id (), enabled);
}

void
ProfileWidget::selectionChanged ()
{
    /*
     * INFO: this slot is called only when profile-switiching
     * feature is set to 'true'
     */
    ProfileContainer *profile =
        static_cast<ProfileContainer*> (this->sender ());

    /* deselect all */
    foreach (ProfileContainer *cont, m_Containers)
        cont->setSelected (false);
    /* and select the current */
    profile->setSelected (true);

    m_ProfileIf->setProfile (profile->id ());
}

void
ProfileWidget::profileChanged (int id)
{
    /*
     * No-op if profile-switching feature is disabled...
     */
    if (m_switchEnabled == false)
        return;

    /*
     * this function called when the profile is changed
     * in an other process
     * [eg.: status-indicator-menu profile selection dialog]
     */

    /* deselect all */
    foreach (ProfileContainer *cont, m_Containers)
        cont->setSelected (false);

    /* and select the current */
    m_Containers.value(id)->setSelected (true);
}

void
ProfileWidget::setVibration (
        int profileId,
        bool enabled)
{
    SYS_DEBUG ("set vibration for profile: %d, enabled: %s",
               profileId, SYS_BOOL (enabled));

    ProfileContainer *cont = m_Containers.value (profileId);

    if (cont)
        cont->setChecked (enabled);

}

void
ProfileWidget::retranslateUi ()
{
    SYS_DEBUG ("");

    // Re-load the profiles-data [with the new translations]
    QList<ProfileDataInterface::ProfileData> l = m_ProfileIf->getProfilesData();

    for (int i = 0; i < l.count(); ++i) {
        ProfileDataInterface::ProfileData d = l.at (i);

        // Update the containers title field
        m_Containers.value (d.profileId)->setText (d.profileName);
    }
}

<|endoftext|>


<commit_before>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <svdpi.h>

#include "cosim.h"
#include "spike_cosim.h"

extern "C" {
void *spike_cosim_init(svBitVecVal *start_pc, svBitVecVal *start_mtvec,
                       const char *log_file_path_cstr) {
  std::string log_file_path;

  if (log_file_path_cstr) {
    log_file_path = log_file_path_cstr;
  }

  SpikeCosim *cosim =
      new SpikeCosim(start_pc[0], start_mtvec[0], log_file_path, false, true);
  cosim->add_memory(0x80000000, 0x10000000);
  return static_cast<Cosim *>(cosim);
}

void spike_cosim_release(void *cosim_handle) {
  auto cosim = static_cast<Cosim *>(cosim_handle);

  delete cosim;
}
}
<commit_msg>[dv] Fix cosim memory size<commit_after>// Copyright lowRISC contributors.
// Licensed under the Apache License, Version 2.0, see LICENSE for details.
// SPDX-License-Identifier: Apache-2.0

#include <svdpi.h>

#include "cosim.h"
#include "spike_cosim.h"

extern "C" {
void *spike_cosim_init(svBitVecVal *start_pc, svBitVecVal *start_mtvec,
                       const char *log_file_path_cstr) {
  std::string log_file_path;

  if (log_file_path_cstr) {
    log_file_path = log_file_path_cstr;
  }

  SpikeCosim *cosim =
      new SpikeCosim(start_pc[0], start_mtvec[0], log_file_path, false, true);
  cosim->add_memory(0x80000000, 0x80000000);
  return static_cast<Cosim *>(cosim);
}

void spike_cosim_release(void *cosim_handle) {
  auto cosim = static_cast<Cosim *>(cosim_handle);

  delete cosim;
}
}
<|endoftext|>


<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Author: Svein Lindal <slindal@fys.uio.no>                      *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/// @file   AliAnaConvCorrPhoton.cxx
/// @author Svein Lindal
/// @brief  Class used to fill calculate correlation between photons - jets

#include "AliAnaConvCorrPhotonJet.h"
#include "AliAODTrack.h"
#include "TClonesArray.h"
#include "AliAODConversionParticle.h"
#include "AliAODJet.h"

#include "TRefArray.h"
#include "TH1F.h"
#include <iostream>
// Gamma - jet correlation analysis task
// Authors: Svein Lindal

using namespace std;
ClassImp(AliAnaConvCorrPhotonJet)

//________________________________________________________________________________
AliAnaConvCorrPhotonJet::AliAnaConvCorrPhotonJet() :
AliAnaConvCorrBase("photonJet", "Photon Jet"),
  fhPtFracGamma(NULL),
  fhPtFracPion(NULL)
{
  //consctructor
}
//________________________________________________________________________________
AliAnaConvCorrPhotonJet::AliAnaConvCorrPhotonJet(TString name) :
  AliAnaConvCorrBase(name, "Photon Jet"),
  fhPtFracGamma(NULL),
  fhPtFracPion(NULL)
{
  //consctructor
}

//________________________________________________________________________________
AliAnaConvCorrPhotonJet::~AliAnaConvCorrPhotonJet() {
  //destructor
}

void AliAnaConvCorrPhotonJet::CreateHistograms() {

  CreateBaseHistograms();
  fhPtFracGamma = new TH1F("fhPtFracGamma", "fhPtFracGamma", 100, 0, 10);
  GetHistograms()->Add(fhPtFracGamma);
  fhPtFracPion = new TH1F("fhPtFracPion", "fhPtFracPion", 100, 0, 10);
  GetHistograms()->Add(fhPtFracPion);

}

void AliAnaConvCorrPhotonJet::DoJetAnalysisGamma(AliAODJet * jet, const TClonesArray * const photons, const  TClonesArray *const pions ) const{
  //See header file for documetation
  Int_t trackIDs[4];

  for(Int_t i = 0; i < photons->GetEntriesFast(); i++) {
    AliAODConversionParticle * photon = dynamic_cast<AliAODConversionParticle*>(photons->At(i));
    if(photon) {
      trackIDs[0] = photon->GetLabel1();
      trackIDs[1] = photon->GetLabel2();
      if(IsParticleInJet(jet, 2, trackIDs)){
	fhPtFracGamma->Fill(photon->Pt()/jet->Pt());
      }
    }
  }

  for(Int_t i = 0; i < pions->GetEntriesFast(); i++) {
    AliAODConversionParticle * pion = dynamic_cast<AliAODConversionParticle*>(pions->At(i));
    if(pion) {
      //pion->GetGrandChildren(photons, trackIDs);
      if(IsParticleInJet(jet, 4, trackIDs)){
	fhPtFracPion->Fill(pion->Pt()/jet->Pt());
      }
    }
  }

}

//________________________________________________________________________________
Bool_t AliAnaConvCorrPhotonJet::IsParticleInJet(AliAODJet * jet, Int_t nTracks, Int_t * trackIds) const {
  //See header file for documetation

  Int_t mTracks = 0;
  TRefArray * refTracks = jet->GetRefTracks();
  for(Int_t jRef = 0; jRef < refTracks->GetEntriesFast(); jRef++) {
    AliAODTrack * track = dynamic_cast<AliAODTrack*>(refTracks->At(jRef));
    if(track) {
      for(Int_t it = 0; it < nTracks; it++) {
	if (track->GetID() == trackIds[it]) {
	  mTracks++;
	}
      }
    }
  }

  //cout <<mTracks << " " << (mTracks > 1) << endl;
  return (mTracks > 1);
}

//________________________________________________________________________________
Double_t AliAnaConvCorrPhotonJet::ExtractFromJet(AliAODJet * jet, const AliAODConversionParticle * const particle) const {
  //See header file for documetation

  Float_t jetPt = jet->Pt();
  cout << "Jet pt before and after: " << jetPt << "    ";

  TRefArray * refTracks = jet->GetRefTracks();
  for(Int_t jRef = 0; jRef < refTracks->GetEntriesFast(); jRef++) {
    AliAODTrack * track = dynamic_cast<AliAODTrack*>(refTracks->At(jRef));
    if(track) {
      if (track->GetID() == particle->GetLabel1() || track->GetID() == particle->GetLabel2()) {
	cout << " - " << track->Pt() << "  ";
	jetPt = jetPt - track->Pt();
      } else {
	//cout << track->Pt() << endl;
      }
    } else {
      cout <<"FUUUUUUUUUUUUUUUUUCJK"<<endl;
    }
  }

  cout << jetPt << endl;
  return jetPt;
}

///_______________________________________________________________________________
void AliAnaConvCorrPhotonJet::CorrelateWithHadrons(const AliAODConversionParticle * const photon, const TClonesArray * const jets, const Bool_t isolated) {
  FillTriggerCounters(photon, isolated);
  //See header file for documentation
  if (jets) {
    for(int ij = 0; ij < jets->GetEntriesFast(); ij++) {
      AliAODJet * jet = dynamic_cast<AliAODJet*>(jets->At(ij));
      if(jet) {
		//Double_t jetPt = ExtractFromJet(jet, photon);
		//FillHistograms(photon->Pt(), jetPt, GetDPhi(photon->Phi() - jet->Phi()), photon->Eta() - jet->Eta(), isolated);
      }
    }
  }
}
<commit_msg>Coverity 18474<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Author: Svein Lindal <slindal@fys.uio.no>                      *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

/// @file   AliAnaConvCorrPhoton.cxx
/// @author Svein Lindal
/// @brief  Class used to fill calculate correlation between photons - jets

#include "AliAnaConvCorrPhotonJet.h"
#include "AliAODTrack.h"
#include "TClonesArray.h"
#include "AliAODConversionParticle.h"
#include "AliAODJet.h"

#include "TRefArray.h"
#include "TH1F.h"
#include <iostream>
// Gamma - jet correlation analysis task
// Authors: Svein Lindal

using namespace std;
ClassImp(AliAnaConvCorrPhotonJet)

//________________________________________________________________________________
AliAnaConvCorrPhotonJet::AliAnaConvCorrPhotonJet() :
AliAnaConvCorrBase("photonJet", "Photon Jet"),
  fhPtFracGamma(NULL),
  fhPtFracPion(NULL)
{
  //consctructor
}
//________________________________________________________________________________
AliAnaConvCorrPhotonJet::AliAnaConvCorrPhotonJet(TString name) :
  AliAnaConvCorrBase(name, "Photon Jet"),
  fhPtFracGamma(NULL),
  fhPtFracPion(NULL)
{
  //consctructor
}

//________________________________________________________________________________
AliAnaConvCorrPhotonJet::~AliAnaConvCorrPhotonJet() {
  //destructor
}

void AliAnaConvCorrPhotonJet::CreateHistograms() {

  CreateBaseHistograms();
  fhPtFracGamma = new TH1F("fhPtFracGamma", "fhPtFracGamma", 100, 0, 10);
  GetHistograms()->Add(fhPtFracGamma);
  fhPtFracPion = new TH1F("fhPtFracPion", "fhPtFracPion", 100, 0, 10);
  GetHistograms()->Add(fhPtFracPion);

}

void AliAnaConvCorrPhotonJet::DoJetAnalysisGamma(AliAODJet * jet, const TClonesArray * const photons, const  TClonesArray *const pions ) const{
  //See header file for documetation
  Int_t trackIDs[4]={0};

  for(Int_t i = 0; i < photons->GetEntriesFast(); i++) {
    AliAODConversionParticle * photon = dynamic_cast<AliAODConversionParticle*>(photons->At(i));
    if(photon) {
      trackIDs[0] = photon->GetLabel1();
      trackIDs[1] = photon->GetLabel2();
      if(IsParticleInJet(jet, 2, trackIDs)){
	fhPtFracGamma->Fill(photon->Pt()/jet->Pt());
      }
    }
  }

  for(Int_t i = 0; i < pions->GetEntriesFast(); i++) {
    AliAODConversionParticle * pion = dynamic_cast<AliAODConversionParticle*>(pions->At(i));
    if(pion) {
      //pion->GetGrandChildren(photons, trackIDs);
      if(IsParticleInJet(jet, 4, trackIDs)){
	fhPtFracPion->Fill(pion->Pt()/jet->Pt());
      }
    }
  }

}

//________________________________________________________________________________
Bool_t AliAnaConvCorrPhotonJet::IsParticleInJet(AliAODJet * jet, Int_t nTracks, Int_t * trackIds) const {
  //See header file for documetation

  Int_t mTracks = 0;
  TRefArray * refTracks = jet->GetRefTracks();
  for(Int_t jRef = 0; jRef < refTracks->GetEntriesFast(); jRef++) {
    AliAODTrack * track = dynamic_cast<AliAODTrack*>(refTracks->At(jRef));
    if(track) {
      for(Int_t it = 0; it < nTracks; it++) {
	if (track->GetID() == trackIds[it]) {
	  mTracks++;
	}
      }
    }
  }

  //cout <<mTracks << " " << (mTracks > 1) << endl;
  return (mTracks > 1);
}

//________________________________________________________________________________
Double_t AliAnaConvCorrPhotonJet::ExtractFromJet(AliAODJet * jet, const AliAODConversionParticle * const particle) const {
  //See header file for documetation

  Float_t jetPt = jet->Pt();
  cout << "Jet pt before and after: " << jetPt << "    ";

  TRefArray * refTracks = jet->GetRefTracks();
  for(Int_t jRef = 0; jRef < refTracks->GetEntriesFast(); jRef++) {
    AliAODTrack * track = dynamic_cast<AliAODTrack*>(refTracks->At(jRef));
    if(track) {
      if (track->GetID() == particle->GetLabel1() || track->GetID() == particle->GetLabel2()) {
	cout << " - " << track->Pt() << "  ";
	jetPt = jetPt - track->Pt();
      } else {
	//cout << track->Pt() << endl;
      }
    } else {
      cout <<"FUUUUUUUUUUUUUUUUUCJK"<<endl;
    }
  }

  cout << jetPt << endl;
  return jetPt;
}

///_______________________________________________________________________________
void AliAnaConvCorrPhotonJet::CorrelateWithHadrons(const AliAODConversionParticle * const photon, const TClonesArray * const jets, const Bool_t isolated) {
  FillTriggerCounters(photon, isolated);
  //See header file for documentation
  if (jets) {
    for(int ij = 0; ij < jets->GetEntriesFast(); ij++) {
      AliAODJet * jet = dynamic_cast<AliAODJet*>(jets->At(ij));
      if(jet) {
		//Double_t jetPt = ExtractFromJet(jet, photon);
		//FillHistograms(photon->Pt(), jetPt, GetDPhi(photon->Phi() - jet->Phi()), photon->Eta() - jet->Eta(), isolated);
      }
    }
  }
}
<|endoftext|>


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

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/schema/schema_utils.h"

#include "tensorflow/lite/kernels/internal/compatibility.h"

namespace tflite {

// The following GetBuiltinCode methods are the utility methods for reading
// builtin operatore code, ensuring compatibility issues between v3 and v3a
// schema. Always the maximum value of the two fields always will be the correct
// value as follows:
//
// - Supporting schema version v3 models
//
// The `builtin_code` field is not available in the v3 models. Flatbuffer
// library will feed zero value, which is the default value in the v3a schema.
// The actual builtin operatore code value will exist in the
// `deprecated_builtin_code` field. At the same time, it implies that
// `deprecated_builtin_code` >= `builtin_code` and the maximum value of the two
// fields will be same with `deprecated_builtin_code'.
//
// - Supporting builtin operator codes beyonds 127
//
// New builtin operators, whose operator code is larger than 127, can not be
// assigned to the `deprecated_builtin_code` field. In such cases, the
// value of the `builtin_code` field should be used for the builtin operator
// code. In the case, the maximum value of the two fields will be the value of
// the `builtin_code` as the right value.

BuiltinOperator GetBuiltinCode(const OperatorCode *op_code) {
  // Caller should guarantee that the given argument value is not a nullptr.
  TFLITE_DCHECK(op_code != nullptr);

  return (op_code->builtin_code() ? op_code->builtin_code()
                                  : static_cast<BuiltinOperator>(
                                        op_code->deprecated_builtin_code()));
}

BuiltinOperator GetBuiltinCode(const OperatorCodeT *op_code) {
  // Caller should guarantee that the given argument value is not a nullptr.
  TFLITE_DCHECK(op_code != nullptr);

  return (op_code->builtin_code
              ? op_code->builtin_code
              : static_cast<BuiltinOperator>(op_code->deprecated_builtin_code));
}

int8_t ConvertBuiltinCodeToDeprecatedBuiltinCode(
    const BuiltinOperator builtin_code) {
  return (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES)
             ? static_cast<int8_t>(builtin_code)
             : static_cast<int8_t>(
                   BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
}

// The following methods are the following `OperatorCode` table object creation
// methods for backward compatibility.  These are manually copied from the
// flatbuffer generated code from schema v3. They serve as overloads for the
// v3a's CreateOperatorCode functions in schema_generated.h and enable code that
// still assumes flatbuffer schema v3 to be unchanged with the inclusion of the
// schema_utils header.
// TODO(b/162392898): remove once all callers are updated to use schema v3a
// functions.

flatbuffers::Offset<OperatorCode> CreateOperatorCode(
    flatbuffers::FlatBufferBuilder &_fbb, BuiltinOperator builtin_code,
    flatbuffers::Offset<flatbuffers::String> custom_code, int32_t version) {
  OperatorCodeBuilder builder_(_fbb);
  builder_.add_version(version);

  int8_t deprecated_builtin_code =
      static_cast<int8_t>(BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
  if (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES) {
    deprecated_builtin_code = static_cast<int8_t>(builtin_code);
  }
  builder_.add_deprecated_builtin_code(deprecated_builtin_code);
  builder_.add_custom_code(custom_code);
  builder_.add_builtin_code(builtin_code);
  return builder_.Finish();
}

flatbuffers::Offset<OperatorCode> CreateOperatorCodeDirect(
    flatbuffers::FlatBufferBuilder &_fbb, BuiltinOperator builtin_code,
    const char *custom_code, int32_t version) {
  auto custom_code__ = custom_code ? _fbb.CreateString(custom_code) : 0;
  int8_t deprecated_builtin_code =
      static_cast<int8_t>(BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
  if (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES) {
    deprecated_builtin_code = static_cast<int8_t>(builtin_code);
  }
  return CreateOperatorCode(_fbb, deprecated_builtin_code, custom_code__,
                            version, builtin_code);
}

}  // namespace tflite
<commit_msg>Change the implementation of getter methods of schema utils.<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/lite/schema/schema_utils.h"

#include <algorithm>

#include "tensorflow/lite/kernels/internal/compatibility.h"

namespace tflite {

// The following GetBuiltinCode methods are the utility methods for reading
// builtin operatore code, ensuring compatibility issues between v3 and v3a
// schema. Always the maximum value of the two fields always will be the correct
// value as follows:
//
// - Supporting schema version v3 models
//
// The `builtin_code` field is not available in the v3 models. Flatbuffer
// library will feed zero value, which is the default value in the v3a schema.
// The actual builtin operatore code value will exist in the
// `deprecated_builtin_code` field. At the same time, it implies that
// `deprecated_builtin_code` >= `builtin_code` and the maximum value of the two
// fields will be same with `deprecated_builtin_code'.
//
// - Supporting builtin operator codes beyonds 127
//
// New builtin operators, whose operator code is larger than 127, can not be
// assigned to the `deprecated_builtin_code` field. In such cases, the
// value of the `builtin_code` field should be used for the builtin operator
// code. In the case, the maximum value of the two fields will be the value of
// the `builtin_code` as the right value.

BuiltinOperator GetBuiltinCode(const OperatorCode *op_code) {
  // Caller should guarantee that the given argument value is not a nullptr.
  TFLITE_DCHECK(op_code != nullptr);

  return std::max(
      op_code->builtin_code(),
      static_cast<BuiltinOperator>(op_code->deprecated_builtin_code()));
}

BuiltinOperator GetBuiltinCode(const OperatorCodeT *op_code) {
  // Caller should guarantee that the given argument value is not a nullptr.
  TFLITE_DCHECK(op_code != nullptr);

  return std::max(op_code->builtin_code, static_cast<BuiltinOperator>(
                                             op_code->deprecated_builtin_code));
}

int8_t ConvertBuiltinCodeToDeprecatedBuiltinCode(
    const BuiltinOperator builtin_code) {
  return (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES)
             ? static_cast<int8_t>(builtin_code)
             : static_cast<int8_t>(
                   BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
}

// The following methods are the following `OperatorCode` table object creation
// methods for backward compatibility.  These are manually copied from the
// flatbuffer generated code from schema v3. They serve as overloads for the
// v3a's CreateOperatorCode functions in schema_generated.h and enable code that
// still assumes flatbuffer schema v3 to be unchanged with the inclusion of the
// schema_utils header.
// TODO(b/162392898): remove once all callers are updated to use schema v3a
// functions.

flatbuffers::Offset<OperatorCode> CreateOperatorCode(
    flatbuffers::FlatBufferBuilder &_fbb, BuiltinOperator builtin_code,
    flatbuffers::Offset<flatbuffers::String> custom_code, int32_t version) {
  OperatorCodeBuilder builder_(_fbb);
  builder_.add_version(version);

  int8_t deprecated_builtin_code =
      static_cast<int8_t>(BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
  if (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES) {
    deprecated_builtin_code = static_cast<int8_t>(builtin_code);
  }
  builder_.add_deprecated_builtin_code(deprecated_builtin_code);
  builder_.add_custom_code(custom_code);
  builder_.add_builtin_code(builtin_code);
  return builder_.Finish();
}

flatbuffers::Offset<OperatorCode> CreateOperatorCodeDirect(
    flatbuffers::FlatBufferBuilder &_fbb, BuiltinOperator builtin_code,
    const char *custom_code, int32_t version) {
  auto custom_code__ = custom_code ? _fbb.CreateString(custom_code) : 0;
  int8_t deprecated_builtin_code =
      static_cast<int8_t>(BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES);
  if (builtin_code < BuiltinOperator_PLACEHOLDER_FOR_GREATER_OP_CODES) {
    deprecated_builtin_code = static_cast<int8_t>(builtin_code);
  }
  return CreateOperatorCode(_fbb, deprecated_builtin_code, custom_code__,
                            version, builtin_code);
}

}  // namespace tflite
<|endoftext|>


<commit_before><commit_msg>fix build bustage<commit_after><|endoftext|>


<commit_before>
/* Test program to test the timer callbacks
*/

#include <iostream>
#include "SDL.hh"
#include <ctime>
#include <sstream>

using namespace RAGE;
using namespace RAGE::SDL;
using namespace std;

static long ticks;

Logger testlog("testTimer");

/*static unsigned int callback(unsigned int interval, void * args)
{
	testlog << nl << SDL::GetTicks() - ticks  << " ms : Static Function called back !" ;
	return 50;
}*/

int random(int min, int max)
{
	return min + (rand()%(max+1-min));
}

std::string Int_To_String(const int &to_convert)
{
	std::stringstream s;
    if (s << to_convert) // conversion worked
        return s.str();

	//failed
	return NULL;
}

class SimpleObject
{
	friend class ObjectWithCallbacks;
	friend class OwnerOfObjWCallbacks;
	friend class DerivateOwnerOfObjWCallbacks;

public:
	int callback_interval, cb_frames;
	SimpleObject()
	{
		callback_interval = random(50,100);
		cb_frames = random(5,9);
	}
};

class SimpleArgObject
{

public:
	int isao;

	SimpleArgObject()
	{
		isao = random(1,10);
	}
};

class ObjectWithCallbacks
{
	friend class OwnerOfObjWCallbacks;

private:
	SDL::NewTimer<ObjectWithCallbacks> *Play_Timer_1x;
	SimpleObject *sobj;

	int direct_timer_it, direct_timer_int;

	int loop_nb;

	long start_timer_tick;

protected:
	int flag; //0: default|initial, 1: used by callback, 2: callback ended

public:
	ObjectWithCallbacks() : sobj(NULL), Play_Timer_1x(NULL)
	{
	try	{
		direct_timer_it = 8;
		direct_timer_int = 200;
		loop_nb = 0;

		flag = 0;
		start_timer_tick = 0;

		sobj = new SimpleObject();

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks Constructor " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks Constructor" );
	}
	}

	~ObjectWithCallbacks()
	{
		Clean_ObjectWithCallbacks();
	}

	void Clean_ObjectWithCallbacks()
	{
		if (Play_Timer_1x != NULL)
		{
			Play_Timer_1x->abort();
			delete Play_Timer_1x, Play_Timer_1x = NULL;
		}

		delete sobj, sobj = NULL;
	}

	//Manual abort
	void stop()
	{
		if (Play_Timer_1x != NULL)
		{
			testlog << nl << Play_Timer_1x << " aborted by ObjectWithCallbacks::stop()" << std::endl;
			Play_Timer_1x->abort();
			delete Play_Timer_1x, Play_Timer_1x = NULL;
			flag = 0;
		}
	}

	void play1_1(SimpleArgObject*& ArgObject)
	{
	try {

		loop_nb = 0;
		flag = 1;
		delete Play_Timer_1x, Play_Timer_1x = NULL;

		Play_Timer_1x = new SDL::NewTimer<ObjectWithCallbacks>(this,&ObjectWithCallbacks::callback1_1, (void*)(ArgObject)/*NULL*/ );

		testlog << nl << "play1_1 create Timer " << Play_Timer_1x << " and launching it" << std::endl;

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::play1_1 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::play1_1" );
	}
	}

private:
	unsigned int callback1_1(unsigned int interval, void* args)
	{
	try	{

		testlog << nl << SDL::GetTicks() - ticks  << " ms : " << this << "'s callback1_1 called back at frame " << loop_nb << std::endl;

		if (args == NULL)
		{
			assert(args == NULL && "Arg Pointer is NULL !");
			throw std::logic_error("Arg Pointer is NULL !");
		}

		//Check nb of frame
		if (++loop_nb < sobj->cb_frames)
			return sobj->callback_interval;
		else
		{
			flag = 2;
			return 0;
		}

	} catch (std::exception &exc)	{
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::callback1_1 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::callback1_1" );
	}
	}

public:
	unsigned int callback2(unsigned int interval, void* args)
	{
	try	{
		testlog << nl << SDL::GetTicks() - ticks  << " ms : direct callback2 Called back ! Number: " << direct_timer_it-- ;

		if ( direct_timer_it != 0 )
			return direct_timer_int;

		testlog << nl << "Stopping direct timer" << std::endl;
		return 0;

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::callback2 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::callback2" );
	}
	}
};

class OwnerOfObjWCallbacks
{
	friend class DerivateOwnerOfObjWCallbacks;
	friend class ObjectWithCallbacks;

protected:
	ObjectWithCallbacks* objwcb;
	SimpleArgObject* sao;

public:
	OwnerOfObjWCallbacks() : objwcb(NULL), sao(NULL)
	{
	try {

		objwcb = new ObjectWithCallbacks();
		sao = new SimpleArgObject();

	} catch (std::exception &exc) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Error in OwnerOfObjWCallbacks Constructor()" +(string)exc.what() );
	} catch (...) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Unhandled Error in OwnerOfObjWCallbacks Constructor" );
	}
	}

	virtual ~OwnerOfObjWCallbacks()
	{
		Clean_OwnerOfObjWCallbacks();
	}

	void Clean_OwnerOfObjWCallbacks()
	{
		delete objwcb, objwcb = NULL;
		delete sao, sao = NULL;
	}

	void DoSthg()
	{
	try {

		switch (objwcb->flag)
		{
		case 0: //no callback running
			testlog << nl << "OwnerOfObjWCallbacks " << this << "'s ObjectWithCallbacks::play1_1() called" << std::endl;
			objwcb->start_timer_tick = SDL::GetTicks();
			objwcb->play1_1( sao );
			break;

		case 1: //one callback running
			if (objwcb->start_timer_tick + 1100 < SDL::GetTicks()) //1100ms = max nb de frame potential * max interval potentiel + 100ms
			{
				testlog << nl << "ERROR : A timer encounter an abornal termination for OwnerOfObjWCallbacks " << this << std::endl;
				throw logic_error( " A timer encounter an abornal termination");
			}
			break;

		case 2: //one callback ended
			testlog << nl << "callback1_1 Ended, Resetting objwcb->flag to 0 inside " << this << " OwnerOfObjWCallbacks" << std::endl;
			objwcb->flag = 0;
			break;

		default:
			throw logic_error( "unkown objwcb->flag value : " + Int_To_String(objwcb->flag) );
			break;

		}

	} catch (std::exception &exc) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Error in OwnerOfObjWCallbacks::DoSthg() : " + (string)exc.what() );
	} catch (...) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Unhandled Error in OwnerOfObjWCallbacks::DoSthg" );
	}
	}
};

/*class DerivateOwnerOfObjWCallbacks : public OwnerOfObjWCallbacks
{

public:
	DerivateOwnerOfObjWCallbacks()
	{}
};*/

int main(int argc, char *argv[])
{
try {
	unsigned int NB_OBJ = 15;
	long TEST_DURATION = 20000; //ms

/***Init & Implement***/

	//Init the rand method using the current time in order to generate more random numbers
	srand( (unsigned)time( NULL ) );

	testlog.enableFileLog("testTimer.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance().initTimer();

	//static SDL_TimerID gt_id = SDL::AddGlobalTimer(50,callback,NULL);

	testlog << nl<<"Creating instance";
	ObjectWithCallbacks* gobj = new ObjectWithCallbacks();

	testlog << nl<<"Creating instance timer";
	SDL::Timer<ObjectWithCallbacks> direct_timer;
	direct_timer.setCallback(gobj,&ObjectWithCallbacks::callback2,(void*)NULL);
	testlog << nl <<"Starting instance timer 2 (every 200ms)";
	direct_timer.launch(200);

	vector<OwnerOfObjWCallbacks*>* voocb = new vector<OwnerOfObjWCallbacks*>;
	for (unsigned int i = 0; i < NB_OBJ; i++)
	{
		voocb->push_back( new OwnerOfObjWCallbacks() );
	}

	//DerivateOwnerOfObjWCallbacks* iocb = new DerivateOwnerOfObjWCallbacks();

/***Run***/
	//SDL::Delay(15000); //TODO Display time running
	ticks = SDL::GetTicks();

	while (SDL::GetTicks() < (ticks + TEST_DURATION))
	{
		for (unsigned int i = 0; i < voocb->size(); i++)
		{
			voocb->at(i)->DoSthg();
		}
		//iocb->DoSthg();
	}

/***Clean***/
	testlog << nl << "Cleaning and finished";

	direct_timer.abort();

	delete gobj, gobj = NULL;

	for (unsigned int i = 0; i < voocb->size(); i++)
	{
		delete voocb->at(i), voocb->at(i) = NULL;
	}
	delete voocb, voocb = NULL;

	//delete iocb, iocb = NULL;

	//SDL::RemoveGlobalTimer(gt_id);

	return 0;
} catch (std::exception &exc) {
	testlog << nl << " ***** ERROR ***** : " << exc.what();
	//SDL::Delay(2000);

} catch (...) {
	throw std::logic_error("Unhandled Error in Main !" );
}
}
<commit_msg> improving test Timer... and trying stuff... <commit_after>
/* Test program to test the timer callbacks
*/

#include <iostream>
#include "SDL.hh"
#include <ctime>
#include <sstream>

//to be able to easily remove the locks
#define SCOPED_LOCK(mtx) ScopedLock lock(mtx)
//#define SCOPED_LOCK(mtx)

using namespace RAGE;
using namespace RAGE::SDL;
using namespace std;

static long ticks;

Logger testlog("testTimer");

/*static unsigned int callback(unsigned int interval, void * args)
{
	testlog << nl << SDL::GetTicks() - ticks  << " ms : Static Function called back !" ;
	return 50;
}*/

int random(int min, int max)
{
	return min + (rand()%(max+1-min));
}

std::string Int_To_String(const int &to_convert)
{
	std::stringstream s;
    if (s << to_convert) // conversion worked
        return s.str();

	//failed
	return NULL;
}

class SimpleObject
{
	friend class ObjectWithCallbacks;
	friend class OwnerOfObjWCallbacks;
	friend class DerivateOwnerOfObjWCallbacks;

public:
	int callback_interval, cb_frames;
	SimpleObject()
	{
		callback_interval = random(50,100);
		cb_frames = random(5,9);
	}
};

class SimpleArgObject
{

public:
	int isao;

	SimpleArgObject()
	{
		isao = random(1,10);
	}
};

class ObjectWithCallbacks
{
	friend class OwnerOfObjWCallbacks;

private:
	SDL::NewTimer<ObjectWithCallbacks> *Play_Timer_1x;
	SimpleObject *sobj;

	int direct_timer_it, direct_timer_int;

	int loop_nb;

	long start_timer_tick;

	Mutex mymtx;

protected:
	int flag; //0: default|initial, 1: used by callback, 2: callback ended

public:
	ObjectWithCallbacks() : sobj(NULL), Play_Timer_1x(NULL)
	{
	try	{
		direct_timer_it = 8;
		direct_timer_int = 200;
		loop_nb = 0;

		flag = 0;
		start_timer_tick = 0;

		sobj = new SimpleObject();

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks Constructor " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks Constructor" );
	}
	}

	~ObjectWithCallbacks()
	{
		Clean_ObjectWithCallbacks();
	}

	void Clean_ObjectWithCallbacks()
	{
		if (Play_Timer_1x != NULL)
		{
			Play_Timer_1x->abort();
			delete Play_Timer_1x, Play_Timer_1x = NULL;
		}

		delete sobj, sobj = NULL;
	}

	//Manual abort
	void stop()
	{
SCOPED_LOCK(mymtx);

		if (Play_Timer_1x != NULL)
		{
			testlog << nl << Play_Timer_1x << " aborted by ObjectWithCallbacks::stop()" << std::endl;
			Play_Timer_1x->abort();
			delete Play_Timer_1x, Play_Timer_1x = NULL;
			flag = 0;
		}
	}

	void play1_1(SimpleArgObject*& ArgObject)
	{
	try {
SCOPED_LOCK(mymtx);

		loop_nb = 0;
		flag = 1;
		delete Play_Timer_1x, Play_Timer_1x = NULL;

		Play_Timer_1x = new SDL::NewTimer<ObjectWithCallbacks>(this,&ObjectWithCallbacks::callback1_1, (void*)(ArgObject)/*NULL*/ );

		testlog << nl << this << "\'s play1_1 create Timer " << Play_Timer_1x << " and launching it" << std::endl;

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::play1_1 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::play1_1" );
	}
	}

private:
	unsigned int callback1_1(unsigned int interval, void* args)
	{
	try	{
SCOPED_LOCK(mymtx);
		testlog << nl << SDL::GetTicks() - ticks  << " ms : " << this << "\'s callback1_1 called back at frame " << loop_nb << std::endl;

		if (args == NULL)
		{
			assert(args == NULL && "Arg Pointer is NULL !");
			throw std::logic_error("Arg Pointer is NULL !");
		}

		//Check nb of frame
		if (++loop_nb < sobj->cb_frames)
			return sobj->callback_interval;
		else
		{
			flag = 2;
			return 0;
		}

	} catch (std::exception &exc)	{
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::callback1_1 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::callback1_1" );
	}
	}

public:
	unsigned int callback2(unsigned int interval, void* args)
	{
	try	{
SCOPED_LOCK(mymtx);
		testlog << nl << " ====>> " << SDL::GetTicks() - ticks  << " ms : " << this << "\'s direct callback2 Called back ! Number: " << direct_timer_it-- ;

		if ( direct_timer_it != 0 )
			return direct_timer_int;

		testlog << nl << "Stopping " << this << "\'s direct timer" << std::endl;
		return 0;

	} catch (std::exception &exc) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Error in ObjectWithCallbacks::callback2 " + (string)exc.what() );
	} catch (...) {
		Clean_ObjectWithCallbacks();
		throw std::logic_error("Unhandled Error in ObjectWithCallbacks::callback2" );
	}
	}
};

class OwnerOfObjWCallbacks
{
	friend class DerivateOwnerOfObjWCallbacks;
	friend class ObjectWithCallbacks;

protected:
	ObjectWithCallbacks* objwcb;
	SimpleArgObject* sao;

public:
	OwnerOfObjWCallbacks() : objwcb(NULL), sao(NULL)
	{
	try {

		objwcb = new ObjectWithCallbacks();
		sao = new SimpleArgObject();

	} catch (std::exception &exc) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Error in OwnerOfObjWCallbacks Constructor()" +(string)exc.what() );
	} catch (...) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Unhandled Error in OwnerOfObjWCallbacks Constructor" );
	}
	}

	virtual ~OwnerOfObjWCallbacks()
	{
		Clean_OwnerOfObjWCallbacks();
	}

	void Clean_OwnerOfObjWCallbacks()
	{
		delete objwcb, objwcb = NULL;
		delete sao, sao = NULL;
	}

	void DoSthg()
	{
	try {
SCOPED_LOCK(objwcb->mymtx);
		switch (objwcb->flag)
		{
		case 0: //no callback running
			testlog << nl << "OwnerOfObjWCallbacks " << this << "\'s ObjectWithCallbacks @ " << this->objwcb << " ::play1_1() called" << std::endl;
			objwcb->start_timer_tick = SDL::GetTicks();
			objwcb->play1_1( sao );
			break;

		case 1: //one callback running
			if (objwcb->start_timer_tick + 1100 < SDL::GetTicks()) //1100ms = max nb de frame potential * max interval potentiel + 100ms
			{
				testlog << nl << "ERROR : A timer encounter an abornal termination for OwnerOfObjWCallbacks " << this << "\'s ObjectWithCallbacks @ " << this->objwcb << std::endl;
				throw logic_error( " A timer encounter an abornal termination");
			}
			break;

		case 2: //one callback ended
			testlog << nl << "callback1_1 Ended, Resetting objwcb->flag to 0 inside OwnerOfObjWCallbacks" << this << "\'s ObjectWithCallbacks @ " <<this->objwcb << std::endl;
			objwcb->flag = 0;
			break;

		default:
			throw logic_error( "unkown objwcb->flag value : " + Int_To_String(objwcb->flag) );
			break;

		}

	} catch (std::exception &exc) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Error in OwnerOfObjWCallbacks::DoSthg() : " + (string)exc.what() );
	} catch (...) {
		Clean_OwnerOfObjWCallbacks();
		throw std::logic_error("Unhandled Error in OwnerOfObjWCallbacks::DoSthg" );
	}
	}
};

/*class DerivateOwnerOfObjWCallbacks : public OwnerOfObjWCallbacks
{

public:
	DerivateOwnerOfObjWCallbacks()
	{}
};*/

int main(int argc, char *argv[])
{
try {
	unsigned int NB_OBJ = 15;
	long TEST_DURATION = 20000; //ms

/***Init & Implement***/

	//Init the rand method using the current time in order to generate more random numbers
	srand( (unsigned)time( NULL ) );

	testlog.enableFileLog("testTimer.log");
	testlog << nl<<"SDL init...";

	SDL::App::getInstance().initTimer();

	//static SDL_TimerID gt_id = SDL::AddGlobalTimer(50,callback,NULL);

	testlog << nl<<"Creating instance";
	ObjectWithCallbacks* gobj = new ObjectWithCallbacks();

	testlog << nl<<"Creating instance timer";
	SDL::NewTimer<ObjectWithCallbacks> direct_timer(gobj,&ObjectWithCallbacks::callback2,(void*)NULL,200);

	testlog << nl <<"Starting instance timer 2 (every 200ms)";

	vector<OwnerOfObjWCallbacks*>* voocb = new vector<OwnerOfObjWCallbacks*>;
	for (unsigned int i = 0; i < NB_OBJ; i++)
	{
		voocb->push_back( new OwnerOfObjWCallbacks() );
	}

	//DerivateOwnerOfObjWCallbacks* iocb = new DerivateOwnerOfObjWCallbacks();

/***Run***/
	//SDL::Delay(15000); //TODO Display time running
	ticks = SDL::GetTicks();

	while (SDL::GetTicks() < (ticks + TEST_DURATION))
	{
		for (unsigned int i = 0; i < voocb->size(); i++)
		{
			voocb->at(i)->DoSthg();
		}
		//iocb->DoSthg();
	}

/***Clean***/
	testlog << nl << "Cleaning and finished";

	direct_timer.abort();

	delete gobj, gobj = NULL;

	for (unsigned int i = 0; i < voocb->size(); i++)
	{
		delete voocb->at(i), voocb->at(i) = NULL;
	}
	delete voocb, voocb = NULL;

	//delete iocb, iocb = NULL;

	//SDL::RemoveGlobalTimer(gt_id);

	return 0;
} catch (std::exception &exc) {
	testlog << nl << " ***** ERROR ***** : " << exc.what();
	//SDL::Delay(2000);

} catch (...) {
	throw std::logic_error("Unhandled Error in Main !" );
}
}
<|endoftext|>