<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"

#include "IECore/PointDistribution.h"
#include "IECore/VectorTypedData.h"

#include "IECorePython/PointDistributionBinding.h"

using namespace boost::python;
using namespace IECore;
using namespace IECore;

namespace
{

struct ConstantDensitySampler
{
	float operator() ( const Imath::V2f &pos )
	{
		return 1.0f;
	}
};

struct VectorPointEmitter
{
	VectorPointEmitter( std::vector<Imath::V2f> &p )
		:	points( p )
	{
	}

	void operator() ( const Imath::V2f &pos )
	{
		points.push_back( pos );
	}

	std::vector<Imath::V2f> &points;
};

object callWrapper( const PointDistribution &pd, const Imath::Box2f &bounds, float density, object &densitySampler, object &pointEmitter )
{
	if( pointEmitter==object() )
	{
		V2fVectorDataPtr result = new V2fVectorData;
		VectorPointEmitter pe( result->writable() );
		if( densitySampler==object() )
		{
			ConstantDensitySampler defaultSampler;
			pd( bounds, density, defaultSampler, pe );
		}
		else
		{
			pd( bounds, density, densitySampler, pe );
		}
		return object( result );
	}
	else
	{
		if( densitySampler==object() )
		{
			ConstantDensitySampler defaultSampler;
			pd( bounds, density, defaultSampler, pointEmitter );
		}
		else
		{
			pd( bounds, density, densitySampler, pointEmitter );
		}
		return object();
	}
}

} // namespace

namespace IECorePython
{

void bindPointDistribution()
{
	class_<PointDistribution, boost::noncopyable>( "PointDistribution", no_init )
		.def( init<const std::string &>() )
		.def( "__call__", callWrapper, ( arg_( "self" ), arg_( "bounds" ), arg_( "density" ), arg_( "densitySampler" ), arg_( "pointEmitter" )=object() ) )
		.def( "__call__", callWrapper, ( arg_( "self" ), arg_( "bounds" ), arg_( "density" ), arg_( "pointEmitter" )=object() ) )
		.def( "defaultInstance", &PointDistribution::defaultInstance, return_value_policy<reference_existing_object>() )
		.staticmethod( "defaultInstance" )
	;
}

} // namespace IECorePython
<commit_msg>PointDistributionBinding : Wrap density sampler<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2009-2010, Image Engine Design Inc. All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//
//     * Neither the name of Image Engine Design nor the names of any
//       other contributors to this software may be used to endorse or
//       promote products derived from this software without specific prior
//       written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////

// This include needs to be the very first to prevent problems with warnings
// regarding redefinition of _POSIX_C_SOURCE
#include "boost/python.hpp"

#include "IECore/PointDistribution.h"
#include "IECore/VectorTypedData.h"

#include "IECorePython/PointDistributionBinding.h"

using namespace boost::python;
using namespace IECore;
using namespace IECore;

namespace
{

struct ConstantDensitySampler
{
	float operator() ( const Imath::V2f &pos )
	{
		return 1.0f;
	}
};

struct VectorPointEmitter
{
	VectorPointEmitter( std::vector<Imath::V2f> &p )
		:	points( p )
	{
	}

	void operator() ( const Imath::V2f &pos )
	{
		points.push_back( pos );
	}

	std::vector<Imath::V2f> &points;
};

struct PythonDensitySampler
{
	PythonDensitySampler( object &sampler )
		:	sampler( sampler )
	{
	}

	float operator() ( const Imath::V2f &pos )
	{
		return extract<float>( sampler( pos ) );
	}

	object sampler;
};

object callWrapper( const PointDistribution &pd, const Imath::Box2f &bounds, float density, object &densitySampler, object &pointEmitter )
{
	if( pointEmitter==object() )
	{
		V2fVectorDataPtr result = new V2fVectorData;
		VectorPointEmitter pe( result->writable() );
		if( densitySampler==object() )
		{
			ConstantDensitySampler defaultSampler;
			pd( bounds, density, defaultSampler, pe );
		}
		else
		{
			PythonDensitySampler pythonDensitySampler( densitySampler );
			pd( bounds, density, pythonDensitySampler, pe );
		}
		return object( result );
	}
	else
	{
		if( densitySampler==object() )
		{
			ConstantDensitySampler defaultSampler;
			pd( bounds, density, defaultSampler, pointEmitter );
		}
		else
		{
			PythonDensitySampler pythonDensitySampler( densitySampler );
			pd( bounds, density, pythonDensitySampler, pointEmitter );
		}
		return object();
	}
}

} // namespace

namespace IECorePython
{

void bindPointDistribution()
{
	class_<PointDistribution, boost::noncopyable>( "PointDistribution", no_init )
		.def( init<const std::string &>() )
		.def( "__call__", callWrapper, ( arg_( "self" ), arg_( "bounds" ), arg_( "density" ), arg_( "densitySampler" ), arg_( "pointEmitter" )=object() ) )
		.def( "__call__", callWrapper, ( arg_( "self" ), arg_( "bounds" ), arg_( "density" ), arg_( "pointEmitter" )=object() ) )
		.def( "defaultInstance", &PointDistribution::defaultInstance, return_value_policy<reference_existing_object>() )
		.staticmethod( "defaultInstance" )
	;
}

} // namespace IECorePython
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

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

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

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

#include <Modules/Legacy/Fields/GetFieldBoundary.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

//  private:
//    SCIRunAlgo::GetFieldBoundaryAlgo algo_;

GetFieldBoundary::GetFieldBoundary()
  : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false)
{
  //! Forward error messages;
  algo_.set_progress_reporter(this);
}

void
GetFieldBoundary::execute()
{
  FieldHandle field;

  get_input_handle("Field",field,true);

  // If parameters changed, do algorithm
  if (inputs_changed_ ||
      !oport_cached("BoundaryField") ||
      !oport_cached("Mapping"))
  {
    update_state(Executing);

    // Output dataflow objects:
    FieldHandle ofield;
    MatrixHandle mapping;

    // Entry point to algorithm
    if (!(algo_.run(field,ofield,mapping))) return;

    // Send Data flow objects downstream
    send_output_handle("BoundaryField", ofield);
    send_output_handle("Mapping", mapping);
  }
}
<commit_msg>algo injection<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2009 Scientific Computing and Imaging Institute,
   University of Utah.

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

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

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

#include <Modules/Legacy/Fields/GetFieldBoundary.h>
#include <Core/Algorithms/Legacy/Fields/MeshDerivatives/GetFieldBoundary.h>

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Modules::Fields;

GetFieldBoundary::GetFieldBoundary()
  : Module(ModuleLookupInfo("GetFieldBoundary", "NewField", "SCIRun"), false)
{
  algo_ = algoFactory_->create(get_module_name(), getLogger());
}

void
GetFieldBoundary::execute()
{
  FieldHandle field;

  get_input_handle("Field",field,true);

  // If parameters changed, do algorithm
  if (inputs_changed_ ||
      !oport_cached("BoundaryField") ||
      !oport_cached("Mapping"))
  {
    update_state(Executing);

    // Output dataflow objects:
    FieldHandle ofield;
    MatrixHandle mapping;

    // Entry point to algorithm
    if (!(algo_.run(field,ofield,mapping))) return;

    // Send Data flow objects downstream
    send_output_handle("BoundaryField", ofield);
    send_output_handle("Mapping", mapping);
  }
}
<|endoftext|>


<commit_before>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Svein Lindal <slindal@fys.uio.no   >                  *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * 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   AliHLTEveCalo.cxx
/// @author Svein Lindal <slindal@fys.uio.no>
/// @brief  Calorimeter base class for the HLT EVE display

#include "AliHLTEveCalo.h"
#include "AliHLTHOMERBlockDesc.h"
#include "TCanvas.h"
#include "AliHLTEveBase.h"
#include "TEveBoxSet.h"
#include "AliPHOSGeometry.h"
#include "TVector3.h"
#include "AliEveHOMERManager.h"
#include "TEveManager.h"
#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloClusterDataStruct.h"
#include "AliHLTCaloClusterReader.h"
#include "TEveTrans.h"
#include "TString.h"
#include "TH2F.h"
#include "TH1F.h"

ClassImp(AliHLTEveCalo);

AliHLTEveCalo::AliHLTEveCalo(Int_t nm, TString name) :
  AliHLTEveBase(),
  fBoxSetDigits(NULL),
  fBoxSetClusters(NULL),
  fElementList(NULL),
  fNModules(nm),
  fName(name),
  fPadTitles(NULL)
{
  // Constructor.

  SetMaxHistograms(9);

  fPadTitles = new TString[GetMaxHistograms()];

  for(int i = 0; i < GetMaxHistograms(); i++) {
    fPadTitles[i] = "";
  }

}

AliHLTEveCalo::~AliHLTEveCalo()
{
  //Destructor
  if(fBoxSetDigits)
    delete fBoxSetDigits;
  fBoxSetDigits = NULL;

  if(fBoxSetClusters)
    delete fBoxSetClusters;
  fBoxSetClusters = NULL;

  if(fElementList) {

    delete fElementList;
  }
  fElementList = NULL;
}

void AliHLTEveCalo::ProcessBlock(AliHLTHOMERBlockDesc * block) {
  //See header file for documentation

  if ( block->GetDataType().CompareTo("ROOTHIST") == 0 ) {
    ProcessHistogram(block);

  } else {

    if( !fElementList ) {
      fElementList = CreateElementList();
      fEventManager->GetEveManager()->AddElement(fElementList);
    }

    if ( block->GetDataType().CompareTo("CALOCLUS") == 0 ){
      //cout <<"Skipping calo clusters"<<endl;
      ProcessClusters( block );
    }
    else if ( block->GetDataType().CompareTo("DIGITTYP") == 0 ) {
      //ProcessDigits( block);
      //
    }
    else if ( block->GetDataType().CompareTo("CHANNELT") == 0 )
      ProcessClusters( block );
  }
}

void AliHLTEveCalo::ProcessHistogram(AliHLTHOMERBlockDesc * block ) {
  //See header file for documentation

  if(!fCanvas) {
    fCanvas = CreateCanvas(Form("%s QA", fName.Data()), Form("%s QA", fName.Data()));
    fCanvas->Divide(3, 3);
  }

  AddHistogramsToCanvas(block, fCanvas, fHistoCount);

}

// void AliHLTEveCalo::ProcessDigits(AliHLTHOMERBlockDesc* block) {
//   //See header file for documentation

//   AliHLTCaloDigitDataStruct *ds = reinterpret_cast<AliHLTCaloDigitDataStruct*> (block->GetData());
//   UInt_t nDigits = block->GetSize()/sizeof(AliHLTCaloDigitDataStruct);

//   for(UInt_t i = 0; i < nDigits; i++, ds++) {

//     Float_t x = (ds->fX - 32)* 2.2;
//       Float_t z = (ds->fZ - 28) * 2.2;

//     fBoxSetDigits[4-ds->fModule].AddBox(x, 0, z, 2.2, ds->fEnergy*200, 2.2);
//     fBoxSetDigits[4-ds->fModule].DigitValue(static_cast<Int_t>(ds->fEnergy*10));
//   }

// }

void AliHLTEveCalo::ProcessClusters(AliHLTHOMERBlockDesc* block) {
  //See header file for documentation

  AliHLTCaloClusterHeaderStruct *dh = reinterpret_cast<AliHLTCaloClusterHeaderStruct*> (block->GetData());
  AliHLTCaloClusterReader * clusterReader = new AliHLTCaloClusterReader();
  clusterReader->SetMemory(dh);

  AliHLTCaloClusterDataStruct * ds;

  while( (ds = clusterReader->NextCluster()) ){
     AddClusters(ds->fGlobalPos, ds->fModule, ds->fEnergy);
  }

  AliHLTCaloDigitDataStruct *dg = clusterReader->GetDigits();
  UInt_t nDigits = clusterReader->GetNDigits();;
  for(UInt_t i = 0; i < nDigits; i++, dg++) {
    AddDigits(dg->fX, dg->fZ, dg->fModule, dg->fEnergy);
  }
}

void AliHLTEveCalo::UpdateElements() {
  //See header file for documentation
  if(fCanvas) fCanvas->Update();

  if(fBoxSetDigits) {
    for(int im = 0; im < fNModules; im++) {
      fBoxSetDigits[im].ElementChanged();
    }
  }

  if(fBoxSetClusters) {
    for(int im = 0; im < fNModules; im++) {
      fBoxSetClusters[im].ElementChanged();
    }
  }

}

void AliHLTEveCalo::ResetElements(){
  //See header file for documentation
  fHistoCount = 0;

  if ( fBoxSetDigits ){
    for(int im = 0; im < fNModules; im++){
      fBoxSetDigits[im].Reset();
    }
  }

  if ( fBoxSetClusters ){
    for(int im = 0; im < fNModules; im++){
      fBoxSetClusters[im].Reset();
    }
  }

}

Int_t AliHLTEveCalo::GetPadNumber(TString name) {

  //cout << "GetPadNumber name   " << name << endl;

  for(int i = 0; i < GetMaxHistograms(); i++) {
    if (!fPadTitles[i].CompareTo(name)){
      return i+1;
    }
    else if (!fPadTitles[i].CompareTo("")) {
      //cout <<"in empty title"<<endl;
      fPadTitles[i] = name;
      return i+1;
    }
  }

  if(fPadTitles[GetMaxHistograms()].CompareTo("")) {
    cout << "AliHLTEveCalo::GetPadNumber:  We have more histograms than we have room for"<< endl;
  }
  return 1;

}

void AliHLTEveCalo::AddHistogramsToCanvas(AliHLTHOMERBlockDesc * block, TCanvas * canvas, Int_t &cdCount ) {
  //See header file for documentation

  if ( ! block->GetClassName().CompareTo("TObjArray")) {
    TIter next((TObjArray*)(block->GetTObject()));
    TObject *object;

    while (( object = (TObject*) next())) {

      Int_t iPad = GetPadNumber((static_cast<TH1*>(object))->GetName());
      canvas->cd(iPad);

      //Check if histo is 2D histo
      TH2F* histo = dynamic_cast<TH2F*>(object);
      if(histo){

	Int_t lb = histo->FindLastBinAbove(0,1);
	if(lb > -1) {
	  histo->SetAxisRange(0, histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	  histo->SetAxisRange(0, histo->GetYaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 2) + 3), "Y");
	}

	histo->Draw("COLZ");
      }

      //Must be 1D histo
      else {
	TH1F* histo = dynamic_cast<TH1F*>(object);
	if (histo) {

	  TString name = histo->GetName();

	  if(name.Contains("Energy")) {
	    histo->SetAxisRange(0, histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	  }

	  else if(name.Contains("InvMass")) {
	    histo->SetAxisRange(histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1) - 3), histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	    histo->Fit("gaus", "", "", histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1)), histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1)));
	    //histo->Fit("gaus", "", "", histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1)), 0.3);
	    //histo->Fit("gaus", )
	  }

	  histo->Draw();
	} else {
	  cout <<"AliHLTEveCaloBase::AddHistogramsTocCanvas: Histogram neither TH1F nor TH2F"<<endl;
	}
      }
    }

  } else if ( ! block->GetClassName().CompareTo("TH1F")) {

    TH1F* histo = reinterpret_cast<TH1F*>(block->GetTObject());
    if(histo) {

      Int_t iPad = GetPadNumber(histo->GetName());
      canvas->cd(iPad);
      histo->Draw();
    }

  } else if ( ! block->GetClassName().CompareTo("TH2F")) {

    TH2F *histo = reinterpret_cast<TH2F*>(block->GetTObject());
    if(histo) {

      Int_t iPad = GetPadNumber(histo->GetName());
      canvas->cd(iPad);
      histo->Draw();
    }

  }

  canvas->cd();
}

<commit_msg>fixed compilation warnings<commit_after>/**************************************************************************
 * This file is property of and copyright by the ALICE HLT Project        *
 * ALICE Experiment at CERN, All rights reserved.                         *
 *                                                                        *
 * Primary Authors: Svein Lindal <slindal@fys.uio.no   >                  *
 *                  for The ALICE HLT Project.                            *
 *                                                                        *
 * 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   AliHLTEveCalo.cxx
/// @author Svein Lindal <slindal@fys.uio.no>
/// @brief  Calorimeter base class for the HLT EVE display

#include "AliHLTEveCalo.h"
#include "AliHLTHOMERBlockDesc.h"
#include "TCanvas.h"
#include "AliHLTEveBase.h"
#include "TEveBoxSet.h"
#include "AliPHOSGeometry.h"
#include "TVector3.h"
#include "AliEveHOMERManager.h"
#include "TEveManager.h"
#include "AliHLTCaloDigitDataStruct.h"
#include "AliHLTCaloClusterDataStruct.h"
#include "AliHLTCaloClusterReader.h"
#include "TEveTrans.h"
#include "TString.h"
#include "TH2F.h"
#include "TH1F.h"

ClassImp(AliHLTEveCalo);

AliHLTEveCalo::AliHLTEveCalo(Int_t nm, TString name) :
  AliHLTEveBase(),
  fBoxSetDigits(NULL),
  fBoxSetClusters(NULL),
  fElementList(NULL),
  fNModules(nm),
  fName(name),
  fPadTitles(NULL)
{
  // Constructor.

  SetMaxHistograms(9);

  fPadTitles = new TString[GetMaxHistograms()];

  for(int i = 0; i < GetMaxHistograms(); i++) {
    fPadTitles[i] = "";
  }

}

AliHLTEveCalo::~AliHLTEveCalo()
{
  //Destructor
  if(fBoxSetDigits)
    delete fBoxSetDigits;
  fBoxSetDigits = NULL;

  if(fBoxSetClusters)
    delete fBoxSetClusters;
  fBoxSetClusters = NULL;

  if(fElementList) {

    delete fElementList;
  }
  fElementList = NULL;
}

void AliHLTEveCalo::ProcessBlock(AliHLTHOMERBlockDesc * block) {
  //See header file for documentation

  if ( block->GetDataType().CompareTo("ROOTHIST") == 0 ) {
    ProcessHistogram(block);

  } else {

    if( !fElementList ) {
      fElementList = CreateElementList();
      fEventManager->GetEveManager()->AddElement(fElementList);
    }

    if ( block->GetDataType().CompareTo("CALOCLUS") == 0 ){
      //cout <<"Skipping calo clusters"<<endl;
      ProcessClusters( block );
    }
    else if ( block->GetDataType().CompareTo("DIGITTYP") == 0 ) {
      //ProcessDigits( block);
      //
    }
    else if ( block->GetDataType().CompareTo("CHANNELT") == 0 )
      ProcessClusters( block );
  }
}

void AliHLTEveCalo::ProcessHistogram(AliHLTHOMERBlockDesc * block ) {
  //See header file for documentation

  if(!fCanvas) {
    fCanvas = CreateCanvas(Form("%s QA", fName.Data()), Form("%s QA", fName.Data()));
    fCanvas->Divide(3, 3);
  }

  AddHistogramsToCanvas(block, fCanvas, fHistoCount);

}

// void AliHLTEveCalo::ProcessDigits(AliHLTHOMERBlockDesc* block) {
//   //See header file for documentation

//   AliHLTCaloDigitDataStruct *ds = reinterpret_cast<AliHLTCaloDigitDataStruct*> (block->GetData());
//   UInt_t nDigits = block->GetSize()/sizeof(AliHLTCaloDigitDataStruct);

//   for(UInt_t i = 0; i < nDigits; i++, ds++) {

//     Float_t x = (ds->fX - 32)* 2.2;
//       Float_t z = (ds->fZ - 28) * 2.2;

//     fBoxSetDigits[4-ds->fModule].AddBox(x, 0, z, 2.2, ds->fEnergy*200, 2.2);
//     fBoxSetDigits[4-ds->fModule].DigitValue(static_cast<Int_t>(ds->fEnergy*10));
//   }

// }

void AliHLTEveCalo::ProcessClusters(AliHLTHOMERBlockDesc* block) {
  //See header file for documentation

  AliHLTCaloClusterHeaderStruct *dh = reinterpret_cast<AliHLTCaloClusterHeaderStruct*> (block->GetData());
  AliHLTCaloClusterReader * clusterReader = new AliHLTCaloClusterReader();
  clusterReader->SetMemory(dh);

  AliHLTCaloClusterDataStruct * ds;

  while( (ds = clusterReader->NextCluster()) ){
     AddClusters(ds->fGlobalPos, ds->fModule, ds->fEnergy);
  }

  AliHLTCaloDigitDataStruct *dg = clusterReader->GetDigits();
  UInt_t nDigits = clusterReader->GetNDigits();;
  for(UInt_t i = 0; i < nDigits; i++, dg++) {
    AddDigits(dg->fX, dg->fZ, dg->fModule, dg->fEnergy);
  }
}

void AliHLTEveCalo::UpdateElements() {
  //See header file for documentation
  if(fCanvas) fCanvas->Update();

  if(fBoxSetDigits) {
    for(int im = 0; im < fNModules; im++) {
      fBoxSetDigits[im].ElementChanged();
    }
  }

  if(fBoxSetClusters) {
    for(int im = 0; im < fNModules; im++) {
      fBoxSetClusters[im].ElementChanged();
    }
  }

}

void AliHLTEveCalo::ResetElements(){
  //See header file for documentation
  fHistoCount = 0;

  if ( fBoxSetDigits ){
    for(int im = 0; im < fNModules; im++){
      fBoxSetDigits[im].Reset();
    }
  }

  if ( fBoxSetClusters ){
    for(int im = 0; im < fNModules; im++){
      fBoxSetClusters[im].Reset();
    }
  }

}

Int_t AliHLTEveCalo::GetPadNumber(TString name) {

  //cout << "GetPadNumber name   " << name << endl;

  for(int i = 0; i < GetMaxHistograms(); i++) {
    if (!fPadTitles[i].CompareTo(name)){
      return i+1;
    }
    else if (!fPadTitles[i].CompareTo("")) {
      //cout <<"in empty title"<<endl;
      fPadTitles[i] = name;
      return i+1;
    }
  }

  if(fPadTitles[GetMaxHistograms()].CompareTo("")) {
    cout << "AliHLTEveCalo::GetPadNumber:  We have more histograms than we have room for"<< endl;
  }
  return 1;

}

void AliHLTEveCalo::AddHistogramsToCanvas(AliHLTHOMERBlockDesc * block, TCanvas * canvas, Int_t &/*cdCount*/) {
  //See header file for documentation

  if ( ! block->GetClassName().CompareTo("TObjArray")) {
    TIter next((TObjArray*)(block->GetTObject()));
    TObject *object;

    while (( object = (TObject*) next())) {

      Int_t iPad = GetPadNumber((static_cast<TH1*>(object))->GetName());
      canvas->cd(iPad);

      //Check if histo is 2D histo
      TH2F* histo = dynamic_cast<TH2F*>(object);
      if(histo){

	Int_t lb = histo->FindLastBinAbove(0,1);
	if(lb > -1) {
	  histo->SetAxisRange(0, histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	  histo->SetAxisRange(0, histo->GetYaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 2) + 3), "Y");
	}

	histo->Draw("COLZ");
      }

      //Must be 1D histo
      else {
	TH1F* histo = dynamic_cast<TH1F*>(object);
	if (histo) {

	  TString name = histo->GetName();

	  if(name.Contains("Energy")) {
	    histo->SetAxisRange(0, histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	  }

	  else if(name.Contains("InvMass")) {
	    histo->SetAxisRange(histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1) - 3), histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1) + 3), "X");
	    histo->Fit("gaus", "", "", histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1)), histo->GetXaxis()->GetBinUpEdge(histo->FindLastBinAbove(0, 1)));
	    //histo->Fit("gaus", "", "", histo->GetXaxis()->GetBinLowEdge(histo->FindFirstBinAbove(0, 1)), 0.3);
	    //histo->Fit("gaus", )
	  }

	  histo->Draw();
	} else {
	  cout <<"AliHLTEveCaloBase::AddHistogramsTocCanvas: Histogram neither TH1F nor TH2F"<<endl;
	}
      }
    }

  } else if ( ! block->GetClassName().CompareTo("TH1F")) {

    TH1F* histo = reinterpret_cast<TH1F*>(block->GetTObject());
    if(histo) {

      Int_t iPad = GetPadNumber(histo->GetName());
      canvas->cd(iPad);
      histo->Draw();
    }

  } else if ( ! block->GetClassName().CompareTo("TH2F")) {

    TH2F *histo = reinterpret_cast<TH2F*>(block->GetTObject());
    if(histo) {

      Int_t iPad = GetPadNumber(histo->GetName());
      canvas->cd(iPad);
      histo->Draw();
    }

  }

  canvas->cd();
}

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file.
#include "FormatterToSourceTree.hpp"

#include <cassert>

#include <sax/AttributeList.hpp>

#include <XalanDOM/XalanDOMException.hpp>
#include <XalanDOM/XalanDocumentFragment.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrefixResolver.hpp>

#include <XMLSupport/FormatterToDOM.hpp>

#include "XalanSourceTreeComment.hpp"
#include "XalanSourceTreeDocument.hpp"
#include "XalanSourceTreeDocumentFragment.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeHelper.hpp"
#include "XalanSourceTreeProcessingInstruction.hpp"
#include "XalanSourceTreeText.hpp"

FormatterToSourceTree::FormatterToSourceTree(XalanSourceTreeDocument*	theDocument) :
	FormatterListener(OUTPUT_METHOD_DOM),
	m_document(theDocument),
	m_documentFragment(0),
	m_currentElement(0),
	m_elementStack(),
	m_lastChild(0),
	m_lastChildStack(),
	m_textBuffer()
{
}

FormatterToSourceTree::FormatterToSourceTree(
			XalanSourceTreeDocument*			theDocument,
			XalanSourceTreeDocumentFragment*	theDocumentFragment) :
	FormatterListener(OUTPUT_METHOD_DOM),
	m_document(theDocument),
	m_documentFragment(theDocumentFragment),
	m_currentElement(0),
	m_elementStack(),
	m_lastChild(0),
	m_lastChildStack(),
	m_textBuffer()
{
	assert(m_document != 0);
	assert(m_documentFragment != 0);
}

FormatterToSourceTree::~FormatterToSourceTree()
{
}

void
FormatterToSourceTree::setDocumentLocator(const Locator* const		/* locator */)
{
}

void
FormatterToSourceTree::startDocument()
{
	m_currentElement = 0;

	m_elementStack.clear();

	m_lastChild = 0;

	m_lastChildStack.clear();

	m_lastChildStack.reserve(eDefaultStackSize);

	clear(m_textBuffer);

	reserve(m_textBuffer, eDefaultTextBufferSize);

	// Push a dummy value for the current element, so we
	// don't have to check for an empty stack in endElement().
	m_elementStack.push_back(ElementStackType::value_type(0));
}

void
FormatterToSourceTree::endDocument()
{
	// Pop off the dummy value that we pushed in
	// startDocument()...
	m_elementStack.pop_back();

	assert(m_elementStack.empty() == true);
	assert(m_lastChildStack.empty() == true);
	assert(isEmpty(m_textBuffer) == true);
}

// A helper function to manage appending the new child.
template <class ParentNodeType, class ChildNodeType>
inline void
doAppendChildNode(
			ParentNodeType*		theParent,
			XalanNode*&			theLastChild,
			ChildNodeType		theNewChild)
{
	assert(theParent != 0);
	assert(theNewChild != 0);

	if (theLastChild == 0)
	{
		theParent->appendChildNode(theNewChild);
	}
	else
	{
		XalanSourceTreeHelper::appendSibling(theLastChild, theNewChild);
	}

	theLastChild = theNewChild;
}

// A helper function to manage appending the new child.
template <class ChildNodeType>
inline void
doAppendChildNode(
			XalanSourceTreeDocument*			theDocument,
			XalanSourceTreeDocumentFragment*	theDocumentFragment,
			XalanSourceTreeElement*				theCurrentElement,
			XalanNode*&							theLastChild,
			ChildNodeType						theNewChild)
{
	assert(theDocument != 0);
	assert(theNewChild != 0);

	if (theCurrentElement == 0)
	{
		if (theDocumentFragment != 0)
		{
			doAppendChildNode(theDocumentFragment, theLastChild, theNewChild);
		}
		else
		{
			// If there is no current element. it means we haven't
			// created the document element yet, so always append
			// to the document, rather than the last child.
			theDocument->appendChildNode(theNewChild);
		}
	}
	else
	{
		doAppendChildNode(theCurrentElement, theLastChild, theNewChild);
	}
}

void
FormatterToSourceTree::startElement(
			const	XMLCh* const	name,
			AttributeList&			attrs)
{
	processAccumulatedText();

	XalanSourceTreeElement* const	theNewElement =
		createElementNode(name, attrs, m_currentElement);

	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			theNewElement);

	m_elementStack.push_back(theNewElement);

	m_lastChildStack.push_back(m_lastChild);

	m_currentElement = theNewElement;

	m_lastChild = 0;
}

void
FormatterToSourceTree::endElement(const	XMLCh* const	/* name */)
{
	processAccumulatedText();

	assert(m_elementStack.empty() == false);

	// Pop the element of the stack...
	m_elementStack.pop_back();

	assert(m_elementStack.empty() == false);

	// Get the element from the back of the
	// stack.
	m_currentElement = m_elementStack.back();

	assert(m_lastChildStack.empty() == false);

	m_lastChild = m_lastChildStack.back();

	// Pop the last child stack
	m_lastChildStack.pop_back();
}

void
FormatterToSourceTree::characters(
			const XMLCh* const	chars,
			const unsigned int	length)
{
	if (m_documentFragment != 0)
	{
		doCharacters(chars, length);
	}
	else if (m_currentElement == 0)
	{
		if (isXMLWhitespace(chars) == false)
		{
			throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
		}
	}
	else
	{
		append(m_textBuffer, chars, length);
	}
}

void
FormatterToSourceTree::charactersRaw(
		const XMLCh* const	chars,
		const unsigned int	length)
{
	assert(m_document != 0);

	processAccumulatedText();

	doProcessingInstruction(c_wstr(s_xsltNextIsRawString), c_wstr(s_formatterListenerString));

	characters(chars, length);
}

void
FormatterToSourceTree::entityReference(const XMLCh* const	/* name */)
{
}

void
FormatterToSourceTree::ignorableWhitespace(
			const XMLCh* const	chars,
			const unsigned int	length)
{
	assert(m_document != 0);

	// Ignore any whitespace reported before the document element has been parsed.
	if (m_elementStack.empty() == false)
	{
		assert(m_documentFragment != 0 || m_document->getDocumentElement() != 0);

		processAccumulatedText();

		XalanSourceTreeText* const	theNewTextNode =
			m_document->createTextIWSNode(chars, length, m_currentElement);

		doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
	}
	else if(m_documentFragment != 0)
	{
		processAccumulatedText();

		XalanSourceTreeText* const	theNewTextNode =
			m_document->createTextIWSNode(chars, length, m_currentElement);

		doAppendChildNode(m_currentElement, m_lastChild, theNewTextNode);
	}
}

void
FormatterToSourceTree::processingInstruction(
			const XMLCh* const	target,
			const XMLCh* const	data)
{
	assert(m_document != 0);

	processAccumulatedText();

	doProcessingInstruction(target, data);
}

void
FormatterToSourceTree::resetDocument()
{
}

void
FormatterToSourceTree::comment(const XMLCh* const	data)
{
	assert(m_document != 0);

	processAccumulatedText();

	XalanSourceTreeComment* const	theNewComment =
		m_document->createCommentNode(data, length(data), m_currentElement);

	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			theNewComment);
}

void
FormatterToSourceTree::cdata(
			const XMLCh* const	/* ch */,
			const unsigned int 	/* length */)
{
}

void
FormatterToSourceTree::processAccumulatedText()
{
	if (isEmpty(m_textBuffer) == false)
	{
		doCharacters(c_wstr(m_textBuffer), length(m_textBuffer));

		clear(m_textBuffer);
	}
}

void
FormatterToSourceTree::doCharacters(
			const XMLCh*				chars,
			XalanDOMString::size_type	length)
{
	if (m_currentElement != 0)
	{
		doAppendChildNode(
			m_currentElement,
			m_lastChild,
			m_document->createTextNode(chars, length, m_currentElement));
	}
	else if (m_documentFragment != 0)
	{
		doAppendChildNode(
			m_documentFragment,
			m_lastChild,
			m_document->createTextNode(chars, length, m_currentElement));
	}
	else
	{
		throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
	}
}

XalanSourceTreeElement*
FormatterToSourceTree::createElementNode(
			const XalanDOMChar*			name,
			AttributeList&				attrs,
			XalanSourceTreeElement*		theParentElement)
{
	if (m_prefixResolver != 0)
	{
		return m_document->createElementNode(name, attrs, *m_prefixResolver, theParentElement);
	}
	else
	{
		return m_document->createElementNode(name, attrs, theParentElement);
	}
}

void
FormatterToSourceTree::doProcessingInstruction(
			const XMLCh*	target,
			const XMLCh*	data)
{
	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			m_document->createProcessingInstructionNode(target, data));
}
<commit_msg>Fixed glitch in ignorableWhitespace() and removed variable.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
// Class header file.
#include "FormatterToSourceTree.hpp"

#include <cassert>

#include <sax/AttributeList.hpp>

#include <XalanDOM/XalanDOMException.hpp>
#include <XalanDOM/XalanDocumentFragment.hpp>

#include <PlatformSupport/DOMStringHelper.hpp>
#include <PlatformSupport/PrefixResolver.hpp>

#include <XMLSupport/FormatterToDOM.hpp>

#include "XalanSourceTreeComment.hpp"
#include "XalanSourceTreeDocument.hpp"
#include "XalanSourceTreeDocumentFragment.hpp"
#include "XalanSourceTreeElement.hpp"
#include "XalanSourceTreeHelper.hpp"
#include "XalanSourceTreeProcessingInstruction.hpp"
#include "XalanSourceTreeText.hpp"

FormatterToSourceTree::FormatterToSourceTree(XalanSourceTreeDocument*	theDocument) :
	FormatterListener(OUTPUT_METHOD_DOM),
	m_document(theDocument),
	m_documentFragment(0),
	m_currentElement(0),
	m_elementStack(),
	m_lastChild(0),
	m_lastChildStack(),
	m_textBuffer()
{
}

FormatterToSourceTree::FormatterToSourceTree(
			XalanSourceTreeDocument*			theDocument,
			XalanSourceTreeDocumentFragment*	theDocumentFragment) :
	FormatterListener(OUTPUT_METHOD_DOM),
	m_document(theDocument),
	m_documentFragment(theDocumentFragment),
	m_currentElement(0),
	m_elementStack(),
	m_lastChild(0),
	m_lastChildStack(),
	m_textBuffer()
{
	assert(m_document != 0);
	assert(m_documentFragment != 0);
}

FormatterToSourceTree::~FormatterToSourceTree()
{
}

void
FormatterToSourceTree::setDocumentLocator(const Locator* const		/* locator */)
{
}

void
FormatterToSourceTree::startDocument()
{
	m_currentElement = 0;

	m_elementStack.clear();

	m_lastChild = 0;

	m_lastChildStack.clear();

	m_lastChildStack.reserve(eDefaultStackSize);

	clear(m_textBuffer);

	reserve(m_textBuffer, eDefaultTextBufferSize);

	// Push a dummy value for the current element, so we
	// don't have to check for an empty stack in endElement().
	m_elementStack.push_back(ElementStackType::value_type(0));
}

void
FormatterToSourceTree::endDocument()
{
	// Pop off the dummy value that we pushed in
	// startDocument()...
	m_elementStack.pop_back();

	assert(m_elementStack.empty() == true);
	assert(m_lastChildStack.empty() == true);
	assert(isEmpty(m_textBuffer) == true);
}

// A helper function to manage appending the new child.
template <class ParentNodeType, class ChildNodeType>
inline void
doAppendChildNode(
			ParentNodeType*		theParent,
			XalanNode*&			theLastChild,
			ChildNodeType		theNewChild)
{
	assert(theParent != 0);
	assert(theNewChild != 0);

	if (theLastChild == 0)
	{
		theParent->appendChildNode(theNewChild);
	}
	else
	{
		XalanSourceTreeHelper::appendSibling(theLastChild, theNewChild);
	}

	theLastChild = theNewChild;
}

// A helper function to manage appending the new child.
template <class ChildNodeType>
inline void
doAppendChildNode(
			XalanSourceTreeDocument*			theDocument,
			XalanSourceTreeDocumentFragment*	theDocumentFragment,
			XalanSourceTreeElement*				theCurrentElement,
			XalanNode*&							theLastChild,
			ChildNodeType						theNewChild)
{
	assert(theDocument != 0);
	assert(theNewChild != 0);

	if (theCurrentElement == 0)
	{
		if (theDocumentFragment != 0)
		{
			doAppendChildNode(theDocumentFragment, theLastChild, theNewChild);
		}
		else
		{
			// If there is no current element. it means we haven't
			// created the document element yet, so always append
			// to the document, rather than the last child.
			theDocument->appendChildNode(theNewChild);
		}
	}
	else
	{
		doAppendChildNode(theCurrentElement, theLastChild, theNewChild);
	}
}

void
FormatterToSourceTree::startElement(
			const	XMLCh* const	name,
			AttributeList&			attrs)
{
	processAccumulatedText();

	XalanSourceTreeElement* const	theNewElement =
		createElementNode(name, attrs, m_currentElement);

	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			theNewElement);

	m_elementStack.push_back(theNewElement);

	m_lastChildStack.push_back(m_lastChild);

	m_currentElement = theNewElement;

	m_lastChild = 0;
}

void
FormatterToSourceTree::endElement(const	XMLCh* const	/* name */)
{
	processAccumulatedText();

	assert(m_elementStack.empty() == false);

	// Pop the element of the stack...
	m_elementStack.pop_back();

	assert(m_elementStack.empty() == false);

	// Get the element from the back of the
	// stack.
	m_currentElement = m_elementStack.back();

	assert(m_lastChildStack.empty() == false);

	m_lastChild = m_lastChildStack.back();

	// Pop the last child stack
	m_lastChildStack.pop_back();
}

void
FormatterToSourceTree::characters(
			const XMLCh* const	chars,
			const unsigned int	length)
{
	if (m_documentFragment != 0)
	{
		doCharacters(chars, length);
	}
	else if (m_currentElement == 0)
	{
		if (isXMLWhitespace(chars) == false)
		{
			throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
		}
	}
	else
	{
		append(m_textBuffer, chars, length);
	}
}

void
FormatterToSourceTree::charactersRaw(
		const XMLCh* const	chars,
		const unsigned int	length)
{
	assert(m_document != 0);

	processAccumulatedText();

	doProcessingInstruction(c_wstr(s_xsltNextIsRawString), c_wstr(s_formatterListenerString));

	characters(chars, length);
}

void
FormatterToSourceTree::entityReference(const XMLCh* const	/* name */)
{
}

void
FormatterToSourceTree::ignorableWhitespace(
			const XMLCh* const	chars,
			const unsigned int	length)
{
	assert(m_document != 0);

	// Ignore any whitespace reported before the document element has been parsed.
	if (m_elementStack.empty() == false)
	{
		assert(m_documentFragment != 0 || m_document->getDocumentElement() != 0);

		processAccumulatedText();

		doAppendChildNode(
			m_currentElement,
			m_lastChild,
			m_document->createTextIWSNode(chars, length, m_currentElement));
	}
	else if(m_documentFragment != 0)
	{
		processAccumulatedText();

		doAppendChildNode(
			m_documentFragment,
			m_lastChild,
			m_document->createTextIWSNode(chars, length, m_currentElement));
	}
}

void
FormatterToSourceTree::processingInstruction(
			const XMLCh* const	target,
			const XMLCh* const	data)
{
	assert(m_document != 0);

	processAccumulatedText();

	doProcessingInstruction(target, data);
}

void
FormatterToSourceTree::resetDocument()
{
}

void
FormatterToSourceTree::comment(const XMLCh* const	data)
{
	assert(m_document != 0);

	processAccumulatedText();

	XalanSourceTreeComment* const	theNewComment =
		m_document->createCommentNode(data, length(data), m_currentElement);

	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			theNewComment);
}

void
FormatterToSourceTree::cdata(
			const XMLCh* const	/* ch */,
			const unsigned int 	/* length */)
{
}

void
FormatterToSourceTree::processAccumulatedText()
{
	if (isEmpty(m_textBuffer) == false)
	{
		doCharacters(c_wstr(m_textBuffer), length(m_textBuffer));

		clear(m_textBuffer);
	}
}

void
FormatterToSourceTree::doCharacters(
			const XMLCh*				chars,
			XalanDOMString::size_type	length)
{
	if (m_currentElement != 0)
	{
		doAppendChildNode(
			m_currentElement,
			m_lastChild,
			m_document->createTextNode(chars, length, m_currentElement));
	}
	else if (m_documentFragment != 0)
	{
		doAppendChildNode(
			m_documentFragment,
			m_lastChild,
			m_document->createTextNode(chars, length, m_currentElement));
	}
	else
	{
		throw XalanDOMException(XalanDOMException::HIERARCHY_REQUEST_ERR);
	}
}

XalanSourceTreeElement*
FormatterToSourceTree::createElementNode(
			const XalanDOMChar*			name,
			AttributeList&				attrs,
			XalanSourceTreeElement*		theParentElement)
{
	if (m_prefixResolver != 0)
	{
		return m_document->createElementNode(name, attrs, *m_prefixResolver, theParentElement);
	}
	else
	{
		return m_document->createElementNode(name, attrs, theParentElement);
	}
}

void
FormatterToSourceTree::doProcessingInstruction(
			const XMLCh*	target,
			const XMLCh*	data)
{
	doAppendChildNode(
			m_document,
			m_documentFragment,
			m_currentElement,
			m_lastChild,
			m_document->createProcessingInstructionNode(target, data));
}
<|endoftext|>


<commit_before>
//Description:
//Threshold a voxel dataset where we only extract the exterior faces and
//pass those faces to openGL for rendering

#include <dax/cont/Scheduler.h>
#include <dax/cont/ArrayHandle.h>
#include <dax/cont/ArrayHandleCounting.h>
#include <dax/cont/UnstructuredGrid.h>
#include <dax/CellTag.h>
#include <dax/CellTraits.h>

#include <dax/math/Compare.h> //Min && Max
#include <dax/math/Precision.h> //Floor
#include <dax/math/Trig.h> //Sin Cos, etc
#include <dax/math/VectorAnalysis.h> //Normal && Cross

//exec headers we need
#include <dax/exec/internal/WorkletBase.h> //required for error handling
#include <dax/exec/CellVertices.h>

//headers we need for opengl support
#include <dax/opengl/testing/WindowBase.h>
#include <dax/opengl/TransferToOpenGL.h>

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

namespace
{
typedef dax::Tuple<unsigned char,4> ColorType;

class InitFields : public dax::exec::WorkletMapField
{
  dax::Id XDim, YDim;
public:
  typedef void ControlSignature(Field(In), Field(In), Field(In), Field(Out), Field(Out), Field(Out));
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);

  InitFields(dax::Id mesh_x_dim, dax::Id mesh_y_dim):
    XDim(mesh_x_dim), YDim(mesh_y_dim)
    {}

  DAX_EXEC_EXPORT
  void operator()(dax::Id index,
                  dax::Scalar frequency,
                  dax::Vector2 seeds,
                  dax::Vector3& coord,
                  ColorType& color,
                  dax::Vector2& velocity ) const
  {
    //compute our places given the flat index
    const dax::Id x_index = index % XDim;
    const dax::Id y_index = index / YDim;

    //compute out our coords
    coord[0] = x_index / static_cast<dax::Scalar>(XDim) + seeds[0];
    coord[1] = y_index / static_cast<dax::Scalar>(YDim) + seeds[1];
    coord[2] = dax::math::Sin(coord[0]*frequency) *
               dax::math::Cos(coord[1]*frequency) * 0.2f;

    //compute the starting color and velcity
    color=ColorType(0,255,255,1);
    velocity=dax::make_Vector2(0.0f,0.0f);

  }
};

class ComputeStep : public dax::exec::WorkletMapField
{
  dax::Scalar TimeStep;
  dax::Id XDim, YDim;
  dax::Scalar MouseX, MouseY;
public:
  typedef void ControlSignature(Field(In), Field(In), Field(In), Field(In), Field(Out), Field(Out), Field(Out));
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7);

  ComputeStep(dax::Scalar time, dax::Id mesh_x_dim, dax::Id mesh_y_dim,
              dax::Scalar mouse_x, dax::Scalar mouse_y):
    TimeStep(time),XDim(mesh_x_dim), YDim(mesh_y_dim),
    MouseX(mouse_x), MouseY(mouse_y)
    {}

  DAX_EXEC_EXPORT
  void operator()(dax::Id index,
                  dax::Scalar frequency,
                  const dax::Vector3& in_pos,
                  const dax::Vector2& in_vel,
                  dax::Vector3& pos,
                  ColorType& color,
                  dax::Vector2& vel ) const
  {
    const dax::Scalar speed = 0.0005f;

    const dax::Id x_index = index % XDim;
    const dax::Id y_index = index / YDim;

    const dax::Scalar xX = (this->MouseX - XDim/2 + 128)/(float)XDim*4.5f;
    const dax::Scalar yY = (this->MouseY - YDim/2 + 128)/(float)YDim*4.5f;
    const dax::Scalar u = x_index / (float) XDim;
    const dax::Scalar v = y_index / (float) YDim;

    const dax::Vector2 computed_xyz(-in_pos[0] + xX, -in_pos[2] + yY);
    const dax::Vector2 normalized = dax::math::Normal(computed_xyz);
    vel = in_vel + normalized;

    const dax::Scalar updated_speed = dax::math::Sqrt(dax::dot(vel,vel));
    const dax::Scalar original_speed = dax::math::Sqrt(dax::dot(computed_xyz,computed_xyz));

    if(updated_speed >= 0.125f)
      {
      vel[0] = normalized[0]/original_speed*0.1f;
      vel[1] = normalized[1]/original_speed*0.1f;
      }

    pos[0] = in_pos[0] + vel[0] * updated_speed;
    pos[1] = dax::math::Sin(u*frequency + TimeStep) *
             dax::math::Cos(v*frequency + TimeStep) * 0.2f;
    pos[2] = in_pos[2] + vel[1] * updated_speed;

    color = ColorType(128/original_speed,(int)(255/(original_speed*51)),255,10);

  }
};

struct TwizzledGLHandles
{
  //stores two sets of handles, each time
  //you call for the handles it switches
  //what ones it returns
  TwizzledGLHandles()
    {
    this->State = 0;
    }

  void initHandles()
  {
    glGenBuffers(2,CoordHandles);
    glGenBuffers(2,ColorHandles);

    glBindBuffer(GL_ARRAY_BUFFER, CoordHandles[0]);
    glBindBuffer(GL_ARRAY_BUFFER, CoordHandles[1]);
    glBindBuffer(GL_ARRAY_BUFFER, ColorHandles[0]);
    glBindBuffer(GL_ARRAY_BUFFER, ColorHandles[1]);
  }

  void handles(GLuint& coord, GLuint& color) const
    {
    coord = CoordHandles[this->State%2];
    color = ColorHandles[this->State%2];
    }

  void switchHandles()
    {
    ++this->State;
    }
private:
  GLuint CoordHandles[2];
  GLuint ColorHandles[2];
  unsigned int State; //when we roll over we need to stay positive
};

class particle_renderer :
                  public dax::opengl::testing::WindowBase<particle_renderer>
{
private:
  GLvoid* bufferObjectPtr( unsigned int idx )
    {
    return (GLvoid*) ( ((char*)NULL) + idx );
    }

  dax::cont::Scheduler<> Scheduler;
  dax::cont::ArrayHandle<dax::Vector2> SeedHandle;
  dax::cont::ArrayHandle<dax::Vector3> ParticleCoords;
  dax::cont::ArrayHandle<dax::Vector2> ParticleVelocity;
  dax::cont::ArrayHandle<ColorType> ParticleColors;

  unsigned int XDim, YDim;
  dax::Scalar TimeStep;
  dax::Scalar Frequency;

  float MouseX, MouseY, RotateX, RotateY, TranslateZ;
  int ActiveMouseButtons;

  //gl array ids that hold the rendering info
  TwizzledGLHandles TwizzleHandles;

public:
  DAX_CONT_EXPORT particle_renderer( unsigned int x_dim,
                                     unsigned int y_dim,
                                     std::vector<dax::Vector2>& seeds)
  {
  //this doesn't copy the data it just references the vectors internal data
  this->XDim = x_dim;
  this->YDim = y_dim;
  this->SeedHandle = dax::cont::make_ArrayHandle(seeds);

  this->MouseX = 0;
  this->MouseY = 0;
  this->ActiveMouseButtons = 0;

  this->TimeStep = 0.0f;
  this->Frequency = 2.42f;

  this->RotateX = 0;
  this->RotateY = 0;
  this->TranslateZ = -3.0;
  }

  void construct_starting_data()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    //pass the initial seed data
    InitFields init(this->XDim,this->YDim);
    const dax::Id size = this->XDim * this->YDim;

    this->Scheduler.Invoke(init,
                           dax::cont::make_ArrayHandleCounting(0,size),
                           this->Frequency,
                           this->SeedHandle,
                           this->ParticleCoords,
                           this->ParticleColors,
                           this->ParticleVelocity);

    this->SeedHandle.ReleaseResourcesExecution();
    //now push that to opengl
    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);

    this->TwizzleHandles.switchHandles();
    this->TwizzleHandles.handles(coord,color);
    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);

  }

  void compute_next_step()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    ComputeStep compu_step(this->TimeStep, this->XDim, this->YDim,
                           this->MouseX, this->MouseY);
    const dax::Id size = this->XDim * this->YDim;

    this->Scheduler.Invoke(compu_step,
                           dax::cont::make_ArrayHandleCounting(0,size),
                           this->Frequency,
                           this->ParticleCoords,
                           this->ParticleVelocity,
                           this->ParticleCoords,
                           this->ParticleColors,
                           this->ParticleVelocity);

    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);
  }

  //called after opengl is inited, this is where we can set our gl flags
  DAX_CONT_EXPORT void PostInit()
  {
    //init the gl handles for the twizzler
    this->TwizzleHandles.initHandles();

    glDisable(GL_DEPTH_TEST);
    glShadeModel(GL_SMOOTH);

    // good old-fashioned fixed function lighting
    float white[4] = { 0.8, 0.8, 0.8, 1.0 };
    float lightPos[4] = { 100.0, 100.0, -100.0, 1.0 };

    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);

    glLightfv(GL_LIGHT0, GL_AMBIENT, white);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
    glLightfv(GL_LIGHT0, GL_SPECULAR, white);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);

    glClearColor(0.0, 0.0, 0.0, 1.0);
    //Viewport
    glViewport(0, 0, 800.0f, 600.0f);

    //Projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, (800.0f /  600.0f), 0.1, 10.0);

    this->construct_starting_data();
  }

  DAX_CONT_EXPORT void Display()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //View matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glTranslatef(0.0, 0.0, this->TranslateZ);
    glRotatef(90.0, 1.0, 0.0, 0.0);

    //Render from VBO
    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, coord);
    glVertexPointer(3, GL_FLOAT, 0, bufferObjectPtr(0) );

    glEnableClientState(GL_COLOR_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, color);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, bufferObjectPtr(0) );

    const dax::Id size = this->XDim * this->YDim;

    glDrawArrays(GL_POINTS, 0, size);

    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    glutSwapBuffers();
    glutPostRedisplay();

    this->TimeStep += 0.01;

    this->TwizzleHandles.switchHandles();
    this->compute_next_step();
  }

  DAX_CONT_EXPORT void Idle(){ }

  DAX_CONT_EXPORT void ChangeSize(int daxNotUsed(w), int daxNotUsed(h)) {}

  DAX_CONT_EXPORT void Key(unsigned char key, int daxNotUsed(x), int daxNotUsed(y) )
  {
    switch(key)
      {
      case(27):
        exit(0);
      default:
        break;
      }
  }

  DAX_CONT_EXPORT void SpecialKey(int key,
                                  int daxNotUsed(x), int daxNotUsed(y) )
  {
  }

  DAX_CONT_EXPORT void Mouse(int button, int state,
                             int x, int y )
  {
  }

  DAX_CONT_EXPORT void MouseMove(int x, int y )
  {
    this->MouseX = x;
    this->MouseY = y;
  }
};

struct seed_rand
{
  dax::Vector2 operator()() const
  {
    dax::Vector2 vec;
    vec[0] = ((std::rand() % 100) - 100) / 2400.0f;
    vec[1] = ((std::rand() % 100) - 100) / 2400.0f;
    return vec;
  }
};
}

int main(int, char**)
{
  const unsigned int x_dim = 1024;
  const unsigned int y_dim = 1024;
  std::vector<dax::Vector2> seeds(x_dim*y_dim);

  //fill the vector with random numbers
  std::srand(42); //I like this seed :-)
  std::generate(seeds.begin(),seeds.end(),seed_rand());

  //setup the input to threshold
  particle_renderer renderer(x_dim,y_dim,seeds);

  //init the render window
  renderer.Init("Particle Demo", 800, 600);

  //start drawing
  renderer.Start();
  return 0;
}
<commit_msg>More work on the particle dax demo.<commit_after>
//Description:
//Threshold a voxel dataset where we only extract the exterior faces and
//pass those faces to openGL for rendering

#include <dax/cont/Scheduler.h>
#include <dax/cont/ArrayHandle.h>
#include <dax/cont/ArrayHandleCounting.h>
#include <dax/cont/UnstructuredGrid.h>
#include <dax/CellTag.h>
#include <dax/CellTraits.h>

#include <dax/math/Compare.h> //Min && Max
#include <dax/math/Precision.h> //Floor
#include <dax/math/Trig.h> //Sin Cos, etc
#include <dax/math/VectorAnalysis.h> //Normal && Cross

//exec headers we need
#include <dax/exec/internal/WorkletBase.h> //required for error handling
#include <dax/exec/CellVertices.h>

//headers we need for opengl support
#include <dax/opengl/testing/WindowBase.h>
#include <dax/opengl/TransferToOpenGL.h>

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

namespace
{
typedef dax::Tuple<unsigned char,4> ColorType;

class InitFields : public dax::exec::WorkletMapField
{
  dax::Id XDim, YDim;
public:
  typedef void ControlSignature(Field(In), Field(In), Field(In), Field(Out), Field(Out), Field(Out));
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6);

  InitFields(dax::Id mesh_x_dim, dax::Id mesh_y_dim):
    XDim(mesh_x_dim), YDim(mesh_y_dim)
    {}

  DAX_EXEC_EXPORT
  void operator()(dax::Id index,
                  dax::Scalar frequency,
                  dax::Vector2 seeds,
                  dax::Vector3& coord,
                  ColorType& color,
                  dax::Vector2& velocity ) const
  {
    //compute our places given the flat index
    const dax::Id x_index = index % XDim;
    const dax::Id y_index = index / YDim;

    //compute out our coords
    coord[0] = x_index / static_cast<dax::Scalar>(XDim) + seeds[0];
    coord[1] = y_index / static_cast<dax::Scalar>(YDim) + seeds[1];
    coord[2] = dax::math::Sin(coord[0]*frequency) *
               dax::math::Cos(coord[1]*frequency) * 0.2f;

    //compute the starting color and velcity
    color=ColorType(0,255,255,1);
    velocity=dax::make_Vector2(0.0f,0.0f);

  }
};

class PauseStep : public dax::exec::WorkletMapField
{
  dax::Scalar TimeStep;
  dax::Id XDim, YDim;
  dax::Scalar MouseX, MouseY;
public:
  typedef void ControlSignature(Field(In), Field(In), Field(In), Field(In), Field(Out), Field(Out), Field(Out));
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7);

  PauseStep(dax::Scalar time, dax::Id mesh_x_dim, dax::Id mesh_y_dim,
              dax::Scalar mouse_x, dax::Scalar mouse_y):
    TimeStep(time),XDim(mesh_x_dim), YDim(mesh_y_dim),
    MouseX(mouse_x), MouseY(mouse_y)
    {}

  DAX_EXEC_EXPORT
  void operator()(dax::Id index,
                  dax::Scalar frequency,
                  const dax::Vector3& in_pos,
                  const dax::Vector2& in_vel,
                  dax::Vector3& pos,
                  ColorType& color,
                  dax::Vector2& vel ) const
  {
    const dax::Scalar speed = 0.05f;
    const dax::Id x_index = index % XDim;
    const dax::Id y_index = index / YDim;

    const dax::Scalar xX = (this->MouseX - XDim/2 + 128)/(float)XDim*4.5f;
    const dax::Scalar yY = (this->MouseY - YDim/2 + 128)/(float)YDim*4.5f;
    const dax::Scalar u = x_index / (float) XDim;
    const dax::Scalar v = y_index / (float) YDim;

    vel[0] = 0; vel[1]=0;

    const dax::Vector2 computed_xyz(-in_pos[0] + xX, -in_pos[2] + yY);
    const dax::Scalar rmag = dax::math::RMagnitude(computed_xyz);

    pos[0]= in_pos[0] + (computed_xyz[0] * speed) * rmag;
    pos[0]= in_pos[0] + (computed_xyz[0] * speed) * rmag;

    color = ColorType(255*rmag,255*rmag, 255, 10);
    pos[1] = dax::math::Sin(u*frequency + TimeStep) *
             dax::math::Cos(v*frequency + TimeStep) * 0.2f;
  }
};

class ComputeStep : public dax::exec::WorkletMapField
{
  dax::Scalar TimeStep;
  dax::Id XDim, YDim;
  dax::Scalar MouseX, MouseY;
public:
  typedef void ControlSignature(Field(In), Field(In), Field(In), Field(In), Field(Out), Field(Out), Field(Out));
  typedef void ExecutionSignature(_1, _2, _3, _4, _5, _6, _7);

  ComputeStep(dax::Scalar time, dax::Id mesh_x_dim, dax::Id mesh_y_dim,
              dax::Scalar mouse_x, dax::Scalar mouse_y):
    TimeStep(time),XDim(mesh_x_dim), YDim(mesh_y_dim),
    MouseX(mouse_x), MouseY(mouse_y)
    {}

  DAX_EXEC_EXPORT
  void operator()(dax::Id index,
                  dax::Scalar frequency,
                  const dax::Vector3& in_pos,
                  const dax::Vector2& in_vel,
                  dax::Vector3& pos,
                  ColorType& color,
                  dax::Vector2& vel ) const
  {
    const dax::Id x_index = index % XDim;
    const dax::Id y_index = index / YDim;

    const dax::Scalar xX = (this->MouseX - XDim/2 + 128)/(float)XDim*4.5f;
    const dax::Scalar yY = (this->MouseY - YDim/2 + 128)/(float)YDim*4.5f;
    const dax::Scalar u = x_index / (float) XDim;
    const dax::Scalar v = y_index / (float) YDim;

    const dax::Vector2 computed_xyz(-in_pos[0] + xX, -in_pos[2] + yY);

    const dax::Scalar rmag = dax::math::RMagnitude(computed_xyz);
    dax::Vector2 normalized = (computed_xyz * rmag);
    vel = normalized * rmag * 0.1f;

    pos[0] = in_pos[0] + vel[0];
    pos[1] = dax::math::Sin(u*frequency + TimeStep) *
             dax::math::Cos(v*frequency + TimeStep) * 0.2f;
    pos[2] = in_pos[2] + vel[1];

    color = ColorType(140*rmag,70*rmag,255,10);

  }
};

struct TwizzledGLHandles
{
  //stores two sets of handles, each time
  //you call for the handles it switches
  //what ones it returns
  TwizzledGLHandles()
    {
    this->State = 0;
    }

  void initHandles()
  {
    glGenBuffers(2,CoordHandles);
    glGenBuffers(2,ColorHandles);

    glBindBuffer(GL_ARRAY_BUFFER, CoordHandles[0]);
    glBindBuffer(GL_ARRAY_BUFFER, CoordHandles[1]);
    glBindBuffer(GL_ARRAY_BUFFER, ColorHandles[0]);
    glBindBuffer(GL_ARRAY_BUFFER, ColorHandles[1]);
  }

  void handles(GLuint& coord, GLuint& color) const
    {
    coord = CoordHandles[this->State%2];
    color = ColorHandles[this->State%2];
    }

  void switchHandles()
    {
    ++this->State;
    }
private:
  GLuint CoordHandles[2];
  GLuint ColorHandles[2];
  unsigned int State; //when we roll over we need to stay positive
};

class particle_renderer :
                  public dax::opengl::testing::WindowBase<particle_renderer>
{
private:
  GLvoid* bufferObjectPtr( unsigned int idx )
    {
    return (GLvoid*) ( ((char*)NULL) + idx );
    }

  dax::cont::Scheduler<> Scheduler;
  dax::cont::ArrayHandle<dax::Vector2> SeedHandle;
  dax::cont::ArrayHandle<dax::Vector3> ParticleCoords;
  dax::cont::ArrayHandle<dax::Vector2> ParticleVelocity;
  dax::cont::ArrayHandle<ColorType> ParticleColors;

  unsigned int XDim, YDim;
  dax::Scalar TimeStep;
  dax::Scalar Frequency;

  float MouseX, MouseY, RotateX, RotateY, TranslateZ;
  int ActiveMouseButtons;

  //gl array ids that hold the rendering info
  TwizzledGLHandles TwizzleHandles;

public:
  DAX_CONT_EXPORT particle_renderer( unsigned int x_dim,
                                     unsigned int y_dim,
                                     std::vector<dax::Vector2>& seeds)
  {
  //this doesn't copy the data it just references the vectors internal data
  this->XDim = x_dim;
  this->YDim = y_dim;
  this->SeedHandle = dax::cont::make_ArrayHandle(seeds);

  this->MouseX = 0;
  this->MouseY = 0;
  this->ActiveMouseButtons = 0;

  this->TimeStep = 0.0f;
  this->Frequency = 1.42f;

  this->RotateX = 0;
  this->RotateY = 0;
  this->TranslateZ = -3.0;
  }

  void construct_starting_data()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    //pass the initial seed data
    InitFields init(this->XDim,this->YDim);
    const dax::Id size = this->XDim * this->YDim;

    this->Scheduler.Invoke(init,
                           dax::cont::make_ArrayHandleCounting(0,size),
                           this->Frequency,
                           this->SeedHandle,
                           this->ParticleCoords,
                           this->ParticleColors,
                           this->ParticleVelocity);

    this->SeedHandle.ReleaseResourcesExecution();
    //now push that to opengl
    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);

    this->TwizzleHandles.switchHandles();
    this->TwizzleHandles.handles(coord,color);
    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);

  }

  void compute_next_step()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    ComputeStep compu_step(this->TimeStep, this->XDim, this->YDim,
                           this->MouseX, this->MouseY);
    const dax::Id size = this->XDim * this->YDim;

    this->Scheduler.Invoke(compu_step,
                           dax::cont::make_ArrayHandleCounting(0,size),
                           this->Frequency,
                           this->ParticleCoords,
                           this->ParticleVelocity,
                           this->ParticleCoords,
                           this->ParticleColors,
                           this->ParticleVelocity);

    dax::opengl::TransferToOpenGL(this->ParticleCoords, coord);
    dax::opengl::TransferToOpenGL(this->ParticleColors, color);
  }

  //called after opengl is inited, this is where we can set our gl flags
  DAX_CONT_EXPORT void PostInit()
  {
    //init the gl handles for the twizzler
    this->TwizzleHandles.initHandles();

    glDisable(GL_DEPTH_TEST);
    glShadeModel(GL_SMOOTH);

    // good old-fashioned fixed function lighting
    float white[4] = { 0.8, 0.8, 0.8, 1.0 };
    float lightPos[4] = { 100.0, 100.0, -100.0, 1.0 };

    glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, white);
    glMaterialf(GL_FRONT_AND_BACK, GL_SHININESS, 100);

    glLightfv(GL_LIGHT0, GL_AMBIENT, white);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
    glLightfv(GL_LIGHT0, GL_SPECULAR, white);
    glLightfv(GL_LIGHT0, GL_POSITION, lightPos);

    glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, 1);

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);
    glEnable(GL_COLOR_MATERIAL);

    glClearColor(0.0, 0.0, 0.0, 1.0);
    //Viewport
    glViewport(0, 0, 800.0f, 600.0f);

    //Projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60.0, (800.0f /  600.0f), 0.1, 10.0);

    this->construct_starting_data();
  }

  DAX_CONT_EXPORT void Display()
  {
    GLuint coord, color;
    this->TwizzleHandles.handles(coord,color);

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    //View matrix
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glTranslatef(0.0, 0.0, this->TranslateZ);
    glRotatef(90.0, 1.0, 0.0, 0.0);

    //Render from VBO
    glEnableClientState(GL_VERTEX_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, coord);
    glVertexPointer(3, GL_FLOAT, 0, bufferObjectPtr(0) );

    glEnableClientState(GL_COLOR_ARRAY);
    glBindBuffer(GL_ARRAY_BUFFER, color);
    glColorPointer(4, GL_UNSIGNED_BYTE, 0, bufferObjectPtr(0) );

    const dax::Id size = this->XDim * this->YDim;
    glDrawArrays(GL_POINTS, 0, size);

    glDisableClientState(GL_COLOR_ARRAY);
    glDisableClientState(GL_VERTEX_ARRAY);

    glutSwapBuffers();
    glutPostRedisplay();

    this->TimeStep += 0.01;

    this->TwizzleHandles.switchHandles();
    this->compute_next_step();
  }

  DAX_CONT_EXPORT void Idle(){ }

  DAX_CONT_EXPORT void ChangeSize(int daxNotUsed(w), int daxNotUsed(h)) {}

  DAX_CONT_EXPORT void Key(unsigned char key, int daxNotUsed(x), int daxNotUsed(y) )
  {
    switch(key)
      {
      case(27):
        exit(0);
      default:
        break;
      }
  }

  DAX_CONT_EXPORT void SpecialKey(int key,
                                  int daxNotUsed(x), int daxNotUsed(y) )
  {
  }

  DAX_CONT_EXPORT void Mouse(int button, int state,
                             int x, int y )
  {
  }

  DAX_CONT_EXPORT void MouseMove(int x, int y )
  {
    this->MouseX = x;
    this->MouseY = y;
  }
};

struct seed_rand
{
  dax::Vector2 operator()() const
  {
    dax::Vector2 vec;
    vec[0] = ((std::rand() % 100) - 100) / 2400.0f;
    vec[1] = ((std::rand() % 100) - 100) / 2400.0f;
    return vec;
  }
};
}

int main(int, char**)
{
  const unsigned int x_dim = 1024;
  const unsigned int y_dim = 1024;
  std::vector<dax::Vector2> seeds(x_dim*y_dim);

  //fill the vector with random numbers
  std::srand(42); //I like this seed :-)
  std::generate(seeds.begin(),seeds.end(),seed_rand());

  //setup the input to threshold
  particle_renderer renderer(x_dim,y_dim,seeds);

  //init the render window
  renderer.Init("Particle Demo", 800, 600);

  //start drawing
  renderer.Start();
  return 0;
}
<|endoftext|>


<commit_before>#include "PreProcessor.h"
#include "MacroAssemblerLibraries.h"
#include "LexicalScanner.h"
#include <sstream>
#include <regex>
#include <cctype>

using std::regex;
using std::regex_match;

regex labelRegex("(.+)?\\:");
regex ifRegex("IF[[:space:]](.+)", std::regex_constants::icase);

PreProcessor::PreProcessor(string inputFileName,string outputFileName) {
	lineCount = 0;
	this->inputFileName = inputFileName;
	this->outputFileName = outputFileName;
	failed = false;
	preProcessingZone = true;
}

PreProcessor::~PreProcessor() {
}

bool PreProcessor::PreProcessPass(ifstream& stream) {
	string line;
	bool writeThisDown;
	vector<string> tokens;

	while (stream.good()) {

		tokens.clear();
		writeThisDown = true;

		line = getNextLine(stream);

		StringLibrary::Tokenize(line, " ",tokens);

		if (tokens.size() < 1) {
			continue; // ignora linhas sem tokens
		}

		if (preProcessingZone && tokens.size() >1) {
			preProcessingZone = !((tokens[0] == "section") || (tokens[0] == "begin" || tokens[1] == "begin"));
		}

		if (IsEQU(tokens)) {
			EvaluateEQU(tokens);
			writeThisDown = false;
		} else if (StringLibrary::CompareInsensitive(tokens[0],"if")) {
			writeThisDown = EvaluateIf(line, stream);
		}

		line = StringLibrary::Trim(line);

		if (writeThisDown && line != "") {
			outputContent << line + "\n";
		}
	}

	stream.close();

	if (failed) {
		printf("Erros de pre-processamento encontrados. O arquivo .pre nao foi gerado\n");
		return false;
	}

	printf("arquivo %s.pre gerado com sucesso\n", outputFileName.c_str());
	saveFile();
	return true;
}

void PreProcessor::EvaluateEQU(const vector<string>& equTokens) {

	if (!preProcessingZone) {
		printError("Diretiva EQU precisa ser definida no inicio do codigo", ErrorPrinter::ErrorType::Syntatic);
		return;
	}

	string identifier = equTokens[0].substr(0, equTokens[0].find(':'));
	if (valueTable.find(identifier) != valueTable.end()) {
		string errorMessage = "Simbolo textual " + identifier + " ja definido.";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return;
	}

	if (isdigit(identifier[0])) {
		string errorMessage = "Identificador " + identifier + " invalido. Primeiro caractere nao pode ser um digito";
		printError(errorMessage,ErrorPrinter::ErrorType::Lexic);
	}

	if (identifier.size() > 50) {
		string errorMessage = "Simbolo textual nao deve possuir mais de 50 caracteres.";
		printError(errorMessage,ErrorPrinter::ErrorType::Lexic);
	}

	if (equTokens.size() > 3) {
		printError("EQU deve possuir apenas 1 operando", ErrorPrinter::ErrorType::Syntatic);
		return;
	}

	if (!StringLibrary::IsInteger(equTokens[2])) {
		printError("Operando do EQU precisa ser um inteiro", ErrorPrinter::ErrorType::Semantic);
		return;
	}

	int valueNumber = std::stoi(equTokens[2], nullptr);

	valueTable.emplace(std::make_pair(identifier, valueNumber));
}

bool PreProcessor::IsEQU(vector<string> tokensLidos) {
	return tokensLidos.size() > 1 && regex_match(tokensLidos[0], labelRegex) && StringLibrary::CompareInsensitive(tokensLidos[1], "equ");
}

bool PreProcessor::EvaluateIf(string & line, istream & stream) {
	vector<string> members;
	StringLibrary::Tokenize(line, " ", members);

	if (members.size() != 2) {
		string errorMessage = "A diretiva if deve possuir somente 1 operando";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return false;
	}

	auto element = valueTable.find(members[1]);
	if (element == valueTable.end()) {
		string errorMessage = "Simbolo " + members[1] + " nao definido";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return false;
	}
	line = getNextLine(stream);

	vector<string> tokens;
	StringLibrary::Tokenize(line, " ", tokens);
	if (IsEQU(tokens)) {
		printError("Diretiva EQU precisa ser definida no inicio do codigo",ErrorPrinter::ErrorType::Semantic);
	}

	return element->second == 1;
}

string PreProcessor::getNextLine(istream & stream) {
	lineCount++;

	string formatedLine;
	std::getline(stream, formatedLine);
	formatedLine = StringLibrary::ToLower(formatedLine);
	LexicalScanner::RemoveComments(formatedLine);
	return StringLibrary::RemoveExcessiveSpaces(formatedLine);
}

void PreProcessor::printError(string message, ErrorPrinter::ErrorType type) {
	failed = true;
	ErrorPrinter::ShowError(type, inputFileName, lineCount, message);
}

void PreProcessor::saveFile() {
	fstream outputStream;
	string fileName = outputFileName + ".pre";

	outputStream.open(fileName, std::fstream::out);
	outputStream << outputContent.rdbuf();
	outputStream.close();
}
<commit_msg>Removidos espaços desnecessários no começo e no final do arquivo<commit_after>#include "PreProcessor.h"
#include "MacroAssemblerLibraries.h"
#include "LexicalScanner.h"
#include <sstream>
#include <regex>
#include <cctype>

using std::regex;
using std::regex_match;

regex labelRegex("(.+)?\\:");
regex ifRegex("IF[[:space:]](.+)", std::regex_constants::icase);

PreProcessor::PreProcessor(string inputFileName,string outputFileName) {
	lineCount = 0;
	this->inputFileName = inputFileName;
	this->outputFileName = outputFileName;
	failed = false;
	preProcessingZone = true;
}

PreProcessor::~PreProcessor() {
}

bool PreProcessor::PreProcessPass(ifstream& stream) {
	string line;
	bool writeThisDown;
	vector<string> tokens;

	while (stream.good()) {

		tokens.clear();
		writeThisDown = true;

		line = getNextLine(stream);

		StringLibrary::Tokenize(line, " ",tokens);

		if (tokens.size() < 1) {
			continue; // ignora linhas sem tokens
		}

		if (preProcessingZone && tokens.size() >1) {
			preProcessingZone = !((tokens[0] == "section") || (tokens[0] == "begin" || tokens[1] == "begin"));
		}

		if (IsEQU(tokens)) {
			EvaluateEQU(tokens);
			writeThisDown = false;
		} else if (StringLibrary::CompareInsensitive(tokens[0],"if")) {
			writeThisDown = EvaluateIf(line, stream);
		}

		line = StringLibrary::Trim(line);

		if (writeThisDown && line != "") {
			if (outputContent.rdbuf() -> in_avail() == 0) {
				outputContent << line;
			} else {
				outputContent << "\n" + line;
			}

		}
	}

	stream.close();

	if (failed) {
		printf("Erros de pre-processamento encontrados. O arquivo .pre nao foi gerado\n");
		return false;
	}

	printf("arquivo %s.pre gerado com sucesso\n", outputFileName.c_str());
	saveFile();
	return true;
}

void PreProcessor::EvaluateEQU(const vector<string>& equTokens) {

	if (!preProcessingZone) {
		printError("Diretiva EQU precisa ser definida no inicio do codigo", ErrorPrinter::ErrorType::Syntatic);
		return;
	}

	string identifier = equTokens[0].substr(0, equTokens[0].find(':'));
	if (valueTable.find(identifier) != valueTable.end()) {
		string errorMessage = "Simbolo textual " + identifier + " ja definido.";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return;
	}

	if (isdigit(identifier[0])) {
		string errorMessage = "Identificador " + identifier + " invalido. Primeiro caractere nao pode ser um digito";
		printError(errorMessage,ErrorPrinter::ErrorType::Lexic);
	}

	if (identifier.size() > 50) {
		string errorMessage = "Simbolo textual nao deve possuir mais de 50 caracteres.";
		printError(errorMessage,ErrorPrinter::ErrorType::Lexic);
	}

	if (equTokens.size() > 3) {
		printError("EQU deve possuir apenas 1 operando", ErrorPrinter::ErrorType::Syntatic);
		return;
	}

	if (!StringLibrary::IsInteger(equTokens[2])) {
		printError("Operando do EQU precisa ser um inteiro", ErrorPrinter::ErrorType::Semantic);
		return;
	}

	int valueNumber = std::stoi(equTokens[2], nullptr);

	valueTable.emplace(std::make_pair(identifier, valueNumber));
}

bool PreProcessor::IsEQU(vector<string> tokensLidos) {
	return tokensLidos.size() > 1 && regex_match(tokensLidos[0], labelRegex) && StringLibrary::CompareInsensitive(tokensLidos[1], "equ");
}

bool PreProcessor::EvaluateIf(string & line, istream & stream) {
	vector<string> members;
	StringLibrary::Tokenize(line, " ", members);

	if (members.size() != 2) {
		string errorMessage = "A diretiva if deve possuir somente 1 operando";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return false;
	}

	auto element = valueTable.find(members[1]);
	if (element == valueTable.end()) {
		string errorMessage = "Simbolo " + members[1] + " nao definido";
		printError(errorMessage,ErrorPrinter::ErrorType::Semantic);
		return false;
	}
	line = getNextLine(stream);

	vector<string> tokens;
	StringLibrary::Tokenize(line, " ", tokens);
	if (IsEQU(tokens)) {
		printError("Diretiva EQU precisa ser definida no inicio do codigo",ErrorPrinter::ErrorType::Semantic);
	}

	return element->second == 1;
}

string PreProcessor::getNextLine(istream & stream) {
	lineCount++;

	string formatedLine;
	std::getline(stream, formatedLine);
	formatedLine = StringLibrary::ToLower(formatedLine);
	LexicalScanner::RemoveComments(formatedLine);
	return StringLibrary::RemoveExcessiveSpaces(formatedLine);
}

void PreProcessor::printError(string message, ErrorPrinter::ErrorType type) {
	failed = true;
	ErrorPrinter::ShowError(type, inputFileName, lineCount, message);
}

void PreProcessor::saveFile() {
	fstream outputStream;
	string fileName = outputFileName + ".pre";

	outputStream.open(fileName, std::fstream::out);
	outputStream << outputContent.rdbuf();
	outputStream.close();
}
<|endoftext|>