<commit_before>#include "VSprite.h"
#include "VGlobal.h"

VSprite::VSprite(sf::Vector2f Position, const sf::String& Filename) : VObject(Position)
{
	RenderState = sf::RenderStates::Default;
	Tint = sf::Color::White;
	Scale = sf::Vector2f(1, 1);
	Offset = sf::Vector2f();

	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4);

	if (Filename != "")
	{
		LoadGraphic(Filename);
	}

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

VSprite::VSprite(float x, float y, const sf::String& filename) : VObject(x, y)
{
	RenderState = sf::RenderStates::Default;
	Tint = sf::Color::White;
	Scale = sf::Vector2f(1, 1);
	Offset = sf::Vector2f();

	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4);

	if (filename != "")
	{
		LoadGraphic(filename);
	}

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

void VSprite::setSize(unsigned int texWidth, unsigned int texHeight, bool animated, int width, int height, int offsetX, int offsetY)
{
	Size = sf::Vector2f(sf::Vector2u(width, height));

	if (Size.x <= 0)
	{
		Size.x = static_cast<float>(animated ? texHeight : texWidth);
		Size.x = std::fminf(Size.x, static_cast<float>(texWidth));
	}
	if (Size.y <= 0)
	{
		Size.y = static_cast<float>(animated ? Size.x : texHeight);
		Size.y = std::fminf(Size.y, static_cast<float>(texHeight));
	}

	FrameSize = sf::Vector2u(Size);
	Animation = VAnimationManager(texWidth, texHeight, FrameSize.x, FrameSize.y, offsetX, offsetY);
	Origin = sf::Vector2f(FrameSize) / 2.0f;

	Radius = Size.x < Size.y ? Size.x / 2 : Size.y / 2;

	vertexArray[0].position = sf::Vector2f();
	vertexArray[1].position = sf::Vector2f(Size.x, 0.0f);
	vertexArray[2].position = sf::Vector2f(Size.x, Size.y);
	vertexArray[3].position = sf::Vector2f(0.0f, Size.y);
}

void VSprite::updateTransform()
{
	float angle = -Angle * VFRAME_PI / 180.f;
	float cosine = static_cast<float>(std::cos(angle));
	float sine = static_cast<float>(std::sin(angle));
	float sxc = Scale.x * cosine;
	float syc = Scale.y * cosine;
	float sxs = Scale.x * sine;
	float sys = Scale.y * sine;
	float tx = -Origin.x * sxc - Origin.y * sys + (Position + Origin - Offset).x;
	float ty =  Origin.x * sxs - Origin.y * syc + (Position + Origin - Offset).y;

	RenderState.transform =
		sf::Transform(	sxc, sys, tx,
						-sxs, syc, ty,
						0.f, 0.f, 1.f);

	if (vertexArray[0].color != Tint)
	{
		vertexArray[0].color = Tint;
		vertexArray[1].color = Tint;
		vertexArray[2].color = Tint;
		vertexArray[3].color = Tint;
	}
}

void VSprite::updateFrame()
{
	sf::FloatRect rect;
	rect.left		= FlipX ? Animation.GetU() + (float)FrameSize.x : Animation.GetU();
	rect.top		= FlipY ? Animation.GetV() + (float)FrameSize.y : Animation.GetV();
	rect.width		= FlipX ? -(float)FrameSize.x : (float)FrameSize.x;
	rect.height		= FlipY ? -(float)FrameSize.y : (float)FrameSize.y;
	vertexArray[0].texCoords = sf::Vector2f(rect.left,				rect.top);
	vertexArray[1].texCoords = sf::Vector2f(rect.left + rect.width, rect.top);
	vertexArray[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height);
	vertexArray[3].texCoords = sf::Vector2f(rect.left,				rect.top + rect.height);
}

VSprite* VSprite::LoadGraphic(const sf::String& filename, bool animated, int width, int height, const sf::IntRect& area)
{
	RenderState.texture = &VGlobal::p()->Content->LoadTexture(filename);

	setSize(
		area.width == 0 ? RenderState.texture->getSize().x : area.width,
		area.height == 0 ? RenderState.texture->getSize().y : area.height,
		animated, width, height, area.left, area.top
		);

	updateFrame();

	return this;
}

VSprite* VSprite::LoadGraphicFromTexture(sf::Texture& texture, bool animated, int width, int height, const sf::IntRect& area)
{
	RenderState.texture = &texture;

	setSize(
		area.width == 0 ? RenderState.texture->getSize().x : area.width,
		area.height == 0 ? RenderState.texture->getSize().y : area.height,
		animated, width, height, area.left, area.top
		);

	updateFrame();
	return this;
}

VSprite* VSprite::MakeGraphic(int width, int height, sf::Color color, float outline, sf::Color outlineColor)
{
	if (disposible && RenderState.texture)
	{
		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}

	sf::Image image;
	image.create(width, height, color);

	for (int y = 0; y < height; y++)
	{
		for (int x = 0; x < width; x++)
		{
			if (x < outline || y < outline || x > width - outline || y > height - outline)
			{
				image.setPixel(x, y, outlineColor);
			}
		}
	}

	sf::Texture* texture = new sf::Texture();
	texture->loadFromImage(image);
	disposible = true;

	RenderState.texture = texture;
	setSize(width, height, false, width, height);

	return this;
}

VSprite* VSprite::MakeGraphicCircle(int radius, sf::Color color, float outline, sf::Color outlineColor)
{
	if (disposible && RenderState.texture)
	{
		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}

	unsigned int diameter = radius * 2;

	sf::Image image;
	image.create(diameter, diameter, sf::Color::Transparent);

	for (unsigned int y = 0; y < diameter; y++)
	{
		for (unsigned int x = 0; x < diameter; x++)
		{
			int dx = radius - x;
			int dy = radius - y;
			int length = (dx * dx) + (dy * dy);

			if (length <= (radius * radius))
			{
				if (outline <= 0 || length <= ((radius - outline) * (radius - outline)))
					image.setPixel(x, y, color);
				else
					image.setPixel(x, y, outlineColor);
			}
		}
	}

	sf::Texture* texture = new sf::Texture();
	texture->loadFromImage(image);
	disposible = true;

	RenderState.texture = texture;
	setSize(radius * 2, radius * 2, false, radius * 2, radius * 2);

	return this;
}

void VSprite::Destroy()
{
	VSUPERCLASS::Destroy();

	if (disposible && RenderState.texture)
	{
		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}
}

void VSprite::Update(float dt)
{
	VSUPERCLASS::Update(dt);
	Animation.Update(dt);
}

void VSprite::Draw(sf::RenderTarget& RenderTarget)
{
	VSUPERCLASS::Draw(RenderTarget);

	bool updateTexture = false;
	if (Animation.GetLastFrame() != Animation.GetCurrentFrame())
		updateTexture = true;

	if ((FlipX && vertexArray[2].texCoords.x - vertexArray[0].texCoords.x > 0) || (!FlipX && vertexArray[2].texCoords.x - vertexArray[0].texCoords.x < 0))
		updateTexture = true;

	if ((FlipY && vertexArray[2].texCoords.y - vertexArray[0].texCoords.y > 0) || (!FlipY && vertexArray[2].texCoords.y - vertexArray[0].texCoords.y < 0))
		updateTexture = true;

	if (updateTexture)
		updateFrame();

	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	if (TestInView(renderTargetView, &scrollView, this, RenderState.transform.transformRect(vertexArray.getBounds())))
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(vertexArray, RenderState);
		RenderTarget.setView(renderTargetView);
	}
}<commit_msg>Prevent constant delete and new texture in MakeGraphic function.<commit_after>#include "VSprite.h"
#include "VGlobal.h"

VSprite::VSprite(sf::Vector2f Position, const sf::String& Filename) : VObject(Position)
{
	RenderState = sf::RenderStates::Default;
	Tint = sf::Color::White;
	Scale = sf::Vector2f(1, 1);
	Offset = sf::Vector2f();

	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4);

	if (Filename != "")
	{
		LoadGraphic(Filename);
	}

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

VSprite::VSprite(float x, float y, const sf::String& filename) : VObject(x, y)
{
	RenderState = sf::RenderStates::Default;
	Tint = sf::Color::White;
	Scale = sf::Vector2f(1, 1);
	Offset = sf::Vector2f();

	vertexArray.setPrimitiveType(sf::Quads);
	vertexArray.resize(4);

	if (filename != "")
	{
		LoadGraphic(filename);
	}

#if _DEBUG
	DebugColor = sf::Color(0, 255, 0, 128);
#endif
}

void VSprite::setSize(unsigned int texWidth, unsigned int texHeight, bool animated, int width, int height, int offsetX, int offsetY)
{
	Size = sf::Vector2f(sf::Vector2u(width, height));

	if (Size.x <= 0)
	{
		Size.x = static_cast<float>(animated ? texHeight : texWidth);
		Size.x = std::fminf(Size.x, static_cast<float>(texWidth));
	}
	if (Size.y <= 0)
	{
		Size.y = static_cast<float>(animated ? Size.x : texHeight);
		Size.y = std::fminf(Size.y, static_cast<float>(texHeight));
	}

	FrameSize = sf::Vector2u(Size);
	Animation = VAnimationManager(texWidth, texHeight, FrameSize.x, FrameSize.y, offsetX, offsetY);
	Origin = sf::Vector2f(FrameSize) / 2.0f;

	Radius = Size.x < Size.y ? Size.x / 2 : Size.y / 2;

	vertexArray[0].position = sf::Vector2f();
	vertexArray[1].position = sf::Vector2f(Size.x, 0.0f);
	vertexArray[2].position = sf::Vector2f(Size.x, Size.y);
	vertexArray[3].position = sf::Vector2f(0.0f, Size.y);
}

void VSprite::updateTransform()
{
	float angle = -Angle * VFRAME_PI / 180.f;
	float cosine = static_cast<float>(std::cos(angle));
	float sine = static_cast<float>(std::sin(angle));
	float sxc = Scale.x * cosine;
	float syc = Scale.y * cosine;
	float sxs = Scale.x * sine;
	float sys = Scale.y * sine;
	float tx = -Origin.x * sxc - Origin.y * sys + (Position + Origin - Offset).x;
	float ty =  Origin.x * sxs - Origin.y * syc + (Position + Origin - Offset).y;

	RenderState.transform =
		sf::Transform(	sxc, sys, tx,
						-sxs, syc, ty,
						0.f, 0.f, 1.f);

	if (vertexArray[0].color != Tint)
	{
		vertexArray[0].color = Tint;
		vertexArray[1].color = Tint;
		vertexArray[2].color = Tint;
		vertexArray[3].color = Tint;
	}
}

void VSprite::updateFrame()
{
	sf::FloatRect rect;
	rect.left		= FlipX ? Animation.GetU() + (float)FrameSize.x : Animation.GetU();
	rect.top		= FlipY ? Animation.GetV() + (float)FrameSize.y : Animation.GetV();
	rect.width		= FlipX ? -(float)FrameSize.x : (float)FrameSize.x;
	rect.height		= FlipY ? -(float)FrameSize.y : (float)FrameSize.y;
	vertexArray[0].texCoords = sf::Vector2f(rect.left,				rect.top);
	vertexArray[1].texCoords = sf::Vector2f(rect.left + rect.width, rect.top);
	vertexArray[2].texCoords = sf::Vector2f(rect.left + rect.width, rect.top + rect.height);
	vertexArray[3].texCoords = sf::Vector2f(rect.left,				rect.top + rect.height);
}

VSprite* VSprite::LoadGraphic(const sf::String& filename, bool animated, int width, int height, const sf::IntRect& area)
{
	RenderState.texture = &VGlobal::p()->Content->LoadTexture(filename);

	setSize(
		area.width == 0 ? RenderState.texture->getSize().x : area.width,
		area.height == 0 ? RenderState.texture->getSize().y : area.height,
		animated, width, height, area.left, area.top
		);

	updateFrame();

	return this;
}

VSprite* VSprite::LoadGraphicFromTexture(sf::Texture& texture, bool animated, int width, int height, const sf::IntRect& area)
{
	RenderState.texture = &texture;

	setSize(
		area.width == 0 ? RenderState.texture->getSize().x : area.width,
		area.height == 0 ? RenderState.texture->getSize().y : area.height,
		animated, width, height, area.left, area.top
		);

	updateFrame();
	return this;
}

VSprite* VSprite::MakeGraphic(int width, int height, sf::Color color, float outline, sf::Color outlineColor)
{
	if (disposible && RenderState.texture)
	{
		if (RenderState.texture->getSize().x == width &&
			RenderState.texture->getSize().y == height)
			return this;

		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}

	sf::Image image;
	image.create(width, height, color);

	for (int y = 0; y < height; y++)
	{
		for (int x = 0; x < width; x++)
		{
			if (x < outline || y < outline || x > width - outline || y > height - outline)
			{
				image.setPixel(x, y, outlineColor);
			}
		}
	}

	sf::Texture* texture = new sf::Texture();
	texture->loadFromImage(image);
	disposible = true;

	RenderState.texture = texture;
	setSize(width, height, false, width, height);

	return this;
}

VSprite* VSprite::MakeGraphicCircle(int radius, sf::Color color, float outline, sf::Color outlineColor)
{
	if (disposible && RenderState.texture)
	{
		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}

	unsigned int diameter = radius * 2;

	sf::Image image;
	image.create(diameter, diameter, sf::Color::Transparent);

	for (unsigned int y = 0; y < diameter; y++)
	{
		for (unsigned int x = 0; x < diameter; x++)
		{
			int dx = radius - x;
			int dy = radius - y;
			int length = (dx * dx) + (dy * dy);

			if (length <= (radius * radius))
			{
				if (outline <= 0 || length <= ((radius - outline) * (radius - outline)))
					image.setPixel(x, y, color);
				else
					image.setPixel(x, y, outlineColor);
			}
		}
	}

	sf::Texture* texture = new sf::Texture();
	texture->loadFromImage(image);
	disposible = true;

	RenderState.texture = texture;
	setSize(radius * 2, radius * 2, false, radius * 2, radius * 2);

	return this;
}

void VSprite::Destroy()
{
	VSUPERCLASS::Destroy();

	if (disposible && RenderState.texture)
	{
		delete RenderState.texture;
		RenderState.texture = nullptr;
		disposible = false;
	}
}

void VSprite::Update(float dt)
{
	VSUPERCLASS::Update(dt);
	Animation.Update(dt);
}

void VSprite::Draw(sf::RenderTarget& RenderTarget)
{
	VSUPERCLASS::Draw(RenderTarget);

	bool updateTexture = false;
	if (Animation.GetLastFrame() != Animation.GetCurrentFrame())
		updateTexture = true;

	if ((FlipX && vertexArray[2].texCoords.x - vertexArray[0].texCoords.x > 0) || (!FlipX && vertexArray[2].texCoords.x - vertexArray[0].texCoords.x < 0))
		updateTexture = true;

	if ((FlipY && vertexArray[2].texCoords.y - vertexArray[0].texCoords.y > 0) || (!FlipY && vertexArray[2].texCoords.y - vertexArray[0].texCoords.y < 0))
		updateTexture = true;

	if (updateTexture)
		updateFrame();

	sf::View renderTargetView = RenderTarget.getView();
	sf::View scrollView = RenderTarget.getDefaultView();

	if (TestInView(renderTargetView, &scrollView, this, RenderState.transform.transformRect(vertexArray.getBounds())))
	{
		RenderTarget.setView(scrollView);
		RenderTarget.draw(vertexArray, RenderState);
		RenderTarget.setView(renderTargetView);
	}
}<|endoftext|>


<commit_before>#include "VirtualMachine.h"
#include <unistd.h>

extern TVMMainEntry VMLoadModule(const char *module);
extern void VMUnloadModule(void);

extern "C"
{

TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[])
{
  TVMMainEntry mainFunc = VMLoadModule(argv[0]);
  if (mainFunc)
  {
    mainFunc(argc, argv);
    // TODO: Handle ticks
    VMUnloadModule();
    return VM_STATUS_SUCCESS;
  }

  return VM_STATUS_FAILURE;
} //VMStart

TVMStatus VMFileWrite(int filedescriptor, void *data, int *length)
{
  if (!data || !length)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
//  MachineFileWrite(filedescriptor, data, length, , );
  if(write(filedescriptor, data, *length))
  {
    return VM_STATUS_SUCCESS;
  }
  return VM_STATUS_FAILURE;
} // VMFileWrite

}//extern?

<commit_msg>extern...<commit_after>#include "VirtualMachine.h"
#include <unistd.h>

extern "C" TVMMainEntry VMLoadModule(const char *module);
extern "C" void VMUnloadModule(void);

TVMStatus VMStart(int tickms, int machinetickms, int argc, char *argv[])
{
  TVMMainEntry mainFunc = VMLoadModule(argv[0]);
  if (mainFunc)
  {
    mainFunc(argc, argv);
    // TODO: Handle ticks
    VMUnloadModule();
    return VM_STATUS_SUCCESS;
  }

  return VM_STATUS_FAILURE;
} //VMStart

TVMStatus VMFileWrite(int filedescriptor, void *data, int *length)
{
  if (!data || !length)
  {
    return VM_STATUS_ERROR_INVALID_PARAMETER;
  }
//  MachineFileWrite(filedescriptor, data, length, , );
  if(write(filedescriptor, data, *length))
  {
    return VM_STATUS_SUCCESS;
  }
  return VM_STATUS_FAILURE;
} // VMFileWrite

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: lockhelper.hxx,v $
 *
 *  $Revision: 1.1 $
 *
 *  last change: $Author: as $ $Date: 2001-06-11 10:11:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_
#define __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_INONCOPYABLE_H_
#include <threadhelp/inoncopyable.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_IMUTEX_H_
#include <threadhelp/imutex.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_IRWLOCK_H_
#include <threadhelp/irwlock.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_FAIRRWLOCK_HXX_
#include <threadhelp/fairrwlock.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @descr          If you use a lock or mutex as a member of your class and whish to use it earlier then other ones
                    you should have a look on this implementation. You must use it as the first base class
                    of your implementation - because base classes are initialized by his order and before your
                    member! Thats why ist a good place to declare your thread help member so.
*//*-*************************************************************************************************************/
enum ELockType
{
    E_NOTHING       = 0 ,
    E_OWNMUTEX      = 1 ,
    E_SOLARMUTEX    = 2 ,
    E_FAIRRWLOCK    = 3
};

#define ENVVAR_LOCKTYPE     DECLARE_ASCII("LOCKTYPE_FRAMEWORK")
#define FALLBACK_LOCKTYPE   E_OWNMUTEX

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          helper to set right lock in right situation
    @descr          This helper support different types of locking:
                        a)  no locks - transparent for user!
                            This could be usefull for simluation or single threaded environments!
                        b)  own mutex
                            An object use his own osl-mutex to be threadsafe. Usefull for easy and exclusiv locking.
                        c)  solar mutex
                            An object use our solar mutex and will be a part of a greater safed "threadsafe code block".
                            Could be usefull for simulation and testing of higher modules!
                        d)  fair rw-lock
                            An object use an implementation of a fair rw-lock. This increase granularity of t hreadsafe mechanism
                            and should be used for high performance threadsafe code!

    @attention      We support two interfaces - "IMutex" and "IRWLock". Don't mix using of it!
                    A guard implementation should use one interface only!

    @implements     IMutex
    @implements     IRWLock

    @base           INonCopyable
                    IMutex
                    IRWLock

    @devstatus      draft
*//*-*************************************************************************************************************/
class LockHelper : public  IMutex
                 , public  IRWLock
                 , private INonCopyable
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------
    public:

        //-------------------------------------------------------------------------------------------------------------
        //  ctor/dtor
        //-------------------------------------------------------------------------------------------------------------
                 LockHelper( ::vos::IMutex* pSolarMutex = NULL );
        virtual ~LockHelper(                                   );

        //-------------------------------------------------------------------------------------------------------------
        //  interface ::framework::IMutex
        //-------------------------------------------------------------------------------------------------------------
        virtual void acquire();
        virtual void release();

        //-------------------------------------------------------------------------------------------------------------
        //  interface ::framework::IRWLock
        //-------------------------------------------------------------------------------------------------------------
        virtual void acquireReadAccess   ();
        virtual void releaseReadAccess   ();
        virtual void acquireWriteAccess  ();
        virtual void releaseWriteAccess  ();
        virtual void downgradeWriteAccess();

        //-------------------------------------------------------------------------------------------------------------
        //  something else
        //-------------------------------------------------------------------------------------------------------------
        static LockHelper&  getGlobalLock       ( ::vos::IMutex* pSolarMutex = NULL );
        ::osl::Mutex&       getShareableOslMutex(                                   );

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------
    private:

        static ELockType& implts_getLockType();

    //-------------------------------------------------------------------------------------------------------------
    //  private member
    //  a) Make some member mutable for using in const functions!
    //  b) "m_eLockType" define, which of follow members is used!
    //     You can use "m_pFairRWLock" as a fair rw-lock (multiple reader / one writer / looks for incoming order of threads too) ...
    //     or you can use a normal osl mutex ("m_pOwnMutex") ...
    //     ... or the solarmuex as "m_pSolarMutex" (must be set from outside! because some components must be vcl-free!)
    //     ... but sometimes you need a shareable osl mutex!
    //     In this case you has some problems: i  ) If your lock type is set to E_OWNMUTEX => it's easy; you can use your member "m_pOwnMutex" - it's a osl mutex.
    //                                              Creation and using of "m_pShareableOslMutex" isn't neccessary!
    //                                         ii ) Otherwise you have no osl mutex ... so you must create "m_pShareableOslMutex" and use it twice!
    //                                              In this case you must lock two member everytime - "m_pShareableMutex" AND "m_pFairRWLock" or "m_pSolarMutex" or ...
    //                                              It isn't realy fine - but the only possible way.
    //                                         iii) There exist another special case - E_NOTHING is set! Then we should create this shareable mutex ...
    //                                              nad you can use it ... but this implmentation ignore it.
    //-------------------------------------------------------------------------------------------------------------
    private:

        ELockType               m_eLockType             ;

        mutable FairRWLock*     m_pFairRWLock           ;
        mutable ::osl::Mutex*   m_pOwnMutex             ;
        mutable ::vos::IMutex*  m_pSolarMutex           ;
        mutable ::osl::Mutex*   m_pShareableOslMutex    ;
};

}       //  namespace framework

#endif  //  #ifndef __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_
<commit_msg>#85529# use solar mutex as default<commit_after>/*************************************************************************
 *
 *  $RCSfile: lockhelper.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: as $ $Date: 2001-06-26 05:28:51 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#ifndef __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_
#define __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_

//_________________________________________________________________________________________________________________
//  my own includes
//_________________________________________________________________________________________________________________

#ifndef __FRAMEWORK_THREADHELP_INONCOPYABLE_H_
#include <threadhelp/inoncopyable.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_IMUTEX_H_
#include <threadhelp/imutex.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_IRWLOCK_H_
#include <threadhelp/irwlock.h>
#endif

#ifndef __FRAMEWORK_THREADHELP_FAIRRWLOCK_HXX_
#include <threadhelp/fairrwlock.hxx>
#endif

//_________________________________________________________________________________________________________________
//  interface includes
//_________________________________________________________________________________________________________________

//_________________________________________________________________________________________________________________
//  other includes
//_________________________________________________________________________________________________________________

#ifndef _OSL_MUTEX_HXX_
#include <osl/mutex.hxx>
#endif

#ifndef _VOS_MUTEX_HXX_
#include <vos/mutex.hxx>
#endif

//_________________________________________________________________________________________________________________
//  namespace
//_________________________________________________________________________________________________________________

namespace framework{

//_________________________________________________________________________________________________________________
//  const
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @descr          If you use a lock or mutex as a member of your class and whish to use it earlier then other ones
                    you should have a look on this implementation. You must use it as the first base class
                    of your implementation - because base classes are initialized by his order and before your
                    member! Thats why ist a good place to declare your thread help member so.
*//*-*************************************************************************************************************/
enum ELockType
{
    E_NOTHING       = 0 ,
    E_OWNMUTEX      = 1 ,
    E_SOLARMUTEX    = 2 ,
    E_FAIRRWLOCK    = 3
};

#define ENVVAR_LOCKTYPE     DECLARE_ASCII("LOCKTYPE_FRAMEWORK")
#define FALLBACK_LOCKTYPE   E_SOLARMUTEX

//_________________________________________________________________________________________________________________
//  declarations
//_________________________________________________________________________________________________________________

/*-************************************************************************************************************//**
    @short          helper to set right lock in right situation
    @descr          This helper support different types of locking:
                        a)  no locks - transparent for user!
                            This could be usefull for simluation or single threaded environments!
                        b)  own mutex
                            An object use his own osl-mutex to be threadsafe. Usefull for easy and exclusiv locking.
                        c)  solar mutex
                            An object use our solar mutex and will be a part of a greater safed "threadsafe code block".
                            Could be usefull for simulation and testing of higher modules!
                        d)  fair rw-lock
                            An object use an implementation of a fair rw-lock. This increase granularity of t hreadsafe mechanism
                            and should be used for high performance threadsafe code!

    @attention      We support two interfaces - "IMutex" and "IRWLock". Don't mix using of it!
                    A guard implementation should use one interface only!

    @implements     IMutex
    @implements     IRWLock

    @base           INonCopyable
                    IMutex
                    IRWLock

    @devstatus      draft
*//*-*************************************************************************************************************/
class LockHelper : public  IMutex
                 , public  IRWLock
                 , private INonCopyable
{
    //-------------------------------------------------------------------------------------------------------------
    //  public methods
    //-------------------------------------------------------------------------------------------------------------
    public:

        //-------------------------------------------------------------------------------------------------------------
        //  ctor/dtor
        //-------------------------------------------------------------------------------------------------------------
                 LockHelper( ::vos::IMutex* pSolarMutex = NULL );
        virtual ~LockHelper(                                   );

        //-------------------------------------------------------------------------------------------------------------
        //  interface ::framework::IMutex
        //-------------------------------------------------------------------------------------------------------------
        virtual void acquire();
        virtual void release();

        //-------------------------------------------------------------------------------------------------------------
        //  interface ::framework::IRWLock
        //-------------------------------------------------------------------------------------------------------------
        virtual void acquireReadAccess   ();
        virtual void releaseReadAccess   ();
        virtual void acquireWriteAccess  ();
        virtual void releaseWriteAccess  ();
        virtual void downgradeWriteAccess();

        //-------------------------------------------------------------------------------------------------------------
        //  something else
        //-------------------------------------------------------------------------------------------------------------
        static LockHelper&  getGlobalLock       ( ::vos::IMutex* pSolarMutex = NULL );
        ::osl::Mutex&       getShareableOslMutex(                                   );

    //-------------------------------------------------------------------------------------------------------------
    //  private methods
    //-------------------------------------------------------------------------------------------------------------
    private:

        static ELockType& implts_getLockType();

    //-------------------------------------------------------------------------------------------------------------
    //  private member
    //  a) Make some member mutable for using in const functions!
    //  b) "m_eLockType" define, which of follow members is used!
    //     You can use "m_pFairRWLock" as a fair rw-lock (multiple reader / one writer / looks for incoming order of threads too) ...
    //     or you can use a normal osl mutex ("m_pOwnMutex") ...
    //     ... or the solarmuex as "m_pSolarMutex" (must be set from outside! because some components must be vcl-free!)
    //     ... but sometimes you need a shareable osl mutex!
    //     In this case you has some problems: i  ) If your lock type is set to E_OWNMUTEX => it's easy; you can use your member "m_pOwnMutex" - it's a osl mutex.
    //                                              Creation and using of "m_pShareableOslMutex" isn't neccessary!
    //                                         ii ) Otherwise you have no osl mutex ... so you must create "m_pShareableOslMutex" and use it twice!
    //                                              In this case you must lock two member everytime - "m_pShareableMutex" AND "m_pFairRWLock" or "m_pSolarMutex" or ...
    //                                              It isn't realy fine - but the only possible way.
    //                                         iii) There exist another special case - E_NOTHING is set! Then we should create this shareable mutex ...
    //                                              nad you can use it ... but this implmentation ignore it.
    //-------------------------------------------------------------------------------------------------------------
    private:

        ELockType               m_eLockType             ;

        mutable FairRWLock*     m_pFairRWLock           ;
        mutable ::osl::Mutex*   m_pOwnMutex             ;
        mutable ::vos::IMutex*  m_pSolarMutex           ;
        mutable ::osl::Mutex*   m_pShareableOslMutex    ;
};

}       //  namespace framework

#endif  //  #ifndef __FRAMEWORK_THREADHELP_LOCKHELPER_HXX_
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DeformableRegistration2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

// Software Guide : BeginLatex
//
// This example demostrates how to use the ``demons'' algorithm to deformably
// register two images. The first step is to include the header files:
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkDemonsRegistrationFilter.h"
#include "itkHistogramMatchingImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet

int main( int argc, char **argv )
{
  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " fixedImageFile movingImageFile ";
    std::cerr << " outputImageFile " << std::endl;
    return 1;
    }

  // Software Guide : BeginLatex
  //
  // Second, we declare the types of the images.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int Dimension = 2;
  typedef unsigned short PixelType;

  typedef itk::Image< PixelType, Dimension >  FixedImageType;
  typedef itk::Image< PixelType, Dimension >  MovingImageType;
  // Software Guide : EndCodeSnippet

  // Set up the file readers
  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;

  FixedImageReaderType::Pointer fixedImageReader   = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName( argv[1] );
  movingImageReader->SetFileName( argv[2] );

  // Software Guide : BeginLatex
  //
  // Image file readers are set up in a similar fashion to previous examples.
  // To support the re-mapping of the moving image intensity we declare an
  // internal image type with a floating point pixel type and cast the input
  // images to the internal image type.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef float InternalPixelType;
  typedef itk::Image< InternalPixelType, Dimension > InternalImageType;

  typedef itk::CastImageFilter< FixedImageType, InternalImageType > FixedImageCasterType;
  typedef itk::CastImageFilter< MovingImageType, InternalImageType > MovingImageCasterType;

  FixedImageCasterType::Pointer fixedImageCaster   = FixedImageCasterType::New();
  MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New();

  fixedImageCaster->SetInput( fixedImageReader->GetOutput() );
  movingImageCaster->SetInput( movingImageReader->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The demons algorithm relies on the assumption that pixels representing the
  // same homologous point on an object have the same intensity on both the
  // fixed and moving images to be registered. In this example, we will
  // preprocess the moving image to match the intensity between the images
  // using the \doxygen{HistogramMatchingImageFilter}.
  //
  // \index{itk::HistogramMatchingImageFilter|textbf}
  //
  // The basic idea is to match the histograms of the two images at a user
  // specified number of quantile values. For robustness, the histograms are
  // matched so that the background pixels are excluded from both histograms.
  // For MR images, a simple procedure is to exclude all gray values that are
  // smaller than the mean gray value of the image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::HistogramMatchingImageFilter<
              InternalImageType,InternalImageType >  MatchingFilterType;

  MatchingFilterType::Pointer matcher = MatchingFilterType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // For this example, we set the moving image as the source or input image and
  // the fixed image as the reference image.
  //
  // \index{itk::HistogramMatchingImageFilter!SetInput()}
  // \index{itk::HistogramMatchingImageFilter!SetSourceImage()}
  // \index{itk::HistogramMatchingImageFilter!SetReferenceImage()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->SetInput( movingImageCaster->GetOutput() );
  matcher->SetReferenceImage( fixedImageCaster->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We then select the number of bins to represent the histograms and the number
  // of points or quantiles values where are to be matched.
  //
  // \index{itk::HistogramMatchingImageFilter!SetNumberOfHistogramLevels()}
  // \index{itk::HistogramMatchingImageFilter!SetNumberOfMatchPoints()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->SetNumberOfHistogramLevels( 1024 );
  matcher->SetNumberOfMatchPoints( 7 );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Simple background extraction is done by thresholding at the mean intensity.
  //
  // \index{itk::HistogramMatchingImageFilter!ThresholdAtMeanIntensityOn()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->ThresholdAtMeanIntensityOn();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // In the \code{DemonsRegistrationFilter}, the deformation field is represented
  // as an image whose pixels are floating point vectors.
  //
  // \index{itk::DemonsRegistrationFilter|textbf}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Vector<float,Dimension> VectorPixelType;
  typedef itk::Image<VectorPixelType,Dimension> DeformationFieldType;

  typedef itk::DemonsRegistrationFilter<
    InternalImageType,InternalImageType,DeformationFieldType> RegistrationFilterType;

  RegistrationFilterType::Pointer filter = RegistrationFilterType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The input fixed image is simply the output of the fixed image casting filter.
  // The input moving image is the output of the histogram matching filter.
  //
  // \index{itk::DemonsRegistrationFilter!SetFixedImage()}
  // \index{itk::DemonsRegistrationFilter!SetMovingImage()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetFixedImage( fixedImageCaster->GetOutput() );
  filter->SetMovingImage( matcher->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The demons registration filter has two parameters: the number of iterations to
  // be performed and the standard deviation of the Gaussian smoothing kernel to
  // be applied to the deformation field after each iteration.
  // \index{itk::DemonsRegistrationFilter!SetNumberOfIterations()}
  // \index{itk::DemonsRegistrationFilter!SetStandardDeviations()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetNumberOfIterations( 150 );
  filter->SetStandardDeviations( 1.0 );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The registration algorithm is triggered by updating the filter. The filter
  // output is the computed deformation field.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->Update();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // A \code{WarpImageFilter} can be used to warp the moving image with the
  // output deformation field. Similar to the \code{ResampleImageFilter}, the
  // \code{WarpImageFilter} requires the specification of the input image to be
  // resampled, an input image interpolator, the output image spacing and
  // origin.
  //
  // \index{itk::WarpImageFilter|textbf}
  // \index{itk::WarpImageFilter!SetInput()}
  // \index{itk::WarpImageFilter!SetInterpolator()}
  // \index{itk::WarpImageFilter!SetOutputSpacing()}
  // \index{itk::WarpImageFilter!SetOutputOrigin()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::WarpImageFilter<
    MovingImageType, MovingImageType, DeformationFieldType >  WarperType;
  typedef itk::LinearInterpolateImageFunction<
                                   MovingImageType, double >  InterpolatorType;

  WarperType::Pointer warper = WarperType::New();
  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();

  warper->SetInput( movingImageReader->GetOutput() );
  warper->SetInterpolator( interpolator );
  warper->SetOutputSpacing( fixedImage->GetSpacing() );
  warper->SetOutputOrigin( fixedImage->GetOrigin() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Unlike the \code{ResampleImageFilter}, the \code{WarpImageFilter} warps or transform
  // the input image with respect to the deformation field represented by an image of vectors.
  // The resulting warped or resampled image is written to file as per previous examples.
  //
  // \index{itk::WarpImageFilter!SetDeformationField()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  warper->SetDeformationField( filter->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Write warped image out to file
  typedef  unsigned char  OutputPixelType;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  typedef itk::CastImageFilter<
                        MovingImageType,
                        OutputImageType > CastFilterType;

  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  WriterType::Pointer      writer =  WriterType::New();
  CastFilterType::Pointer  caster =  CastFilterType::New();

  writer->SetFileName( argv[3] );

  caster->SetInput( warper->GetOutput() );
  writer->SetInput( caster->GetOutput()   );
  writer->Update();

  // Software Guide : BeginLatex
  //
  // Let's execute this example using rat lung data in the previous example.
  // The associated data files can be found in \code{Insight/Examples/Data}:
  // \begin{itemize}
  // \item \code{RatLungSlice1.mha}
  // \item \code{RatLungSlice2.mha}
  // \end{itemize}
  //
  // \begin{figure} \center
  // \includegraphics[width=8cm]{DeformableRegistration2CheckerboardBefore.eps}
  // \includegraphics[width=8cm]{DeformableRegistration2CheckerboardAfter.eps}
  // \caption[Demon's deformable registration output]{Checkerboard comparisons
  // before and after demons-based deformable registration.}
  // \label{fig:DeformableRegistration2Output}
  // \end{figure}
  //
  // The results of the demons-based deformable registration is presented in
  // Figure \ref{fig:DeformableRegistration2Output}. The checkerboard
  // comparision shows that the algorithm was able to recover the misalignment
  // due to expiration.
  //
  // Software Guide : EndLatex

  return 0;

}

<commit_msg>DOC: Formatting details for LaTeX.<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    DeformableRegistration2.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/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 notices for more information.

=========================================================================*/

#include "itkImageFileReader.h"
#include "itkImageFileWriter.h"

// Software Guide : BeginLatex
//
// This example demostrates how to use the ``demons'' algorithm to deformably
// register two images. The first step is to include the header files:
//
// Software Guide : EndLatex

// Software Guide : BeginCodeSnippet
#include "itkDemonsRegistrationFilter.h"
#include "itkHistogramMatchingImageFilter.h"
#include "itkCastImageFilter.h"
#include "itkWarpImageFilter.h"
#include "itkLinearInterpolateImageFunction.h"
// Software Guide : EndCodeSnippet

int main( int argc, char **argv )
{
  if( argc < 3 )
    {
    std::cerr << "Missing Parameters " << std::endl;
    std::cerr << "Usage: " << argv[0];
    std::cerr << " fixedImageFile movingImageFile ";
    std::cerr << " outputImageFile " << std::endl;
    return 1;
    }

  // Software Guide : BeginLatex
  //
  // Second, we declare the types of the images.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  const unsigned int Dimension = 2;
  typedef unsigned short PixelType;

  typedef itk::Image< PixelType, Dimension >  FixedImageType;
  typedef itk::Image< PixelType, Dimension >  MovingImageType;
  // Software Guide : EndCodeSnippet

  // Set up the file readers
  typedef itk::ImageFileReader< FixedImageType  > FixedImageReaderType;
  typedef itk::ImageFileReader< MovingImageType > MovingImageReaderType;

  FixedImageReaderType::Pointer fixedImageReader   = FixedImageReaderType::New();
  MovingImageReaderType::Pointer movingImageReader = MovingImageReaderType::New();

  fixedImageReader->SetFileName( argv[1] );
  movingImageReader->SetFileName( argv[2] );

  // Software Guide : BeginLatex
  //
  // Image file readers are set up in a similar fashion to previous examples.
  // To support the re-mapping of the moving image intensity we declare an
  // internal image type with a floating point pixel type and cast the input
  // images to the internal image type.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef float InternalPixelType;
  typedef itk::Image< InternalPixelType, Dimension > InternalImageType;

  typedef itk::CastImageFilter< FixedImageType, InternalImageType > FixedImageCasterType;
  typedef itk::CastImageFilter< MovingImageType, InternalImageType > MovingImageCasterType;

  FixedImageCasterType::Pointer fixedImageCaster   = FixedImageCasterType::New();
  MovingImageCasterType::Pointer movingImageCaster = MovingImageCasterType::New();

  fixedImageCaster->SetInput( fixedImageReader->GetOutput() );
  movingImageCaster->SetInput( movingImageReader->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The demons algorithm relies on the assumption that pixels representing the
  // same homologous point on an object have the same intensity on both the
  // fixed and moving images to be registered. In this example, we will
  // preprocess the moving image to match the intensity between the images
  // using the \doxygen{HistogramMatchingImageFilter}.
  //
  // \index{itk::HistogramMatchingImageFilter|textbf}
  //
  // The basic idea is to match the histograms of the two images at a user
  // specified number of quantile values. For robustness, the histograms are
  // matched so that the background pixels are excluded from both histograms.
  // For MR images, a simple procedure is to exclude all gray values that are
  // smaller than the mean gray value of the image.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::HistogramMatchingImageFilter<
                                    InternalImageType,
                                    InternalImageType >   MatchingFilterType;

  MatchingFilterType::Pointer matcher = MatchingFilterType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // For this example, we set the moving image as the source or input image and
  // the fixed image as the reference image.
  //
  // \index{itk::HistogramMatchingImageFilter!SetInput()}
  // \index{itk::HistogramMatchingImageFilter!SetSourceImage()}
  // \index{itk::HistogramMatchingImageFilter!SetReferenceImage()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->SetInput( movingImageCaster->GetOutput() );
  matcher->SetReferenceImage( fixedImageCaster->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // We then select the number of bins to represent the histograms and the number
  // of points or quantiles values where are to be matched.
  //
  // \index{itk::HistogramMatchingImageFilter!SetNumberOfHistogramLevels()}
  // \index{itk::HistogramMatchingImageFilter!SetNumberOfMatchPoints()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->SetNumberOfHistogramLevels( 1024 );
  matcher->SetNumberOfMatchPoints( 7 );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Simple background extraction is done by thresholding at the mean intensity.
  //
  // \index{itk::HistogramMatchingImageFilter!ThresholdAtMeanIntensityOn()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  matcher->ThresholdAtMeanIntensityOn();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // In the \doxygen{DemonsRegistrationFilter}, the deformation field is represented
  // as an image whose pixels are floating point vectors.
  //
  // \index{itk::DemonsRegistrationFilter|textbf}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::Vector< float, Dimension >    VectorPixelType;

  typedef itk::Image<  VectorPixelType, Dimension > DeformationFieldType;

  typedef itk::DemonsRegistrationFilter<
                                InternalImageType,
                                InternalImageType,
                                DeformationFieldType>   RegistrationFilterType;

  RegistrationFilterType::Pointer filter = RegistrationFilterType::New();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The input fixed image is simply the output of the fixed image casting filter.
  // The input moving image is the output of the histogram matching filter.
  //
  // \index{itk::DemonsRegistrationFilter!SetFixedImage()}
  // \index{itk::DemonsRegistrationFilter!SetMovingImage()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetFixedImage( fixedImageCaster->GetOutput() );
  filter->SetMovingImage( matcher->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The demons registration filter has two parameters: the number of iterations to
  // be performed and the standard deviation of the Gaussian smoothing kernel to
  // be applied to the deformation field after each iteration.
  // \index{itk::DemonsRegistrationFilter!SetNumberOfIterations()}
  // \index{itk::DemonsRegistrationFilter!SetStandardDeviations()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->SetNumberOfIterations( 150 );
  filter->SetStandardDeviations( 1.0 );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // The registration algorithm is triggered by updating the filter. The filter
  // output is the computed deformation field.
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  filter->Update();
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // A \doxygen{WarpImageFilter} can be used to warp the moving image with the
  // output deformation field. Similar to the \doxygen{ResampleImageFilter}, the
  // \doxygen{WarpImageFilter} requires the specification of the input image to be
  // resampled, an input image interpolator, the output image spacing and
  // origin.
  //
  // \index{itk::WarpImageFilter|textbf}
  // \index{itk::WarpImageFilter!SetInput()}
  // \index{itk::WarpImageFilter!SetInterpolator()}
  // \index{itk::WarpImageFilter!SetOutputSpacing()}
  // \index{itk::WarpImageFilter!SetOutputOrigin()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  typedef itk::WarpImageFilter<
                          MovingImageType,
                          MovingImageType,
                          DeformationFieldType  >     WarperType;

  typedef itk::LinearInterpolateImageFunction<
                                   MovingImageType,
                                   double          >  InterpolatorType;

  WarperType::Pointer warper = WarperType::New();
  InterpolatorType::Pointer interpolator = InterpolatorType::New();

  FixedImageType::Pointer fixedImage = fixedImageReader->GetOutput();

  warper->SetInput( movingImageReader->GetOutput() );
  warper->SetInterpolator( interpolator );
  warper->SetOutputSpacing( fixedImage->GetSpacing() );
  warper->SetOutputOrigin( fixedImage->GetOrigin() );
  // Software Guide : EndCodeSnippet

  // Software Guide : BeginLatex
  //
  // Unlike the \doxygen{ResampleImageFilter}, the \doxygen{WarpImageFilter} warps or transform
  // the input image with respect to the deformation field represented by an image of vectors.
  // The resulting warped or resampled image is written to file as per previous examples.
  //
  // \index{itk::WarpImageFilter!SetDeformationField()}
  //
  // Software Guide : EndLatex

  // Software Guide : BeginCodeSnippet
  warper->SetDeformationField( filter->GetOutput() );
  // Software Guide : EndCodeSnippet

  // Write warped image out to file
  typedef  unsigned char  OutputPixelType;

  typedef itk::Image< OutputPixelType, Dimension > OutputImageType;

  typedef itk::CastImageFilter<
                        MovingImageType,
                        OutputImageType > CastFilterType;

  typedef itk::ImageFileWriter< OutputImageType >  WriterType;

  WriterType::Pointer      writer =  WriterType::New();
  CastFilterType::Pointer  caster =  CastFilterType::New();

  writer->SetFileName( argv[3] );

  caster->SetInput( warper->GetOutput() );
  writer->SetInput( caster->GetOutput()   );
  writer->Update();

  // Software Guide : BeginLatex
  //
  // Let's execute this example using rat lung data in the previous example.
  // The associated data files can be found in \code{Insight/Examples/Data}:
  // \begin{itemize}
  // \item \code{RatLungSlice1.mha}
  // \item \code{RatLungSlice2.mha}
  // \end{itemize}
  //
  // \begin{figure} \center
  // \includegraphics[width=8cm]{DeformableRegistration2CheckerboardBefore.eps}
  // \includegraphics[width=8cm]{DeformableRegistration2CheckerboardAfter.eps}
  // \caption[Demon's deformable registration output]{Checkerboard comparisons
  // before and after demons-based deformable registration.}
  // \label{fig:DeformableRegistration2Output}
  // \end{figure}
  //
  // The results of the demons-based deformable registration is presented in
  // Figure \ref{fig:DeformableRegistration2Output}. The checkerboard
  // comparision shows that the algorithm was able to recover the misalignment
  // due to expiration.
  //
  // Software Guide : EndLatex

  return 0;

}

<|endoftext|>


<commit_before>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include "MQ/Web/SubscriptionMapper.h"

#include "Poco/HexBinaryDecoder.h"

namespace MQ {
namespace Web {

SubscriptionMapper::SubscriptionMapper(CommandServer& commandServer, Poco::JSON::Object::Ptr input)
: MQMapper(commandServer, "Topic", input)
{
}

SubscriptionMapper::~SubscriptionMapper()
{
}

void SubscriptionMapper::change()
{
	poco_assert_dbg(false); // Not yet implemented
}

void SubscriptionMapper::create(bool replace)
{
  poco_assert_dbg(false); // Not yet implemented
}

void SubscriptionMapper::copy(bool replace)
{
	poco_assert_dbg(false); // Not yet implemented
}

Poco::JSON::Array::Ptr SubscriptionMapper::inquire()
{
	createCommand(MQCMD_INQUIRE_SUBSCRIPTION);

	// Required parameters
	addParameter<std::string>(MQCACF_SUB_NAME, "SubName");

	if ( _input->has("SubId") )
	{
		std::string hexId = _input->get("SubId");
		BufferPtr id = new Buffer(hexId.size() / 2);

		std::istringstream iss(hexId);
		Poco::HexBinaryDecoder decoder(iss);
		int c = decoder.get();
		int i = 0;
		while (c != -1 && i < id->size())
		{
			id[i++] = (unsigned char) c;
			c = decoder.get();
		}

		pcf()->addParameter(MQBACF_SUB_ID, id);
	}

	// Optional parameters
	addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope");
	addParameter<MQLONG>(MQIACF_DURABLE_SUBSCRIPTION, "Durable");
	addAttributeList(MQIACF_SUB_ATTRS, "SubscriptionAttrs");
	addParameterNumFromString(MQIACF_SUB_TYPE, "SubscriptionType");

	PCF::Vector commandResponse;
	execute(commandResponse);

	Poco::JSON::Array::Ptr json = new Poco::JSON::Array();
	for(PCF::Vector::iterator it = commandResponse.begin(); it != commandResponse.end(); it++)
	{
		if ( (*it)->getReasonCode() != MQRC_NONE ) // Skip errors (2035 not authorized for example)
			continue;

		if ( (*it)->isExtendedResponse() ) // Skip extended response
			continue;

		json->add(createJSON(**it));
	}

	return json;
}

}} //  Namespace MQ::Web
<commit_msg>Objecttype must be Sub<commit_after>/*
 * Copyright 2010 MQWeb - Franky Braem
 *
 * Licensed under the EUPL, Version 1.1 or - as soon they
 * will be approved by the European Commission - subsequent
 * versions of the EUPL (the "Licence");
 * You may not use this work except in compliance with the
 * Licence.
 * You may obtain a copy of the Licence at:
 *
 * http://joinup.ec.europa.eu/software/page/eupl
 *
 * Unless required by applicable law or agreed to in
 * writing, software distributed under the Licence is
 * distributed on an "AS IS" basis,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
 * express or implied.
 * See the Licence for the specific language governing
 * permissions and limitations under the Licence.
 */
#include "MQ/Web/SubscriptionMapper.h"

#include "Poco/HexBinaryDecoder.h"

namespace MQ {
namespace Web {

SubscriptionMapper::SubscriptionMapper(CommandServer& commandServer, Poco::JSON::Object::Ptr input)
: MQMapper(commandServer, "Sub", input)
{
}

SubscriptionMapper::~SubscriptionMapper()
{
}

void SubscriptionMapper::change()
{
	poco_assert_dbg(false); // Not yet implemented
}

void SubscriptionMapper::create(bool replace)
{
  poco_assert_dbg(false); // Not yet implemented
}

void SubscriptionMapper::copy(bool replace)
{
	poco_assert_dbg(false); // Not yet implemented
}

Poco::JSON::Array::Ptr SubscriptionMapper::inquire()
{
	createCommand(MQCMD_INQUIRE_SUBSCRIPTION);

	// Required parameters
	addParameter<std::string>(MQCACF_SUB_NAME, "SubName");

	if ( _input->has("SubId") )
	{
		std::string hexId = _input->get("SubId");
		BufferPtr id = new Buffer(hexId.size() / 2);

		std::istringstream iss(hexId);
		Poco::HexBinaryDecoder decoder(iss);
		int c = decoder.get();
		int i = 0;
		while (c != -1 && i < id->size())
		{
			id[i++] = (unsigned char) c;
			c = decoder.get();
		}

		pcf()->addParameter(MQBACF_SUB_ID, id);
	}

	// Optional parameters
	addParameter<std::string>(MQCACF_COMMAND_SCOPE, "CommandScope");
	addParameter<MQLONG>(MQIACF_DURABLE_SUBSCRIPTION, "Durable");
	addAttributeList(MQIACF_SUB_ATTRS, "SubscriptionAttrs");
	addParameterNumFromString(MQIACF_SUB_TYPE, "SubscriptionType");

	PCF::Vector commandResponse;
	execute(commandResponse);

	Poco::JSON::Array::Ptr json = new Poco::JSON::Array();
	for(PCF::Vector::iterator it = commandResponse.begin(); it != commandResponse.end(); it++)
	{
		if ( (*it)->getReasonCode() != MQRC_NONE ) // Skip errors (2035 not authorized for example)
			continue;

		if ( (*it)->isExtendedResponse() ) // Skip extended response
			continue;

		json->add(createJSON(**it));
	}

	return json;
}

}} //  Namespace MQ::Web
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * 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.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------------------
/// \class AliMUONRawStreamTrigger
/// This class provides access to MUON digits in raw data.
///
/// It loops over all MUON digits in the raw data given by the AliRawReader.
/// The Next method goes to the next local response. If there are no local response left
/// it returns kFALSE.
/// It can loop also over DDL and store the decoded rawdata in TClonesArrays
/// in payload class.
///
/// Version implement for Trigger
/// \author Christian Finck
//-----------------------------------------------------------------------------

#include <TArrayS.h>

#include "AliMUONRawStreamTrigger.h"
#include "AliMUONDarcHeader.h"
#include "AliMUONRegHeader.h"
#include "AliMUONLocalStruct.h"
#include "AliMUONDDLTrigger.h"
#include "AliMUONLogger.h"

#include "AliRawReader.h"
#include "AliRawDataHeader.h"
#include "AliDAQ.h"
#include "AliLog.h"

#include <cassert>

/// \cond CLASSIMP
ClassImp(AliMUONRawStreamTrigger)
/// \endcond

const Int_t AliMUONRawStreamTrigger::fgkMaxDDL = 2;

//___________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger(TRootIOCtor* /*dummy*/)
:   AliMUONVRawStreamTrigger(),
fPayload(0x0),
fCurrentDDL(0x0),
fCurrentDDLIndex(fgkMaxDDL),
fCurrentDarcHeader(0x0),
fCurrentRegHeader(0x0),
fCurrentRegHeaderIndex(0),
fCurrentLocalStruct(0x0),
fCurrentLocalStructIndex(0),
fLocalStructRead(kFALSE),
fDDL(0),
fNextDDL(kFALSE)
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor with no mem allocation for I/O
  ///
}

//___________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger()
:   AliMUONVRawStreamTrigger(),
    fPayload(new AliMUONPayloadTrigger()),
    fCurrentDDL(0x0),
    fCurrentDDLIndex(fgkMaxDDL),
    fCurrentDarcHeader(0x0),
    fCurrentRegHeader(0x0),
    fCurrentRegHeaderIndex(0),
    fCurrentLocalStruct(0x0),
    fCurrentLocalStructIndex(0),
    fLocalStructRead(kFALSE),
    fDDL(0),
    fNextDDL(kFALSE)
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor for monitoring purposes
  ///

}

//_________________________________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger(AliRawReader* rawReader)
  : AliMUONVRawStreamTrigger(rawReader),
    fPayload(new AliMUONPayloadTrigger()),
    fCurrentDDL(0x0),
    fCurrentDDLIndex(fgkMaxDDL),
    fCurrentDarcHeader(0x0),
    fCurrentRegHeader(0x0),
    fCurrentRegHeaderIndex(0),
    fCurrentLocalStruct(0x0),
    fCurrentLocalStructIndex(0),
    fLocalStructRead(kFALSE),
    fDDL(0),
    fNextDDL(kFALSE)
{
  ///
  /// ctor with AliRawReader as argument
  /// for reconstruction purpose
  ///

}

//___________________________________
AliMUONRawStreamTrigger::~AliMUONRawStreamTrigger()
{
  ///
  /// clean up
  ///
  delete fPayload;
}

//_____________________________________________________________
Bool_t AliMUONRawStreamTrigger::Next(UChar_t& id,   UChar_t& dec,      Bool_t& trigY,
				     UChar_t& yPos, UChar_t& sXDev,    UChar_t& xDev,
				     UChar_t& xPos, Bool_t& triggerY,  Bool_t& triggerX,
				     TArrayS& xPattern, TArrayS& yPattern)
{
  ///
  /// read the next raw digit (local structure)
  /// returns kFALSE if there is no digit left
  /// Should call First() before this method to start the iteration.
  ///

  if ( IsDone() ) return kFALSE;

  if ( fLocalStructRead ) {

    Bool_t ok = GetNextLocalStruct();
    if (!ok)
    {
      // this is the end
      return kFALSE;
    }
  }

  fLocalStructRead = kTRUE;

  id    = fCurrentLocalStruct->GetId();
  dec   = fCurrentLocalStruct->GetDec();
  trigY = fCurrentLocalStruct->GetTrigY();
  yPos  = fCurrentLocalStruct->GetYPos();
  sXDev = fCurrentLocalStruct->GetSXDev();
  xDev  = fCurrentLocalStruct->GetXDev();
  xPos  = fCurrentLocalStruct->GetXPos();

  triggerX = fCurrentLocalStruct->GetTriggerX();
  triggerY = fCurrentLocalStruct->GetTriggerY();

  fCurrentLocalStruct->GetXPattern(xPattern);
  fCurrentLocalStruct->GetYPattern(yPattern);

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::IsDone() const
{
  /// Whether the iteration is finished or not
  return (fCurrentLocalStruct==0);
}

//______________________________________________________
void AliMUONRawStreamTrigger::First()
{
  /// Initialize the iteration process.

  fCurrentDDLIndex = -1;
  // Must reset all the pointers because if we return before calling
  // GetNextLocalStruct() the user might call CurrentDDL(), CurrentBlockHeader(),
  // CurrentRegHeader() or CurrentLocalStruct() which should return reasonable
  // results in that case.
  fCurrentDDL         = 0;
  fCurrentDarcHeader  = 0;
  fCurrentRegHeader   = 0;
  fCurrentLocalStruct = 0;

  // Find the first non-empty structure
  if (not GetNextDDL()) return;
  if (not GetNextRegHeader()) return;
  GetNextLocalStruct();
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextDDL()
{
  /// Returns the next DDL present

  assert( GetReader() != 0 );

  Bool_t kFound(kFALSE);

  while ( fCurrentDDLIndex < fgkMaxDDL-1 && !kFound )
  {
    ++fCurrentDDLIndex;
    GetReader()->Reset();
    GetReader()->Select("MUONTRG",fCurrentDDLIndex,fCurrentDDLIndex);
    if ( GetReader()->ReadHeader() )
    {
      kFound = kTRUE;
    }
  }

  if ( !kFound )
  {
    // fCurrentDDLIndex is set to fgkMaxDDL so that we exit the above loop immediately
    // for a subsequent call to this method, unless NextEvent is called in between.
    fCurrentDDLIndex = fgkMaxDDL;
    // We have not actually been able to complete the loading of the new DDL so
    // we are still on the old one. In this case we do not need to reset fCurrentDDL.
    //fCurrentDDL = 0;
    if (IsErrorLogger()) AddErrorMessage();
    return kFALSE;
  }

  Int_t totalDataWord  = GetReader()->GetDataSize(); // in bytes

  AliRawReader * reader = GetReader();
  if (!reader) return kFALSE;

  const AliRawDataHeader * cdh = reader->GetDataHeader();
  const AliRawDataHeaderV3 * cdh3 = reader->GetDataHeaderV3();

  if (!cdh && !cdh3) return kFALSE;

  Bool_t scalerEvent = ((cdh ?  cdh->GetL1TriggerMessage() : cdh3->GetL1TriggerMessage()) & 0x1) == 0x1;

  AliDebug(3, Form("DDL Number %d totalDataWord %d\n", fCurrentDDLIndex,
                   totalDataWord));

  UInt_t *buffer = new UInt_t[totalDataWord/4];

  if ( !GetReader()->ReadNext((UChar_t*)buffer, totalDataWord) )
  {
    // We have not actually been able to complete the loading of the new DDL so
    // we are still on the old one. In this case we do not need to reset fCurrentDDL.
    //fCurrentDDL = 0;
    delete [] buffer;
    return kFALSE;
  }

#ifndef R__BYTESWAP
  Swap(buffer, totalDataWord / sizeof(UInt_t)); // swap needed for mac power pc
#endif

  fPayload->ResetDDL();

  Bool_t ok = fPayload->Decode(buffer, scalerEvent);

  delete[] buffer;

  fCurrentDDL = fPayload->GetDDLTrigger();

  fCurrentDarcHeader = fCurrentDDL->GetDarcHeader();

  fCurrentRegHeaderIndex = -1;

  return ok;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextRegHeader()
{
  /// Returns the next Reg Header present

  assert( fCurrentDarcHeader != 0 );
  assert( fCurrentDDL != 0 );

  fCurrentRegHeader = 0;

  Int_t i = fCurrentRegHeaderIndex;

  while ( fCurrentRegHeader == 0 && i < fCurrentDarcHeader->GetRegHeaderEntries()-1 )
  {
    ++i;
    fCurrentRegHeader = fCurrentDarcHeader->GetRegHeaderEntry(i);
  }

  if ( !fCurrentRegHeader )
  {
    Bool_t ok = GetNextDDL();
    if (!ok)
    {
      return kFALSE;
    }
    else
    {
      return GetNextRegHeader();
    }
  }

  fCurrentRegHeaderIndex = i;

  fCurrentLocalStructIndex = -1;

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextLocalStruct()
{
  /// Find the next non-empty local structure

  assert( fCurrentRegHeader != 0 );

  fCurrentLocalStruct = 0;

  Int_t i = fCurrentLocalStructIndex;

  while ( fCurrentLocalStruct == 0 && i < fCurrentRegHeader->GetLocalEntries()-1 )
  {
    ++i;
    fCurrentLocalStruct = fCurrentRegHeader->GetLocalEntry(i);
  }

  if ( !fCurrentLocalStruct )
  {
    Bool_t ok = GetNextRegHeader();
    if (!ok)
    {
      return kFALSE;
    }
    else
    {
      return GetNextLocalStruct();
    }
  }

  fCurrentLocalStructIndex = i;

  fLocalStructRead = kFALSE;

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::NextDDL()
{
  /// reading tracker DDL
  /// store local info into Array
  /// store only non-empty structures

  // reset TClones
  fPayload->ResetDDL();

  // loop over the two ddl's

  while ( fDDL < fgkMaxDDL ) {
    GetReader()->Reset();
    GetReader()->Select("MUONTRG", fDDL, fDDL);  //Select the DDL file to be read
    if (GetReader()->ReadHeader()) break;
    AliDebug(3,Form("Skipping DDL %d which does not seem to be there",fDDL));
    ++fDDL;
  }

  if (fDDL >= fgkMaxDDL) {
    fDDL = 0;
    if (IsErrorLogger()) AddErrorMessage();
    return kFALSE;
  }

  AliDebug(3, Form("DDL Number %d\n", fDDL ));

  Int_t totalDataWord = GetReader()->GetDataSize(); // in bytes

  AliRawReader * reader = GetReader();
  if (!reader) return kFALSE;

  const AliRawDataHeader * cdh = reader->GetDataHeader();
  const AliRawDataHeaderV3 * cdh3 = reader->GetDataHeaderV3();

  if (!cdh && !cdh3) return kFALSE;

  Bool_t scalerEvent = ((cdh ?  cdh->GetL1TriggerMessage() : cdh3->GetL1TriggerMessage()) & 0x1) == 0x1;

  UInt_t *buffer = new UInt_t[totalDataWord/4];

  // check not necessary yet, but for future developments
  if (!GetReader()->ReadNext((UChar_t*)buffer, totalDataWord)) return kFALSE;

#ifndef R__BYTESWAP
  Swap(buffer, totalDataWord / sizeof(UInt_t)); // swap needed for mac power pc
#endif

  fPayload->Decode(buffer, scalerEvent);

  fDDL++;

  delete [] buffer;

  return kTRUE;
}

// //______________________________________________________
// void AliMUONRawStreamTrigger::SetMaxReg(Int_t reg)
// {
//   /// set regional card number
//   fPayload->SetMaxReg(reg);
// }

//______________________________________________________
void AliMUONRawStreamTrigger::SetMaxLoc(Int_t loc)
{
  /// set local card number
  fPayload->SetMaxLoc(loc);
}

//______________________________________________________
void AliMUONRawStreamTrigger::AddErrorMessage()
{
/// add message into logger of AliRawReader per event

  TString msg;
  Int_t occurance = 0;
  AliMUONLogger* log = fPayload->GetErrorLogger();

  log->ResetItr();
  while(log->Next(msg, occurance))
  {
    if (msg.Contains("Darc"))
      GetReader()->AddMajorErrorLog(kDarcEoWErr, msg.Data());

    if (msg.Contains("Global"))
      GetReader()->AddMajorErrorLog(kGlobalEoWErr, msg.Data());

    if (msg.Contains("Regional"))
      GetReader()->AddMajorErrorLog(kRegEoWErr, msg.Data());

    if (msg.Contains("Local"))
      GetReader()->AddMajorErrorLog(kLocalEoWErr, msg.Data());
  }

  log->Clear(); // clear after each event
}
<commit_msg>ALIROOT-5420 Missing include<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * 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.                  *
 **************************************************************************/

/* $Id$ */

//-----------------------------------------------------------------------------
/// \class AliMUONRawStreamTrigger
/// This class provides access to MUON digits in raw data.
///
/// It loops over all MUON digits in the raw data given by the AliRawReader.
/// The Next method goes to the next local response. If there are no local response left
/// it returns kFALSE.
/// It can loop also over DDL and store the decoded rawdata in TClonesArrays
/// in payload class.
///
/// Version implement for Trigger
/// \author Christian Finck
//-----------------------------------------------------------------------------

#include <TArrayS.h>

#include "AliMUONRawStreamTrigger.h"
#include "AliMUONDarcHeader.h"
#include "AliMUONRegHeader.h"
#include "AliMUONLocalStruct.h"
#include "AliMUONDDLTrigger.h"
#include "AliMUONLogger.h"

#include "AliRawReader.h"
#include "AliRawDataHeader.h"
#include "AliRawDataHeaderV3.h"
#include "AliDAQ.h"
#include "AliLog.h"

#include <cassert>

/// \cond CLASSIMP
ClassImp(AliMUONRawStreamTrigger)
/// \endcond

const Int_t AliMUONRawStreamTrigger::fgkMaxDDL = 2;

//___________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger(TRootIOCtor* /*dummy*/)
:   AliMUONVRawStreamTrigger(),
fPayload(0x0),
fCurrentDDL(0x0),
fCurrentDDLIndex(fgkMaxDDL),
fCurrentDarcHeader(0x0),
fCurrentRegHeader(0x0),
fCurrentRegHeaderIndex(0),
fCurrentLocalStruct(0x0),
fCurrentLocalStructIndex(0),
fLocalStructRead(kFALSE),
fDDL(0),
fNextDDL(kFALSE)
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor with no mem allocation for I/O
  ///
}

//___________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger()
:   AliMUONVRawStreamTrigger(),
    fPayload(new AliMUONPayloadTrigger()),
    fCurrentDDL(0x0),
    fCurrentDDLIndex(fgkMaxDDL),
    fCurrentDarcHeader(0x0),
    fCurrentRegHeader(0x0),
    fCurrentRegHeaderIndex(0),
    fCurrentLocalStruct(0x0),
    fCurrentLocalStructIndex(0),
    fLocalStructRead(kFALSE),
    fDDL(0),
    fNextDDL(kFALSE)
{
  ///
  /// create an object to read MUON raw digits
  /// Default ctor for monitoring purposes
  ///

}

//_________________________________________________________________
AliMUONRawStreamTrigger::AliMUONRawStreamTrigger(AliRawReader* rawReader)
  : AliMUONVRawStreamTrigger(rawReader),
    fPayload(new AliMUONPayloadTrigger()),
    fCurrentDDL(0x0),
    fCurrentDDLIndex(fgkMaxDDL),
    fCurrentDarcHeader(0x0),
    fCurrentRegHeader(0x0),
    fCurrentRegHeaderIndex(0),
    fCurrentLocalStruct(0x0),
    fCurrentLocalStructIndex(0),
    fLocalStructRead(kFALSE),
    fDDL(0),
    fNextDDL(kFALSE)
{
  ///
  /// ctor with AliRawReader as argument
  /// for reconstruction purpose
  ///

}

//___________________________________
AliMUONRawStreamTrigger::~AliMUONRawStreamTrigger()
{
  ///
  /// clean up
  ///
  delete fPayload;
}

//_____________________________________________________________
Bool_t AliMUONRawStreamTrigger::Next(UChar_t& id,   UChar_t& dec,      Bool_t& trigY,
				     UChar_t& yPos, UChar_t& sXDev,    UChar_t& xDev,
				     UChar_t& xPos, Bool_t& triggerY,  Bool_t& triggerX,
				     TArrayS& xPattern, TArrayS& yPattern)
{
  ///
  /// read the next raw digit (local structure)
  /// returns kFALSE if there is no digit left
  /// Should call First() before this method to start the iteration.
  ///

  if ( IsDone() ) return kFALSE;

  if ( fLocalStructRead ) {

    Bool_t ok = GetNextLocalStruct();
    if (!ok)
    {
      // this is the end
      return kFALSE;
    }
  }

  fLocalStructRead = kTRUE;

  id    = fCurrentLocalStruct->GetId();
  dec   = fCurrentLocalStruct->GetDec();
  trigY = fCurrentLocalStruct->GetTrigY();
  yPos  = fCurrentLocalStruct->GetYPos();
  sXDev = fCurrentLocalStruct->GetSXDev();
  xDev  = fCurrentLocalStruct->GetXDev();
  xPos  = fCurrentLocalStruct->GetXPos();

  triggerX = fCurrentLocalStruct->GetTriggerX();
  triggerY = fCurrentLocalStruct->GetTriggerY();

  fCurrentLocalStruct->GetXPattern(xPattern);
  fCurrentLocalStruct->GetYPattern(yPattern);

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::IsDone() const
{
  /// Whether the iteration is finished or not
  return (fCurrentLocalStruct==0);
}

//______________________________________________________
void AliMUONRawStreamTrigger::First()
{
  /// Initialize the iteration process.

  fCurrentDDLIndex = -1;
  // Must reset all the pointers because if we return before calling
  // GetNextLocalStruct() the user might call CurrentDDL(), CurrentBlockHeader(),
  // CurrentRegHeader() or CurrentLocalStruct() which should return reasonable
  // results in that case.
  fCurrentDDL         = 0;
  fCurrentDarcHeader  = 0;
  fCurrentRegHeader   = 0;
  fCurrentLocalStruct = 0;

  // Find the first non-empty structure
  if (not GetNextDDL()) return;
  if (not GetNextRegHeader()) return;
  GetNextLocalStruct();
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextDDL()
{
  /// Returns the next DDL present

  assert( GetReader() != 0 );

  Bool_t kFound(kFALSE);

  while ( fCurrentDDLIndex < fgkMaxDDL-1 && !kFound )
  {
    ++fCurrentDDLIndex;
    GetReader()->Reset();
    GetReader()->Select("MUONTRG",fCurrentDDLIndex,fCurrentDDLIndex);
    if ( GetReader()->ReadHeader() )
    {
      kFound = kTRUE;
    }
  }

  if ( !kFound )
  {
    // fCurrentDDLIndex is set to fgkMaxDDL so that we exit the above loop immediately
    // for a subsequent call to this method, unless NextEvent is called in between.
    fCurrentDDLIndex = fgkMaxDDL;
    // We have not actually been able to complete the loading of the new DDL so
    // we are still on the old one. In this case we do not need to reset fCurrentDDL.
    //fCurrentDDL = 0;
    if (IsErrorLogger()) AddErrorMessage();
    return kFALSE;
  }

  Int_t totalDataWord  = GetReader()->GetDataSize(); // in bytes

  AliRawReader * reader = GetReader();
  if (!reader) return kFALSE;

  const AliRawDataHeader * cdh = reader->GetDataHeader();
  const AliRawDataHeaderV3 * cdh3 = reader->GetDataHeaderV3();

  if (!cdh && !cdh3) return kFALSE;

  Bool_t scalerEvent = ((cdh ?  cdh->GetL1TriggerMessage() : cdh3->GetL1TriggerMessage()) & 0x1) == 0x1;

  AliDebug(3, Form("DDL Number %d totalDataWord %d\n", fCurrentDDLIndex,
                   totalDataWord));

  UInt_t *buffer = new UInt_t[totalDataWord/4];

  if ( !GetReader()->ReadNext((UChar_t*)buffer, totalDataWord) )
  {
    // We have not actually been able to complete the loading of the new DDL so
    // we are still on the old one. In this case we do not need to reset fCurrentDDL.
    //fCurrentDDL = 0;
    delete [] buffer;
    return kFALSE;
  }

#ifndef R__BYTESWAP
  Swap(buffer, totalDataWord / sizeof(UInt_t)); // swap needed for mac power pc
#endif

  fPayload->ResetDDL();

  Bool_t ok = fPayload->Decode(buffer, scalerEvent);

  delete[] buffer;

  fCurrentDDL = fPayload->GetDDLTrigger();

  fCurrentDarcHeader = fCurrentDDL->GetDarcHeader();

  fCurrentRegHeaderIndex = -1;

  return ok;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextRegHeader()
{
  /// Returns the next Reg Header present

  assert( fCurrentDarcHeader != 0 );
  assert( fCurrentDDL != 0 );

  fCurrentRegHeader = 0;

  Int_t i = fCurrentRegHeaderIndex;

  while ( fCurrentRegHeader == 0 && i < fCurrentDarcHeader->GetRegHeaderEntries()-1 )
  {
    ++i;
    fCurrentRegHeader = fCurrentDarcHeader->GetRegHeaderEntry(i);
  }

  if ( !fCurrentRegHeader )
  {
    Bool_t ok = GetNextDDL();
    if (!ok)
    {
      return kFALSE;
    }
    else
    {
      return GetNextRegHeader();
    }
  }

  fCurrentRegHeaderIndex = i;

  fCurrentLocalStructIndex = -1;

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::GetNextLocalStruct()
{
  /// Find the next non-empty local structure

  assert( fCurrentRegHeader != 0 );

  fCurrentLocalStruct = 0;

  Int_t i = fCurrentLocalStructIndex;

  while ( fCurrentLocalStruct == 0 && i < fCurrentRegHeader->GetLocalEntries()-1 )
  {
    ++i;
    fCurrentLocalStruct = fCurrentRegHeader->GetLocalEntry(i);
  }

  if ( !fCurrentLocalStruct )
  {
    Bool_t ok = GetNextRegHeader();
    if (!ok)
    {
      return kFALSE;
    }
    else
    {
      return GetNextLocalStruct();
    }
  }

  fCurrentLocalStructIndex = i;

  fLocalStructRead = kFALSE;

  return kTRUE;
}

//______________________________________________________
Bool_t AliMUONRawStreamTrigger::NextDDL()
{
  /// reading tracker DDL
  /// store local info into Array
  /// store only non-empty structures

  // reset TClones
  fPayload->ResetDDL();

  // loop over the two ddl's

  while ( fDDL < fgkMaxDDL ) {
    GetReader()->Reset();
    GetReader()->Select("MUONTRG", fDDL, fDDL);  //Select the DDL file to be read
    if (GetReader()->ReadHeader()) break;
    AliDebug(3,Form("Skipping DDL %d which does not seem to be there",fDDL));
    ++fDDL;
  }

  if (fDDL >= fgkMaxDDL) {
    fDDL = 0;
    if (IsErrorLogger()) AddErrorMessage();
    return kFALSE;
  }

  AliDebug(3, Form("DDL Number %d\n", fDDL ));

  Int_t totalDataWord = GetReader()->GetDataSize(); // in bytes

  AliRawReader * reader = GetReader();
  if (!reader) return kFALSE;

  const AliRawDataHeader * cdh = reader->GetDataHeader();
  const AliRawDataHeaderV3 * cdh3 = reader->GetDataHeaderV3();

  if (!cdh && !cdh3) return kFALSE;

  Bool_t scalerEvent = ((cdh ?  cdh->GetL1TriggerMessage() : cdh3->GetL1TriggerMessage()) & 0x1) == 0x1;

  UInt_t *buffer = new UInt_t[totalDataWord/4];

  // check not necessary yet, but for future developments
  if (!GetReader()->ReadNext((UChar_t*)buffer, totalDataWord)) return kFALSE;

#ifndef R__BYTESWAP
  Swap(buffer, totalDataWord / sizeof(UInt_t)); // swap needed for mac power pc
#endif

  fPayload->Decode(buffer, scalerEvent);

  fDDL++;

  delete [] buffer;

  return kTRUE;
}

// //______________________________________________________
// void AliMUONRawStreamTrigger::SetMaxReg(Int_t reg)
// {
//   /// set regional card number
//   fPayload->SetMaxReg(reg);
// }

//______________________________________________________
void AliMUONRawStreamTrigger::SetMaxLoc(Int_t loc)
{
  /// set local card number
  fPayload->SetMaxLoc(loc);
}

//______________________________________________________
void AliMUONRawStreamTrigger::AddErrorMessage()
{
/// add message into logger of AliRawReader per event

  TString msg;
  Int_t occurance = 0;
  AliMUONLogger* log = fPayload->GetErrorLogger();

  log->ResetItr();
  while(log->Next(msg, occurance))
  {
    if (msg.Contains("Darc"))
      GetReader()->AddMajorErrorLog(kDarcEoWErr, msg.Data());

    if (msg.Contains("Global"))
      GetReader()->AddMajorErrorLog(kGlobalEoWErr, msg.Data());

    if (msg.Contains("Regional"))
      GetReader()->AddMajorErrorLog(kRegEoWErr, msg.Data());

    if (msg.Contains("Local"))
      GetReader()->AddMajorErrorLog(kLocalEoWErr, msg.Data());
  }

  log->Clear(); // clear after each event
}
<|endoftext|>