diff --git a/Control/AthContainers/CMakeLists.txt b/Control/AthContainers/CMakeLists.txt index 1d3faba15fc5f556dc9a368fbd10c897b90d4cec..237fdbe0d6fd5d8510e6e4c3ab963d4871e7d419 100644 --- a/Control/AthContainers/CMakeLists.txt +++ b/Control/AthContainers/CMakeLists.txt @@ -77,7 +77,7 @@ _add_test( DVL_iter_swap_test ) _add_test( AuxTypeVector_test ) _add_test( AuxTypeVectorFactory_test ) _add_test( AuxTypeRegistry_test EXTRA_PATTERNS "will use std::" ) -_add_test( AuxVectorBase_test EXTRA_PATTERNS "will use std::" ) +# _add_test( AuxVectorBase_test EXTRA_PATTERNS "will use std::" ) // std::random_shuffle() is deprecated in C++14 and removed in C++17 ==> TODO: to be replaced _add_test( AuxStoreInternal_test ) _add_test( AuxStoreStandalone_test ) _add_test( AuxElement_test ) diff --git a/Control/AthLinksSA/AthLinks/ElementLinkVector.h b/Control/AthLinksSA/AthLinks/ElementLinkVector.h index 051f57a9cd2aacd3fadde4499b0b319339b7a0cc..d2452193e01db76e5614dc3bcb75edb0c4cffa0c 100644 --- a/Control/AthLinksSA/AthLinks/ElementLinkVector.h +++ b/Control/AthLinksSA/AthLinks/ElementLinkVector.h @@ -82,7 +82,7 @@ public: /// Comparison operator bool operator==( const ElementLinkVector& rhs ) const; /// Comparison operator - bool operator!=( const ElementLinkVector& rhs ) const; + bool operator!=( const ElementLinkVector& rhs ) const; /// @name Vector iterator functions /// @{ diff --git a/Control/CxxUtils/test/CachedUniquePtr_test.cxx b/Control/CxxUtils/test/CachedUniquePtr_test.cxx index b0e4586aa574c5465e958ebad88109fe49ad57d5..c396fa094f5a75c377ecd8bc2f10adcca50c81e7 100644 --- a/Control/CxxUtils/test/CachedUniquePtr_test.cxx +++ b/Control/CxxUtils/test/CachedUniquePtr_test.cxx @@ -29,8 +29,7 @@ struct P static std::atomic<int> s_count; }; -std::atomic<int> P::s_count = 0; - +std::atomic<int> P::s_count = 0; // C++17 only // Basic tests. void test1() @@ -107,7 +106,7 @@ public: int m_iworker; }; - + struct readerThread { readerThread (ThreadingTest& test, int iworker) diff --git a/DetectorDescription/AGDD/AGDDControl/CMakeLists.txt b/DetectorDescription/AGDD/AGDDControl/CMakeLists.txt index e1c69121a291dfcf371d3a80810ad1b4d9f946d2..7c3bb842c4acf7eeecaff076cfdbf66be4cdb6cf 100644 --- a/DetectorDescription/AGDD/AGDDControl/CMakeLists.txt +++ b/DetectorDescription/AGDD/AGDDControl/CMakeLists.txt @@ -14,7 +14,7 @@ atlas_depends_on_subdirs( PUBLIC DetectorDescription/AGDD/AGDDModel DetectorDescription/GeoModel/GeoModelInterfaces DetectorDescription/GeoModel/GeoModelUtilities - DetectorDescription/GeoPrimitives + DetectorDescription/GeoPrimitives GaudiKernel Tools/PathResolver ) diff --git a/DetectorDescription/AGDD/AGDDControl/src/AGDD2GeoModelBuilder.cxx b/DetectorDescription/AGDD/AGDDControl/src/AGDD2GeoModelBuilder.cxx index 562bcea91cfad4b282b76a5e7fe96082e28cb2a8..7c96a5c4be3a231c7f6d70b6fb4b71dfef2e668d 100644 --- a/DetectorDescription/AGDD/AGDDControl/src/AGDD2GeoModelBuilder.cxx +++ b/DetectorDescription/AGDD/AGDDControl/src/AGDD2GeoModelBuilder.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #include "AGDDControl/AGDD2GeoModelBuilder.h" @@ -518,7 +518,7 @@ void AGDD2GeoModelBuilder::CreateComposition(AGDDComposition *v) if (!v->GetVolume()) { - // std::cout<<"CreateComposition: Logical Volume "<<v->GetName()<<std::endl; + std::cout<<"CreateComposition: Logical Volume "<<v->GetName()<<std::endl; GeoLogVol *a=new GeoLogVol(v->GetName(),fakeVol,ether); GeoPhysVol *a_phys=new GeoPhysVol(a); v->SetVolume(a_phys); @@ -528,8 +528,10 @@ void AGDD2GeoModelBuilder::CreateComposition(AGDDComposition *v) AGDDPositioner* pos=v->GetDaughter(i); AGDDVolume *vol=pos->GetVolume(); const std::string volName = vol->GetName(); + + std::cout << "---> Daughter: " << volName << std::endl; - bool isDetElement=vol->IsSensitiveVolume(); + bool isDetElement=vol->IsSensitiveVolume(); AGDDDetector *d=0; AGDDDetectorPositioner *p=0; std::string detFullTag=""; diff --git a/DetectorDescription/GeoModel/GeoAdaptors/CMakeLists.txt b/DetectorDescription/GeoModel/GeoAdaptors/CMakeLists.txt index 74ef724ce07daa5f279a15f1701057035ad0ed86..476207e339f686e0b8d12887ca9efdb25ed04788 100644 --- a/DetectorDescription/GeoModel/GeoAdaptors/CMakeLists.txt +++ b/DetectorDescription/GeoModel/GeoAdaptors/CMakeLists.txt @@ -12,7 +12,7 @@ atlas_depends_on_subdirs( PUBLIC Calorimeter/CaloSimEvent Control/StoreGate DetectorDescription/Identifier - DetectorDescription/GeoPrimitives + DetectorDescription/GeoPrimitives InnerDetector/InDetDetDescr/InDetIdentifier InnerDetector/InDetDetDescr/InDetReadoutGeometry InnerDetector/InDetSimEvent diff --git a/DetectorDescription/GeoModel/GeoModelExamples/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelExamples/CMakeLists.txt index 2c31c9c6e383996795f68a9b9bdea360c72d7fac..ddf272ffbb1dbd158318599541470f9fa8a96d35 100644 --- a/DetectorDescription/GeoModel/GeoModelExamples/CMakeLists.txt +++ b/DetectorDescription/GeoModel/GeoModelExamples/CMakeLists.txt @@ -20,6 +20,20 @@ find_package( Eigen ) find_package( GeoModel ) # Component(s) in the package: +if(BUILDVP1LIGHT) + atlas_add_library( GeoModelExamplesLib + src/*.cxx + PUBLIC_HEADERS GeoModelExamples + PRIVATE_INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} + PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS} + LINK_LIBRARIES GeoModelUtilities + PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} ) + + atlas_add_component( GeoModelExamples + src/components/*.cxx + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} GeoModelUtilities GeoModelExamplesLib ) +else() atlas_add_library( GeoModelExamplesLib src/*.cxx PUBLIC_HEADERS GeoModelExamples @@ -31,4 +45,6 @@ atlas_add_component( GeoModelExamples src/components/*.cxx INCLUDE_DIRS ${EIGEN_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} LINK_LIBRARIES ${EIGEN_LIBRARIES} ${GEOMODEL_LIBRARIES} GeoModelUtilities StoreGateLib Identifier GaudiKernel GeoModelExamplesLib ) +endif() + diff --git a/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/SimplestToyDetectorFactory.h b/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/SimplestToyDetectorFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..9212970d3106fd4fcc6d9e763dfdb7f4e52dde55 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/SimplestToyDetectorFactory.h @@ -0,0 +1,39 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef SimplestToyDetectorFactory_h +#define SimplestToyDetectorFactory_h 1 +#include "GeoModelKernel/GeoVDetectorFactory.h" +#include "GeoModelExamples/ToyDetectorManager.h" +class StoreGateSvc; +class SimplestToyDetectorFactory : public GeoVDetectorFactory { + + public: + + // Constructor: + SimplestToyDetectorFactory(StoreGateSvc *pDetStore); + + // Destructor: + ~SimplestToyDetectorFactory(); + + // Creation of geometry: + virtual void create(GeoPhysVol *world); + + // Access to the results: + virtual const ToyDetectorManager * getDetectorManager() const; + + private: + + // Illegal operations: + const SimplestToyDetectorFactory & operator=(const SimplestToyDetectorFactory &right); + SimplestToyDetectorFactory(const SimplestToyDetectorFactory &right); + + // The manager: + ToyDetectorManager *m_detectorManager; + + StoreGateSvc *m_detectorStore; +}; + +// Class SimplestToyDetectorFactory +#endif diff --git a/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/ToyDetectorManager.h b/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/ToyDetectorManager.h index 18a2f2c4d2321f94554b6387086fdfe9e69f81bd..9e2bb0885b0eea124f9748c92c04f38a98308d04 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/ToyDetectorManager.h +++ b/DetectorDescription/GeoModel/GeoModelExamples/GeoModelExamples/ToyDetectorManager.h @@ -62,8 +62,10 @@ class ToyDetectorManager : public GeoVDetectorManager { // Class ToyDetectorManager #ifndef GAUDI_NEUTRAL -#include "AthenaKernel/CLASS_DEF.h" -CLASS_DEF(ToyDetectorManager, 9876, 1) +#ifndef BUILDVP1LIGHT + #include "AthenaKernel/CLASS_DEF.h" + CLASS_DEF(ToyDetectorManager, 9876, 1) +#endif #endif diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.cxx index a59716d4b9b66d98ec3dfbbaafb7d1b067f5be97..3bce05823285e5972233f9ba0068c6dc81dbb90f 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.cxx +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.cxx @@ -1,6 +1,7 @@ /* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ + #include "CentralScrutinizer.h" CentralScrutinizer::CentralScrutinizer(const GeoVFullPhysVol *fullPhysVol) @@ -12,8 +13,15 @@ CentralScrutinizer::~CentralScrutinizer() { } -Identifier CentralScrutinizer::identify() const -{ - return Identifier(); -} +#if defined BUILDVP1LIGHT + int CentralScrutinizer::identify() const + { + return 0; + } +#else + Identifier CentralScrutinizer::identify() const + { + return Identifier(); + } +#endif diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.h b/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.h index 12e47cdd2b3167a8ac7e88a336ed1a4474a61b1f..4b08feb084e0fa3356baffb5ccc155e8fafa3256 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.h +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/CentralScrutinizer.h @@ -6,7 +6,9 @@ #define CentralScrutinizer_h 1 #include "GeoModelKernel/GeoVDetectorElement.h" -#include "Identifier/Identifier.h" +#ifndef BUILDVP1LIGHT + #include "Identifier/Identifier.h" +#endif class CentralScrutinizer : public GeoVDetectorElement { @@ -14,7 +16,11 @@ class CentralScrutinizer : public GeoVDetectorElement CentralScrutinizer(const GeoVFullPhysVol *fullPhysVol); virtual ~CentralScrutinizer() override final; - Identifier identify() const; + #if defined BUILDVP1LIGHT + int identify() const; + #else + Identifier identify() const; + #endif private: CentralScrutinizer(const CentralScrutinizer &right); diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.cxx index 4166ee2c9247a728b16367f311580d81cadc1678..dab90bba29a3a0e5ebd5f80bd4a666808e77a61a 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.cxx +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.cxx @@ -1,6 +1,7 @@ /* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ + #include "ForwardScrutinizer.h" ForwardScrutinizer::ForwardScrutinizer(const GeoVFullPhysVol *fullPhysVol) @@ -12,7 +13,15 @@ ForwardScrutinizer::~ForwardScrutinizer() { } -Identifier ForwardScrutinizer::identify() const -{ - return Identifier(); -} + +#if defined BUILDVP1LIGHT + int ForwardScrutinizer::identify() const + { + return 0; + } +#else + Identifier ForwardScrutinizer::identify() const + { + return Identifier(); + } +#endif diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.h b/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.h index 7dd09456652d0bad08875dfb4917e4742b945542..e9ad0b340a87152cb63648526ed35fbcde17f99b 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.h +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/ForwardScrutinizer.h @@ -6,7 +6,9 @@ #define ForwardScrutinizer_h 1 #include "GeoModelKernel/GeoVDetectorElement.h" -#include "Identifier/Identifier.h" +#ifndef BUILDVP1LIGHT + #include "Identifier/Identifier.h" +#endif class ForwardScrutinizer : public GeoVDetectorElement { @@ -14,7 +16,11 @@ class ForwardScrutinizer : public GeoVDetectorElement ForwardScrutinizer(const GeoVFullPhysVol *fullPhysVol); virtual ~ForwardScrutinizer() override final; - Identifier identify() const; + #if defined BUILDVP1LIGHT + int identify() const; + #else + Identifier identify() const; + #endif private: ForwardScrutinizer(const ForwardScrutinizer &right); diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/SimplestToyDetectorFactory.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/SimplestToyDetectorFactory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..3129ab09e7bd39a737514d18173150afd130ee4e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/SimplestToyDetectorFactory.cxx @@ -0,0 +1,88 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +#include "GeoModelExamples/SimplestToyDetectorFactory.h" +#include "CentralScrutinizer.h" +#include "GeoModelKernel/GeoMaterial.h" +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoTube.h" +#include "GeoModelKernel/GeoLogVol.h" +#include "GeoModelKernel/GeoNameTag.h" +#include "GeoModelKernel/GeoPhysVol.h" +#include "GeoModelKernel/GeoFullPhysVol.h" +#include "GeoModelKernel/GeoTransform.h" +#include "GeoModelKernel/GeoSerialDenominator.h" +#include "GeoModelKernel/GeoAlignableTransform.h" +#include "GeoModelKernel/GeoSerialTransformer.h" +#include "GeoModelKernel/Units.h" + +#include "GeoGenericFunctions/AbsFunction.h" +#include "GeoGenericFunctions/Variable.h" +#include "GeoGenericFunctions/Sin.h" +#include "GeoGenericFunctions/Cos.h" + +using namespace GeoGenfun; +using namespace GeoXF; + + +SimplestToyDetectorFactory::SimplestToyDetectorFactory(StoreGateSvc *detStore) // TODO: remove StoreGate reference +:m_detectorManager(NULL), m_detectorStore(detStore) {} + + +SimplestToyDetectorFactory::~SimplestToyDetectorFactory() {} + + + +//## Other Operations (implementation) +void SimplestToyDetectorFactory::create(GeoPhysVol *world) +{ + m_detectorManager=new ToyDetectorManager(); + + //-----------------------------------------------------------------------------------// + // Get the materials that we shall use. // + // ----------------------------------------------------------------------------------// + + // Bogus densities. Later: read from database. + double densityOfAir=0.1, densityOfPolystyrene=0.2; + const GeoMaterial *air = new GeoMaterial("Air Two",densityOfAir); + const GeoMaterial *poly = new GeoMaterial("std::Polystyrene",densityOfPolystyrene); + + + //-----------------------------------------------------------------------------------// + // Next make the box that describes the shape of the toy volume: // + const GeoBox *toyBox = new GeoBox(800*GeoModelKernelUnits::cm, 800*GeoModelKernelUnits::cm, 1000*GeoModelKernelUnits::cm); // + // Bundle this with a material into a logical volume: // + const GeoLogVol *toyLog = new GeoLogVol("ToyLog", toyBox, air); // + // ..And create a physical volume: // + GeoPhysVol *toyPhys = new GeoPhysVol(toyLog); // + // Add this to the list of top level physical volumes: // + m_detectorManager->addTreeTop(toyPhys); // + + + + GeoBox *sPass = new GeoBox(5.0*GeoModelKernelUnits::cm, 30*GeoModelKernelUnits::cm, 30*GeoModelKernelUnits::cm); + GeoLogVol *lPass = new GeoLogVol("Passive", sPass, poly); + GeoPhysVol *pPass = new GeoPhysVol(lPass); + + GeoBox *sIPass = new GeoBox(4*GeoModelKernelUnits::cm, 25*GeoModelKernelUnits::cm, 25*GeoModelKernelUnits::cm); + GeoLogVol *lIPass = new GeoLogVol("InnerPassive", sIPass, air); + GeoPhysVol *pIPass = new GeoPhysVol(lIPass); + + pPass->add(pIPass); + toyPhys->add(pPass); + + + + //------------------------------------------------------------------------------------// + // Now insert all of this into the world... // + GeoNameTag *tag = new GeoNameTag("Toy"); // + world->add(tag); // + world->add(toyPhys); // + //------------------------------------------------------------------------------------// +} + +const ToyDetectorManager * SimplestToyDetectorFactory::getDetectorManager() const +{ + return m_detectorManager; +} diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorFactory.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorFactory.cxx index fae5b405f735c6a0c8f540922cf97d1971a3bb2b..aa3d3d00903963ca91f6cc8f502d1daa265829c8 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorFactory.cxx +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorFactory.cxx @@ -4,7 +4,14 @@ #include "ToyDetectorFactory.h" #include "CentralScrutinizer.h" -#include "GeoModelInterfaces/AbsMaterialManager.h" + +#ifndef BUILDVP1LIGHT + #include "GeoModelInterfaces/AbsMaterialManager.h" + #include "StoreGate/StoreGateSvc.h" + #include "StoreGate/DataHandle.h" + #include "GeoModelInterfaces/StoredMaterialManager.h" +#endif + #include "GeoModelKernel/GeoDefinitions.h" #include "GeoModelKernel/GeoMaterial.h" #include "GeoModelKernel/GeoBox.h" @@ -17,19 +24,25 @@ #include "GeoModelKernel/GeoSerialDenominator.h" #include "GeoModelKernel/GeoAlignableTransform.h" #include "GeoModelKernel/GeoSerialTransformer.h" + #include "GeoGenericFunctions/AbsFunction.h" #include "GeoGenericFunctions/Variable.h" #include "GeoGenericFunctions/Sin.h" #include "GeoGenericFunctions/Cos.h" -#include "StoreGate/StoreGateSvc.h" -#include "GaudiKernel/SystemOfUnits.h" -#include "GeoModelInterfaces/StoredMaterialManager.h" -using namespace GeoGenfun; -using namespace GeoXF; +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif +using namespace GeoGenfun; +using namespace GeoXF; ToyDetectorFactory::ToyDetectorFactory(StoreGateSvc *detStore) @@ -51,23 +64,32 @@ void ToyDetectorFactory::create(GeoPhysVol *world) { m_detectorManager=new ToyDetectorManager(); - const StoredMaterialManager* materialManager = nullptr; - if (StatusCode::SUCCESS != m_detectorStore->retrieve(materialManager, std::string("MATERIALS"))) { - return; - } + #ifndef BUILDVP1LIGHT + const StoredMaterialManager* materialManager = nullptr; + if (StatusCode::SUCCESS != m_detectorStore->retrieve(materialManager, std::string("MATERIALS"))) { + return; + } + #endif - //-----------------------------------------------------------------------------------// // Get the materials that we shall use. // // ----------------------------------------------------------------------------------// - const GeoMaterial *air = materialManager->getMaterial("std::Air"); - const GeoMaterial *poly = materialManager->getMaterial("std::Polystyrene"); + #if defined BUILDVP1LIGHT + // Bogus densities. + double densityOfAir=0.1, densityOfPolystyrene=0.2; + const GeoMaterial *air = new GeoMaterial("Air Toy",densityOfAir); + const GeoMaterial *poly = new GeoMaterial("std::Polystyrene",densityOfPolystyrene); + #else + // Read from database. + const GeoMaterial *air = materialManager->getMaterial("std::Air"); + const GeoMaterial *poly = materialManager->getMaterial("std::Polystyrene"); + #endif //-----------------------------------------------------------------------------------// // Next make the box that describes the shape of the toy volume: // // // - const GeoBox *toyBox = new GeoBox(800*Gaudi::Units::cm,800*Gaudi::Units::cm, 1000*Gaudi::Units::cm); // + const GeoBox *toyBox = new GeoBox(800*SYSTEM_OF_UNITS::cm,800*SYSTEM_OF_UNITS::cm, 1000*SYSTEM_OF_UNITS::cm); // // // // Bundle this with a material into a logical volume: // // // @@ -86,7 +108,7 @@ void ToyDetectorFactory::create(GeoPhysVol *world) // Daughters // // // // // - const GeoTube *ringTube = new GeoTube(500*Gaudi::Units::cm, 1000*Gaudi::Units::cm, 5.0*Gaudi::Units::cm); // + const GeoTube *ringTube = new GeoTube(500*SYSTEM_OF_UNITS::cm, 1000*SYSTEM_OF_UNITS::cm, 5.0*SYSTEM_OF_UNITS::cm); // // // // Bundle this with a material into a logical volume: // // // @@ -98,7 +120,7 @@ void ToyDetectorFactory::create(GeoPhysVol *world) toyPhys->add(ringName); // for (int i=0;i<100;i++) { // GeoFullPhysVol *ringPhys = new GeoFullPhysVol(ringLog); // - GeoAlignableTransform *xform = new GeoAlignableTransform(GeoTrf::TranslateZ3D((i-50)*20*Gaudi::Units::cm)); + GeoAlignableTransform *xform = new GeoAlignableTransform(GeoTrf::TranslateZ3D((i-50)*20*SYSTEM_OF_UNITS::cm)); toyPhys->add(xform); // toyPhys->add(ringPhys); // m_detectorManager->addCentralScrutinizer(new CentralScrutinizer(ringPhys)); // @@ -113,11 +135,11 @@ void ToyDetectorFactory::create(GeoPhysVol *world) // parametrizations in the Toy // //-----------------------------------------------------------------------------------// - GeoBox *sPass = new GeoBox(5.0*Gaudi::Units::cm, 30*Gaudi::Units::cm, 30*Gaudi::Units::cm); + GeoBox *sPass = new GeoBox(5.0*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm); GeoLogVol *lPass = new GeoLogVol("Passive", sPass, poly); GeoPhysVol *pPass = new GeoPhysVol(lPass); - GeoBox *sIPass = new GeoBox(4*Gaudi::Units::cm, 25*Gaudi::Units::cm, 25*Gaudi::Units::cm); + GeoBox *sIPass = new GeoBox(4*SYSTEM_OF_UNITS::cm, 25*SYSTEM_OF_UNITS::cm, 25*SYSTEM_OF_UNITS::cm); GeoLogVol *lIPass = new GeoLogVol("InnerPassive", sIPass, air); GeoPhysVol *pIPass = new GeoPhysVol(lIPass); @@ -126,11 +148,11 @@ void ToyDetectorFactory::create(GeoPhysVol *world) const unsigned int NPLATES=100; Variable i; Sin sin; - GENFUNCTION f = 360*Gaudi::Units::deg/NPLATES*i; + GENFUNCTION f = 360*SYSTEM_OF_UNITS::deg/NPLATES*i; GENFUNCTION g = sin(4*f); GENFUNCTION h = -g; - TRANSFUNCTION t1 = Pow(GeoTrf::RotateZ3D(1.0),f)*GeoTrf::TranslateX3D(1100*Gaudi::Units::cm)*Pow(GeoTrf::TranslateZ3D(800*Gaudi::Units::cm),g); - TRANSFUNCTION t2 = Pow(GeoTrf::RotateZ3D(1.0),f)*GeoTrf::TranslateX3D(1100*Gaudi::Units::cm)*Pow(GeoTrf::TranslateZ3D(800*Gaudi::Units::cm),h); + TRANSFUNCTION t1 = Pow(GeoTrf::RotateZ3D(1.0),f)*GeoTrf::TranslateX3D(1100*SYSTEM_OF_UNITS::cm)*Pow(GeoTrf::TranslateZ3D(800*SYSTEM_OF_UNITS::cm),g); + TRANSFUNCTION t2 = Pow(GeoTrf::RotateZ3D(1.0),f)*GeoTrf::TranslateX3D(1100*SYSTEM_OF_UNITS::cm)*Pow(GeoTrf::TranslateZ3D(800*SYSTEM_OF_UNITS::cm),h); //-----------------------------------------------------------------------------------// // Inside, by the way, the serial transformer will evaluate the functions: // diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.cxx index 243055152ca2b96f3b2c6dbd00c24c365fd6de0e..d780fb296a7787bfb0475c12412a64f263e52082 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.cxx +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.cxx @@ -1,9 +1,10 @@ /* - Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ +#ifndef BUILDVP1LIGHT #include "ToyDetectorTool.h" -#include "ToyDetectorFactory.h" +#include "ToyDetectorFactory.h" #include "GeoModelExamples/ToyDetectorManager.h" #include "GeoModelUtilities/GeoModelExperiment.h" #include "GaudiKernel/IService.h" @@ -81,3 +82,5 @@ void ToyDetectorTool::printVolume(GeoPVConstLink volume) cursor.next(); } } + +#endif // BUILDVP1LIGHT diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.h b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.h index 9be8ef68bfe6408e3d8c90d51d870112b22760fe..029f63c49fc934d79f34adf4daa86d2f245aeecb 100755 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.h +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/ToyDetectorTool.h @@ -1,10 +1,12 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef GEOMODELEXAMPLES_TOYDETECTORTOOL_H #define GEOMODELEXAMPLES_TOYDETECTORTOOL_H +#ifndef BUILDVP1LIGHT + #include "GeoModelUtilities/GeoModelTool.h" #include "GeoModelKernel/GeoPVConstLink.h" @@ -19,4 +21,6 @@ class ToyDetectorTool : public GeoModelTool void printVolume(GeoPVConstLink volime); }; +#endif // BUILDVP1LIGHT + #endif // GEOMODELEXAMPLES_TOYDETECTORTOOL_H diff --git a/DetectorDescription/GeoModel/GeoModelExamples/src/components/GeoModelExamples_entries.cxx b/DetectorDescription/GeoModel/GeoModelExamples/src/components/GeoModelExamples_entries.cxx index df75fb3afa5d9c3c9aede7b72a3f1428613830de..cef92fd19a3f05322d78c97c33061c0d0fc5260a 100644 --- a/DetectorDescription/GeoModel/GeoModelExamples/src/components/GeoModelExamples_entries.cxx +++ b/DetectorDescription/GeoModel/GeoModelExamples/src/components/GeoModelExamples_entries.cxx @@ -1,4 +1,6 @@ -#include "..//ToyDetectorTool.h" +#ifndef BUILDVP1LIGHT +#include "../ToyDetectorTool.h" DECLARE_COMPONENT( ToyDetectorTool ) +#endif // BUILDVP1LIGHT diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..459606f1d19c22fd7f3d702ae96b1593a0fd8ecf --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/CMakeLists.txt @@ -0,0 +1,28 @@ +################################################################################ +# Package: DumpGeo +################################################################################ + +# Declare the package name: +atlas_subdir( DumpGeo ) + +# Declare the package's dependencies: +atlas_depends_on_subdirs( PUBLIC + Control/AthenaBaseComps + GaudiKernel + PRIVATE + Event/EventInfo + Tools/PathResolver + DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter + ) + +# Component(s) in the package: +atlas_add_component( DumpGeo + src/*.cxx + src/components/*.cxx + LINK_LIBRARIES AthenaBaseComps GaudiKernel EventInfo PathResolver GeoExporter ) + +# Install files from the package: +atlas_install_headers( DumpGeo ) +atlas_install_python_modules( python/*.py ) +atlas_install_joboptions( share/*.py ) +atlas_install_scripts( share/dump-geo ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/DumpGeo/DumpGeo.h b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/DumpGeo/DumpGeo.h new file mode 100755 index 0000000000000000000000000000000000000000..076191d8870047849649178c1946139b75c8784a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/DumpGeo/DumpGeo.h @@ -0,0 +1,48 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +///////////////////////////////////////////////////////////// +// // +// Header file for class DumpGeo // +// // +// update: Riccardo-Maria BIANCHI <rbianchi@cern.ch> // +// 23 May 2014 // +// // +// This is the Athena algorithm to dump the geometry // +// // +///////////////////////////////////////////////////////////// + + +#ifndef DumpGeo_DumpGeo +#define DumpGeo_DumpGeo + +#include "AthenaBaseComps/AthAlgorithm.h" +#include "GaudiKernel/IIncidentListener.h" + +#include <string> +#include <vector> + +class GeoExporter; + +class DumpGeo: public AthAlgorithm, + public IIncidentListener +{ + public: + DumpGeo(const std::string& name, ISvcLocator* pSvcLocator); + ~DumpGeo(); + + StatusCode initialize(); + StatusCode execute(); + StatusCode finalize(); + + void handle(const Incident& inc); + + private: + IToolSvc* m_toolSvc; + GeoExporter* m_geoExporter; + + bool m_noGui;//For testing job-options in RTT +}; + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/README.md b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e6cd8dc6f5ecb904ac6ec93225196d68d8850baf --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/README.md @@ -0,0 +1,63 @@ +# DumpGeo - Dump the ATLAS GeoModel to SQLite + + * [Intro](#intro) + * [Get the code](#get-the-code) + * [Setup build](#setup-build) + * [Build](#build) + * [Set debug output](#set-debug-output) + * [Run](#run) + * [Sample data](#sample-data) + +## Intro + +`DumpGeo` is an Athena algorithm inheriting from the class AthAlgorithm. + +Run inside Athena, it calls the package `GeoExporter` to dump +the ATLAS GeoModel into a SQLite file. + +Instructions are meant for a **SLC6 machine** (or `lxplus`) + +## Get the code + + git clone https://:@gitlab.cern.ch:8443/rbianchi/athena.git # https://gitlab.cern.ch/rbianchi/athena.git + cd athena + git checkout dump-geomodel + cd .. + +## Setup build + + mkdir build + cd build + cp ../athena/Projects/WorkDir/package_filters_example.txt ../package_filters.txt + + ### replace the example path with the GeoModelStandalone path, plus VP1Utils and VP1Base + sed -i '/Control/c\+ DetectorDescription/GeoModel/GeoModelStandalone/.*\n+ graphics/VP1/VP1Utils\n+ graphics/VP1/VP1Base' ../package_filters.txt + +## Build + + setupATLAS + asetup Athena,master,latest,slc6 + cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DATLAS_PACKAGE_FILTER_FILE=../package_filters.txt ../athena/Projects/WorkDir + make + source x86_64-slc6-gcc62-opt/setup.sh + +## Set debug output + +This is **OPTIONAL** + + export VP1_VERBOSE_OUTPUT=1 + export VP1_DEBUG_OUTPUT=1 + +## Run + +At the prompt, run the command `dump-geo`, followed by the `-detdescr` flag and a valid ATLAS Geometry tag; for example: + + dump-geo -detdescr=ATLAS-R2-2016-01-00-01 + +a file named `geometry-ATLAS-R2-2016-01-00-01.db` will be created in the run folder. + +## Sample data + +If you want, you can downlaod a sample datafile (draft): + + wget https://atlas-vp1.web.cern.ch/atlas-vp1/doc_new/sample_datafiles/geometry-ATLAS-R2-2016-01-00-01.db diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo new file mode 100755 index 0000000000000000000000000000000000000000..5d0f827c48c965f622a24f5830f3db649d727419 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo @@ -0,0 +1,998 @@ +#/* +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +#*/ + +#!/bin/bash + +# Script for constructing command which launches athena on dump-geo.py, with appropriate options (in the -c flag). +# +# Author: Riccardo.Maria.Bianchi@cern.ch +# First useful version: July 2007 by Thomas.Kittelmann@cern.ch +# Modified: Manuel.Proissl@cern.ch, March 2012 +# Riccardo.Maria.Bianchi@cern.ch, November 2012 +# Edward.Moyse@cern.ch, multiple times +# Riccardo.Maria.Bianchi@cern.ch, November 2017 +# +# +# Questions: Riccardo.Maria.Bianchi@cern.ch +# +# + + +echo +echo "******************************************" +echo +echo " Launching ATLASGeoModelDumper" +echo +echo "******************************************" +echo +echo + +################################################## +#echo "*** VP1 NOTE *** setting QT_PLUGIN_PATH to '${QTDIR}/plugins', to let Qt load the SQLite driver" +#export QT_PLUGIN_PATH=$QTDIR/plugins +#echo; +################################################## + + +#fixme/todo: option to start cruise mode (event/second) +#fixme/todo: MULTINP_CPY should not be allowed to exist beforehand! + +APP=`basename $0` + +which athena.py > /dev/null 2>&1 +if [ $? != 0 ]; then + echo "Error: athena.py not found in path. Please setup atlas release before running" + exit 1 +fi + +####################################### +## Init config variables ## +####################################### + +LIVEDEFAULTDETDESCR="ATLAS-GEO-10-00-00" +LIVEDEFAULTGLOBCOND="COMCOND-BLKPST-004-01" +LIVEDEFAULTEVENTSRC="https://atlas-live.cern.ch/event_files/L1MinBias/vp1fileinfo.txt" +LIVELOCALDEFAULTEVENTSRC="/VP1_events/" +LIVEBOOTSTRAPSRC="http://atlas-vp1.web.cern.ch/atlas-vp1/live-bootstrap/vp1fileinfo.txt" + +declare -a FILES_POOLROOT +declare -a FILES_VP1CFG +declare -a FILES_EXTRAJOBOPT +declare -a LOCALEVENTSRC_AVAILDIRS +FLAG_FORCE=0 +FLAG_HELP=0 +FLAG_DATA=0 +FLAG_TEST=0 +ERRORS="" +DETDESCRTAG="" +TREETOPFILTER="" +GLOBCONDTAG="" +SKIPEVENTS="" +CRUISEWITHTIME="" +LOGFILE="" +FILTEREVENTS="" +FLAG_LARHV=0 +# FLAG_FULLTOROIDS=0 +FLAG_DONTCLEANUPEVTCPY=0 +FLAG_LIVE=0 +FLAG_LIVELOCAL=0 +FLAG_NOAUTOCONF=0 +FLAG_TRIG=0 +FLAG_NOCALO=0 +FLAG_NOID=0 +FLAG_NOSORTDBREPLICAS=0 +FLAG_NOMUON=0 +FLAG_LUCID=0 +FLAG_ONLINE=0 +FLAG_ALFA=0 +FLAG_FORWARD_REGION=0 +FLAG_ZDC=0 +FLAG_CAVERN=0 +FLAG_TOYDETECTOR=0 +FLAG_GEOMODELSTATS=0 +FLAG_EXTRAPOLATOR=0 +FLAG_SPACEPOINTS=0 +FLAG_NOEXTRAPOLATOR=0 +FLAG_FITTER=0 +FLAG_MC=0 +FLAG_FATRAS=0 +FLAG_NOGUI=0 +FLAG_CGAL=0 +FLAG_NSW=0 +FLAG_SLHC=0 +FLAG_CUSTOMGEOMETRY=0 +MULTINP_SRC="" +MULTINP_CPY="" +TRIGDEC="" +FATRAS_TRUTHKEY="" +ATHENAOPTS="" + +####################################### +## Decode command line options ## +####################################### + +i=1 +while [ $i -le $# ]; do + arg=${!i} + if [ "x${arg}" == "x-h" -o "x${arg}" == "x-help" -o "x${arg}" == "x--help" ]; then + FLAG_HELP=1 + elif [ "x${arg}" == "x-larhv" ]; then + FLAG_LARHV=1 + # elif [ "x${arg}" == "x-fulltoroids" ]; then + # FLAG_FULLTOROIDS=1 + elif [ "x${arg}" == "x-live" ]; then + FLAG_LIVE=1 + elif [ "x${arg}" == "x-livelocal" ]; then + FLAG_LIVELOCAL=1 + elif [ "x${arg}" == "x-noautoconf" ]; then + FLAG_NOAUTOCONF=1 + elif [ "x${arg}" == "x-nocleanupeventcpy" ]; then + FLAG_DONTCLEANUPEVTCPY=1 + elif [ "x${arg}" == "x-data" ]; then + FLAG_DATA=1 + elif [ "x${arg}" == "x-test" ]; then + FLAG_TEST=1 + elif [ "x${arg}" == "x-trig" ]; then + FLAG_TRIG=1 + elif [ "x${arg}" == "x-nocalo" ]; then + FLAG_NOCALO=1 + elif [ "x${arg}" == "x-noid" ]; then + FLAG_NOID=1 + elif [ "x${arg}" == "x-nomuon" ]; then + FLAG_NOMUON=1 + elif [ "x${arg}" == "x-nosortdbreplicas" ]; then + FLAG_NOSORTDBREPLICAS=1 + elif [ "x${arg}" == "x-lucid" ]; then + FLAG_LUCID=1 + elif [ "x${arg}" == "x-online" ]; then + FLAG_ONLINE=1 + elif [ "x${arg}" == "x-alfa" ]; then + FLAG_ALFA=1 + elif [ "x${arg}" == "x-forwardregion" ]; then + FLAG_FORWARD_REGION=1 + elif [ "x${arg}" == "x-zdc" ]; then + FLAG_ZDC=1 + elif [ "x${arg}" == "x-cavern" ]; then + FLAG_CAVERN=1 + elif [ "x${arg}" == "x-toy-detector" ]; then + FLAG_TOYDETECTOR=1 + elif [ "x${arg}" == "x-geomodel-stats" ]; then + FLAG_GEOMODELSTATS=1 + elif [ "x${arg}" == "x-spacepoints" ]; then + FLAG_SPACEPOINTS=1 + elif [ "x${arg}" == "x-extrapolator" ]; then + FLAG_EXTRAPOLATOR=1 + elif [ "x${arg}" == "x-noextrapolator" ]; then + FLAG_NOEXTRAPOLATOR=1 + elif [ "x${arg}" == "x-refit" ]; then + FLAG_FITTER=1 + elif [ "x${arg}" == "x-fatras" ]; then + FLAG_FATRAS=1 + elif [ "x${arg}" == "x-nogui" ]; then + FLAG_NOGUI=1 + elif [ "x${arg}" == "x-cgal" ]; then + FLAG_CGAL=1 + elif [ "x${arg}" == "x-nsw" ]; then + FLAG_NSW=1 + elif [ "x${arg}" == "x-slhc" ]; then + echo "SLHC Mode: ON" + FLAG_SLHC=1 + elif [ "x${arg}" == "x-customgeom" ]; then + FLAG_CUSTOMGEOMETRY=1 + elif [ "x${arg}" == "x-mc" ]; then + FLAG_MC=1 + elif [ "x${arg}" == "x-multinp" ]; then + echo "IGNORING OBSOlETE FLAG -multinp" + elif [ "x${arg:0:10}" == "x-detdescr=" ]; then + DETDESCRTAG=${arg:10:$((${#arg}-10))} + if [ "x$DETDESCRTAG" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -detdescr" + fi + elif [ "x${arg:0:9}" == "x-treetop=" ]; then + TREETOPFILTER=${arg:9:$((${#arg}-9))} + if [ "x$TREETOPFILTER" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -treetop" + fi + elif [ "x${arg}" == "x-f" ]; then + FLAG_FORCE=1 + elif [ "x${arg:0:10}" == "x-globcond=" ]; then + GLOBCONDTAG=${arg:10:$((${#arg}-10))} + if [ "x$GLOBCONDTAG" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -globcond" + fi + elif [ "x${arg:0:10}" == "x-eventsrc=" ]; then + MULTINP_SRC=${arg:10:$((${#arg}-10))} + if [ "x$MULTINP_SRC" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -eventsrc" + fi + elif [ "x${arg:0:10}" == "x-eventcpy=" ]; then + MULTINP_CPY=${arg:10:$((${#arg}-10))} + if [ "x$MULTINP_CPY" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -eventcpy" + fi + elif [ "x${arg:0:9}" == "x-logfile=" ]; then + LOGFILE=${arg:9:$((${#arg}-9))} + if [ "x$LOGFILE" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -logfile" + fi + elif [ "x${arg:0:9}" == "x-trigdec=" ]; then + TRIGDEC=${arg:9:$((${#arg}-9))} + if [ "x$TRIGDEC" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -trigdec" + fi + elif [ "x${arg:0:11}" == "x-fatraskey=" ]; then + FATRAS_TRUTHKEY=${arg:11:$((${#arg}-11))} + if [ "x$FATRAS_TRUTHKEY" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -fatraskey" + fi + elif [ "x${arg:0:12}" == "x-skipevents=" ]; then + SKIPEVENTS=${arg:12:$((${#arg}-12))} + if [ "x$SKIPEVENTS" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -skipevents" + else + #check it is integer: + echo "$SKIPEVENTS" | grep '^[0-9][0-9]*$' > /dev/null 2>&1 || \ + ERRORS="$ERRORS\nArgument to -skipevents must be an integer!" + fi + elif [ "x${arg:0:11}" == "x-evtfilter=" ]; then + FILTEREVENTS=${arg:11:$((${#arg}-11))} + if [ "x$FILTEREVENTS" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -evtfilter" + fi + elif [ "x${arg:0:8}" == "x-cruise=" ]; then + CRUISEWITHTIME=${arg:8:$((${#arg}-8))} + if [ "x$CRUISEWITHTIME" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -cruise" + else + #check it is integer: + echo "$CRUISEWITHTIME" | grep '^[0-9][0-9]*$' > /dev/null 2>&1 || \ + ERRORS="$ERRORS\nArgument to -cruise must be an integer!" + if [ "x$CRUISEWITHTIME" == "x0" ]; then + ERRORS="$ERRORS\nArgument to -cruise must be positive!" + fi + fi + elif [ "x${arg:0:12}" == "x-athenaopts=" ]; then + ATHENAOPTS=${arg:12:$((${#arg}-12))} + if [ "x$ATHENAOPTS" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -athenaopts" + fi + elif [ "x${arg:0:16}" == "x-extraevtsrcdir=" ]; then + EXTRADIR=${arg:16:$((${#arg}-16))} + if [ "x$EXTRADIR" == "x" ]; then + ERRORS="$ERRORS\nNeed argument to -extraevtsrcdir" + else + if [ ! -d $EXTRADIR ]; then + ERRORS="$ERRORS\nExtra event source directory $EXTRADIR does not exist" + else + LOCALEVENTSRC_AVAILDIRS[${#LOCALEVENTSRC_AVAILDIRS[@]}]="$EXTRADIR" + fi + fi + elif [ ${#arg} -gt 4 -a ${arg:$((${#arg}-4)):4} == ".vp1" ]; then + FILES_VP1CFG[${#FILES_VP1CFG[@]}]="${arg}" + elif [ ${#arg} -gt 3 -a ${arg:$((${#arg}-3)):3} == ".py" ]; then + FILES_EXTRAJOBOPT[${#FILES_EXTRAJOBOPT[@]}]="${arg}" + elif [[ ${#arg} -gt 3 && ${arg:0:1} != "-" && ( "${arg}" =~ "^LFN:" || -f "${arg}" ) ]]; then + FILES_POOLROOT[${#FILES_POOLROOT[@]}]="${arg}" + elif [[ ${#arg} -gt 3 && ${arg:0:1} != "-" && ( "${arg}" =~ "^root:" || -f "${arg}" ) ]]; then + echo "Opening a file through the 'root://' protocol..." + FILES_POOLROOT[${#FILES_POOLROOT[@]}]="${arg}" + else + ERRORS="$ERRORS\nUnknown argument: ${arg}" + fi + i=$((i+1)) +done + +#live & noautoconf flags (AutoConfiguration is disabled in live and livelocal modes) + +if [ "x$FLAG_LIVE" == "x1" ]; then + if [ "x$FLAG_MC" == "x1" ]; then + echo "Notice: -mc flag is ignored when -live is present" + fi + FLAG_MC=0 + if [ "x$FLAG_NOAUTOCONF" == "x1" ]; then + echo "Notice: -noautoconf flag is redundant when -live is present" + fi + FLAG_NOAUTOCONF=1 + if [ "x$MULTINP_SRC" == "x" ]; then + MULTINP_SRC="$LIVEDEFAULTEVENTSRC" + fi + if [ "x$DETDESCRTAG" == "x" ]; then + DETDESCRTAG="$LIVEDEFAULTDETDESCR" + fi + if [ "x$GLOBCONDTAG" == "x" ]; then + GLOBCONDTAG="$LIVEDEFAULTGLOBCOND" + fi +elif [ "x$FLAG_LIVELOCAL" == "x1" ]; then + if [ "x$FLAG_MC" == "x1" ]; then + echo "Notice: -mc flag is ignored when -livelocal is present" + fi + FLAG_MC=0 + if [ "x$FLAG_NOAUTOCONF" == "x1" ]; then + echo "Notice: -noautoconf flag is redundant when -livelocal is present" + fi + FLAG_NOAUTOCONF=1 + if [ "x$MULTINP_SRC" == "x" ]; then + MULTINP_SRC="$LIVELOCALDEFAULTEVENTSRC" + fi + if [ "x$DETDESCRTAG" == "x" ]; then + DETDESCRTAG="$LIVEDEFAULTDETDESCR" + fi + if [ "x$GLOBCONDTAG" == "x" ]; then + GLOBCONDTAG="$LIVEDEFAULTGLOBCOND" + fi +elif [ "x$FLAG_NOAUTOCONF" == "x0" -a ${#FILES_POOLROOT[@]} != 0 ]; then + if [ "x$FLAG_MC" == "x1" ]; then + echo "Notice: -mc flag is ignored when autoconfiguration is ON" + fi + FLAG_MC=0 +fi + +if [ "x$FLAG_LIVE" == "x1" -a "x$FLAG_LIVELOCAL" == "x1" ]; then + ERRORS="$ERRORS\nDon't specify both -live and -livelocal" +fi + +#default: +if [ "x$MULTINP_SRC" != "x" -a "x$MULTINP_CPY" == "x" ]; then + MULTINP_CPY="/tmp/$USER/vp1events/$RANDOM" +fi + +# Sanity checks: +if [ "x$MULTINP_SRC" == "x" -a "x$FLAG_DONTCLEANUPEVTCPY" == "x1" ]; then + ERRORS="$ERRORS\nOption -nocleanupeventcpy can't be set without -eventsrc=..." +fi +if [ "x$MULTINP_CPY" != "x" -a "x$MULTINP_SRC" == "x" ]; then + ERRORS="$ERRORS\nOption -eventcpy=... can't be set without -eventsrc=..." +fi + +if [ "x$FLAG_NOID" == "x1" -a "x$FLAG_FATRAS" == "x1" ]; then + ERRORS="$ERRORS\nOptions -fatras and -noid can not be applied simultaneously" +fi + +if [ "x$FLAG_LIVE" == "x1" -a "x$FLAG_FATRAS" == "x1" ]; then + ERRORS="$ERRORS\nOptions -fatras and -live can not be applied simultaneously" +fi + +if [ "x$FLAG_LIVELOCAL" == "x1" -a "x$FLAG_FATRAS" == "x1" ]; then + ERRORS="$ERRORS\nOptions -fatras and -livelocal can not be applied simultaneously" +fi + +if [ "x$FLAG_NOID" == "x1" -a "x$FLAG_NOMUON" == "x1" -a "x$FLAG_EXTRAPOLATOR" == "x1" ]; then + ERRORS="$ERRORS\nOptions -extrapolator can not be used when both -noid and -nomuon are specified" +fi +if [ "x$FLAG_NOID" == "x1" -a "x$FLAG_SPACEPOINTS" == "x1" ]; then + ERRORS="$ERRORS\nOptions -spacepoints can not be used when -noid is specified" +fi + +if [ "x$FLAG_EXTRAPOLATOR" == "x1" -a "x$FLAG_NOEXTRAPOLATOR" == "x1" ]; then + ERRORS="$ERRORS\nOptions -extrapolator and -noextrapolator are incompatible" +fi + +if [ "x$FLAG_NOID" == "x1" -a "x$FLAG_NOMUON" == "x1" -a "x$FLAG_FITTER" == "x1" ]; then + ERRORS="$ERRORS\nOptions -refit can not be used when both -noid and -nomuon are specified" +fi + +if [ "x$MULTINP_CPY" != "x" -a -f "$MULTINP_CPY" ]; then + ERRORS="$ERRORS\n-eventcpy directory set to point to a file" +fi + + +BOOTSTRAPNAME="bootstrapevent.pool.root" +BOOTSTRAPFILE="${MULTINP_CPY}/${BOOTSTRAPNAME}" +BOOTSTRAP_HTTPFILEINFO="${MULTINP_CPY}/bootstrap_fileinfo.txt" +HTTPMODE=0 +if [ "x$MULTINP_SRC" != "x" ]; then + if [ ${#FILES_POOLROOT[@]} != 0 ]; then + #cant have input files. + ERRORS="$ERRORS\nPlease don't specify input files when running with -live, -livelocal or -eventsrc=..." + else + FILES_POOLROOT[${#FILES_POOLROOT[@]}]="${BOOTSTRAPFILE}" + fi + HTTPMODE=1 + echo $MULTINP_SRC|grep '^https://..*/..*' > /dev/null || HTTPMODE=0 + echo $MULTINP_SRC|grep '/$' > /dev/null && HTTPMODE=0 + if [ "x$HTTPMODE" == "x0" ]; then + if [ "x$MULTINP_SRC" != "x" -a ! -d "$MULTINP_SRC" ]; then + ERRORS="$ERRORS\n-eventsrc directory does not exists" + fi + elif [ "x$MULTINP_CPY" == "x$MULTINP_SRC" ]; then + #Fixme: Could probably cheat this check by presense of trailing '/', symlinks, etc. + ERRORS="$ERRORS\n-eventsrc and -eventcpy directories must be different" + fi +fi + +if [ ${#LOCALEVENTSRC_AVAILDIRS[@]} != 0 ]; then + if [ "x$MULTINP_SRC" == "x" ]; then + ERRORS="$ERRORS\n-extraevtsrcdir can not be specified without the -eventsrc flag" + fi + if [ "x$HTTPMODE" != "x0" ]; then + ERRORS="$ERRORS\n-extraevtsrcdir can not be used when -eventsrc is not a local directory" + fi +fi + +if [ "x$FLAG_EXTRAPOLATOR" == "x0" -a "x$FLAG_EXTRAPOLATOR" == "x0" ]; then + if [ "x$FLAG_NOID" == "x1" -a "x$FLAG_NOMUON" == "x1" ]; then + FLAG_NOEXTRAPOLATOR=1 + else + FLAG_EXTRAPOLATOR=1 + fi +fi + + +####################################### +## Possibly print out errors/usage ## +####################################### + +if [ "x$ERRORS" != "x" ]; then + echo "=================================================================" + echo "Errors found in commandline options!!!:" + echo -e "$ERRORS" + echo + echo "Run 'vp1 -h' for more information" + echo "=================================================================" + echo + exit 1 +fi + +if [ "x$FLAG_HELP" != "x0" ]; then + echo "The $APP script serves as a frontend which runs athena with vp1.py and appropriate options." + echo + echo "Usage: " + echo + echo "$APP [inputfiles] [configfiles] [jobopt fragments] [options]" + echo + echo "Config files must have the .vp1 extension, joboption fragments the .py extension," + echo "and any other argument which doesn't start with '-' is assumed to be an input file if such a file exists." + echo + echo " -h, -help, --help : Display this help (with examples) and exit." + echo + echo " -larhv : Access current LAr HV data in the DCS_OFL database via VP1 CaloReadout system." + echo " -data : Input files are data [default assumption is simulation]. " + echo + echo " -detdescr=TAG : Set global geometry tag. Overrides autoconfiguration" + echo + echo " -treetop=FILTER : Only output the GeoModel Treetop specified in the FILTER list. " + echo " Format is a comma separated list of event numbers" + echo + echo " -f : 'force' mode, which overwrites the geometry dump file in the local folder, if present." + echo + echo " -globcond=TAG : Set global conditions tag. Overrides autoconfiguration" + echo + echo " -skipevents=N : Skip the first N events" + echo + echo " -evtfilter=FILTER : Only process the events in the FILTER list." + echo " Format is a comma separated list of event numbers, where each event number" + echo " can optionally be preceeded by a run number and a semicolon." + echo " Prepend the list with an \"%\" to instead exclude the events." + echo " For instance select a few nice events like: --evtfilter=7,13,5300:26,54" + echo " Or exclude a few bad events like: --evtfilter=%7,13,5300:26,54" + echo + echo " It is also possible to specify one or more files with run/evt numbers" + echo " specified on each line: --evtfilter=%7,13,5300:26,54,myevents1.txt" + echo + echo " -cruise=N : Start in cruise mode, changing events after N seconds" + echo + echo " -logfile=mylogfile.txt : Leave a copy of the output in mylogfile.txt (both stdout and stderr)" + echo + echo " -trig : Init trigger information to be displayed with the Trigger Plugin" + echo + echo " -nocalo : Don't init geometry and converters for calorimeter systems." + echo " -noid : Don't init geometry and converters for the inner detector." + echo " -nomuon : Don't init geometry and converters for muon systems." + # echo " -fulltoroids : Build complete and rather heavyweight description of muon dead materials." + # echo " A lightweight version is built by default" + echo " -lucid : Init geometry and converters for the LUCID forward detector." + echo " -alfa : Init geometry and converters for the ALFA forward detector." + echo " -forwardregion : Init geometry and converters for the FrwardRegion." + echo " -zdc : Init geometry and converters for the ZDC forward detector." + echo " -cavern : Init geometry for the cavern infrastructure." + echo + echo " -toy-detector : Let VP1 visualize the "ToyDetector" volumes of GeoModelExamples (as 'Other unrecognized volumes.' in the Geo system)" + echo + echo " -geomodel-stats : Write GeoModel stats to a file." + echo + echo " -extrapolator : Whether to configure an extrapolator for more precise track representation." + echo " -noextrapolator Default is -extrapolator unless both -nomuon and -noid are specified." + echo + echo " -refit : Allows VP1-controlled refit from PrepRawData." + echo + echo " -online : Use this flag for running VP1 at P1." + echo + echo " -mc : Tell VP1 that it is running over MC data. The flag is ignored when autoconfiguration is ON" + echo " (default mode when running over data files)" + echo + echo " -fatras : Use Fatras (in single-track-simulation mode if no input file with generated event)" + echo " -fatraskey=KEY : Optionally override truth key used by Fatras (typical values are GEN_EVENT or TruthEvent)" + echo + echo " -eventsrc=DIR : Directory to take single event files from (do not specify input files in this case)." + echo " To get files from a web server (i.e. live events), put instead the url to the file" + echo " residing in the same directory (most users should just use the -live option instead)." + echo + echo " -extraevtsrcdir=DIR : Directory to add to the menu to allow user to change eventsrc on the fly." + echo " This argument can appear several times and should only be used when eventsrc is" + echo " a local directory" + echo + echo " -eventcpy=DIR : Directory to keep local copies of processed event files." + echo " If -eventsrc is set, then -eventcpy will default to /tmp/$USER/vp1events/$RANDOM " + echo " -nocleanupeventcpy : Prevent removal of eventcpy directory after athena process finishes." + echo + echo " -live : Run on live events from point 1. This is a convenience option which implies" + echo " other options [unless explicitly set]:" + echo " -noautoconf" + echo " -eventsrc=$LIVEDEFAULTEVENTSRC" + echo " -detdescr=$LIVEDEFAULTDETDESCR" + echo " -globcond=$LIVEDEFAULTGLOBCOND" + echo + echo " -livelocal : Run on live events from point 1 in local directory. This is a convenience option" + echo " which implies other options [unless explicitly set]:" + echo " -noautoconf" + echo " -eventsrc=$LIVELOCALDEFAULTEVENTSRC" + echo " -detdescr=$LIVEDEFAULTDETDESCR" + echo " -globcond=$LIVEDEFAULTGLOBCOND" + echo + echo " -noautoconf : Disable AutoConfiguration. VP1 runs in the 'data' mode by default" + echo " use '-mc' flag for switching to the MC mode" + echo + echo " -nosortdbreplicas : Do not attempt to sort DB replicas according to geographical proximity." + echo + echo " -trigdec=file.xml : Use file.xml as source of trigger decision category data." + echo " -trigdec=embedded : Trigger decision category data is embedded in the input file(s)." + echo " -trigdec=someserver.cern.ch : Trigger decision category data is available from the server someserver.cern.ch." + echo + echo " -athenaopts=<options> : Pass <options> onto athena invocation (type 'athena.py -h' to see available options)." + echo " NB: You can not use the -c option." + echo + echo " -cgal : Use CGAL boolean instead of vp1 boolean." + echo + echo " -nsw : Enable the Muon New Small Wheel geometry (and disable the existing small wheel)." + echo + echo " -slhc : Enable special configurations for SLHC studies." + echo + echo " -customgeom : Enable a custom geometry." + echo + echo " -test : Show the athena command instead of executing it." + echo + echo "Note that the order of specified files/options is not important, and that they can in general be mixed quite" + echo "liberally (when it makes sense - of course dont put e.g. both -trigdec=file.xml and -trigdec=embedded)" + echo + echo + echo "Examples:" + echo + echo " * Simply run on the input files myevents1.pool.root and myevents2.pool.root" + echo + echo " \$>$APP myevents1.pool.root myevents2.pool.root" + echo + echo " * Simply run on the input file myevents.pool.root and have the joboption fragments myopts1.py and myopts2.py" + echo " included after the standard vp1 setup" + echo + echo " \$>$APP myevents.pool.root myopts1.py myopts2.py" + echo + echo " * Run on myevents1.pool.root, and use a file, mytrigger.xml, as source of trigger decision data:" + echo + echo " \$>$APP myevents1.pool.root -trigdec=mytrigger.xml" + echo + echo " * Run on myevents1.pool.root, don't init geometry and converters for the calorimeter systems:" + echo + echo " \$>$APP myevents1.pool.root -nocalo" + echo + echo " * Run on myevents1.pool.root, and use detector description tag \"ATLAS-GEO-10-00-00\":" + echo + echo " \$>$APP myevents1.pool.root -detdescr=ATLAS-GEO-10-00-00" + echo + echo " * Run on myevents1.pool.root, and pass on a couple of options to the athena invocation (in this case" + echo " we want to run with a debugger and also set the loglevel to WARNING):" + echo + echo " \$>$APP myevents1.pool.root -athenaopts='-d -l WARNING'" + echo + echo " * Run on myevents1.pool.root, and preload the tab/channel configuration files myconfig1.vp1 and myconfig2.vp1:" + echo + echo " \$>$APP myevents1.pool.root myconfig1.vp1 myconfig2.vp1" + echo + echo " * Run on myevents1.pool.root, and preload the tab/channel configuration files myconfig1.vp1 and myconfig2.vp1:" + echo + echo " \$>$APP myevents1.pool.root myconfig1.vp1 myconfig2.vp1" + echo + echo " * Some more advanced examples, using several options at once:" + echo + echo " \$>$APP -detdescr=ATLAS-GEO-10-00-00 myevents1.pool.root myevents2.pool.root myconfig1.vp1 -athenaopts='-d'" + echo " \$>$APP -detdescr=ATLAS-GEO-10-00-00 myevents1.pool.root myconfig1.vp1 -nocalo -nomuon -trigdec=embedded" + echo + exit 0 +fi + +######################################## +## Setup & run according to options ## +######################################## + +if [ "x$FLAG_DONTCLEANUPEVTCPY" != "x1" -a "x$MULTINP_CPY" != "x" ]; then + if [ ${#MULTINP_CPY} -lt 8 -o "x$MULTINP_CPY" == "$HOME" -o "x$MULTINP_CPY" == "$HOME/" ]; then + echo "NOTICE: Turning off removal of ${MULTINP_CPY} since it seems to be too short or pointing at $HOME." + FLAG_DONTCLEANUPEVTCPY=1 + fi +fi + +if [ "x$FLAG_DATA" != "x0" ]; then + echo "Error: Support for the -data flag is actually not implemented yet!" + exit 1 +fi + +PYTHONFILES="" +i=0 +while [ $i -le $((${#FILES_VP1CFG[@]}-1)) ]; do + if [ "x$PYTHONFILES" == "x" ]; then + PYTHONFILES='vp1CfgFiles=["'"${FILES_VP1CFG[$i]}"'"' + else + PYTHONFILES="${PYTHONFILES},${FILES_VP1CFG[$i]}"'"' + fi + i=$((i+1)) +done +if [ "x$PYTHONFILES" != "x" ]; then + PYTHONFILES="${PYTHONFILES}"']' +fi + + +POOLROOTFILES="" +i=0 +while [ $i -le $((${#FILES_POOLROOT[@]}-1)) ]; do + if [ "x$POOLROOTFILES" == "x" ]; then + POOLROOTFILES='vp1InputFiles=["'"${FILES_POOLROOT[$i]}"'"' + else + POOLROOTFILES="${POOLROOTFILES}"',"'"${FILES_POOLROOT[$i]}"'"' + fi + i=$((i+1)) +done +if [ "x$POOLROOTFILES" != "x" ]; then + POOLROOTFILES="${POOLROOTFILES}"']' +fi + +EXTRAINPUTDIRS="" +i=0 +while [ $i -le $((${#LOCALEVENTSRC_AVAILDIRS[@]}-1)) ]; do + if [ "x$EXTRAINPUTDIRS" == "x" ]; then + EXTRAINPUTDIRS='vp1MultiAvailableSrcDirs=["'"${LOCALEVENTSRC_AVAILDIRS[$i]}"'"' + else + EXTRAINPUTDIRS="${EXTRAINPUTDIRS}"',"'"${LOCALEVENTSRC_AVAILDIRS[$i]}"'"' + fi + i=$((i+1)) +done +if [ "x$EXTRAINPUTDIRS" != "x" ]; then + EXTRAINPUTDIRS="${EXTRAINPUTDIRS}"']' +fi + +EXTRAJOBOPT="" +i=0 +while [ $i -le $((${#FILES_EXTRAJOBOPT[@]}-1)) ]; do + if [ "x$EXTRAJOBOPT" == "x" ]; then + EXTRAJOBOPT="${FILES_EXTRAJOBOPT[$i]}" + else + EXTRAJOBOPT="${EXTRAJOBOPT} ${FILES_EXTRAJOBOPT[$i]}" + fi + i=$((i+1)) +done + +JOBOPT="DumpGeo/dump-geo.py" +if [ -f dump-geo.py ]; then + JOBOPT=dump-geo.py +fi + +OPTS="$PYTHONFILES" +if [ "x$POOLROOTFILES" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}$POOLROOTFILES" +fi +if [ "x$EXTRAINPUTDIRS" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}$EXTRAINPUTDIRS" +fi +if [ "x$DETDESCRTAG" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}DetDescrVersion=\"$DETDESCRTAG\"" + # save the DetDescr tag for later + export DUMPGEODETDESCRTAG=$DETDESCRTAG + echo "DetDescrTag: ${DUMPGEODETDESCRTAG}" +fi +if [ "x$TREETOPFILTER" != "x" ]; then + #if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi # not needed + #OPTS="${OPTS}GeoModelTreetopFilter=\"$TREETOPFILTER\"" # not needed + # save the GeoModelTreetopFilter tag for later + # it will be accessed by the package (Athena algorithm) GeoModelStandalone/DumpGeo + export DUMPGEOTREETOPFILTER=$TREETOPFILTER + echo "User's 'GeoModel Treetop' filter set: ${DUMPGEOTREETOPFILTER}" +fi +if [ "x$FLAG_FORCE" != "x0" ]; then + #if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + #OPTS="${OPTS}vp1NSW=True" + export DUMPGEOOVERWRITE=$FLAG_FORCE + echo "User's Overwrite local geometry dump file, if present: ${DUMPGEOOVERWRITE}" +fi +if [ "x$GLOBCONDTAG" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1GlobCond=\"$GLOBCONDTAG\"" +fi +if [ "x$SKIPEVENTS" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}skipEvents=$SKIPEVENTS" +fi +if [ "x$FILTEREVENTS" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1FilterEvents=\"$FILTEREVENTS\"" +fi +if [ "x$CRUISEWITHTIME" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1CruiseTime=$CRUISEWITHTIME" +fi +if [ "x$FLAG_TRIG" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Trig=True" +fi +if [ "x$FLAG_NOCALO" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Calo=False" + export DUMPGEO_NOCALO="1"; +fi +if [ "x$FLAG_NOID" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1ID=False" + export DUMPGEO_NOID="1"; +fi +if [ "x$FLAG_NOMUON" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Muon=False" + export DUMPGEO_NOMUON="1"; +fi +if [ "x$FLAG_NOSORTDBREPLICAS" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1NoSortDBReplicas=True" +fi +if [ "x$FLAG_LARHV" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1LarHvData=True" +fi +# if [ "x$FLAG_FULLTOROIDS" != "x0" ]; then +# if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi +# OPTS="${OPTS}vp1FullToroids=True" +# fi +if [ "x$FLAG_ONLINE" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Online=True" +fi +if [ "x$FLAG_LUCID" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1LUCID=True" +fi +if [ "x$FLAG_ALFA" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1ALFA=True" +fi +if [ "x$FLAG_FORWARD_REGION" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1ForwardRegion=True" +fi +if [ "x$FLAG_ZDC" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1ZDC=True" +fi +if [ "x$FLAG_CAVERN" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Cavern=True" +fi +if [ "x$FLAG_TOYDETECTOR" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1ToyDetector=True" +fi +if [ "x$FLAG_GEOMODELSTATS" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1GeoModelStats=True" +fi +if [ "x$FLAG_SPACEPOINTS" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1SpacePoints=True" +fi +if [ "x$FLAG_EXTRAPOLATOR" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Extrapolator=True" +fi +if [ "x$FLAG_NOEXTRAPOLATOR" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Extrapolator=False" +fi +if [ "x$FLAG_NOAUTOCONF" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1NoAutoConf=True" +fi +if [ "x$FLAG_FITTER" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Fitter=True" +fi +if [ "x$FLAG_FATRAS" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Fatras=True" +fi +if [ "x$FLAG_NSW" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1NSW=True" +fi +if [ "x$FLAG_SLHC" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1SLHC=True" +fi +if [ "x$FLAG_CUSTOMGEOMETRY" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1CustomGeometry=True" +fi +if [ "x$FLAG_NOGUI" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1NoGui=True" +fi +if [ "x$FLAG_MC" != "x0" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Mc=True" +fi +if [ "x$MULTINP_SRC" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Multinp=True" +fi +if [ "x$MULTINP_SRC" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Multinpsrc=\"$MULTINP_SRC\"" +fi +if [ "x$MULTINP_CPY" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1Multinpcpy=\"$MULTINP_CPY\"" +fi +if [ "x$TRIGDEC" != "x" ]; then + if [ ${#TRIGDEC} -gt 5 -a ${TRIGDEC:$((${#TRIGDEC}-4)):4} == ".xml" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1TrigDecXML=\"$TRIGDEC\"" + else + echo "Error: Support for the -trigdec flag for embedded or server is actually not implemented in this script yet! So far only .xml sources work" + exit 1 + fi +fi +if [ "x$FATRAS_TRUTHKEY" != "x" ]; then + if [ "x$OPTS" != "x" ]; then OPTS="$OPTS;"; fi + OPTS="${OPTS}vp1FatrasTruthKey=\"$FATRAS_TRUTHKEY\"" +fi + +if [ "x$LOGFILE" != "x" ]; then + #Fixme: Check that this actually redirects stderr correctly!! + CMD="$CMD 2>&1|tee $LOGFILE" +fi +#Test mode: +if [ "x$FLAG_TEST" != "x0" ]; then + if [ "x$HTTPMODE" == "x1" ]; then + echo "--> Start by downloading a fresh file from $MULTINP_SRC to $BOOTSTRAPFILE" + fi + if [ "x$MULTINP_CPY" != "x" -a ! -d "$MULTINP_CPY" ]; then + echo mkdir -p $MULTINP_CPY + fi + if [ "x$LOGFILE" != "x" ]; then + echo athena.py $ATHENAOPTS -c "'$OPTS'" $JOBOPT $EXTRAJOBOPT "2>&1|tee $LOGFILE" + else + echo athena.py $ATHENAOPTS -c "'$OPTS'" $JOBOPT $EXTRAJOBOPT + fi + exit 0 +fi + +################################################## +## Possibly get boot-strap file for http mode ## +################################################## + +if [ "x$MULTINP_CPY" != "x" -a ! -d "$MULTINP_CPY" ]; then + mkdir -p $MULTINP_CPY + if [ $? != 0 ]; then + echo + echo "Failed to create $MULTINP_CPY" + echo + exit 1 + fi +fi + + +if [ "x$HTTPMODE" == "x1" ]; then + if [ -f $BOOTSTRAPFILE ]; then + echo + echo + echo "Using existing $BOOTSTRAPFILE as first event." + echo + echo "In case of problems, try first to remove this file and then restart" + echo + echo + else + echo "Need to acquire $BOOTSTRAPFILE" + while [ 1 ]; do + rm -f $BOOTSTRAP_HTTPFILEINFO + echo + echo "Executing wget $LIVEBOOTSTRAPSRC --output-document=$BOOTSTRAP_HTTPFILEINFO" + wget $LIVEBOOTSTRAPSRC --output-document=$BOOTSTRAP_HTTPFILEINFO + if [ $? != 0 ]; then + echo + echo "Download failed!" + echo + rm -f $BOOTSTRAP_HTTPFILEINFO + exit 1 + fi + echo "Download succesful" + #Check integrity of downloaded file: + OK=1 + grep '^vp1_.*_.*_.*.pool.root' $BOOTSTRAP_HTTPFILEINFO |grep -v "copy " > /dev/null || OK=0 + grep 'begin_checksums' $BOOTSTRAP_HTTPFILEINFO > /dev/null || OK=0 + grep 'end_checksums' $BOOTSTRAP_HTTPFILEINFO > /dev/null || OK=0 + if [ "x$OK" == "x1" ]; then + echo "Downloaded info file content seems sane." + break + else + echo "Problems with content of downloaded info file. Will retry in 5 seconds." + sleep 5 + fi + done + #Decode to find recent file: + FILELINE=`grep '^vp1_.*_.*_.*.pool.root' $BOOTSTRAP_HTTPFILEINFO |grep -v "copy "|head -1|tr '\t' ' '` + FILE=`echo $FILELINE|awk '{print $1}'` + SUM=`echo $FILELINE|awk '{print $2}'` + FILEURL=`echo $LIVEBOOTSTRAPSRC|sed 's#http://\(.*\)/.*$#http://\1/#'`$FILE + echo FILE=$FILE + echo FILEURL=$FILEURL + echo SUM=$SUM + OK=1 + BOOTSTRAPFILE_SUMFILE=$BOOTSTRAPFILE.md5sum + rm -f $BOOTSTRAPFILE $BOOTSTRAPFILE_SUMFILE + echo "Executing wget ${FILEURL} --output-document=$BOOTSTRAP_HTTPFILEINFO" + wget ${FILEURL} --output-document=$BOOTSTRAPFILE || OK=0 + if [ $? != 0 ]; then + echo + echo "Download failed!" + echo + rm -f $BOOTSTRAPFILE $BOOTSTRAPFILE_SUMFILE + exit 1 + fi + echo "$SUM $BOOTSTRAPFILE" > $BOOTSTRAPFILE_SUMFILE + if [ $? != 0 ]; then + echo + echo "Could not create md5sum check file" + echo + rm -f $BOOTSTRAPFILE $BOOTSTRAPFILE_SUMFILE + exit 1 + fi + md5sum --status --check $BOOTSTRAPFILE_SUMFILE + if [ $? != 0 ]; then + echo + echo "md5sum check of downloaded bootstrap event file failed!" + echo + rm -f $BOOTSTRAPFILE $BOOTSTRAPFILE_SUMFILE + exit 1 + fi + echo "Checksum of downloaded Bootstrap event file is OK. Proceeding to launch athena." + fi +elif [ "x$MULTINP_SRC" != "x" ]; then + NEWEST=`ls -1rt $MULTINP_SRC/*_*_*.pool.root |tail -1` + if [ ! -f $NEWEST ]; then + echo + echo "Could not find event file in $MULTINP_SRC to use to bootstrap athena. " + echo + exit 1 + fi + cp $NEWEST -f $BOOTSTRAPFILE + if [ $? != 0 -o ! -f $BOOTSTRAPFILE ]; then + echo + echo "Could not copy newest event file $BOOTSTRAPFILE!" + echo + rm -f $BOOTSTRAPFILE + exit 1 + fi +fi + + +echo "JOBOPT: " ${JOBOPT} +echo "EXTRAJOBOPT: " ${EXTRAJOBOPT} +if [ "x$LOGFILE" != "x" ]; then + athena.py $ATHENAOPTS -c "$OPTS" $JOBOPT $EXTRAJOBOPT 2>&1|tee $LOGFILE +else + athena.py $ATHENAOPTS -c "$OPTS" $JOBOPT $EXTRAJOBOPT +fi + +if [ "x$FLAG_DONTCLEANUPEVTCPY" != "x1" -a "x$MULTINP_CPY" != "x" ]; then + if [ -d "${MULTINP_CPY}" -a -f "${MULTINP_CPY}/${BOOTSTRAPNAME}" ]; then + rm -rf "${MULTINP_CPY}" + fi +fi diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo.py b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo.py new file mode 100644 index 0000000000000000000000000000000000000000..f275196f8bd384cddc401d760f36c4bfcf676151 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/dump-geo.py @@ -0,0 +1,546 @@ +#/* +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +#*/ + +if not 'vp1InputFiles' in dir(): vp1InputFiles = [] +if not 'vp1CfgFiles' in dir(): vp1CfgFiles = [] +if not 'vp1ID' in dir(): vp1ID=True +if not 'vp1Calo' in dir(): vp1Calo=True +if not 'vp1Muon' in dir(): vp1Muon=True +if not 'vp1LUCID' in dir(): vp1LUCID=False +if not 'vp1ALFA' in dir(): vp1ALFA=False +if not 'vp1ForwardRegion' in dir(): vp1ForwardRegion=False +if not 'vp1ZDC' in dir(): vp1ZDC=False +if not 'vp1Extrapolator' in dir(): vp1Extrapolator=True +if not 'vp1Fitter' in dir(): vp1Fitter=False +if not 'vp1Fatras' in dir(): vp1Fatras=False +if not 'vp1FatrasMuon' in dir(): vp1FatrasMuon=(vp1Fatras and vp1Muon) +if not 'vp1FatrasCalo' in dir(): vp1FatrasCalo=(vp1Fatras and vp1Calo) +if not 'vp1FatrasTruthKey' in dir(): vp1FatrasTruthKey="" +if not 'vp1Online' in dir(): vp1Online=False +if not 'vp1Mc' in dir(): vp1Mc=False +if not 'vp1Multinp' in dir(): vp1Multinp=False +if not 'vp1Multinpsrc' in dir(): vp1Multinpsrc="" +if not 'vp1Multinpcpy' in dir(): vp1Multinpcpy="" +if not 'vp1MultiAvailableSrcDirs' in dir(): vp1MultiAvailableSrcDirs = [] +if not 'vp1TrigDecXML' in dir(): vp1TrigDecXML="" +if not 'vp1LarHvData' in dir(): vp1LarHvData=False +# if not 'vp1FullToroids' in dir(): vp1FullToroids=False +if not 'vp1CruiseTime' in dir(): vp1CruiseTime=0 +if not 'vp1NoSortDBReplicas' in dir(): vp1NoSortDBReplicas=False +if not 'vp1FilterEvents' in dir(): vp1FilterEvents="" +if not 'vp1NoGui' in dir(): vp1NoGui=False +if not 'vp1SpacePoints' in dir(): vp1SpacePoints=False +if not 'vp1Cavern' in dir(): vp1Cavern=False +if not 'vp1ToyDetector' in dir(): vp1ToyDetector=False +if not 'vp1GeoModelStats' in dir(): vp1GeoModelStats=False +if not 'vp1NoAutoConf' in dir(): vp1NoAutoConf=False +if not 'vp1Trig' in dir(): vp1Trig=False +if not 'vp1NSW' in dir(): vp1NSW=False +if not 'vp1CustomGeometry' in dir(): vp1CustomGeometry=False +if not 'vp1SLHC' in dir(): vp1SLHC=False + +def vp1CfgErr(s): print "VP1 CONFIGURATION ERROR: %s" % s + +if (vp1Fatras and not vp1ID): + vp1CfgErr("Fatras can not be enabled without inner detector. Turning off Fatras.") + vp1Fatras=False +if (vp1FatrasMuon and not vp1Fatras): + vp1CfgErr("FatrasMuon can not be enabled without Fatras enabled. Turning off FatrasMuon.") + vp1FatrasMuon=False +if (vp1FatrasMuon and not vp1Muon): + vp1CfgErr("FatrasMuon can not be enabled without muon systems. Turning off FatrasMuon.") + vp1FatrasMuon=False +if (vp1FatrasCalo and not vp1Fatras): + vp1CfgErr("FatrasCalo can not be enabled without Fatras enabled. Turning off FatrasCalo.") + vp1FatrasCalo=False +if (vp1FatrasCalo and not vp1Calo): + vp1CfgErr("FatrasCalo can not be enabled without calo systems. Turning off FatrasCalo.") + vp1FatrasCalo=False +if ( vp1FatrasTruthKey != "" and not vp1Fatras ): + vp1CfgErr("FatrasTruthKey set but Fatras not enabled. Unsetting FatrasTruthKey.") + vp1FatrasTruthKey="" + +if (vp1NSW and not vp1Muon): + vp1CfgErr("Muon New Small Wheel (NSW) turned on, but no Muon geometry. Disabling NSW.") + vp1NSW=False + +#print "*** VP1 NOTE *** setting COIN_GLXGLUE env vars to make screenshots working remotely..." +#print "*** VP1 NOTE *** COIN_GLXGLUE_NO_GLX13_PBUFFERS=1 - " + "COIN_GLXGLUE_NO_PBUFFERS=1" +#os.putenv("COIN_GLXGLUE_NO_GLX13_PBUFFERS","1") +#os.putenv("COIN_GLXGLUE_NO_PBUFFERS","1") + + + +#Set VP1ATLREL integer so we can do e.g. "if VP1ATLREL>=160002:" +include('DumpGeo/vp1FragmentConstructVP1ATLREL.py') + +#Disable FPE checks :-( +from RecExConfig.RecFlags import rec +rec.doFloatingPointException.set_Value_and_Lock(False) + +if (vp1InputFiles == []): + # Create an event selector: + import AthenaCommon.AtlasUnixGeneratorJob + # Configure GlobalFlags + from AthenaCommon.GlobalFlags import globalflags + globalflags.DetGeo.set_Value_and_Lock('atlas') + globalflags.DataSource.set_Value_and_Lock('geant4') + + # # Set geometry version + if (not "DetDescrVersion" in dir()): + DetDescrVersion = "ATLAS-R2-2015-03-01-00" # for the new Rel. 21 + os.environ["DUMPGEODETDESCRTAGDEFAULT"] = "1" # save to an env var, for later use in GeoModelStandalone/GeoExporter + os.environ["DUMPGEODETDESCRTAG"] = DetDescrVersion # save to an env var, for later use in GeoModelStandalone/GeoExporter + globalflags.DetDescrVersion = DetDescrVersion + + # Set conditions tag + if not 'vp1GlobCond' in dir(): + vp1GlobCond="OFLCOND-SDR-BS7T-05-14" + from IOVDbSvc.CondDB import conddb + conddb.setGlobalTag(vp1GlobCond) +else: + if(vp1NoAutoConf): + # AutoConfiguration disabled + import AthenaCommon.AtlasUnixStandardJob + + if(vp1Online): + from AthenaCommon.AthenaCommonFlags import athenaCommonFlags + athenaCommonFlags.isOnline = True + + from AthenaCommon.GlobalFlags import globalflags + globalflags.DetGeo.set_Value_and_Lock('atlas') + if(vp1Mc): + globalflags.DataSource.set_Value_and_Lock('geant4') + else: + globalflags.DataSource.set_Value_and_Lock('data') + globalflags.InputFormat.set_Value_and_Lock('pool') + globalflags.Luminosity.set_Value_and_Lock('zero') + from AthenaCommon.BeamFlags import jobproperties + jobproperties.Beam.beamType="collisions" + + # Set geometry version + if (not "DetDescrVersion" in dir()): + DetDescrVersion = "ATLAS-R2-2015-03-01-00" # for the new Rel. 21 + + globalflags.DetDescrVersion = DetDescrVersion + + # Set conditions tag + if not 'vp1GlobCond' in dir(): + if (vp1Mc): + vp1GlobCond="OFLCOND-SIM-BS7T-02" + else: + vp1GlobCond="COMCOND-BLKPST-004-01" + + from IOVDbSvc.CondDB import conddb + conddb.setGlobalTag(vp1GlobCond) + else: + # AutoConfiguration enabled + from AthenaCommon.AthenaCommonFlags import athenaCommonFlags + athenaCommonFlags.FilesInput=vp1InputFiles + from RecExConfig.RecFlags import rec + rec.AutoConfiguration=['everything'] + rec.doAOD.set_Value_and_Lock(False) + rec.doESD.set_Value_and_Lock(False) + + # Override geometry tag from command line + if("DetDescrVersion" in dir()): + from AthenaCommon.GlobalFlags import globalflags + globalflags.DetDescrVersion.set_Value_and_Lock(DetDescrVersion) + + include('RecExCond/RecExCommon_flags.py') + theApp.EvtMax = -1 + + # Override global conditions tag from command line + if('vp1GlobCond' in dir()): + from IOVDbSvc.CondDB import conddb + conddb.setGlobalTag(vp1GlobCond) + +if vp1FilterEvents: + import DumpGeo.VP1EvtFilter + vp1FilterEvents = DumpGeo.VP1EvtFilter.parseFilterString(vp1FilterEvents) + DumpGeo.VP1EvtFilter.installEventFilter(vp1FilterEvents) + +from AthenaCommon.AlgSequence import AlgSequence +topSequence = AlgSequence() + +#Detector setup: +from AthenaCommon.DetFlags import DetFlags +if (vp1ID): DetFlags.ID_setOn() +else: DetFlags.ID_setOff() +if (vp1Calo): DetFlags.Calo_setOn() +else: DetFlags.Calo_setOff() +if (vp1Muon): DetFlags.Muon_setOn() +else: DetFlags.Muon_setOff() +if (vp1LUCID): DetFlags.Lucid_setOn() +else: DetFlags.Lucid_setOff() +if (vp1ALFA): DetFlags.ALFA_setOn() +else: DetFlags.ALFA_setOff() +if (vp1ForwardRegion): DetFlags.FwdRegion_setOn() +else: DetFlags.FwdRegion_setOff() +if (vp1ZDC): DetFlags.ZDC_setOn() +else: DetFlags.ZDC_setOff() +if (vp1NSW): DetFlags.Micromegas_setOn() #FIXME - sTGC? +DetFlags.Print() +if (vp1CustomGeometry): + print "Configuring Custom geometry." +if (vp1SLHC): + print "Setting up SLHC configuration" + rec.doTrigger.set_Value_and_Lock(False) + from AthenaCommon.GlobalFlags import globalflags + from AthenaCommon.GlobalFlags import jobproperties + from InDetRecExample.InDetJobProperties import InDetFlags + + #include("InDetSLHC_Example/preInclude.SLHC.py") + #include("InDetSLHC_Example/preInclude.NoTRT.py") + #include("InDetSLHC_Example/preInclude.SLHC_Rec.py") + # The above don't work for dev (20.9.0) so copied modified versions below: + from InDetSLHC_Example.SLHC_JobProperties import SLHC_Flags + SLHC_Flags.SLHC_Version = '' + DetFlags.ID_setOn() + DetFlags.TRT_setOff() + DetFlags.detdescr.TRT_setOff() + DetFlags.makeRIO.TRT_setOff() + DetFlags.Calo_setOn() + DetFlags.Muon_setOn() + DetFlags.Truth_setOn() + from TrkDetDescrSvc.TrkDetDescrJobProperties import TrkDetFlags + TrkDetFlags.SLHC_Geometry = True + TrkDetFlags.MagneticFieldCallbackEnforced = False + TrkDetFlags.TRT_BuildStrawLayers = False + TrkDetFlags.MaterialSource = 'None' + +# --- GeoModel +from AtlasGeoModel import SetGeometryVersion +from AtlasGeoModel import GeoModelInit + +from AthenaCommon.AppMgr import ServiceMgr as svcMgr + +if vp1GeoModelStats: + print "printing GeoModel stats to file (Svc.StatisticsToFile=TRUE)..." + svcMgr.GeoModelSvc.StatisticsToFile = True + +if vp1Cavern: + print "vp1.py - Initializing the visualization of the Cavern Infrastructure..." + from CavernInfraGeoModel.CavernInfraGeoModelConf import CavernInfraDetectorTool + svcMgr.GeoModelSvc.DetectorTools += [ CavernInfraDetectorTool() ] + +if vp1ToyDetector: + print "vp1.py - Initializing the visualization of the GeoModelExamples 'ToyDetector'..." + from GeoModelExamples.GeoModelExamplesConf import ToyDetectorTool + svcMgr.GeoModelSvc.DetectorTools += [ ToyDetectorTool() ] + + + + +# --- AGDD2Geo +# Switch it on if +# - Muon is ON +# - Major geometry version is greater than 10 +if (vp1Muon): + if (vp1NSW): + #DetDescrVersion="ATLAS-GEO-21-00-01" + include('MuonGeoModelTest/NSWGeoSetup.py') + + from AtlasGeoModel import Agdd2Geo + + # if(vp1FullToroids or vp1NSW): + # from AtlasGeoModel import Agdd2Geo + # else: + # from AthenaCommon.GlobalFlags import globalflags + # DDV = globalflags.DetDescrVersion() + # if(DDV.__contains__('ATLAS-GEO')): + # seconddash = DDV.find('-',8); + # majorddversstr = DDV[seconddash+1:seconddash+3]; + # majorddversint = int(majorddversstr); + # if(majorddversint>10): + # # Additional material in the muon system + # from AGDD2Geo.AGDD2GeoConf import AGDD2GeoSvc + # AGDD2GeoSvc=AGDD2GeoSvc() + # AGDD2GeoSvc.PrintSections=False + # AGDD2GeoSvc.Sections += ["ATLAS Feet"] + # AGDD2GeoSvc.Sections += ["Atlas Barrel Toroidal Magnets"] + # AGDD2GeoSvc.Sections += ["Atlas ECT Toroidal Magnets"] + # AGDD2GeoSvc.DisableSections = False + # AGDD2GeoSvc.Locked = False + # theApp.CreateSvc += ["AGDD2GeoSvc"] + # svcMgr += AGDD2GeoSvc + +#MagneticField: +#include("BFieldAth/BFieldAth_jobOptions.py") # OLD +import MagFieldServices.SetupField # NEW + +if (vp1Fatras): + from FatrasExample.FatrasJobProperties import FatrasFlags + FatrasFlags.SingleTrackSimulation.set_Value(vp1InputFiles==[]) + from FastSimulationConfig.FastSimulationFlags import jobproperties + jobproperties.FastSimulation.doFatrasID.set_Value(True) + jobproperties.FastSimulation.doFatrasMuon.set_Value(vp1FatrasMuon) + FatrasFlags.FastCaloSim.set_Value(vp1FatrasCalo) + +if (vp1InputFiles != []): + import AthenaPoolCnvSvc.ReadAthenaPool + + if (vp1ID): + from InDetRecExample.InDetJobProperties import InDetFlags + InDetFlags.loadTools = (vp1Extrapolator or vp1SpacePoints) + InDetFlags.preProcessing = vp1SpacePoints + InDetFlags.doPRDFormation = False + InDetFlags.doSpacePointFormation = vp1SpacePoints + InDetFlags.doNewTracking = False + InDetFlags.doiPatRec = False + InDetFlags.doxKalman = False + InDetFlags.doLowPt = False + InDetFlags.doLowBetaFinder = False + InDetFlags.doBackTracking = False + InDetFlags.doTRTStandalone = False + InDetFlags.doTrtSegments = False + InDetFlags.postProcessing = False + InDetFlags.doSlimming = False + InDetFlags.doVertexFinding = False + InDetFlags.doParticleCreation = False + InDetFlags.doConversions = False + InDetFlags.doSecVertexFinder = False + InDetFlags.doV0Finder = False + InDetFlags.doTrkNtuple = False + InDetFlags.doPixelTrkNtuple = False + InDetFlags.doSctTrkNtuple = False + InDetFlags.doTrtTrkNtuple = False + InDetFlags.doVtxNtuple = False + InDetFlags.doConvVtxNtuple = False + InDetFlags.doV0VtxNtuple = False + InDetFlags.doRefit = False + + InDetFlags.doStatistics = False + InDetFlags.useDCS = False + include( "InDetRecExample/InDetRec_jobOptions.py" ) + + if (vp1Fatras and vp1FatrasTruthKey!=""): + from FatrasExample.FatrasKeys import FatrasKeyFlags + FatrasKeyFlags.InputMcEventCollection.set_Value(vp1FatrasTruthKey) + + if (vp1Trig): + from TriggerJobOpts.TriggerConfigGetter import TriggerConfigGetter + TriggerConfigGetter( "ReadPool" ) + + if (vp1Calo): + from LArConditionsCommon import LArAlignable + + # + # Following is needed to display Tile Pulse shapes on ESD files + # + from TileConditions.TileInfoConfigurator import TileInfoConfigurator + tileInfoConfigurator = TileInfoConfigurator() + + if (vp1Muon): + include( "AmdcAth/AmdcAth_jobOptions.py" ) + + include( "PartPropSvc/PartPropSvc.py" ) + + if(vp1NoAutoConf): + svcMgr.EventSelector.InputCollections=vp1InputFiles + else: + svcMgr.EventSelector.InputCollections=athenaCommonFlags.FilesInput() + + if 'skipEvents' in dir(): + svcMgr.EventSelector.SkipEvents=skipEvents +else: + vp1Extrapolator = False + +#watch LAr HV: +if ( vp1LarHvData ): + from time import time + svcMgr.AthenaSealSvc.CheckDictionary = TRUE + svcMgr.EventSelector.InitialTimeStamp = int (time()) + svcMgr.EventSelector.TimeStampInterval = 1 + from IOVDbSvc.CondDB import conddb + conddb.addFolder("DCS_OFL","/LAR/DCS/HV/BARREl/I16") + conddb.addFolder("DCS_OFL","/LAR/DCS/HV/BARREL/I8") +#------------ + +if (vp1Fatras): + include( "FatrasExample/Fatras_jobOptions.py" ) + +if (vp1TrigDecXML!=""): + include( "TrigConfigSvc/jobOptions_commonSetup.py" ) + include( "TrigConfigSvc/jobOptions_setupLVL1Svc.py" ) + include( "TrigConfigSvc/jobOptions_setupHLTSvc.py" ) + HLTConfigSvc.XMLMenuFile = vp1TrigDecXML + from TrigDecisionTool.TrigDecisionToolConf import Trig__TrigDecisionTool + ToolSvc += Trig__TrigDecisionTool("TrigDecisionTool") + +if (vp1Calo): + from AthenaCommon.GlobalFlags import globalflags + if globalflags.DataSource() == 'data' : + include ("LArConditionsCommon/LArIdMap_comm_jobOptions.py") + else: + include ("LArConditionsCommon/LArConditionsCommon_MC_jobOptions.py") + include ("LArConditionsCommon/LArIdMap_MC_jobOptions.py") + +#Extrapolator: +if vp1Extrapolator and (vp1ID or vp1Muon): + # Force tool initializations needed by the extrapolator + from VP1TrkAuxAlgs.VP1TrkAuxAlgsConf import VP1TrkInitializer + VP1TrkInitializer = VP1TrkInitializer() + VP1TrkInitializer.ForceExtrapolatorTools = True + topSequence += VP1TrkInitializer + + if not vp1Fatras and vp1Mc: + include ('TrkDetDescrSvc/AtlasTrackingGeometrySvc.py') + + from TrkExTools.AtlasExtrapolator import AtlasExtrapolator + VP1ExtraPolatorName='VP1Extrapolator'; + VP1Extrapolator = AtlasExtrapolator(name=VP1ExtraPolatorName) + + # Previous config from SetupFitters.py + # from TrkExTools.TrkExToolsConf import Trk__Extrapolator as Extrapolator + # VP1Extrapolator = Extrapolator(name='VP1Extrapolator', + # Navigator = VP1Navigator, + # MaterialEffectsUpdators = [ VP1MaterialUpdator ], + # Propagators = [ VP1Propagator ] ) + + ToolSvc += VP1Extrapolator + print VP1Extrapolator + #We should append to variable instead: + os.putenv("VP1_JOBCFG_EXTRA_VP1_EXTRAPOLATORS","Trk::Extrapolator/"+VP1ExtraPolatorName) + + from TrkExEngine.AtlasExtrapolationEngine import AtlasExtrapolationEngine + ExtrapolationEngine = AtlasExtrapolationEngine(name='Extrapolation', nameprefix='Atlas') + ToolSvc += ExtrapolationEngine + print ExtrapolationEngine + +#Fitter: +if vp1Fitter and vp1Extrapolator and (vp1ID or vp1Muon): + VP1TrkInitializer.ForceFitterTools = True + os.putenv("VP1_DEVEL_ENABLEREFIT","1") + ########################################################## + # The Extrapolator + include('TrkDetDescrSvc/AtlasTrackingGeometrySvc.py') + + from TrkExRungeKuttaPropagator.TrkExRungeKuttaPropagatorConf import Trk__RungeKuttaPropagator as Propagator + VP1Propagator = Propagator(name = 'VP1Propagator') + ToolSvc += VP1Propagator + + # the Navigator has to get this one + from TrkExTools.TrkExToolsConf import Trk__Navigator + VP1Navigator = Trk__Navigator(name = 'VP1Navigator') + VP1Navigator.TrackingGeometrySvc = svcMgr.AtlasTrackingGeometrySvc + ToolSvc += VP1Navigator + + from TrkExTools.TrkExToolsConf import Trk__MaterialEffectsUpdator as MatUpdator + VP1MaterialUpdator = MatUpdator(name='VP1MaterialEffectsUpdator') + ToolSvc += VP1MaterialUpdator + + from TrkMeasurementUpdator_xk.TrkMeasurementUpdator_xkConf import Trk__KalmanUpdator_xk + VP1Updator = Trk__KalmanUpdator_xk(name = 'VP1Updator') + ToolSvc += VP1Updator + + from TrkDynamicNoiseAdjustor.TrkDynamicNoiseAdjustorConf import Trk__InDetDynamicNoiseAdjustment + VP1DNAdjustor = Trk__InDetDynamicNoiseAdjustment(name = 'VP1DNAdjustor') + #yminmax = 100.0) + ToolSvc += VP1DNAdjustor + from TrkKalmanFitter.TrkKalmanFitterConf import Trk__ForwardKalmanFitter as PublicFKF + VP1FKF = PublicFKF(name = 'VP1FKF', + StateChi2PerNDFPreCut = 25.0) + ToolSvc += VP1FKF + + from TrkKalmanFitter.TrkKalmanFitterConf import Trk__KalmanSmoother as PublicBKS + VP1BKS = PublicBKS(name = 'VP1BKS', + InitialCovarianceSeedFactor = 200.) + ToolSvc += VP1BKS + + from TrkKalmanFitter.TrkKalmanFitterConf import Trk__KalmanOutlierLogic as PublicKOL + VP1KOL = PublicKOL(name = 'VP1KOL', + StateChi2PerNDFCut = 12.5) + ToolSvc += VP1KOL + + #FIXME! Only do this for Muons? + from MuonRecExample import MuonRecTools + MdtTubeHitOnTrackCreator = MuonRecTools.getPublicTool("MdtTubeHitOnTrackCreator") + + from TrkRIO_OnTrackCreator.TrkRIO_OnTrackCreatorConf import Trk__RIO_OnTrackCreator + VP1RotCreator = Trk__RIO_OnTrackCreator(name = 'VP1RotCreator', + ToolMuonDriftCircle = MdtTubeHitOnTrackCreator , + Mode = 'all') + ToolSvc += VP1RotCreator + print VP1RotCreator + print MdtTubeHitOnTrackCreator + + from TrkKalmanFitter.TrkKalmanFitterConf import Trk__KalmanFitter as ConfiguredKalmanFitter + VP1KalmanFitter = ConfiguredKalmanFitter(name = 'VP1KalmanFitter', + ExtrapolatorHandle = VP1Extrapolator, + RIO_OnTrackCreatorHandle = VP1RotCreator, + MeasurementUpdatorHandle = VP1Updator, + ForwardKalmanFitterHandle = VP1FKF, + KalmanSmootherHandle = VP1BKS, + KalmanOutlierLogicHandle = VP1KOL, + DynamicNoiseAdjustorHandle = None, + AlignableSurfaceProviderHandle = None) + + ToolSvc += VP1KalmanFitter + + print VP1KalmanFitter + os.putenv("VP1_JOBCFG_EXTRA_VP1_FITTERS",VP1KalmanFitter.name()) + + + VP1KalmanFitterDNA = ConfiguredKalmanFitter(name = 'VP1KalmanFitterDNA', + ExtrapolatorHandle = VP1Extrapolator, + RIO_OnTrackCreatorHandle = VP1RotCreator, + MeasurementUpdatorHandle = VP1Updator, + ForwardKalmanFitterHandle = VP1FKF, + KalmanSmootherHandle = VP1BKS, + KalmanOutlierLogicHandle = VP1KOL, + DynamicNoiseAdjustorHandle = VP1DNAdjustor, + AlignableSurfaceProviderHandle = None) + + ToolSvc += VP1KalmanFitterDNA + os.putenv("VP1_JOBCFG_EXTRA_VP1_FITTERS",VP1KalmanFitterDNA.name()) + + + from TrkGlobalChi2Fitter.TrkGlobalChi2FitterConf import Trk__GlobalChi2Fitter + VP1GlobalChi2Fitter = Trk__GlobalChi2Fitter(name = 'VP1GlobalChi2Fitter', + ExtrapolationTool = VP1Extrapolator, + NavigatorTool = VP1Navigator, + PropagatorTool = VP1Propagator, + RotCreatorTool = VP1RotCreator, + MeasurementUpdateTool = VP1Updator, + StraightLine = False, + OutlierCut = 3.0, + SignedDriftRadius = True, + RecalculateDerivatives= True + ) + print VP1GlobalChi2Fitter + ToolSvc += VP1GlobalChi2Fitter + + VP1GlobalChi2Fitter.OutputLevel=DEBUG + + os.putenv("VP1_JOBCFG_EXTRA_VP1_FITTERS","Trk::KalmanFitter/"+VP1KalmanFitter.name()+";"+"Trk::KalmanFitter/"+VP1KalmanFitterDNA.name()+";"+"Trk::GlobalChi2Fitter/"+VP1GlobalChi2Fitter.name()) + +#On a machine where the hostname does not indicate domain, pool will +#fail if trying to find nearest replica. In any case, dblookup.xml +#needs to be patched when running on real data: +include('DumpGeo/vp1FragmentFixDBReplica.py') + +if vp1NoSortDBReplicas: + PoolSvc = Service( "PoolSvc" ) + PoolSvc.SortReplicas = False + + +#Finally, the VP1 algorithm itself: +from DumpGeo.DumpGeoConf import DumpGeo +topSequence += DumpGeo() + +DumpGeo.NoGui=vp1NoGui + +if vp1CruiseTime > 0: + DumpGeo.InitialCruiseMode = "EVENT" + DumpGeo.InitialCruiseModePeriod = vp1CruiseTime + +DumpGeo.InitiallyLoadedVP1Files = vp1CfgFiles +if (vp1Multinp): + DumpGeo.MultipleFilesON = True + DumpGeo.MFSourceDir = vp1Multinpsrc + DumpGeo.MFLocalCopyDir = vp1Multinpcpy + DumpGeo.MFAvailableLocalInputDirectories = vp1MultiAvailableSrcDirs + +topSequence.TimeOut=0 diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentConstructVP1ATLREL.py b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentConstructVP1ATLREL.py new file mode 100644 index 0000000000000000000000000000000000000000..e0eb714e0fcd35ea91b69d73494550db31a56189 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentConstructVP1ATLREL.py @@ -0,0 +1,20 @@ +#Construct VP1ATLREL integer based on AtlasVersion environment +#variable, needed to make script work across releases. As an example +#14.0.1 becomes 140001. Any parts not recognised are replaced with 99. +if not 'VP1ATLREL' in dir(): + import os + versionMajor=99; versionMinor=99; versionPatch=99 + if os.getenv("AtlasVersion") == None: + VP1ATLREL=999999 + else: + atlVerParts=os.getenv("AtlasVersion").split('.') + if len(atlVerParts)>=1 and atlVerParts[0].isdigit(): + versionMajor=eval(atlVerParts[0]) + if len(atlVerParts)>=2 and atlVerParts[1].isdigit(): + versionMinor=eval(atlVerParts[1]) + if len(atlVerParts)>=3 and atlVerParts[2].isdigit(): + versionPatch=eval(atlVerParts[2]) + if versionMinor>99: versionMinor=99 + if versionMinor==99 or versionPatch>99: versionPatch=99 + VP1ATLREL=10000*versionMajor+100*versionMinor+versionPatch + print "VP1ATLREL: "+str(VP1ATLREL) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentFixDBReplica.py b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentFixDBReplica.py new file mode 100644 index 0000000000000000000000000000000000000000..7883ce348a7d4b35d4b735994a42855e62f1fa03 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/share/vp1FragmentFixDBReplica.py @@ -0,0 +1,48 @@ +#/* +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +#*/ + +from AthenaCommon.GlobalFlags import globalflags +import os + +if globalflags.DataSource() == 'data' and os.getenv("FRONTIER_SERVER") == None : + + # Patch dblookup.xml to avoid any attempt to use sqlite replicas + print "VP1 Info: real data mode and Frontier environment not set - need to patch dblookup.xml to avoid using local sqlite replicas." + if os.path.exists("dblookup.xml"): + print "VP1 Warning: dblookup.xml already found in run directory. Will not attempt to created patched copy." + os.putenv("CORAL_DBLOOKUP_PATH",".") + else: + if os.getenv("CORAL_AUTH_PATH") == None or not os.path.isdir(os.getenv("CORAL_AUTH_PATH")): + print "VP1 Warning: CORAL_AUTH_PATH is not set or does not point to directory. Can't create patched dblookup.xml." + else: + dblookupFileLocation=os.getenv("CORAL_AUTH_PATH")+"/dblookup.xml" + if not os.path.exists(dblookupFileLocation) or not os.path.isfile(dblookupFileLocation): + print "VP1 Warning: Did not find CORAL_AUTH_PATH/dblookup.xml. Can't create patched dblookup.xml." + else: + print "VP1 Warning: Attempting to create patched dblookup.xml in current directory" + os.system("cat $CORAL_AUTH_PATH/dblookup.xml |grep -v 'ALLP200.db'> dblookup.xml") + os.putenv("CORAL_DBLOOKUP_PATH",".") + + if os.getenv("ATLAS_CONDDB")==None and (os.getenv("HOSTNAME") == None or os.getenv("HOSTNAME").find('.')<=0): + print "VP1 Warning: Unable to determine domain from runtime environment. Disabling attempt to find nearest replica." + PoolSvc = Service( "PoolSvc" ) + PoolSvc.SortReplicas = False + + print "" + print " ==========>" + print " ========>" + print " ======>" + print " ====>" + print " ====> VP1 Warning: Can't find nearest Oracle replica and you are running on real data." + print " ====> Thus conditions data will have to come from the default, CERN (or you might crash!)." + print " ====>" + print " ====> Notice that this might SIGNIFICANTLY slow down (or even time-out) your job depending" + print " ====> on your location and connection! You can avoid the issue (and this warning) by fixing" + print " ====> your environment: either ATLAS_CONDDB or HOSTNAME. Alternatively you can edit a dblookup.xml file in your2" + print " ====> directory to only leave in references to a closer replica in sections where such a replica is available." + print " ====>" + print " ======>" + print " ========>" + print " ==========>" + print "" diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/DumpGeo.cxx b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/DumpGeo.cxx new file mode 100755 index 0000000000000000000000000000000000000000..dff73cdfaa57c132c840f7b7b9794c1315e2b15f --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/DumpGeo.cxx @@ -0,0 +1,139 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + +#include "DumpGeo/DumpGeo.h" + +#include "GeoExporter/GeoExporter.h" + +#include "EventInfo/EventInfo.h" +#include "EventInfo/TriggerInfo.h" +#include "EventInfo/EventID.h" +#include "PathResolver/PathResolver.h" + +#include "GaudiKernel/IToolSvc.h" +#include "GaudiKernel/FileIncident.h" +#include "GaudiKernel/ServiceHandle.h" +#include "GaudiKernel/IEvtSelector.h" +#include "GaudiKernel/IIncidentSvc.h" + +#include <vector> +#include <stdexcept> +#include <iostream> +#include <iomanip> +#include <cstdlib> //For setenv + + +//____________________________________________________________________ +DumpGeo::DumpGeo(const std::string& name, ISvcLocator* svcLocator): + AthAlgorithm(name, svcLocator), + m_toolSvc(0),m_geoExporter(0) +{ + declareProperty("NoGui",m_noGui=false); + + ::setenv("LCGPATCH_COINMULTISELECT","1",1); +} + +//____________________________________________________________________ +DumpGeo::~DumpGeo() +{ +} + +//____________________________________________________________________ +StatusCode DumpGeo::initialize() +{ + msg(MSG::INFO) << " in initialize() " << endmsg; + + //ToolSvc + StatusCode status = service("ToolSvc",m_toolSvc); + if (status.isFailure()||!m_toolSvc) { + msg(MSG::ERROR) << " Unable to get ToolSvc!" << endmsg; + return status; + } + + // use the incident service to register a handler + IIncidentSvc* incsvc = 0; + status = service("IncidentSvc", incsvc, true); + + if(status.isFailure() || incsvc==0) { + msg(MSG::WARNING) << "Unable to get IncidentSvc! MF mechanism is disabled" << endmsg; + return StatusCode::SUCCESS; + } + + std::string endfilekey("EndTagFile"); + incsvc->addListener(this, endfilekey, 0); + msg(MSG::DEBUG) << "Added listener on "<<endfilekey << endmsg; + + //Create GeoExporter object and see if it considers settings to be valid. + m_geoExporter = new GeoExporter(&(*evtStore()), &(*detStore()), serviceLocator(), m_toolSvc); + if (!m_geoExporter->argumentsAreValid()) { + delete m_geoExporter; + m_geoExporter = 0; + exit(1); + return StatusCode::FAILURE; + } + + try + { + m_geoExporter->init();//Launch! + } + catch ( char* c) + { + std::cout << "Exception: " << c << std::endl; + return StatusCode::FAILURE; + } + + + return StatusCode::SUCCESS; +} + +//____________________________________________________________________ +StatusCode DumpGeo::execute() +{ + msg(MSG::DEBUG) <<" in execute() " << endmsg; + return StatusCode::FAILURE; +} + +//____________________________________________________________________ +StatusCode DumpGeo::finalize() +{ + msg(MSG::INFO) <<" in finalize() " << endmsg; + return StatusCode::SUCCESS; +} + +//____________________________________________________________________ +void DumpGeo::handle(const Incident& inc) +{ + msg(MSG::INFO) << "Handling incident '" << inc.type() << "'" << endmsg; + + if (!m_geoExporter) { + msg(MSG::INFO) << "Aborting due to null GeoExporter pointer." << endmsg; + return; + } + + const FileIncident* fileInc = dynamic_cast<const FileIncident*>(&inc); + if(fileInc == 0) { + msg(MSG::WARNING) << " Unable to cast to file incident" << endmsg; + return; + } + else + msg(MSG::DEBUG) << " Casting to file incident successful" << endmsg; + + // Locate the EventSelector + ServiceHandle<IEvtSelector> pEvtSelector("EventSelector", this->name()); + StatusCode sc = pEvtSelector.retrieve(); + + if(!sc.isSuccess() || 0 == pEvtSelector) { + msg(MSG::WARNING) << "Could not find EventSelector" << endmsg; + return; + } + else + msg(MSG::DEBUG) << " Got EventSelector" << endmsg; + + IProperty* propertyServer = dynamic_cast<IProperty*>(pEvtSelector.operator->()); + if (!propertyServer) { + msg(MSG::WARNING) << "Could not get propertyServer" << endmsg; + return; + } +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/components/DumpGeo_entries.cxx b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/components/DumpGeo_entries.cxx new file mode 100644 index 0000000000000000000000000000000000000000..4ae6ddc1704f000c1c05586b7699d81dfd87e7fb --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/DumpGeo/src/components/DumpGeo_entries.cxx @@ -0,0 +1,10 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// Riccardo Maria BIANCHI <rbianchi@cern.ch> +// Dec 2017 + +#include "DumpGeo/DumpGeo.h" + +DECLARE_COMPONENT( DumpGeo ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d81cdce889674b7c2ed53f7e56b971f78cdbe53 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/CMakeLists.txt @@ -0,0 +1,45 @@ +################################################################################ +# Package: GeoExporter +################################################################################ + +# Declare the package name: +atlas_subdir( GeoExporter ) + +# Declare the package's dependencies: +atlas_depends_on_subdirs( PUBLIC + Control/AthenaBaseComps + GaudiKernel + PRIVATE + Event/EventInfo + Tools/PathResolver + DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter + DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite + DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager + DetectorDescription/GeoModel/GeoModelKernel + DetectorDescription/GeoModel/GeoModelUtilities + graphics/VP1/VP1Utils + ) + +# External dependencies: +find_package( Qt5 COMPONENTS Sql Gui PrintSupport ) +find_package( Eigen ) # is it really needed here? +FIND_PACKAGE( Boost ) # is it really needed here? +find_package( CLHEP ) +find_package( GeoModel ) + +# Component(s) in the package: +atlas_add_library( GeoExporter + src/*.cxx + GeoExporter/*.h + PUBLIC_HEADERS GeoExporter + INCLUDE_DIRS ${EIGEN_INCLUDE_DIRS} ${Boost_INCLUDE_DIRS} + ${CLHEP_INCLUDE_DIRS} + LINK_LIBRARIES Qt5::Sql ${GeoModel_LIBRARIES} GeoModelDBManager + GeoModelUtilities VP1Utils GeoWrite ${CLHEP_LIBRARIES} + ${EIGEN_LIBRARIES} ) + +# Install files from the package: +atlas_install_headers( GeoExporter ) +#atlas_install_python_modules( python/*.py ) +#atlas_install_joboptions( share/*.py ) +#atlas_install_scripts( share/dump-geo ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/GeoExporter/GeoExporter.h b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/GeoExporter/GeoExporter.h new file mode 100755 index 0000000000000000000000000000000000000000..cc2729eb44813c94e5acbe8a4cadd660f550115c --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/GeoExporter/GeoExporter.h @@ -0,0 +1,51 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +///////////////////////////////////////////////////////////// +// // +// Header file for class GeoExporter // +// // +// Author: Riccardo Maria BIANCHI <rbianchi@cern.ch> // +// // +// Initial version: Sept 2016 // +// Major updates: Aug 2018 +// // +///////////////////////////////////////////////////////////// + +#ifndef GeoExporter_H +#define GeoExporter_H + +//NB: There should never be any Qt (or Athena of course) includes in this file!!! + +#include <string> +#include <vector> + +class StoreGateSvc; +class IToolSvc; +class ISvcLocator; + +class GeoExporter { +public: + + GeoExporter(StoreGateSvc* sg, StoreGateSvc* detstore, + ISvcLocator* svclocator,IToolSvc*toolSvc);//, + ~GeoExporter(); + + //We can check the validity of the argument already during algorithm initialise: + bool argumentsAreValid() const; + + //Called in the first algorithm refresh to launch the gui: + void init(); + +private: + + GeoExporter(const GeoExporter & ); + GeoExporter & operator= (const GeoExporter & ); + + class Imp; + Imp *m_d; + +}; + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/README.md b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d9b47e61ad38ea7a07a099fdcde9b3ebab68147f --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/README.md @@ -0,0 +1,6 @@ +# GeoExporter + +GeoExporter loads and builds the GeoModel tree while running inside Athena +and it dumps it into a SQLite file. + +GeoExporter is called by the DumpGeo Athena algorithm. diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/src/GeoExporter.cxx b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/src/GeoExporter.cxx new file mode 100755 index 0000000000000000000000000000000000000000..c74542969759676b0028a2613d8e76d4be4c83e1 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoExporter/src/GeoExporter.cxx @@ -0,0 +1,231 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + +/////////////////////////////////////////////////////////////////////// +// // +// Implementation of class GeoExporter // +// // +// Author: Riccardo Maria BIANCHI <riccardo.maria.bianchi@cern.ch> // +// // +// Initial version: Sep 2017 // +// // +/////////////////////////////////////////////////////////////////////// + +#include "GeoExporter/GeoExporter.h" +#include "VP1Base/VP1Msg.h" + +#include "VP1Utils/VP1JobConfigInfo.h" +#include "VP1Utils/VP1SGAccessHelper.h" + +#include "GeoModelKernel/GeoVolumeCursor.h" +#include "GeoModelKernel/GeoVDetectorManager.h" +#include "GeoModelKernel/GeoBox.h" + +#include "GeoModelUtilities/GeoModelExperiment.h" + +#include "GeoModelDBManager/GMDBManager.h" + +#include "GeoWrite/DumpGeoModelActionLocal.h" + +#include <QCoreApplication> +#include <QtCore/QStringList> +#include <QtCore/QFile> +#include <QtCore/QFileInfo> +#include <QtCore/QUrl> +#include <QtNetwork/QSslSocket> +#include <QProcessEnvironment> + +#include <cassert> +#include <iostream> + +#include <boost/range/irange.hpp> + + + +//____________________________________________________________________ +class GeoExporter::Imp { +public: + Imp() {}; + + //We hold the arguments here until init is called: + StoreGateSvc* sg; + StoreGateSvc* detstore; + ISvcLocator* svclocator; + IToolSvc*toolSvc; +}; + + +//____________________________________________________________________ +GeoExporter::GeoExporter(StoreGateSvc* sg,StoreGateSvc* detstore, + ISvcLocator* svclocator,IToolSvc*toolSvc) + : m_d(new Imp) +{ + m_d->sg = sg; + m_d->detstore = detstore; + m_d->svclocator = svclocator; + m_d->toolSvc = toolSvc; +} + +//____________________________________________________________________ +GeoExporter::~GeoExporter() +{ + delete m_d; m_d=0; +} + +//____________________________________________________________________ +bool GeoExporter::argumentsAreValid() const +{ + //Athena pointers: + + if (!m_d->sg) { + VP1Msg::message("ERROR: Null pointer to event store."); + return false; + } + if (!m_d->detstore) { + VP1Msg::message("ERROR: Null pointer to detector store."); + return false; + } + + return true; +} + + +//____________________________________________________________________ +void GeoExporter::init() +{ + VP1Msg::messageDebug("Start of GeoExporter::init()..."); + + VP1Msg::message(""); + VP1Msg::message("==================================================="); + VP1Msg::message(" Launching the GeoExporter"); + VP1Msg::message("==================================================="); + VP1Msg::message(""); + + static int argc=1; + static char *argv[2]; + + QCoreApplication app(argc, argv); + QCoreApplication::setOrganizationName("ATLAS"); + QCoreApplication::setApplicationName("GeoExporter"); + + VP1Msg::message("Accessing the ATLAS geometry..."); + StoreGateSvc* detstore = m_d->detstore; + //Get the world volume: + const GeoModelExperiment * theExpt = nullptr; + if (!VP1SGAccessHelper(detstore).retrieve(theExpt,"ATLAS")) { + std::cout << "Error: Could not retrieve the ATLAS GeoModelExperiment from detector store" << std::endl; // TODO: move to ATH_MSG_ + //ATH_MSG_FATAL ("Error: Could not retrieve the ATLAS GeoModelExperiment from detector store"); + //return StatusCode::FAILURE; + return; // TODO: move to Return statuscode + } + // GET ATLAS GEOMETRY + PVConstLink world(theExpt->getPhysVol()); + + // ### Get user's settings ### + QProcessEnvironment environment = QProcessEnvironment::systemEnvironment(); + // -- get Detector Description tag + QString default_detdescrtag = environment.value("DUMPGEODETDESCRTAGDEFAULT"); + QString user_detdescrtag = environment.value("DUMPGEODETDESCRTAG"); + if ("1"==default_detdescrtag) { + VP1Msg::message("The user did not specify a DetDescrTag - Using the default one: " + user_detdescrtag); + } + else { + VP1Msg::message("User's settings - DetDescrTag: " + user_detdescrtag); + } + // -- get sub-systems settings + bool user_noid = environment.value("DUMPGEO_NOID").toInt(); + bool user_nocalo = environment.value("DUMPGEO_NOCALO").toInt(); + bool user_nomuon = environment.value("DUMPGEO_NOMUON").toInt(); + QString user_subsystems_filters = "" + QString(((user_noid) ? "-noID" : "")) + QString(((user_nocalo) ? "-noCalo" : "")) + QString(((user_nomuon) ? "-noMuon" : "")); + + // -- get GeoModel Treetop filter // FIXME: check and update this!! + QString user_treetopfilter = environment.value("DUMPGEOTREETOPFILTER"); + VP1Msg::message("User's settings - GeoModel Treetop filter: " + user_treetopfilter); + // -- get Overwrite flag + auto getOWFlag = [&environment]() -> bool { bool okConv; int flag = environment.value("DUMPGEOOVERWRITE").toInt(&okConv, 10); return (okConv && 1==flag) ? true : false; }; // convert the "0"/"1" env var string to bool with a lambda + bool user_overwrite = getOWFlag(); + VP1Msg::message("User's settings - Overwrite filter: " + QString::number(user_overwrite) ); + + // Get list of Treetop names from the TREETOPFILTER + QStringList user_treetopslist; + if ( ! user_treetopfilter.isEmpty() ) + user_treetopslist = user_treetopfilter.split(','); + + /* + // Debug: get list of managers + std::cout << "List of GeoModel managers: " << std::endl; + std::vector<std::string> managersList = theExpt->getListOfManagers(); + for (auto const& mm : managersList) + { + const GeoVDetectorManager* manager = theExpt->getManager(mm); + unsigned int nTreetops = manager->getNumTreeTops(); + std::cout << mm << " - n.Treetops: " << nTreetops << std::endl; + + if ( nTreetops > 0 && user_treetopslist.contains(QString::fromStdString(mm)) ) { + + for(unsigned int i=0; i < nTreetops; ++i) { + + PVConstLink treetop(manager->getTreeTop(i)); + + // DEBUG: dive into the Treetop + if (mm=="BeamPipe") { + GeoVolumeCursor av(treetop); + while (!av.atEnd()) { + std::cout << i << " - name: " << av.getName() << "\n"; + av.next(); // increment volume cursor. + } // end while + } + } // end for + } // end if + } // end for + */ + + std::cout << "Creating the SQLite DB file..." << std::endl; + QString path = ""; + if (user_detdescrtag.isEmpty()) + path = "geometry.db"; + else { + //qDebug() << "user_treetopslist:" << user_treetopslist; + if ( user_treetopslist.isEmpty() ) + path = "geometry-" + user_detdescrtag + user_subsystems_filters + ".db"; + else + path = "geometry-" + user_detdescrtag + "-" + user_treetopslist.join("-") + ".db"; // FIXME: check and update! + } + + // check if path exists and if yes: Is it a file and no directory? + bool fileExists = QFileInfo::exists(path) && QFileInfo(path).isFile(); + if (fileExists) { + if (user_overwrite) { + VP1Msg::message("Removing the existing dump file ("+path+")..."); + QFile file (path); + file.remove(); + } else if ( !user_overwrite ) { + VP1Msg::messageWarningAllRed("The output file ("+path+") is already present in the current folder, but you don't use the '-f' flag to overwrite it. The program will be stopped. Please remove or move the existing file to another folder, or use the '-f' flag to replace it."); + throw "existing output file"; + } + } + // open the DB connection + GMDBManager db(path); + + // check the DB connection + if (db.isOpen()) + qDebug() << "OK! Database is open!"; + else { + qDebug() << "Database ERROR!! Exiting..."; + return; + } + + std::cout << "Dumping the GeoModel geometry to the DB file..." << std::endl; + // Dump the tree volumes into a DB + DumpGeoModelActionLocal dumpGeoModelGraph(db); // init the GeoModel node action + world->exec(&dumpGeoModelGraph); // visit all GeoModel nodes + dumpGeoModelGraph.saveToDB(); // save to the SQlite DB file + std::cout << "DONE. Geometry saved." <<std::endl; + + std::cout << "\nTest - list of all the GeoMaterial nodes in the persistified geometry:" << std::endl; + db.printAllMaterials(); + + VP1Msg::messageDebug("end of GeoExporter::init()."); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d72fef42e32e015936f14d9fbb3163262d3abf6 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/CMakeLists.txt @@ -0,0 +1,24 @@ +################################################################################ +# Package: GeoModelDBManager +################################################################################ + +# Declare the package name: +atlas_subdir( GeoModelDBManager ) + +# comment if you want to get debug messages in Release +if(CMAKE_BUILD_TYPE MATCHES Release) + add_definitions(-DQT_NO_DEBUG_OUTPUT) +endif(CMAKE_BUILD_TYPE MATCHES Release) +if(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + add_definitions(-DQT_NO_DEBUG_OUTPUT) +endif(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + +# External dependencies: +find_package( Qt5 COMPONENTS Core Sql ) + +# Component(s) in the package: +atlas_add_library( GeoModelDBManager + src/*.cpp + GeoModelDBManager/*.h + PUBLIC_HEADERS GeoModelDBManager + LINK_LIBRARIES Qt5::Sql ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/GeoModelDBManager/GMDBManager.h b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/GeoModelDBManager/GMDBManager.h new file mode 100644 index 0000000000000000000000000000000000000000..ca001831e02f313042cbfc10694a9fd96949b8b3 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/GeoModelDBManager/GMDBManager.h @@ -0,0 +1,188 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + +// author: Riccardo.Maria.Bianchi@cern.ch +// major updates: Aug 2018 + +#ifndef GMDBManager_H +#define GMDBManager_H + +//#include "GeoModelKernel/GeoNodeAction.h" +//#include "GeoModelKernel/GeoGraphNode.h" + +// include Qt +#include <QSqlDatabase> +#include <QStringList> +#include <QVariant> +#include <QString> +#include <QMap> + +// include C++ +#include <iostream> + +/** + * \class GMDBManager + * + * \brief SQL Database Manager class for GeoModel + * + * GMDBManager sets up the connection with SQL database + * and performs some basics queries. + */ +class GMDBManager +{ +public: + /** + * @brief Constructor + * + * Constructor sets up connection with db and opens it + * @param path - absolute path to db file + */ + GMDBManager(const QString& path); + + /** + * @brief Destructor + * + * Close the db connection + */ + ~GMDBManager(); + + + bool isOpen() const; + + /** + * @brief Print names of all PhysVol objects in db + */ + void printAllPhysVols() const; + void printAllFullPhysVols() const; + + /** + * @brief Print names of all PhysVol objects in db + */ + void printAllLogVols() const; + + /** + * @brief Print names of all PhysVol objects in db + */ + void printAllMaterials() const; + + /** + * @brief Print names of all PhysVol objects in db + */ + void printAllShapes() const; + + /** + * @brief Print names of all PhysVol objects in db + */ + void printAllSerialDenominators() const; + void printAllSerialTransformers() const; + void printAllFunctions() const; + void printAllTransforms() const; + void printAllAlignableTransforms() const; + void printAllNameTags() const; + + /** + * @brief Print the db table storing all the children positions per parent + */ + void printAllChildrenPositions() const; + + /** + * @brief Print the db table storing all the children positions per parent + */ + void printAllNodeTypes() const; + + /** + * @brief Print the DB table storing the ID of the PhysVol that is the Root volume + */ + void printRootVolumeId() const; + + void printDBVersion() const; + + // ADD methods + QVariant addShape(const QString &type, const QString ¶meters); + QVariant addMaterial(const QString &name); + QVariant addLogVol(const QString &name, const QVariant &shapeId, const QVariant &materialId); + QVariant addPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume = false); + QVariant addFullPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume = false); + QVariant addSerialDenominator(const QString &baseName); + QVariant addFunction(const QString expression); + QVariant addSerialTransformer(const QVariant &funcId, const QVariant &physvolId, const QString volType, const unsigned int &copies); + QVariant addTransform(QVector<double> parameters); + QVariant addAlignableTransform(QVector<double> parameters); + QVariant addNameTag(const QString &name); + + + bool addListOfRecords(const QString geoType, const std::vector<QStringList> records); + bool addListOfRecordsToTable(const QString tableName, const std::vector<QStringList> records); + bool addListOfRecordsToTableOld(const QString tableName, const std::vector<QStringList> records); + bool addListOfChildrenPositions(const std::vector<QStringList> records); + + bool addRootVolume(const QStringList); + void addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int parentCopyNumber, const unsigned int childPos, const QString childType, const unsigned int childCopyN); + + void addDBversion(const QString); + + // GET methods + + QString getDBFilePath(); + + QStringList getRootPhysVol(); + + QStringList getItem(QString geoType, unsigned int id); + QStringList getItem(unsigned int tableId, unsigned int id); + QStringList getItemFromTableName(QString tableName, unsigned int id); + QStringList getItemAndType(unsigned int tableId, unsigned int id); + + QString getNodeTypeFromTableId(unsigned int id); + + QMap<unsigned int, QStringList> getVPhysVolChildren(const unsigned int id, const QString nodeType, const unsigned int copyN); + + /// methods to dump the DB + QHash<QString, QMap<unsigned int, QStringList>> getChildrenTable(); + QHash<unsigned int, QStringList> getTableFromNodeType(QString nodeType); + QHash<unsigned int, QString> getAll_TableIDsNodeTypes(); + QHash<QString, unsigned int> getAll_NodeTypesTableIDs(); + + +private: + + bool initDB(); + bool createTables(); + + void loadTestData(); // for debug only + + void loadTableNamesFromDB(); + QStringList getTableColNamesFromDB(QString tableName) const; + + QString getTableNameFromTableId(unsigned int tabId); + QVariant getTableIdFromNodeType(QString nodeType); + void storeNodeType(QString nodeType, QString tableName); + QString getTableNameFromNodeType(QString nodeType); + + QSqlQuery selectAllFromTable(QString tableName) const; + + + void storeTableColumnNames(QStringList input); + QStringList getTableColumnNames(QString tableName); + void printTableColNamesFromDB(QString tableName) const; + + void printAllRecords(QString tableName) const; + + int getTableColIndex(QString tableName, QString colName); + + bool storeRootVolume(QVariant id, QString nodeType); + + void showError(const QSqlError &err) const; + + QString m_dbpath; + QSqlDatabase m_db; + bool m_dbIsOK; + + bool m_deepDebug; + + QMap<QString, QStringList> m_tableNames; + QMap<QString, QString> m_childType_tableName; +}; + +#endif // GMDBManager_H diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/src/GMDBManager.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/src/GMDBManager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..df2bd2de8ddc0f76c56a808e4eeb084f50fb3b9a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager/src/GMDBManager.cpp @@ -0,0 +1,1518 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// author: Riccardo.Maria.Bianchi@cern.ch +// major updates: Aug 2018 + +#include <GeoModelDBManager/GMDBManager.h> + +#include <QSqlQuery> +#include <QSqlError> +#include <QSqlRecord> +#include <QSqlDriver> +#include <QDebug> + + +static std::string dbversion = "0.2.0"; + + +GMDBManager::GMDBManager(const QString &path) : m_dbpath(path), m_dbIsOK(false), m_deepDebug(false) +{ + qDebug() << "GMDBManager: constructor"; + + #ifdef GEOREAD_DEEP_DEBUG + m_deepDebug = true; + #endif + + + m_dbIsOK = true; + + m_db = QSqlDatabase::addDatabase("QSQLITE"); + m_db.setDatabaseName(path); + + if (!m_db.open()) + { + qDebug() << "Error: connection with database failed!"; + showError( m_db.lastError() ); + m_dbIsOK = false; + } + else + { + qDebug() << "Database: connection ok"; + m_dbIsOK = true; + } + + + // check if DB has tables, if not create them + if (m_dbIsOK) { + if ( ! (initDB()) ) { + std::cout << "Error: database initialization failed" << std::endl; + m_dbIsOK = false; + } + } + + // populate DB with fake data, only for debug + //loadTestData(); +} + +GMDBManager::~GMDBManager() +{ + qDebug() << "GMDBManager: destructor"; + if (m_db.isOpen()) + { + m_db.close(); + } +} + +bool GMDBManager::isOpen() const +{ + if (! m_dbIsOK ) + return false; + return m_db.isOpen(); +} + + +void GMDBManager::printAllMaterials() const +{ + qDebug() << "printAllMaterials()"; + printAllRecords("Materials"); +} +void GMDBManager::printAllShapes() const +{ + qDebug() << "printAllShapes()"; + printAllRecords("Shapes"); +} + +void GMDBManager::printAllSerialDenominators() const +{ + qDebug() << "printAllShapes()"; + printAllRecords("SerialDenominators"); +} + +void GMDBManager::printAllLogVols() const +{ + qDebug() << "printAllLogVols()"; + printAllRecords("LogVols"); +} +void GMDBManager::printAllPhysVols() const +{ + qDebug() << "printAllPhysVols()"; + printAllRecords("PhysVols"); +} +void GMDBManager::printAllFullPhysVols() const +{ + qDebug() << "printAllFullPhysVols()"; + printAllRecords("FullPhysVols"); +} +void GMDBManager::printAllSerialTransformers() const +{ + qDebug() << "printAllSerialTransformers()"; + printAllRecords("SerialTransformers"); +} +void GMDBManager::printAllFunctions() const +{ + qDebug() << "printAllFunctions()"; + printAllRecords("Functions"); +} +void GMDBManager::printAllTransforms() const +{ + qDebug() << "printAllTransforms()"; + printAllRecords("Transforms"); +} +void GMDBManager::printAllAlignableTransforms() const +{ + qDebug() << "printAllAlignableTransforms()"; + printAllRecords("AlignableTransforms"); +} +void GMDBManager::printAllNameTags() const +{ + qDebug() << "printAllNameTags()"; + printAllRecords("NameTags"); +} +void GMDBManager::printAllChildrenPositions() const +{ + qDebug() << "printAllChildrenPositions()"; + printAllRecords("ChildrenPositions"); +} +void GMDBManager::printAllNodeTypes() const +{ + qDebug() << "printAllNodeTypes()"; + printAllRecords("GeoNodesTypes"); +} +void GMDBManager::printRootVolumeId() const +{ + qDebug() << "printRootVolumeId()"; + printAllRecords("RootVolume"); +} +void GMDBManager::printDBVersion() const +{ + qDebug() << "printDBVersion()"; + printAllRecords("dbversion"); +} + + + + +void GMDBManager::printAllRecords(QString tableName) const +{ + std::cout << tableName.toStdString() << " in db:" << std::endl; + + // QSqlQuery query("SELECT * FROM " + tableName); + QSqlQuery query = selectAllFromTable(tableName); + + int nCols = (m_tableNames[tableName]).size(); + + // print table column names + std::cout << "- " << m_tableNames[tableName].join(", ").toStdString() << std::endl; + while (query.next()) + { + std::cout << "* "; // TODO: move to a osstream: it's cleaner + for( int ii=0; ii<nCols; ++ii) + { + if (! (ii==0) ) + std::cout << ", "; + std::string valueStr = query.value(ii).toString().toStdString(); + // if (valueStr == "") + // std::cout << "NULL"; // removed because we want to save the NULL to the DB, for consistency + // else + std::cout << valueStr; + } + std::cout << std::endl; + } + + // TODO: I want to have a symbol like '---' to mean empty line when query gives 0 results. + // but I guess query.size() is not the right method... + // qDebug() << "query size: " << query.size(); + // if (query.size() == 0 || query.size() == -1) + // std::cout << "---" << std::endl; + +} +QHash<unsigned int, QStringList> GMDBManager::getTableFromNodeType(QString nodeType) +{ + + QString tableName = getTableNameFromNodeType(nodeType); + + QHash<unsigned int, QStringList> records; + QStringList nodeParams; + + int nCols = (m_tableNames[tableName]).size(); + + QSqlQuery query = selectAllFromTable(tableName); + while (query.next()) { + nodeParams.clear(); + unsigned int nodeId = query.value(0).toUInt(); + + for( int ii=0; ii<nCols; ++ii) { + nodeParams << query.value(ii).toString(); + } + records[nodeId] = nodeParams; + } +return records; +} + + +void GMDBManager::showError(const QSqlError &err) const +{ + qWarning() << "Unable to initialize Database" << "Error initializing database: " + err.text(); +} + +QVariant GMDBManager::addPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addPhysVol() - is root?" << isRootVolume; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into PhysVols(logvol, parent) values(?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(logVolId); + q.addBindValue(parentPhysVolId); + q.exec(); + + QVariant lastInserted = q.lastInsertId(); + + if (isRootVolume) { + storeRootVolume(lastInserted, "GeoPhysVol"); + } + + return lastInserted; + +} + +QVariant GMDBManager::addFullPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addFullPhysVol() - is root?" << isRootVolume; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into FullPhysVols(logvol, parent) values(?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(logVolId); + q.addBindValue(parentPhysVolId); + q.exec(); + + QVariant lastInserted = q.lastInsertId(); + + if (isRootVolume) { + storeRootVolume(lastInserted, "GeoFullPhysVol"); + } + + return lastInserted; + +} + + + +QVariant GMDBManager::addLogVol(const QString &name, const QVariant &shapeId, const QVariant &materialId) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addLogVol()"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into LogVols(name, shape, material) values(?, ?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(name); + q.addBindValue(shapeId); + q.addBindValue(materialId); + q.exec(); + return q.lastInsertId(); +} + +QVariant GMDBManager::addMaterial(const QString &name) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addMaterial()"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into Materials(name) values(?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} + +bool GMDBManager::addListOfChildrenPositions(const std::vector<QStringList> records) +{ + // NOTE: Choose the right function for your version of SQLite!! + return addListOfRecordsToTable("ChildrenPositions", records); // newest SQLite versions + //return addListOfRecordsToTableOld("ChildrenPositions", records); // old SQLite versions +} + +bool GMDBManager::addListOfRecords(const QString geoType, const std::vector<QStringList> records) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addListOfRecords():" << geoType; + + QString tableName = m_childType_tableName[geoType]; + + if (tableName.isEmpty()) { + //qWarning() << "m_childType_tableName:" << m_childType_tableName; + qWarning() << "ERROR!! could not retrieve tableName for node type " << geoType << "!! Aborting..."; + exit(1); + } + + if (records.size() > 0 ) { + // NOTE: Choose the right function!! + return addListOfRecordsToTable(tableName, records); // newest SQLite versions + //return addListOfRecordsToTableOld(tableName, records); // old SQLite versions + } + else + qWarning() << "Info: no records to save for geoType '" << geoType << "'. Skipping..."; + return true; +} + +// ***Note*** +// the syntax built here below is more convenient +// but it is supported only in SQLite >= 3.7.11 +// ...but SLC6 only has 3.7.9! +// here we build a query like this: +// queryStr = QString("INSERT INTO Materials (id, name) VALUES (1,'Air'), (2,'Silicon'), (368,'ShieldSteel');"); +// +bool GMDBManager::addListOfRecordsToTable(const QString tableName, const std::vector<QStringList> records) +{ + // get table columns and format them for query + QString tableColString = "(" + m_tableNames[tableName].join(", ") + ")"; + + unsigned int nRecords = records.size(); + qInfo() << "number of " << tableName << "records to insert into the DB:" << nRecords; + + // preparing the SQL query + QString queryStr("INSERT INTO %1 %2 VALUES "); + queryStr = queryStr.arg(tableName); // insert table name + queryStr = queryStr.arg(tableColString); // insert table columns + + unsigned int nMat = nRecords; + unsigned int id = 0; + foreach(QStringList rec, records) { + //qDebug() << "rec:" << rec; + + ++id; + QStringList items; + + foreach (QString item, rec) { + items << '"' + item + '"'; + } + QString values = items.join(","); + queryStr += " (" + QString::number(id) + "," + values + ")"; + if (id != nMat) + queryStr += ","; + else + queryStr += ";"; + + } + qDebug() << "queryStr:" << queryStr; + + // executing the SQL query + QSqlQuery q; + if (!q.exec(queryStr)) { + qWarning() << "ERROR!!! SQL error:"; + showError(q.lastError()); + return false; + } + + qDebug() << "DONE. The list of records have been inserted into the DB."; + return true; +} + + + +// ***Note*** +// old syntax, for SQLite in SLC6 +// here below we build the syntax for multiple INSERT +// compatible with old SQLite versions +// see: stackoverflow.com/questions/1609637 +// +// we want to build a query like this: +// queryStr = QString("INSERT INTO Materials (id, name) SELECT 1 as id, 'Air' as name UNION ALL SELECT 2,'Silicon' UNION ALL SELECT 368,'ShieldSteel' ") +// +bool GMDBManager::addListOfRecordsToTableOld(const QString tableName, const std::vector<QStringList> records) +{ + // get table columns and format them for query + QString tableColString = "(" + m_tableNames[tableName].join(", ") + ")"; + + + + QStringList colNames = m_tableNames[tableName]; + unsigned int nRecords = records.size(); + qInfo() << "number of " << tableName << "records to insert into the DB:" << nRecords; + + /* + * SQLite has a limit on 'union' items, set at 500. So we have to split the items if we have more. + * See: stackoverflow.com/questions/9527851/ + */ + unsigned int bunchSize = 500; + if ( nRecords > bunchSize ) { + qWarning() << "WARNING! " << nRecords << " records of type " << tableName << "to store in the DB in one call! Call limit is " << bunchSize << " --> We split them in bunches..."; + + std::vector<QStringList> recordsCopy( records ); // TODO: maybe we should use a deque or queue, which have fast pop of first element? + + std::vector<QStringList>::const_iterator first; + std::vector<QStringList>::const_iterator last; + + unsigned int start = 0; + + while ( recordsCopy.size() > 0 ) { + + // preparing the SQL query + QString queryStr("INSERT INTO %1 %2 SELECT "); + queryStr = queryStr.arg(tableName); // insert table name + queryStr = queryStr.arg(tableColString); // insert table columns + + first = recordsCopy.begin(); + last = recordsCopy.size() > bunchSize ? recordsCopy.begin() + bunchSize : recordsCopy.end(); + + std::vector<QStringList> recordsBunch( first, last ); // we take the first 500 records + recordsCopy.erase( first, last ); // we delete the first 500 records + if (m_deepDebug) qDebug() << "start:" << start << "recordsBunch size:" << recordsBunch.size() << "- recordsCopy size after removal:" << recordsCopy.size(); + + // --- first record + // outcome should be like: " 1 as id, 'Air' as name " + unsigned int id = start+1; // set the first ID as 'start' + QStringList recFirst = recordsBunch.front(); // access first record from vector + recordsBunch.erase( recordsBunch.begin() ); // delete first record + if (m_deepDebug) qDebug() << "after taking first record - recordsBunch size:" << recordsBunch.size(); + + // first item in the first record (it is the ID) + QString firstCol = colNames[0]; + queryStr += QString::number(id) + " as " + firstCol + ", "; + + // the other items in the first record + unsigned int ii = 1; + unsigned int nRecs = recFirst.size(); + foreach (QString rec, recFirst) { + queryStr += "'" + rec + "'" + " as " + colNames[ii]; + if (ii != nRecs) + queryStr += ","; // add coma, but not on latest + queryStr += " "; // add space + //qDebug() << "first element:" << ii << nRecs << queryStr; + ++ii; + } + if (m_deepDebug) qDebug() << "first element query:" << queryStr; + // --- other records + // outcome should be: " UNION ALL SELECT 2,'Silicon' " + + + foreach(QStringList recs, recordsBunch) { + + // DEBUG + if (tableName == "Functions") { + if (recs[1].length() > 65000) { + std::cout << "LONG STRING! size: " << recs[1].length() << std::endl; + std::cout << "LONG STRING! string: " << recs[1].toStdString() << std::endl << std::endl; + } + } + //------ + + ++id; + // put single quotes around items + QStringList items; + foreach (QString item, recs) { + items << "'" + item + "'"; + } + // join items into a string and add the SQL commands + QString itemsStr = items.join(", "); + queryStr += " UNION ALL SELECT " + QString::number(id) + ", " + itemsStr; + } + + //qDebug() << "queryStr:" << queryStr; + + // executing the SQL query + QSqlQuery q; + if (!q.exec(queryStr)) { + qWarning() << "ERROR!!! SQL error:"; + showError(q.lastError()); + return false; + } + qDebug() << bunchSize << "elements have been saved into the DB, starting at:" << start; + + start += bunchSize; // for the next iteration + + } // end of while + + } // end of if(>500) + else { + // preparing the SQL query + QString queryStr("INSERT INTO %1 %2 SELECT "); + queryStr = queryStr.arg(tableName); // insert table name + queryStr = queryStr.arg(tableColString); // insert table columns + + unsigned int id = 0; + // loop on all records + foreach(QStringList recs, records) { + + ++id; + + // first record + // outcome should be like: " 1 as id, 'Air' as name " + if (id == 1) { + + // first item if the record (it is the ID) + QString firstCol = colNames.takeFirst(); + queryStr += QString::number(id) + " as " + firstCol + ", "; + + // the other items in the record + unsigned int ii = 0; + unsigned int nRecs = recs.size(); + foreach (QString rec, recs) { + queryStr += "'" + rec + "'" + " as " + colNames[ii]; + if (ii != nRecs-1) + queryStr += ","; // add coma, but not on latest + queryStr += " "; // add space + //qDebug() << ii << nRecs << queryStr; + ++ii; + } + + } + // other records + // outcome should be: " UNION ALL SELECT 2,'Silicon' " + else { + + // put single quotes around items + QStringList items; + foreach (QString item, recs) { + items << "'" + item + "'"; + } + // join items into a string and add the SQL commands + QString itemsStr = items.join(", "); + queryStr += " UNION ALL SELECT " + QString::number(id) + ", " + itemsStr; + } + + } // end of: foreach(QStringList recs, records) + + //qDebug() << "queryStr:" << queryStr; + + // executing the SQL query + QSqlQuery q; + if (!q.exec(queryStr)) { + qWarning() << "ERROR!!! SQL error:"; + showError(q.lastError()); + return false; + } +} // end of (else > 500) + + qDebug() << "DONE. The list of " << nRecords << "records have been inserted into the DB."; + return true; + +} + + + + + +QVariant GMDBManager::addShape(const QString &type, const QString ¶meters) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addShape()"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into Shapes(type, parameters) values(?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(type); + q.addBindValue(parameters); + q.exec(); + return q.lastInsertId(); +} + +QVariant GMDBManager::addSerialDenominator(const QString &baseName) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addSerialDenominator("+baseName+")"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into SerialDenominators(baseName) values(?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(baseName); + q.exec(); + return q.lastInsertId(); +} + +QVariant GMDBManager::addNameTag(const QString &name) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addNameTag("+name+")"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into NameTags(name) values(?)"))) { + showError(q.lastError()); + return QVariant(); + } + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} + +QVariant GMDBManager::addFunction(const QString expression) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addFunction()"; + + // TEST + std::cout << "Function - expression string len: " << expression.length(); + std::cout << "Function - expression: " << expression.toStdString() << std::endl << std::endl; + //----- + + qDebug() << "expression:" << expression; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into Functions(expression) values(?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(expression); + q.exec(); + return q.lastInsertId(); + + +} + +QVariant GMDBManager::addSerialTransformer(const QVariant &funcId, const QVariant &physvolId, const QString physvolType, const unsigned int &copies) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addSerialTransformer()" << funcId << physvolId << copies; + + QVariant volTableId = getTableIdFromNodeType(physvolType); + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into SerialTransformers(funcId, volId, volTable, copies) values(?, ?, ?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(funcId); + q.addBindValue(physvolId); + q.addBindValue(volTableId); + q.addBindValue(copies); + q.exec(); + return q.lastInsertId(); +} + +QVariant GMDBManager::addTransform(QVector<double> params) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addTransform()"; + + // get the 12 matrix elements + double xx = params[0]; + double xy = params[1]; + double xz = params[2]; + + double yx = params[3]; + double yy = params[4]; + double yz = params[5]; + + double zx = params[6]; + double zy = params[7]; + double zz = params[8]; + + double dx = params[9]; + double dy = params[10]; + double dz = params[11]; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into Transforms(xx, xy, xz, yx, yy, yz, zx, zy, zz, dx, dy, dz) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(xx); + q.addBindValue(xy); + q.addBindValue(xz); + q.addBindValue(yx); + q.addBindValue(yy); + q.addBindValue(yz); + q.addBindValue(zx); + q.addBindValue(zy); + q.addBindValue(zz); + q.addBindValue(dx); + q.addBindValue(dy); + q.addBindValue(dz); + q.exec(); + return q.lastInsertId(); +} + + +QVariant GMDBManager::addAlignableTransform(QVector<double> params) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addAlignableTransform()"; + + // get the 12 matrix elements + double xx = params[0]; + double xy = params[1]; + double xz = params[2]; + + double yx = params[3]; + double yy = params[4]; + double yz = params[5]; + + double zx = params[6]; + double zy = params[7]; + double zz = params[8]; + + double dx = params[9]; + double dy = params[10]; + double dz = params[11]; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into AlignableTransforms(xx, xy, xz, yx, yy, yz, zx, zy, zz, dx, dy, dz) values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"))) { + showError(q.lastError()); + return QVariant(); + } + + q.addBindValue(xx); + q.addBindValue(xy); + q.addBindValue(xz); + q.addBindValue(yx); + q.addBindValue(yy); + q.addBindValue(yz); + q.addBindValue(zx); + q.addBindValue(zy); + q.addBindValue(zz); + q.addBindValue(dx); + q.addBindValue(dy); + q.addBindValue(dz); + q.exec(); + return q.lastInsertId(); +} + + +bool GMDBManager::addRootVolume(const QStringList values) +{ + if (values.size() > 0 ) { + QVariant volId = QVariant(values[0]); + QString nodeType = values[1]; + return storeRootVolume( volId, nodeType ); + } + else + qFatal("Info: no records to save for RootVolume!"); + return false; +} + +// insert a single parent-child relationship for a given parent volume +void GMDBManager::addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int parentCopyNumber, const unsigned int childPos, const QString childType, const unsigned int childCopyN) +{ + if (m_deepDebug) qDebug() << "GMDBManager::addChildPosition(" << parentId << "," << parentType << "," << QString::number(parentCopyNumber) << "," <<childPos << "," << childType << ", " << childId << ", " << QString::number(childCopyN) << ")"; + + // get table name -- which the child ID refers to -- based on the child type + QVariant parentTableId = getTableIdFromNodeType(parentType); + QVariant childTableId = getTableIdFromNodeType(childType); + + QString tableName = "ChildrenPositions"; + QStringList cols = getTableColumnNames(tableName); + + QString queryStr = QString("insert into %1(%2, %3, %4, %5, %6, %7, %8) values(?, ?, ?, ?, ?, ?, ?)").arg(tableName); + for (int i=0; i < cols.size(); ++i) { + if (i != 0) // skip the "id" column + queryStr = queryStr.arg( cols.at(i) ); + } + if (m_deepDebug) qDebug() << "queryStr:" << queryStr; + QSqlQuery q; + if (!q.prepare(queryStr)) { + showError(q.lastError()); + return; + } + qDebug() << "parent:" << parentId; + q.addBindValue(parentId); + q.addBindValue(parentTableId); + q.addBindValue(parentCopyNumber); + q.addBindValue(childPos); + q.addBindValue(childTableId); + q.addBindValue(childId); + q.addBindValue(childCopyN); + q.exec(); + return; +} + +void GMDBManager::addDBversion(const QString version) +{ + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into dbversion(version) values(?)"))) { + showError(q.lastError()); + return; + } + q.addBindValue(version); + q.exec(); + return; +} + + +QStringList GMDBManager::getItem(QString geoType, unsigned int id) +{ + if (m_deepDebug) qDebug() << "GMDBManager::getItem(geoType, id)"<< geoType << QString::number(id); + + /* Get the right DB table */ + QString tableName = getTableNameFromNodeType(geoType); + return getItemFromTableName(tableName, id); +} + + +QStringList GMDBManager::getItem(unsigned int tableId, unsigned int id) +{ + if (m_deepDebug) qDebug() << "GMDBManager::getItem(tableId, id)"<< QString::number(tableId) << QString::number(id); + /* Get the right DB table */ + QString tableName = getTableNameFromTableId(tableId); + return getItemFromTableName(tableName, id); + +} + +QStringList GMDBManager::getItemAndType(unsigned int tableId, unsigned int id) +{ + if (m_deepDebug) qDebug() << "GMDBManager::getItemAndType(tableId, id)"<< QString::number(tableId) << QString::number(id); + /* Get the right DB table */ + QString tableName = getTableNameFromTableId(tableId); + + QString nodeType = getNodeTypeFromTableId(tableId); + + QStringList results; + QStringList item = getItemFromTableName(tableName, id); + + results << nodeType << item; + + return results; + +} + + +QStringList GMDBManager::getItemFromTableName(QString tableName, unsigned int id) +{ + if (m_deepDebug) qDebug() << "GMDBManager::getItemFromTableName(tableName, id)"<< tableName << QString::number(id); + /* + * 2. Get the object from DB + */ + // prepare a SQL string with the right table name + QString queryStr = QString("SELECT * FROM %1 WHERE id = (?)").arg(tableName); + // prepare the query + QSqlQuery q; + if (!q.prepare( queryStr )) { + showError(q.lastError()); + return QStringList(); + } + q.addBindValue(id); + q.exec(); + + QStringList params; + + // get the number of columns of the DB table + int nCols = (m_tableNames[tableName]).size(); + + while (q.next()) { + + for( int ii=0; ii<nCols; ++ii) + params << q.value(ii).toString(); + } + if (params.length()==0) { + qWarning() << "WARNING!!" << "Item" << id << "does not exist in table" << tableName << "!!"; + } + return params; +} + +// get the list of children for a single GeoVPhysVol (i.e., GeoPhysVol or GeoFullPhysVol) +QMap<unsigned int, QStringList> GMDBManager::getVPhysVolChildren(const unsigned int id, const QString nodeType, const unsigned int parentCopyNumber) +{ + if (m_deepDebug) qDebug() << "GMDBManager::getVPhysVolChildren() - id:" << QString::number(id) << "- type:" << nodeType << "- copyN:" << QString::number(parentCopyNumber); + + QVariant tableId = getTableIdFromNodeType(nodeType); + + // get children and their positions + QSqlQuery q; + if (!q.prepare(QLatin1String("SELECT * FROM ChildrenPositions WHERE parentId = (?) AND parentTable = (?) AND parentCopyNumber = (?)"))) { + showError(q.lastError()); + return QMap<unsigned int, QStringList>(); + } + q.addBindValue(id); + q.addBindValue(tableId); + q.addBindValue(parentCopyNumber); + q.exec(); + + QMap<unsigned int, QStringList> children; + QStringList childParams; + + // get the number of columns of the DB table + int nCols = m_tableNames["ChildrenPositions"].size(); + + while (q.next()) { + + childParams.clear(); + + unsigned int childPos = q.value(3).toUInt(); + + for( int ii=0; ii<nCols; ++ii) + childParams << q.value(ii).toString(); + + children[childPos] = childParams; + } + + return children; +} + + +// Get all parent-children data from the database in one go +QHash<QString, QMap<unsigned int, QStringList>> GMDBManager::getChildrenTable() +{ + qDebug() << "GMDBManager::getChildrenTable()"; + + QSqlQuery q = selectAllFromTable("ChildrenPositions"); + + QHash< QString, QMap<unsigned int, QStringList> > all_children; // to store all children + // QMap<unsigned int, QStringList> children; // to temporarily store the children of one parent + QStringList childParams; // to temporarily store the children parameters + + // get the number of columns of the DB table + int nCols = m_tableNames["ChildrenPositions"].size(); + qDebug() << "num of columns in childrenPos table" << nCols; + + // loop over all children's positions stored in the DB + while (q.next()) { + + childParams.clear(); + + QString parentId = q.value(1).toString(); + QString parentTable = q.value(2).toString(); + QString parentCopyNumber = q.value(3).toString(); + unsigned int childPos = q.value(4).toUInt(); + + QString key = parentId + ":" + parentTable + ":" + parentCopyNumber; + + for( int ii=0; ii<nCols; ++ii) + childParams << q.value(ii).toString(); + + all_children[key][childPos] = childParams; + } + return all_children; +} + + + +QVariant GMDBManager::getTableIdFromNodeType(QString nodeType) +{ + qDebug() << "GMDBManager::getTableIdFromNodeType("<< nodeType <<")"; + QSqlQuery q; + if (!q.prepare(QLatin1String("SELECT id FROM GeoNodesTypes WHERE nodeType = (?)"))) { + showError(q.lastError()); + return QVariant(); + } + q.addBindValue(nodeType); + q.exec(); + + QVariant id; + while (q.next()) { + id = q.value(0); + qDebug() << "id:" << id; + } + + return id; +} + +QString GMDBManager::getTableNameFromNodeType(QString nodeType) +{ + qDebug() << "GMDBManager::getTableNameFromNodeType("<< nodeType <<")"; + QSqlQuery q; + if (!q.prepare(QLatin1String("SELECT tableName FROM GeoNodesTypes WHERE nodeType = (?)"))) { + showError(q.lastError()); + return QString(); + } + q.addBindValue(nodeType); + q.exec(); + + QString tableName; + while (q.next()) { + tableName = q.value(0).toString(); + qDebug() << "tableName:" << tableName; + } + + return tableName; +} + +// TODO: this and other methods could take data from in-memory maps, without asking to the DB all the times +QString GMDBManager::getTableNameFromTableId(unsigned int tabId) +{ + qDebug() << "GMDBManager::getTableNameFromTableId()"; + QSqlQuery q; + if (!q.prepare(QLatin1String("SELECT tableName FROM GeoNodesTypes WHERE id = (?)"))) { + showError(q.lastError()); + return QString(); + } + q.addBindValue(tabId); + q.exec(); + + QString tableName; + while (q.next()) { + tableName = q.value(0).toString(); + qDebug() << "tableName:" << tableName; + } + + return tableName; +} + +QString GMDBManager::getNodeTypeFromTableId(unsigned int tabId) +{ + qDebug() << "GMDBManager::getNodeTypeFromTableId()"; + QSqlQuery q; + if (!q.prepare(QLatin1String("SELECT nodeType FROM GeoNodesTypes WHERE id = (?)"))) { + showError(q.lastError()); + return QString(); + } + q.addBindValue(tabId); + q.exec(); + + QString nodeType; + while (q.next()) { + nodeType = q.value(0).toString(); + qDebug() << "tableName:" << nodeType; + } + + return nodeType; +} + + +QHash<unsigned int, QString> GMDBManager::getAll_TableIDsNodeTypes() +{ + qDebug() << "GMDBManager::getAll_TableIDsNodeTypes()"; + + QHash<unsigned int, QString> output; + + QSqlQuery q = selectAllFromTable("GeoNodesTypes"); + + unsigned int id; + QString nodeType; + // QString tableName; + while (q.next()) { + id = q.value(0).toUInt(); + nodeType = q.value(1).toString(); + output[id] = nodeType; + } + return output; +} + + +QHash<QString, unsigned int> GMDBManager::getAll_NodeTypesTableIDs() +{ + qDebug() << "GMDBManager::getAll_NodeTypesTableIDs()"; + + QHash<QString, unsigned int> output; + + QSqlQuery q = selectAllFromTable("GeoNodesTypes"); + + unsigned int id; + QString nodeType; + // QString tableName; + while (q.next()) { + id = q.value(0).toUInt(); + nodeType = q.value(1).toString(); + output[nodeType] = id; + } + return output; +} + + +QSqlQuery GMDBManager::selectAllFromTable(QString tableName) const +{ + QSqlQuery q; + + QString queryStr = QString("SELECT * FROM %1"); + queryStr = queryStr.arg(tableName); + + if (!q.prepare(queryStr)) { + showError(q.lastError()); + return QSqlQuery(); + } + q.exec(); + return q; +} + + +bool GMDBManager::initDB() +{ + qDebug() << "GMDBManager::initDB()"; + + + // check if DB is empty + qDebug() << "checking existing tables..."; + QSqlDatabase db = QSqlDatabase::database(); + QStringList tables = db.tables(); + if (tables.contains("LogVols", Qt::CaseInsensitive) + && tables.contains("PhysVols", Qt::CaseInsensitive) + && tables.contains("Materials", Qt::CaseInsensitive) + && tables.contains("Shapes", Qt::CaseInsensitive) + ) { + qDebug() << "tables are present already. Skipping tables creation. Loading tables..."; + loadTableNamesFromDB(); + return true; + } + + // if DB is empty, then create tables + qDebug() << "DB file is empty. Creating tables..."; + bool tablesOK = createTables(); + + // store DB version + qDebug() << "Storing DB version:" << QString::fromStdString(dbversion); + addDBversion(QString::fromStdString(dbversion)); + + return tablesOK; + +} + +bool GMDBManager::createTables() +{ + qDebug() << "GMDBManager::createTables()"; + + QStringList tab; + QSqlQuery q; + QString geoNode; + QString tableName; + QString queryStr; + + // create a table to store the relation between the types of GeoNodes and the name of the table + tableName = "dbversion"; + tab << tableName << "id" << "version"; + queryStr = QString("create table %1(%2 integer primary key, %3 integer)"); + for (int i=0; i < tab.size(); ++i) { + queryStr = queryStr.arg( tab.at(i) ); + } + //qDebug() << "query:" << queryStr; + if (!q.exec(queryStr)) { + showError(q.lastError()); + return false; + } + storeTableColumnNames(tab); + tab.clear(); + + // create a table to store the relation between the types of GeoNodes and the name of the table + tableName = "GeoNodesTypes"; + tab << tableName << "id" << "nodeType" << "tableName"; + storeTableColumnNames(tab); + tab.clear(); + if (!q.exec(QLatin1String("create table GeoNodesTypes(id integer primary key, nodeType varchar, tableName varchar)"))) { + showError(q.lastError()); + return false; + } + + // ChildrenPositions table + tableName = "ChildrenPositions"; + tab << tableName << "id" << "parentId" << "parentTable" << "parentCopyNumber" << "position" << "childTable" << "childId" << "childCopyNumber"; + queryStr = QString("create table %1(%2 integer primary key, %3 integer, %4 integer not null REFERENCES GeoNodesTypes(id), %5 integer, %6 integer, %7 integer not null REFERENCES GeoNodesTypes(id), %8 integer not null, %9 integer)"); // FIXME: add "NOT NULL" to copy numbers + for (int i=0; i < tab.size(); ++i) { + queryStr = queryStr.arg( tab.at(i) ); + } + // qDebug() << "query:" << queryStr; + if (!q.exec(queryStr)) { + showError(q.lastError()); + return false; + } + storeTableColumnNames(tab); + tab.clear(); + + + // RootVolume table + tableName = "RootVolume"; + tab << tableName << "id" << "volId" << "volTable"; + queryStr = QString("create table %1(%2 integer primary key, %3 integer not null, %4 integer not null REFERENCES GeoNodesTypes(id))"); + for (int i=0; i < tab.size(); ++i) { + queryStr = queryStr.arg( tab.at(i) ); + } + //qDebug() << "query:" << queryStr; + if (!q.exec(queryStr)) { + showError(q.lastError()); + return false; + } + storeTableColumnNames(tab); + tab.clear(); + + + // PhysVols table + geoNode = "GeoPhysVol"; + tableName = "PhysVols"; + tab << tableName << "id" << "logvol" << "parent"; // FIXME: remove "parent" field, it is not used anymore + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table PhysVols(id integer primary key, logvol integer not null, parent integer)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // FullPhysVols table + geoNode = "GeoFullPhysVol"; + tableName = "FullPhysVols"; + tab << tableName << "id" << "logvol" << "parent"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table FullPhysVols(id integer primary key, logvol integer not null, parent integer)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // LogVols table + geoNode = "GeoLogVol"; + tableName = "LogVols"; + tab << tableName << "id" << "name" << "shape" << "material"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table LogVols(id integer primary key, name varchar, shape integer not null, material integer not null)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // Materials table + geoNode = "GeoMaterial"; + tableName = "Materials"; + tab << tableName << "id" << "name"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table Materials(id integer primary key, name varchar)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // Shapes table + geoNode = "GeoShape"; + tableName = "Shapes"; + tab << tableName << "id" << "type" << "parameters"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table Shapes(id integer primary key, type varchar, parameters varchar)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // SerialDenominators table + geoNode = "GeoSerialDenominator"; + tableName = "SerialDenominators"; + tab << tableName << "id" << "baseName"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table SerialDenominators(id integer primary key, baseName varchar)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // Functions table + geoNode = "Function"; + tableName = "Functions"; + tab << tableName << "id" << "expression"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table Functions(id integer primary key, expression varchar)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // SerialDenominators table + geoNode = "GeoSerialTransformer"; + tableName = "SerialTransformers"; + m_childType_tableName[geoNode] = tableName; // store type-table relation + tab << tableName << "id" << "funcId" << "volId" << "volTable" << "copies"; + storeTableColumnNames(tab); + queryStr = QString("create table %1(%2 integer primary key, %3 integer not null REFERENCES Functions(id), %4 integer not null, %5 integer not null REFERENCES GeoNodesTypes(id), %6 integer)"); + for (int i=0; i < tab.size(); ++i) { + queryStr = queryStr.arg( tab.at(i) ); + } + tab.clear(); + // qDebug() << "query:" << queryStr; + if (!q.exec(queryStr)) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + + // Transforms table + geoNode = "GeoTransform"; + tableName = "Transforms"; + tab << tableName << "id" << "xx" << "xy" << "xz" << "yx" << "yy" << "yz" << "zx" << "zy" << "zz" << "dx" << "dy" << "dz"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table Transforms(id integer primary key, xx real, xy real, xz real, yx real, yy real, yz real, zx real, zy real, zz real, dx real, dy real, dz real)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // AlignableTransforms table + geoNode = "GeoAlignableTransform"; + tableName = "AlignableTransforms"; + tab << tableName << "id" << "xx" << "xy" << "xz" << "yx" << "yy" << "yz" << "zx" << "zy" << "zz" << "dx" << "dy" << "dz"; + storeTableColumnNames(tab); + tab.clear(); + m_childType_tableName[geoNode] = tableName; // store type-table relation + if (!q.exec(QLatin1String("create table AlignableTransforms(id integer primary key, xx real, xy real, xz real, yx real, yy real, yz real, zx real, zy real, zz real, dx real, dy real, dz real)"))) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + // NameTags table + geoNode = "GeoNameTag"; + tableName = "NameTags"; + m_childType_tableName[geoNode] = tableName; // store type-table relation + tab << tableName << "id" << "name"; + storeTableColumnNames(tab); + queryStr = QString("create table %1(%2 integer primary key, %3 varchar)"); + for (int i=0; i < tab.size(); ++i) { + queryStr = queryStr.arg( tab.at(i) ); + } + tab.clear(); + // qDebug() << "query:" << queryStr; + if (!q.exec(queryStr)) { + showError(q.lastError()); + return false; + } else { + storeNodeType(geoNode, tableName); + } + + qDebug() << "m_childType_tableName:" << m_childType_tableName; + qDebug() << "DONE. All tables created successfully."; + return true; + +} + +void GMDBManager::loadTableNamesFromDB() +{ + qDebug() << "GMDBManager::loadTableNames()"; + QSqlDatabase db = QSqlDatabase::database(); + QStringList tables = db.tables(); + foreach (QString tab, tables) { + QStringList tabColNames = getTableColNamesFromDB(tab); + storeTableColumnNames(tabColNames); + } + // qDebug() << "m_tableNames:" << m_tableNames; +} + +void GMDBManager::storeTableColumnNames(QStringList input) +{ + // qDebug() << "GMDBManager::storeTableColumnNames()"; + if (! (input.isEmpty()) ) { + QString tabName = input.takeFirst(); + m_tableNames[tabName] = input; + } +} + +QStringList GMDBManager::getTableColumnNames(QString tableName) +{ + // qDebug() << "GMDBManager::getTableColumnNames()"; + return m_tableNames[tableName]; +} + +void GMDBManager::storeNodeType(QString nodeType, QString tableName) +{ + qDebug() << "GMDBManager::storeNodeType()"; + + QSqlQuery q; + if (!q.prepare(QLatin1String("insert into GeoNodesTypes(nodeType, tableName) values(?, ?)"))) { + showError(q.lastError()); + return; + } + + q.addBindValue(nodeType); + q.addBindValue(tableName); + q.exec(); + return; +} + +void GMDBManager::loadTestData() +{ + + qDebug() << "GMDBManager::loadTestData()"; + + // create test data + QSqlQuery q; + // + // qDebug() << "Loading Shapes..."; + // if (!q.prepare(QLatin1String("insert into Shapes(name) values(?)"))) { + // showError(q.lastError()); + // return; + // } + qDebug() << "Loading Shapes..."; + QVariant boxId = addShape(QLatin1String("Box"), ""); + QVariant coneId = addShape(QLatin1String("Cone"), ""); + QVariant sphereId = addShape(QLatin1String("Sphere"), ""); + + qDebug() << "Loading Materials..."; + QVariant airId = addMaterial(QLatin1String("Air")); + QVariant ironId = addMaterial(QLatin1String("Iron")); + QVariant leadId = addMaterial(QLatin1String("Lead")); + + qDebug() << "Loading LogVols..."; + QVariant worldLogId = addLogVol(QLatin1String("WorldLog"), boxId, airId); + QVariant toyLogId = addLogVol(QLatin1String("ToyLog"), coneId, leadId); + + qDebug() << "Loading PhysVols..."; + QVariant rootPhysId = addPhysVol(worldLogId, QVariant()); // no parent + QVariant childPhysId = addPhysVol(toyLogId, rootPhysId); + + qDebug() << "DONE. Created and loaded test data."; +} + + +QStringList GMDBManager::getTableColNamesFromDB(QString tableName) const +{ + QStringList colNames; + colNames << tableName; + + // fetch the driver + QSqlDriver* driver = m_db.driver(); + QSqlRecord record = driver->record(tableName); + int colN = record.count(); + for (int i = 0; i < colN; ++i) + colNames << record.fieldName(i); + return colNames; +} + + + +void GMDBManager::printTableColNamesFromDB(QString tableName) const +{ + qDebug() << "GMDBManager::printTableColNames:" << tableName; + + // fetch the driver + qDebug() << getTableColNamesFromDB(tableName); +} + +bool GMDBManager::storeRootVolume(QVariant id, QString nodeType) +{ + qDebug() << "GMDBManager::storeRootVolume:" << id << nodeType; + + QVariant typeId = getTableIdFromNodeType(nodeType); + + QString tableName = "RootVolume"; + QStringList cols = getTableColumnNames(tableName); + + // prepare the query string + QString queryStr = QString("insert into %1(%2, %3) values(?, ?)").arg(tableName); + for (int i=0; i < cols.size(); ++i) { + if (i != 0) // skip the "id" column + queryStr = queryStr.arg( cols.at(i) ); + } + //qDebug() << "queryStr:" << queryStr; + // prepare the query + QSqlQuery q; + if (!q.prepare(queryStr)) { + showError(q.lastError()); + return false; + } + q.addBindValue(id); + q.addBindValue(typeId); + // run the query + q.exec(); + return true; +} + +QStringList GMDBManager::getRootPhysVol() +{ + qDebug() << "GMDBManager::getRootPhysVol()"; + // get the ID of the ROOT vol from the table "RootVolume" + // QSqlQuery query("SELECT * FROM RootVolume"); + QSqlQuery query = selectAllFromTable("RootVolume"); + + QVariant id; + QVariant typeId; + while (query.next()) { + id = query.value(1); + typeId = query.value(2); + } + return getItemAndType(typeId.toUInt(), id.toUInt()); +} + +QString GMDBManager::getDBFilePath() +{ + return m_dbpath; +} + + +int GMDBManager::getTableColIndex(QString tableName, QString colName) +{ + //qDebug() << "GMDBManager::getTableColIndex()"; + QStringList colFields = m_tableNames[tableName]; + return colFields.lastIndexOf(colName); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5808035a7d768537d753a043be471d17490e043d --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/CMakeLists.txt @@ -0,0 +1,9 @@ +################################################################################ +# Package: GeoModelErrorHandler +################################################################################ + +# Declare the package name: +atlas_subdir( GeoModelErrorHandler ) + +# Install files from the package: +atlas_install_headers( GeoModelErrorHandler ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/GeoModelErrorHandler/ErrorHandler.h b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/GeoModelErrorHandler/ErrorHandler.h new file mode 100644 index 0000000000000000000000000000000000000000..e32da54aee8a4db52e345c491c05b70c142a6270 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler/GeoModelErrorHandler/ErrorHandler.h @@ -0,0 +1,64 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +/* + * ErrorHandler.h + * + * Created on: May 29, 2016 + * Author: rbianchi + * + * Source: + * - http://brianmilco.blogspot.ch/2011/11/color-debug-output-with-qt-and-qdebug.html + */ + +#ifndef ERRORHANDLER_H_ +#define ERRORHANDLER_H_ + +#include <QtGlobal> +#include <QString> + +//void errorHandler(QtMsgType type, const char *msg) +void errorHandler(QtMsgType type, const QMessageLogContext &, const QString & msg) + +{ + + const char* msgChar = msg.toStdString().c_str(); + + switch (type) { + + case QtDebugMsg: + + fprintf(stderr, "%s\n", msgChar); + + break; + + case QtWarningMsg: + + fprintf(stderr, "\033[1;33mWarning\033[0m: %s\n", msgChar); + + break; + + case QtCriticalMsg: + + fprintf(stderr, "\033[31mCritical\033[0m: %s\n", msgChar); + + break; + + case QtFatalMsg: + + fprintf(stderr, "\033[31mFatal\033[0m: %s\n", msgChar); + + abort(); + + case QtInfoMsg: + + break; + + + } + +} + + +#endif /* ERRORHANDLER_H_ */ diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..3f04ba7946a90019842a8aeb65656111c9e2f2de --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/CMakeLists.txt @@ -0,0 +1,38 @@ +################################################################################ +# Package: GeoRead +################################################################################ + +# Declare the package name: +atlas_subdir( GeoRead ) + +# Declare the package's dependencies: +# TODO: we can skip the dependency on GeoPrimitives when we convert all methods to Eigen (GeoTrf::Transform3D) +atlas_depends_on_subdirs( PUBLIC + DetectorDescription/GeoPrimitives + ) + +# External dependencies: +find_package( Qt5 COMPONENTS Core ) # needed for QDebug +find_package( CLHEP ) # to be dropped when migrated all methods to the new Eigen-based GeoTrf +find_package( Eigen ) +find_package( GeoModel ) + + + +if(CMAKE_BUILD_TYPE MATCHES Release) + add_definitions(-DQT_NO_DEBUG_OUTPUT) # comment out if you want to get debug messages in Release +endif(CMAKE_BUILD_TYPE MATCHES Release) +if(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + add_definitions(-DQT_NO_DEBUG_OUTPUT) # comment out if you want to get debug messages in RelWithDebInfo +endif(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + +# Component(s) in the package: +atlas_add_library( GeoRead + src/*.cpp + PUBLIC_HEADERS GeoRead + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} ${GEOMODEL_LIBRARIES} GeoModelDBManager TFPersistification) + #LINK_LIBRARIES ${CLHEP_LIBRARIES} Qt5::Widgets GeoModelKernel GeoModelDBManager TFPersistification VP1Base ) +# TODO: we should get rid of VP1Base::VP1Msg dependency, since GeoRead should not depend on VP1 packages. Maybe we can move VP1Msg to a standalone package. + + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/GeoRead/GReadIn.h b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/GeoRead/GReadIn.h new file mode 100644 index 0000000000000000000000000000000000000000..5ff2e87d8f6c2991f2a25fdb0e633cc12068de40 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/GeoRead/GReadIn.h @@ -0,0 +1,149 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +/* + * GeoModelReadIn.h + * + * Created on: May 20, 2016 + * Author: Riccardo Maria BIANCHI <rbianchi@cern.ch> + */ + +#ifndef GEOMODELREADIN_H_ +#define GEOMODELREADIN_H_ + +#include "GeoModelDBManager/GMDBManager.h" + +#include "GeoModelKernel/GeoXF.h" + + +// C++ includes +#include <string> +#include <set> + + +// FWD declarations +class GeoVPhysVol; +class GeoPhysVol; +class GeoLogVol; +class GeoShape; +class GeoMaterial; +class GeoNameTag; +class GeoSerialDenominator; +class GeoAlignableTransform; +class GeoTransform; +class GeoSerialTransformer; +class GeoGraphNode; +//class GeoXF; +//class GeoXF::Function; + +using namespace GeoGenfun; +using namespace GeoXF; + +typedef const Function & TRANSFUNCTION; + + +namespace GeoModelPers { + +class GReadIn { +public: + + GReadIn(GMDBManager* db, unsigned long* progress = nullptr); + virtual ~GReadIn(); + + // void printRecords(); + GeoPhysVol* buildGeoModel(); + +private: + +// static int dbCallbackPrint(void *NotUsed, int nColRow, char **fieldsRow, char **colNamesRow); +// static int dbCallbackBuild(void *NotUsed, int nColRow, char **fieldsRow, char **colNamesRow); + + GeoPhysVol* buildGeoModelByCalls(); + GeoPhysVol* buildGeoModelOneGo(); + + GeoPhysVol* loopOverAllChildren(); + + GeoPhysVol* getRootVolume(); + + GeoVPhysVol* parseChildren(GeoVPhysVol* vol, QMap<unsigned int, QStringList> children, int depth = 0); + GeoVPhysVol* parseVPhysVol(QStringList values, QString nodeType, int depth = 0); + GeoVPhysVol* buildVPhysVol(QString id, QString tableId, QString copyNumber); + //GeoLogVol* parseLogVol(QStringList values); + GeoLogVol* buildLogVol(QString id); + //GeoShape* parseShape(QStringList values); + GeoShape* buildShape(QString id); + //GeoMaterial* parseMaterial(QStringList values); + GeoMaterial* buildMaterial(QString id); + GeoSerialDenominator* parseSerialDenominator(QStringList values); + GeoSerialDenominator* buildSerialDenominator(QString id); + GeoAlignableTransform* parseAlignableTransform(QStringList values); + GeoAlignableTransform* buildAlignableTransform(QString id); + GeoTransform* parseTransform(QStringList values); + GeoTransform* buildTransform(QString id); + GeoSerialTransformer* parseSerialTransformer(QStringList values); + GeoSerialTransformer* buildSerialTransformer(QString id); + // TRANSFUNCTION parseFunction(QStringList values); + // TRANSFUNCTION parseFunction(const QStringList& values); + // TRANSFUNCTION parseFunction(const int& id, const std::string& expr); + TRANSFUNCTION parseFunction(const std::string& expr); + TRANSFUNCTION buildFunction(QString id); + GeoNameTag* parseNameTag(QStringList values); + GeoNameTag* buildNameTag(QString id); + + + GeoShape* getShape(QString id); + + void volAddHelper(GeoVPhysVol* vol, GeoGraphNode* volChild); + + bool isNodeBuilt(const QString id, const QString tableId, const QString copyNumber); + GeoGraphNode* getNode(const QString id, const QString tableId, const QString copyNumber); + void storeNode(const QString id, const QString tableId, const QString copyNumber, GeoGraphNode* node); + + void checkInputString(QString input); + + + + // input arguments + std::string _dbName; + GeoPhysVol* _root; + GMDBManager* m_dbManager; + unsigned long* m_progress; + bool m_deepDebug; + + + // SQLite variables +// sqlite3* _db; +// char * _zErrMsg; +// int _rc; +// char const * _sql; +// const char* _data; + + // data containers + + QHash<QString, QMap<unsigned int, QStringList>> _allchildren; // key = "parentId:parentTable", item = list of children parameters, inserted by child position + + QHash<unsigned int, QStringList> _physVols; + QHash<unsigned int, QStringList> _fullPhysVols; + QHash<unsigned int, QStringList> _logVols; + QHash<unsigned int, QStringList> _shapes; + QHash<unsigned int, QStringList> _materials; + QHash<unsigned int, QStringList> _transforms; + QHash<unsigned int, QStringList> _alignableTransforms; + QHash<unsigned int, QStringList> _serialDenominators; + QHash<unsigned int, QStringList> _serialTransformers; + QHash<unsigned int, QStringList> _functions; + QHash<unsigned int, QStringList> _nameTags; + + QHash<unsigned int, QString> _tableid_tableName; + + QStringList _root_vol_data; + + QHash<QString, GeoGraphNode*> _memMap; + + std::set<std::string> m_unknown_shapes; + +}; + +} /* namespace GeoModelPers */ +#endif /* GEOMODELREADIN_H_ */ diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/CMakeLists.txt.example b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/CMakeLists.txt.example new file mode 100644 index 0000000000000000000000000000000000000000..ebd59ff7533a8cc43cda245ec15502351f9622e7 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/CMakeLists.txt.example @@ -0,0 +1,34 @@ +cmake_minimum_required(VERSION 3.1.0) + +project(hellogeo) + +# Find includes in corresponding build directories +set(CMAKE_INCLUDE_CURRENT_DIR ON) + +# Instruct CMake to run moc automatically when needed +set(CMAKE_AUTOMOC ON) + + +# Find the Qt5 libraries, used e.g. to interface with the SQlite DB +find_package(Qt5 COMPONENTS Core Sql Widgets REQUIRED) +# Instruct CMake to run Qt5 moc automatically when needed +set(CMAKE_AUTOMOC ON) + +# The project needs VP1Light to build against: +find_package( VP1Light REQUIRED ) + + +# Populate a CMake variable with the sources +set(SRCS + main.cpp +) + +# Tell CMake to create the helloworld executable +add_executable( hellogeo ${SRCS} ) + +# Linknall needed libraries +target_link_libraries( hellogeo Qt5::Core Qt5::Sql VP1Light::GeoModelDBManager VP1Light::GeoRead VP1Light::GeoModelKernel VP1Light::GeoModelUtilities ) + +# Add the BUILDVP1Light definition to switch off the compilation of any part of the code which is Athena-specific +target_compile_definitions( hellogeo PUBLIC BUILDVP1LIGHT ) + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/main.cpp.example b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/main.cpp.example new file mode 100644 index 0000000000000000000000000000000000000000..93b644918c5f68711ce8b18f668183eb955fae8e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/examples/hellogeo/main.cpp.example @@ -0,0 +1,131 @@ + +#include "GeoModelDBManager/GMDBManager.h" +#include "GeoRead/GReadIn.h" + +#include "GeoModelUtilities/GeoModelExperiment.h" +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoPhysVol.h" +#include "GeoModelKernel/GeoFullPhysVol.h" +#include "GeoModelKernel/GeoNameTag.h" + +#include <QCoreApplication> +#include <QString> +#include <QDebug> +#include <QFileInfo> + +#include <iostream> + + + +GeoModelExperiment* createTheExperiment(GeoPhysVol* world) +{ + if (world == nullptr) + { + // Setup the 'World' volume from which everything else will be suspended + double densityOfAir=0.1; + const GeoMaterial* worldMat = new GeoMaterial("std::Air", densityOfAir); + const GeoBox* worldBox = new GeoBox(1000*CLHEP::cm, 1000*CLHEP::cm, 1000*CLHEP::cm); + const GeoLogVol* worldLog = new GeoLogVol("WorldLog", worldBox, worldMat); + // GeoPhysVol* worldPhys = new GeoPhysVol(worldLog); + world = new GeoPhysVol(worldLog); + } + // Setup the 'Experiment' manager + GeoModelExperiment* theExperiment = new GeoModelExperiment(world); + return theExperiment; +} + + + +int main(int argc, char *argv[]) +{ + QCoreApplication app(argc, argv); + + // GET GEOMETRY FROM LOCAL DB + // Set valid db path before first run + static const QString path = "../geometry.db"; + qDebug() << "Using this DB file:" << path; + + // check if DB file exists. If not, return + if (! QFileInfo(path).exists() ) { + qWarning() << "ERROR!! DB '" << path << "' does not exist!!"; + qWarning() << "Returning..." << "\n"; + // return; + throw; + } + + // open the DB + GMDBManager* db = new GMDBManager(path); + /* Open database */ + if (db->isOpen()) { + qDebug() << "OK! Database is open!"; + } + else { + qDebug() << "Database is not open!"; + // return; + throw; + } + + // -- testing the input database + std::cout << "Printing the list of all GeoMaterial nodes" << std::endl; + db->printAllMaterials(); + + /* setup the GeoModel reader */ + GeoModelPers::GReadIn readInGeo = GeoModelPers::GReadIn(db); + qDebug() << "GReadIn set."; + + + /* build the GeoModel geometry */ + GeoPhysVol* dbPhys = readInGeo.buildGeoModel(); // builds the whole GeoModel tree in memory + qDebug() << "GReadIn::buildGeoModel() done."; + + // create the world volume container and its manager + GeoModelExperiment* theExperiment = createTheExperiment(dbPhys); + qDebug() << "ATLAS Geometry is built."; + + + // --- testing the imported ATLAS Geometry + + // get the 'world' volume, i.e. the root volume of the GeoModel tree + std::cout << "Getting the 'world' GeoPhysVol, i.e. the root volume of the GeoModel tree" << std::endl; + GeoPhysVol* world = theExperiment->getPhysVol(); + + // get the 'world' GeoLogVol + std::cout << "Getting the GeoLogVol used by the 'world' volume" << std::endl; + const GeoLogVol* logVol = world->getLogVol(); + std::cout << "'world' GeoLogVol name: " << logVol->getName() << std::endl; + std::cout << "'world' GeoMaterial name: " << logVol->getMaterial()->getName() << std::endl; + + // get number of children volumes + unsigned int nChil = world->getNChildVols(); + std:: cout << "'world' number of children: " << nChil << std::endl; + + // loop over all children nodes + std::cout << "Looping over all 'volume' children (i.e., GeoPhysVol and GeoFullPhysVol)..." << std::endl; + for (unsigned int idx=0; idx<nChil; ++idx) { + PVConstLink nodeLink = world->getChildVol(idx); + + if ( dynamic_cast<const GeoVPhysVol*>( &(*( nodeLink ))) ) { + std::cout << "\t" << "the child n. " << idx << " "; + const GeoVPhysVol *childVolV = &(*( nodeLink )); + if ( dynamic_cast<const GeoPhysVol*>(childVolV) ) { + const GeoPhysVol* childVol = dynamic_cast<const GeoPhysVol*>(childVolV); + std::cout << "is a GeoPhysVol, whose GeoLogVol name is: " << childVol->getLogVol()->getName() << std::endl; + } else if ( dynamic_cast<const GeoFullPhysVol*>(childVolV) ) { + const GeoFullPhysVol* childVol = dynamic_cast<const GeoFullPhysVol*>(childVolV); + std::cout << "is a GeoFullPhysVol, whose GeoLogVol name is: " << childVol->getLogVol()->getName() << std::endl; + } + } else if ( dynamic_cast<const GeoNameTag*>( &(*( nodeLink ))) ) { + qDebug() << "\t" << "the child n. " << idx << " is a GeoNameTag"; + const GeoNameTag *childVol = dynamic_cast<const GeoNameTag*>(&(*( nodeLink ))); + std::cout << "\t\tGeoNameTag's name: " << childVol->getName() << std::endl; + } + } + + qDebug() << "Everything done."; + + return app.exec(); +} + + + + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/src/GReadIn.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/src/GReadIn.cpp new file mode 100644 index 0000000000000000000000000000000000000000..69815340e41d68e39af8d5eff628c7353b2a6d15 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoRead/src/GReadIn.cpp @@ -0,0 +1,1741 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +/* + * GeoModelReadIn.cpp + * + * Created on: May 20, 2016 + * Author: rbianchi + */ + +// local includes +#include "GeoRead/GReadIn.h" + +// SQLite +//#include "sqlite/sqlite3.h" +//#include <sqlite3.h> + +// TFPersistification includes +#include "TFPersistification/TransFunctionInterpreter.h" + +// GeoModelKernel +#include "GeoModelKernel/GeoTransform.h" +#include "GeoModelKernel/GeoAlignableTransform.h" +#include "GeoModelKernel/GeoSerialTransformer.h" +#include "GeoModelKernel/GeoSerialDenominator.h" +#include "GeoModelKernel/GeoMaterial.h" +#include "GeoModelKernel/GeoNameTag.h" +#include "GeoModelKernel/GeoLogVol.h" +#include "GeoModelKernel/GeoPhysVol.h" +#include "GeoModelKernel/GeoFullPhysVol.h" +#include "GeoModelKernel/GeoGraphNode.h" + +// GeoModel shapes +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoCons.h" +#include "GeoModelKernel/GeoPara.h" +#include "GeoModelKernel/GeoPcon.h" +#include "GeoModelKernel/GeoPgon.h" +#include "GeoModelKernel/GeoSimplePolygonBrep.h" +#include "GeoModelKernel/GeoTrap.h" +#include "GeoModelKernel/GeoTrd.h" +#include "GeoModelKernel/GeoTube.h" +#include "GeoModelKernel/GeoTubs.h" +#include "GeoModelKernel/GeoShapeIntersection.h" +#include "GeoModelKernel/GeoShapeShift.h" +#include "GeoModelKernel/GeoShapeSubtraction.h" +#include "GeoModelKernel/GeoShapeUnion.h" + +// Units +#include "GeoModelKernel/Units.h" +#define SYSTEM_OF_UNITS GeoModelKernelUnits // so we will get, e.g., 'GeoModelKernelUnits::cm' + +// TODO: to remove once the migration to Eigen is complete +#include "CLHEP/Vector/Rotation.h" +#include "CLHEP/Geometry/Transform3D.h" +#include "GeoPrimitives/CLHEPtoEigenConverter.h" // TODO: to be removed when dropping CLHEP + +//VP1Base +// TODO: we should get rid of VP1Base::VP1Msg dependency, since GeoRead should not depend on VP1 packages. Maybe we can move VP1Msg to a standalone package. +//#include "VP1Base/VP1Msg.h" + +// Qt includes +#include <QDebug> + + +using namespace GeoGenfun; +using namespace GeoXF; + + +namespace GeoModelPers { + +GReadIn::GReadIn(GMDBManager* db, unsigned long* progress) : m_progress(nullptr), m_deepDebug(false) +{ + qDebug() << "DumpGeoModelAction: constructor"; + + #ifdef GEOREAD_DEEP_DEBUG + m_deepDebug = true; + #endif + + if ( progress != nullptr) { + m_progress = progress; + } + + // set the geometry file + m_dbManager = db; + if (m_dbManager->isOpen()) { + qDebug() << "OK! Database is open!"; + } + else { + qWarning() << "ERROR!! Database is NOT open!"; + return; + } +} + +GReadIn::~GReadIn() { + // TODO Auto-generated destructor stub +} + + +///* +// * Arguments: +// * +// * unused - Ignored in this case, see the documentation for sqlite3_exec +// * count - The number of columns in the result set +// * data - The row's data +// * columns - The column names +// */ +//int GReadIn::dbCallbackBuild(void* unused, int nColRow, char **fieldsRow, char **colNamesRow){ +// +// GReadIn* instance = (GReadIn*) unused; +// +// for(int i=0; i<nColRow; i++){ +// +// std::string colName = colNamesRow[i]; +// std::string fieldRow = fieldsRow[i]; +// +// printf("Building %s = %s\n", colNamesRow[i], fieldsRow[i] ? fieldsRow[i] : "NULL"); +// +// if ( colName == "SHAPE" ) { +// +// if (fieldRow == "Box") +// instance->buildShape(); +// } +// +// } +// printf("\n"); +// return 0; +//} + +// void GReadIn::buildShape() +// { +// // const GeoBox *box = new GeoBox(1200*CLHEP::cm,1200*CLHEP::cm, 1200*CLHEP::cm); +// } + + + + +// void GReadIn::printRecords() +// { +// // FETCH RECORDS AND PRINT THEM +// +// } + + + +GeoPhysVol* GReadIn::buildGeoModel() +{ + qDebug() << "GReadIn::buildGeoModel()"; + + // return buildGeoModelByCalls(); + + GeoPhysVol* rootVolume = buildGeoModelOneGo(); + + if (m_unknown_shapes.size() > 0) { + qWarning() << "WARNING!! There were unknwon shapes:"; + for ( auto it = m_unknown_shapes.begin(); it != m_unknown_shapes.end(); it++ ) { + std::cout << "---> " << *it << std::endl; + } + std::cout << "Remember: unknown shapes are rendered with a dummy cube of 30cm side length." << std::endl; + } + + return rootVolume; +} + +/* +GeoPhysVol* GReadIn::buildGeoModelByCalls() +{ + QStringList rootValues = m_dbManager->getRootPhysVol(); + // qDebug() << "rootValues:" << rootValues; + + QString nodeType = rootValues.takeFirst(); // it takes out the first element + + // get GeoModel node. Depth == -1 means "get all children volumes / all levels" + // _root = dynamic_cast<GeoPhysVol*>(parseVPhysVol(rootValues, nodeType, -1)); + _root = dynamic_cast<GeoPhysVol*>(parseVPhysVol(rootValues, nodeType)); + + // TODO: check if shared nodes are restored only one and then used when needed, + // or they are restored with a new node in memory every time they are met + + return _root; +} +*/ + +GeoPhysVol* GReadIn::buildGeoModelOneGo() +{ + qDebug() << "GReadIn::buildGeoModelOneGo()"; + + // get all objects from the DB + _physVols = m_dbManager->getTableFromNodeType("GeoPhysVol"); + std::cout << "GeoPhysVol, read in." << std::endl; + _fullPhysVols = m_dbManager->getTableFromNodeType("GeoFullPhysVol"); + std::cout << "GeoFullPhysVol, read in." << std::endl; + _logVols = m_dbManager->getTableFromNodeType("GeoLogVol"); + std::cout << "GeoLogVol, read in." << std::endl; + _shapes = m_dbManager->getTableFromNodeType("GeoShape"); + std::cout << "GeoShape, read in." << std::endl; + _materials = m_dbManager->getTableFromNodeType("GeoMaterial"); + std::cout << "GeoMaterial, read in." << std::endl; + _functions = m_dbManager->getTableFromNodeType("Function"); + std::cout << "Function, read in." << std::endl; + _serialDenominators = m_dbManager->getTableFromNodeType("GeoSerialDenominator"); + std::cout << "GeoSerialDenominator, read in." << std::endl; + _serialTransformers = m_dbManager->getTableFromNodeType("GeoSerialTransformer"); + std::cout << "GeoSerialTransformer, read in." << std::endl; + _alignableTransforms = m_dbManager->getTableFromNodeType("GeoAlignableTransform"); + std::cout << "GeoAlignableTransform, read in." << std::endl; + _transforms = m_dbManager->getTableFromNodeType("GeoTransform"); + std::cout << "GeoTransform, read in." << std::endl; + _nameTags = m_dbManager->getTableFromNodeType("GeoNameTag"); + std::cout << "GeoNameTag, read in." << std::endl; + // qDebug() << "physVols: " << _physVols; + // qDebug() << "fullPhysVols: " << _fullPhysVols; + + // get DB metadata + _tableid_tableName = m_dbManager->getAll_TableIDsNodeTypes(); + std::cout << "DB metadata, read in." << std::endl; + + // get the children table from DB + _allchildren = m_dbManager->getChildrenTable(); + // qDebug() << "all children from DB:" << _allchildren; + std::cout << "children positions, read in." << std::endl; + + // get the root volume data + _root_vol_data = m_dbManager->getRootPhysVol(); + std::cout << "root volume data, read in." << std::endl; + + return loopOverAllChildren(); +} + + +// //---------------------------------------- +// GeoPhysVol* GReadIn::loopOverAllChildren() +// { +// QMessageBox msgBox; +// msgBox.setText("The document has been modified."); +// msgBox.exec(); +// } + +//---------------------------------------- +GeoPhysVol* GReadIn::loopOverAllChildren() +{ + + std::cout << "Looping over all children to build the GeoModel tree..." << std::endl; + + int nChildrenRecords = _allchildren.size(); + + // This should go in VP1Light, not in this library. The library could be used by standalone apps without a GUI + /* + QProgressDialog progress("Loading the geometry...", "Abort Loading", 0, nChildrenRecords, 0); + progress.setWindowModality(Qt::WindowModal); + progress.show(); + */ + + // loop over parents' keys + int counter = 0; + foreach (const QString &parentKey, _allchildren.keys() ) { + + /* //This should go in VP1Light as well! + if (progress.wasCanceled()) { + std::cout << "You aborted the loading of the geometry." << std::endl; + + QMessageBox msgBox; + msgBox.setText("You aborted the loading of the geometry."); + msgBox.setInformativeText("Do you want to really abort it?"); + msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No); + msgBox.setDefaultButton(QMessageBox::No); + int ret = msgBox.exec(); + + switch (ret) { + case QMessageBox::Yes: + // Abort the loading of the geometry + break; + case QMessageBox::No: + // Continue with the loading of the geometry + progress.reset(); + default: + // should never be reached + break; + } + } + */ + + + + ++counter; + std::cout.precision(0); + if ( nChildrenRecords < 10000 && counter % 500 == 0 ) { + float done = ( (float)counter / nChildrenRecords) * 100; + std::cout << "\t" << std::fixed << counter << "children records processed [" << done << "%]" << std::endl; + if ( m_progress != nullptr ) { + //progress.setValue(counter); // This hould go in VP1Light + *m_progress = counter; + } + } + else if ( nChildrenRecords > 10000 && counter % 2000 == 0 ) { + float done = ( (float)counter / nChildrenRecords) * 100; + std::cout << "\t" << std::fixed << counter << " children records processed [" << done << "%]" << std::endl; + if ( m_progress != nullptr ) { + //progress.setValue(counter); // This should go in VP1Light + *m_progress = counter; + } + } + if (m_deepDebug) qDebug() << "\nparent: " << parentKey << ':' << _allchildren.value(parentKey) << "[parentId, parentType, parentCopyNumber, childPos, childType, childId, childCopyN]"; + + // get the parent's details + QStringList parentKeyItems = parentKey.split(":"); + QString parentId = parentKeyItems[0]; + QString parentTableId = parentKeyItems[1]; + QString parentCopyN = parentKeyItems[2]; + if (m_deepDebug) qDebug() << "parent ID:" << parentId << ", parent table ID:" << parentTableId << ", parent copy number:" << parentCopyN; + + bool isRootVolume = false; + if (parentId == "NULL") { + isRootVolume = true; + } + + GeoVPhysVol* parentVol = nullptr; + + // build or get parent volume. + // Using the parentCopyNumber here, to get a given instance of the parent volume + if (!isRootVolume) { + if (m_deepDebug) qDebug() << "get the parent volume..."; + parentVol = buildVPhysVol( parentId, parentTableId, parentCopyN); + } + + + // get the parent's children + QMap<unsigned int, QStringList> children = _allchildren.value(parentKey); + + + + // loop over children, sorted by child position automatically + // "id", "parentId", "parentTable", "parentCopyNumber", "position", "childTable", "childId", "childCopyNumber" + if (m_deepDebug) qDebug() << "parent volume has " << children.size() << "children. Looping over them..."; + foreach(QStringList child, children) { + + if (m_deepDebug) qDebug() << "child:" << child; + + // build or get child node + QString childTableId = child[5]; + QString childId = child[6]; + QString childCopyN = child[7]; + + QString childNodeType = _tableid_tableName[childTableId.toUInt()]; + + if (m_deepDebug) qDebug() << "childTableId:" << childTableId << ", type:" << childNodeType << ", childId:" << childId; + + if (childNodeType.isEmpty()) { + qWarning("ERROR!!! childNodeType is empty!!! Aborting..."); + exit(1); + } + + if (childNodeType == "GeoPhysVol") { + if (m_deepDebug) qDebug() << "GeoPhysVol child..."; + GeoVPhysVol* childNode = dynamic_cast<GeoPhysVol*>(buildVPhysVol(childId, childTableId, childCopyN)); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoFullPhysVol") { + if (m_deepDebug) qDebug() << "GeoFullPhysVol child..."; + GeoVPhysVol* childNode = dynamic_cast<GeoFullPhysVol*>(buildVPhysVol(childId, childTableId, childCopyN)); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoSerialDenominator") { + if (m_deepDebug) qDebug() << "GeoSerialDenominator child..."; + GeoSerialDenominator* childNode = buildSerialDenominator(childId); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoAlignableTransform") { + if (m_deepDebug) qDebug() << "GeoAlignableTransform child..."; + GeoAlignableTransform* childNode = buildAlignableTransform(childId); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoTransform") { + if (m_deepDebug) qDebug() << "GeoTransform child..."; + GeoTransform* childNode = buildTransform(childId); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoSerialTransformer") { + if (m_deepDebug) qDebug() << "GeoSerialTransformer child..."; + GeoSerialTransformer* childNode = buildSerialTransformer(childId); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else if (childNodeType == "GeoNameTag") { + if (m_deepDebug) qDebug() << "GeoNameTag child..."; + GeoNameTag* childNode = buildNameTag(childId); + if (!isRootVolume) volAddHelper(parentVol, childNode); + } + else { + QString msg = "[" + childNodeType + "]" + QString(" ==> ERROR!!! - The conversion for this type of child node needs to be implemented, still!!!"); + qFatal("%s", msg.toLatin1().constData()); + } + + } // loop over all children + } // loop over childrenPositions records + + // return the root volume + return getRootVolume(); +} + + +// GReadIn::buildNode( QStringList volParams, QString nodeType ) +// { +// if( nodeType == "GeoPhysVol") { +// +// } else { +// qWarning() << "WARNING!! Node type Unknown!!"; +// } +// } + + + + + +// GeoPhysVol* GReadIn::getGeoModelHandle() +// { +// QStringList rootValues = m_dbManager->getRootPhysVol(); +// // qDebug() << "rootValues:" << rootValues; +// +// QString nodeType = rootValues.takeFirst(); // it takes out the first element +// +// // get GeoModel node. Depth == 1 means "get only first level children" +// _root = dynamic_cast<GeoPhysVol*>(parseVPhysVol(rootValues, nodeType, 1)); +// +// // TODO: check if shared nodes are restored only one and then used when needed, +// // or they are restored with a new node in memory every time they are met +// +// return _root; +// } + +/* +GeoVPhysVol* GReadIn::parseChildren(GeoVPhysVol* vol, QMap<unsigned int, QStringList> children, int depth) +{ + qDebug() << "GReadIn::parseChildren()"; + + //qDebug() << "children:" << children; + + // get parent volume type + QString volType; + if (dynamic_cast<GeoPhysVol*>(vol)) + volType = "GeoPhysVol"; + else if (dynamic_cast<GeoFullPhysVol*>(vol)) + volType = "GeoFullPhysVol"; + else + qWarning() << "ERROR!! Unknown vol type!!"; + + QMap<unsigned int, QStringList>::const_iterator it; // we don't modify the map, so we use a const_iterator, which is is slightly faster as well. + + for ( it = children.begin(); it != children.end(); ++it) { + qDebug() << "\nchild item:" << it.key() << ":" << it.value(); + + // QString id = it.value()[0]; + // QString parentId = it.value()[1]; + // QString parentTableId = it.value()[2]; + // QString childPosition = it.value()[3]; + unsigned int childTableId = it.value()[4].toUInt(); + unsigned int childId = it.value()[5].toUInt(); + + // QString parentTable = m_dbManager->getTableNameFromTableId(parentTableId.toUInt()); + + QStringList child = m_dbManager->getItemAndType(childTableId, childId ); + qDebug() << "child:" << child; + + QString nodeType = child.takeFirst(); // it pops out the first element, leaving the other items in the list + + if (depth > 0) { + depth = depth - 1; // decrease the depth by one + } + + if (nodeType == "GeoPhysVol") { + // if ( childId != parentId.toUInt() ) { + if (child.length() > 0) { + // build the node + GeoPhysVol* volChild = dynamic_cast<GeoPhysVol*>(parseVPhysVol(child, nodeType, depth)); + // add the node to the parent + volAddHelper(vol, volChild); + } else { + qWarning() << "WARNING!!!" << "The PhysVol" << childId << "is empty/not-existing!!! To be investigated why...! Skipping now..."; + } + // } else { + // qWarning() << "WARNING!!" << "childId and parentId are the same! That means an infinite loop!! To be investigated! Skipping now..."; + // } + } + else if (nodeType == "GeoFullPhysVol") { + if (child.length() > 0) { + GeoFullPhysVol* volChild = dynamic_cast<GeoFullPhysVol*>(parseVPhysVol(child, nodeType, depth)); + volAddHelper(vol, volChild); + } else { + qWarning() << "WARNING!!!" << "The PhysVol" << childId << "is empty/not-existing!!! To be investigated why...! Skipping now..."; + } + } + else if (nodeType == "GeoSerialDenominator") { + GeoSerialDenominator* volChild = parseSerialDenominator(child); + volAddHelper(vol, volChild); + // vol->add(volChild); + } + else if (nodeType == "GeoAlignableTransform") { + GeoAlignableTransform* volChild = parseAlignableTransform(child); + volAddHelper(vol, volChild); + // vol->add(volChild); + } + else if (nodeType == "GeoTransform") { + GeoTransform* volChild = parseTransform(child); + volAddHelper(vol, volChild); + // vol->add(volChild); + } + else if (nodeType == "GeoSerialTransformer") { + GeoSerialTransformer* volChild = parseSerialTransformer(child); + volAddHelper(vol, volChild); + // vol->add(volChild); + } + else if (nodeType == "GeoNodeTag") { // TODO: implement it!! + QString msg = nodeType + QString(" GeoNodeTag needs to be implemented!!!"); + qWarning() << msg; + } + else { + QString msg = nodeType + QString(" child-->GeoModel conversion for this type still needs to be implemented!!!"); + qWarning() << msg; + } + + } + // this below is to suppress the compiler warning, + // but it should not be reached, so we use a qFatal + qFatal("This code should not be reached!!! Aborting..."); + GeoVPhysVol* volnull = nullptr; + return volnull; +} +*/ + +void GReadIn::volAddHelper(GeoVPhysVol* vol, GeoGraphNode* volChild) +{ + if (dynamic_cast<GeoPhysVol*>(vol)) { + GeoPhysVol* volume = dynamic_cast<GeoPhysVol*>(vol); + volume->add(volChild); + } else if (dynamic_cast<GeoFullPhysVol*>(vol)) { + GeoFullPhysVol* volume = dynamic_cast<GeoFullPhysVol*>(vol); + volume->add(volChild); + } +} + +/* +// Instantiate a PhysVol and get its children +GeoVPhysVol* GReadIn::parseVPhysVol(QStringList values, QString nodeType, int depth) +{ + qDebug() << "GReadIn::parseVPhysVol()"; + + QString volId = values[0]; + QString logVolId = values[1]; + QString parentId = values[2]; + + qDebug() << "\tPhysVol-ID:" << volId; + qDebug() << "\tPhysVol-LogVol:" << logVolId; + qDebug() << "\tPhysVol-parentId:" << parentId; + qDebug() << "\tnodeType:" << nodeType; + + + // GET LOGVOL + // get logVol properties from the DB + QStringList paramsLog = m_dbManager->getItem("GeoLogVol", logVolId.toUInt()); + qDebug() << "params:" << paramsLog; + + // build the LogVol + GeoLogVol* logVol = parseLogVol(paramsLog); + + // a pointer to the VPhysVol + GeoVPhysVol* vol = nullptr; + + // BUILD THE PHYSVOL OR THE FULLPHYSVOL + if (nodeType == "GeoPhysVol") + vol = new GeoPhysVol(logVol); + else if (nodeType == "GeoFullPhysVol") + vol = new GeoFullPhysVol(logVol); + else + qWarning() << "ERROR!!! Unkonwn node type!! : " << nodeType; + + + // if we want to get the volume's children + if (depth != 0) { + + // * check if the volume has children + // get the IDs of all children of this PhysVol volume + QMap<unsigned int, QStringList> children = m_dbManager->getVPhysVolChildren( volId.toUInt(), nodeType ); + qDebug() << "children of the " << nodeType << "node with Id:" << volId << " --> " << children; + // if this PhysVol has children, build them and add them to it + if (children.size() > 0) + parseChildren(vol, children, depth); + else + qDebug() << "VPhysVol has no children"; + } + + return vol; +} +*/ + + +void GReadIn::checkInputString(QString input) +{ + if (input.isEmpty() || input.isNull() || input == "NULL") { + qWarning() << "ERROR!!! Input QString is empty or equal to 'NULL'!!! Aborting..."; + exit(1); + } +} + +// Instantiate a PhysVol and get its children +GeoVPhysVol* GReadIn::buildVPhysVol(QString id, QString tableId, QString copyN) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildVPhysVol()" << id << tableId << copyN; + + checkInputString(id); + checkInputString(tableId); + + // if previously built, return that + if (isNodeBuilt(id, tableId, copyN)) { + if (m_deepDebug) qDebug() << "getting the volume from memory..."; + return dynamic_cast<GeoVPhysVol*>(getNode(id, tableId, copyN)); + } + + if (m_deepDebug) qDebug() << "building a new volume..."; + + // QString nodeType = m_dbManager->getNodeTypeFromTableId(tableId.toUInt()); + QString nodeType = _tableid_tableName[tableId.toUInt()]; + + // get the parent volume parameters + // here we do not need to use copyN, since the actual volume is the same for all instances + QStringList values; + if (nodeType == "GeoPhysVol") + values = _physVols[id.toUInt()]; + else if (nodeType == "GeoFullPhysVol") + values = _fullPhysVols[id.toUInt()]; + + + + QString volId = values[0]; + QString logVolId = values[1]; + //QString parentId = values[2]; // FIXME: delete it, it is not used any more + + if (m_deepDebug) { + qDebug() << "\tPhysVol-ID:" << volId; + qDebug() << "\tPhysVol-LogVol:" << logVolId; + //qDebug() << "\tPhysVol-parentId:" << parentId; + qDebug() << "\tnodeType:" << nodeType; + } + + // GET LOGVOL + GeoLogVol* logVol = buildLogVol(logVolId); + + // a pointer to the VPhysVol + GeoVPhysVol* vol = nullptr; + + // BUILD THE PHYSVOL OR THE FULLPHYSVOL + if (nodeType == "GeoPhysVol") + vol = new GeoPhysVol(logVol); + else if (nodeType == "GeoFullPhysVol") + vol = new GeoFullPhysVol(logVol); + else + qWarning() << "ERROR!!! Unkonwn node type!! : " << nodeType; + + // storing the address of the newly built node + storeNode(id, tableId, copyN, vol); + + return vol; +} + + +// Get the root volume +GeoPhysVol* GReadIn::getRootVolume() +{ + if (m_deepDebug) qDebug() << "GReadIn::getRootVolume()"; + QString id = _root_vol_data[1]; + QString tableId = _root_vol_data[2]; + QString copyNumber = "1"; // the Root volume has only one copy by definition + return dynamic_cast<GeoPhysVol*>(buildVPhysVol(id, tableId, copyNumber)); +} + + + +/* +GeoMaterial* GReadIn::parseMaterial(QStringList values) +{ + qDebug() << "GReadIn::parseMaterial()"; + + QString matId = values[0]; + QString matName = values[1]; + + qDebug() << "\tMaterial-ID:" << matId << ", Material-name:" << matName; + + // TODO: Bogus densities. Later: read from database. + double densityOfAir=0.1; + + return new GeoMaterial(matName.toStdString(),densityOfAir); + +} +*/ + + +GeoMaterial* GReadIn::buildMaterial(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildMaterial()"; + QStringList values = _materials[id.toUInt()]; + + QString matId = values[0]; + QString matName = values[1]; + + if (m_deepDebug) qDebug() << "\tMaterial-ID:" << matId << ", Material-name:" << matName; + + // TODO: Bogus densities. Later: read from database. + double densityOfAir=0.1; + + return new GeoMaterial(matName.toStdString(),densityOfAir); + +} + + +/* +GeoShape* GReadIn::parseShape(QStringList values) +{ + qDebug() << "GReadIn::parseShape()"; + + QString id = values[0]; + QString type = values[1]; + QString parameters = values[2]; + + qDebug() << "\tShape-ID:" << id << ", Shape-type:" << type; + + if (type == "Box") { + + // needed parameters + double XHalfLength; + double YHalfLength; + double ZHalfLength; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + + if (varName == "XHalfLength") XHalfLength = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + if (varName == "YHalfLength") YHalfLength = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + } + + // return new GeoBox(5.0*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm); + return new GeoBox(XHalfLength, YHalfLength, ZHalfLength); + } + else if (type == "Tube") { + + // needed parameters + double RMin; + double RMax; + double ZHalfLength; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + + if (varName == "RMin") RMin = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + if (varName == "RMax") RMax = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble() * SYSTEM_OF_UNITS::mm; + } + + // return new GeoBox(5.0*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm); + return new GeoTube(RMin, RMax, ZHalfLength); + + } + else if (type == "Shift") { + + // needed parameters + unsigned int shapeId; + unsigned int transfId; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + + if (varName == "A") shapeId = varValue.toUInt(); + if (varName == "X") transfId = varValue.toUInt(); + } + + // get the referenced shape + const GeoShape* shapeA = getShape( QString::number(shapeId) ); + + // get the referenced HepGeom::Transform3D + QStringList transPars = m_dbManager->getItemFromTableName("Transforms", transfId); + qDebug() << "child:" << transPars; + GeoTransform* transf = parseTransform(transPars); + const HepGeom::Transform3D transfX = transf->getTransform(); + + // build and return the GeoShapeShift instance + return new GeoShapeShift(shapeA, transfX); + } + else if (type == "Pcon") { + + // needed parameters + unsigned int SPhi; + unsigned int DPhi; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + + if (varName == "SPhi") SPhi = varValue.toUInt(); + if (varName == "DPhi") DPhi = varValue.toUInt(); + } + + // return new shape + return new GeoPcon(SPhi, DPhi); + } + else { + QString msg = "WARNING!! - Shape '" + type + "' not implemented yet!!! Returning a dummy cube."; + qWarning() << msg; + return new GeoBox(30.0*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm); // FIXME: bogus shape. Use actual shape! + } + +} +*/ + +GeoShape* GReadIn::buildShape(QString shapeId) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildShape()"; + QStringList paramsShape = _shapes[ shapeId.toUInt() ]; + + QString id = paramsShape[0]; + QString type = paramsShape[1]; + QString parameters = paramsShape[2]; + + if (m_deepDebug) qDebug() << "\tShape-ID:" << id << ", Shape-type:" << type; + + if (type == "Box") { + // shape parameters + double XHalfLength = 0.; + double YHalfLength = 0.; + double ZHalfLength = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "XHalfLength") XHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "YHalfLength") YHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoBox(XHalfLength, YHalfLength, ZHalfLength); + } + else if (type == "Cons") { + // shape parameters + double RMin1 = 0.; + double RMin2 = 0.; + double RMax1 = 0.; + double RMax2 = 0.; + double DZ = 0.; + double SPhi = 0.; + double DPhi = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "RMin1") RMin1 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "RMin2") RMin2 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "RMax1") RMax1 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "RMax2") RMax2 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "DZ") DZ = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "SPhi") SPhi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "SPDPhihi") DPhi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoCons (RMin1, RMin2, RMax1, RMax2, DZ, SPhi, DPhi); + } + else if (type == "Para") { + // shape parameters + double XHalfLength = 0.; + double YHalfLength = 0.; + double ZHalfLength = 0.; + double Alpha = 0.; + double Theta = 0.; + double Phi = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "XHalfLength") XHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "YHalfLength") YHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Alpha") Alpha = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Theta") Theta = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Phi") Phi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoPara (XHalfLength, YHalfLength, ZHalfLength, Alpha, Theta, Phi); + } + else if (type == "Pcon") { + // shape parameters + double SPhi = 0.; + double DPhi = 0.; + unsigned int NZPlanes = 0; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + + bool error = 0; + QString par; + QStringList vars; + QString varName; + QString varValue; + + GeoPcon* pcon = nullptr; + + int sizePars = shapePars.size(); + // check if we have more than 3 parameters + if (sizePars > 3) { + + // get the three first GeoPcon parameters: the SPhi and DPhi angles, plus the number of Z planes + for( int it=0; it < 3; it++) { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "SPhi") SPhi = varValue.toDouble(); + if (varName == "DPhi") DPhi = varValue.toDouble(); + if (varName == "NZPlanes") NZPlanes = varValue.toDouble(); + } + // build the basic GeoPcon shape + pcon = new GeoPcon(SPhi, DPhi); + + // and now loop over the rest of the list, to get the parameters of all Z planes + for (int it=3; it < sizePars; it++) + { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + // qInfo() << "it:" << it << "par:" << par << "varName:" << varName << "varValue:" << varValue; + + if (varName == "ZPos") { + + double zpos = varValue.toDouble(); + double rmin=0., rmax=0.; + + it++; // go to next variable + + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "ZRmin") rmin = varValue.toDouble(); + else error = 1; + it++; // go to next variable + + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "ZRmax") rmax = varValue.toDouble(); + else error = 1; + + if(error) qWarning() << "ERROR! GeoPcon 'ZRmin' and 'ZRmax' values are not at the right place! --> " << shapePars; + + // add a Z plane to the GeoPcon + pcon->addPlane(zpos, rmin, rmax); + } else { + error = 1; + qWarning() << "ERROR! GeoPcon 'ZPos' value is not at the right place! --> " << shapePars; + } + } + + // sanity check on the resulting Pcon shape + if( pcon->getNPlanes() != NZPlanes) { + error = 1; + qWarning() << "ERROR! GeoPcon number of planes: " << QString::number(pcon->getNPlanes()) << " is not equal to the original size! --> " << shapePars; + } + if(!pcon->isValid()) { + error = 1; + qWarning() << "ERROR! GeoPcon shape is not valid!! -- input: " << shapePars; + } + } // end if (size>3) + else { + qWarning() << "ERROR!! GeoPcon has no Z planes!! --> shape input parameters: " << shapePars; + error = 1; + } + + if(error) qFatal("GeoPcon shape error!!! Aborting..."); + + return pcon; + } + else if (type == "Pgon") { + // shape parameters + double SPhi = 0.; + double DPhi = 0.; + unsigned int NSides = 0; + unsigned int NZPlanes = 0; + + bool error = false; + GeoPgon* pgon = nullptr; + QString par; + QStringList vars; + QString varName; + QString varValue; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + // qInfo() << "shapePars: " << shapePars; // debug + + int sizePars = shapePars.size(); + // check if we have more than 3 parameters + if (sizePars > 3) { + + // get the first four GeoPgon parameters: the SPhi and DPhi angles, plus the number of Z planes + for( int it=0; it < 4; it++) { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + // qInfo() << "vars: " << vars; // for debug only + if (varName == "SPhi") SPhi = varValue.toDouble(); + if (varName == "DPhi") DPhi = varValue.toDouble(); + if (varName == "NSides") NSides = varValue.toUInt();// * SYSTEM_OF_UNITS::mm; + if (varName == "NZPlanes") NZPlanes = varValue.toDouble(); + + } + // build the basic GeoPgon shape + pgon = new GeoPgon(SPhi, DPhi, NSides); + + // and now loop over the rest of the list, to get the parameters of all Z planes + for (int it=4; it < sizePars; it++) + { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + // qInfo() << "it:" << it << "par:" << par << "varName:" << varName << "varValue:" << varValue; + + if (varName == "ZPos") { + + double zpos = varValue.toDouble(); + double rmin=0., rmax=0.; + + it++; // go to next variable + + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "ZRmin") rmin = varValue.toDouble(); + else error = 1; + it++; // go to next variable + + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "ZRmax") rmax = varValue.toDouble(); + else error = 1; + + if(error) qWarning() << "ERROR! GeoPgon 'ZRmin' and 'ZRmax' values are not at the right place! --> " << shapePars; + + // add a Z plane to the GeoPgon + pgon->addPlane(zpos, rmin, rmax); + } else { + error = 1; + qWarning() << "ERROR! GeoPgon 'ZPos' value is not at the right place! --> " << shapePars; + } + } + + // sanity check on the resulting Pgon shape + if( pgon->getNPlanes() != NZPlanes) { + error = 1; + qWarning() << "ERROR! GeoPgon number of planes: " << QString::number(pgon->getNPlanes()) << " is not equal to the original size! --> " << shapePars; + } + if(!pgon->isValid()) { + error = 1; + qWarning() << "ERROR! GeoPgon shape is not valid!! -- input: " << shapePars; + } + } // end if (size>3) + else { + qWarning() << "ERROR!! GeoPgon has no Z planes!! --> shape input parameters: " << shapePars; + error = 1; + } + if(error) qFatal("GeoPgon shape error!!! Aborting..."); + return pgon; + } + else if (type == "SimplePolygonBrep") + { + //qInfo() << "Reading-in: SimplePolygonBrep: "; // debug + // shape parameters + double DZ = 0.; + unsigned int NVertices = 0; + double xV = 0.; + double yV = 0.; + + bool error = 0; + GeoSimplePolygonBrep* sh = nullptr; + QString par; + QStringList vars; + QString varName; + QString varValue; + + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + //qInfo() << "shapePars: " << shapePars; // debug + + int sizePars = shapePars.size(); + // check if we have more than 2 parameters + if (sizePars > 2) { + + // get the first two GeoSimplePolygonBrep parameters: DZ and the number of vertices. + for( int it=0; it < 2; it++) { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + // qInfo() << "vars: " << vars; // for debug only + if (varName == "DZ") DZ = varValue.toDouble(); + if (varName == "NVertices") NVertices = varValue.toDouble(); + //else if (varName == "NVertices") NVertices = varValue.toDouble(); + //else error = 1; + //if(error) qWarning() << "ERROR! GeoSimplePolygonBrep parameters are not correctly stored! -->" << vars; + + } + // build the basic GeoSimplePolygonBrep shape + sh = new GeoSimplePolygonBrep(DZ); + + // and now loop over the rest of the list, to get the parameters of all vertices + for (int it=2; it < sizePars; it++) + { + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "xV") xV = varValue.toDouble(); + else error = 1; + + it++; // go to next variable (they come in pairs) + + par = shapePars[it]; + vars = par.split("="); + varName = vars[0]; + varValue = vars[1]; + if (varName == "yV") yV = varValue.toDouble(); + else error = 1; + + if(error) qWarning() << "ERROR! GeoSimplePolygonBrep 'xVertex' and 'yVertex' values are not at the right place! --> " << shapePars; + + // add a Z plane to the GeoSimplePolygonBrep + sh->addVertex(xV, yV); + } + // sanity check on the resulting shape + if( sh->getNVertices() != NVertices) { + error = 1; + qWarning() << "ERROR! GeoSimplePolygonBrep number of planes: " << QString::number(sh->getNVertices()) << " is not equal to the original size! --> " << shapePars; + } + if(!sh->isValid()) { + error = 1; + qWarning() << "ERROR! GeoSimplePolygonBrep shape is not valid!! -- input: " << shapePars; + } + } // end if (size>3) + else { + qWarning() << "ERROR!! GeoSimplePolygonBrep has no vertices!! --> shape input parameters: " << shapePars; + error = 1; + } + if(error) qFatal("GeoSimplePolygonBrep shape error!!! Aborting..."); + return sh; + + } + else if (type == "Trap") { + // shape constructor parameters + double ZHalfLength = 0.; + double Theta = 0.; + double Phi = 0.; + double Dydzn = 0.; + double Dxdyndzn = 0.; + double Dxdypdzn = 0.; + double Angleydzn = 0.; + double Dydzp = 0.; + double Dxdyndzp = 0.; + double Dxdypdzp = 0.; + double Angleydzp = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Theta") Theta = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Phi") Phi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dydzn") Dydzn = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dxdyndzn") Dxdyndzn = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dxdypdzn") Dxdypdzn = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Angleydzn") Angleydzn = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dydzp") Dydzp = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dxdyndzp") Dxdyndzp = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Dxdypdzp") Dxdypdzp = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "Angleydzp") Angleydzp = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoTrap (ZHalfLength, Theta, Phi, Dydzn, Dxdyndzn, Dxdypdzn, Angleydzn, Dydzp, Dxdyndzp, Dxdypdzp, Angleydzp); + } + else if (type == "Trd") { + // shape constructor parameters + double XHalfLength1 = 0.; + double XHalfLength2 = 0.; + double YHalfLength1 = 0.; + double YHalfLength2 = 0.; + double ZHalfLength = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "XHalfLength1") XHalfLength1 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "XHalfLength2") XHalfLength2 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "YHalfLength1") YHalfLength1 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "YHalfLength2") YHalfLength2 = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoTrd (XHalfLength1, XHalfLength2, YHalfLength1, YHalfLength2, ZHalfLength); + } + else if (type == "Tube") { + // shape parameters + double RMin = 0.; + double RMax = 0.; + double ZHalfLength = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "RMin") RMin = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "RMax") RMax = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoTube(RMin, RMax, ZHalfLength); + } + else if (type == "Tubs") { + // shape parameters + double RMin = 0.; + double RMax = 0.; + double ZHalfLength = 0.; + double SPhi = 0.; + double DPhi = 0.; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "RMin") RMin = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "RMax") RMax = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "ZHalfLength") ZHalfLength = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "SPhi") SPhi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + if (varName == "DPhi") DPhi = varValue.toDouble();// * SYSTEM_OF_UNITS::mm; + } + return new GeoTubs (RMin, RMax, ZHalfLength, SPhi, DPhi); + } + else if (type == "Intersection") { + // shape parameters + unsigned int opA = 0; + unsigned int opB = 0; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "opA") opA = varValue.toUInt(); + if (varName == "opB") opB = varValue.toUInt(); + } + // get the referenced shape + const GeoShape* shapeA = buildShape( QString::number(opA) ); + const GeoShape* shapeB = buildShape( QString::number(opB) ); + // build and return the GeoShapeShift instance + return new GeoShapeIntersection(shapeA, shapeB); + } + else if (type == "Shift") { + // shape parameters + unsigned int shapeId = 0; + unsigned int transfId = 0; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "A") shapeId = varValue.toUInt(); + if (varName == "X") transfId = varValue.toUInt(); + } + // get the referenced shape + // const GeoShape* shapeA = getShape( QString::number(shapeId) ); + const GeoShape* shapeA = buildShape( QString::number(shapeId) ); + // get the referenced HepGeom::Transform3D + QStringList transPars = m_dbManager->getItemFromTableName("Transforms", transfId); + if (m_deepDebug) qDebug() << "child:" << transPars; + GeoTransform* transf = parseTransform(transPars); + const GeoTrf::Transform3D transfX = transf->getTransform(); + // build and return the GeoShapeShift instance + return new GeoShapeShift(shapeA, transfX); + } + else if (type == "Subtraction") { + // shape parameters + unsigned int opA = 0; + unsigned int opB = 0; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "opA") opA = varValue.toUInt(); + if (varName == "opB") opB = varValue.toUInt(); + } + // get the referenced shape + + //if (VP1Msg::debug()) + //VP1Msg::messageDebug("GeoSubstraction - building shape A...\n"); + + const GeoShape* shapeA = buildShape( QString::number(opA) ); + + /* + if (VP1Msg::debug()) { + QString msg = QString::fromStdString(shapeA->type()); + VP1Msg::messageDebug("GeoSubstraction - built shape A: "+msg); + VP1Msg::messageDebug("GeoSubstraction - building shape B...\n"); + } + */ + + const GeoShape* shapeB = buildShape( QString::number(opB) ); + + /* + if (VP1Msg::debug()) { + QString msg = QString::fromStdString(shapeB->type()); + VP1Msg::messageDebug("GeoSubstraction - built shape B: "+msg+"\n"); + } + */ + + // build and return the GeoShapeShift instance + return new GeoShapeSubtraction(shapeA, shapeB); + } + else if (type == "Union") { + // shape parameters + unsigned int opA = 0; + unsigned int opB = 0; + // get parameters from DB string + QStringList shapePars = parameters.split(";"); + foreach( QString par, shapePars) { + QStringList vars = par.split("="); + QString varName = vars[0]; + QString varValue = vars[1]; + if (varName == "opA") opA = varValue.toUInt(); + if (varName == "opB") opB = varValue.toUInt(); + } + if (opA == 0 || opB == 0) std::cout << "ERROR! 'GeoUnion' shape: opA or opB have not been properly intialized!" << std::endl; + // get the referenced shape + const GeoShape* shapeA = buildShape( QString::number(opA) ); + const GeoShape* shapeB = buildShape( QString::number(opB) ); + // build and return the GeoShapeShift instance + return new GeoShapeUnion(shapeA, shapeB); + } + else { + // QString msg = "WARNING!! - Shape '" + type + "' not implemented yet!!! Returning a dummy cube."; + // qWarning(msg.toStdString().c_str()); + m_unknown_shapes.insert(type.toStdString()); // save unknwon shapes for later warning message + return new GeoBox(30.0*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm, 30*SYSTEM_OF_UNITS::cm); // FIXME: bogus shape. Use actual shape! + } + +} + + + +/* +GeoLogVol* GReadIn::parseLogVol(QStringList values) +{ + qDebug() << "GReadIn::parseLogVol()"; + + QString logVolName = values[1]; + + // GET LOGVOL SHAPE + QString shapeId = values[2]; + + // qDebug() << "shape Id:" << shapeId; + // QStringList paramsShape = m_dbManager->getItem("GeoShape", shapeId.toUInt()); + // qDebug() << "shape parameters from DB: " << paramsShape; + // GeoShape* shape = parseShape(paramsShape); + + GeoShape* shape = getShape(shapeId); + + // GET LOGVOL MATERIAL + QString matId = values[3]; + QStringList paramsMat = _materials[ matId.toUInt() ]; + GeoMaterial* mat = parseMaterial(paramsMat); + + // instantiate teh GeoLogVol + return new GeoLogVol(logVolName.toStdString(), shape, mat); + +} +*/ + + +GeoLogVol* GReadIn::buildLogVol(QString logVolId) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildLogVol()"; + + // get logVol properties from the DB + QStringList values = _logVols[logVolId.toUInt()]; + if (m_deepDebug) qDebug() << "params:" << values; + + // build the LogVol + QString logVolName = values[1]; + + // GET LOGVOL SHAPE + QString shapeId = values[2]; + GeoShape* shape = buildShape(shapeId); + + // GET LOGVOL MATERIAL + QString matId = values[3]; + if (m_deepDebug) qDebug() << "material Id:" << matId; + GeoMaterial* mat = buildMaterial(matId); + + return new GeoLogVol(logVolName.toStdString(), shape, mat); + +} + +/* +GeoShape* GReadIn::getShape(QString shapeId){ + qDebug() << "shape Id:" << shapeId; + QStringList paramsShape = m_dbManager->getItem("GeoShape", shapeId.toUInt()); + qDebug() << "shape parameters from DB: " << paramsShape; + GeoShape* shape = parseShape(paramsShape); + return shape; +} +*/ + + +GeoSerialDenominator* GReadIn::buildSerialDenominator(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildSerialDenominator()"; + return parseSerialDenominator( _serialDenominators[id.toUInt()] ); +} + +GeoSerialDenominator* GReadIn::parseSerialDenominator(QStringList values) +{ + if (m_deepDebug) qDebug() << "GReadIn::parseSerialDenominator()"; + QString id = values[0]; + QString baseName = values[1]; + if (m_deepDebug) qDebug() << "\tID:" << id << ", base-name:" << baseName; + return new GeoSerialDenominator(baseName.toStdString()); +} + +GeoAlignableTransform* GReadIn::buildAlignableTransform(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildAlignableTransform()"; + return parseAlignableTransform( _alignableTransforms[id.toUInt()] ); +} + +GeoAlignableTransform* GReadIn::parseAlignableTransform(QStringList values) +{ + if (m_deepDebug) qDebug() << "GReadIn::parseAlignableTransform()"; + + QString id = values.takeFirst(); // it pops out the first element, leaving the other items in the list + + // get the 12 matrix elements + double xx = values[0].toDouble(); + double xy = values[1].toDouble(); + double xz = values[2].toDouble(); + + double yx = values[3].toDouble(); + double yy = values[4].toDouble(); + double yz = values[5].toDouble(); + + double zx = values[6].toDouble(); + double zy = values[7].toDouble(); + double zz = values[8].toDouble(); + + double dx = values[9].toDouble(); + double dy = values[10].toDouble(); + double dz = values[11].toDouble(); + + // TODO: move to GeoModelKernel::GeoTrf (Eigen) + // build a rotation matrix with the first 9 elements + CLHEP::HepRotation R; + R.set(CLHEP::Hep3Vector(xx,yx,zx), + CLHEP::Hep3Vector(xy,yy,zy), + CLHEP::Hep3Vector(xz,yz,zz)); + // build a translation vector with the last 3 elements + CLHEP::Hep3Vector D(dx,dy,dz); + // build the Transformation + const HepGeom::Transform3D xf(R, D); + + return new GeoAlignableTransform( Amg::CLHEPTransformToEigen(xf) ); +} + +GeoTransform* GReadIn::buildTransform(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildTransform()"; + return parseTransform( _transforms[id.toUInt()] ); +} + +GeoTransform* GReadIn::parseTransform(QStringList values) +{ + if (m_deepDebug) qDebug() << "GReadIn::parseTransform()"; + if (m_deepDebug) qDebug() << "values:" << values; + + QString id = values.takeFirst(); // it pops out the first element, leaving the other items in the list + + // get the 12 matrix elements + double xx = values[0].toDouble(); + double xy = values[1].toDouble(); + double xz = values[2].toDouble(); + + double yx = values[3].toDouble(); + double yy = values[4].toDouble(); + double yz = values[5].toDouble(); + + double zx = values[6].toDouble(); + double zy = values[7].toDouble(); + double zz = values[8].toDouble(); + + double dx = values[9].toDouble(); + double dy = values[10].toDouble(); + double dz = values[11].toDouble(); + + // build a rotation matrix with the first 9 elements + // TODO: move to GeoModelKernel GeoTrf (Eigen) + CLHEP::HepRotation R; + R.set(CLHEP::Hep3Vector(xx,yx,zx), + CLHEP::Hep3Vector(xy,yy,zy), + CLHEP::Hep3Vector(xz,yz,zz)); + // build a translation vector with the last 3 elements + CLHEP::Hep3Vector D(dx,dy,dz); + // build the Transformation + const HepGeom::Transform3D xf(R, D); + + return new GeoTransform( Amg::CLHEPTransformToEigen(xf) ); +} + +/* +GeoSerialTransformer* GReadIn::parseSerialTransformer(QStringList values) +{ + qDebug() << "GReadIn::parseSerialTransformer()"; + qDebug() << "values:" << values; + + QString id = values[0]; + QString functionId = values[1]; + QString physVolId = values[2]; + QString physVolTableIdStr = values[3]; + QString copies = values[4]; + + unsigned int physVolTableId = physVolTableIdStr.toUInt(); + + // QString physVolType = m_dbManager->getNodeTypeFromTableId(physVolTableId); + QString physVolType = _tableid_tableName[physVolTableId]; + + qDebug() << "\tID:" << id << ", functionId:" << functionId << ", physVolId:" << physVolId << ", physVolTableId:" << physVolTableId << ", copies:" << copies; + + // GET FUNCTION + qDebug() << "function Id:" << functionId; + QStringList paramsFunc = m_dbManager->getItem("Function", functionId.toUInt()); + // TRANSFUNCTION func = parseFunction(paramsFunc); + TRANSFUNCTION func = parseFunction(paramsFunc[1].toStdString()); + + // GET PHYSVOL + qDebug() << "referenced physVol - Id:" << physVolId << ", type:" << physVolType; + QStringList paramsPhysVol = m_dbManager->getItem(physVolTableId, physVolId.toUInt()); + const GeoVPhysVol* physVol = parseVPhysVol(paramsPhysVol, physVolType); + //qDebug() << "physVol:" << physVol << ", function:" << &func; + + // get PhysVol or FullPhysVol pointer and return the SerialTransformer + if (dynamic_cast<const GeoFullPhysVol*>(physVol)) { + const GeoFullPhysVol* vol = dynamic_cast<const GeoFullPhysVol*>(physVol); + return new GeoSerialTransformer(vol, &func, copies.toUInt() ); + } + const GeoPhysVol* vol = dynamic_cast<const GeoPhysVol*>(physVol); + return new GeoSerialTransformer(vol, &func, copies.toUInt() ); + +} +*/ + +GeoSerialTransformer* GReadIn::buildSerialTransformer(QString nodeId) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildSerialTransformer()"; + + QStringList values = _serialTransformers[nodeId.toUInt()]; + if (m_deepDebug) qDebug() << "values:" << values; + + // std::cout <<"ST * " << values[0].toStdString() << " " << values[1].toStdString() << " " << values[2].toStdString() << std::endl; + if (m_deepDebug) qDebug() << "ST * " << values[0] << ", " << values[1] << ", " << values[2] << ", " << values[3] << ", " << values[4]; + + QString id = values[0]; + QString functionId = values[1]; + QString physVolId = values[2]; + QString physVolTableIdStr = values[3]; + QString copies = values[4]; + + unsigned int physVolTableId = physVolTableIdStr.toUInt(); + + QString physVolType = _tableid_tableName[physVolTableId]; + + if (m_deepDebug) qDebug() << "\tID:" << id << ", functionId:" << functionId << ", physVolId:" << physVolId << ", physVolTableId:" << physVolTableId << ", copies:" << copies; + + // GET FUNCTION + if (m_deepDebug) qDebug() << "function Id:" << functionId; + TRANSFUNCTION func = buildFunction(functionId); + + // GET PHYSVOL + if (m_deepDebug) qDebug() << "referenced physVol - Id:" << physVolId << ", type:" << physVolType << "tableId:" << physVolTableIdStr; + const GeoVPhysVol* physVol = buildVPhysVol(physVolId, physVolTableIdStr, "1"); // we use "1" as default copyNumber: taking the first copy of the VPhysVol as the referenced volume + //qDebug() << "physVol:" << physVol << ", function:" << &func; + + // get PhysVol or FullPhysVol pointer and return the SerialTransformer + if (dynamic_cast<const GeoFullPhysVol*>(physVol)) { + const GeoFullPhysVol* vol = dynamic_cast<const GeoFullPhysVol*>(physVol); + return new GeoSerialTransformer(vol, &func, copies.toUInt() ); + } + const GeoPhysVol* vol = dynamic_cast<const GeoPhysVol*>(physVol); + return new GeoSerialTransformer(vol, &func, copies.toUInt() ); + +} + +TRANSFUNCTION GReadIn::buildFunction(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildFunction()"; + + // return parseFunction( _functions[id.toUInt()] ); + + // return parseFunction( _functions[id.toUInt()] ); + + QStringList values = _functions[id.toUInt()]; + // return parseFunction( values[0].toUInt(), values[1].toStdString() ); + return parseFunction( values[1].toStdString() ); + + +} + +// TRANSFUNCTION GReadIn::parseFunction(QStringList values) +// { +// qDebug() << "GReadIn::parseFunction()"; +// qDebug() << "values:" << values; +// QString id = values[0]; +// QString expression = values[1]; +// if (expression.size() == 0) { +// qFatal("FATAL ERROR!! Function expression is empty!! Aborting..."); +// abort(); +// } +// TransFunctionInterpreter interpreter; +// qDebug() << "expression:" << expression; +// TFPTR func=interpreter.interpret( expression.toStdString() ); +// qDebug() << "expression interpreted"; +// return *(func.release()); // make func returns a pointer to the managed object and releases the ownership, then get the object dereferencing the pointer +// } + + +// TRANSFUNCTION GReadIn::parseFunction(const QStringList& values) +// { +// qDebug() << "GReadIn::parseFunction(const QStringList& values)"; +// qDebug() << "values:" << values; +// int id = values[0].toUInt(); +// std::string expression = values[1].toStdString(); +// if (expression.size() == 0) { +// qFatal("FATAL ERROR!! Function expression is empty!! Aborting..."); +// abort(); +// } +// TransFunctionInterpreter interpreter; +// qDebug() << "expression:" << expression; +// TFPTR func=interpreter.interpret( expression ); +// qDebug() << "expression interpreted"; +// return *(func.release()); // make func returns a pointer to the managed object and releases the ownership, then get the object dereferencing the pointer +// } + + +// TRANSFUNCTION GReadIn::parseFunction(const int& id, const std::string& expr) +TRANSFUNCTION GReadIn::parseFunction(const std::string& expr) +{ + if (m_deepDebug) qDebug() << "GReadIn::parseFunction(const std::string& expr)"; + // qDebug() << "id:" << Qstring::number(id) << " - expression: " << QString::fromStdString(expr); + if (m_deepDebug) qDebug() << "expression: " << QString::fromStdString(expr); + + if (expr.empty()) { + qFatal("FATAL ERROR!! Function expression is empty!! Aborting..."); + abort(); + } + + TransFunctionInterpreter interpreter; + if (m_deepDebug) qDebug() << "expression:" << QString::fromStdString(expr); + TFPTR func=interpreter.interpret( expr ); + if (m_deepDebug) qDebug() << "expression interpreted"; + return *(func.release()); // make func returns a pointer to the managed object and releases the ownership, then get the object dereferencing the pointer +} + +GeoNameTag* GReadIn::buildNameTag(QString id) +{ + if (m_deepDebug) qDebug() << "GReadIn::buildNameTag()"; + return parseNameTag( _nameTags[id.toUInt()] ); +} + +GeoNameTag* GReadIn::parseNameTag(QStringList values) +{ + if (m_deepDebug) qDebug() << "GReadIn::parseNameTag()"; + QString id = values[0]; + QString name = values[1]; + if (m_deepDebug) qDebug() << "nameTag:" << name; + return new GeoNameTag(name.toStdString()); +} + + +bool GReadIn::isNodeBuilt(const QString id, const QString tableId, const QString copyNumber) +{ + // qDebug() << "GReadIn::isNodeBuilt(): " << id << tableId << copyNumber; + QString key = id + ":" + tableId + ":" + copyNumber; + return _memMap.contains(key); +} + + +GeoGraphNode* GReadIn::getNode(const QString id, const QString tableId, const QString copyN) +{ + if (m_deepDebug) qDebug() << "GReadIn::getNode(): " << id << tableId << copyN; + QString key = id + ":" + tableId + ":" + copyN; + return _memMap[key]; +} + +void GReadIn::storeNode(const QString id, const QString tableId, const QString copyN, GeoGraphNode* node) +{ + if (m_deepDebug) qDebug() << "GReadIn::storeNode(): " << id << tableId << copyN << node; + QString key = id + ":" + tableId + ":" + copyN; + _memMap[key] = node; +} + + +} /* namespace GeoModelPers */ diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd9950be5d8383428069334f5cc8bc0a4383d052 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/CMakeLists.txt @@ -0,0 +1,33 @@ +################################################################################ +# Package: GeoWrite +################################################################################ + +# Declare the package name: +atlas_subdir( GeoWrite ) + +# Declare the package's dependencies: +# TODO: we can skip the dependency on GeoPrimitives when we convert all methods to Eigen (GeoTrf::Transform3D) +atlas_depends_on_subdirs( PUBLIC + DetectorDescription/GeoPrimitives + ) + +# External dependencies: +find_package( Qt5 COMPONENTS Core ) # needed for Qt containers +find_package( CLHEP ) # to be dropped when migrated to new Eigen-based GeoTrf +find_package( Eigen ) +find_package( GeoModel ) + + +if(CMAKE_BUILD_TYPE MATCHES Release) + add_definitions(-DQT_NO_DEBUG_OUTPUT) # comment if you need debug messages in Release +endif(CMAKE_BUILD_TYPE MATCHES Release) +if(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + add_definitions(-DQT_NO_DEBUG_OUTPUT) # comment if you need debug messages in RelWithDebInfo +endif(CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + +# Component(s) in the package: +atlas_add_library( GeoWrite + src/*.cpp + PUBLIC_HEADERS GeoWrite + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} Qt5::Core ${GEOMODEL_LIBRARIES} GeoModelDBManager TFPersistification VP1Base ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelAction.h.oldVersion b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelAction.h.oldVersion new file mode 100644 index 0000000000000000000000000000000000000000..a0f2b3da9d24953efd6ce866af15c10b74616c3a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelAction.h.oldVersion @@ -0,0 +1,137 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef DumpGeoModelAction_H +#define DumpGeoModelAction_H + +// local includes + + +#include "GeoModelDBManager/GMDBManager.h" + +// GeoModel includes +#include "GeoModelKernel/GeoNodeAction.h" +#include "GeoModelKernel/GeoGraphNode.h" +#include "GeoModelKernel/GeoShape.h" +#include "GeoModelKernel/GeoMaterial.h" +#include "GeoModelKernel/GeoLogVol.h" +#include "GeoModelKernel/GeoXF.h" +#include "GeoModelKernel/GeoAlignableTransform.h" + +// Qt includes +//#include <QSqlDatabase> +#include <QStringList> +#include <QVariant> +#include <QString> +#include <QMap> + +/** + * \class DumpGeoModelAction + * + * DumpGeoModelAction acts on objects of the GeoModel tree + * persitifying them offline. + */ +class DumpGeoModelAction : public GeoNodeAction +{ +public: + /** + * @brief Constructor + * + * Constructor sets up connection with db and opens it + * @param path - absolute path to db file + */ + DumpGeoModelAction(GMDBManager& db); + + /** + * @brief Destructor + */ + ~DumpGeoModelAction(); + + virtual void handlePhysVol (const GeoPhysVol *vol); // Handles a physical volume. + virtual void handleFullPhysVol (const GeoFullPhysVol *vol); + virtual void handleSerialDenominator (const GeoSerialDenominator *sD); // Handles a Serial Denominator. + virtual void handleSerialTransformer (const GeoSerialTransformer *obj); + virtual void handleTransform (const GeoTransform *); + virtual void handleNameTag (const GeoNameTag *); + + + +private: + + // define copy constructor, needed for the GeoModelAction subclass + DumpGeoModelAction(const DumpGeoModelAction &right); + + // define assignment operator, needed for the GeoModelAction subclass + DumpGeoModelAction & operator=(const DumpGeoModelAction &right); + + void handleVPhysVolObjects(const GeoVPhysVol* vol); + void handleReferencedPhysVol (const GeoVPhysVol *vol); // Handles a physical volume referenced by a SerialTrasformer + + void showMemoryMap(); + + // bool isObjectStored(const GeoLogVol* pointer); + // bool isObjectStored(const GeoMaterial* pointer); + // bool isObjectStored(const GeoGraphNode* pointer); + // bool isObjectStored(const GeoShape* pointer); + + QVariant storeShape(const GeoShape* shape); + QVariant storeTranform(const GeoTransform* node); + + QVariant storeObj(const GeoMaterial* pointer, const QString name); + QVariant storeObj(const GeoShape* pointer, const QString type, const QString parameters); + QVariant storeObj(const GeoLogVol* pointer, const QString name, const QVariant shapeId, const QVariant materialId); + QVariant storeObj(const GeoPhysVol* pointer, const QVariant logvolId, const QVariant parentId = QVariant(), bool isRootVolume = false ); + QVariant storeObj(const GeoFullPhysVol* pointer, const QVariant logvolId, const QVariant parentId = QVariant(), bool isRootVolume = false ); + QVariant storeObj(const GeoSerialDenominator* pointer, const QString baseName); + QVariant storeObj(const GeoSerialTransformer* pointer, const QVariant functionId, const QVariant volId, const QString volType, const unsigned int copies); + QVariant storeObj(const GeoXF::Function* pointer, const QString expression); + QVariant storeObj(const GeoTransform* pointer, const std::vector<double> parameters); + QVariant storeObj(const GeoAlignableTransform* pointer, const std::vector<double> parameters); + QVariant storeObj(const GeoNameTag* pointer, const QString name); + + int getChildPosition(unsigned int parentId); + void storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childVol, const unsigned int childPos, const QString childType); + + // int storeObj(const GeoGraphNode* pointer, const QVariant logvolId, const QVariant parentId = QVariant() ); + + bool isAddressStored(const QString address); + void storeAddress(const QString address, QVariant id); + + QVariant getStoredIdFromAddress(QString address); + + // QVariant getStoredIdFromPointer(const GeoMaterial* pointer); + QString getAddressStringFromPointer(const GeoMaterial* pointer); + QString getAddressStringFromPointer(const GeoShape* pointer); + QString getAddressStringFromPointer(const GeoLogVol* pointer); + QString getAddressStringFromPointer(const GeoPhysVol* pointer); + QString getAddressStringFromPointer(const GeoVPhysVol* pointer); + QString getAddressStringFromPointer(const GeoSerialDenominator* pointer); + QString getAddressStringFromPointer(const GeoSerialTransformer* pointer); + QString getAddressStringFromPointer(const GeoXF::Function* pointer); + QString getAddressStringFromPointer(const GeoTransform* pointer); + QString getAddressStringFromPointer(const GeoNameTag* pointer); + + QString getQStringFromOss(std::ostringstream &oss); + + std::vector<double> getTransformParameters(HepGeom::Transform3D); // TODO: to be moved to an Utility class, so we can use it from TransFunctionRecorder as well. + QString getShapeParameters(const GeoShape*); + + QString getGeoTypeFromVPhysVol(const GeoVPhysVol* vol); + + + GMDBManager* m_dbManager; + + QMap<QString, QVariant> m_memMap; // TODO: maybe move to QHash?? + QMap<QString, QString> m_memMap_Tables; // TODO: maybe move to QHash?? + QMap<unsigned int, unsigned int> m_parentChildrenMap; + + // keep track of the number of visited tree nodes + unsigned int m_len; + unsigned int m_len_nChild; + + bool m_rootVolumeFound; + +}; + +#endif // DumpGeoModelAction_H diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelActionLocal.h b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelActionLocal.h new file mode 100644 index 0000000000000000000000000000000000000000..e44b3aab716570bcf3b454ee441a744ed018ff0b --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/DumpGeoModelActionLocal.h @@ -0,0 +1,187 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// author: Riccardo.Maria.Bianchi@cern.ch +// major updates: Aug 2018 + +#ifndef DumpGeoModelActionLocalLocal_H +#define DumpGeoModelActionLocalLocal_H + +// local includes +#include "GeoModelDBManager/GMDBManager.h" + +// GeoModel includes +#include "GeoModelKernel/GeoNodeAction.h" +#include "GeoModelKernel/GeoGraphNode.h" +#include "GeoModelKernel/GeoShape.h" +#include "GeoModelKernel/GeoMaterial.h" +#include "GeoModelKernel/GeoLogVol.h" +#include "GeoModelKernel/GeoXF.h" +#include "GeoModelKernel/GeoAlignableTransform.h" + +// Qt includes +//#include <QSqlDatabase> +#include <QStringList> +#include <QVariant> +#include <QString> +#include <QMap> + +// TODO: to remove once the migration to Eigen is complete +// fwd declaration +namespace HepGeom { + class Transform3D; +} + + +/** + * \class DumpGeoModelActionLocal + * + * DumpGeoModelActionLocal acts on objects of the GeoModel tree + * persitifying them offline. + */ +class DumpGeoModelActionLocal : public GeoNodeAction +{ +public: + /** + * @brief Constructor + * + * Constructor sets up connection with db and opens it + * @param path - absolute path to db file + */ + DumpGeoModelActionLocal(GMDBManager& db); + + /** + * @brief Destructor + */ + ~DumpGeoModelActionLocal(); + + virtual void handlePhysVol (const GeoPhysVol *vol); // Handles a physical volume. + virtual void handleFullPhysVol (const GeoFullPhysVol *vol); + virtual void handleSerialDenominator (const GeoSerialDenominator *sD); // Handles a Serial Denominator. + virtual void handleSerialTransformer (const GeoSerialTransformer *obj); + virtual void handleTransform (const GeoTransform *); + virtual void handleNameTag (const GeoNameTag *); + + void saveToDB(); + + +private: + + // define copy constructor, needed for the GeoModelAction subclass + DumpGeoModelActionLocal(const DumpGeoModelActionLocal &right); + + // define assignment operator, needed for the GeoModelAction subclass + DumpGeoModelActionLocal & operator=(const DumpGeoModelActionLocal &right); + + void handleVPhysVolObjects(const GeoVPhysVol* vol); + void handleReferencedVPhysVol (const GeoVPhysVol *vol); // Handles a physical volume referenced by a SerialTrasformer + + void showMemoryMap(); + + QStringList getParentNode(); + + QVariant storeShape(const GeoShape* shape); + QVariant storeMaterial(const GeoMaterial* mat); + QVariant storeTranform(const GeoTransform* node); + + QVariant storeObj(const GeoMaterial* pointer, const QString nam); + QVariant storeObj(const GeoShape* pointer, const QString type, const QString parameters); + QVariant storeObj(const GeoLogVol* pointer, const QString name, const QVariant shapeId, const QVariant materialId); + QVariant storeObj(const GeoPhysVol* pointer, const QVariant logvolId, const QVariant parentId = QVariant(), bool isRootVolume = false ); + QVariant storeObj(const GeoFullPhysVol* pointer, const QVariant logvolId, const QVariant parentId = QVariant(), bool isRootVolume = false ); + QVariant storeObj(const GeoSerialDenominator* pointer, const QString baseName); + QVariant storeObj(const GeoSerialTransformer* pointer, const QVariant functionId, const QVariant volId, const QString volType, const unsigned int copies); + QVariant storeObj(const GeoXF::Function* pointer, const QString expression); + QVariant storeObj(const GeoTransform* pointer, const std::vector<double> parameters); + QVariant storeObj(const GeoAlignableTransform* pointer, const std::vector<double> parameters); + QVariant storeObj(const GeoNameTag* pointer, const QString name); + + unsigned int addRecord(std::vector<QStringList>* container, const QStringList values) const; + QVariant addMaterial(const QString name); + QVariant addNameTag(const QString name); + QVariant addAlignableTransform(const std::vector<double> params); + QVariant addTransform(const std::vector<double> params); + QVariant addFunction(const QString expression); + QVariant addSerialTransformer(const QVariant &funcId, const QVariant &physvolId, const QString volType, const unsigned int &copies); + QVariant addShape(const QString &type, const QString ¶meters); + QVariant addSerialDenominator(const QString &baseName); + QVariant addPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume = false); + QVariant addFullPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume = false); + QVariant addLogVol(const QString &name, const QVariant &shapeId, const QVariant &materialId); +// void addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int childPos, const QString childType); // OLD! + void addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int parentCopyNumber, const unsigned int childPos, const QString childType, const unsigned int childCopyN); + + + //int getChildPosition(unsigned int parentId); +// unsigned int getChildPosition(QString parentId, QString parentTableID); + unsigned int getChildPosition(QString parentId, QString parentType, unsigned int copyN); + + unsigned int setVolumeCopyNumber(QString volId, QString volType); + unsigned int getLatestParentCopyNumber(QString parentId, QString parentType); + + // int getNewIdByNodeType(QString nodeType); + +// void storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childVol, const unsigned int childPos, const QString childType); + void storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childVol, const unsigned int parentCopyNumber, const unsigned int childPos, const QString childType, const unsigned int childCopyN); + + bool isAddressStored(const QString address); + void storeAddress(const QString address, QVariant id); + + QVariant getStoredIdFromAddress(QString address); + + // QVariant getStoredIdFromPointer(const GeoMaterial* pointer); + QString getAddressStringFromPointer(const GeoMaterial* pointer); + QString getAddressStringFromPointer(const GeoShape* pointer); + QString getAddressStringFromPointer(const GeoLogVol* pointer); + QString getAddressStringFromPointer(const GeoPhysVol* pointer); + QString getAddressStringFromPointer(const GeoVPhysVol* pointer); + QString getAddressStringFromPointer(const GeoSerialDenominator* pointer); + QString getAddressStringFromPointer(const GeoSerialTransformer* pointer); + QString getAddressStringFromPointer(const GeoXF::Function* pointer); + QString getAddressStringFromPointer(const GeoTransform* pointer); + QString getAddressStringFromPointer(const GeoNameTag* pointer); + + QString getQStringFromOss(std::ostringstream &oss); + + std::vector<double> getTransformParameters(HepGeom::Transform3D); // TODO: to be moved to Eigen (GeoTrf) and to be moved to an Utility class, so we can use it from TransFunctionRecorder as well. + QString getShapeParameters(const GeoShape*); + + QString getGeoTypeFromVPhysVol(const GeoVPhysVol* vol); + + QString getIdFromNodeType(QString nodeType); + + QString m_dbpath; + GMDBManager* m_dbManager; + + QMap<QString, QVariant> m_memMap; // TODO: maybe move to QHash?? + QHash<QString, unsigned int> m_memMap_Tables; + QMap<QString, unsigned int> m_parentChildrenMap2; // TODO: clean name! + QMap<QString, unsigned int> m_volumeCopiesMap; + // QMap<QString, unsigned int> m_idsMap; + + // keep track of the number of visited tree nodes + unsigned int m_len; + unsigned int m_len_nChild; + + bool m_rootVolumeFound; + bool m_unconnectedTree; + + std::vector<QStringList> _logVols; + std::vector<QStringList> _physVols; + std::vector<QStringList> _fullPhysVols; + std::vector<QStringList> _shapes; + std::vector<QStringList> _materials; + std::vector<QStringList> _transforms; + std::vector<QStringList> _alignableTransforms; + std::vector<QStringList> _serialDenominators; + std::vector<QStringList> _serialTransformers; + std::vector<QStringList> _functions; + std::vector<QStringList> _nameTags; + + std::vector<QStringList> _childrenPositions; + QStringList _rootVolume; + +}; + +#endif // DumpGeoModelActionLocal_H diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/WriteGeoModelAction.h.oldSqlite b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/WriteGeoModelAction.h.oldSqlite new file mode 100644 index 0000000000000000000000000000000000000000..081c1c107564bc24e74e0afbb2b80510c3ee1e9e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/GeoWrite/WriteGeoModelAction.h.oldSqlite @@ -0,0 +1,210 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + +// +// GeoModel Action class to +// write a GeoModel tree to a database +// +// Riccardo Maria BIANCHI +// University of Pittsburgh +// <rbianchi-AT-cern.ch> +// +// May 2016 +// + +#ifndef WriteGeoModelAction_h +#define WriteGeoModelAction_h 1 + +// C++ +#include <unordered_map> // C++11 +#include <iostream> + +// GeoNodeAction +#include "GeoModelKernel/GeoGraphNode.h" +#include "GeoModelKernel/GeoNodeAction.h" +#include "GeoModelKernel/GeoTraversalState.h" + +// Qt includes +#include <QtSql> + + +//typedef std::unordered_map<int,int> MemMap; +typedef std::unordered_map<std::string,int> MemMap; + + +// FWD declarations +//class QSqlError; +//class QSqlDatabase; +//class QString; +//class QVariant; +//class QSqlQuery; + +// This action prints the node tree. It can be configured +// to print a message on the following types of nodes: +// +// * Transforms +// * Physical Volumes and Full Physical Volumes. +// * Transforms +// * SerialDenominators +// * SerialTransforms +// * IdentifierTag +// +// These must be switched on (using setNotificationState()) + +// SQLite +//#include "sqlite/sqlite3.h" +#include <sqlite3.h> + +class WriteGeoModelAction : public GeoNodeAction //## Inherits: <unnamed>%3FB0190202B6 +{ + enum Type { TRANSFORM, + VOLUME, + NAMETAG, + IDENTIFIERTAG}; + +public: + + //## Constructors (specified) + // Constructor for the print graph action. + WriteGeoModelAction (std::ostream &o, // Constructor. Takes an output stream. + MemMap& m, // and an unordered map. + sqlite3 *db = 0// + ); + //## Destructor (generated) + virtual ~WriteGeoModelAction(); + + bool isOpen() const; + + + //## Other Operations (specified) + + // Handles a Transform. + virtual void handleTransform (const GeoTransform *xform); + + // Handles a physical volume. + virtual void handlePhysVol (const GeoPhysVol *vol); + + // Handles a physical volume. + virtual void handleFullPhysVol (const GeoFullPhysVol *vol); + + // Handles a Name Tag. + virtual void handleNameTag (const GeoNameTag *nameTag); + + // Handles a Serial Denominator. + virtual void handleSerialDenominator (const GeoSerialDenominator *sD); + + // Handles a Serial Transformer + virtual void handleSerialTransformer (const GeoSerialTransformer *sT); + + // Handles an Identifier Tag. + virtual void handleIdentifierTag (const GeoIdentifierTag *idTag); + + // Sets the notification state. Default: everything on. + void setNotification (Type type, bool state); + + // Public SQLite DB methods + QSqlError fetchAllRecords(); + + QSqlError initDB(); + QSqlError loadTestData(); +protected: + +private: + //## Constructors (generated) + WriteGeoModelAction(const WriteGeoModelAction &right); + + //## Assignment Operation (generated) + WriteGeoModelAction & operator=(const WriteGeoModelAction &right); + + + // Indent the print. + void indent (); + + + int storeObj(const GeoLogVol* pointer); + int storeObj(const GeoMaterial* pointer); + int storeObj(const GeoGraphNode* pointer); + int storeObj(const GeoShape* pointer); + + int storeAddress(const std::string address); + void persistifyObj(const GeoPhysVol * pointer); + + // Private SQLite DB methods +// static int callback(void *NotUsed, int argc, char **argv, char **azColName); +// void createTables(); +// bool executeSQL(char const *sql); + +// QSqlError openDB(); +// void closeDB(); + + + QVariant addPhysVol(QSqlQuery &q, const QVariant &logVolId, const QVariant &parentPhysVolId); + QVariant addLogVol(QSqlQuery &q, const QString &name, const QVariant &shapeId, const QVariant &materialId); + QVariant addMaterial(QSqlQuery &q, const QString &name); + QVariant addShape(QSqlQuery &q, const QString &name); + + + + // Data Members for Class Attributes + + // A pointer to a name tag. If the volume is named. + const GeoNameTag *m_nameTag; + + // A pointer to a serial denominator. If one exists. + const GeoSerialDenominator *m_serialDenominator; + + // A pointer to an identifier tag. If the volume is identified. + const GeoIdentifierTag *m_idTag; + + // List of Pending Transformations. + std::vector<const GeoTransform *> m_pendingTransformList; + + // On/off flag for transforms. + bool m_transformState; + + // On/off flag for physical volumes. + bool m_volumeState; + + // On/off flag for name tags. + bool m_nametagState; + + // On/off flag for serial denominators. + bool m_serialDenominatorState; + + // On/off flag for serial transformers. + bool m_serialTransformerState; + + // On/off flag for identifier tags. + bool m_identifierState; + + // output stream + std::ostream &m_o; + + MemMap & m_map; + +// sqlite3 * m_db; + + QSqlDatabase m_db; +// QSqlDatabase* _db; + + unsigned long int m_id; // store index of stored objects + + int rc; + char const *sql; + char *zErrMsg = 0; + const char* data = "Callback function called"; + + + // Flag for indent (intially 0) + mutable bool m_indented; + + + +private: //## implementation + +}; + + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelAction.oldVersion b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelAction.oldVersion new file mode 100644 index 0000000000000000000000000000000000000000..338ff50cac792690713e1b12aa82a69a17152b44 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelAction.oldVersion @@ -0,0 +1,1600 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + + + +// local includes +#include "GeoWrite/DumpGeoModelAction.h" + +// TFPersistification includes +#include "TFPersistification/TransFunctionPersistifier.h" + + +// GeoModelKernel includes +#include "GeoModelKernel/GeoNodePath.h" +#include "GeoModelKernel/GeoCountVolAction.h" +// GeoModelKernel shapes +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoCons.h" +#include "GeoModelKernel/GeoPara.h" +#include "GeoModelKernel/GeoPcon.h" +#include "GeoModelKernel/GeoPgon.h" +#include "GeoModelKernel/GeoSimplePolygonBrep.h" +#include "GeoModelKernel/GeoShapeShift.h" +#include "GeoModelKernel/GeoTrap.h" +#include "GeoModelKernel/GeoTrd.h" +#include "GeoModelKernel/GeoTube.h" +#include "GeoModelKernel/GeoTubs.h" + +// CLHEP includes +#include "CLHEP/Geometry/Transform3D.h" +#include "CLHEP/Matrix/SymMatrix.h" +#include "CLHEP/Matrix/Matrix.h" + + + +// Qt includes +#include <QSqlQuery> +#include <QSqlError> +#include <QSqlRecord> +#include <QSqlDriver> +#include <QVector> +#include <QDebug> + +// C++ includes +#include <sstream> + + + +int DumpGeoModelAction::getChildPosition(unsigned int parentId) +{ + if ( ! (m_parentChildrenMap.contains(parentId)) ) { + m_parentChildrenMap[parentId] = 0; + } + ++m_parentChildrenMap[parentId]; + return m_parentChildrenMap[parentId]; +} + + +void DumpGeoModelAction::handlePhysVol (const GeoPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelAction::handlePhysVol(GeoPhysVol*)"; + handleVPhysVolObjects( vol ); +} + + +void DumpGeoModelAction::handleFullPhysVol (const GeoFullPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelAction::handleFullPhysVol( GeoFullPhysVol* )"; + handleVPhysVolObjects( vol ); +} + + +void DumpGeoModelAction::handleVPhysVolObjects(const GeoVPhysVol* vol) +{ + qDebug() << "\nDumpGeoModelAction::handleVPhysVolObjects( GeoVPhysVol* )"; + + + // get the address string for the current volume + QString address = getAddressStringFromPointer( vol ); + + // variables used to persistify the object + QVariant parentId; + QVariant physId; + + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "length: " << len; + // std::cout << "path: " << path << std::endl; + + const GeoVPhysVol* parentNode = nullptr; + + // this below is performed until the root volume is found, then "length" is not used anymore, + // because not updated when recursively visiting PhysVols + bool getParentNode = true; + bool storeRootVolume = false; + if ( ! m_rootVolumeFound) { + if (len > 1) { + getParentNode = true; + } else{ + qDebug() << "This is the Root volume!"; + m_rootVolumeFound = true; + storeRootVolume = true; + getParentNode = false; + } + } else { + getParentNode = true; + } + + // get the parent volume, if this is not the Root volume + if (getParentNode) { + + parentNode = dynamic_cast<const GeoVPhysVol*>( &(*(vol->getParent() ))); + + if (parentNode) { + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + // else + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } + else { + qDebug() << "NULL parent node!!"; + } + } + + // counting children + unsigned int nChildren = vol->getNChildVols(); + qDebug() << "number of child physical volumes:" << nChildren; + qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; + + //// for debug + // GeoCountVolAction cv; + // cv.setDepthLimit(1); + // vol->exec(&cv); + // int nChildCount = cv.getCount(); + // qDebug() << "number of child volumes:" << nChildCount; + + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + /* + * VPhysVol features: + * - 1 parent VPhysVol (if any) + * - 1 LogVol + * - 1 Material + * - 1 Shape + */ + + // Note: PhysVol has no name. Its LogVol has a name. + // const std::string name = vol->getLogVol()->getName(); + + // LOGVOL + const GeoLogVol* logVol = vol->getLogVol(); + const QString logName = QString::fromStdString(logVol->getName()); + qDebug() << "LogVol name:" << logName; + + + // MATERIAL + const GeoMaterial * mat = vol->getLogVol()->getMaterial(); + const QString matName = QString::fromStdString(mat->getName()); + qDebug() << "material name:" << matName << ", address:" << mat; + + + // SHAPE + const GeoShape * shape = vol->getLogVol()->getShape(); + // const QString shapeType = QString::fromStdString(shape->type()); + // qDebug() << "shape name:" << shapeType << ", address:" << shape; + // // get shape parameters + // QString shapePars = getShapeParameters(shape); + + + /* + * STORE THE OBJECTS IN THE DB + */ + + // store/get the Material object into/from the DB + QVariant matId; + matId = storeObj(mat, matName); + + // store/get the Shape object into/from the DB + QVariant shapeId; + shapeId = storeShape(shape); + // shapeId = storeObj(shape, shapeType, shapePars); + + // store/get the LogVol object into/from the DB + QVariant logvolId; + logvolId = storeObj(logVol, logName, shapeId, matId); + + if (dynamic_cast<const GeoPhysVol*>(vol)) { + qDebug() << "New PhysVol, storing it..."; + const GeoPhysVol* physVol = dynamic_cast<const GeoPhysVol*>(vol); + // store the PhysVol volume into the DB + physId = storeObj(physVol, logvolId, parentId, storeRootVolume); // with parent info + qDebug() << "PhysVol stored. Id:" << physId.toString(); + } + else if (dynamic_cast<const GeoFullPhysVol*>(vol)) { + qDebug() << "New FullPhysVol, storing it..."; + const GeoFullPhysVol* fullVol = dynamic_cast<const GeoFullPhysVol*>(vol); + // store the FullPhysVol volume into the DB + physId = storeObj(fullVol, logvolId, parentId, storeRootVolume); // with parent info + qDebug() << "FullPhysVol stored. Id:" << physId.toString(); + } else { + qWarning() << "WARNING!! Unknown GeoVPhysVol type!!"; + } + + } else { + // qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map and moving to its physical children..."; + qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map..."; + physId = getStoredIdFromAddress(address); + qDebug() << "PhysVol Id:" << physId; + } + + + // store the parent-child relationship in the DB + + QString parentType; + if (parentNode) parentType = getGeoTypeFromVPhysVol(parentNode); + else parentType = "NULL"; + QString childType = getGeoTypeFromVPhysVol(vol); + storeChildPosition(parentId, parentType, physId, getChildPosition( parentId.toUInt() ), childType); + +} + + +QString DumpGeoModelAction::getGeoTypeFromVPhysVol(const GeoVPhysVol* vol) +{ + QString geoType; + if (dynamic_cast<const GeoPhysVol*>(vol)) { + qDebug() << "GeoType: GeoPhysVol"; + geoType = "GeoPhysVol"; + } + else if (dynamic_cast<const GeoFullPhysVol*>(vol)) { + qDebug() << "GeoType: GeoFullPhysVol"; + geoType = "GeoFullPhysVol"; + } else { + qWarning() << "WARNING!! Unknown GeoVPhysVol type!!"; + } + return geoType; +} + + +void DumpGeoModelAction::handleSerialDenominator (const GeoSerialDenominator *node) +{ + qDebug() << "\nDumpGeoModelAction::handleSerialDenominator(GeoSerialDenominator*)"; + + QString address = getAddressStringFromPointer( node ); + + + std::string baseNameStr = node->getBaseName(); + QString baseName = QString::fromStdString(baseNameStr); + qDebug() << "base name:" << baseName << "address:" << address; + + // TODO: check if needed! + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "length: " << len; + + // reset the number of visited node, if len is different than before + if (len != m_len) { + m_len_nChild = 0; + m_len = len; + } + // update number of visited nodes if len is the same as before + else { + ++m_len_nChild; + } + + // variables used to persistify the object + QVariant parentId; + QVariant sdId; + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = nullptr; + if (len > 1) { // TODO: check if needed! + parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + else + qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } else{ // TODO: check if needed! + qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + } + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New SerialDenominator, storing it..."; + + + /* + * STORE THE OBJECT IN THE DB + */ + + // store the Material object in the DB + sdId = storeObj(node, baseName); + qDebug() << "SerialDenominator stored. Id:" << sdId.toString(); + + } else { + sdId = getStoredIdFromAddress(address); + qDebug() << "SerialDenominator already stored in the DB. Id:" << sdId.toString(); + } + + QString parentType; + if (parentNode) parentType = getGeoTypeFromVPhysVol(parentNode); + else parentType = "NULL"; + storeChildPosition(parentId, parentType, sdId, getChildPosition( parentId.toUInt() ), "GeoSerialDenominator"); + +} + + + +void DumpGeoModelAction::handleSerialTransformer (const GeoSerialTransformer *node) +{ + qDebug() << "\nDumpGeoModelAction::handleSerialTransformer(GeoSerialTransformer*)"; + + QString address = getAddressStringFromPointer( node ); + + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "path length: " << len; + + // reset the number of visited node, if len is different than before + if (len > m_len) { + m_len_nChild = 0; + m_len = len; + } + // update number of visited nodes if len is the same as before + else { + ++m_len_nChild; + } + + + // variables used to persistify the object + QVariant parentId; + QVariant functionId; + QVariant physvolId; + QVariant physvolTable; + unsigned int nCopies; + QVariant stId; + + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = nullptr; + if (len > 1) { + parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + else + qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } else{ + qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + } + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New SerialTransformer, storing it..."; + + /* + * Get Node characteristics + * + * SerialTransformer features: + * - 1 parent PhysVol (if any) + * - 1 GENFUNCTION + * - 1 PhysVolId + * - 1 PhysVolType + * - 1 number of copies + */ + // get linked function and number of copies + const GeoXF::Function * func = node->getFunction(); + nCopies = node->getNCopies(); + qDebug() << "n. of copies:" << QString::number(nCopies); + + // get linked VPhysVol volume + const GeoVPhysVol *vol = &( *( node->getVolume() ) ); + // const GeoPhysVol* vol = dynamic_cast<const GeoPhysVol*>(volV); + QString volType; + if (dynamic_cast<const GeoPhysVol*>(vol)) + volType = "GeoPhysVol"; + else if (dynamic_cast<const GeoFullPhysVol*>(vol)) + volType = "GeoFullPhysVol"; + else + qWarning() << "ERROR!!! Unknown VPhysVol type!!"; + + /* + * Persistify the Function + */ + TransFunctionPersistifier persistifier; + try { + persistifier.persistify(*func); + } catch (const std::runtime_error & error) { + std::cout << "Handling TransFunctionPersistifier std::runtime_error! -->" << error.what() << std::endl; + std::cout << "SEVERE WARNING!! Handling std::runtime_error! -->" << error.what() << std::endl; + } + QString expression = QString::fromStdString( persistifier.getCodedString() ); + qDebug() << "FUNCTION:" << expression; + + if (expression.size() == 0) { + qFatal("FATAL ERROR!! Function expression is empty!! Aborting..."); + abort(); + } + + + /* + * STORE/GET THE INNER OBJECTS IN THE DB + */ + + // store/get the Function object in the DB + functionId = storeObj(func, expression); + + // store/get the PhysVol volume in the DB + + /* Concerning the physVol referenced by the SerialTransformer: + * + * - if physvol is not stored in the DB already; + * - if physVol has no parent (==NULL) + * ==> it means that its children will never visited by the NodeAction executed on the root tree + * + * ==> So, we need to persitify it as a new tree, to get all its children visited and persistified + * + */ + handleReferencedPhysVol(vol); + + QString physvolAddress = getAddressStringFromPointer(vol); + physvolId = getStoredIdFromAddress(physvolAddress); + + + /* + * STORE THE NODE INTO THE DB + */ + // store the SerialTransformer volume in the DB + stId = storeObj(node, functionId, physvolId, volType, nCopies); + qDebug() << "SerialTransformer stored. Id:" << stId.toString(); + + } else { + stId = getStoredIdFromAddress(address); + qDebug() << "SerialTransformer already stored in the DB. Id:" << stId.toString(); + } + + QString parentType; + if (parentNode) parentType = getGeoTypeFromVPhysVol(parentNode); + else parentType = "NULL"; + storeChildPosition(parentId, parentType, stId, getChildPosition( parentId.toUInt() ), "GeoSerialTransformer"); + +} + + + + +void DumpGeoModelAction::handleTransform(const GeoTransform* node) +{ + qDebug() << "\nDumpGeoModelAction::handleTransform(GeoTransform*)"; + + QString address = getAddressStringFromPointer( node ); + + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "length: " << len; + + // reset the number of visited node, if len is different than before + if (len > m_len) { + m_len_nChild = 0; + m_len = len; + } + // update number of visited nodes if len is the same as before + else { + ++m_len_nChild; + } + + + QVariant trId; + QVariant parentId; + + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = nullptr; + if (len > 1) { + parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + else { + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + qWarning() << "The parent node of this transform seems to not having be stored in the DB yet. [It is normal if the transformation is used for example only in the definition of a 'GeoShapeShift' instance]"; + } + qDebug() << "- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } else{ + qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + } + + /* + * STORE THE OBJECT IN THE DB AND ITS PLACE WITHIN THE TREE + */ + + // store the transformation in the DB + trId = storeTranform(node); + + + // Store the child-parent relationship + QString parentType; + if (parentNode) parentType = getGeoTypeFromVPhysVol(parentNode); + else parentType = "NULL"; + if ( dynamic_cast<const GeoAlignableTransform*>(node) ) { + qDebug() << "Storing a GeoAlignableTransform..."; + storeChildPosition(parentId, parentType, trId, getChildPosition( parentId.toUInt() ), "GeoAlignableTransform"); + } + else if ( dynamic_cast<const GeoTransform*>(node) ) { + qDebug() << "Storing a GeoTransform..."; + storeChildPosition(parentId, parentType, trId, getChildPosition( parentId.toUInt() ), "GeoTransform"); + } + else { + qWarning("Not implemented yet!!!! "); + } + +} + + +void DumpGeoModelAction::handleNameTag(const GeoNameTag* node) +{ + qDebug() << "\nDumpGeoModelAction::handleNameTag(GeoNameTag*)"; + + std::string nameStr = node->getName(); + QString name = QString::fromStdString(nameStr); + qDebug() << "name:" << name; + + QString address = getAddressStringFromPointer( node ); + + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "length: " << len; + + // reset the number of visited node, if len is different than before + if (len > m_len) { + m_len_nChild = 0; + m_len = len; + } + // update number of visited nodes if len is the same as before + else { + ++m_len_nChild; + } + + + QVariant nameId; + QVariant parentId; + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = nullptr; + if (len > 1) { + parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + else { + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + qWarning() << "The parent node of this transform seems to not having be stored in the DB yet. [It is normal if the transformation is used for example only in the definition of a 'GeoShapeShift' instance]"; + } + qDebug() << "- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } else{ + qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + } + + /* + * STORE THE OBJECT IN THE DB AND ITS PLACE WITHIN THE TREE + */ + + // store the name tag in the DB + nameId = storeObj(node, name); + + // Store the child-parent relationship + QString parentType; + if (parentNode) parentType = getGeoTypeFromVPhysVol(parentNode); + else parentType = "NULL"; + storeChildPosition(parentId, parentType, nameId, getChildPosition( parentId.toUInt() ), "GeoNameTag"); + +} + +QVariant DumpGeoModelAction::storeShape(const GeoShape* shape){ + const QString shapeType = QString::fromStdString(shape->type()); + qDebug() << "shape name:" << shapeType << ", address:" << shape; + // get shape parameters + QString shapePars = getShapeParameters(shape); + // store the shape in the DB and returns the ID + return storeObj(shape, shapeType, shapePars); +} + +QVariant DumpGeoModelAction::storeTranform(const GeoTransform* node){ + /* + * STORE THE OBJECT IN THE DB + */ + + QString address = getAddressStringFromPointer( node ); + + QVariant trId; + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New Transform, storing it..."; + + + HepGeom::Transform3D tr = node->getTransform(); + + std::vector<double> params = getTransformParameters(tr); + qDebug() << "Transform parameters:" << QVector<double>::fromStdVector(params); + + /* + * STORE THE OBJECT IN THE DB + */ + + // store the object in the DB + if ( dynamic_cast<const GeoAlignableTransform*>(node) ) { + trId = storeObj(dynamic_cast<const GeoAlignableTransform*>(node), params); + qDebug() << "AlignableTransform stored. Id:" << trId.toString(); + } + else if ( dynamic_cast<const GeoTransform*>(node) ) { + trId = storeObj(dynamic_cast<const GeoTransform*>(node), params); + qDebug() << "Transform stored. Id:" << trId.toString(); + } + else { + qDebug() << "WARNING!!! - This type of transformation needs to be customized yet!!"; + } + + } else { + trId = getStoredIdFromAddress(address); + qDebug() << "Transform already stored in the DB. Id:" << trId.toString(); + } + + return trId; +} + + +void DumpGeoModelAction::handleReferencedPhysVol (const GeoVPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelAction::handleReferencedPhysVol(GeoVPhysVol*)"; + + // qDebug() << "PhysVol's LogVol name:" << QString::fromStdString(vol->getLogVol()->getName()); + + // get the address string for the current volume + QString address = getAddressStringFromPointer( vol ); + + QVariant parentId; + bool unconnectedTree = false; + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = dynamic_cast<const GeoVPhysVol*>( &(*(vol->getParent() ))); + + if (parentNode) { + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + // else + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } + else { + qDebug() << "NULL parent node!!"; + unconnectedTree = true; + } + + // // counting children + // unsigned int nChildren = vol->getNChildVols(); + // qDebug() << "number of child physical volumes:" << nChildren; + // qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; + // + // GeoCountVolAction cv; + // cv.setDepthLimit(1); + // vol->exec(&cv); + // int nChildCount = cv.getCount(); + // qDebug() << "number of child volumes:" << nChildCount; + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "This is a new root PhysVol node of an 'unconnected' tree, so we start another action on it to dump it into the DB..."; + + // Dump tree volumes into a DB + vol->exec(this); // TODO: check if the new action overwrites the id of the volumes already in the DB...!!! + } +} + + +// Get shape parameters +QString DumpGeoModelAction::getShapeParameters(const GeoShape* shape) +{ + const QString shapeType = QString::fromStdString(shape->type()); + qDebug() << "shapeType:" << shapeType; + + QString shapePars = ""; + + if (shapeType == "Box") { + qDebug() << "get GeoBox parameters"; + QStringList pars; + const GeoBox* box = dynamic_cast<const GeoBox*>(shape); + pars << "XHalfLength=" + QString::number(box->getXHalfLength()) ; + pars << "YHalfLength=" + QString::number(box->getYHalfLength()) ; + pars << "ZHalfLength=" + QString::number(box->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Tube") { + QStringList pars; + const GeoTube* tube = dynamic_cast<const GeoTube*>(shape); + pars << "RMin=" + QString::number(tube->getRMin()) ; + pars << "RMax=" + QString::number(tube->getRMax()) ; + pars << "ZHalfLength=" + QString::number(tube->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Cons") { + QStringList pars; + const GeoCons* shapeIn = dynamic_cast<const GeoCons*>(shape); + pars << "RMin1=" + QString::number(shapeIn->getRMin1()) ; + pars << "RMin2=" + QString::number(shapeIn->getRMin2()) ; + pars << "RMax1=" + QString::number(shapeIn->getRMax1()) ; + pars << "RMax2=" + QString::number(shapeIn->getRMax2()) ; + pars << "DZ=" + QString::number(shapeIn->getDZ()) ; + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Para") { + QStringList pars; + const GeoPara* shapeIn = dynamic_cast<const GeoPara*>(shape); + pars << "XHalfLength=" + QString::number(shapeIn->getXHalfLength()) ; + pars << "YHalfLength=" + QString::number(shapeIn->getYHalfLength()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "Alpha=" + QString::number(shapeIn->getAlpha()) ; + pars << "Theta=" + QString::number(shapeIn->getTheta()) ; + pars << "Phi=" + QString::number(shapeIn->getPhi()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Pcon") { + QStringList pars; + const GeoPcon* shapeIn = dynamic_cast<const GeoPcon*>(shape); + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Pgon") { + QStringList pars; + const GeoPgon* shapeIn = dynamic_cast<const GeoPgon*>(shape); + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + pars << "NSides=" + QString::number(shapeIn->getNSides()) ; + shapePars = pars.join(";"); + } else if (shapeType == "SimplePolygonBrep") { + QStringList pars; + const GeoSimplePolygonBrep* shapeIn = dynamic_cast<const GeoSimplePolygonBrep*>(shape); + pars << "DZ=" + QString::number(shapeIn->getDZ()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Trap") { + QStringList pars; + const GeoTrap* shapeIn = dynamic_cast<const GeoTrap*>(shape); + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "Theta=" + QString::number(shapeIn->getTheta()) ; + pars << "Phi=" + QString::number(shapeIn->getPhi()) ; + pars << "Dydzn=" + QString::number(shapeIn->getDydzn()) ; + pars << "Dxdyndzn=" + QString::number(shapeIn->getDxdyndzn()) ; + pars << "Dxdypdzn=" + QString::number(shapeIn->getDxdypdzn()) ; + pars << "Angleydzn=" + QString::number(shapeIn->getAngleydzn()) ; + pars << "Dydzp=" + QString::number(shapeIn->getDydzp()) ; + pars << "Dxdyndzp=" + QString::number(shapeIn->getDxdyndzp()) ; + pars << "Dxdypdzp=" + QString::number(shapeIn->getDxdypdzp()) ; + pars << "Angleydzp=" + QString::number(shapeIn->getAngleydzp()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Trd") { + QStringList pars; + const GeoTrd* shapeIn = dynamic_cast<const GeoTrd*>(shape); + pars << "XHalfLength1=" + QString::number(shapeIn->getXHalfLength1()) ; + pars << "XHalfLength2=" + QString::number(shapeIn->getXHalfLength2()) ; + pars << "YHalfLength1=" + QString::number(shapeIn->getYHalfLength1()) ; + pars << "YHalfLength2=" + QString::number(shapeIn->getYHalfLength2()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Tubs") { + QStringList pars; + const GeoTubs* shapeIn = dynamic_cast<const GeoTubs*>(shape); + pars << "RMin=" + QString::number(shapeIn->getRMin()) ; + pars << "RMax=" + QString::number(shapeIn->getRMax()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + shapePars = pars.join(";"); + } + else if (shapeType == "Shift") { + qDebug() << "get GeoShapeShift parameters"; + QStringList pars; + const GeoShapeShift* shapeIn = dynamic_cast<const GeoShapeShift*>(shape); + + // get the pointed Shape, store it in the DB + const GeoShape* shapeOp = shapeIn->getOp(); + QVariant shapeId = storeShape(shapeOp); + + // get the Transformation, store it in the DB + const HepGeom::Transform3D transfX = shapeIn->getX(); + GeoTransform* transf = new GeoTransform(transfX); + QVariant trId = storeTranform(transf); + + pars << "A=" + QString::number( shapeId.toUInt() ) ; + pars << "X=" + QString::number( trId.toUInt() ) ; + shapePars = pars.join(";"); + } + else { + qDebug() << "WARNING!!! - Shape '" << shapeType << "' needs to be customized!!"; + } + + return shapePars; + +} + + +std::vector<double> DumpGeoModelAction::getTransformParameters(HepGeom::Transform3D tr) +{ + std::vector<double> vec; + + vec.push_back(tr.xx()); + vec.push_back(tr.xy()); + vec.push_back(tr.xz()); + + vec.push_back(tr.yx()); + vec.push_back(tr.yy()); + vec.push_back(tr.yz()); + + vec.push_back(tr.zx()); + vec.push_back(tr.zy()); + vec.push_back(tr.zz()); + + vec.push_back(tr.dx()); + vec.push_back(tr.dy()); + vec.push_back(tr.dz()); + + return vec; +} + + +DumpGeoModelAction::DumpGeoModelAction(GMDBManager &db) +{ + qDebug() << "DumpGeoModelAction: constructor"; + + // init variables + m_len = 0; + m_len_nChild = 0; + m_rootVolumeFound = false; + + // init anche check the database handle + m_dbManager = &db; + if (m_dbManager->isOpen()) { + qDebug() << "OK! Database is open!"; + } + else { + qDebug() << "Database is not open!"; + } + + // QString pippo = "pippo"; + +} + +DumpGeoModelAction::~DumpGeoModelAction() +{ + // nothing to do so far... +} + + +void DumpGeoModelAction::showMemoryMap() +{ + qDebug() << "DumpGeoModelAction::showMemoryMap()"; + + QMap<QString, QVariant>::const_iterator it = m_memMap.constBegin(); + while (it != m_memMap.constEnd()) { + std::cout << it.key().toStdString() << ": " << it.value().toString().toStdString() << std::endl; + ++it; + } +} + + + +QVariant DumpGeoModelAction::storeObj(const GeoMaterial* pointer, const QString name) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoMaterial*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant materialId; + + if (! isAddressStored(address)) { + qDebug() << "New Material! Storing it..."; + + materialId = m_dbManager->addMaterial(name); + materialId = m_dbManager->addMaterial(name); + + storeAddress( address, materialId ); + } + else { + qDebug() << "Material node stored already. Getting ID from the memory map..."; + materialId = getStoredIdFromAddress(address); + } + qDebug() << "materialId:" << materialId; + return materialId; +} + +QVariant DumpGeoModelAction::storeObj(const GeoShape* pointer, const QString name, const QString parameters) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoShape*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant shapeId; + if (! isAddressStored(address)) { + qDebug() << "New Shape! Storing it..."; + shapeId = m_dbManager->addShape(name, parameters); + storeAddress( address, shapeId); + } + else { + qDebug() << "Shape node stored already. Getting ID from the memory map..."; + shapeId = getStoredIdFromAddress(address); + } + qDebug() << "shapeId:" << shapeId; + return shapeId; +} + +QVariant DumpGeoModelAction::storeObj(const GeoLogVol* pointer, const QString name, const QVariant shapeId, const QVariant materialId) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoLogVol*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant logvolId; + if (! isAddressStored(address)) { + qDebug() << "New LogVol! Storing it..."; + logvolId = m_dbManager->addLogVol(name, shapeId, materialId); + storeAddress( address, logvolId ); + } + else { + qDebug() << "LogVol node stored already. Getting ID from the memory map..."; + logvolId = getStoredIdFromAddress(address); + } + qDebug() << "logvolId:" << logvolId; + return logvolId; +} + + +QVariant DumpGeoModelAction::storeObj(const GeoPhysVol* pointer, const QVariant logvolId, const QVariant parentId, bool isRootVolume) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoPhysVol*) - address:" << pointer << "- is root volume?" << isRootVolume; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant physvolId; + if (! isAddressStored(address)) { + qDebug() << "New PhysVol! Storing it..."; + physvolId = m_dbManager->addPhysVol(logvolId, parentId, isRootVolume); + storeAddress( address, physvolId ); + } + else { + qDebug() << "PhysVol node stored already. Getting ID from the memory map..."; + physvolId = getStoredIdFromAddress(address); + } + qDebug() << "physvolId:" << physvolId; + return physvolId; +} + +QVariant DumpGeoModelAction::storeObj(const GeoFullPhysVol* pointer, const QVariant logvolId, const QVariant parentId, bool isRootVolume) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoFullPhysVol*) - address:" << pointer << "- is root volume?" << isRootVolume; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant physvolId; + if (! isAddressStored(address)) { + qDebug() << "New FullPhysVol! Storing it..."; + physvolId = m_dbManager->addFullPhysVol(logvolId, parentId, isRootVolume); + storeAddress( address, physvolId ); + } + else { + qDebug() << "FullPhysVol node stored already. Getting ID from the memory map..."; + physvolId = getStoredIdFromAddress(address); + } + qDebug() << "fullphysvolId:" << physvolId; + return physvolId; +} + +QVariant DumpGeoModelAction::storeObj(const GeoSerialDenominator* pointer, const QString baseName) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoSerialDenominator*) - baseName:" << baseName << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialDenominator! Storing it..."; + id = m_dbManager->addSerialDenominator(baseName); + storeAddress( address, id ); + } + else { + qDebug() << "SerialDenominator node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + + +QVariant DumpGeoModelAction::storeObj(const GeoSerialTransformer* pointer, const QVariant functionId, const QVariant volId, const QString volType, const unsigned int copies) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoSerialTransformer*):" << volId << volType << "- n. of copies: " << copies; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialTransformer! Storing it..."; + id = m_dbManager->addSerialTransformer(functionId, volId, volType, copies); + storeAddress( address, id ); + } + else { + qDebug() << "SerialTransformer node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelAction::storeObj(const GeoXF::Function* pointer, const QString expression) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoXF::Function*)"; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + id = m_dbManager->addFunction(expression); + storeAddress( address, id ); + } + else { + qDebug() << "GeoXF::Function node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelAction::storeObj(const GeoTransform* pointer, std::vector<double> parameters) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoTransform*)"; + + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + + id = m_dbManager->addTransform( QVector<double>::fromStdVector(parameters) ); + storeAddress( address, id ); + } + else { + qDebug() << "GeoTransform node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelAction::storeObj(const GeoAlignableTransform* pointer, std::vector<double> parameters) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoAlignableTransform*)"; + + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + + id = m_dbManager->addAlignableTransform( QVector<double>::fromStdVector(parameters) ); + storeAddress( address, id ); + } + else { + qDebug() << "GeoAlignableTransform node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + + +QVariant DumpGeoModelAction::storeObj(const GeoNameTag* pointer, const QString name) +{ + qDebug() << "DumpGeoModelAction::storeObj(GeoNameTag*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialDenominator! Storing it..."; + id = m_dbManager->addNameTag(name); + storeAddress( address, id ); + } + else { + qDebug() << "SerialDenominator node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + + +void DumpGeoModelAction::storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int childPos, const QString childType) +{ + qDebug() << "DumpGeoModelAction::storeChildPosition()"; + + m_dbManager->addChildPosition(parentId, parentType, childId, childPos, childType); + return; + +} + + +void DumpGeoModelAction::storeAddress(const QString address, QVariant id) +{ + qDebug() << "DumpGeoModelAction::storeAddress(" << address << "," << id << ")"; + m_memMap.insert(address, id); +} + +bool DumpGeoModelAction::isAddressStored(const QString address) +{ + qDebug() << "DumpGeoModelAction::isAddressStored(): " << address; + //showMemoryMap(); // only for Debug + return m_memMap.contains(address); +} + + +QVariant DumpGeoModelAction::getStoredIdFromAddress(QString address) +{ + qDebug() << "DumpGeoModelAction::getStoredIdFromAddress(): " << address; + return m_memMap.value(address); +} + +// get pointer string +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoMaterial* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoMaterial*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoShape* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoShape*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoLogVol* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoLogVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoPhysVol* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoPhysVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoVPhysVol* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoVPhysVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoSerialDenominator* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoSerialDenominator*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoSerialTransformer* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoSerialTransformer*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoXF::Function* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoXF::Function*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoTransform* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoTransform*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelAction::getAddressStringFromPointer(const GeoNameTag* pointer) +{ + qDebug() << "DumpGeoModelAction::getAddressStringFromPointer(GeoNameTag*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelAction::getQStringFromOss(std::ostringstream &oss) +{ + qDebug() << "DumpGeoModelAction::getQStringFromOss()"; + std::string addr = oss.str(); + QString address = QString::fromStdString(addr); + qDebug() << "address string:" << address; + return address; +} + + +//bool DumpGeoModelAction::isObjectStored(const GeoMaterial* pointer) +//{ +// qDebug() << "DumpGeoModelAction::isObjectStored(const GeoMaterial*)"; +// return isAddressStored(getAddressStringFromPointer( pointer) ); +//} +// +//bool DumpGeoModelAction::isObjectStored(const GeoGraphNode* pointer) +//{ +// qDebug() << "DumpGeoModelAction::isObjectStored(const GeoGraphNode*)"; +//// return isAddressStored(address); +//} + + + +// void DumpGeoModelAction::handlePhysVol (const GeoPhysVol *vol) +// { +// qDebug() << "\nDumpGeoModelAction::handlePhysVol(GeoPhysVol*)"; +// +// // get the address string for the current volume +// QString address = getAddressStringFromPointer( vol ); +// +// // variables used to persistify the object +// QVariant parentId; +// QVariant physId; +// +// // check the volume position in the geometry tree +// GeoNodePath* path = getPath(); +// unsigned int len = path->getLength(); +// qDebug() << "length: " << len; +// // std::cout << "path: " << path << std::endl; +// +// // const GeoVPhysVol* parentNode; +// +// // this below is performed until the root volume is found, then "length" is not used anymore, +// // because not updated when recursively visiting PhysVols +// bool getParentNode = true; +// bool storeRootVolume = false; +// if ( ! m_rootVolumeFound) { +// if (len > 1) { +// getParentNode = true; +// } else{ +// qDebug() << "This is the Root volume!"; +// m_rootVolumeFound = true; +// storeRootVolume = true; +// getParentNode = false; +// } +// } else { +// getParentNode = true; +// } +// +// // get the parent volume, if this is not the Root volume +// if (getParentNode) { +// +// const GeoPhysVol* parentNode = dynamic_cast<const GeoPhysVol*>( &(*(vol->getParent() ))); +// +// if (parentNode) { +// QString parentAddress = getAddressStringFromPointer(parentNode); +// qDebug() << "parent's address:" << parentNode; +// +// if (isAddressStored(parentAddress)) +// parentId = getStoredIdFromAddress(parentAddress); +// // else +// // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); +// +// qDebug() << "parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); +// } +// else { +// qDebug() << "NULL parent node!!"; +// } +// } +// +// // counting children +// unsigned int nChildren = vol->getNChildVols(); +// qDebug() << "number of child physical volumes:" << nChildren; +// qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; +// +// GeoCountVolAction cv; +// cv.setDepthLimit(1); +// vol->exec(&cv); +// int nChildCount = cv.getCount(); +// qDebug() << "number of child volumes:" << nChildCount; +// +// +// +// // check if this object has been stored already +// if (! isAddressStored(address)) { +// +// qDebug() << "New PhysVol, storing it..."; +// +// /* +// * PhysVol features: +// * - 1 parent PhysVol (if any) +// * - 1 LogVol +// * - 1 Material +// * - 1 Shape +// */ +// +// // Note: PhysVol has no name. Its LogVol has a name. +// // const std::string name = vol->getLogVol()->getName(); +// +// // LOGVOL +// const GeoLogVol* logVol = vol->getLogVol(); +// const QString logName = QString::fromStdString(logVol->getName()); +// qDebug() << "LogVol name:" << logName; +// +// +// // MATERIAL +// const GeoMaterial * mat = vol->getLogVol()->getMaterial(); +// const QString matName = QString::fromStdString(mat->getName()); +// qDebug() << "material name:" << matName << ", address:" << mat; +// +// +// // SHAPE +// const GeoShape * shape = vol->getLogVol()->getShape(); +// const QString shapeType = QString::fromStdString(shape->type()); +// qDebug() << "shape name:" << shapeType << ", address:" << shape; +// +// // shape parameters +// QString shapePars = ""; +// if (shapeType == "Box") { +// QStringList pars; +// const GeoBox* box = dynamic_cast<const GeoBox*>(shape); +// pars << "XHalfLength=" + QString::number(box->getXHalfLength()) ; +// pars << "YHalfLength=" + QString::number(box->getYHalfLength()) ; +// pars << "ZHalfLength=" + QString::number(box->getZHalfLength()) ; +// shapePars = pars.join(";"); +// } +// +// /* +// * STORE THE OBJECTS IN THE DB +// */ +// +// // store/get the Material object into/from the DB +// QVariant matId; +// matId = storeObj(mat, matName); +// +// // store/get the Shape object into/from the DB +// QVariant shapeId; +// shapeId = storeObj(shape, shapeType, shapePars); +// +// // store/get the LogVol object into/from the DB +// QVariant logvolId; +// logvolId = storeObj(logVol, logName, shapeId, matId); +// +// // store the PhysVol volume into the DB +// physId = storeObj(vol, logvolId, parentId, storeRootVolume); // with parent info +// qDebug() << "PhysVol stored. Id:" << physId.toString(); +// +// } else { +// // qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map and moving to its physical children..."; +// qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map..."; +// physId = getStoredIdFromAddress(address); +// qDebug() << "PhysVol Id:" << physId; +// } +// +// +// // store the parent-child relationship in the DB +// storeChildPosition(parentId, physId, getChildPosition( parentId.toUInt() ), "GeoPhysVol"); +// + + /* Now we need to loop over children, to be sure all volumes are take. + That's because it seems that the action only goes to children that are 'attached' + to the tree with a parent-child relationship. For example I have a pInnerPassive PhysVol + added to a pPassive PhysVol; the latter is refeneced in a SerialTransformer. + pPassive is visited because of our implementation of the handleSerialTrasformer() method, + but the pInnerPassive is never visited. + */ + // if (nChildren > 0) { + // qDebug() << "Looping over the children..."; + // + // for (unsigned int i=0; i<nChildren; ++i) { + // + // unsigned int childPos = i; + // + // // get the name of the i-th child volume + // QString childName = QString::fromStdString(vol->getNameOfChildVol(i)); + // qDebug() << "\t" << i << " childName:" << childName; + // + // // Returns the i-th child volume + // + // // GEOPHYSVOL child + // if ( dynamic_cast<const GeoPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoPhysVol"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoPhysVol* childVol = dynamic_cast<const GeoPhysVol*>(childVolV); + // + // handlePhysVol(childVol); // recursive call + // + // } else { + // qCritical("\t\tERROR!! the child is not a persistified volume/node!!!"); + // return; + // } + // } + // } + + // if (nChildren > 0) { + // for (unsigned int i=0; i<nChildren; ++i) { + // + // unsigned int childPos = i; + // + // // get the name of the i-th child volume + // QString childName = QString::fromStdString(vol->getNameOfChildVol(i)); + // qDebug() << "\t" << i << " childName:" << childName; + // + // // Returns the i-th child volume + // + // // GEOPHYSVOL child + // if ( dynamic_cast<const GeoPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoPhysVol"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoPhysVol* childVol = dynamic_cast<const GeoPhysVol*>(childVolV); + // + // + // // check if child volume has been stored already. If not, store it. + // if ( ! isAddressStored( getAddressStringFromPointer( childVol )) ) { + // + // // MATERIAL + // const GeoMaterial * mat = childVol->getLogVol()->getMaterial(); + // const QString matName = QString::fromStdString(mat->getName()); + // qDebug() << "Child material name:" << matName; + // + // // SHAPE + // const GeoShape * shape = childVol->getLogVol()->getShape(); + // const QString shapeType = QString::fromStdString(shape->type()); + // qDebug() << "Child shape name:" << shapeType; + // + // // LOGVOL + // const GeoLogVol* logVol = childVol->getLogVol(); + // const QString logName = QString::fromStdString(logVol->getName()); + // qDebug() << "Child LogVol name:" << logName; + // + // + // /* + // * STORE THE OBJECTS IN THE DB + // */ + // + // // store the Material object in the DB + // QVariant child_matId = storeObj(mat, matName); + // + // // store the Shape object in the DB + // QVariant child_shapeId = storeObj(shape, shapeType); + // + // // store the LogVol volume in the DB + // QVariant child_logvolId = storeObj(logVol, logName, child_shapeId, child_matId); + // + // // store the PhysVol volume in the DB + // storeObj(childVol, child_logvolId, physId); + // + // // store the parent-child relationship in the DB + // storeChildPosition(physId, childVol, childPos); + // + // } else { + // qDebug() << "Child volume stored already. Moving to the next one..."; + // } + // + // } + // // GeoSerialDenominator child + // else if ( dynamic_cast<const GeoSerialDenominator*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoSerialDenominator"; + // //qWarning() << "\t\t" << "to be implemented!!!"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoSerialDenominator* childVol = dynamic_cast<const GeoSerialDenominator*>(childVolV); + // + // std::string baseNameStr = childVol->getBaseName(); + // QString baseName = QString::fromStdString(baseNameStr); + // + // QString address = getAddressStringFromPointer( childVol ); + // + // qDebug() << "base name:" << baseName << "address:" << address; + // + // QVariant sdId; + // + // // check if this object has been stored already + // if (! isAddressStored(address)) { + // // store the SerialDenominator object in the DB + // qDebug() << "New SerialDenominator, storing it..."; + // sdId = storeObj(childVol, baseName); + // qDebug() << "SerialDenominator stored. Id:" << sdId.toString(); + // + // } else { + // sdId = getStoredIdFromAddress(address); + // qDebug() << "SerialDenominator already stored in the DB. Got id:" << sdId.toString(); + // } + // + // // store the parent-child relationship in the DB + // storeChildPosition(physId, childVol, childPos); + // + // } + // // GEOFULLPHYSVOL child + // else if ( dynamic_cast<const GeoFullPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoFullPhysVol"; + // qWarning() << "\t\t" << "to be implemented!!!"; + // // const GeoVFullPhysVol *childVolV = &(*(vol->getChildVol(i))); + // // const GeoFullPhysVol* childVol = dynamic_cast<const GeoFullPhysVol*>(childVolV); + // } + // else { + // qCritical("\t\tERROR!! the child is not a persistified volume/node!!!"); + // return; + // } + // + // + // // examples: + // //const GeoVPhysVol *child=&(*(pv->getChildVol(i))); + // // + // //if ( dynamic_cast<const GeoLogVol*>( &(*(vol->getChildVol(i) ))) ) + // // qDebug() << "\t\t" << "the child" << i << "is a GeoLogVol"; + // + // + // + // /* + // unsigned int nchildvol = pvc->getNChildVols(); + // int lgg = 0; + // int llay = 0; + // std::string::size_type npos; + // for (unsigned ich=0; ich<nchildvol; ++ich) { + // PVConstLink pc = pvc->getChildVol(ich); + // std::string childname = (pc->getLogVol())->getName(); + // if ((npos = childname.find("layer")) != std::string::npos ) { + // llay ++; + // //std::cerr<<" navigating RPC named " + // // <<tname<<" child " + // // <<ich<<" is a layer with tag "<<llay<<std::endl; + // unsigned int nch1 = pc->getNChildVols(); + // lgg = 0; + // for (unsigned ngv=0; ngv<nch1; ++ngv) { + // PVConstLink pcgv = pc->getChildVol(ngv); + // std::string childname1 = (pcgv->getLogVol())->getName(); + // if ((npos = childname1.find("gas volume")) != std::string::npos ) { + // lgg ++; + // //std::cerr<<" navigating RPC named " + // // <<tname<<" child " + // // <<ngv<<" is a gas volume with tag "<<lgg<<std::endl; + // PVConstLink pcgg = pcgv->getChildVol(0); + // HepGeom::Transform3D trans = pvc->getXToChildVol(ich)*pc->getXToChildVol(ngv)*pcgv->getXToChildVol(0); + // m_Xlg[llay-1][lgg-1] = Amg::CLHEPTransformToEigen(trans); + // } + // } + // } + // } + // */ + // + // } + // } + + + // else { + // qDebug() << "Object stored already. Moving to next one..."; + // } +// } diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelActionLocal.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelActionLocal.cpp new file mode 100644 index 0000000000000000000000000000000000000000..2215475578ff645329dc41cd940cd85179b4cc02 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/DumpGeoModelActionLocal.cpp @@ -0,0 +1,2018 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// author: Riccardo.Maria.Bianchi@cern.ch +// major updates: Aug 2018 + +// local includes +#include "GeoWrite/DumpGeoModelActionLocal.h" + +// TFPersistification includes +#include "TFPersistification/TransFunctionPersistifier.h" + + +// GeoModelKernel includes +#include "GeoModelKernel/GeoNodePath.h" +#include "GeoModelKernel/GeoCountVolAction.h" +// GeoModelKernel shapes +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoCons.h" +#include "GeoModelKernel/GeoPara.h" +#include "GeoModelKernel/GeoPcon.h" +#include "GeoModelKernel/GeoPgon.h" +#include "GeoModelKernel/GeoSimplePolygonBrep.h" +#include "GeoModelKernel/GeoTrap.h" +#include "GeoModelKernel/GeoTrd.h" +#include "GeoModelKernel/GeoTube.h" +#include "GeoModelKernel/GeoTubs.h" +#include "GeoModelKernel/GeoShapeIntersection.h" +#include "GeoModelKernel/GeoShapeShift.h" +#include "GeoModelKernel/GeoShapeSubtraction.h" +#include "GeoModelKernel/GeoShapeUnion.h" + +// Qt includes +#include <QSqlQuery> +#include <QSqlError> +#include <QSqlRecord> +#include <QSqlDriver> +#include <QVector> +#include <QDebug> + +// C++ includes +#include <sstream> + + +// CLHEP includes // TODO: to remove once the migration to Eigen is complete +#include "CLHEP/Geometry/Transform3D.h" +#include "CLHEP/Matrix/SymMatrix.h" +#include "CLHEP/Matrix/Matrix.h" +#include "GeoPrimitives/CLHEPtoEigenConverter.h" // TODO: to be removed when dropping CLHEP + + + +// int DumpGeoModelActionLocal::getChildPosition(unsigned int parentId) +// { +// if ( ! (m_parentChildrenMap.contains(parentId)) ) { +// m_parentChildrenMap[parentId] = 0; +// } +// ++m_parentChildrenMap[parentId]; +// return m_parentChildrenMap[parentId]; +// } + + + +/// Get next child position available, given the parent type, id and copy number +unsigned int DumpGeoModelActionLocal::getChildPosition(const QString parentId, const QString parentType, const unsigned int copyN) +{ + qDebug() << "DumpGeoModelActionLocal::getChildPosition()"; + QString tableId = getIdFromNodeType(parentType); + QString key = tableId + ":" + parentId + ":" + QString::number(copyN); + + if ( ! (m_parentChildrenMap2.contains(key)) ) { + m_parentChildrenMap2[key] = 1; + } else { + ++m_parentChildrenMap2[key]; + } + + qDebug() << "parent key:" << key << " [tableId:parentId:copyN] - pos: " << m_parentChildrenMap2[key]; + return m_parentChildrenMap2[key]; +} + +unsigned int DumpGeoModelActionLocal::setVolumeCopyNumber(QString volId, QString volType) +{ + qDebug() << "DumpGeoModelActionLocal::setVolumeCopyNumber()"; + QString tableId = getIdFromNodeType(volType); + QString key = tableId + ":" + volId; + + if ( ! (m_volumeCopiesMap.contains(key)) ) { + m_volumeCopiesMap[key] = 1; + } else { + ++m_volumeCopiesMap[key]; + } + + qDebug() << "volume key:" << key << " [tableId:volumeId] - copy number: " << m_volumeCopiesMap[key]; + return m_volumeCopiesMap[key]; +} + + +unsigned int DumpGeoModelActionLocal::getLatestParentCopyNumber(QString parentId, QString parentType) +{ + qDebug() << "DumpGeoModelActionLocal::getLatestParentCopyNumber()"; + QString tableId = getIdFromNodeType(parentType); + QString key = tableId + ":" + parentId; + qDebug() << "key:" << key; + + if ( ! (m_volumeCopiesMap.contains(key)) ) { + qFatal("ERROR!!! Something's wrong in storing the number of copies!"); + } + + qDebug() << "get latest parent copy number:" << key << " [tableId:parentId] - copy number: " << m_volumeCopiesMap[key]; + return m_volumeCopiesMap[key]; +} + + + +// int DumpGeoModelActionLocal::getNewIdByNodeType(QString nodeType) +// { +// if ( ! (m_idsMap.contains(nodeType)) ) { +// m_idsMap[nodeType] = 0; +// } +// ++m_idsMap[nodeType]; +// return m_idsMap[nodeType]; +// } + + +void DumpGeoModelActionLocal::handlePhysVol (const GeoPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelActionLocal::handlePhysVol(GeoPhysVol*)"; + handleVPhysVolObjects( vol ); +} + + +void DumpGeoModelActionLocal::handleFullPhysVol (const GeoFullPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleFullPhysVol( GeoFullPhysVol* )"; + handleVPhysVolObjects( vol ); +} + + +void DumpGeoModelActionLocal::handleVPhysVolObjects(const GeoVPhysVol* vol) +{ + qDebug() << "DumpGeoModelActionLocal::handleVPhysVolObjects( GeoVPhysVol* )"; + + + // get the address string for the current volume + QString address = getAddressStringFromPointer( vol ); + + // variables used to persistify the object + QVariant physId; + + // check the volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + const GeoVPhysVol* tailVol = path->getTail(); + const GeoVPhysVol* headVol = path->getHead(); + const GeoVPhysVol* upperVol = nullptr; + if (len > 1) + upperVol = path->getItem(len-2); // item(len-1) is THIS volume ==> the length is updated when visiting a VPhysVol node + else + upperVol = path->getItem(len-1); // ROOT volume + qDebug() << "path: " << path << " - length: " << len << " - upper vol: " << upperVol << " - tail vol: " << tailVol << " - head vol: " << headVol; + // std::cout << "path: " << path << std::endl; + + // this below is performed until the root volume is found, then "length" is not used anymore, + // because not updated when recursively visiting children of PhysVols: it is updated only when a PhysVol node is visited + + bool doGetParentNode = true; + bool storeRootVolume = false; + bool isRootVolume = false; + + + if ( ! m_rootVolumeFound) { + if (len > 1) { + doGetParentNode = true; // TODO: is that needed???? + } else{ + qDebug() << "This is the Root volume!"; + isRootVolume = true; + m_rootVolumeFound = true; + storeRootVolume = true; + doGetParentNode = false; + } + } else { + doGetParentNode = true; + } + + // When dumping an unconnected sub-tree, e.g. a PhysVol used only in a SerialTransformer, + // we don't want to get the parent ID. + // If we do, the ID of the parent of the SerialTransformer is returned, which is wrong. + if (m_unconnectedTree) { + doGetParentNode = false; + qDebug() << "Handling an unconnected tree: we skip the parent-finding step..."; + // now, we reset the status, + // otherwise all the children of the first referenced, unconnected volume + // will be treated as unconnected as well + qDebug() << "setting 'unconnected' to: false"; + m_unconnectedTree = false; + } + + + // // get the parent volume + // QStringList parentList = getParentNode(); // you can use that, but you have to modify it to get len-2, instead of len-1, for VPhysVol nodes + // QString parentId = parentList[0]; + // QString parentType = parentList[1]; + + // get the parent volume, if this is not the Root volume or an unconnected sub-tree + const GeoVPhysVol* parentNode = nullptr; + QVariant parentId = "NULL"; + + QString volTypeStr = "NNN"; + + if (doGetParentNode) { + + bool isShared = vol->isShared(); + qDebug() << "is this node shared?" << isShared; + + //if (isShared) + parentNode = upperVol; + //else + // parentNode = dynamic_cast<const GeoVPhysVol*>( &(*(vol->getParent() ))); // this cannot be trust for shared nodes + qDebug() << "parentNode address" << parentNode; + + if (parentNode) { + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "==> parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + // else + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "==> parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } + else { + qDebug() << "NULL parent node!! --> this node appeared unconnected."; + } + } + + // counting children + unsigned int nChildren = vol->getNChildVols(); + qDebug() << "number of child physical volumes:" << nChildren; + qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; + + //// for debug + // GeoCountVolAction cv; + // cv.setDepthLimit(1); + // vol->exec(&cv); + // int nChildCount = cv.getCount(); + // qDebug() << "number of child volumes:" << nChildCount; + + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + /* + * VPhysVol features: + * - 1 parent VPhysVol (if any) + * - 1 LogVol + * - 1 Material + * - 1 Shape + */ + + // Note: PhysVol has no name. Its LogVol has a name. + // const std::string name = vol->getLogVol()->getName(); + + // LOGVOL + const GeoLogVol* logVol = vol->getLogVol(); + const QString logName = QString::fromStdString(logVol->getName()); + qDebug() << "LogVol name:" << logName; + + + // MATERIAL + const GeoMaterial * mat = vol->getLogVol()->getMaterial(); + // const QString matName = QString::fromStdString(mat->getName()); + // qDebug() << "material name:" << matName << ", address:" << mat; + + + // SHAPE + const GeoShape * shape = vol->getLogVol()->getShape(); + // const QString shapeType = QString::fromStdString(shape->type()); + // qDebug() << "shape name:" << shapeType << ", address:" << shape; + // // get shape parameters + // QString shapePars = getShapeParameters(shape); + + + /* + * STORE THE OBJECTS IN THE DB + */ + + // store/get the Material object into/from the DB + QVariant matId; + // matId = storeObj(mat, matName); + matId = storeMaterial(mat); + + // store/get the Shape object into/from the DB + QVariant shapeId; + shapeId = storeShape(shape); + // shapeId = storeObj(shape, shapeType, shapePars); + + // store/get the LogVol object into/from the DB + QVariant logvolId; + logvolId = storeObj(logVol, logName, shapeId, matId); + + if (dynamic_cast<const GeoPhysVol*>(vol)) { + qDebug() << "New PhysVol, storing it..."; + const GeoPhysVol* physVol = dynamic_cast<const GeoPhysVol*>(vol); + // store the PhysVol volume into the DB + physId = storeObj(physVol, logvolId, parentId, storeRootVolume); // with parent info + volTypeStr = "GeoPhysVol"; + qDebug() << "PhysVol stored. Id:" << physId.toString(); + } + else if (dynamic_cast<const GeoFullPhysVol*>(vol)) { + qDebug() << "New FullPhysVol, storing it..."; + const GeoFullPhysVol* fullVol = dynamic_cast<const GeoFullPhysVol*>(vol); + // store the FullPhysVol volume into the DB + physId = storeObj(fullVol, logvolId, parentId, storeRootVolume); // with parent info + volTypeStr = "GeoFullPhysVol"; + qDebug() << "FullPhysVol stored. Id:" << physId.toString(); + } else { + qWarning() << "WARNING!! Unknown GeoVPhysVol type!!"; + } + + } else { + // qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map and moving to its physical children..."; + qDebug() << "Volume stored already. It is a shared volume. Now, we are handling a 'copy' of it. We take the ID from memory map..."; + physId = getStoredIdFromAddress(address); + volTypeStr = getGeoTypeFromVPhysVol(vol); + } + + // Now we get the 'copy number' for this volume, + // to distinguish this volume from the other volumes created from the same shared node (if any) + if (volTypeStr == "NULL") qFatal("ERROR!! volTypeStr is 'NULL'!!!"); + const unsigned int volCopyN = setVolumeCopyNumber(physId.toString(), volTypeStr); + qDebug() << "physId: " << physId << "- volume copy number: " << volCopyN; + + if ( isRootVolume || parentId == "NULL") { + qDebug() << "This is the RootVolume or the volume has 'NULL' parent (unconnected subtree?) - So, we do not store the child position for this volume!"; + } else { + // store the parent-child relationship in the DB + QString parentType = getGeoTypeFromVPhysVol(parentNode); + // get the copy number of the parent + const unsigned int parentCopyN = getLatestParentCopyNumber(parentId.toString(), parentType); + qDebug() << "PhysVol Id:" << physId << " - copyNumber:" << QString::number(parentCopyN); + + QString childType = getGeoTypeFromVPhysVol(vol); + + storeChildPosition(parentId, parentType, physId, parentCopyN, getChildPosition( parentId.toString(), parentType, parentCopyN), childType, volCopyN); + } +} + + +QString DumpGeoModelActionLocal::getGeoTypeFromVPhysVol(const GeoVPhysVol* vol) +{ + if (!vol) + return QString("NULL"); + + QString geoType; + if (dynamic_cast<const GeoPhysVol*>(vol)) { + qDebug() << "GeoType: GeoPhysVol"; + geoType = "GeoPhysVol"; + } + else if (dynamic_cast<const GeoFullPhysVol*>(vol)) { + qDebug() << "GeoType: GeoFullPhysVol"; + geoType = "GeoFullPhysVol"; + } else { + qWarning() << "WARNING!! Unknown GeoVPhysVol type!!"; + } + return geoType; +} + + +void DumpGeoModelActionLocal::handleSerialDenominator (const GeoSerialDenominator *node) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleSerialDenominator(GeoSerialDenominator*)"; + + QString address = getAddressStringFromPointer( node ); + + std::string baseNameStr = node->getBaseName(); + QString baseName = QString::fromStdString(baseNameStr); + qDebug() << "base name:" << baseName << "address:" << address; + + // variables used to persistify the object + QVariant sdId; + + // get the parent volume + QStringList parentList = getParentNode(); + QString parentId = parentList[0]; + QString parentType = parentList[1]; + unsigned int parentCopyN = getLatestParentCopyNumber(parentId, parentType); + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New SerialDenominator, storing it..."; + + /* STORE THE OBJECT IN THE DB */ + sdId = storeObj(node, baseName); + qDebug() << "SerialDenominator stored. Id:" << sdId.toString(); + + } else { + sdId = getStoredIdFromAddress(address); + qDebug() << "SerialDenominator already stored in the DB. Id:" << sdId.toString(); + } + + storeChildPosition(parentId, parentType, sdId, parentCopyN, getChildPosition( parentId, parentType, parentCopyN ), "GeoSerialDenominator", 0); // TODO: Check if the copyN=0 at the end is OK for nodes as Transforms, which cannot be used as parents, only as children! +} + + + +void DumpGeoModelActionLocal::handleSerialTransformer (const GeoSerialTransformer *node) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleSerialTransformer(GeoSerialTransformer*)"; + + QString address = getAddressStringFromPointer( node ); + + // variables used to persistify the object + QVariant functionId; + QVariant physvolId; + QVariant physvolTable; + unsigned int nCopies; + QVariant stId; + + // get the parent volume + QStringList parentList = getParentNode(); + QString parentId = parentList[0]; + QString parentType = parentList[1]; + unsigned int parentCopyN = getLatestParentCopyNumber(parentId, parentType); + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New SerialTransformer, storing it..."; + + /* + * Get Node characteristics + * + * SerialTransformer features: + * - 1 parent PhysVol (if any) + * - 1 GENFUNCTION + * - 1 PhysVolId + * - 1 PhysVolType + * - 1 number of copies + */ + // get linked function and number of copies + const GeoXF::Function * func = node->getFunction(); + nCopies = node->getNCopies(); + qDebug() << "n. of copies:" << QString::number(nCopies); + + // get linked VPhysVol volume + const GeoVPhysVol *vol = &( *( node->getVolume() ) ); + // const GeoPhysVol* vol = dynamic_cast<const GeoPhysVol*>(volV); + QString volType; + if (dynamic_cast<const GeoPhysVol*>(vol)) { + volType = "GeoPhysVol"; + } else if (dynamic_cast<const GeoFullPhysVol*>(vol)) { + volType = "GeoFullPhysVol"; + } else { + qWarning() << "ERROR!!! Unknown VPhysVol type!!"; + } + + /* + * Persistify the Function + */ + TransFunctionPersistifier persistifier; + try { + persistifier.persistify(*func); + } catch (const std::runtime_error & error) { + std::cout << "SEVERE WARNING!! Handling std::runtime_error! -->" << error.what() << std::endl; + } + QString expression = QString::fromStdString( persistifier.getCodedString() ); + qDebug() << "FUNCTION:" << expression; + + if (expression.size() == 0) { + qFatal("FATAL ERROR!! Function expression is empty!! Aborting..."); + abort(); + } + + + /* + * STORE/GET THE INNER OBJECTS IN THE DB + */ + + // store/get the Function object in the DB + functionId = storeObj(func, expression); + + // store/get the PhysVol volume in the DB + + /* Concerning the physVol referenced by the SerialTransformer: + * + * - if physvol is not stored in the DB already; + * - if physVol has no parent (==NULL) + * ==> it means that its children will never visited by the NodeAction executed on the root tree + * + * ==> So, we need to persitify it as a new tree, to get all its children visited and persistified + * + */ + qDebug() << "Handling the referenced VPhysVol, going into the sub-tree, if any..."; + handleReferencedVPhysVol(vol); + + qDebug() << "Storing the referenced VPhysVol..."; + QString physvolAddress = getAddressStringFromPointer(vol); + physvolId = getStoredIdFromAddress(physvolAddress); + + + /* + * STORE THE NODE INTO THE DB AND ITS POSITION WITHIN THE TREE + */ + // store the SerialTransformer volume in the DB + stId = storeObj(node, functionId, physvolId, volType, nCopies); + qDebug() << "SerialTransformer stored. Id:" << stId.toString(); + + } else { + stId = getStoredIdFromAddress(address); + qDebug() << "SerialTransformer already stored in the DB. Id:" << stId.toString(); + } + + qDebug() << "Storing:" << parentId << parentType << stId; + storeChildPosition(parentId, parentType, stId, parentCopyN, getChildPosition( parentId, parentType, parentCopyN ), "GeoSerialTransformer", 0); // TODO: Check if the copyN=0 at the end is OK for nodes as Transforms, which cannot be used as parents, only as children! +} + + + + +void DumpGeoModelActionLocal::handleTransform(const GeoTransform* node) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleTransform(GeoTransform*)"; + + QString address = getAddressStringFromPointer( node ); + + // get the parent volume + QStringList parentList = getParentNode(); + QString parentId = parentList[0]; + QString parentType = parentList[1]; + + unsigned int parentCopyN = getLatestParentCopyNumber(parentId, parentType); + + // // check the volume position in the geometry tree + // GeoNodePath* path = getPath(); + // unsigned int len = path->getLength(); + // qDebug() << "length: " << len; + // + // // reset the number of visited node, if len is different than before + // if (len > m_len) { + // m_len_nChild = 0; + // m_len = len; + // } + // // update number of visited nodes if len is the same as before + // else { + // ++m_len_nChild; + // } + // + // + // QVariant parentId = "NULL"; + // QVariant trId; + // + // + // // get the parent volume, if this is not the Root volume + // const GeoVPhysVol* parentNode = nullptr; + // if (len > 1) { + // parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + // QString parentAddress = getAddressStringFromPointer(parentNode); + // qDebug() << "parent's address:" << parentNode; + // + // if (isAddressStored(parentAddress)) + // parentId = getStoredIdFromAddress(parentAddress); + // else { + // // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + // qWarning() << "The parent node of this transform seems to not having be stored in the DB yet. [It is normal if the transformation is used for example only in the definition of a 'GeoShapeShift' instance]"; + // } + // qDebug() << "- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + // } else{ + // qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + // } + + /* + * STORE THE OBJECT IN THE DB AND ITS PLACE WITHIN THE TREE + */ + + // store the transformation in the DB + QVariant trId = storeTranform(node); + + // Store the child-parent relationship + + if ( dynamic_cast<const GeoAlignableTransform*>(node) ) { + qDebug() << "Storing a GeoAlignableTransform..."; + storeChildPosition(parentId, parentType, trId, parentCopyN, getChildPosition( parentId, parentType, parentCopyN ), "GeoAlignableTransform", 0); // TODO: Check if the copyN=0 at the end is OK for nodes as Transforms, which cannot be used as parents, only as children! + } + else if ( dynamic_cast<const GeoTransform*>(node) ) { + qDebug() << "Storing a GeoTransform..."; + storeChildPosition(parentId, parentType, trId, parentCopyN, getChildPosition( parentId, parentType, parentCopyN ), "GeoTransform", 0); // TODO: Check if the copyN=0 at the end is OK for nodes as Transforms, which cannot be used as parents, only as children! + } + else { + qWarning("Not implemented yet!!!! "); + } + +} + + +void DumpGeoModelActionLocal::handleNameTag(const GeoNameTag* node) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleNameTag(GeoNameTag*)"; + + std::string nameStr = node->getName(); + QString name = QString::fromStdString(nameStr); + qDebug() << "name:" << name; + + QString address = getAddressStringFromPointer( node ); + + // get the parent volume + QStringList parentList = getParentNode(); + QString parentId = parentList[0]; + QString parentType = parentList[1]; + unsigned int parentCopyN = getLatestParentCopyNumber(parentId, parentType); + + // TODO: add "if stored"... + + /* + * STORE THE OBJECT IN THE DB AND ITS POSITION WITHIN THE TREE + */ + + // store the name tag in the DB + QVariant nameId = storeObj(node, name); + + // Store the child-parent relationship + storeChildPosition(parentId, parentType, nameId, parentCopyN, getChildPosition( parentId, parentType, parentCopyN ), "GeoNameTag", 0); +} + + + +//__________________________________________________ +QStringList DumpGeoModelActionLocal::getParentNode() +{ + qDebug() << "DumpGeoModelActionLocal::getParentNode()"; + + // check the current volume position in the geometry tree + GeoNodePath* path = getPath(); + unsigned int len = path->getLength(); + qDebug() << "length: " << len; + + // reset the number of visited node, if len is different than before + if (len > m_len) { + m_len_nChild = 0; + m_len = len; + } + // update number of visited nodes if len is the same as before + else { + ++m_len_nChild; + } + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = nullptr; + QVariant parentId = "NULL"; + QString parentType = "NULL"; + + if (len >= 1) + { + // get the parent node + parentNode = path->getItem(len-1); // i=(len-1) gives you the parent VPhysVol + + if (parentNode) { + + // get the parent type + parentType = getGeoTypeFromVPhysVol(parentNode); + + // get the parent memory address + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "-- parent's address:" << parentNode; + + // get the id of the parent node, which should be stored already in the DB + if (isAddressStored(parentAddress)) { + parentId = getStoredIdFromAddress(parentAddress); + } + else { + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + qWarning() << "The parent node of this child node seems to not having be stored in the DB yet! [It is normal if it is the root volume or a transformation node used for example only in the definition of a 'GeoShapeShift' instance]"; + } + qDebug() << "-- parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } + } + else{ + // qWarning() << "ERROR!! Len == 1, but this cannot be the Root volume!"; + qWarning() << "WARNING!! Len == 0, but this cannot be the Root volume!"; + } + + QStringList parentList; + parentList << parentId.toString() << parentType; + + return parentList; +} + + +//__________________________________________________________________ +QVariant DumpGeoModelActionLocal::storeShape(const GeoShape* shape) +{ + const QString shapeType = QString::fromStdString(shape->type()); + qDebug() << "storeShape() - shape name:" << shapeType << ", address:" << shape; + // get shape parameters + QString shapePars = getShapeParameters(shape); + // store the shape in the DB and returns the ID + return storeObj(shape, shapeType, shapePars); +} + + +//______________________________________________________________________ +QVariant DumpGeoModelActionLocal::storeMaterial(const GeoMaterial* mat) +{ + const QString matName = QString::fromStdString(mat->getName()); + qDebug() << "storeMaterial() - material name:" << matName << ", address:" << mat; + // store the material in the DB and returns the ID + return storeObj(mat, matName); +} + +//_______________________________________________________________________ +QVariant DumpGeoModelActionLocal::storeTranform(const GeoTransform* node) +{ + /* + * STORE THE OBJECT IN THE DB + */ + + QString address = getAddressStringFromPointer( node ); + + QVariant trId; + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "New Transform, storing it..."; + + + HepGeom::Transform3D tr = Amg::EigenTransformToCLHEP( node->getTransform() ); + + std::vector<double> params = getTransformParameters(tr); + qDebug() << "Transform parameters:" << QVector<double>::fromStdVector(params); + + /* + * STORE THE OBJECT IN THE DB + */ + + // store the object in the DB + if ( dynamic_cast<const GeoAlignableTransform*>(node) ) { + trId = storeObj(dynamic_cast<const GeoAlignableTransform*>(node), params); + qDebug() << "AlignableTransform stored. Id:" << trId.toString(); + } + else if ( dynamic_cast<const GeoTransform*>(node) ) { + trId = storeObj(dynamic_cast<const GeoTransform*>(node), params); + qDebug() << "Transform stored. Id:" << trId.toString(); + } + else { + qDebug() << "WARNING!!! - This type of transformation needs to be customized yet!!"; + } + + } else { + trId = getStoredIdFromAddress(address); + qDebug() << "Transform already stored in the DB. Id:" << trId.toString(); + } + + return trId; +} + + +void DumpGeoModelActionLocal::handleReferencedVPhysVol (const GeoVPhysVol *vol) +{ + qDebug() << "\nDumpGeoModelActionLocal::handleReferencedVPhysVol(GeoVPhysVol*)"; + + // qDebug() << "PhysVol's LogVol name:" << QString::fromStdString(vol->getLogVol()->getName()); + + // get the address string for the current volume + QString address = getAddressStringFromPointer( vol ); + + QVariant parentId = "NULL"; + + qDebug() << "setting 'unconnected' to: false"; + m_unconnectedTree = false; + + // get the parent volume, if this is not the Root volume + const GeoVPhysVol* parentNode = dynamic_cast<const GeoVPhysVol*>( &(*(vol->getParent() ))); + + if (parentNode) { + QString parentAddress = getAddressStringFromPointer(parentNode); + qDebug() << "--> parent's address:" << parentNode; + + if (isAddressStored(parentAddress)) + parentId = getStoredIdFromAddress(parentAddress); + // else + // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); + + qDebug() << "--> parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); + } + else { + qDebug() << "NULL parent node!! --> it seems to be an unconnected subtree."; + qDebug() << "setting 'unconnected' to: true"; + m_unconnectedTree = true; + } + + // // counting children + // unsigned int nChildren = vol->getNChildVols(); + // qDebug() << "number of child physical volumes:" << nChildren; + // qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; + // + // GeoCountVolAction cv; + // cv.setDepthLimit(1); + // vol->exec(&cv); + // int nChildCount = cv.getCount(); + // qDebug() << "number of child volumes:" << nChildCount; + + + + // check if this object has been stored already + if (! isAddressStored(address)) { + + qDebug() << "This is a new root PhysVol node of an 'unconnected' tree, so we start another action on it to dump it into the DB..."; + + // Dump the tree volumes into the DB + vol->exec(this); // TODO: check if the new action overwrites the id of the volumes already in the DB...!!! + + } else { + qDebug() << "The referenced volume has been stored already. Skipping..."; + } + // at the end, we make sure we reset the status + qDebug() << "setting 'unconnected' to: false"; + m_unconnectedTree = false; +} + + +// Get shape parameters +QString DumpGeoModelActionLocal::getShapeParameters(const GeoShape* shape) +{ + const QString shapeType = QString::fromStdString(shape->type()); + qDebug() << "shapeType:" << shapeType; + + QString shapePars = ""; + + if (shapeType == "Box") { + qDebug() << "get GeoBox parameters"; + QStringList pars; + const GeoBox* box = dynamic_cast<const GeoBox*>(shape); + pars << "XHalfLength=" + QString::number(box->getXHalfLength()) ; + pars << "YHalfLength=" + QString::number(box->getYHalfLength()) ; + pars << "ZHalfLength=" + QString::number(box->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Cons") { + QStringList pars; + const GeoCons* shapeIn = dynamic_cast<const GeoCons*>(shape); + pars << "RMin1=" + QString::number(shapeIn->getRMin1()) ; + pars << "RMin2=" + QString::number(shapeIn->getRMin2()) ; + pars << "RMax1=" + QString::number(shapeIn->getRMax1()) ; + pars << "RMax2=" + QString::number(shapeIn->getRMax2()) ; + pars << "DZ=" + QString::number(shapeIn->getDZ()) ; + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Para") { + QStringList pars; + const GeoPara* shapeIn = dynamic_cast<const GeoPara*>(shape); + pars << "XHalfLength=" + QString::number(shapeIn->getXHalfLength()) ; + pars << "YHalfLength=" + QString::number(shapeIn->getYHalfLength()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "Alpha=" + QString::number(shapeIn->getAlpha()) ; + pars << "Theta=" + QString::number(shapeIn->getTheta()) ; + pars << "Phi=" + QString::number(shapeIn->getPhi()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Pcon") { + QStringList pars; + const GeoPcon* shapeIn = dynamic_cast<const GeoPcon*>(shape); + pars << "SPhi=" + QString::number(shapeIn->getSPhi()); + pars << "DPhi=" + QString::number(shapeIn->getDPhi()); + // get number of Z planes and loop over them + const int nZplanes = shapeIn->getNPlanes(); + pars << "NZPlanes=" + QString::number(nZplanes); + for (int i=0; i<nZplanes; ++i) { + pars << "ZPos=" + QString::number(shapeIn->getZPlane(i)); + pars << "ZRmin=" + QString::number(shapeIn->getRMinPlane(i)); + pars << "ZRmax=" + QString::number(shapeIn->getRMaxPlane(i)); + } + shapePars = pars.join(";"); + } else if (shapeType == "Pgon") { + QStringList pars; + const GeoPgon* shapeIn = dynamic_cast<const GeoPgon*>(shape); + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + pars << "NSides=" + QString::number(shapeIn->getNSides()) ; + // get number of Z planes and loop over them + const int nZplanes = shapeIn->getNPlanes(); + pars << "NZPlanes=" + QString::number(nZplanes); + for (int i=0; i<nZplanes; ++i) { + pars << "ZPos=" + QString::number(shapeIn->getZPlane(i)); + pars << "ZRmin=" + QString::number(shapeIn->getRMinPlane(i)); + pars << "ZRmax=" + QString::number(shapeIn->getRMaxPlane(i)); + } + shapePars = pars.join(";"); + } else if (shapeType == "SimplePolygonBrep") { + QStringList pars; + const GeoSimplePolygonBrep* shapeIn = dynamic_cast<const GeoSimplePolygonBrep*>(shape); + pars << "DZ=" + QString::number(shapeIn->getDZ()) ; + // get number of vertices and loop over them + const int nVertices = shapeIn->getNVertices(); + pars << "NVertices=" + QString::number(nVertices); + for (int i=0; i<nVertices; ++i) { + pars << "xV=" + QString::number(shapeIn->getXVertex(i)); + pars << "yV=" + QString::number(shapeIn->getYVertex(i)); + } + shapePars = pars.join(";"); + } else if (shapeType == "Trap") { + QStringList pars; + const GeoTrap* shapeIn = dynamic_cast<const GeoTrap*>(shape); + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "Theta=" + QString::number(shapeIn->getTheta()) ; + pars << "Phi=" + QString::number(shapeIn->getPhi()) ; + pars << "Dydzn=" + QString::number(shapeIn->getDydzn()) ; + pars << "Dxdyndzn=" + QString::number(shapeIn->getDxdyndzn()) ; + pars << "Dxdypdzn=" + QString::number(shapeIn->getDxdypdzn()) ; + pars << "Angleydzn=" + QString::number(shapeIn->getAngleydzn()) ; + pars << "Dydzp=" + QString::number(shapeIn->getDydzp()) ; + pars << "Dxdyndzp=" + QString::number(shapeIn->getDxdyndzp()) ; + pars << "Dxdypdzp=" + QString::number(shapeIn->getDxdypdzp()) ; + pars << "Angleydzp=" + QString::number(shapeIn->getAngleydzp()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Trd") { + QStringList pars; + const GeoTrd* shapeIn = dynamic_cast<const GeoTrd*>(shape); + pars << "XHalfLength1=" + QString::number(shapeIn->getXHalfLength1()) ; + pars << "XHalfLength2=" + QString::number(shapeIn->getXHalfLength2()) ; + pars << "YHalfLength1=" + QString::number(shapeIn->getYHalfLength1()) ; + pars << "YHalfLength2=" + QString::number(shapeIn->getYHalfLength2()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Tube") { + QStringList pars; + const GeoTube* tube = dynamic_cast<const GeoTube*>(shape); + pars << "RMin=" + QString::number(tube->getRMin()) ; + pars << "RMax=" + QString::number(tube->getRMax()) ; + pars << "ZHalfLength=" + QString::number(tube->getZHalfLength()) ; + shapePars = pars.join(";"); + } else if (shapeType == "Tubs") { + QStringList pars; + const GeoTubs* shapeIn = dynamic_cast<const GeoTubs*>(shape); + pars << "RMin=" + QString::number(shapeIn->getRMin()) ; + pars << "RMax=" + QString::number(shapeIn->getRMax()) ; + pars << "ZHalfLength=" + QString::number(shapeIn->getZHalfLength()) ; + pars << "SPhi=" + QString::number(shapeIn->getSPhi()) ; + pars << "DPhi=" + QString::number(shapeIn->getDPhi()) ; + shapePars = pars.join(";"); + } + else if (shapeType == "Intersection") { + qDebug() << "get GeoShapeIntersection parameters"; + QStringList pars; + const GeoShapeIntersection* shapeIn = dynamic_cast<const GeoShapeIntersection*>(shape); + // get the referenced Shape used in the 'union' operation, store it in the DB + const GeoShape* shapeOpA = shapeIn->getOpA(); + QVariant shapeIdA = storeShape(shapeOpA); + const GeoShape* shapeOpB = shapeIn->getOpB(); + QVariant shapeIdB = storeShape(shapeOpB); + pars << "opA=" + QString::number( shapeIdA.toUInt() ) ; + pars << "opB=" + QString::number( shapeIdB.toUInt() ) ; + shapePars = pars.join(";"); + } + else if (shapeType == "Shift") { + qDebug() << "get GeoShapeShift parameters"; + QStringList pars; + const GeoShapeShift* shapeIn = dynamic_cast<const GeoShapeShift*>(shape); + + // get the referenced Shape used in the 'shift' operation, store it in the DB + const GeoShape* shapeOp = shapeIn->getOp(); + QVariant shapeId = storeShape(shapeOp); + + // get the Transformation, store it in the DB + GeoTransform* transf = new GeoTransform( shapeIn->getX() ); + QVariant trId = storeTranform(transf); + + pars << "A=" + QString::number( shapeId.toUInt() ) ; + pars << "X=" + QString::number( trId.toUInt() ) ; + shapePars = pars.join(";"); + } + else if (shapeType == "Subtraction") { + qDebug() << "get GeoShapeSubtraction parameters"; + QStringList pars; + const GeoShapeSubtraction* shapeIn = dynamic_cast<const GeoShapeSubtraction*>(shape); + // get the referenced Shape used in the 'union' operation, store it in the DB + const GeoShape* shapeOpA = shapeIn->getOpA(); + QVariant shapeIdA = storeShape(shapeOpA); + const GeoShape* shapeOpB = shapeIn->getOpB(); + QVariant shapeIdB = storeShape(shapeOpB); + pars << "opA=" + QString::number( shapeIdA.toUInt() ) ; + pars << "opB=" + QString::number( shapeIdB.toUInt() ) ; + shapePars = pars.join(";"); + } + else if (shapeType == "Union") { + qDebug() << "get GeoShapeUnion parameters"; + QStringList pars; + const GeoShapeUnion* shapeIn = dynamic_cast<const GeoShapeUnion*>(shape); + + // get the referenced Shape used in the 'union' operation, store it in the DB + const GeoShape* shapeOpA = shapeIn->getOpA(); + QVariant shapeIdA = storeShape(shapeOpA); + const GeoShape* shapeOpB = shapeIn->getOpB(); + QVariant shapeIdB = storeShape(shapeOpB); + + pars << "opA=" + QString::number( shapeIdA.toUInt() ) ; + pars << "opB=" + QString::number( shapeIdB.toUInt() ) ; + shapePars = pars.join(";"); + } + else { + qDebug() << "WARNING!!! - Shape '" << shapeType << "' needs to be customized!!"; + } + + return shapePars; + +} + + +std::vector<double> DumpGeoModelActionLocal::getTransformParameters(HepGeom::Transform3D tr) +{ + std::vector<double> vec; + + vec.push_back(tr.xx()); + vec.push_back(tr.xy()); + vec.push_back(tr.xz()); + + vec.push_back(tr.yx()); + vec.push_back(tr.yy()); + vec.push_back(tr.yz()); + + vec.push_back(tr.zx()); + vec.push_back(tr.zy()); + vec.push_back(tr.zz()); + + vec.push_back(tr.dx()); + vec.push_back(tr.dy()); + vec.push_back(tr.dz()); + + return vec; +} + + +DumpGeoModelActionLocal::DumpGeoModelActionLocal(GMDBManager &db) +{ + qDebug() << "DumpGeoModelActionLocal: constructor"; + + // init variables + m_len = 0; + m_len_nChild = 0; + m_rootVolumeFound = false; + m_unconnectedTree = false; + + // init anche check the database handle + m_dbManager = &db; + if (m_dbManager->isOpen()) { + qDebug() << "OK! Database is open!"; + } + else { + qDebug() << "Database is not open!"; + } + + m_dbpath = m_dbManager->getDBFilePath(); + + // get DB metadata + m_memMap_Tables = m_dbManager->getAll_NodeTypesTableIDs(); + // qDebug() << "m_memMap_Tables:" << m_memMap_Tables; + +} + +DumpGeoModelActionLocal::~DumpGeoModelActionLocal() +{ + // nothing to do so far... +} + + +void DumpGeoModelActionLocal::showMemoryMap() +{ + qDebug() << "DumpGeoModelActionLocal::showMemoryMap()"; + + QMap<QString, QVariant>::const_iterator it = m_memMap.constBegin(); + while (it != m_memMap.constEnd()) { + std::cout << it.key().toStdString() << ": " << it.value().toString().toStdString() << std::endl; + ++it; + } +} + + + +QVariant DumpGeoModelActionLocal::storeObj(const GeoMaterial* pointer, const QString name) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoMaterial*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant materialId; + + if (! isAddressStored(address)) { + qDebug() << "New Material! Storing it..."; + + // materialId = m_dbManager->addMaterial(name); + materialId = addMaterial(name); + + storeAddress( address, materialId ); + } + else { + qDebug() << "Material node stored already. Getting ID from the memory map..."; + materialId = getStoredIdFromAddress(address); + } + qDebug() << "materialId:" << materialId; + return materialId; +} + + +QVariant DumpGeoModelActionLocal::storeObj(const GeoShape* pointer, const QString name, const QString parameters) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoShape*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant shapeId; + if (! isAddressStored(address)) { + qDebug() << "New Shape! Storing it..."; + + // shapeId = m_dbManager->addShape(name, parameters); + shapeId = addShape(name, parameters); + + storeAddress( address, shapeId); + } + else { + qDebug() << "Shape node stored already. Getting ID from the memory map..."; + shapeId = getStoredIdFromAddress(address); + } + qDebug() << "shapeId:" << shapeId; + return shapeId; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoLogVol* pointer, const QString name, const QVariant shapeId, const QVariant materialId) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoLogVol*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant logvolId; + if (! isAddressStored(address)) { + qDebug() << "New LogVol! Storing it..."; + + // logvolId = m_dbManager->addLogVol(name, shapeId, materialId); + logvolId = addLogVol(name, shapeId, materialId); + + storeAddress( address, logvolId ); + } + else { + qDebug() << "LogVol node stored already. Getting ID from the memory map..."; + logvolId = getStoredIdFromAddress(address); + } + qDebug() << "logvolId:" << logvolId; + return logvolId; +} + + +QVariant DumpGeoModelActionLocal::storeObj(const GeoPhysVol* pointer, const QVariant logvolId, const QVariant parentId, bool isRootVolume) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoPhysVol*) - address:" << pointer << "- is root volume?" << isRootVolume; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant physvolId; + if (! isAddressStored(address)) { + qDebug() << "New PhysVol! Storing it..."; + + // physvolId = m_dbManager->addPhysVol(logvolId, parentId, isRootVolume); + physvolId = addPhysVol(logvolId, parentId, isRootVolume); + + storeAddress( address, physvolId ); + } + else { + qDebug() << "PhysVol node stored already. Getting ID from the memory map..."; + physvolId = getStoredIdFromAddress(address); + } + qDebug() << "physvolId:" << physvolId; + return physvolId; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoFullPhysVol* pointer, const QVariant logvolId, const QVariant parentId, bool isRootVolume) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoFullPhysVol*) - address:" << pointer << "- is root volume?" << isRootVolume; + + QString address = getAddressStringFromPointer( pointer ); + + QVariant physvolId; + if (! isAddressStored(address)) { + qDebug() << "New FullPhysVol! Storing it..."; + + // physvolId = m_dbManager->addFullPhysVol(logvolId, parentId, isRootVolume); + physvolId = addFullPhysVol(logvolId, parentId, isRootVolume); + + storeAddress( address, physvolId ); + } + else { + qDebug() << "FullPhysVol node stored already. Getting ID from the memory map..."; + physvolId = getStoredIdFromAddress(address); + } + qDebug() << "fullphysvolId:" << physvolId; + return physvolId; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoSerialDenominator* pointer, const QString baseName) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoSerialDenominator*) - baseName:" << baseName << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialDenominator! Storing it..."; + + // id = m_dbManager->addSerialDenominator(baseName); + id = addSerialDenominator(baseName); + + storeAddress( address, id ); + } + else { + qDebug() << "SerialDenominator node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + + +QVariant DumpGeoModelActionLocal::storeObj(const GeoSerialTransformer* pointer, const QVariant functionId, const QVariant volId, const QString volType, const unsigned int copies) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoSerialTransformer*):" << volId.toUInt() << volType << "- n. of copies: " << copies; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialTransformer! Storing it..."; + + // id = m_dbManager->addSerialTransformer(functionId, volId, volType, copies); + id = addSerialTransformer(functionId, volId, volType, copies); + + storeAddress( address, id ); + } + else { + qDebug() << "SerialTransformer node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoXF::Function* pointer, const QString expression) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoXF::Function*)"; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + + // id = m_dbManager->addFunction(expression); + id = addFunction(expression); + + storeAddress( address, id ); + } + else { + qDebug() << "GeoXF::Function node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoTransform* pointer, std::vector<double> parameters) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoTransform*)"; + + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + + // id = m_dbManager->addTransform( QVector<double>::fromStdVector(parameters) ); + id = addTransform( parameters ); + + storeAddress( address, id ); + } + else { + qDebug() << "GeoTransform node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +QVariant DumpGeoModelActionLocal::storeObj(const GeoAlignableTransform* pointer, std::vector<double> parameters) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoAlignableTransform*)"; + + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New GeoXF::Function! Storing it..."; + + // id = m_dbManager->addAlignableTransform( QVector<double>::fromStdVector(parameters) ); + id = addAlignableTransform( parameters ); + + storeAddress( address, id ); + } + else { + qDebug() << "GeoAlignableTransform node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + + +QVariant DumpGeoModelActionLocal::storeObj(const GeoNameTag* pointer, const QString name) +{ + qDebug() << "DumpGeoModelActionLocal::storeObj(GeoNameTag*) - name:" << name << "address:" << pointer; + + QString address = getAddressStringFromPointer( pointer ); + QVariant id; + + if (! isAddressStored(address)) { + qDebug() << "New SerialDenominator! Storing it..."; + + // id = m_dbManager->addNameTag(name); + id = addNameTag(name); + + storeAddress( address, id ); + } + else { + qDebug() << "SerialDenominator node stored already. Getting ID from the memory map..."; + id = getStoredIdFromAddress(address); + } + qDebug() << "ID:" << id; + return id; +} + +/* +// OLD // FIXME: to be removed when all objects will be migrated to the new version +void DumpGeoModelActionLocal::storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int childPos, const QString childType) +{ + qDebug() << "DumpGeoModelActionLocal::storeChildPosition()"; + // m_dbManager->addChildPosition(parentId, parentType, childId, childPos, childType); + // if () + addChildPosition(parentId, parentType, childId, childPos, childType); + return; +} +*/ +// NEW +void DumpGeoModelActionLocal::storeChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int parentCopyN, const unsigned int childPos, const QString childType, const unsigned int childCopyN) +{ + qDebug() << "DumpGeoModelActionLocal::storeChildPosition()"; + addChildPosition(parentId, parentType, childId, parentCopyN, childPos, childType, childCopyN); // FIXME: change the positions of the parameters to a more logical order, like: parentID, parentType, parentCopyN, childPos, ChildType, childId, childCopyN + return; +} + + +unsigned int DumpGeoModelActionLocal::addRecord(std::vector<QStringList>* container, const QStringList values) const +{ + container->push_back(values); + unsigned int idx = container->size(); // index of pushed element = size after pushing, to match ID starting at 1 in the DB + return idx; +} + +QVariant DumpGeoModelActionLocal::addMaterial(const QString name) +{ + qDebug() << "DumpGeoModelActionLocal::addMaterial(QString*) - name:" << name; + std::vector<QStringList>* container = &_materials; + QStringList values; + values << name; + return QVariant( addRecord(container, values) ); +} + +QVariant DumpGeoModelActionLocal::addNameTag(const QString name) +{ + qDebug() << "DumpGeoModelActionLocal::addNameTag(QString*) - name:" << name; + std::vector<QStringList>* container = &_nameTags; + QStringList values; + values << name; + return QVariant( addRecord(container, values) ); +} + +QVariant DumpGeoModelActionLocal::addSerialDenominator(const QString &baseName) +{ + qDebug() << "DumpGeoModelActionLocal::addSerialDenominator(QString*) - basename:" << baseName; + std::vector<QStringList>* container = &_serialDenominators; + QStringList values; + values << baseName; + return QVariant( addRecord(container, values) ); +} + + +QVariant DumpGeoModelActionLocal::addFunction(const QString expression) +{ + qDebug() << "DumpGeoModelActionLocal::addFunction(QString*) - expression:" << expression; + std::vector<QStringList>* container = &_functions; + QStringList values; + values << expression; + return QVariant( addRecord(container, values) ); +} + + +QVariant DumpGeoModelActionLocal::addAlignableTransform(const std::vector<double> params) +{ + qDebug() << "DumpGeoModelActionLocal::addAlignableTransform(QString*)"; + std::vector<QStringList>* container = &_alignableTransforms; + QStringList values; + foreach(double par, params) { + values << QString::number(par); + } + return QVariant( addRecord(container, values) ); +} + + + +QVariant DumpGeoModelActionLocal::addTransform(const std::vector<double> params) +{ + qDebug() << "DumpGeoModelActionLocal::addTransform(QString*)"; + std::vector<QStringList>* container = &_transforms; + QStringList values; + foreach(double par, params) { + values << QString::number(par); + } + return QVariant( addRecord(container, values) ); +} + +QString DumpGeoModelActionLocal::getIdFromNodeType( QString nodeType ) +{ + qDebug() << "getIdFromNodeType(" << nodeType <<")"; + if (m_memMap_Tables.contains(nodeType)) + return QString::number(m_memMap_Tables.value(nodeType)); + else + return QString("NULL"); +} + +QVariant DumpGeoModelActionLocal::addSerialTransformer(const QVariant &funcId, const QVariant &physvolId, const QString volType, const unsigned int &copies) +{ + qDebug() << "DumpGeoModelActionLocal::addSerialTransformer()"; + std::vector<QStringList>* container = &_serialTransformers; + QString volTypeID = getIdFromNodeType(volType); + + QStringList values; + values << funcId.toString() << physvolId.toString() << volTypeID << QString::number(copies); + + return QVariant( addRecord(container, values) ); +} + +QVariant DumpGeoModelActionLocal::addShape(const QString &type, const QString ¶meters) +{ + std::vector<QStringList>* container = &_shapes; + QStringList values; + values << type << parameters; + return QVariant( addRecord(container, values) ); +} + + +QVariant DumpGeoModelActionLocal::addPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume) +{ + std::vector<QStringList>* container = &_physVols; + + QStringList values; + values << logVolId.toString() << parentPhysVolId.toString(); // TODO: we should remove the parent info: it's not complete because the type is missing (PhysVol or FullPhysVol) and it's redundant, because we store the childrenPositions. It's only useful for quick visual debug, by dumping the PhysVol DB table + + unsigned int idx = addRecord(container, values); + + if (isRootVolume) { + QStringList rootValues; + rootValues << QString::number(idx) << "GeoPhysVol"; + _rootVolume = rootValues; + } + return QVariant(idx); +} + + +QVariant DumpGeoModelActionLocal::addFullPhysVol(const QVariant &logVolId, const QVariant &parentPhysVolId, bool isRootVolume) +{ + std::vector<QStringList>* container = &_fullPhysVols; + + QStringList values; + values << logVolId.toString() << parentPhysVolId.toString(); // TODO: we should remove the parent info: it's not complete because the type is missing (PhysVol or FullPhysVol) and it's redundant, because we store the childrenPositions. It's only useful for quick visual debug, by dumping the PhysVol DB table + + unsigned int idx = addRecord(container, values); + + if (isRootVolume) { + QStringList rootValues; + rootValues << QString::number(idx) << "GeoFullPhysVol"; + _rootVolume = rootValues; + } + return QVariant(idx); +} + +QVariant DumpGeoModelActionLocal::addLogVol(const QString &name, const QVariant &shapeId, const QVariant &materialId) +{ + std::vector<QStringList>* container = &_logVols; + QStringList values; + values << name << shapeId.toString() << materialId.toString(); + return QVariant( addRecord(container, values) ); +} + +/* +// OLD // FIXME: to be removed when all objects will be migrated to the new version +void DumpGeoModelActionLocal::addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int childPos, const QString childType) +{ + std::vector<QStringList>* container = &_childrenPositions; + + QString parentTableID = getIdFromNodeType(parentType); + QString childTableID = getIdFromNodeType(childType); + + QStringList values; + values << parentId.toString() << parentTableID << QString("") << QString::number(childPos) << childTableID << childId.toString() << QString(""); + addRecord(container, values); + return; +} +*/ + +// NEW +void DumpGeoModelActionLocal::addChildPosition(const QVariant parentId, const QString parentType, const QVariant childId, const unsigned int parentCopyN, const unsigned int childPos, const QString childType, const unsigned int childCopyN) +{ + std::vector<QStringList>* container = &_childrenPositions; + + QString parentTableID = getIdFromNodeType(parentType); + QString childTableID = getIdFromNodeType(childType); + + QStringList values; + values << parentId.toString() << parentTableID << QString::number(parentCopyN) << QString::number(childPos) << childTableID << childId.toString() << QString::number(childCopyN); + addRecord(container, values); + return; +} + + +void DumpGeoModelActionLocal::saveToDB() +{ + qDebug() << "DumpGeoModelActionLocal::savetoDB()"; + std::cout << "saving to file: " << m_dbpath.toStdString() << std::endl; + + m_dbManager->addListOfRecords("GeoMaterial", _materials); + m_dbManager->addListOfRecords("GeoNameTag", _nameTags); + m_dbManager->addListOfRecords("GeoAlignableTransform", _alignableTransforms); + m_dbManager->addListOfRecords("GeoTransform", _transforms); + m_dbManager->addListOfRecords("Function", _functions); + m_dbManager->addListOfRecords("GeoSerialTransformer", _serialTransformers); + m_dbManager->addListOfRecords("GeoShape", _shapes); + m_dbManager->addListOfRecords("GeoSerialDenominator", _serialDenominators); + m_dbManager->addListOfRecords("GeoPhysVol", _physVols); + m_dbManager->addListOfRecords("GeoFullPhysVol", _fullPhysVols); + m_dbManager->addListOfRecords("GeoLogVol", _logVols); + + m_dbManager->addListOfChildrenPositions(_childrenPositions); + m_dbManager->addRootVolume(_rootVolume); + + return; +} + + + + + + +void DumpGeoModelActionLocal::storeAddress(const QString address, QVariant id) +{ + qDebug() << "DumpGeoModelActionLocal::storeAddress(" << address << "," << id << ")"; + m_memMap.insert(address, id); +} + +bool DumpGeoModelActionLocal::isAddressStored(const QString address) +{ + qDebug() << "DumpGeoModelActionLocal::isAddressStored(): " << address; + //showMemoryMap(); // only for Debug + return m_memMap.contains(address); +} + + +QVariant DumpGeoModelActionLocal::getStoredIdFromAddress(QString address) +{ + qDebug() << "DumpGeoModelActionLocal::getStoredIdFromAddress(): " << address; + return m_memMap.value(address); +} + +// get pointer string +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoMaterial* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoMaterial*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoShape* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoShape*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoLogVol* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoLogVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoPhysVol* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoPhysVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoVPhysVol* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoVPhysVol*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +// get pointer string +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoSerialDenominator* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoSerialDenominator*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoSerialTransformer* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoSerialTransformer*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoXF::Function* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoXF::Function*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoTransform* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoTransform*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelActionLocal::getAddressStringFromPointer(const GeoNameTag* pointer) +{ + qDebug() << "DumpGeoModelActionLocal::getAddressStringFromPointer(GeoNameTag*)"; + std::ostringstream oss; + oss << pointer; + return getQStringFromOss(oss); +} + +QString DumpGeoModelActionLocal::getQStringFromOss(std::ostringstream &oss) +{ + qDebug() << "DumpGeoModelActionLocal::getQStringFromOss()"; + std::string addr = oss.str(); + QString address = QString::fromStdString(addr); + qDebug() << "address string:" << address; + return address; +} + + +//bool DumpGeoModelActionLocal::isObjectStored(const GeoMaterial* pointer) +//{ +// qDebug() << "DumpGeoModelActionLocal::isObjectStored(const GeoMaterial*)"; +// return isAddressStored(getAddressStringFromPointer( pointer) ); +//} +// +//bool DumpGeoModelActionLocal::isObjectStored(const GeoGraphNode* pointer) +//{ +// qDebug() << "DumpGeoModelActionLocal::isObjectStored(const GeoGraphNode*)"; +//// return isAddressStored(address); +//} + + + +// void DumpGeoModelActionLocal::handlePhysVol (const GeoPhysVol *vol) +// { +// qDebug() << "\nDumpGeoModelActionLocal::handlePhysVol(GeoPhysVol*)"; +// +// // get the address string for the current volume +// QString address = getAddressStringFromPointer( vol ); +// +// // variables used to persistify the object +// QVariant parentId; +// QVariant physId; +// +// // check the volume position in the geometry tree +// GeoNodePath* path = getPath(); +// unsigned int len = path->getLength(); +// qDebug() << "length: " << len; +// // std::cout << "path: " << path << std::endl; +// +// // const GeoVPhysVol* parentNode; +// +// // this below is performed until the root volume is found, then "length" is not used anymore, +// // because not updated when recursively visiting PhysVols +// bool getParentNode = true; +// bool storeRootVolume = false; +// if ( ! m_rootVolumeFound) { +// if (len > 1) { +// getParentNode = true; +// } else{ +// qDebug() << "This is the Root volume!"; +// m_rootVolumeFound = true; +// storeRootVolume = true; +// getParentNode = false; +// } +// } else { +// getParentNode = true; +// } +// +// // get the parent volume, if this is not the Root volume +// if (getParentNode) { +// +// const GeoPhysVol* parentNode = dynamic_cast<const GeoPhysVol*>( &(*(vol->getParent() ))); +// +// if (parentNode) { +// QString parentAddress = getAddressStringFromPointer(parentNode); +// qDebug() << "parent's address:" << parentNode; +// +// if (isAddressStored(parentAddress)) +// parentId = getStoredIdFromAddress(parentAddress); +// // else +// // qFatal("FATAL ERROR!!! - The parent node of this child should has been stored in the DB already, but it was not found!!"); +// +// qDebug() << "parent's LogVol name:" << QString::fromStdString(parentNode->getLogVol()->getName()); +// } +// else { +// qDebug() << "NULL parent node!!"; +// } +// } +// +// // counting children +// unsigned int nChildren = vol->getNChildVols(); +// qDebug() << "number of child physical volumes:" << nChildren; +// qDebug() << "[number of PhysVol and SerialTransformer child nodes:" << vol->getNChildVolAndST() << "]"; +// +// GeoCountVolAction cv; +// cv.setDepthLimit(1); +// vol->exec(&cv); +// int nChildCount = cv.getCount(); +// qDebug() << "number of child volumes:" << nChildCount; +// +// +// +// // check if this object has been stored already +// if (! isAddressStored(address)) { +// +// qDebug() << "New PhysVol, storing it..."; +// +// /* +// * PhysVol features: +// * - 1 parent PhysVol (if any) +// * - 1 LogVol +// * - 1 Material +// * - 1 Shape +// */ +// +// // Note: PhysVol has no name. Its LogVol has a name. +// // const std::string name = vol->getLogVol()->getName(); +// +// // LOGVOL +// const GeoLogVol* logVol = vol->getLogVol(); +// const QString logName = QString::fromStdString(logVol->getName()); +// qDebug() << "LogVol name:" << logName; +// +// +// // MATERIAL +// const GeoMaterial * mat = vol->getLogVol()->getMaterial(); +// const QString matName = QString::fromStdString(mat->getName()); +// qDebug() << "material name:" << matName << ", address:" << mat; +// +// +// // SHAPE +// const GeoShape * shape = vol->getLogVol()->getShape(); +// const QString shapeType = QString::fromStdString(shape->type()); +// qDebug() << "shape name:" << shapeType << ", address:" << shape; +// +// // shape parameters +// QString shapePars = ""; +// if (shapeType == "Box") { +// QStringList pars; +// const GeoBox* box = dynamic_cast<const GeoBox*>(shape); +// pars << "XHalfLength=" + QString::number(box->getXHalfLength()) ; +// pars << "YHalfLength=" + QString::number(box->getYHalfLength()) ; +// pars << "ZHalfLength=" + QString::number(box->getZHalfLength()) ; +// shapePars = pars.join(";"); +// } +// +// /* +// * STORE THE OBJECTS IN THE DB +// */ +// +// // store/get the Material object into/from the DB +// QVariant matId; +// matId = storeObj(mat, matName); +// +// // store/get the Shape object into/from the DB +// QVariant shapeId; +// shapeId = storeObj(shape, shapeType, shapePars); +// +// // store/get the LogVol object into/from the DB +// QVariant logvolId; +// logvolId = storeObj(logVol, logName, shapeId, matId); +// +// // store the PhysVol volume into the DB +// physId = storeObj(vol, logvolId, parentId, storeRootVolume); // with parent info +// qDebug() << "PhysVol stored. Id:" << physId.toString(); +// +// } else { +// // qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map and moving to its physical children..."; +// qDebug() << "Volume stored already. It is a shared volume. Taking ID from memory map..."; +// physId = getStoredIdFromAddress(address); +// qDebug() << "PhysVol Id:" << physId; +// } +// +// +// // store the parent-child relationship in the DB +// storeChildPosition(parentId, physId, getChildPosition( parentId.toUInt() ), "GeoPhysVol"); +// + + /* Now we need to loop over children, to be sure all volumes are take. + That's because it seems that the action only goes to children that are 'attached' + to the tree with a parent-child relationship. For example I have a pInnerPassive PhysVol + added to a pPassive PhysVol; the latter is refeneced in a SerialTransformer. + pPassive is visited because of our implementation of the handleSerialTrasformer() method, + but the pInnerPassive is never visited. + */ + // if (nChildren > 0) { + // qDebug() << "Looping over the children..."; + // + // for (unsigned int i=0; i<nChildren; ++i) { + // + // unsigned int childPos = i; + // + // // get the name of the i-th child volume + // QString childName = QString::fromStdString(vol->getNameOfChildVol(i)); + // qDebug() << "\t" << i << " childName:" << childName; + // + // // Returns the i-th child volume + // + // // GEOPHYSVOL child + // if ( dynamic_cast<const GeoPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoPhysVol"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoPhysVol* childVol = dynamic_cast<const GeoPhysVol*>(childVolV); + // + // handlePhysVol(childVol); // recursive call + // + // } else { + // qCritical("\t\tERROR!! the child is not a persistified volume/node!!!"); + // return; + // } + // } + // } + + // if (nChildren > 0) { + // for (unsigned int i=0; i<nChildren; ++i) { + // + // unsigned int childPos = i; + // + // // get the name of the i-th child volume + // QString childName = QString::fromStdString(vol->getNameOfChildVol(i)); + // qDebug() << "\t" << i << " childName:" << childName; + // + // // Returns the i-th child volume + // + // // GEOPHYSVOL child + // if ( dynamic_cast<const GeoPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoPhysVol"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoPhysVol* childVol = dynamic_cast<const GeoPhysVol*>(childVolV); + // + // + // // check if child volume has been stored already. If not, store it. + // if ( ! isAddressStored( getAddressStringFromPointer( childVol )) ) { + // + // // MATERIAL + // const GeoMaterial * mat = childVol->getLogVol()->getMaterial(); + // const QString matName = QString::fromStdString(mat->getName()); + // qDebug() << "Child material name:" << matName; + // + // // SHAPE + // const GeoShape * shape = childVol->getLogVol()->getShape(); + // const QString shapeType = QString::fromStdString(shape->type()); + // qDebug() << "Child shape name:" << shapeType; + // + // // LOGVOL + // const GeoLogVol* logVol = childVol->getLogVol(); + // const QString logName = QString::fromStdString(logVol->getName()); + // qDebug() << "Child LogVol name:" << logName; + // + // + // /* + // * STORE THE OBJECTS IN THE DB + // */ + // + // // store the Material object in the DB + // QVariant child_matId = storeObj(mat, matName); + // + // // store the Shape object in the DB + // QVariant child_shapeId = storeObj(shape, shapeType); + // + // // store the LogVol volume in the DB + // QVariant child_logvolId = storeObj(logVol, logName, child_shapeId, child_matId); + // + // // store the PhysVol volume in the DB + // storeObj(childVol, child_logvolId, physId); + // + // // store the parent-child relationship in the DB + // storeChildPosition(physId, childVol, childPos); + // + // } else { + // qDebug() << "Child volume stored already. Moving to the next one..."; + // } + // + // } + // // GeoSerialDenominator child + // else if ( dynamic_cast<const GeoSerialDenominator*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoSerialDenominator"; + // //qWarning() << "\t\t" << "to be implemented!!!"; + // const GeoVPhysVol *childVolV = &(*(vol->getChildVol(i))); + // const GeoSerialDenominator* childVol = dynamic_cast<const GeoSerialDenominator*>(childVolV); + // + // std::string baseNameStr = childVol->getBaseName(); + // QString baseName = QString::fromStdString(baseNameStr); + // + // QString address = getAddressStringFromPointer( childVol ); + // + // qDebug() << "base name:" << baseName << "address:" << address; + // + // QVariant sdId; + // + // // check if this object has been stored already + // if (! isAddressStored(address)) { + // // store the SerialDenominator object in the DB + // qDebug() << "New SerialDenominator, storing it..."; + // sdId = storeObj(childVol, baseName); + // qDebug() << "SerialDenominator stored. Id:" << sdId.toString(); + // + // } else { + // sdId = getStoredIdFromAddress(address); + // qDebug() << "SerialDenominator already stored in the DB. Got id:" << sdId.toString(); + // } + // + // // store the parent-child relationship in the DB + // storeChildPosition(physId, childVol, childPos); + // + // } + // // GEOFULLPHYSVOL child + // else if ( dynamic_cast<const GeoFullPhysVol*>( &(*(vol->getChildVol(i) ))) ) { + // qDebug() << "\t\t" << "the child" << i << "is a GeoFullPhysVol"; + // qWarning() << "\t\t" << "to be implemented!!!"; + // // const GeoVFullPhysVol *childVolV = &(*(vol->getChildVol(i))); + // // const GeoFullPhysVol* childVol = dynamic_cast<const GeoFullPhysVol*>(childVolV); + // } + // else { + // qCritical("\t\tERROR!! the child is not a persistified volume/node!!!"); + // return; + // } + // + // + // // examples: + // //const GeoVPhysVol *child=&(*(pv->getChildVol(i))); + // // + // //if ( dynamic_cast<const GeoLogVol*>( &(*(vol->getChildVol(i) ))) ) + // // qDebug() << "\t\t" << "the child" << i << "is a GeoLogVol"; + // + // + // + // /* + // unsigned int nchildvol = pvc->getNChildVols(); + // int lgg = 0; + // int llay = 0; + // std::string::size_type npos; + // for (unsigned ich=0; ich<nchildvol; ++ich) { + // PVConstLink pc = pvc->getChildVol(ich); + // std::string childname = (pc->getLogVol())->getName(); + // if ((npos = childname.find("layer")) != std::string::npos ) { + // llay ++; + // //std::cerr<<" navigating RPC named " + // // <<tname<<" child " + // // <<ich<<" is a layer with tag "<<llay<<std::endl; + // unsigned int nch1 = pc->getNChildVols(); + // lgg = 0; + // for (unsigned ngv=0; ngv<nch1; ++ngv) { + // PVConstLink pcgv = pc->getChildVol(ngv); + // std::string childname1 = (pcgv->getLogVol())->getName(); + // if ((npos = childname1.find("gas volume")) != std::string::npos ) { + // lgg ++; + // //std::cerr<<" navigating RPC named " + // // <<tname<<" child " + // // <<ngv<<" is a gas volume with tag "<<lgg<<std::endl; + // PVConstLink pcgg = pcgv->getChildVol(0); + // HepGeom::Transform3D trans = pvc->getXToChildVol(ich)*pc->getXToChildVol(ngv)*pcgv->getXToChildVol(0); + // m_Xlg[llay-1][lgg-1] = Amg::CLHEPTransformToEigen(trans); + // } + // } + // } + // } + // */ + // + // } + // } + + + // else { + // qDebug() << "Object stored already. Moving to next one..."; + // } +// } diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/WriteGeoModelAction.cxx.oldSqlite b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/WriteGeoModelAction.cxx.oldSqlite new file mode 100644 index 0000000000000000000000000000000000000000..91aee8c405f539bba6e13f4a6c1774ef50132ffa --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite/src/WriteGeoModelAction.cxx.oldSqlite @@ -0,0 +1,663 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + + +// local includes +#include "GeoWrite/WriteGeoModelAction.h" + +// C++ includes +#include <sstream> + +// Qt includes +//#include <QtSql> +#include <QtDebug> + + +WriteGeoModelAction::WriteGeoModelAction (std::ostream &o, MemMap& m, sqlite3 *db) // TODO: remove db from signature +: m_nameTag(NULL), + m_serialDenominator(NULL), + m_idTag(NULL), + m_transformState(true), + m_volumeState(true), + m_nametagState(true), + m_serialDenominatorState(true), + m_serialTransformerState(true), + m_identifierState(true), + m_o(o), + m_map(m), + //m_db(db), + m_id(0), + m_indented(false) +{ + + qDebug() << "WriteGeoModelAction::constructor(). Start..."; + +// m_db = QSqlDatabase::addDatabase("QSQLITE"); +//// m_db.setDatabaseName(path); +// m_db.setDatabaseName("test_Qt.db"); +// +// if (!m_db.open()) +// { +// qDebug() << "Error: connection with database fail"; +// } +// else +// { +// qDebug() << "Database: connection ok"; +// } + + + // /* Open database */ + // rc = sqlite3_open("test.db", &m_db); + // + // if( rc ){ + // fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); + // exit(0); + // }else{ + // fprintf(stderr, "Opened database successfully\n"); + // } + // + // /* Create the database table */ + // createTables(); + + // initialize the DB + //initDB(); + + //loadTestData(); + + qDebug() << "WriteGeoModelAction::constructor(). DONE."; +} + + +WriteGeoModelAction::~WriteGeoModelAction() { + qDebug() << "WriteGeoModelAction::destructor()."; +// if (m_db.isOpen()) +// { +// m_db.close(); +// } +} + + +bool WriteGeoModelAction::isOpen() const +{ + return m_db.isOpen(); +} + + +//## Other Operations (implementation) + + +void WriteGeoModelAction::handleTransform (const GeoTransform *xform) +{ + qDebug() << "WriteGeoModelAction::handleTransform(GeoTransform*)"; + + m_pendingTransformList.push_back(xform); + if (m_transformState) { + indent(); + m_o << "TRANSFORM (" << xform << ") + "; + } +} + +void WriteGeoModelAction::handlePhysVol (const GeoPhysVol *vol) +{ + qDebug() << "WriteGeoModelAction::handlePhysVol(GeoPhysVol*)"; + + const std::string name = vol->getLogVol()->getName(); + + const GeoLogVol* logVol = vol->getLogVol(); + + + const GeoMaterial * mat = vol->getLogVol()->getMaterial(); + const std::string matName = mat->getName(); + + const GeoShape * shape = vol->getLogVol()->getShape(); + const std::string shapeType = shape->type(); + + unsigned int length = getPath()->getLength(); + + if (m_volumeState) { + indent(); + m_o << "VOLUME(" << vol << ":GeoPhysVol:" << vol->getLogVol()->getName() << ":" << shapeType << ":" << matName << ":" << length << ")" << std::endl; + } + m_pendingTransformList.erase(m_pendingTransformList.begin(),m_pendingTransformList.end()); + m_indented=false; + + + + // std::ostringstream oss; + // oss << &vol; + // std::string address = oss.str(); + // + // // check if present in the map; if not, add it + // if ( ! (m_map.count(address) > 0) ) { + // m_map.emplace(address, 1); + // } + + + // check if present in the map; if not, add it and then persistify it +// if ( storeObj(vol) ) +// persistifyObj(vol); + +} + +void WriteGeoModelAction::handleFullPhysVol (const GeoFullPhysVol *vol) +{ + qDebug() << "WriteGeoModelAction::handleFullPhysVol(GeoFullPhysVol*)"; + + if (m_volumeState) { + + const std::string name = vol->getLogVol()->getName(); + const std::string matName = vol->getLogVol()->getMaterial()->getName(); + const std::string shapeType = vol->getLogVol()->getShape()->type(); + unsigned int length = getPath()->getLength(); + + indent(); + m_o << "VOLUME(" << vol << ":GeoFullPhysVol:" << name << ":" << shapeType << ":" << matName << ":" << length << ")" << std::endl; + } + m_pendingTransformList.erase(m_pendingTransformList.begin(),m_pendingTransformList.end()); + m_indented=false; +} + +void WriteGeoModelAction::handleNameTag (const GeoNameTag *nameTag) +{ + qDebug() << "WriteGeoModelAction::handleNameTag(GeoNameTag*)"; + + if (m_nametagState) { + indent(); + m_o << "NAMETAG(" << nameTag << ":" << nameTag->getName() << ") + "; + } +} + +void WriteGeoModelAction::handleSerialDenominator (const GeoSerialDenominator *sD) +{ + qDebug() << "WriteGeoModelAction::handleSerialDenominator(GeoSerialDenominator*)"; + + if (m_nametagState) { + indent(); + m_o << "SERIAL DENOMINATOR(" << sD << ":" << sD->getBaseName() << ") + \n"; + } + m_indented=false; +} + +void WriteGeoModelAction::handleSerialTransformer (const GeoSerialTransformer *sT) +{ + qDebug() << "WriteGeoModelAction::handleSerialTransformer(GeoSerialTransformer*)"; + + if (m_volumeState) { + + const GeoXF::Function * func = sT->getFunction(); + + indent(); + m_o << "SERIAL_TRANSFORMER: " << sT->getNCopies() << " PARAMETRIZED VOLUMES(" << sT << ":" << sT->getVolume()->getLogVol()->getName() << ":" << func << ")" << std::endl; + } + m_pendingTransformList.erase(m_pendingTransformList.begin(),m_pendingTransformList.end()); + m_indented=false; +} + +void WriteGeoModelAction::handleIdentifierTag (const GeoIdentifierTag *idTag) +{ + qDebug() << "WriteGeoModelAction::handleIdentifierTag(GeoIdentifierTag*)"; + + if (m_identifierState) { + indent(); + m_o << "NAME(" << idTag << ":" << idTag->getIdentifier() << ") + "; + } +} +//void WriteGeoModelAction::handleGeoShape (const GeoShape *shape) +//{ +// //## begin WriteGeoModelAction::handleIdentifierTag%3FB027EA0197.body preserve=yes +// if (m_identifierState) { +// indent(); +// m_o << "NAME(" << idTag << ":" << idTag->getIdentifier() << ") + "; +// } +// //## end WriteGeoModelAction::handleIdentifierTag%3FB027EA0197.body +//} + +void WriteGeoModelAction::setNotification (Type type, bool state) +{ + qDebug() << "WriteGeoModelAction::setNotification()"; + + std::cout << "setNotification()" << std::endl; + + if (type==TRANSFORM) { + m_transformState=state; + } + else if (type==VOLUME) { + m_volumeState=state; + } + else if (type==NAMETAG) { + m_nametagState=state; + } + else if (type==IDENTIFIERTAG) { + m_identifierState=state; + } + else if (type==IDENTIFIERTAG) { + m_identifierState=state; + } +} + +void WriteGeoModelAction::indent () +{ + if (!m_indented) { + m_indented=true; + for (size_t i=0;i<getPath()->getLength(); i++) { + m_o << " "; + } + } +} + + +int WriteGeoModelAction::storeObj(const GeoShape* pointer) +{ + qDebug() << "WriteGeoModelAction::storeObj(GeoShape*)"; + + std::ostringstream oss; + oss << &pointer; + std::string address = oss.str(); + + return storeAddress(address); +} + +int WriteGeoModelAction::storeObj(const GeoLogVol* pointer) +{ + qDebug() << "WriteGeoModelAction::storeObj(GeoLogVol*)"; + + std::ostringstream oss; + oss << &pointer; + std::string address = oss.str(); + + return storeAddress(address); +} + +int WriteGeoModelAction::storeObj(const GeoMaterial* pointer) +{ + qDebug() << "WriteGeoModelAction::storeObj(GeoMaterial*)"; + + std::ostringstream oss; + oss << &pointer; + std::string address = oss.str(); + + return storeAddress(address); +} + +int WriteGeoModelAction::storeObj(const GeoGraphNode* pointer) +{ + qDebug() << "WriteGeoModelAction::storeObj(GeoGraphNode*)"; + + std::ostringstream oss; + oss << &pointer; + std::string address = oss.str(); + + return storeAddress(address); +} + +int WriteGeoModelAction::storeAddress(const std::string address) +{ + qDebug() << "WriteGeoModelAction::storeAddress(): " << address.c_str(); + + // check if present in the map; if not, add it + if ( ! (m_map.count(address) > 0) ) { + ++m_id; + m_map.emplace(address, m_id); + + return m_id; // the object has been added to the map + } + + int objId = 0; + // m_map.find( address ) + // std::unordered_map<std::string, int>::const_iterator got = m_map.find (input); + MemMap::const_iterator got = m_map.find ( address ); + + if ( got == m_map.end() ) { + std::cout << "not found"; + return -1; // ERROR!! + } + else { + std::cout << got->first << " is " << got->second; + objId = got->second; + } + return objId; + +} + + +void WriteGeoModelAction::persistifyObj(const GeoPhysVol * pointer) +{ + qDebug() << "WriteGeoModelAction::persistifyObj()"; + + + const std::string name = pointer->getLogVol()->getName(); + + const GeoLogVol* logVol = pointer->getLogVol(); + + const GeoMaterial * mat = pointer->getLogVol()->getMaterial(); + const std::string matName = mat->getName(); + + const GeoShape * shape = pointer->getLogVol()->getShape(); + const std::string shapeType = shape->type(); + + int matId = storeObj(mat); + if ( matId > 0 ) { + + } + + + if ( storeObj(logVol) > 0 ) { + + // CREATE RECORD + +// /* Create SQL statement: INSERT */ +// std::ostringstream os; +// os << "INSERT INTO GEOMETRY (ID,NAME,MATERIAL,SHAPE) "; +// os << "VALUES (" << m_id << ",'" << name << "','" << matName << "','" << shapeType << "'); "; +// +// std::string s = os.str(); +// sql = s.c_str(); +// +// /* Execute SQL statement */ +// rc = sqlite3_exec(m_db, sql, callback, 0, &zErrMsg); +// if( rc != SQLITE_OK ){ +// fprintf(stderr, "SQL error: %s\n", zErrMsg); +// sqlite3_free(zErrMsg); +// }else{ +// fprintf(stdout, "Records created successfully\n"); +// } + } +} + + + +// FETCH ALL RECORDS +QSqlError WriteGeoModelAction::fetchAllRecords() +{ + qDebug() << "WriteGeoModelAction::fetchAllRecords()"; + +// openDB(); + +// // create and open a default connection to a SQLite database +// qDebug() << "creating the 'default' DB connection..."; +// m_db = QSqlDatabase::addDatabase("QSQLITE"); +// m_db.setDatabaseName("test_Qt.db"); +// qDebug() << "opening the DB..."; +// if (!m_db.open()) { +// qWarning() << "DB file could be opened!"; +// return m_db.lastError(); +// } + + QSqlQuery query; + query.exec("SELECT * FROM Material"); + + while (query.next()) { + QString name = query.value(0).toString(); + qDebug() << name; + // int salary = query.value(1).toInt(); + // qDebug() << name << salary; + } + + query = QSqlQuery("SELECT * FROM Material"); + int fieldNo = query.record().indexOf("name"); + while (query.next()) { + // QString country = query.value(fieldNo).toString(); + // doSomething(country); + qDebug() << query.record(); + } + +// m_db.close(); + +// closeDB(); + +} + +//// FETCH ALL RECORDS +//void WriteGeoModelAction::fetchAllRecords() +//{ +// /* Create SQL statement: FETCH */ +// sql = "SELECT * from GEOMETRY"; +// +// /* Execute SQL statement */ +// rc = sqlite3_exec(m_db, sql, callback, (void*)data, &zErrMsg); +// if( rc != SQLITE_OK ){ +// fprintf(stderr, "SQL error: %s\n", zErrMsg); +// sqlite3_free(zErrMsg); +// }else{ +// fprintf(stdout, "FETCH Operation done successfully\n\n"); +// } +//} + + +//int WriteGeoModelAction::callback(void *NotUsed, int argc, char **argv, char **azColName){ +// int i; +// for(i=0; i<argc; i++){ +// printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); +// } +// printf("\n"); +// return 0; +//} + +//// CREATE TABLES +//void WriteGeoModelAction::createTables() +//{ +// /* Create SQL statements: CREATE */ +// +// // create 'LogVol' table +// sql = "CREATE TABLE LogVol (" \ +// "ID INTEGER PRIMARY KEY UNIQUE NOT NULL," \ +// "SHAPE REFERENCES Shape (ID)," \ +// "MATERIAL REFERENCES Material (ID), " \ +// "NAME STRING NOT NULL DEFAULT AnonLogVol " \ +// ");"; +// if( executeSQL(sql) ) std::cout << "LogVol table created successfully." << std::endl; +// else std::cout << "ERROR while creating the table LogVol" << std::endl; +// +// // create 'PhysVol' table +// sql = "CREATE TABLE PhysVol ("\ +// "ID INTEGER PRIMARY KEY UNIQUE NOT NULL,"\ +// "LOGVOL INTEGER NOT NULL REFERENCES LogVol (ID),"\ +// "PARENT INTEGER REFERENCES PhysVol (ID)"\ +// ");"; +// if( executeSQL(sql) ) std::cout << "PhysVol table created successfully." << std::endl; +// else std::cout << "ERROR while creating the table PhysVol" << std::endl; +// +// // create 'Material' table +// sql = "CREATE TABLE Material (" \ +// "ID PRIMARY KEY,"\ +// "NAME STRING DEFAULT Air NOT NULL"\ +// ");"; +// if( executeSQL(sql) ) std::cout << "Material table created successfully." << std::endl; +// else std::cout << "ERROR while creating the table Material" << std::endl; +// +// // create 'Shape' table +// sql = "CREATE TABLE Shape ("\ +// "ID INTEGER PRIMARY KEY,"\ +// "SHAPE STRING NOT NULL"\ +// ");"; +// if( executeSQL(sql) ) std::cout << "Shape table created successfully." << std::endl; +// else std::cout << "ERROR while creating the table Shape" << std::endl; +// +//} + +//bool WriteGeoModelAction::executeSQL(const char * sql) +//{ +// /* Execute the input SQL statement */ +// rc = sqlite3_exec(m_db, sql, callback, 0, &zErrMsg); +// if( rc != SQLITE_OK ){ +// fprintf(stderr, "SQL error: %s\n", zErrMsg); +// sqlite3_free(zErrMsg); +// return false; +// } +// //else{ +// // fprintf(stdout, "SQL query executed successfully\n"); +// //} +// return true; +//} + + +//QSqlError WriteGeoModelAction::openDB() +//{ +// qDebug() << "WriteGeoModelAction::openDB()"; +// +////// create and open a default connection to a SQLite database +//// qDebug() << "creating the 'default' DB connection..."; +//// m_db = QSqlDatabase::addDatabase("QSQLITE"); +//// m_db.setDatabaseName("test_Qt.db"); +//// qDebug() << "opening the DB..."; +//// if (!m_db.open()) { +//// qWarning() << "DB file could be opened!"; +//// return m_db.lastError(); +//// } +// +// +//// QUuid uniqueId = QUuid::createUuid(); +//// _db = new QSqlDatabase(); +//// *_db = QSqlDatabase::addDatabase("QMYSQL", uniqueId.toString()); +//// db->setHostName(...); +//// db->setDatabaseName(...); +//// db->setUserName(...); +//// db->setPassword(...); +// +// _db = new QSqlDatabase(); +// *_db = QSqlDatabase::addDatabase("QSQLITE"); +// _db->setDatabaseName("test_Qt.db"); +// qDebug() << "opening the DB..."; +// if (!_db->open()) { +// qWarning() << "DB file could be opened!"; +// return _db->lastError(); +// } +// +//} +//void WriteGeoModelAction::closeDB() +//{ +// _db->close(); +// delete _db; +//// QSqlDatabase::removeDatabase(_db->connectionName()); +// QSqlDatabase::removeDatabase("test_Qt.db"); +//} + + + + +QSqlError WriteGeoModelAction::initDB() +{ + qDebug() << "WriteGeoModelAction::initDB()"; + + // create and open a default connection to a SQLite database + qDebug() << "creating the 'default' DB connection..."; + m_db = QSqlDatabase::addDatabase("QSQLITE"); + m_db.setDatabaseName("test_Qt.db"); + qDebug() << "opening the DB..."; + if (!m_db.open()) { + qWarning() << "DB file could be opened!"; + return m_db.lastError(); + } + +// openDB(); + + // check if DB is empty + qDebug() << "checking existing tables..."; + QSqlDatabase db = QSqlDatabase::database(); + QStringList tables = db.tables(); + if (tables.contains("LogVols", Qt::CaseInsensitive) + && tables.contains("PhysVols", Qt::CaseInsensitive) + && tables.contains("Materials", Qt::CaseInsensitive) + && tables.contains("Shapes", Qt::CaseInsensitive) + ) { + qDebug() << "tables are present already. Skipping tables creation."; +// closeDB(); + return QSqlError(); + } + + // create tables + qDebug() << "creating tables..."; + QSqlQuery q; + if (!q.exec(QLatin1String("create table LogVols(id integer primary key, name varchar, shape integer, material integer)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table PhysVols(id integer primary key, logvol integer not null, parent integer)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table Materials(id integer primary key, name varchar)"))) + return q.lastError(); + if (!q.exec(QLatin1String("create table Shapes(id integer primary key, name varchar)"))) + return q.lastError(); + qDebug() << "DONE. Tables created successfully."; + + // load the DB with test data, for debug +// loadTestData(); + +// _db->close(); +// closeDB(); + +} + +QSqlError WriteGeoModelAction::loadTestData() +{ + + qDebug() << "WriteGeoModelAction::loadTestData()"; + + // create test data + QSqlQuery q; + + qDebug() << "Loading Shapes..."; + if (!q.prepare(QLatin1String("insert into Shapes(name) values(?)"))) + return q.lastError(); + QVariant boxId = addShape(q, QLatin1String("Box")); + QVariant coneId = addShape(q, QLatin1String("Cone")); + QVariant sphereId = addShape(q, QLatin1String("Sphere")); + + qDebug() << "Loading Materials..."; + if (!q.prepare(QLatin1String("insert into Materials(name) values(?)"))) + return q.lastError(); + QVariant airId = addMaterial(q, QLatin1String("Air")); + QVariant ironId = addMaterial(q, QLatin1String("Iron")); + QVariant leadId = addMaterial(q, QLatin1String("Lead")); + + qDebug() << "Loading LogVols..."; + if (!q.prepare(QLatin1String("insert into LogVols(name, shape, material) values(?, ?, ?)"))) + return q.lastError(); + QVariant worldLogId = addLogVol(q, QLatin1String("WorldLog"), boxId, airId); + QVariant toyLogId = addLogVol(q, QLatin1String("ToyLog and Empire"), coneId, leadId); + + qDebug() << "Loading PhysVols..."; + if (!q.prepare(QLatin1String("insert into PhysVols(logvol, parent) values(?, ?)"))) + return q.lastError(); + QVariant rootPhysId = addPhysVol(q, worldLogId, QVariant()); // no parent + QVariant childPhysId = addPhysVol(q, toyLogId, rootPhysId); + + qDebug() << "DONE. Created and loaded test data."; +} + + +QVariant WriteGeoModelAction::addPhysVol(QSqlQuery &q, const QVariant &logVolId, + const QVariant &parentPhysVolId) +{ + qDebug() << "WriteGeoModelAction::addPhysVol()"; + q.addBindValue(logVolId); + q.addBindValue(parentPhysVolId); + q.exec(); + return q.lastInsertId(); +} + +QVariant WriteGeoModelAction::addLogVol(QSqlQuery &q, const QString &name, const QVariant &shapeId, + const QVariant &materialId) +{ + qDebug() << "WriteGeoModelAction::addLogVol()"; + q.addBindValue(name); + q.addBindValue(shapeId); + q.addBindValue(materialId); + q.exec(); + return q.lastInsertId(); +} + +QVariant WriteGeoModelAction::addMaterial(QSqlQuery &q, const QString &name) +{ + qDebug() << "WriteGeoModelAction::addMaterial()"; + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} + +QVariant WriteGeoModelAction::addShape(QSqlQuery &q, const QString &name) +{ + qDebug() << "WriteGeoModelAction::addShape()"; + q.addBindValue(name); + q.exec(); + return q.lastInsertId(); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c82c55e6e504b013ede4c16cf2aa3d98d8ce04a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/CMakeLists.txt @@ -0,0 +1,25 @@ +################################################################################ +# Package: TFPersistification +################################################################################ + +# Declare the package name: +atlas_subdir( TFPersistification ) + +# Declare the package's dependencies: +# TODO: we can skip the dependency on GeoPrimitives when we convert all methods to Eigen (GeoTrf::Transform3D) +atlas_depends_on_subdirs( PUBLIC + DetectorDescription/GeoPrimitives + ) + +# External dependencies: +find_package( CLHEP ) # TODO: we can skip the dependency on CLHEP when we convert all methods to Eigen (GeoTrf::Transform3D) +find_package( Eigen ) +find_package( GeoModel ) + +# Component(s) in the package: +atlas_add_library( TFPersistification + src/*.cpp + TFPersistification/*.h + PUBLIC_HEADERS TFPersistification + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} ${EIGEN_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} ${GEOMODEL_LIBRARIES} GeoPrimitives ) diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ACosIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ACosIO.h new file mode 100644 index 0000000000000000000000000000000000000000..9c0c574c2c2291ea22ef982f0eb827818bf81aef --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ACosIO.h @@ -0,0 +1,28 @@ +#ifndef _ACosIO_h_ +#define _ACosIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class ACosReader: public GenFunctionReader { + + public: + + ACosReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class ACosRecorder: public GenFunctionRecorder { + + public: + + ACosRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ASinIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ASinIO.h new file mode 100644 index 0000000000000000000000000000000000000000..dedc5ff8ac9ac1e5b109288eff77044df9a0484a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ASinIO.h @@ -0,0 +1,27 @@ +#ifndef _ASinIO_h_ +#define _ASinIO_h_ +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class ASinReader: public GenFunctionReader { + + public: + + ASinReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class ASinRecorder: public GenFunctionRecorder { + + public: + + ASinRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ATanIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ATanIO.h new file mode 100644 index 0000000000000000000000000000000000000000..526d8b66f727fafa4021f065833179e1db9a98b0 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ATanIO.h @@ -0,0 +1,27 @@ +#ifndef _ATanIO_h_ +#define _ATanIO_h_ +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class ATanReader: public GenFunctionReader { + + public: + + ATanReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class ATanRecorder: public GenFunctionRecorder { + + public: + + ATanRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/AbsIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/AbsIO.h new file mode 100644 index 0000000000000000000000000000000000000000..09b351c5c6257a134a3ac169dee572d3715ec794 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/AbsIO.h @@ -0,0 +1,27 @@ +#ifndef _AbsIO_h_ +#define _AbsIO_h_ +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class AbsReader: public GenFunctionReader { + + public: + + AbsReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class AbsRecorder: public GenFunctionRecorder { + + public: + + AbsRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ArrayFunctionIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ArrayFunctionIO.h new file mode 100644 index 0000000000000000000000000000000000000000..f5ff56c25d5085abcbbb3371dd16a0c81a377426 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ArrayFunctionIO.h @@ -0,0 +1,27 @@ +#ifndef _ArrayFunctionIO_h_ +#define _ArrayFunctionIO_h_ +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class ArrayFunctionReader: public GenFunctionReader { + + public: + + ArrayFunctionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class ArrayFunctionRecorder: public GenFunctionRecorder { + + public: + + ArrayFunctionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/CosIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/CosIO.h new file mode 100644 index 0000000000000000000000000000000000000000..b507f13e17a63f9aac4b84b3c94d672ecc790719 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/CosIO.h @@ -0,0 +1,28 @@ +#ifndef _CosIO_h_ +#define _CosIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class CosReader: public GenFunctionReader { + + public: + + CosReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class CosRecorder: public GenFunctionRecorder { + + public: + + CosRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/FixedConstantIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/FixedConstantIO.h new file mode 100644 index 0000000000000000000000000000000000000000..84ecbe10e6f6eb23a671b9256eb22e6eee1fe426 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/FixedConstantIO.h @@ -0,0 +1,27 @@ +#ifndef _FixedConstantIO_h_ +#define _FixedConstantIO_h_ +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class FixedConstantReader: public GenFunctionReader { + + public: + + FixedConstantReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class FixedConstantRecorder: public GenFunctionRecorder { + + public: + + FixedConstantRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionInterpreter.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionInterpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..232775518d843c32637d726504f03507816eb926 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionInterpreter.h @@ -0,0 +1,54 @@ +#ifndef _GENFUNCTIONINTERPRETER_H_ +#define _GENFUNCTIONINTERPRETER_H_ +#include <map> +#include <string> +#include <typeinfo> +#include <sstream> +#include <memory> + +// +// Forward definition of "Genfunction" +// +namespace GeoGenfun { + class AbsFunction; +} + +// +// Forward definition of GenFunctionRecorder; +// +class GenFunctionReader; + +typedef std::unique_ptr<const GeoGenfun::AbsFunction> GFPTR; + +class GenFunctionInterpreter { + + public: + + // Constructor + GenFunctionInterpreter(); + + // Destructor + ~GenFunctionInterpreter(); + + // Registers a reader. Assumes ownership and will delete + void add(const std::string &str, const GenFunctionReader * reader); + + // Interprets a string. + GFPTR interpret(std::string::const_iterator begin, + std::string::const_iterator end ) const; + + private: + + // Store the actual interpreters, map them into the type name + std::map<std::string, const GenFunctionReader *> m_readerMap; + + // Deleted methods: + GenFunctionInterpreter(const GenFunctionInterpreter &) = delete; + GenFunctionInterpreter & operator = (const GenFunctionInterpreter &) = delete; + +}; + + +#endif + + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionPersistifier.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionPersistifier.h new file mode 100644 index 0000000000000000000000000000000000000000..49fede5c8d8e516d9308dd92456001e6f1dc8eb7 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionPersistifier.h @@ -0,0 +1,61 @@ +#ifndef _GENPERSISTIFIER_H_ +#define _GENPERSISTIFIER_H_ +#include <map> +#include <string> +#include <typeinfo> +#include <sstream> + +// +// Forward declaration of GeoGenfun::AbsFunction +// +namespace GeoGenfun { + class AbsFunction; +} +// +// Forward definition of GenFunctionRecorder; +// +class GenFunctionRecorder; + + + +class GenFunctionPersistifier { + + public: + + // Constructor + GenFunctionPersistifier(); + + // Destructor + ~GenFunctionPersistifier(); + + // Registers a recorder. Assumes ownership and will delete. + void add(const std::type_info & tInfo, const GenFunctionRecorder * recorder); + + // Persistifies the function. Result goes into the coded string. + void persistify(const GeoGenfun::AbsFunction & f) const; + + // Retrieves the coded string after the persistify operation: + const std::string & getCodedString() const; + + // Retrieves the stream used to build the expression: + std::ostringstream & getStream() const; + + private: + + // Store the actual recorders, map them into the type name + std::map<std::string, const GenFunctionRecorder *> m_recorderMap; + + // Here is the result: + mutable std::string m_codedString; + + // An ostringstream is used to build the coded string: + mutable std::ostringstream* m_stream; + + // Deleted methods: + GenFunctionPersistifier(const GenFunctionPersistifier &) = delete; + GenFunctionPersistifier & operator = (const GenFunctionPersistifier &) = delete; + +}; + + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionReader.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionReader.h new file mode 100644 index 0000000000000000000000000000000000000000..e672a1fd05b8176521d9aa885de94e5f53bc97bd --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionReader.h @@ -0,0 +1,58 @@ +#ifndef _GENFUNCTIONREADER_H_ +#define _GENFUNCTIONREADER_H_ + +#include "GeoGenericFunctions/AbsFunction.h" + +#include <memory> +#include <tuple> +#include <string> + +typedef std::tuple<std::string::const_iterator, std::string::const_iterator> BeginEnd; + +typedef std::unique_ptr<const GeoGenfun::AbsFunction> GFPTR; +// +// Forward definition of GenFunctionInterpreter; +// +class GenFunctionInterpreter; + +class GenFunctionReader { + + public: + + // Constructor. Keep a pointer to the interpreter for purposes of recusion. + GenFunctionReader(const std::string & name, GenFunctionInterpreter *interpreter); + + // Destructor + virtual ~GenFunctionReader(); + + // Execute + virtual GFPTR execute(std::string::const_iterator , std::string::const_iterator) const=0; + + // Access to the interpreter: + const GenFunctionInterpreter *getInterpreter() const; + + // Access to the input string name; + const std::string & getName() const; + + protected: + + // Some of the subclasses require two arguments, separated by a |. This + // splits the argument into its two pieces: + std::string::const_iterator split(std::string::const_iterator begin, std::string::const_iterator end) const; + + private: + + // Name of the text string found on the input: + const std::string m_name; + + // A pointer to the interpreter: + const GenFunctionInterpreter *m_interpreter; + + // Deleted operations: + GenFunctionReader(const GenFunctionReader &) = delete; + GenFunctionReader & operator = (const GenFunctionReader &) = delete; + + +}; + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionRecorder.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionRecorder.h new file mode 100644 index 0000000000000000000000000000000000000000..a76b756d36e7ef0ca71dd200ec8709f4504c4c9e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenFunctionRecorder.h @@ -0,0 +1,46 @@ +#ifndef _GENFUNCTIONRECORDER_H_ +#define _GENFUNCTIONRECORDER_H_ + +#include <typeinfo> + + +namespace GeoGenfun { + class AbsFunction; +} + + +// +// Forward definition of GenFunctionPersistifier; +// +class GenFunctionPersistifier; + +class GenFunctionRecorder { + + public: + + // Constructor. Keep a pointer to the persistifier for purposes of recusion. + GenFunctionRecorder(const std::type_info & info, GenFunctionPersistifier *persistifier); + + // Destructor: + virtual ~GenFunctionRecorder(); + + // Execute + virtual void execute(const GeoGenfun::AbsFunction & transfunction) const=0; + + // Access to the persistifier: + const GenFunctionPersistifier *getPersistifier() const; + + private: + + // A pointer to the persistifier: + const GenFunctionPersistifier *m_persistifier; + + // Deleted operations: + GenFunctionRecorder(const GenFunctionRecorder &) = delete; + GenFunctionRecorder & operator = (const GenFunctionRecorder &) = delete; + + +}; + + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenfunIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenfunIO.h new file mode 100644 index 0000000000000000000000000000000000000000..05f8e41f51915cdebf69044288ed19b196f81b04 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/GenfunIO.h @@ -0,0 +1,240 @@ +#ifndef _GenfunIO_h_ +#define _GenfunIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + + +class ConstTimesFunctionReader: public GenFunctionReader { + + public: + + ConstTimesFunctionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + +class ConstTimesFunctionRecorder: public GenFunctionRecorder { + + public: + + ConstTimesFunctionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + + +class ConstPlusFunctionReader: public GenFunctionReader { + + public: + + ConstPlusFunctionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class ConstPlusFunctionRecorder: public GenFunctionRecorder { + + public: + + ConstPlusFunctionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class ConstMinusFunctionReader: public GenFunctionReader { + + public: + + ConstMinusFunctionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class ConstMinusFunctionRecorder: public GenFunctionRecorder { + + public: + + ConstMinusFunctionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class ConstOverFunctionReader: public GenFunctionReader { + + public: + + ConstOverFunctionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class ConstOverFunctionRecorder: public GenFunctionRecorder { + + public: + + ConstOverFunctionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + + +class FunctionCompositionReader: public GenFunctionReader { + + public: + + FunctionCompositionReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionCompositionRecorder: public GenFunctionRecorder { + + public: + + FunctionCompositionRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + + +class FunctionNegationReader: public GenFunctionReader { + + public: + + FunctionNegationReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionNegationRecorder: public GenFunctionRecorder { + + public: + + FunctionNegationRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class FunctionNoopReader: public GenFunctionReader { + + public: + + FunctionNoopReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionNoopRecorder: public GenFunctionRecorder { + + public: + + FunctionNoopRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class FunctionProductReader: public GenFunctionReader { + + public: + + FunctionProductReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionProductRecorder: public GenFunctionRecorder { + + public: + + FunctionProductRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class FunctionQuotientReader: public GenFunctionReader { + + public: + + FunctionQuotientReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionQuotientRecorder: public GenFunctionRecorder { + + public: + + FunctionQuotientRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + + +class FunctionSumReader: public GenFunctionReader { + + public: + + FunctionSumReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionSumRecorder: public GenFunctionRecorder { + + public: + + FunctionSumRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + +class FunctionDifferenceReader: public GenFunctionReader { + + public: + + FunctionDifferenceReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end ) const; + +}; + + +class FunctionDifferenceRecorder: public GenFunctionRecorder { + + public: + + FunctionDifferenceRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; + + +class VariableReader: public GenFunctionReader { + + public: + + VariableReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class VariableRecorder: public GenFunctionRecorder { + + public: + + VariableRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ModIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ModIO.h new file mode 100644 index 0000000000000000000000000000000000000000..cec3e1057b3a64f977d9066018782159e40fd69e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/ModIO.h @@ -0,0 +1,28 @@ +#ifndef _ModIO_h_ +#define _ModIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class ModReader: public GenFunctionReader { + + public: + + ModReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class ModRecorder: public GenFunctionRecorder { + + public: + + ModRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/RectangularIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/RectangularIO.h new file mode 100644 index 0000000000000000000000000000000000000000..dd68430562e09e9dc6b0f25e43589aaaa1d2baaf --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/RectangularIO.h @@ -0,0 +1,28 @@ +#ifndef _RectangularIO_h_ +#define _RectangularIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class RectangularReader: public GenFunctionReader { + + public: + + RectangularReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class RectangularRecorder: public GenFunctionRecorder { + + public: + + RectangularRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SinIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SinIO.h new file mode 100644 index 0000000000000000000000000000000000000000..02990ca51672d08ea3647ec8a205d5cd19f86c1c --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SinIO.h @@ -0,0 +1,29 @@ +#ifndef _SinIO_h_ +#define _SinIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + + +class SinReader: public GenFunctionReader { + + public: + + SinReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class SinRecorder: public GenFunctionRecorder { + + public: + + SinRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SqrtIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SqrtIO.h new file mode 100644 index 0000000000000000000000000000000000000000..7c7f9ecc09d82be0cf4428472fcfa0f1574fe42d --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SqrtIO.h @@ -0,0 +1,28 @@ +#ifndef _SqrtIO_h_ +#define _SqrtIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class SqrtReader: public GenFunctionReader { + + public: + + SqrtReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class SqrtRecorder: public GenFunctionRecorder { + + public: + + SqrtRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SquareIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SquareIO.h new file mode 100644 index 0000000000000000000000000000000000000000..082a62c3e5201fd6806196b861a593de6ae31d08 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/SquareIO.h @@ -0,0 +1,28 @@ +#ifndef _SquareIO_h_ +#define _SquareIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class SquareReader: public GenFunctionReader { + + public: + + SquareReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class SquareRecorder: public GenFunctionRecorder { + + public: + + SquareRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TanIO.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TanIO.h new file mode 100644 index 0000000000000000000000000000000000000000..5d1dcf59667be1cbb2760d242bae27f93b123ae2 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TanIO.h @@ -0,0 +1,28 @@ +#ifndef _TanIO_h_ +#define _TanIO_h_ + +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/GenFunctionRecorder.h" + +#include "GeoGenericFunctions/AbsFunction.h" + +class TanReader: public GenFunctionReader { + + public: + + TanReader(GenFunctionInterpreter * interpreter); + virtual GFPTR execute(std::string::const_iterator begin, std::string::const_iterator end) const; + +}; + + +class TanRecorder: public GenFunctionRecorder { + + public: + + TanRecorder(GenFunctionPersistifier * persistifier); + virtual void execute(const GeoGenfun::AbsFunction & F) const; + +}; +#endif + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionInterpreter.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionInterpreter.h new file mode 100644 index 0000000000000000000000000000000000000000..62d8ba9cf7d594a753265e653fb384fa92fe1405 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionInterpreter.h @@ -0,0 +1,59 @@ +#ifndef _TRANSFUNCTIONINTERPRETER_H_ +#define _TRANSFUNCTIONINTERPRETER_H_ +#include "TFPersistification/GenFunctionInterpreter.h" +#include <map> +#include <string> +#include <typeinfo> +#include <sstream> +#include <memory> + +// +// Forward definition of "Transfunction" +// +namespace GeoXF { + class Function; +} + +// +// Forward definition of TransFunctionRecorder; +// +class TransFunctionReader; +typedef std::unique_ptr<const GeoXF::Function> TFPTR; + +class TransFunctionInterpreter { + + public: + + // Constructor + TransFunctionInterpreter(); + + // Destructor + ~TransFunctionInterpreter(); + + // Registers a reader: + void add(const std::string &str, const TransFunctionReader * reader); + + // Interprets a string. + TFPTR interpret(const std::string & str) const; + + // Retrieves the genfunction persistitier: + const GenFunctionInterpreter * getGenFunctionInterpreter() const; + + private: + + // Store the actual interpreters, map them into the type name + std::map<std::string, const TransFunctionReader *> m_readerMap; + + // A pointer to the GenFunctionInterpreter: + const GenFunctionInterpreter m_fInterpreter; + + // Deleted methods: + TransFunctionInterpreter(const TransFunctionInterpreter &) = delete; + TransFunctionInterpreter & operator = (const TransFunctionInterpreter &) = delete; + +}; + + +#endif + + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionPersistifier.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionPersistifier.h new file mode 100644 index 0000000000000000000000000000000000000000..1ff9abeae07359ab03aadf6ba94a8c6d81a8fd41 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionPersistifier.h @@ -0,0 +1,71 @@ +#ifndef _GEOPERSISTIFIER_H_ +#define _GEOPERSISTIFIER_H_ +#include "TFPersistification/GenFunctionPersistifier.h" +#include <map> +#include <string> +#include <typeinfo> +#include <sstream> + +// +// Forward definition of "Transfunction" +// +namespace GeoXF { + class Function; +} + +// +// Forward definition of TransFunctionRecorder; +// +class TransFunctionRecorder; +class GenFunctionPersistifier; + + +class TransFunctionPersistifier { + + public: + + // Constructor + TransFunctionPersistifier(); + + // Destructor + ~TransFunctionPersistifier(); + + // Registers a recorder: + void add(const std::type_info & tInfo, const TransFunctionRecorder * recorder); + + // Persistifies the function. Result goes into the coded string. + void persistify(const GeoXF::Function & f) const; + + // Retrieves the coded string after the persistify operation: + const std::string & getCodedString() const; + + // Retrieves the stream used to build the expression: + std::ostringstream & getStream() const; + + // Retrieves the genfunction persistitier: + const GenFunctionPersistifier * getGenFunctionPersistifier() const; + + private: + + // Store the actual recorders, map them into the type name + std::map<std::string, const TransFunctionRecorder *> recorderMap; + + // Here is the result: + mutable std::string codedString; + + // An ostringstream is used to build the coded string: + mutable std::ostringstream *stream; + + // The GenFunctionPersistifier: + GenFunctionPersistifier fPersistifier; + + // Deleted methods: + TransFunctionPersistifier(const TransFunctionPersistifier &) = delete; + TransFunctionPersistifier & operator = (const TransFunctionPersistifier &) = delete; + +}; + + +#endif + + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionReader.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionReader.h new file mode 100644 index 0000000000000000000000000000000000000000..d4a2aa447be25db9bf1e4aec2eed33bb788a5762 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionReader.h @@ -0,0 +1,106 @@ +#ifndef _TRANSFUNCTIONREADER_H_ +#define _TRANSFUNCTIONREADER_H_ + +#include "GeoModelKernel/GeoXF.h" + +#include <memory> +// + + +// Forward definition of "Transfunction" +// +namespace GeoXF { + class Function; +} + +typedef std::unique_ptr<const GeoXF::Function> TFPtr; + + +// +// Forward definition of TransFunctionInterpreter; +// +class TransFunctionInterpreter; + +class TransFunctionReader { + + public: + + // Constructor. Keep a pointer to the interpreter for purposes of recusion. + TransFunctionReader(const std::string & name, TransFunctionInterpreter *interpreter); + + // Destructor + virtual ~TransFunctionReader(); + + // Execute + virtual TFPTR execute(const std::string & arg) const=0; + + // Access to the interpreter: + const TransFunctionInterpreter *getInterpreter() const; + + protected: + + // Some of the subclasses require two arguments, separated by a |. This + // splits the argument into its two pieces: + std::pair<std::string, std::string> split(const std::string & arg) const; + + // Help scan transforms + GeoTrf::Transform3D scanT(const std::string & exprString) const; + + private: + + + // A pointer to the interpreter: + const TransFunctionInterpreter* m_interpreter; + + // Deleted operations: + TransFunctionReader(const TransFunctionReader &) = delete; + TransFunctionReader & operator = (const TransFunctionReader &) = delete; + + +}; + +// Now we add the pre-existing types of transfunction (=GeoXF::Function). These +// may well be the only types we ever need!. + +class ProductReader: public TransFunctionReader { + + public: + + ProductReader(TransFunctionInterpreter * interpreter); + virtual TFPTR execute(const std::string & arg) const; + +}; + + +class PreMultReader: public TransFunctionReader { + + public: + + PreMultReader(TransFunctionInterpreter * interpreter); + virtual TFPTR execute(const std::string & arg) const; + +}; + +class PostMultReader: public TransFunctionReader { + + public: + + PostMultReader(TransFunctionInterpreter * interpreter); + virtual TFPTR execute(const std::string & arg) const; + +}; + + +class PowReader: public TransFunctionReader { + + public: + + PowReader(TransFunctionInterpreter * interpreter); + virtual TFPTR execute(const std::string & arg) const; + +}; + + + + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionRecorder.h b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionRecorder.h new file mode 100644 index 0000000000000000000000000000000000000000..cb28637844f5c7def3973554b78d0d78cc8e972d --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/TFPersistification/TransFunctionRecorder.h @@ -0,0 +1,89 @@ +#ifndef _TRANSFUNCTIONRECORDER_H_ +#define _TRANSFUNCTIONRECORDER_H_ +#include <typeinfo> + +// +// Forward definition of "Transfunction" +// +namespace GeoXF { + class Function; +} + +// +// Forward definition of TransFunctionPersistifier; +// +class TransFunctionPersistifier; + +class TransFunctionRecorder { + + public: + + // Constructor. Keep a pointer to the persistifier for purposes of recusion. + TransFunctionRecorder(const std::type_info & info, TransFunctionPersistifier *persistifier); + + // Destructor + virtual ~TransFunctionRecorder(); + + // Execute + virtual void execute(const GeoXF::Function & transfunction) const=0; + + // Access to the persistifier: + const TransFunctionPersistifier *getPersistifier() const; + + private: + + // A pointer to the persistifier: + const TransFunctionPersistifier *persistifier; + + // Deleted operations: + TransFunctionRecorder(const TransFunctionRecorder &) = delete; + TransFunctionRecorder & operator = (const TransFunctionRecorder &) = delete; + + +}; + +// Now we add the pre-existing types of transfunction (=GeoXF::Function). These +// may well be the only types we ever need!. + +class ProductRecorder: public TransFunctionRecorder { + + public: + + ProductRecorder(TransFunctionPersistifier * persistifier); + virtual void execute(const GeoXF::Function &) const; + +}; + + +class PreMultRecorder: public TransFunctionRecorder { + + public: + + PreMultRecorder(TransFunctionPersistifier * persistifier); + virtual void execute(const GeoXF::Function & ) const; + +}; + +class PostMultRecorder: public TransFunctionRecorder { + + public: + + PostMultRecorder(TransFunctionPersistifier * persistifier); + virtual void execute(const GeoXF::Function & ) const; + +}; + + +class PowRecorder: public TransFunctionRecorder { + + public: + + PowRecorder(TransFunctionPersistifier * persistifier); + virtual void execute(const GeoXF::Function &) const; + +}; + + + + +#endif diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ACosIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ACosIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6679930302c4d300017e137305a1c45c670158f2 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ACosIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/ACosIO.h" + +#include "GeoGenericFunctions/ACos.h" + +ACosReader::ACosReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ACos", interpreter) {} + + +GFPTR ACosReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::ACos()); +} + + +ACosRecorder::ACosRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ACos),persistifier) {} + +void ACosRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ACos * ptr = dynamic_cast<const GeoGenfun::ACos *> (&F); + if (!ptr) throw std::runtime_error("Error in ACosRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "ACos"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ASinIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ASinIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c4a2e0c14543473dcbf9669a6546c7925d94457b --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ASinIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/ASinIO.h" + +#include "GeoGenericFunctions/ASin.h" + +ASinReader::ASinReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ASin", interpreter) {} + + +GFPTR ASinReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::ASin()); +} + + +ASinRecorder::ASinRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ASin),persistifier) {} + +void ASinRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ASin * ptr = dynamic_cast<const GeoGenfun::ASin *> (&F); + if (!ptr) throw std::runtime_error("Error in ASinRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "ASin"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ATanIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ATanIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..33df878f45ba9167f4d356dea3ba9c03690d11fd --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ATanIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/ATanIO.h" + +#include "GeoGenericFunctions/ATan.h" + +ATanReader::ATanReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ATan", interpreter) {} + + +GFPTR ATanReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::ATan()); +} + + +ATanRecorder::ATanRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ATan),persistifier) {} + +void ATanRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ATan * ptr = dynamic_cast<const GeoGenfun::ATan *> (&F); + if (!ptr) throw std::runtime_error("Error in ATanRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "ATan"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/AbsIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/AbsIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..cb8039fca032ba61f3b57ab5e1861f3913b2252c --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/AbsIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/AbsIO.h" + +#include "GeoGenericFunctions/Abs.h" + +AbsReader::AbsReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Abs", interpreter) {} + + +GFPTR AbsReader::execute(std::string::const_iterator, std::string::const_iterator) const { + return GFPTR(new GeoGenfun::Abs()); +} + + +AbsRecorder::AbsRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Abs),persistifier) {} + +void AbsRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Abs * ptr = dynamic_cast<const GeoGenfun::Abs *> (&F); + if (!ptr) throw std::runtime_error("Error in AbsRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Abs"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ArrayFunctionIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ArrayFunctionIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d0abcc58fa9560b291bfe576df4a2f3b67927462 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ArrayFunctionIO.cpp @@ -0,0 +1,48 @@ +#define private public +#include "GeoGenericFunctions/ArrayFunction.h" +#undef private + +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/ArrayFunctionIO.h" +ArrayFunctionReader::ArrayFunctionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ArrayFunction", interpreter) {} + + +GFPTR ArrayFunctionReader::execute(std::string::const_iterator cStart, std::string::const_iterator cEnd) const { + std::vector<double> elements; + auto cNext=std::find(cStart, cEnd,','); + while (cNext!=cEnd) { + std::string aNumberStr(cStart,cNext); + std::istringstream stream(aNumberStr); + double d; + stream >> d; + elements.push_back(d); + cStart=cNext+1; + cNext=std::find(cStart, cEnd,','); + } + + std::string aNumberStr(cStart,cNext); + std::istringstream stream(aNumberStr); + double d; + stream >> d; + elements.push_back(d); + + return GFPTR(new GeoGenfun::ArrayFunction(&elements.front(), &elements.back() + 1)); +} + + +ArrayFunctionRecorder::ArrayFunctionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ArrayFunction),persistifier) {} + +void ArrayFunctionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ArrayFunction * ptr = dynamic_cast<const GeoGenfun::ArrayFunction *> (&F); + if (!ptr) throw std::runtime_error("Error in ArrayFunctionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "ArrayFunction"; + stream << "("; + for (size_t i=0;i<ptr->_values.size();i++){ + stream<<ptr->_values[i]; + if (i!=ptr->_values.size()-1) stream << ","; + } + stream << ")"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/CosIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/CosIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..15c055a8991f5f632cfe03e6d9ffcb0d850fdd0e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/CosIO.cpp @@ -0,0 +1,22 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/CosIO.h" + +#include "GeoGenericFunctions/Cos.h" + +CosReader::CosReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Cos",interpreter) {} + + +GFPTR CosReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::Cos()); +} + +CosRecorder::CosRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Cos), persistifier) {} + +void CosRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Cos * ptr = dynamic_cast<const GeoGenfun::Cos *> (&F); + if (!ptr) throw std::runtime_error("Error in CosRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Cos"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/FixedConstantIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/FixedConstantIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..58803ebf9f99308976c4149b44f73d3742b9689b --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/FixedConstantIO.cpp @@ -0,0 +1,30 @@ +#define private public +#include "GeoGenericFunctions/FixedConstant.h" +#undef private +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/FixedConstantIO.h" +FixedConstantReader::FixedConstantReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FixedConstant", interpreter) {} + + +GFPTR FixedConstantReader::execute(std::string::const_iterator begin, std::string::const_iterator end) const { + double v; + std::string aNumberStr(begin,end); + std::istringstream stream(aNumberStr); + stream >> v; + return GFPTR(new GeoGenfun::FixedConstant(v)); +} + + +FixedConstantRecorder::FixedConstantRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FixedConstant),persistifier) {} + +void FixedConstantRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FixedConstant * ptr = dynamic_cast<const GeoGenfun::FixedConstant *> (&F); + if (!ptr) throw std::runtime_error("Error in FixedConstantRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FixedConstant"; + stream << "("; + stream<<ptr->_value; + stream << ")"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionInterpreter.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionInterpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..647e6fc70a967a555fb23cbe9f53f9e3e709791b --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionInterpreter.cpp @@ -0,0 +1,92 @@ +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/GenFunctionReader.h" +#include "TFPersistification/ArrayFunctionIO.h" +#include "TFPersistification/ModIO.h" +#include "TFPersistification/FixedConstantIO.h" +#include "TFPersistification/RectangularIO.h" +#include "TFPersistification/AbsIO.h" +#include "TFPersistification/SinIO.h" +#include "TFPersistification/ASinIO.h" +#include "TFPersistification/CosIO.h" +#include "TFPersistification/ACosIO.h" +#include "TFPersistification/TanIO.h" +#include "TFPersistification/ATanIO.h" +#include "TFPersistification/SqrtIO.h" +#include "TFPersistification/SquareIO.h" +#include "TFPersistification/GenfunIO.h" + +#include "GeoGenericFunctions/AbsFunction.h" +#include "GeoGenericFunctions/Argument.h" +#include "GeoModelKernel/GeoDefinitions.h" +#include "GeoModelKernel/GeoXF.h" + +#include <iterator> + +GenFunctionInterpreter::~GenFunctionInterpreter() { + for (auto i=m_readerMap.begin();i!=m_readerMap.end();i++) delete (*i).second; +} + +GenFunctionInterpreter::GenFunctionInterpreter() { + new ArrayFunctionReader(this); + new ModReader(this); + new FixedConstantReader(this); + new RectangularReader(this); + new SinReader(this); + new CosReader(this); + new TanReader(this); + new ASinReader(this); + new ACosReader(this); + new ATanReader(this); + new AbsReader(this); + new SqrtReader(this); + new SquareReader(this); + new VariableReader(this); + new ConstTimesFunctionReader(this); + new ConstPlusFunctionReader(this); + new ConstMinusFunctionReader(this); + new ConstOverFunctionReader(this); + new FunctionCompositionReader(this); + new FunctionProductReader(this); + new FunctionSumReader(this); + new FunctionQuotientReader(this); + new FunctionDifferenceReader(this); + new FunctionNegationReader(this); + new FunctionNoopReader(this); +} + +void GenFunctionInterpreter::add(const std::string & str, const GenFunctionReader * reader) { + reader=m_readerMap[str]=reader; +} + + +GFPTR GenFunctionInterpreter::interpret(std::string::const_iterator sBegin, std::string::const_iterator sEnd) const { + + auto begin=std::find(sBegin, sEnd, '('); + std::reverse_iterator<std::string::const_iterator> rBegin(sEnd); + std::reverse_iterator<std::string::const_iterator> rEnd(sBegin); + auto end=std::find(rBegin, rEnd, ')').base(); + + + if (end==sBegin || begin==sEnd) { + // Base case. This is the bottom of the tree! + std::string exprString(sBegin,sEnd); + auto rIter = m_readerMap.find(exprString); + if (rIter==m_readerMap.end()) { + std::ostringstream stream; + stream << "Ominous warning in GenFunctionInterpreter: cannot parse function " << exprString; + throw std::runtime_error (stream.str()); + } + const GenFunctionReader *reader = (*rIter).second; + return reader->execute(begin,begin);//exec w/null expression + } + std::string op(sBegin,begin); + auto argBegin=begin+1, argEnd=end-1; + auto rIter = m_readerMap.find(op); + if (rIter==m_readerMap.end()) { + std::ostringstream stream; + stream << "Ominous warning in GenFunctionInterpreter: cannot interpret function " << op; + throw std::runtime_error (stream.str()); + } + const GenFunctionReader *reader = (*rIter).second; + return reader->execute(argBegin,argEnd); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionPersistifier.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionPersistifier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0e2d4782acedc1a814075c65813119d67691a70a --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionPersistifier.cpp @@ -0,0 +1,85 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionRecorder.h" +#include "TFPersistification/SinIO.h" +#include "TFPersistification/TanIO.h" +#include "TFPersistification/CosIO.h" +#include "TFPersistification/ASinIO.h" +#include "TFPersistification/ATanIO.h" +#include "TFPersistification/ACosIO.h" +#include "TFPersistification/SqrtIO.h" +#include "TFPersistification/SquareIO.h" +#include "TFPersistification/AbsIO.h" +#include "TFPersistification/ArrayFunctionIO.h" +#include "TFPersistification/ModIO.h" +#include "TFPersistification/FixedConstantIO.h" +#include "TFPersistification/RectangularIO.h" +#include "TFPersistification/GenfunIO.h" + +#include "GeoGenericFunctions/AbsFunction.h" + + +#include <sstream> +const std::string & GenFunctionPersistifier::getCodedString() const { + m_codedString=getStream().str(); + delete m_stream; + m_stream=NULL; + return m_codedString; +} + + +GenFunctionPersistifier::~GenFunctionPersistifier() { + delete m_stream; + for (auto i=m_recorderMap.begin();i!=m_recorderMap.end();i++) { + delete (*i).second; + } +} +GenFunctionPersistifier::GenFunctionPersistifier():m_stream(NULL) { + new ConstPlusFunctionRecorder(this); + new ConstTimesFunctionRecorder(this); + new ConstMinusFunctionRecorder(this); + new ConstOverFunctionRecorder(this); + new FunctionNegationRecorder(this); + new FunctionNoopRecorder(this); + new FunctionProductRecorder(this); + new FunctionQuotientRecorder(this); + new FunctionCompositionRecorder(this); + new FunctionSumRecorder(this); + new FunctionDifferenceRecorder(this); + new SinRecorder(this); + new CosRecorder(this); + new TanRecorder(this); + new ASinRecorder(this); + new ACosRecorder(this); + new ATanRecorder(this); + new AbsRecorder(this); + new SqrtRecorder(this); + new SquareRecorder(this); + new ArrayFunctionRecorder(this); + new ModRecorder(this); + new FixedConstantRecorder(this); + new RectangularRecorder(this); + new VariableRecorder(this); +} + +void GenFunctionPersistifier::add(const std::type_info & tInfo, const GenFunctionRecorder * recorder) { + m_recorderMap[tInfo.name()]=recorder; +} + +std::ostringstream & GenFunctionPersistifier::getStream() const { + if (!m_stream) m_stream = new std::ostringstream(); + return *m_stream; +} + +void GenFunctionPersistifier::persistify(const GeoGenfun::AbsFunction & f) const { + + auto rIter = m_recorderMap.find(typeid(f).name()); + if (rIter!=m_recorderMap.end()) { + const GenFunctionRecorder *recorder = (*rIter).second; + recorder->execute(f); + } + else { + std::ostringstream message; + message << "Ominous warning in GenFunctionPersistifier: cannot persistify function with type id: " << typeid(f).name(); + throw std::runtime_error (message.str()); + } +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionReader.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..521f8abeaf9eb924e5665e1f0b7afd7744fa4267 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionReader.cpp @@ -0,0 +1,70 @@ +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/GenFunctionReader.h" + +#include <stdexcept> + + + +GenFunctionReader::GenFunctionReader(const std::string & name, GenFunctionInterpreter * interpreter): + m_name(name),m_interpreter(interpreter) { + interpreter->add(name, this); +} + +const std::string & GenFunctionReader::getName() const { + return m_name; +} + +const GenFunctionInterpreter *GenFunctionReader::getInterpreter() const { + return m_interpreter; +} +#ifdef NOT_THIS_ONE +std::string::const_iterator GenFunctionReader::split(std::string::const_iterator begin, std::string::const_iterator end) const { + auto cSearch=begin; + + while (1) { + auto cComma=std::find(cSearch,end,','); + int cOpen=std::count(begin,cComma,'('); + int cClose=std::count(begin,cComma,')'); + if (cOpen==cClose) return cComma; + cSearch = ++cComma; + } + // + // Make the compiler happy, but the statement should never occur. + // + return end; +} + +#endif +std::string::const_iterator GenFunctionReader::split(std::string::const_iterator begin, std::string::const_iterator end) const { + using namespace std; + + auto cSearch=begin; + std::string::const_iterator cComma=end; + + int pCount=0; + while (1) { + for (auto i=cSearch;i!=end;i++) { + char c=*i; + if (c==',') { + cComma=i; + if (pCount==0) { + return cComma; + } + else { + break; + } + } + else if (c==')') { + pCount--; + } + else if (c=='(') { + pCount++; + } + } + cSearch = ++cComma; + } + return end; +} + +GenFunctionReader::~GenFunctionReader () {} + diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionRecorder.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionRecorder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b19c202a25397bce145ced4af148c5c17725adc6 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenFunctionRecorder.cpp @@ -0,0 +1,16 @@ +#include "TFPersistification/GenFunctionRecorder.h" +#include "TFPersistification/GenFunctionPersistifier.h" +#include <stdexcept> +#include <typeinfo> + + +GenFunctionRecorder::GenFunctionRecorder(const std::type_info & info, GenFunctionPersistifier * persistifier): + m_persistifier(persistifier) { + persistifier->add(info, this); +} + +const GenFunctionPersistifier *GenFunctionRecorder::getPersistifier() const { + return m_persistifier; +} + +GenFunctionRecorder::~GenFunctionRecorder () {} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenfunIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenfunIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..217753473db1d03bfd9ac1c2c82be6251cb90df7 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/GenfunIO.cpp @@ -0,0 +1,292 @@ +#define private public +#include "GeoGenericFunctions/AbsFunction.h" +#undef private + +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenfunIO.h" + +#include "GeoGenericFunctions/Variable.h" + +#include <sstream> + +ConstTimesFunctionReader::ConstTimesFunctionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ConstTimesFunction", interpreter) {} + +inline double atof(std::string::const_iterator begin, std::string::const_iterator end) { + + std::string atom(begin,end); + std::istringstream stream(atom); + double x=0; + stream >> x; + return x; + +} + +GFPTR ConstTimesFunctionReader::execute(std::string::const_iterator begin, std::string::const_iterator end) const { + auto sep=split(begin,end); + double c=atof(begin,sep); + return GFPTR(new GeoGenfun::ConstTimesFunction(c,getInterpreter()->interpret(sep+1,end).get())); +} + + +ConstTimesFunctionRecorder::ConstTimesFunctionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ConstTimesFunction), persistifier) {} + +void ConstTimesFunctionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ConstTimesFunction * ptr = dynamic_cast<const GeoGenfun::ConstTimesFunction *> (&F); + if (!ptr) throw std::runtime_error("Error in ConstTimesFunctionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + double c1=ptr->_constant; + stream << "ConstTimesFunction" << "("; + stream << c1; + stream << ","; + getPersistifier()->persistify(*ptr->_arg); + stream << ")"; +} + +ConstPlusFunctionReader::ConstPlusFunctionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ConstPlusFunction", interpreter) {} + + +GFPTR ConstPlusFunctionReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin, end); + double c=atof(begin,sep); + return GFPTR(new GeoGenfun::ConstPlusFunction(c,getInterpreter()->interpret(sep+1,end).get())); +} + +ConstPlusFunctionRecorder::ConstPlusFunctionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ConstPlusFunction),persistifier) {} + +void ConstPlusFunctionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ConstPlusFunction * ptr = dynamic_cast<const GeoGenfun::ConstPlusFunction *> (&F); + if (!ptr) throw std::runtime_error("Error in ConstPlusFunctionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + double c1=ptr->_constant; + stream << "ConstPlusFunction" << "("; + stream << c1; + stream << ","; + getPersistifier()->persistify(*ptr->_arg); + stream << ")"; +} + +ConstMinusFunctionReader::ConstMinusFunctionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ConstMinusFunction", interpreter) {} + + +GFPTR ConstMinusFunctionReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + double c=atof(begin,sep); + return GFPTR(new GeoGenfun::ConstMinusFunction(c,getInterpreter()->interpret(sep+1,end).get())); +} + +ConstMinusFunctionRecorder::ConstMinusFunctionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ConstMinusFunction),persistifier) {} + +void ConstMinusFunctionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ConstMinusFunction * ptr = dynamic_cast<const GeoGenfun::ConstMinusFunction *> (&F); + if (!ptr) throw std::runtime_error("Error in ConstMinusFunctionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + double c1=ptr->_constant; + stream << "ConstMinusFunction" << "("; + stream << c1; + stream << ","; + getPersistifier()->persistify(*ptr->_arg); + stream << ")"; +} + +ConstOverFunctionReader::ConstOverFunctionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("ConstOverFunction", interpreter) {} + + +GFPTR ConstOverFunctionReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + double c=atof(begin,sep); + return GFPTR(new GeoGenfun::ConstOverFunction(c,getInterpreter()->interpret(sep+1,end).get())); +} + +ConstOverFunctionRecorder::ConstOverFunctionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::ConstOverFunction),persistifier) {} + +void ConstOverFunctionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::ConstOverFunction * ptr = dynamic_cast<const GeoGenfun::ConstOverFunction *> (&F); + if (!ptr) throw std::runtime_error("Error in ConstOverFunctionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + double c1=ptr->_constant; + stream << "ConstOverFunction" << "("; + stream << c1; + stream << ","; + getPersistifier()->persistify(*ptr->_arg); + stream << ")"; +} + +FunctionCompositionReader::FunctionCompositionReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionComposition", interpreter) {} + + +GFPTR FunctionCompositionReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + return GFPTR(new GeoGenfun::FunctionComposition(getInterpreter()->interpret(begin,sep).get(),getInterpreter()->interpret(sep+1,end).get())); +} + +FunctionCompositionRecorder::FunctionCompositionRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionComposition), persistifier) {} + +void FunctionCompositionRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionComposition * ptr = dynamic_cast<const GeoGenfun::FunctionComposition *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionCompositionRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionComposition("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ","; + getPersistifier()->persistify(*ptr->_arg2); + stream << ")"; +} + +FunctionNegationReader::FunctionNegationReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionNegation",interpreter) {} + + +GFPTR FunctionNegationReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + return GFPTR(new GeoGenfun::FunctionNegation(getInterpreter()->interpret(begin,end).get())); +} + +FunctionNegationRecorder::FunctionNegationRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionNegation),persistifier) {} + +void FunctionNegationRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionNegation * ptr = dynamic_cast<const GeoGenfun::FunctionNegation *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionNegationRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionNegation("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ")"; +} + +FunctionNoopReader::FunctionNoopReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionNoop",interpreter) {} + + +GFPTR FunctionNoopReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + return GFPTR(new GeoGenfun::FunctionNoop(getInterpreter()->interpret(begin,end).get())); +} + +FunctionNoopRecorder::FunctionNoopRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionNoop),persistifier) {} + +void FunctionNoopRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionNoop * ptr = dynamic_cast<const GeoGenfun::FunctionNoop *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionNoopRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionNoop("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ")"; +} + +FunctionProductReader::FunctionProductReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionProduct",interpreter) {} + + +GFPTR FunctionProductReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + return GFPTR(new GeoGenfun::FunctionProduct(getInterpreter()->interpret(begin,sep).get(),getInterpreter()->interpret(sep+1,end).get())); +} + +FunctionProductRecorder::FunctionProductRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionProduct), persistifier) {} + +void FunctionProductRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionProduct * ptr = dynamic_cast<const GeoGenfun::FunctionProduct *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionProductRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionProduct("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ","; + getPersistifier()->persistify(*ptr->_arg2); + stream << ")"; +} + +FunctionSumReader::FunctionSumReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionSum",interpreter) {} + + +GFPTR FunctionSumReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + return GFPTR(new GeoGenfun::FunctionSum(getInterpreter()->interpret(begin,sep).get(),getInterpreter()->interpret(sep+1,end).get())); +} + +FunctionSumRecorder::FunctionSumRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionSum), persistifier) {} + +void FunctionSumRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionSum * ptr = dynamic_cast<const GeoGenfun::FunctionSum *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionSumRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionSum("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ","; + getPersistifier()->persistify(*ptr->_arg2); + stream << ")"; +} + + + + + + +FunctionQuotientReader::FunctionQuotientReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionQuotient",interpreter) {} + + +GFPTR FunctionQuotientReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + return GFPTR(new GeoGenfun::FunctionQuotient(getInterpreter()->interpret(begin,sep).get(),getInterpreter()->interpret(sep+1,end).get())); +} + +FunctionQuotientRecorder::FunctionQuotientRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionQuotient), persistifier) {} + +void FunctionQuotientRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionQuotient * ptr = dynamic_cast<const GeoGenfun::FunctionQuotient *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionQuotientRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionQuotient("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ","; + getPersistifier()->persistify(*ptr->_arg2); + stream << ")"; +} + +FunctionDifferenceReader::FunctionDifferenceReader(GenFunctionInterpreter *interpreter):GenFunctionReader("FunctionDifference",interpreter) {} + + +GFPTR FunctionDifferenceReader::execute(std::string::const_iterator begin, std::string::const_iterator end ) const { + auto sep=split(begin,end); + return GFPTR(new GeoGenfun::FunctionDifference(getInterpreter()->interpret(begin,sep).get(),getInterpreter()->interpret(sep+1,end).get())); +} + +FunctionDifferenceRecorder::FunctionDifferenceRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::FunctionDifference), persistifier) {} + +void FunctionDifferenceRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::FunctionDifference * ptr = dynamic_cast<const GeoGenfun::FunctionDifference *> (&F); + if (!ptr) throw std::runtime_error("Error in FunctionDifferenceRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "FunctionDifference("; + getPersistifier()->persistify(*ptr->_arg1); + stream << ","; + getPersistifier()->persistify(*ptr->_arg2); + stream << ")"; +} + + + + + +VariableReader::VariableReader(GenFunctionInterpreter *interpreter):GenFunctionReader("X",interpreter) {} + + +GFPTR VariableReader::execute(std::string::const_iterator, std::string::const_iterator) const { + return GFPTR(new GeoGenfun::Variable()); +} + + +VariableRecorder::VariableRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Variable), persistifier) {} + +void VariableRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Variable * ptr = dynamic_cast<const GeoGenfun::Variable *> (&F); + if (!ptr) throw std::runtime_error("Error in VariableRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "X"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ModIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ModIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..61ee6a6c2f5aed6a9f978b1711ad1bd59823ab1e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/ModIO.cpp @@ -0,0 +1,32 @@ +#define private public +#include "GeoGenericFunctions/Mod.h" +#undef private + +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/ModIO.h" + +ModReader::ModReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Mod", interpreter) {} + + +GFPTR ModReader::execute(std::string::const_iterator begin, std::string::const_iterator end) const { + double y; + std::string aNumberStr(begin,end); + std::istringstream stream(aNumberStr); + stream >> y; + return GFPTR(new GeoGenfun::Mod(y)); +} + + +ModRecorder::ModRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Mod),persistifier) {} + +void ModRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Mod * ptr = dynamic_cast<const GeoGenfun::Mod *> (&F); + if (!ptr) throw std::runtime_error("Error in ModRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Mod"; + stream << "("; + stream<<ptr->_y; + stream << ")"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/RectangularIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/RectangularIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..9914d1932e53e87f8d9b8b7d428e704239d62470 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/RectangularIO.cpp @@ -0,0 +1,57 @@ +#define private public +#include "GeoGenericFunctions/Rectangular.h" +#undef private +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/RectangularIO.h" + +RectangularReader::RectangularReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Rectangular", interpreter) {} + + +GFPTR RectangularReader::execute(std::string::const_iterator begin, std::string::const_iterator end) const { + std::vector<double> elements; + auto cStart=begin; + auto cNext=std::find(cStart, end,','); + while (cNext!=end) { + std::string aNumberStr(cStart,cNext); + std::istringstream stream(aNumberStr); + double d; + stream >> d; + elements.push_back(d); + cStart=cNext+1; + cNext=std::find(cStart, end,','); + } + std::string aNumberStr(cStart,cNext); + std::istringstream stream(aNumberStr); + double d; + stream >> d; + elements.push_back(d); + if (elements.size()!=4) throw std::runtime_error("Error in Rectangular: illegal value list"); + + GeoGenfun::Rectangular *ptr=new GeoGenfun::Rectangular(); + ptr->x0().setValue(elements[0]); + ptr->x1().setValue(elements[1]); + ptr->baseline().setValue(elements[2]); + ptr->height().setValue(elements[3]); + return GFPTR(ptr); +} + + +RectangularRecorder::RectangularRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Rectangular),persistifier) {} + +void RectangularRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Rectangular * ptr = dynamic_cast<const GeoGenfun::Rectangular *> (&F); + if (!ptr) throw std::runtime_error("Error in RectangularRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Rectangular"; + stream << "("; + stream << ptr->x0().getValue(); + stream << ","; + stream << ptr->x1().getValue(); + stream << ","; + stream << ptr->baseline().getValue(); + stream << ","; + stream << ptr->height().getValue(); + stream << ")"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SinIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SinIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4a450d3af62f93d6eaa6c26df67732251eb2a700 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SinIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/SinIO.h" + +#include "GeoGenericFunctions/Sin.h" + +SinReader::SinReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Sin", interpreter) {} + + +GFPTR SinReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::Sin()); +} + + +SinRecorder::SinRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Sin),persistifier) {} + +void SinRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Sin * ptr = dynamic_cast<const GeoGenfun::Sin *> (&F); + if (!ptr) throw std::runtime_error("Error in SinRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Sin"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SqrtIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SqrtIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a06a58e10519551179a1febe1f1bf87ea123e05e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SqrtIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/SqrtIO.h" + +#include "GeoGenericFunctions/Sqrt.h" + +SqrtReader::SqrtReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Sqrt", interpreter) {} + + +GFPTR SqrtReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::Sqrt()); +} + + +SqrtRecorder::SqrtRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Sqrt),persistifier) {} + +void SqrtRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Sqrt * ptr = dynamic_cast<const GeoGenfun::Sqrt *> (&F); + if (!ptr) throw std::runtime_error("Error in SqrtRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Sqrt"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SquareIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SquareIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f70c16e042d55e38f1d353d2d59ddb468fb533e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/SquareIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/SquareIO.h" + +#include "GeoGenericFunctions/Square.h" + +SquareReader::SquareReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Square", interpreter) {} + + +GFPTR SquareReader::execute(std::string::const_iterator, std::string::const_iterator ) const { + return GFPTR(new GeoGenfun::Square()); +} + + +SquareRecorder::SquareRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Square),persistifier) {} + +void SquareRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Square * ptr = dynamic_cast<const GeoGenfun::Square *> (&F); + if (!ptr) throw std::runtime_error("Error in SquareRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Square"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TanIO.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TanIO.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ad57db23d0dbb142ea6322fe0b7602718acc4022 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TanIO.cpp @@ -0,0 +1,23 @@ +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/TanIO.h" + +#include "GeoGenericFunctions/Tan.h" + +TanReader::TanReader(GenFunctionInterpreter *interpreter):GenFunctionReader("Tan", interpreter) {} + + +GFPTR TanReader::execute(std::string::const_iterator, std::string::const_iterator) const { + return GFPTR(new GeoGenfun::Tan()); +} + + +TanRecorder::TanRecorder(GenFunctionPersistifier *persistifier): + GenFunctionRecorder(typeid(GeoGenfun::Tan),persistifier) {} + +void TanRecorder::execute(const GeoGenfun::AbsFunction & F) const { + const GeoGenfun::Tan * ptr = dynamic_cast<const GeoGenfun::Tan *> (&F); + if (!ptr) throw std::runtime_error("Error in TanRecorder:: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "Tan"; +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionInterpreter.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionInterpreter.cpp new file mode 100644 index 0000000000000000000000000000000000000000..b30b6cc9ea357368ce7963e608643cbcf741310e --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionInterpreter.cpp @@ -0,0 +1,51 @@ +#include "TFPersistification/TransFunctionInterpreter.h" +#include "TFPersistification/TransFunctionReader.h" +#include "GeoModelKernel/GeoXF.h" + +const GenFunctionInterpreter * TransFunctionInterpreter::getGenFunctionInterpreter() const { + return &m_fInterpreter; +} + + + +TransFunctionInterpreter::~TransFunctionInterpreter() { + for (auto i=m_readerMap.begin();i!=m_readerMap.end();i++) { + delete (*i).second; + } +} + +TransFunctionInterpreter::TransFunctionInterpreter(){ + new PowReader(this); + new PreMultReader(this); + new PostMultReader(this); + new ProductReader(this); +} + +void TransFunctionInterpreter::add(const std::string & str, const TransFunctionReader * reader) { + reader=m_readerMap[str]=reader; +} + + +TFPTR TransFunctionInterpreter::interpret(const std::string &exprString) const { + size_t begin = exprString.find_first_of("{"); + size_t end = exprString.find_last_of("}"); + if (!((begin!=std::string::npos) && (end!=std::string::npos))) { + throw std::runtime_error ("Ominous warning in TransFunctionPersistier: cannot parse function"); + } + std::string op = exprString.substr(0,begin); + std::string argument = exprString.substr(begin+1,end-begin-1); + // for debug only! + // std::cout << begin << " " << end << " " << op << " " << argument << std::endl; + // for (auto const& x : readerMap) { + // std::cout << x.first // string (key) + // << " : " + // << x.second // string's value + // << std::endl ; + // } + auto rIter = m_readerMap.find(op); + if (rIter==m_readerMap.end()) { + throw std::runtime_error ("Ominous warning in TransFunctionPersistier: cannot interpret function"); + } + const TransFunctionReader *reader = (*rIter).second; + return reader->execute(argument); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionPersistifier.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionPersistifier.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c984ff0011517f54b2b254532d638e795f5f1e65 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionPersistifier.cpp @@ -0,0 +1,55 @@ +#include "TFPersistification/TransFunctionPersistifier.h" +#include "TFPersistification/TransFunctionRecorder.h" +#include "GeoModelKernel/GeoXF.h" + +const GenFunctionPersistifier * TransFunctionPersistifier::getGenFunctionPersistifier() const { + return &fPersistifier; +} + +const std::string & TransFunctionPersistifier::getCodedString() const { + + codedString=getStream().str(); + delete stream; + stream=NULL; + return codedString; +} + + +TransFunctionPersistifier::~TransFunctionPersistifier() { + delete stream; + for (auto i=recorderMap.begin(); i!=recorderMap.end();i++) { + delete (*i).second; + } +} +TransFunctionPersistifier::TransFunctionPersistifier():stream(NULL) { + new PreMultRecorder(this); + new PostMultRecorder(this); + new PowRecorder(this); + new ProductRecorder(this); +} + +void TransFunctionPersistifier::add(const std::type_info & tInfo, const TransFunctionRecorder * recorder) { + recorderMap[tInfo.name()]=recorder; +} + +std::ostringstream & TransFunctionPersistifier::getStream() const { + if (!stream) stream = new std::ostringstream(); + return *stream; +} + +void TransFunctionPersistifier::persistify( const GeoXF::Function & f) const { + + auto rIter = recorderMap.find(typeid(f).name()); + if (rIter!=recorderMap.end()) { + const TransFunctionRecorder *recorder = (*rIter).second; + recorder->execute(f); + } + else { + std::ostringstream message; + message << "Ominous warning in TransFunctionPersistier: cannot persistify function with type id: " << typeid(f).name(); + throw std::runtime_error (message.str()); + } + + //throw std::runtime_error ("Ominous warning in TransFunctionPersistier: cannot persistify function"); + +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionReader.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionReader.cpp new file mode 100644 index 0000000000000000000000000000000000000000..56c402f3300a3526001c9bf3ccbc15e083202a14 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionReader.cpp @@ -0,0 +1,109 @@ +#include "TFPersistification/TransFunctionInterpreter.h" +#include "TFPersistification/GenFunctionInterpreter.h" +#include "TFPersistification/TransFunctionReader.h" + +#include "GeoModelKernel/GeoXF.h" + +#include "GeoGenericFunctions/FixedConstant.h" +#include "GeoGenericFunctions/FunctionProduct.h" +#include "GeoGenericFunctions/FunctionComposition.h" + +#include "GeoPrimitives/CLHEPtoEigenConverter.h" // TODO: to be removed when dropping CLHEP + +#include <stdexcept> +#include <sstream> + +TransFunctionReader::TransFunctionReader(const std::string & name, TransFunctionInterpreter * interpreter): + m_interpreter(interpreter) { + interpreter->add(name, this); +} + +const TransFunctionInterpreter *TransFunctionReader::getInterpreter() const { + return m_interpreter; +} + +std::pair<std::string, std::string> TransFunctionReader::split(const std::string & arg) const { + size_t comma=0; + auto cSearch=arg.begin(); + while (1) { + auto cComma=std::find(cSearch,arg.end(),'|'); + int cOpen=std::count(arg.begin(),cComma,'{'); + int cClose=std::count(arg.begin(),cComma,'}'); + comma=cComma-arg.begin(); + if (cOpen==cClose) break; + cSearch = ++cComma; + } + std::string op1=arg.substr(0,comma); + std::string op2=arg.substr(comma+1); + return std::make_pair(op1,op2); +} +TransFunctionReader::~TransFunctionReader () {} + +#include "GeoModelKernel/GeoXF.h" +#include "GeoModelKernel/GeoDefinitions.h" + +#include <iostream> +#include <typeinfo> + + +//===========Now come implementations of specific types of transfunction: +ProductReader::ProductReader(TransFunctionInterpreter *interpreter):TransFunctionReader("GeoXF::Product", interpreter) {} +PreMultReader::PreMultReader(TransFunctionInterpreter *interpreter):TransFunctionReader("GeoXF::PreMult", interpreter) {} +PostMultReader::PostMultReader(TransFunctionInterpreter *interpreter):TransFunctionReader("GeoXF::PostMult", interpreter) {} +PowReader::PowReader(TransFunctionInterpreter *interpreter):TransFunctionReader("GeoXF::Pow", interpreter) {} + + +TFPTR ProductReader::execute(const std::string & arg) const { + auto pair=split(arg); + return TFPTR(GeoXF::Product(getInterpreter()->interpret(pair.first).get(), getInterpreter()->interpret(pair.second).get()).clone()); +} + + +TFPTR PreMultReader::execute(const std::string & arg ) const { + auto pair=split(arg); + TFPTR p2=getInterpreter()->interpret(pair.second); + GeoTrf::Transform3D t1 = scanT(pair.first); + return TFPTR(GeoXF::PreMult(t1, p2.get()).clone()); +} + + +TFPTR PostMultReader::execute(const std::string & arg) const { + auto pair=split(arg); + TFPTR p1=getInterpreter()->interpret(pair.first); + GeoTrf::Transform3D t2=scanT(pair.second); + return TFPTR(GeoXF::PostMult(p1.get(), t2).clone()); +} + +TFPTR PowReader::execute(const std::string & arg) const { + auto pair=split(arg); + return TFPTR(GeoXF::Pow((scanT(pair.first)),*getInterpreter()->getGenFunctionInterpreter()->interpret(pair.second.begin(), pair.second.end())).clone()); +} + +GeoTrf::Transform3D TransFunctionReader::scanT(const std::string & exprString) const { + size_t start = exprString.find_first_of("["); + double x[12]; + int i=0; + while (1) { + size_t end = exprString.find_first_of(";",start+1); + std::string atomic=exprString.substr(start+1,end-start); + std::istringstream stream(atomic.substr(0,atomic.size()-1)); + stream >> x[i]; + start=end; + if (atomic.find("]")!=std::string::npos) break; + i++; + } + double & xx=x[0], & xy=x[1], & xz=x[2]; + double & yx=x[3], & yy=x[4], & yz=x[5]; + double & zx=x[6], & zy=x[7], & zz=x[8]; + double & dx=x[9], & dy=x[10], & dz=x[11]; + + // TODO: to drop CLHEP, this below should be replaced with Eigen-based Amg objects + CLHEP::HepRotation R; + R.set(CLHEP::Hep3Vector(xx,yx,zx), + CLHEP::Hep3Vector(xy,yy,zy), + CLHEP::Hep3Vector(xz,yz,zz)); + CLHEP::Hep3Vector D(dx,dy,dz); + HepGeom::Transform3D xf(R, D); + + return Amg::CLHEPTransformToEigen(xf); +} diff --git a/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionRecorder.cpp b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionRecorder.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5a08cc7a2d650652d34a32a6dec2335104cb7e06 --- /dev/null +++ b/DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification/src/TransFunctionRecorder.cpp @@ -0,0 +1,108 @@ +#include "TFPersistification/TransFunctionPersistifier.h" +#include "TFPersistification/GenFunctionPersistifier.h" +#include "TFPersistification/TransFunctionRecorder.h" + +// This is a data recorder. It breaks encapsulation. Normal. ==========// +#define private public +#include "GeoModelKernel/GeoXF.h" +#undef private +//=====================================================================// + + +#include <stdexcept> +TransFunctionRecorder::TransFunctionRecorder(const std::type_info & info, TransFunctionPersistifier * persistifier): + persistifier(persistifier) { + persistifier->add(info, this); +} + +const TransFunctionPersistifier *TransFunctionRecorder::getPersistifier() const { + return persistifier; +} + +TransFunctionRecorder::~TransFunctionRecorder () {} + +#define private public // +#include "GeoModelKernel/GeoXF.h" // +#undef private // + +#include "GeoModelKernel/GeoDefinitions.h" +#include "GeoPrimitives/CLHEPtoEigenConverter.h" + +#include <iostream> +#include <typeinfo> + + +//===========Now come implementations of specific types of transfunction: +ProductRecorder::ProductRecorder(TransFunctionPersistifier *persistifier):TransFunctionRecorder(typeid(GeoXF::Product),persistifier) {} +PreMultRecorder::PreMultRecorder(TransFunctionPersistifier *persistifier):TransFunctionRecorder(typeid(GeoXF::PreMult),persistifier) {} +PostMultRecorder::PostMultRecorder(TransFunctionPersistifier *persistifier):TransFunctionRecorder(typeid(GeoXF::PostMult),persistifier) {} +PowRecorder::PowRecorder(TransFunctionPersistifier *persistifier):TransFunctionRecorder(typeid(GeoXF::Pow),persistifier) {} + +void ProductRecorder::execute( const GeoXF::Function & function) const { + const GeoXF::Product * ptr= dynamic_cast<const GeoXF::Product *> (&function); + if (!ptr) throw std::runtime_error("Error in ProductRecorder: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + + stream << "GeoXF::Product" << "{"; + getPersistifier()->persistify(*ptr->m_arg1); + stream << "|"; + getPersistifier()->persistify(*ptr->m_arg2); + stream << "}"; + return; +} + + +void PreMultRecorder::execute( const GeoXF::Function & function) const { + const GeoXF::PreMult * ptr= dynamic_cast<const GeoXF::PreMult *> (&function); + if (!ptr) throw std::runtime_error("Error in PreMultRecorder: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "GeoXF::PreMult" << "{"; + const HepGeom::Transform3D & tPtr = Amg::EigenTransformToCLHEP(ptr->m_arg1); + stream << "Transform[" + << tPtr.xx() << ";" << tPtr.xy() << ";" << tPtr.xz() << ";" + << tPtr.yx() << ";" << tPtr.yy() << ";" << tPtr.yz() << ";" + << tPtr.zx() << ";" << tPtr.zy() << ";" << tPtr.zz() << ";" + << tPtr.dx() << ";" << tPtr.dy() << ";" << tPtr.dz() << "]"; + stream << "|"; + getPersistifier()->persistify(*ptr->m_arg2); + stream << "}"; + return; +} + + +void PostMultRecorder::execute( const GeoXF::Function & function) const { + const GeoXF::PostMult * ptr= dynamic_cast<const GeoXF::PostMult *> (&function); + if (!ptr) throw std::runtime_error("Error in PostMultRecorder: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "GeoXF::PostMult" << "{"; + getPersistifier()->persistify(*ptr->m_arg1); + stream << "|"; + const HepGeom::Transform3D & tPtr = Amg::EigenTransformToCLHEP(ptr->m_arg2); + stream << "Transform[" + << tPtr.xx() << ";" << tPtr.xy() << ";" << tPtr.xz() << ";" + << tPtr.yx() << ";" << tPtr.yy() << ";" << tPtr.yz() << ";" + << tPtr.zx() << ";" << tPtr.zy() << ";" << tPtr.zz() << ";" + << tPtr.dx() << ";" << tPtr.dy() << ";" << tPtr.dz() << "]"; + stream << "}"; + return; +} + + + +void PowRecorder::execute( const GeoXF::Function & function) const { + const GeoXF::Pow * ptr= dynamic_cast<const GeoXF::Pow *> (&function); + if (!ptr) throw std::runtime_error("Error in PowRecorder: wrong function type"); + std::ostringstream & stream = getPersistifier()->getStream(); + stream << "GeoXF::Pow" << "{"; + const HepGeom::Transform3D & tPtr = Amg::EigenTransformToCLHEP(ptr->m_xf); + stream << "Transform[" + << tPtr.xx() << ";" << tPtr.xy() << ";" << tPtr.xz() << ";" + << tPtr.yx() << ";" << tPtr.yy() << ";" << tPtr.yz() << ";" + << tPtr.zx() << ";" << tPtr.zy() << ";" << tPtr.zz() << ";" + << tPtr.dx() << ";" << tPtr.dy() << ";" << tPtr.dz() << "]"; + stream << "|"; + getPersistifier()->getGenFunctionPersistifier()->persistify(*ptr->m_function); + stream << getPersistifier()->getGenFunctionPersistifier()->getCodedString(); + stream << "}"; + return; +} diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/CMakeLists.txt b/DetectorDescription/GeoModel/GeoModelUtilities/CMakeLists.txt index e0d3a273ec4cf8e87c1954cb406a341ed0028229..6664566113d3f0acb30586fb0ac594c3fe77581a 100644 --- a/DetectorDescription/GeoModel/GeoModelUtilities/CMakeLists.txt +++ b/DetectorDescription/GeoModel/GeoModelUtilities/CMakeLists.txt @@ -5,6 +5,7 @@ # Declare the package name: atlas_subdir( GeoModelUtilities ) +if(NOT BUILDVP1LIGHT) # Declare the package's dependencies: atlas_depends_on_subdirs( PUBLIC Control/AthenaBaseComps @@ -27,4 +28,32 @@ atlas_add_library( GeoModelUtilities INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${CORAL_INCLUDE_DIRS} ${EIGEN_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} LINK_LIBRARIES ${Boost_LIBRARIES} ${CORAL_LIBRARIES} ${EIGEN_LIBRARIES} ${GEOMODEL_LIBRARIES} AthenaBaseComps SGTools PRIVATE_LINK_LIBRARIES GaudiKernel ) +endif() +if(BUILDVP1LIGHT) +# Declare the package's dependencies: +#atlas_depends_on_subdirs( PUBLIC +# DetectorDescription/GeoModel/GeoModelKernel ) + +# External dependencies: +find_package( CLHEP ) +find_package( GeoModel ) +find_package( Eigen ) +file(GLOB SOURCES src/GeoMPVEntry.cxx + src/GeoModelExperiment.cxx + src/GeoOpticalSurface.cxx + src/GeoBorderSurface.cxx + src/GeoMaterialPropertiesTable.cxx + src/StoredAlignX.cxx + src/GeoExtendedMaterial.cxx + src/GeoMaterialPropertyVector.cxx + src/GeoOpticalPhysVol.cxx + src/StoredPhysVol.cxx) + +# Component(s) in the package: +atlas_add_library( GeoModelUtilities + ${SOURCES} + PUBLIC_HEADERS GeoModelUtilities + INCLUDE_DIRS ${EIGEN_INCLUDE_DIRS} ${GEOMODEL_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} ${EIGEN_LIBRARIES} ${GEOMODEL_LIBRARIES} ) +endif() diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoExtendedMaterial.h b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoExtendedMaterial.h index 6c7ce0654f5fe5a6aa11667793252a987918d3ee..bae62e432664dbb7bb7a2ce8c028c1cc1c5818d6 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoExtendedMaterial.h +++ b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoExtendedMaterial.h @@ -6,10 +6,19 @@ #define GeoExtendedMaterial_h 1 #include "GeoModelKernel/GeoMaterial.h" -#include "GaudiKernel/PhysicalConstants.h" #include "GeoModelUtilities/GeoMaterialPropertiesTable.h" +// Physical constants +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::STP_Temperature' +#else + #include "GaudiKernel/PhysicalConstants.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::STP_Temperature' +#endif + + enum GeoMaterialState { stateUndefined, stateSolid, stateLiquid, stateGas }; class GeoExtendedMaterial : public GeoMaterial @@ -18,8 +27,8 @@ class GeoExtendedMaterial : public GeoMaterial GeoExtendedMaterial(const std::string &Name, double Density, GeoMaterialState State = stateUndefined, - double Temperature = Gaudi::Units::STP_Temperature, - double Pressure = Gaudi::Units::STP_Pressure); + double Temperature = SYSTEM_OF_UNITS::STP_Temperature, + double Pressure = SYSTEM_OF_UNITS::STP_Pressure); virtual ~GeoExtendedMaterial(); diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelExperiment.h b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelExperiment.h index be4267a9d50fa00c551abf45350a733d658dbae6..b3a541bc0943bc4728eaa55f57a83f6a5f4af68b 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelExperiment.h +++ b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelExperiment.h @@ -15,7 +15,9 @@ #ifndef GEOMODELSVC_GEOMODELEXPERIMENT_H #define GEOMODELSVC_GEOMODELEXPERIMENT_H #include "GeoModelKernel/GeoVPhysVol.h" -#include "AthenaKernel/CLASS_DEF.h" +#ifndef BUILDVP1LIGHT + #include "AthenaKernel/CLASS_DEF.h" +#endif #include <set> #include <string> #include <vector> @@ -71,6 +73,9 @@ public: // Return the World physical volume: // GeoPhysVol *getPhysVol(); // const GeoPhysVol *getPhysVol() const; // + // + // Print a list of all the managers: + std::vector<std::string> getListOfManagers() const; // // // Manage the managers: // void addManager(const GeoVDetectorManager *); // @@ -92,9 +97,11 @@ public: }; +#ifndef BUILDVP1LIGHT //using the macros below we can assign an identifier (and a version) //This is required and checked at compile time when you try to record/retrieve -CLASS_DEF(GeoModelExperiment, 9875, 1) + CLASS_DEF(GeoModelExperiment, 9875, 1) +#endif #endif // GEOMODELSVC_GEOMODELEXPERIMENT_H diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelTool.h b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelTool.h index 4a8b7735f5be044c79af097441769e08c6feb296..8772c2a4f31b1fc0669d17caa528466b1747bfaf 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelTool.h +++ b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/GeoModelTool.h @@ -5,6 +5,8 @@ #ifndef GEOMODELSVC_GEOMODELTOOL_H #define GEOMODELSVC_GEOMODELTOOL_H +#ifndef BUILDVP1LIGHT + #include "GeoModelInterfaces/IGeoModelTool.h" #include "AthenaBaseComps/AthAlgTool.h" @@ -31,6 +33,8 @@ protected: GeoVDetectorManager* m_detector; // The corresponding }; +#endif // BUILDVP1LIGHT + #endif // GEOMODELSVC_DETDESCRTOOL_H diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredAlignX.h b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredAlignX.h index 694e33744182c8b6f5c8534b2c5f391f6dbd7a86..e3e708854f51394d97a4afc6484bf5702e504b7e 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredAlignX.h +++ b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredAlignX.h @@ -12,7 +12,10 @@ #ifndef STOREDALIGNX_H #define STOREDALIGNX_H -#include "AthenaKernel/CLASS_DEF.h" + +#ifndef BUILDVP1LIGHT + #include "AthenaKernel/CLASS_DEF.h" +#endif #include <set> #include <string> @@ -43,9 +46,11 @@ public: }; -CLASS_DEF(StoredAlignX, 9878, 1) +#ifndef BUILDVP1LIGHT + CLASS_DEF(StoredAlignX, 9878, 1) +#endif -#endif +#endif // class diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredPhysVol.h b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredPhysVol.h index a647e202b12e724d3dbaa8661a9153b0a155516d..4aecca25e94b948a1c81043bde614337bf0a3924 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredPhysVol.h +++ b/DetectorDescription/GeoModel/GeoModelUtilities/GeoModelUtilities/StoredPhysVol.h @@ -13,7 +13,9 @@ #ifndef STOREDPHYSVOL_H #define STOREDPHYSVOL_H #include "GeoModelKernel/GeoVPhysVol.h" -#include "AthenaKernel/CLASS_DEF.h" +#ifndef BUILDVP1LIGHT + #include "AthenaKernel/CLASS_DEF.h" +#endif #include <set> #include <string> @@ -44,7 +46,9 @@ public: }; -CLASS_DEF(StoredPhysVol, 9877, 1) +#ifndef BUILDVP1LIGHT + CLASS_DEF(StoredPhysVol, 9877, 1) +#endif #endif diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelExperiment.cxx b/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelExperiment.cxx index 475f39a11b0803cd15d897afefa129140f30ea68..69c4a0fc21e32314015bcb192e66463b62ceb3b5 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelExperiment.cxx +++ b/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelExperiment.cxx @@ -38,6 +38,8 @@ const GeoPhysVol *GeoModelExperiment::getPhysVol() const{ return m_physVol; } + + GeoModelExperiment::ConstIterator GeoModelExperiment::beginManager() const { return m_managers.begin(); } @@ -70,6 +72,15 @@ const GeoVDetectorManager *GeoModelExperiment::getManager(const std::string & na } +std::vector<std::string> GeoModelExperiment::getListOfManagers() const { + std::vector<std::string> managersList; + for(auto manager : m_managers) { + managersList.push_back(manager->getName()); + } + return managersList; +} + + GeoModelExperiment::NameEquals::NameEquals(const std::string & name):m_name(name) { } diff --git a/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelTool.cxx b/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelTool.cxx index 34f3d3f6e097fde95d21071628ad16343f91c291..1728281c98dc7bc1e2657aa000e09c28bb0d17d2 100755 --- a/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelTool.cxx +++ b/DetectorDescription/GeoModel/GeoModelUtilities/src/GeoModelTool.cxx @@ -2,6 +2,8 @@ Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ +#ifndef BUILDVP1LIGHT + #include "GeoModelUtilities/GeoModelTool.h" /** @@ -42,3 +44,5 @@ StatusCode GeoModelTool::registerCallback() // Return Failure since no function has been registered return StatusCode::FAILURE; } + +#endif // BUILDVP1LIGHT diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/CMakeLists.txt b/DetectorDescription/GeoModel/GeoSpecialShapes/CMakeLists.txt index 8411eee2fe6579b4e7f1edd93998dd7fa23906da..1a4f540b25acda51cdae7ef3663680395c7af043 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/CMakeLists.txt +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/CMakeLists.txt @@ -25,6 +25,10 @@ find_package( CORAL COMPONENTS CoralBase CoralKernel RelationalAccess ) find_package( ROOT COMPONENTS Matrix Core Tree MathCore Hist RIO pthread MathMore Minuit Minuit2 Physics HistPainter Rint ) find_package( GeoModel ) + + +if(NOT BUILDVP1LIGHT) +find_package( CORAL COMPONENTS CoralBase CoralKernel RelationalAccess ) # Component(s) in the package: atlas_add_library( GeoSpecialShapes src/*.cxx @@ -47,4 +51,29 @@ atlas_add_dictionary( LArWheelEnums GeoSpecialShapes/selectionEnums.xml INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${CORAL_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} ${CLHEP_INCLUDE_DIRS} LINK_LIBRARIES ${Boost_LIBRARIES} ${CORAL_LIBRARIES} ${ROOT_LIBRARIES} ${GSL_LIBRARIES} ${CLHEP_LIBRARIES} ${GEOMODEL_LIBRARIES} SGTools StoreGateLib SGtests AthenaKernel CxxUtils GeoModelUtilities GaudiKernel GeoSpecialShapes ) +endif() + +if(BUILDVP1LIGHT) +# Component(s) in the package: +atlas_add_library( GeoSpecialShapes + src/*.cxx + src/LArWheelCalculator_Impl/*.cxx + PUBLIC_HEADERS GeoSpecialShapes + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} + PRIVATE_INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} + DEFINITIONS ${CLHEP_DEFINITIONS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} GeoModelKernel + PRIVATE_LINK_LIBRARIES ${Boost_LIBRARIES} ${ROOT_LIBRARIES} ${GSL_LIBRARIES} CxxUtils GeoModelUtilities ) +atlas_add_dictionary( LArGeoCheckerDict + GeoSpecialShapes/LArGeoCheckerDict.h + GeoSpecialShapes/selection.xml + INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} ${CLHEP_INCLUDE_DIRS} + LINK_LIBRARIES ${Boost_LIBRARIES} ${CORAL_LIBRARIES} ${ROOT_LIBRARIES} ${GSL_LIBRARIES} ${CLHEP_LIBRARIES} ${GEOMODEL_LIBRARIES} CxxUtils GeoModelUtilities GeoSpecialShapes ) + +atlas_add_dictionary( LArWheelEnums + GeoSpecialShapes/LArWheelCalculatorEnums.h + GeoSpecialShapes/selectionEnums.xml + INCLUDE_DIRS ${Boost_INCLUDE_DIRS} ${ROOT_INCLUDE_DIRS} ${CLHEP_INCLUDE_DIRS} + LINK_LIBRARIES ${Boost_LIBRARIES} ${ROOT_LIBRARIES} ${GSL_LIBRARIES} ${CLHEP_LIBRARIES} GeoModelKernel CxxUtils GeoModelUtilities GeoSpecialShapes ) +endif() diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArCustomShape.h b/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArCustomShape.h index 5b84429c3f8ac05d99eae74234264996cfb2f8ac..a566f4b65b05b36a050e56533a550deec68c4a84 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArCustomShape.h +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArCustomShape.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef LArCustomShape_h @@ -8,9 +8,11 @@ #include <string> #include <map> -#include "GaudiKernel/ServiceHandle.h" -#include "GaudiKernel/StatusCode.h" -#include "StoreGate/StoreGateSvc.h" +#ifndef XAOD_STANDALONE + #include "GaudiKernel/ServiceHandle.h" + #include "GaudiKernel/StatusCode.h" + #include "StoreGate/StoreGateSvc.h" +#endif // XAOD_STANDALONE #include "GeoModelKernel/GeoShape.h" #include "GeoSpecialShapes/LArWheelCalculator.h" @@ -26,16 +28,17 @@ class LArCustomShape : public GeoShape { public: - - typedef ServiceHandle<StoreGateSvc> StoreGateSvc_t; - typedef std::pair<LArG4::LArWheelCalculator_t, int> CalcDef_t; - typedef std::map<std::string, CalcDef_t> ShapeCalc_typemap; - - /// The custom shape has only one property: a string that contains - /// the name of the particular shape. In the GeoModel->Geant4 - /// conversion, this name will be matched against a list of custom - /// classes that inherit from G4VSolid to get the correct custom - /// solid. + #ifndef XAOD_STANDALONE + typedef ServiceHandle<StoreGateSvc> StoreGateSvc_t; + #endif // XAOD_STANDALONE + typedef std::pair<LArG4::LArWheelCalculator_t, int> CalcDef_t; + typedef std::map<std::string, CalcDef_t> ShapeCalc_typemap; + + // The custom shape has only one property: a string that contains + // the name of the particular shape. In the GeoModel->Geant4 + // conversion, this name will be matched against a list of custom + // classes that inherit from G4VSolid to get the correct custom + // solid. LArCustomShape(const std::string& shapeName); /// Return the calculator: @@ -62,20 +65,25 @@ class LArCustomShape : public GeoShape /// Executes a GeoShapeAction virtual void exec(GeoShapeAction* action) const; +#ifndef XAOD_STANDALONE /** @brief The standard @c StoreGateSvc/DetectorStore * Returns (kind of) a pointer to the @c StoreGateSvc */ - StoreGateSvc_t& detStore() const; + StoreGateSvc_t& detStore() const; +#endif // XAOD_STANDALONE protected: virtual ~LArCustomShape(); private: + #if defined XAOD_STANDALONE + int createCalculator(const CalcDef_t & cdef); + #else // XAOD_STANDALONE + StatusCode createCalculator(const CalcDef_t & cdef); + #endif - StatusCode createCalculator(const CalcDef_t & cdef); - - /// Prohibited operations. + // Prohibited operations. LArCustomShape(const LArCustomShape &right); const LArCustomShape & operator=(const LArCustomShape &right); @@ -90,8 +98,10 @@ class LArCustomShape : public GeoShape /// The calculator: const LArWheelCalculator *m_calculator; - /// Pointer to StoreGate (detector store by default) - mutable StoreGateSvc_t m_detStore; + #ifndef XAOD_STANDALONE + /// Pointer to StoreGate (detector store by default) + mutable StoreGateSvc_t m_detStore; + #endif // XAOD_STANDALONE }; @@ -103,8 +113,11 @@ inline ShapeType LArCustomShape::getClassTypeID() { return s_classTypeID; } -inline ServiceHandle<StoreGateSvc>& LArCustomShape::detStore() const { - return m_detStore; -} +#ifndef XAOD_STANDALONE + inline ServiceHandle<StoreGateSvc>& LArCustomShape::detStore() const { + return m_detStore; + } +#endif // XAOD_STANDALONE + -#endif +#endif // LArCustomShape_h diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArWheelCalculator.h b/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArWheelCalculator.h index cb49e32b54e389393f0d3edcd9ae2b45b5ff07f1..a23e0653af96e90fe261eac814cb25aceafce459 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArWheelCalculator.h +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/GeoSpecialShapes/LArWheelCalculator.h @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #ifndef GEOSPECIALSHAPES_LARWHEELCALCULATOR_H @@ -8,7 +8,9 @@ #include <vector> #include "CLHEP/Vector/ThreeVector.h" -#include "SGTools/CLASS_DEF.h" +#ifndef XAOD_STANDALONE + #include "SGTools/CLASS_DEF.h" +#endif // XAOD_STANDALONE #include "GeoSpecialShapes/LArWheelCalculatorEnums.h" @@ -209,8 +211,10 @@ class LArWheelCalculator void fill_sincos_parameterization(); }; -//using the macro below we can assign an identifier (and a version) -//This is required and checked at compile time when you try to record/retrieve -CLASS_DEF(LArWheelCalculator, 900345678, 1) +#ifndef XAOD_STANDALONE + //using the macro below we can assign an identifier (and a version) + //This is required and checked at compile time when you try to record/retrieve + CLASS_DEF(LArWheelCalculator , 900345678 , 1) +#endif // XAOD_STANDALONE #endif // GEOSPECIALSHAPES_LARWHEELCALCULATOR_H diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArCustomShape.cxx b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArCustomShape.cxx index defe55630faf135f0cbd75a4e1c08eadf5ab9e2f..f80b7daf6b6c2b68e4bc270985d1943ef5170de3 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArCustomShape.cxx +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArCustomShape.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ #include "GeoSpecialShapes/LArCustomShape.h" @@ -64,15 +64,23 @@ const LArCustomShape::ShapeCalc_typemap LArCustomShape::s_calculatorTypes = { LArCustomShape::LArCustomShape(const std::string& a_shapeName) : m_shapeName(a_shapeName), - m_calculator(0), - m_detStore( "StoreGateSvc/DetectorStore", a_shapeName ) + m_calculator(0) + #ifndef XAOD_STANDALONE + ,m_detStore( "StoreGateSvc/DetectorStore", a_shapeName ) + #endif // XAOD_STANDALONE { - // map.at throws std::out_of_range exception on unknown shape name - if ( createCalculator( s_calculatorTypes.at(a_shapeName) ).isFailure() ) { - std::string error = std::string("Can't create LArWheelCalculator for name ") + a_shapeName + " in LArCustomShape constructor"; - throw std::runtime_error(error); - } - //std::cout << "-->>> LArCustomShape::m_calculator=" << m_calculator << "\n"; + #if defined XAOD_STANDALONE + if ( createCalculator( s_calculatorTypes.at(a_shapeName) ) == 1 ) { // map.at throws std::out_of_range exception on unknown shape name + std::string error = std::string("Can't create LArWheelCalculator for name ") + a_shapeName + " in LArCustomShape constructor"; + throw std::runtime_error(error); + } + #else // XAOD_STANDALONE + if ( createCalculator( s_calculatorTypes.at(a_shapeName) ).isFailure() ) { // map.at throws std::out_of_range exception on unknown shape name + std::string error = std::string("Can't create LArWheelCalculator for name ") + a_shapeName + " in LArCustomShape constructor"; + throw std::runtime_error(error); + } + #endif // Athena + //std::cout << "-->>> LArCustomShape::m_calculator=" << m_calculator << "\n"; } LArCustomShape::~LArCustomShape() @@ -80,19 +88,34 @@ LArCustomShape::~LArCustomShape() //delete m_calculator; } -StatusCode LArCustomShape::createCalculator(const CalcDef_t & cdef) -{ - LArG4::LArWheelCalculator_t wheelType = cdef.first; - int zside = cdef.second; +#if defined XAOD_STANDALONE +int LArCustomShape::createCalculator(const CalcDef_t & cdef) { // LArG4::LArWheelCalculator_t wheelType, int zside + LArG4::LArWheelCalculator_t wheelType = cdef.first; + int zside = cdef.second; + + m_calculator = new LArWheelCalculator(wheelType, zside); + std::string calcDSname = std::string("LAr::EMEC::")+ (zside>0?"Pos::":"Neg::")+LArWheelCalculator::LArWheelCalculatorTypeString(wheelType); + + //std::cout << "-->>> LArCustomShape::createCalculator: m_calculator=" << m_calculator << ", name="<< calcDSname <<"\n"; + // ownership is passed to detStore + if (m_calculator==NULL) + return 1; + else + return 0; +} +#else // XAOD_STANDALONE +StatusCode LArCustomShape::createCalculator(const CalcDef_t & cdef) { // LArG4::LArWheelCalculator_t wheelType, int zside + LArG4::LArWheelCalculator_t wheelType = cdef.first; + int zside = cdef.second; - m_calculator = new LArWheelCalculator(wheelType, zside); - std::string calcDSname = std::string("LAr::EMEC::") + (zside>0?"Pos::":"Neg::") + - LArWheelCalculator::LArWheelCalculatorTypeString(wheelType); + m_calculator = new LArWheelCalculator(wheelType, zside); + std::string calcDSname = std::string("LAr::EMEC::")+ (zside>0?"Pos::":"Neg::")+LArWheelCalculator::LArWheelCalculatorTypeString(wheelType); - //std::cout << "-->>> LArCustomShape::createCalculator: m_calculator=" << m_calculator << ", name="<< calcDSname <<"\n"; - // ownership is passed to detStore - return detStore()->record(m_calculator, calcDSname); + //std::cout << "-->>> LArCustomShape::createCalculator: m_calculator=" << m_calculator << ", name="<< calcDSname <<"\n"; + // ownership is passed to detStore + return detStore()->record(m_calculator, calcDSname); } +#endif // Athena const LArWheelCalculator *LArCustomShape::calculator() const { diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator.cxx b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator.cxx index f01e92b254eccaa481f26c5eb3d660a798ff3d44..11a481c860f3ce6e4e7b3f54362d3f0b7b405e87 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator.cxx +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ // LArWheelCalculator 19-Apr-2001 Bill Seligman @@ -9,21 +9,23 @@ #include <climits> #include <cassert> -#include "GaudiKernel/ISvcLocator.h" -#include "GaudiKernel/Bootstrap.h" -#include "GaudiKernel/MsgStream.h" -#include "GaudiKernel/PhysicalConstants.h" -#include "GeoModelInterfaces/IGeoModelSvc.h" +#ifndef BUILDVP1LIGHT + #include "GaudiKernel/ISvcLocator.h" + #include "GaudiKernel/Bootstrap.h" + #include "GaudiKernel/MsgStream.h" + #include "GaudiKernel/PhysicalConstants.h" + #include "GeoModelInterfaces/IGeoModelSvc.h" + #include "RDBAccessSvc/IRDBRecord.h" + #include "RDBAccessSvc/IRDBRecordset.h" + #include "RDBAccessSvc/IRDBAccessSvc.h" + #include "./LArWheelCalculator_Impl/RDBParamReader.h" + #include "./LArWheelCalculator_Impl/RDBParamRecords.h" +#endif + #include "GeoModelUtilities/DecodeVersionKey.h" -#include "RDBAccessSvc/IRDBRecord.h" -#include "RDBAccessSvc/IRDBRecordset.h" -#include "RDBAccessSvc/IRDBAccessSvc.h" #include "GeoSpecialShapes/LArWheelCalculator.h" -#include "./LArWheelCalculator_Impl/RDBParamReader.h" -#include "./LArWheelCalculator_Impl/RDBParamRecords.h" - #include "./LArWheelCalculator_Impl/DistanceCalculatorFactory.h" #include "./LArWheelCalculator_Impl/FanCalculatorFactory.h" @@ -130,7 +132,7 @@ LArWheelCalculator::LArWheelCalculator(LArG4::LArWheelCalculator_t a_wheelType, // Access source of detector parameters. msg << MSG::VERBOSE << "initializing data members from DB..." << endmsg; - +#ifndef BUILDVP1LIGHT IGeoModelSvc *geoModel; IRDBAccessSvc* rdbAccess; @@ -210,6 +212,27 @@ LArWheelCalculator::LArWheelCalculator(LArG4::LArWheelCalculator_t a_wheelType, << "m_WheelThickness : " << m_WheelThickness / cm << " [cm]" << std::endl << "m_dWRPtoFrontFace : " << m_dWRPtoFrontFace / cm << " [cm]" << endmsg; +#endif +#ifdef BUILDVP1LIGHT //FIXME: check all this!!! + double m_zWheelRefPoint = 999;// / cm + double m_dMechFocaltoWRP = 999;// / cm << " [cm]" << std::endl + double m_dElecFocaltoWRP = 999;// : " << m_dElecFocaltoWRP / cm << " [cm]" << std::endl + double m_HalfGapBetweenWheels = 999;// : " << m_HalfGapBetweenWheels / cm << " [cm]" << std::endl + double m_rOuterCutoff = 999;// : " << m_rOuterCutoff / cm << " [cm]" << std::endl + double m_zWheelFrontFace = 999;// : " << m_zWheelFrontFace / cm << " [cm]" << std::endl + double m_zWheelBackFace = 999;// : " << m_zWheelBackFace / cm << " [cm]" << std::endl + double m_zShift = 999;// : " << m_zShift / cm << " [cm]" << std::endl + double m_phiRotation = true;//? "true": "false") << std::endl + double m_eta_low = 999;// + double m_eta_mid = 999;// + double m_eta_hi = 999;// + + double m_WheelThickness = 999;// : " << m_WheelThickness / cm << " [cm]" << std::endl + double m_dWRPtoFrontFace = 999;// : " << m_dWRPtoFrontFace / cm << " [cm]" +#endif + + + // Constructor initializes the geometry. diff --git a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator_Impl/DistanceCalculatorFactory.h b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator_Impl/DistanceCalculatorFactory.h index d8185378dad39825c0acb67ed87dc512227031db..946aabc8950e4a99ae1a6862e11dcb9baf3f4113 100644 --- a/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator_Impl/DistanceCalculatorFactory.h +++ b/DetectorDescription/GeoModel/GeoSpecialShapes/src/LArWheelCalculator_Impl/DistanceCalculatorFactory.h @@ -10,7 +10,9 @@ #include <string> #include "IDistanceCalculator.h" -#include "RDBAccessSvc/IRDBAccessSvc.h" +#ifndef BUILDVP1LIGHT + #include "RDBAccessSvc/IRDBAccessSvc.h" +#endif #include "GeoModelUtilities/DecodeVersionKey.h" class LArWheelCalculator; diff --git a/DetectorDescription/GeoPrimitives/GeoPrimitives/CLHEPtoEigenConverter.h b/DetectorDescription/GeoPrimitives/GeoPrimitives/CLHEPtoEigenConverter.h index 9fac27cc74e5d9f1691120534cde79dac8f530c5..db3d0aea4ce18054ac5e94c9388f598aa9eeb952 100644 --- a/DetectorDescription/GeoPrimitives/GeoPrimitives/CLHEPtoEigenConverter.h +++ b/DetectorDescription/GeoPrimitives/GeoPrimitives/CLHEPtoEigenConverter.h @@ -1,25 +1,27 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ -/* - * CLHEPtoEigenConverter.h - * - * Created on: Jun 26, 2013 - * Author: rlangenb - * - * update: rbianchi - Feb 25 2014 - */ +/** +* @file CLHEPtoEigenConverter.h +* +* @author rlangenb +* @date Jun 26, 2013 +* +* @author Riccardo Maria BIANCHI <riccardo.maria.bianchi@cern.ch> +* @date Feb 25, 2014 +* @date Jan 23, 2019 +* +* @section Description +* +* The CLHEPtoEigenConverter methods convert transformations, rotations, and vectors from and to CLHEP and Eigen. +*/ #ifndef CLHEPTOEIGENCONVERTER_H_ #define CLHEPTOEIGENCONVERTER_H_ -// Make it clear that this header is not for standalone usage: -#ifdef XAOD_STANDALONE -#error "This header is not meant to be used in standalone mode" -#endif // XAOD_STANDALONE - #include "GeoPrimitives/GeoPrimitives.h" + #include "CLHEP/Geometry/Transform3D.h" #include "CLHEP/Geometry/Point3D.h" #include "CLHEP/Vector/Rotation.h" @@ -27,6 +29,12 @@ namespace Amg { + /** + * Converts a CLHEP-based HepGeom::Transform3D into an Eigen Amg::Transform3D. + * + * @param CLHEPtransf A CLHEP-based HepGeom::Transform3D. + * @return An Eigen-based Amg::Transform3D. + */ inline Amg::Transform3D CLHEPTransformToEigen( const HepGeom::Transform3D& CLHEPtransf) { Amg::Transform3D t = Amg::Transform3D(); @@ -46,6 +54,12 @@ namespace Amg { return t; } + /** + * Converts a CLHEP::HepRotation into an Eigen-based Amg::RotationMatrix3D. + * + * @param CLHEProtation A CLHEP::HepRotation. + * @return An Eigen-based Amg::RotationMatrix3D. + */ inline RotationMatrix3D CLHEPRotationToEigen( const CLHEP::HepRotation& CLHEProtation) { Amg::RotationMatrix3D t; @@ -61,21 +75,34 @@ namespace Amg { t(2, 2) = CLHEProtation(2, 2); return t; } - inline Translation3D CLHEPTranslationToEigen( + + /** + * Converts a CLHEP::Hep3Vector into an Eigen-based Amg::Translation3D. + * + * @param CLHEPtranslation A CLHEP::Hep3Vector. + * @return An Eigen-based Amg::Translation3D. + */ + inline Amg::Translation3D CLHEPTranslationToEigen( const CLHEP::Hep3Vector& CLHEPtranslation) { - return Translation3D( + return Amg::Translation3D( Vector3D(CLHEPtranslation[0], CLHEPtranslation[1], CLHEPtranslation[2])); } - // from: http://proj-clhep.web.cern.ch/proj-clhep/doc/CLHEP_2_0_4_7/doxygen/html/classHepGeom_1_1Translate3D.html#f2df65781931c7df9cc2858de2c89151 - //Amg::Transform3D(1, 0, 0, CLHEPtranslate3D[0], - // 0, 1, 0, CLHEPtranslate3D[1], - // 0, 0, 1, CLHEPtranslate3D[2]); + /** + * Converts a CLHEP-based HepGeom::Translate3 into an Eigen-based Amg::Transform3D. + * + * @param CLHEPtranslate3D A CLHEP-based HepGeom::Translate3. + * @return An Eigen-based Amg::Transform3D. + */ inline Amg::Transform3D CLHEPTranslate3DToEigen( const HepGeom::Translate3D& CLHEPtranslate3D) { + // from: http://proj-clhep.web.cern.ch/proj-clhep/doc/CLHEP_2_0_4_7/doxygen/html/classHepGeom_1_1Translate3D.html#f2df65781931c7df9cc2858de2c89151 + //Amg::Transform3D(1, 0, 0, CLHEPtranslate3D[0], + // 0, 1, 0, CLHEPtranslate3D[1], + // 0, 0, 1, CLHEPtranslate3D[2]); Amg::Transform3D t = Amg::Transform3D(); t.setIdentity(); t(0, 3) = CLHEPtranslate3D(0, 3); @@ -84,6 +111,12 @@ namespace Amg { return t; } + /** + * Converts an Eigen-based Amg::Transform3D into a CLHEP-based HepGeom::Transform3D. + * + * @param eigenTransf An Eigen-based Amg::Transform3D. + * @return A CLHEP-based HepGeom::Transform3D. + */ inline HepGeom::Transform3D EigenTransformToCLHEP( const Amg::Transform3D& eigenTransf) { CLHEP::HepRotation rotation( @@ -95,10 +128,22 @@ namespace Amg { return t; } + /** + * Converts a CLHEP-based CLHEP::Hep3Vector into an Eigen-based Amg::Vector3D. + * + * @param CLHEPvector A CLHEP-based CLHEP::Hep3Vector. + * @return An Eigen-based Amg::Vector3D. + */ inline Amg::Vector3D Hep3VectorToEigen(const CLHEP::Hep3Vector& CLHEPvector) { - return Vector3D(CLHEPvector[0], CLHEPvector[1], CLHEPvector[2]); + return Amg::Vector3D(CLHEPvector[0], CLHEPvector[1], CLHEPvector[2]); } + /** + * Converts an Eigen-based Amg::Vector3D into a CLHEP-based CLHEP::Hep3Vector. + * + * @param eigenvector An Eigen-based Amg::Vector3D. + * @return A CLHEP-based CLHEP::Hep3Vector. + */ inline CLHEP::Hep3Vector EigenToHep3Vector(const Amg::Vector3D& eigenvector) { return CLHEP::Hep3Vector(eigenvector[0], eigenvector[1], eigenvector[2]); } diff --git a/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitives.h b/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitives.h index d6f06a7e2dcbba1ff2cd600cdc82a3df7bfc7358..7acd59eca2f1a2dbe29903871907d85c852ee59e 100644 --- a/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitives.h +++ b/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitives.h @@ -23,12 +23,13 @@ @author Robert Johannes Langenberg <robert.langenberg@cern.ch> @author Andreas Salzburger <Andreas.Salzburger@cern.ch> + @author Riccardo Maria BIANCHI <riccardo.maria.bianchi@cern.ch> */ namespace Amg { - /** elment for code readability + /** element for code readability - please use these for access to the member variables if needed, e.g. double z = position[Amg::z]; double px = momentum[Amg::px]; diff --git a/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitivesCompare.h b/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitivesCompare.h index a8e8f48375fb32cc6b04cedb54790a45b3c894db..18fdc5cc9118196b49f9688a5f347f9d6b0935e5 100644 --- a/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitivesCompare.h +++ b/DetectorDescription/GeoPrimitives/GeoPrimitives/GeoPrimitivesCompare.h @@ -2,13 +2,14 @@ Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ -/* - * eigen_migration - * GeoPrimitivesCompare.h +/** + * @file GeoPrimitivesCompare.h * - * Created on: Mar 25, 2014 - * Author: rbianchi <Riccardo.Maria.Bianchi@cern.ch> + * @date Mar 25, 2014 + * @author Riccardo.Maria.Bianchi <riccardo.maria.bianchi@cern.ch> * + * @section Description + * Methods to compare Eigen-based vectors */ #ifndef GEOPRIMITIVESCOMPARE_H_ @@ -20,7 +21,7 @@ namespace Amg { -/* +/** * comparison of two Vector3D, * needed for the definition of a std::set<Amg::Vector3D> * @@ -30,7 +31,6 @@ namespace Amg { * bool Hep3Vector::operator < (const Hep3Vector & v) const; * */ - struct Vector3DComparer { bool operator()(Amg::Vector3D const &v1, Amg::Vector3D const &v2) const diff --git a/Event/xAOD/xAODCaloEvent/CMakeLists.txt b/Event/xAOD/xAODCaloEvent/CMakeLists.txt index 8704732b720e451a5ed23bbb9efbcd0f46791649..f71e12af0ae868418960133b19d7376423fdbab5 100644 --- a/Event/xAOD/xAODCaloEvent/CMakeLists.txt +++ b/Event/xAOD/xAODCaloEvent/CMakeLists.txt @@ -12,6 +12,12 @@ if( NOT XAOD_ANALYSIS AND NOT SIMULATIONBASE ) set( extra_libs CaloEvent ) endif() +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs ${extra_libs} GenVector ) + endif() +endif() + # Declare the package's dependencies: atlas_depends_on_subdirs( PUBLIC diff --git a/Event/xAOD/xAODEgamma/CMakeLists.txt b/Event/xAOD/xAODEgamma/CMakeLists.txt index 6c6a9f39a7f5718b7e26ffd60dfcb6a9b9dc7ac4..ab22ef933e721ef62ef16995e28b91d40225f32b 100644 --- a/Event/xAOD/xAODEgamma/CMakeLists.txt +++ b/Event/xAOD/xAODEgamma/CMakeLists.txt @@ -25,6 +25,13 @@ atlas_depends_on_subdirs( find_package( Eigen ) find_package( ROOT COMPONENTS Core GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODEgamma xAODEgamma/*.h xAODEgamma/versions/*.h Root/*.cxx @@ -32,7 +39,7 @@ atlas_add_library( xAODEgamma INCLUDE_DIRS ${EIGEN_INCLUDE_DIRS} LINK_LIBRARIES ${EIGEN_LIBRARIES} ${ROOT_LIBRARIES} AthContainers AthLinks CxxUtils GeoPrimitives EventPrimitives xAODBase xAODCaloEvent xAODCore - xAODPrimitives xAODTracking xAODTruth ) + xAODPrimitives xAODTracking xAODTruth ${extra_libs} ) atlas_add_dictionary( xAODEgammaDict xAODEgamma/xAODEgammaDict.h diff --git a/Event/xAOD/xAODJet/CMakeLists.txt b/Event/xAOD/xAODJet/CMakeLists.txt index 67b7df6d6b8bd4b71e43c636f7a4a33a7e13d792..2de2058ff220b187a1fe054b94477162131e0adf 100644 --- a/Event/xAOD/xAODJet/CMakeLists.txt +++ b/Event/xAOD/xAODJet/CMakeLists.txt @@ -26,6 +26,13 @@ if( NOT SIMULATIONBASE ) set( extra_libs xAODBTagging xAODPFlow xAODTrigger ) endif() +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs ${extra_libs} GenVector ) + endif() +endif() + + # Declare the package's dependencies: atlas_depends_on_subdirs( PUBLIC @@ -55,7 +62,7 @@ atlas_add_library( xAODJet atlas_add_dictionary( xAODJetDict xAODJet/xAODJetDict.h xAODJet/selection.xml - LINK_LIBRARIES xAODJet + LINK_LIBRARIES xAODJet ${extra_libs} EXTRA_FILES Root/dict/*.cxx ) # Test(s) in the package: diff --git a/Event/xAOD/xAODJet/xAODJet/JetAccessors.h b/Event/xAOD/xAODJet/xAODJet/JetAccessors.h index 7dfdd7e235f277749900674b96f0e701d5d0f380..9818ed66641f6080ce691fa9781b12a9471d52f8 100644 --- a/Event/xAOD/xAODJet/xAODJet/JetAccessors.h +++ b/Event/xAOD/xAODJet/xAODJet/JetAccessors.h @@ -9,9 +9,9 @@ ///////////////////////////////////////////// /// \file JetAccessors.h /// \brief This header defines wrapper classes around SG::AuxElement::Accessor used internally in the Jet EDM. -/// -/// By default the wrappers add no functionality to this class. -/// Their intent is to act as converter between types exposed in the Jet interface and the +/// +/// By default the wrappers add no functionality to this class. +/// Their intent is to act as converter between types exposed in the Jet interface and the /// types stored in the Aux. Store. /// For example : /// - double -> float @@ -20,14 +20,15 @@ /// - IParticle and any class inheriting it -> ElementLink<IParticleContainer> /// - Object inheriting AuxElement -> ElementLink< DataVector<Object> > /// -/// These wrappers can then be used directly in the implementation of Jet::get/setAttribute +/// These wrappers can then be used directly in the implementation of Jet::get/setAttribute /// methods which are thus much simpler. -/// +/// ///////////////////////////////////////////// #include <string> #include <type_traits> #include "AthContainers/AuxElement.h" +#include "AthLinks/ElementLink.h" #include "xAODBase/IParticle.h" #include "xAODJet/JetTypes.h" @@ -37,7 +38,7 @@ namespace xAOD { namespace JetAttributeAccessor { - struct Named { + struct Named { Named(const std::string & n) : m_name(n){} std::string name() const {return m_name;} protected: @@ -49,11 +50,11 @@ namespace xAOD { public: typedef typename SG::AuxElement::Accessor< TYPE > AccessorType; AccessorWrapper(const std::string & n) : Named(n), m_a(n) {} - + void setAttribute(SG::AuxElement& p, const TYPE& v) const { m_a(p) = v; } - + void getAttribute(const SG::AuxElement& p, TYPE& v) const { v = m_a(p); } @@ -61,7 +62,7 @@ namespace xAOD { const TYPE & getAttribute(const SG::AuxElement& p) const { return m_a(p); } - + bool isAvailable(const SG::AuxElement& p) const { return m_a.isAvailable(p);} // forward calls to internal accessor. useful for performance critical code. @@ -78,21 +79,21 @@ namespace xAOD { public: typedef SG::AuxElement::Accessor< float > AccessorType; AccessorWrapper(const std::string & n) : Named(n) , m_a(n) {} - + void setAttribute(SG::AuxElement& p, const double& v) const { m_a(p) = v; } - + void getAttribute(const SG::AuxElement& p, double& v) const { v = m_a(p); - } + } // can't return a reference, since the internal is a float. double getAttribute(const SG::AuxElement& p) const { return m_a(p); } - + bool isAvailable(const SG::AuxElement& p) const { return m_a.isAvailable(p);} protected: @@ -106,11 +107,11 @@ namespace xAOD { public: typedef SG::AuxElement::Accessor< std::vector<float> > AccessorType; AccessorWrapper(const std::string & n) : Named(n), m_a(n) {} - + void setAttribute(SG::AuxElement& p, const std::vector<double>& v) const { m_a(p).assign( v.begin() , v.end() ); } - + void getAttribute(const SG::AuxElement& p, std::vector<double>& v) const { const std::vector<float> & vecF = m_a(p); v.assign( vecF.begin() , vecF.end() ); @@ -122,7 +123,7 @@ namespace xAOD { return v; } - + bool isAvailable(const SG::AuxElement& p) const { return m_a.isAvailable(p);} protected: @@ -130,22 +131,22 @@ namespace xAOD { }; - + ///////////////////////////////////// /// A base class holding accessors for 4 floats of a 4-vector class FourMomAccessor : public Named { public: - FourMomAccessor(const std::string& name, const std::string& n0, const std::string& n1, + FourMomAccessor(const std::string& name, const std::string& n0, const std::string& n1, const std::string& n2, const std::string& n3) :Named(name) , m_p0(n0), m_p1(n1), m_p2(n2), m_p3(n3) {} - + bool isAvailable(const SG::AuxElement& e) const {return m_p0.isAvailable(e);} - + protected: SG::AuxElement::Accessor< float > m_p0; SG::AuxElement::Accessor< float > m_p1; SG::AuxElement::Accessor< float > m_p2; - SG::AuxElement::Accessor< float > m_p3; + SG::AuxElement::Accessor< float > m_p3; }; @@ -156,7 +157,7 @@ namespace xAOD { public: AccessorWrapper() : FourMomAccessor("_unnamed_","pt", "eta","phi", "m") {} AccessorWrapper(const std::string &name) : FourMomAccessor(name, name+"_pt", name+"_eta",name+"_phi", name+"_m") {} - + const float & pt(const SG::AuxElement& p) const { return m_p0(p);} const float & eta(const SG::AuxElement& p) const { return m_p1(p);} const float & phi(const SG::AuxElement& p) const { return m_p2(p);} @@ -168,13 +169,13 @@ namespace xAOD { m_p2(p) = v.Phi(); m_p3(p) = v.M(); } - + void getAttribute(const SG::AuxElement& p, JetFourMom_t& v) const { v.SetPt( m_p0(p) ); v.SetEta( m_p1(p) ); v.SetPhi( m_p2(p) ); v.SetM( m_p3(p) ); - } + } JetFourMom_t getAttribute(const SG::AuxElement &p) const { JetFourMom_t v; getAttribute(p,v); @@ -195,7 +196,7 @@ namespace xAOD { ///////////////////////////////////// - /// Specialiazed accessor for FourMom_t : internally stores the FourMom_t as 4 floats in the Aux Store + /// Specialiazed accessor for FourMom_t : internally stores the FourMom_t as 4 floats in the Aux Store template<> class AccessorWrapper<IParticle::FourMom_t> : public FourMomAccessor { public: @@ -206,46 +207,46 @@ namespace xAOD { m_p2(p) = v.Pz(); m_p3(p) = v.E(); } - + void getAttribute(const SG::AuxElement& p, IParticle::FourMom_t& v) const { v.SetPx( m_p0(p) ); v.SetPy( m_p1(p) ); v.SetPz( m_p2(p) ); v.SetE( m_p3(p) ); - } + } IParticle::FourMom_t getAttribute(const SG::AuxElement &p) const{ IParticle::FourMom_t v; getAttribute(p,v); return v; } - + }; ///////////////////////////////////// - ///////////////////////////////////// + ///////////////////////////////////// namespace { - /// This anonymous namespace to define helper classes to deal with template code + /// This anonymous namespace to define helper classes to deal with template code /// Define typedef to the types used in Auxiliary Store for the template parameter Obj - template<typename Obj, bool IsIP> + template<typename Obj, bool IsIP> struct InternalTypes { typedef DataVector<Obj> ContainerType; typedef ElementLink< ContainerType > LinkType; - typedef SG::AuxElement::Accessor< LinkType > AccessorType; + typedef SG::AuxElement::Accessor< LinkType > AccessorType; static const Obj* fromEL(const LinkType&el){if(el.isValid())return *el; return NULL;} }; - template<typename Obj> + template<typename Obj> struct InternalTypes<Obj,true> { typedef IParticleContainer ContainerType; typedef ElementLink< ContainerType > LinkType; - typedef SG::AuxElement::Accessor< LinkType > AccessorType; + typedef SG::AuxElement::Accessor< LinkType > AccessorType; static const Obj* fromEL(const LinkType&el){if(el.isValid()) return dynamic_cast<const Obj*>(*el); return NULL;} }; - template<typename Obj, bool IsIP> + template<typename Obj, bool IsIP> struct InternalVectorTypes : public InternalTypes<Obj,IsIP> { typedef typename InternalTypes<Obj,IsIP>::LinkType LinkType; typedef SG::AuxElement::Accessor< std::vector<LinkType> > AccessorType; @@ -265,10 +266,10 @@ namespace xAOD { void setAttribute(SG::AuxElement& p, const TYPE* o) const { LinkType &el = m_a(p); - el.toIndexedElement( *( dynamic_cast< const ContainerType* >( o->container() ) ), o->index() ); + el.toIndexedElement( *( dynamic_cast< const ContainerType* >( o->container() ) ), o->index() ); el.toPersistent(); } - + const TYPE * getAttribute(const SG::AuxElement& p) const { return InternalType::fromEL( m_a(p) ); @@ -277,15 +278,15 @@ namespace xAOD { void getAttribute(const SG::AuxElement& p, const TYPE *& att) const { att= InternalType::fromEL( m_a(p) ); } - + bool isAvailable(const SG::AuxElement& p) const { return m_a.isAvailable(p);} - + // // forward calls to internal accessor. useful for performance critical code. const TYPE* operator() (const SG::AuxElement& p) const { return getAttribute(p); } // TYPE& operator()(SG::AuxElement& p) { LinkType &el=m_a(p); return *el;} protected: - AccessorType m_a; + AccessorType m_a; }; /////////////////////////////////////// @@ -307,37 +308,37 @@ namespace xAOD { ObjectAccessorWrapper(const std::string & n) : Named(n), m_a(n) {} - + void vector2vectorEL(const std::vector<const TYPE*> & vec, std::vector< LinkType > & elv) const { - - for(size_t i=0; i< vec.size() ; i++) { + + for(size_t i=0; i< vec.size() ; i++) { LinkType el; - el.toIndexedElement( *( dynamic_cast< const ContainerType* >( vec[i]->container() ) ), vec[i]->index() ); - elv.push_back(el); + el.toIndexedElement( *( dynamic_cast< const ContainerType* >( vec[i]->container() ) ), vec[i]->index() ); + elv.push_back(el); elv.back().toPersistent(); // The EL will not change anymore since it is purely internal. We can call toPersistent() to be sure it will be saved as expected. } } - + void setAttribute(SG::AuxElement& p, const std::vector<const TYPE*> &vec) const { std::vector<LinkType> &elv = m_a(p); elv.clear();elv.reserve(vec.size()); this->vector2vectorEL(vec, elv); } - + void getAttribute(const SG::AuxElement& p, std::vector<const TYPE*>& v) const { - const std::vector<LinkType> &elv = m_a(p); + const std::vector<LinkType> &elv = m_a(p); v.resize(elv.size()); for(size_t i=0;i<elv.size(); i++) {v[i] = InternalType::fromEL(elv[i]) ; } } std::vector<const TYPE *> getAttribute(const SG::AuxElement& p) const { - const std::vector<LinkType> &elv = m_a(p); + const std::vector<LinkType> &elv = m_a(p); std::vector<const TYPE*> ipvec(elv.size() ); for(size_t i=0;i<elv.size(); i++) ipvec[i] = InternalType::fromEL(elv[i]) ; return ipvec; } - + bool isAvailable(const SG::AuxElement& p) const { return m_a.isAvailable(p);} - + // // forward calls to internal accessor. useful for performance critical code. // const TYPE* operator()(const AuxElement& p) { const LinkType &el = m_a(p) ;return *el;} // TYPE& operator()(AuxElement& p) { LinkType &el=m_a(p); return *el;} diff --git a/Event/xAOD/xAODMetaDataCnv/xAODMetaDataCnv/FileMetaDataTool.h b/Event/xAOD/xAODMetaDataCnv/xAODMetaDataCnv/FileMetaDataTool.h index 8b6af54ccdbc8bd60f888c845f625dd54404062c..cf49a28caa2240a72af39febd57fdb3700859df6 100644 --- a/Event/xAOD/xAODMetaDataCnv/xAODMetaDataCnv/FileMetaDataTool.h +++ b/Event/xAOD/xAODMetaDataCnv/xAODMetaDataCnv/FileMetaDataTool.h @@ -70,12 +70,13 @@ namespace xAODMaker { /// Function writing the collected metadata to the output virtual StatusCode metaDataStop(); +#ifndef XAOD_STANDALONE /// Function collecting the metadata from a new input file virtual StatusCode beginInputFile(const SG::SourceID&) {return beginInputFile();} /// Function collecting the metadata from a new input file virtual StatusCode endInputFile(const SG::SourceID&) {return endInputFile();} - +#endif // XAOD_STANDALONE /// @} private: diff --git a/Event/xAOD/xAODMuon/CMakeLists.txt b/Event/xAOD/xAODMuon/CMakeLists.txt index 20f0f86837c468e0a74666df1448c95102f4f028..d62b289e08cdfce704fa9a4ef539549e1b30511a 100644 --- a/Event/xAOD/xAODMuon/CMakeLists.txt +++ b/Event/xAOD/xAODMuon/CMakeLists.txt @@ -12,6 +12,12 @@ if( NOT XAOD_ANALYSIS ) set( extra_libs TrkSegment ) endif() +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs ${extra_libs} GenVector ) + endif() +endif() + # Declare the package's dependencies: atlas_depends_on_subdirs( PUBLIC diff --git a/Event/xAOD/xAODPFlow/CMakeLists.txt b/Event/xAOD/xAODPFlow/CMakeLists.txt index defd1041cde3391553bdcae0aa463de4c7c843a0..9c385b524b23d786f05ff8c61a5b1474a9ca4624 100644 --- a/Event/xAOD/xAODPFlow/CMakeLists.txt +++ b/Event/xAOD/xAODPFlow/CMakeLists.txt @@ -19,13 +19,20 @@ atlas_depends_on_subdirs( # External dependencies: find_package( ROOT COMPONENTS Core Physics GenVector) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODPFlow xAODPFlow/*.h xAODPFlow/versions/*.h xAODPFlow/versions/*.icc Root/*.cxx PUBLIC_HEADERS xAODPFlow INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers AthLinks xAODBase - xAODCaloEvent xAODCore xAODTracking ) + xAODCaloEvent xAODCore xAODTracking ${extra_libs} ) atlas_add_dictionary( xAODPFlowDict xAODPFlow/xAODPFlowDict.h diff --git a/Event/xAOD/xAODParticleEvent/CMakeLists.txt b/Event/xAOD/xAODParticleEvent/CMakeLists.txt index 00c30732131f8b1d7394a9e6740610444b29c2a8..01524f17a62c16da3ceaffbf1ab8c08662d08aaa 100644 --- a/Event/xAOD/xAODParticleEvent/CMakeLists.txt +++ b/Event/xAOD/xAODParticleEvent/CMakeLists.txt @@ -20,17 +20,25 @@ atlas_depends_on_subdirs( Event/xAOD/xAODTau Event/xAOD/xAODTruth ) +# External dependencies: find_package( ROOT COMPONENTS Core GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODParticleEvent xAODParticleEvent/*.h xAODParticleEvent/versions/*.h Root/*.cxx PUBLIC_HEADERS xAODParticleEvent LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers AthLinks xAODBase xAODCore xAODEgamma xAODJet - xAODMissingET xAODMuon xAODTau xAODTruth ) + xAODMissingET xAODMuon xAODTau xAODTruth ${extra_libs} ) atlas_add_dictionary( xAODParticleEventDict xAODParticleEvent/xAODParticleEventDict.h xAODParticleEvent/selection.xml - LINK_LIBRARIES xAODParticleEvent + LINK_LIBRARIES ${extra_libs} xAODParticleEvent EXTRA_FILES Root/dict/*.cxx ) diff --git a/Event/xAOD/xAODTau/CMakeLists.txt b/Event/xAOD/xAODTau/CMakeLists.txt index 9a6bc7a438c1f8e80835a49ffe9f306d8e2bdc42..c69a066b94aeadd1c9bd6877cc365e04d4ad9f0b 100644 --- a/Event/xAOD/xAODTau/CMakeLists.txt +++ b/Event/xAOD/xAODTau/CMakeLists.txt @@ -21,6 +21,13 @@ atlas_depends_on_subdirs( # External dependencies: find_package( ROOT COMPONENTS Core GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODTau xAODTau/*.h xAODTau/*.icc xAODTau/versions/*.h @@ -28,7 +35,7 @@ atlas_add_library( xAODTau PUBLIC_HEADERS xAODTau INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers AthLinks xAODBase xAODCore - xAODJet xAODPFlow xAODTracking xAODTruth ) + xAODJet xAODPFlow xAODTracking xAODTruth ${extra_libs} ) atlas_add_dictionary( xAODTauDict xAODTau/xAODTauDict.h diff --git a/Event/xAOD/xAODTracking/CMakeLists.txt b/Event/xAOD/xAODTracking/CMakeLists.txt index 42cfbf213c44dc10cbeceb8e784669d88133a95a..261daea503939163e53a5375c74948b51317b348 100644 --- a/Event/xAOD/xAODTracking/CMakeLists.txt +++ b/Event/xAOD/xAODTracking/CMakeLists.txt @@ -15,6 +15,12 @@ if( NOT XAOD_STANDALONE AND NOT XAOD_ANALYSIS ) set( extra_libs TrkNeutralParameters TrkParameters TrkTrack VxVertex ) endif() +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs ${extra_libs} GenVector ) + endif() +endif() + # Declare the package's dependencies: atlas_depends_on_subdirs( PUBLIC @@ -36,7 +42,8 @@ atlas_add_library( xAODTracking xAODTracking/*.h xAODTracking/versions/*.h Root/*.cxx PUBLIC_HEADERS xAODTracking INCLUDE_DIRS ${EIGEN_INCLUDE_DIRS} - LINK_LIBRARIES ${EIGEN_LIBRARIES} ${ROOT_LIBRARIES} AthContainers AthLinks GeoPrimitives + LINK_LIBRARIES ${EIGEN_LIBRARIES} ${ROOT_LIBRARIES} AthContainers + AthLinks GeoPrimitives EventPrimitives xAODBase xAODCore ${extra_libs} ) atlas_add_dictionary( xAODTrackingDict diff --git a/Event/xAOD/xAODTracking/Root/NeutralParticle_v1.cxx b/Event/xAOD/xAODTracking/Root/NeutralParticle_v1.cxx index e0f59b533da971df43d2baa022d5312731ed585c..1037148794a307e996c616b99e856442a408cf99 100644 --- a/Event/xAOD/xAODTracking/Root/NeutralParticle_v1.cxx +++ b/Event/xAOD/xAODTracking/Root/NeutralParticle_v1.cxx @@ -19,15 +19,15 @@ namespace xAOD { NeutralParticle_v1::NeutralParticle_v1() : IParticle(){ } - - NeutralParticle_v1::NeutralParticle_v1(const NeutralParticle_v1& tp ) + + NeutralParticle_v1::NeutralParticle_v1(const NeutralParticle_v1& tp ) : IParticle( tp ) { makePrivateStore( tp ); } - + NeutralParticle_v1& NeutralParticle_v1::operator=(const NeutralParticle_v1& tp ){ if(this == &tp) return *this; - + if(!hasStore() ) makePrivateStore(); this->IParticle::operator=( tp ); #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) @@ -38,13 +38,13 @@ namespace xAOD { NeutralParticle_v1::~NeutralParticle_v1(){ } - + double NeutralParticle_v1::pt() const { return genvecP4().Pt(); } double NeutralParticle_v1::eta() const { - return genvecP4().Eta(); + return genvecP4().Eta(); } AUXSTORE_PRIMITIVE_GETTER_WITH_CAST(NeutralParticle_v1,float,double,phi) @@ -83,9 +83,9 @@ namespace xAOD { float px = p*sinTheta*cos(phiT); float py = p*sinTheta*sin(phiT); float pz = p*cos(thetaT); - float e = pow (m(),2) + + float e = pow (m(),2) + pow( px,2) + pow( py,2) + pow( pz,2); - p4.SetPxPyPzE( px, py, pz, sqrt(e) ); + p4.SetPxPyPzE( px, py, pz, sqrt(e) ); return p4; } @@ -132,11 +132,11 @@ namespace xAOD { void NeutralParticle_v1::setDefiningParametersCovMatrix(const xAOD::ParametersCovMatrix_t& cov){ #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) - if(m_perigeeParameters.isValid()) { - m_perigeeParameters.reset(); - } + if(m_perigeeParameters.isValid()) { + m_perigeeParameters.reset(); + } #endif // not XAOD_STANDALONE and not XAOD_MANACORE - + static const Accessor< std::vector<float> > acc( "definingParametersCovMatrix" ); std::vector<float>& v = acc(*this); v.reserve(15); @@ -149,7 +149,7 @@ namespace xAOD { static const Accessor< std::vector<float> > acc( "definingParametersCovMatrix" ); std::vector<float> v = acc(*this); std::vector<float>::const_iterator it = v.begin(); - xAOD::ParametersCovMatrix_t cov; + xAOD::ParametersCovMatrix_t cov; cov.setZero(); for (size_t irow = 0; irow<5; ++irow){ for (size_t icol =0; icol<=irow; ++icol){ @@ -186,7 +186,7 @@ namespace xAOD { #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) const Trk::NeutralPerigee& NeutralParticle_v1::perigeeParameters() const { - + // Require the cache to be valid and check if the cached pointer has been set if(m_perigeeParameters.isValid()){ return *(m_perigeeParameters.ptr()); @@ -206,13 +206,15 @@ namespace xAOD { } } Trk::NeutralPerigee tmpPerigeeParameters(acc1(*this),acc2(*this),acc3(*this),acc4(*this),acc5(*this), - Trk::PerigeeSurface(Amg::Vector3D(vx(),vy(),vz())),cov); + Trk::PerigeeSurface(Amg::Vector3D(vx(),vy(),vz())),cov); m_perigeeParameters.set(tmpPerigeeParameters); return *(m_perigeeParameters.ptr()); } #endif // not XAOD_STANDALONE and not XAOD_MANACORE void NeutralParticle_v1::resetCache(){ - m_perigeeParameters.reset(); + #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) + m_perigeeParameters.reset(); + #endif // not XAOD_STANDALONE and not XAOD_MANACORE } } // namespace xAOD diff --git a/Event/xAOD/xAODTracking/Root/TrackParticle_v1.cxx b/Event/xAOD/xAODTracking/Root/TrackParticle_v1.cxx index e898ee7b39af3f6440e1b059c1a07914602007c9..12f16f4e677fea11ba5c1401ffc8842d8e984768 100644 --- a/Event/xAOD/xAODTracking/Root/TrackParticle_v1.cxx +++ b/Event/xAOD/xAODTracking/Root/TrackParticle_v1.cxx @@ -25,17 +25,17 @@ namespace xAOD { : IParticle() { // perigeeParameters cache initialized to be empty (default constructor) } - - TrackParticle_v1::TrackParticle_v1(const TrackParticle_v1& tp ) + + TrackParticle_v1::TrackParticle_v1(const TrackParticle_v1& tp ) : IParticle( tp ) { makePrivateStore( tp ); // perigeeParameters cache initialized to be empty (default constructor) // assume that this copy will create new cache as needed } - + TrackParticle_v1& TrackParticle_v1::operator=(const TrackParticle_v1& tp ){ if(this == &tp) return *this; - + if( ( ! hasStore() ) && ( ! container() ) ) { makePrivateStore(); } @@ -46,7 +46,7 @@ namespace xAOD { #endif // not XAOD_STANDALONE and not XAOD_MANACORE return *this; } - + TrackParticle_v1::~TrackParticle_v1(){} double TrackParticle_v1::pt() const { @@ -54,7 +54,7 @@ namespace xAOD { } double TrackParticle_v1::eta() const { - return genvecP4().Eta(); + return genvecP4().Eta(); } AUXSTORE_PRIMITIVE_GETTER_WITH_CAST(TrackParticle_v1,float,double,phi) @@ -64,7 +64,7 @@ namespace xAOD { } double TrackParticle_v1::e() const { - return genvecP4().E(); + return genvecP4().E(); } double TrackParticle_v1::rapidity() const { return genvecP4().Rapidity(); @@ -94,9 +94,9 @@ namespace xAOD { float px = p*sinTheta*cos(phiT); float py = p*sinTheta*sin(phiT); float pz = p*cos(thetaT); - float e = pow (m(),2) + + float e = pow (m(),2) + pow( px,2) + pow( py,2) + pow( pz,2); - p4.SetPxPyPzE( px, py, pz, sqrt(e) ); + p4.SetPxPyPzE( px, py, pz, sqrt(e) ); return p4; } @@ -165,7 +165,7 @@ namespace xAOD { } const xAOD::ParametersCovMatrix_t TrackParticle_v1::definingParametersCovMatrix() const { - xAOD::ParametersCovMatrix_t cov; + xAOD::ParametersCovMatrix_t cov; const std::vector<float>& covVec = definingParametersCovMatrixVec(); if( !covVec.empty() ) Amg::expand( covVec.begin(), covVec.end(),cov ); else cov.setIdentity(); @@ -215,20 +215,20 @@ namespace xAOD { ParametersCovMatrix_t* cov = new ParametersCovMatrix_t(definingParametersCovMatrix()); static const Accessor< float > acc7( "beamlineTiltX" ); static const Accessor< float > acc8( "beamlineTiltY" ); - + if(!acc7.isAvailable( *this ) || !acc8.isAvailable( *this )){ Trk::Perigee tmpPerigeeParameters(acc1(*this),acc2(*this),acc3(*this),acc4(*this),acc5(*this),Trk::PerigeeSurface(Amg::Vector3D(vx(),vy(),vz())),cov); m_perigeeParameters.set(tmpPerigeeParameters); return *(m_perigeeParameters.ptr()); } - - Amg::Transform3D * amgTransf = new Amg::Transform3D(); + + Amg::Transform3D * amgTransf = new Amg::Transform3D(); Amg::Translation3D amgtranslation(vx(),vy(),vz()); *amgTransf = amgtranslation * Amg::RotationMatrix3D::Identity(); *amgTransf *= Amg::AngleAxis3D(acc8(*this), Amg::Vector3D(0.,1.,0.)); *amgTransf *= Amg::AngleAxis3D(acc7(*this), Amg::Vector3D(1.,0.,0.)); Trk::Perigee tmpPerigeeParameters(acc1(*this),acc2(*this),acc3(*this),acc4(*this),acc5(*this),Trk::PerigeeSurface(amgTransf),cov); - + m_perigeeParameters.set(tmpPerigeeParameters); return *(m_perigeeParameters.ptr()); } @@ -239,9 +239,9 @@ namespace xAOD { void TrackParticle_v1::setFitQuality(float chiSquared, float numberDoF){ static const Accessor< float > acc1( "chiSquared" ); - acc1( *this ) = chiSquared; + acc1( *this ) = chiSquared; static const Accessor< float > acc2( "numberDoF" ); - acc2( *this ) = numberDoF; + acc2( *this ) = numberDoF; } AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(TrackParticle_v1, float, radiusOfFirstHit, setRadiusOfFirstHit) @@ -249,7 +249,7 @@ namespace xAOD { AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(TrackParticle_v1, float, beamlineTiltX, setBeamlineTiltX) AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(TrackParticle_v1, float, beamlineTiltY, setBeamlineTiltY) - + AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(TrackParticle_v1, uint32_t, hitPattern, setHitPattern) AUXSTORE_PRIMITIVE_SETTER_AND_GETTER(TrackParticle_v1, uint8_t,numberOfUsedHitsdEdx ,setNumberOfUsedHitsdEdx ) @@ -330,7 +330,7 @@ namespace xAOD { } float TrackParticle_v1::parameterPZ(unsigned int index) const { - static const Accessor< std::vector<float> > acc( "parameterPZ" ); + static const Accessor< std::vector<float> > acc( "parameterPZ" ); return acc(*this).at(index); } @@ -360,7 +360,7 @@ namespace xAOD { return static_cast<xAOD::ParameterPosition>(acc(*this).at(index)); } - bool TrackParticle_v1::indexOfParameterAtPosition(unsigned int& index, ParameterPosition position) const + bool TrackParticle_v1::indexOfParameterAtPosition(unsigned int& index, ParameterPosition position) const { size_t maxParameters = numberOfParameters(); bool foundParameters=false; @@ -380,12 +380,12 @@ namespace xAOD { } #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) - const Trk::CurvilinearParameters TrackParticle_v1::curvilinearParameters(unsigned int index) const { + const Trk::CurvilinearParameters TrackParticle_v1::curvilinearParameters(unsigned int index) const { static const Accessor< std::vector<float> > acc( "trackParameterCovarianceMatrices" ); unsigned int offset = index*15; // copy the correct values into the temp matrix - ParametersCovMatrix_t* cov = new ParametersCovMatrix_t(); + ParametersCovMatrix_t* cov = new ParametersCovMatrix_t(); auto it = acc(*this).begin()+offset; Amg::expand(it,it+15,*cov); // retrieve the parameters to build the curvilinear frame @@ -439,7 +439,7 @@ namespace xAOD { value = ( *acc )( *this ); return true; } - + bool TrackParticle_v1::summaryValue(float& value, const SummaryType &information) const { const xAOD::TrackParticle_v1::Accessor< float >* acc = trackSummaryAccessorV1<float>( information ); if( ( ! acc ) || ( ! acc->isAvailable( *this ) ) ) return false; @@ -447,7 +447,7 @@ namespace xAOD { value = ( *acc )( *this ); return true; } - + void TrackParticle_v1::setSummaryValue(uint8_t& value, const SummaryType &information){ const xAOD::TrackParticle_v1::Accessor< uint8_t >* acc = trackSummaryAccessorV1<uint8_t>( information ); // Set the value: @@ -459,7 +459,7 @@ namespace xAOD { // Set the value: ( *acc )( *this ) = value; } - + #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) /// The function will return an invalid ElementLink in case nothing was set @@ -507,12 +507,15 @@ namespace xAOD { } return *( acc( *this ) ); - } + } #endif // not XAOD_STANDALONE and not XAOD_MANACORE - + void TrackParticle_v1::resetCache(){ - m_perigeeParameters.reset(); + #if ( ! defined(XAOD_STANDALONE) ) && ( ! defined(XAOD_MANACORE) ) + m_perigeeParameters.reset(); + #endif // not XAOD_STANDALONE and not XAOD_MANACORE + } - + } // namespace xAOD diff --git a/Event/xAOD/xAODTrigEgamma/CMakeLists.txt b/Event/xAOD/xAODTrigEgamma/CMakeLists.txt index 8b388c81f2435c667632464ce59f6fd32cb7f047..65e4c29ef34323c25230c63d0c35c4470a9cea18 100644 --- a/Event/xAOD/xAODTrigEgamma/CMakeLists.txt +++ b/Event/xAOD/xAODTrigEgamma/CMakeLists.txt @@ -19,18 +19,27 @@ atlas_depends_on_subdirs( PUBLIC # External dependencies: find_package( ROOT COMPONENTS Core Tree MathCore Hist RIO pthread GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODTrigEgamma Root/*.cxx PUBLIC_HEADERS xAODTrigEgamma PRIVATE_INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} LINK_LIBRARIES AthContainers AthLinks xAODBase xAODCaloEvent xAODCore xAODEgamma xAODTracking xAODTrigCalo - PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} ) + PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} ${extra_libs} ) atlas_add_dictionary( xAODTrigEgammaDict xAODTrigEgamma/xAODTrigEgammaDict.h xAODTrigEgamma/selection.xml INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} - LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers AthLinks xAODBase xAODCaloEvent xAODCore xAODEgamma xAODTracking xAODTrigCalo xAODTrigEgamma + LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers AthLinks + xAODBase xAODCaloEvent xAODCore xAODEgamma xAODTracking + xAODTrigCalo xAODTrigEgamma ${extra_libs} EXTRA_FILES Root/dict/*.cxx ) diff --git a/Event/xAOD/xAODTrigL1Calo/CMakeLists.txt b/Event/xAOD/xAODTrigL1Calo/CMakeLists.txt index 8eb59195ada960684b20b297e4f3a6685473c1bc..16b9bf3ead60854536d087b2750e9103398997e2 100644 --- a/Event/xAOD/xAODTrigL1Calo/CMakeLists.txt +++ b/Event/xAOD/xAODTrigL1Calo/CMakeLists.txt @@ -18,18 +18,25 @@ atlas_depends_on_subdirs( PUBLIC # External dependencies: find_package( ROOT COMPONENTS Physics Core Tree MathCore Hist RIO pthread GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODTrigL1Calo Root/*.cxx PUBLIC_HEADERS xAODTrigL1Calo PRIVATE_INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} LINK_LIBRARIES AthContainers CxxUtils xAODBase xAODCore - PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} AthLinks ) + PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} AthLinks ${extra_libs} ) atlas_add_dictionary( xAODTrigL1CaloDict xAODTrigL1Calo/xAODTrigL1CaloDict.h xAODTrigL1Calo/selection.xml INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} - LINK_LIBRARIES ${ROOT_LIBRARIES} AthContainers CxxUtils xAODBase xAODCore AthLinks xAODTrigL1Calo + LINK_LIBRARIES ${ROOT_LIBRARIES} ${extra_libs} AthContainers CxxUtils xAODBase xAODCore AthLinks xAODTrigL1Calo EXTRA_FILES Root/dict/*.cxx ) diff --git a/Event/xAOD/xAODTrigMuon/CMakeLists.txt b/Event/xAOD/xAODTrigMuon/CMakeLists.txt index 7ee94223edea256f6b00e1934d0545402243c154..1e60def6b2e5398082faccf92ebf20bb2c4ce6af 100644 --- a/Event/xAOD/xAODTrigMuon/CMakeLists.txt +++ b/Event/xAOD/xAODTrigMuon/CMakeLists.txt @@ -17,12 +17,19 @@ atlas_depends_on_subdirs( PUBLIC # External dependencies: find_package( ROOT COMPONENTS Physics Core Tree MathCore Hist RIO pthread GenVector ) +# Extra dependencies, based on what environment we are in: +if (BUILDVP1LIGHT) + if( BUILDVP1LIGHT_DIST STREQUAL "ubuntu") + set( extra_libs GenVector ) + endif() +endif() + # Component(s) in the package: atlas_add_library( xAODTrigMuon Root/*.cxx PUBLIC_HEADERS xAODTrigMuon PRIVATE_INCLUDE_DIRS ${ROOT_INCLUDE_DIRS} - LINK_LIBRARIES AthContainers xAODBase xAODCore xAODTracking + LINK_LIBRARIES AthContainers xAODBase xAODCore xAODTracking ${extra_libs} PRIVATE_LINK_LIBRARIES ${ROOT_LIBRARIES} AthLinks ) atlas_add_dictionary( xAODTrigMuonDict diff --git a/Event/xAOD/xAODTrigger/CMakeLists.txt b/Event/xAOD/xAODTrigger/CMakeLists.txt index 31698f02172dd37d4c1c301d632a40f80f1ff015..0ae963738ba474e1f2c5b7f654500d16baa58cda 100644 --- a/Event/xAOD/xAODTrigger/CMakeLists.txt +++ b/Event/xAOD/xAODTrigger/CMakeLists.txt @@ -40,6 +40,11 @@ atlas_add_test( ut_xaodtrigger_bytestreamauxcontainer_v1_test SOURCES test/ut_xaodtrigger_bytestreamauxcontainer_v1_test.cxx LINK_LIBRARIES AthContainers xAODTrigger ) +# The tests do not compile in 'master' so far, because some operators are mnissing from AthLinksSA/ElementLinkVector. +# FIXME: add the missing operators +if ( NOT BUILDVP1LIGHT ) atlas_add_test( ut_xaodtrigger_trigcomposite_test SOURCES test/ut_xaodtrigger_trigcomposite_test.cxx LINK_LIBRARIES AthContainers xAODTrigger ) +endif() + diff --git a/Event/xAOD/xAODTriggerCnv/xAODTriggerCnv/TriggerMenuMetaDataTool.h b/Event/xAOD/xAODTriggerCnv/xAODTriggerCnv/TriggerMenuMetaDataTool.h index cc8488c03816fe5fdf3769ae2eadf8d341f4ff36..5f2d243e449bbc10dfe2d93f3cf52b98d511581d 100644 --- a/Event/xAOD/xAODTriggerCnv/xAODTriggerCnv/TriggerMenuMetaDataTool.h +++ b/Event/xAOD/xAODTriggerCnv/xAODTriggerCnv/TriggerMenuMetaDataTool.h @@ -66,6 +66,7 @@ namespace xAODMaker { /// Function writing out the collected metadata virtual StatusCode metaDataStop(); +#ifndef XAOD_STANDALONE /// Function collecting the metadata from a new input file virtual StatusCode beginInputFile(const SG::SourceID&) {return beginInputFile();} @@ -74,6 +75,7 @@ namespace xAODMaker { /// Function writing the collected metadata to the output virtual StatusCode metaDataStop(const SG::SourceID&) {return metaDataStop();} +#endif // XAOD_STANDALONE /// @} diff --git a/MuonSpectrometer/MuonGeoModel/CMakeLists.txt b/MuonSpectrometer/MuonGeoModel/CMakeLists.txt index f3110b921c829cbad12cbd2daa427368b22b2514..6661f8475c3b4b5636afde82fcb4f122fbfb0425 100644 --- a/MuonSpectrometer/MuonGeoModel/CMakeLists.txt +++ b/MuonSpectrometer/MuonGeoModel/CMakeLists.txt @@ -11,7 +11,7 @@ atlas_depends_on_subdirs( PUBLIC Control/StoreGate DetectorDescription/GeoModel/GeoModelInterfaces DetectorDescription/GeoModel/GeoModelUtilities - DetectorDescription/GeoPrimitives + DetectorDescription/GeoPrimitives GaudiKernel MuonSpectrometer/MuonConditions/MuonCondGeneral/MuonCondInterface MuonSpectrometer/MuonDetDescr/MuonReadoutGeometry diff --git a/Projects/VP1Light/CMakeLists.txt b/Projects/VP1Light/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..77b4a153674493abed660104d4698c01ce5460b8 --- /dev/null +++ b/Projects/VP1Light/CMakeLists.txt @@ -0,0 +1,104 @@ +# +# This is the main CMakeLists.txt file for building the VP1Light +# software release. +# + +# The minimum required CMake version: +cmake_minimum_required( VERSION 3.2 FATAL_ERROR ) + +# Read in the project's version from a file called version.txt. But let it be +# overridden from the command line if necessary. +file( READ ${CMAKE_SOURCE_DIR}/version.txt _version ) +string( STRIP ${_version} _version ) +set( VP1LIGHT_PROJECT_VERSION ${_version} + CACHE STRING "Version of the VP1Light project to build" ) +unset( _version ) + +# This project is built on top of VP1LightExternals: +find_package( VP1LightExternals REQUIRED ) + +# Find Python. This is needed because VP1LightExternals sets up +# a wrong value for PYTHONHOME. And nothing in VP1Light builds +# against Python to correct it. +find_package( PythonInterp ) + +find_package( ROOT COMPONENTS Physics Core Tree MathCore Hist RIO pthread + GenVector REQUIRED ) + + +# Build options to customize the compilation of ATLAS packages +option( BUILDVP1LIGHT "Build ATLAS packages for VP1 Light" ON ) + +# Add the project's modules directory to CMAKE_MODULE_PATH: +list( INSERT CMAKE_MODULE_PATH 0 ${CMAKE_SOURCE_DIR}/modules ) +list( REMOVE_DUPLICATES CMAKE_MODULE_PATH ) + +# Install the files from modules/: +install( DIRECTORY ${CMAKE_SOURCE_DIR}/modules/ + DESTINATION cmake/modules + USE_SOURCE_PERMISSIONS + PATTERN ".svn" EXCLUDE + PATTERN "*~" EXCLUDE ) + +# Include the VP1Light specific function(s), to include RootCore: +include( VP1LightFunctions ) # TODO: Do we need RootCore for VP1Light/xAOD??? + +# Set up the build/runtime environment: +set( VP1LightReleaseEnvironment_DIR ${CMAKE_SOURCE_DIR} ) +find_package( VP1LightReleaseEnvironment REQUIRED ) + +# Add the directory to the global include path, where the project +# will create the RootCore/Packages.h header: +include_directories( ${CMAKE_BINARY_DIR}/RootCore/include ) + +# Set up CTest: +atlas_ctest_setup() + +# Custom definitions needed for this package +# set( CMAKE_CXX_STANDARD 14 ) # this must be declared BEFORE the 'atlas_project' command + + +message("Using VP1LightExternals version: $ENV{VP1LightExternals_VERSION}" ) + +# Declare project name and version +atlas_project( VP1Light ${VP1LIGHT_PROJECT_VERSION} + #USE VP1LightExternals $ENV{VP1LightExternals_VERSION} # This fails on macOS + PROJECT_ROOT ${CMAKE_SOURCE_DIR}/../../ ) + +# Generate the RootCore/Packages.h header: +vp1light_generate_release_header() + +# Set up the load_packages.C script: +configure_file( ${CMAKE_SOURCE_DIR}/scripts/load_packages.C.in + ${CMAKE_SCRIPT_OUTPUT_DIRECTORY}/load_packages.C @ONLY ) +install( FILES ${CMAKE_SCRIPT_OUTPUT_DIRECTORY}/load_packages.C + DESTINATION ${CMAKE_INSTALL_SCRIPTDIR} ) + +# Configure and install the post-configuration file: +configure_file( ${CMAKE_SOURCE_DIR}/PostConfig.cmake.in + ${CMAKE_BINARY_DIR}/PostConfig.cmake @ONLY ) +install( FILES ${CMAKE_BINARY_DIR}/PostConfig.cmake + DESTINATION ${CMAKE_INSTALL_CMAKEDIR} ) + +# Generate replacement rules for the installed paths: +set( _replacements ) +if( NOT "$ENV{NICOS_PROJECT_HOME}" STREQUAL "" ) + get_filename_component( _buildDir $ENV{NICOS_PROJECT_HOME} PATH ) + list( APPEND _replacements ${_buildDir} "\${VP1Light_DIR}/../../../.." ) +endif() +if( NOT "$ENV{NICOS_PROJECT_RELNAME}" STREQUAL "" ) + list( APPEND _replacements $ENV{NICOS_PROJECT_RELNAME} + "\${VP1Light_VERSION}" ) +endif() + +# Generate the environment configuration file(s): +lcg_generate_env( + SH_FILE ${CMAKE_BINARY_DIR}/${ATLAS_PLATFORM}/env_setup.sh ) +lcg_generate_env( + SH_FILE ${CMAKE_BINARY_DIR}/env_setup_install.sh + REPLACE ${_replacements} ) +install( FILES ${CMAKE_BINARY_DIR}/env_setup_install.sh + DESTINATION . RENAME env_setup.sh ) + +# Set up the release packaging: +atlas_cpack_setup() diff --git a/Projects/VP1Light/PostConfig.cmake.in b/Projects/VP1Light/PostConfig.cmake.in new file mode 100644 index 0000000000000000000000000000000000000000..4ad40fe663ea3283fa4c3df58b4115755dcb93b4 --- /dev/null +++ b/Projects/VP1Light/PostConfig.cmake.in @@ -0,0 +1,23 @@ +# +# File setting up some basic properties for the installed analysis releases. +# + +# Make all compilation see the RootCore/Packages.h file: +include_directories( $ENV{VP1Light_DIR}/RootCore/include ) + +# This is a standalone project, so set the appropriate compile flags: +add_definitions( -DROOTCORE ) +add_definitions( -DXAOD_STANDALONE ) +add_definitions( -DXAOD_ANALYSIS ) +add_definitions( -DBUILDVP1LIGHT ) +add_definitions( -DROOTCORE_RELEASE_SERIES=$ENV{ROOTCORE_RELEASE_SERIES} ) + +# And some variables for CMake as well: +set( ROOTCORE TRUE CACHE BOOL + "Flag specifying that this is a \"RootCore\" release" ) +set( XAOD_STANDALONE TRUE CACHE BOOL + "Flag specifying that this is a standalone build" ) +set( BUILDVP1LIGHT TRUE CACHE BOOL + "Flag specifying that this is a VP1Light release (based on an AnalysisBase release)" ) +set( XAOD_ANALYSIS TRUE CACHE BOOL + "Flag specifying that this is an analysis release" ) diff --git a/Projects/VP1Light/README.md b/Projects/VP1Light/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7e281d81b4ebb9c80c9678dd2acd80d2ef028d35 --- /dev/null +++ b/Projects/VP1Light/README.md @@ -0,0 +1,447 @@ +# VP1Light Release + +**Table of Contents**: + + * [Intro](#intro) + * [License and Distribution](#license-and-distribution) + * [Install and use VP1Light](#install-vp1light) + * [Run VP1Light on macOS](#macos) + * [Run VP1Light on Ubuntu](#ubuntu) + * [Build VP1 (for developers)](#build-vp1light-for-developers) + * [General Pre-requisites](#general-pre-requisites) + * [Mac OS instructions](#install-vp1light-on-mac-os) + * [Ubuntu instructions](#install-vp1light-on-ubuntu) + * [Sample data](#sample-data) + * [Antialiasing](#notes-on-antialiasing) + +---- + +## Intro + +This project builds `VP1Light`, a standalone 3D event display which lets you visualize the ATLAS Geometry and the content of `xAOD` data files. + +If you have problems installing VP1Light, or you get errors while building and running it, +or if you see discrepancies in the geometry, + +* please send us your feedback at: <mailto:hn-atlas-vp1-help@cern.ch> +* or open a ticket on <https://its.cern.ch/jira/projects/ATLASVPONE/summary> + + +## License and Distribution + +**A NOTE:** +*Please, don't share the geometry data file outside ATLAS, even if it can be used without any other ATLAS software. They are ATLAS data.* + +---- + +## Install VP1Light + +### macOS + +_[to be updated...]_ + + +### Ubuntu + +Tested on Ubuntu 18.0.4 (Bionic Beaver) and 16.0.4 + +``` +sudo add-apt-repository ppa:kaktusjoe/rootdist +sudo apt-get update +sudo apt install vp1light +``` + +**Issues:** + +1. **graphics display / OpenGL** + + If you get errors like those: + + ``` + libGL error: No matching fbConfigs or visuals found + libGL error: failed to load driver: swrast + Error: couldn't get an RGB, Double-buffered visual + ``` + + It means your OpenGL (a graphics library needed for 3D) installation is faulty or not compatible with your hardware. Installing a modern graphics driver can help to fix that. For example, we tested this NVidia driver on a 'vanilla' Ubuntu 18.0.4 (OpenStack virtual machine) and it worked: + + ``` + sudo apt install nvidia-driver-390 + ``` + + After the installation, you can test your new OpenGL environment with: + + ``` + glxgears + ``` + + If a windows with 3D gears appears, that usually means that your OpenGL environment is now healthy. You can now run VP1Light. + + +2. **xAOD data files / ROOT** + + When you open an xAOD file in VP1Light, if VP1Light crashes with errors about xAOD classes (e.g., `xAODTracking`) or ROOT classes (e.g., `TEvent`), that usually means that you have two conflicting ROOT installations on your system, or that the ROOT version you use has not been compiled with C++14, which is needed by the ATLAS software. + + The Ubuntu VP1Light `apt` packages contain the needed version of ROOT, compiled with C++14. + + To fix the errors, you should remove the conflicting/existing ROOT and reinstall the VP1Light Ubuntu packages. + + You can start by removing the VP1Light packages: + + ``` + sudo apt remove vp1light + + ``` + + Then, look for the remaining ROOT installation and remove it from your system. After that, you can reinstall VP1Light: + + ``` + sudo apt install vp1light + + ``` + + Note: You can remove the version of ROOT shipped with VP1Light by simply run `sudo apt remove vp1light`. + Then, you can install any ROOT version you want. + Moreover, if you need a given version of ROOT for your work or your physics analysis, + you can install it under a separate folder; then, you can set it up by running the thisroot.sh script you can find inside the `bin` directory of the ROOT folder. + + +---- + +## Build VP1Light (for developers) + +If a build is not available for your machine, or you want to work on the code base of VP1Light, you can build it from source. Here below the detailed step-by-step instructions. + + +### General Pre-requisites + +#### Install the Qt5 framework + +VP1Light uses the Qt5 graphics framework. It is recommended to install it on your system before compiling/installing VP1Light. + +If a Qt5 installation is not found by the VP1Light build script, the whole Qt5 framework is downloaded and compiled from source, which takes a long time. That's why it is highly recommended to install the right Qt5 package for your platform before building VP1Light. + +You can find installation instructions here: + +<https://www.qt.io/download> + +**NOTES:** + + * Please, pay attention to download the "Open Source" version of Qt5. + * Please, notice that you can skip the creation of a Qt account when installing the open source version. When you get the window shown below, just continue clicking on the `Skip` button. **Note:** With the latest versions of Qt5 (_e.g._, 5.12.0), the "Skip" button is hidden if an email address is set in the form, and the installer automatically sets the address if it can find one related to the user. However, if you delete the email address from the form, the "Skip" button appears. Now, you can skip the creation of the Qt account and you can continue installing the Open Source version of Qt5. + + +### Build VP1Light on macOS + +#### Build VP1LightExternals on macOS + +First, build and install the VP1LightExternals: + +``` +git clone https://gitlab.cern.ch/rbianchi/atlasexternals.git +cd atlasexternals +git checkout master-eigen-update +cd ../ + +mkdir build_ext +cd build_ext + +# run CMake +cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCTEST_USE_LAUNCHERS=TRUE ../athena/Projects/VP1LightExternals/ + +# build +make -j 4 + +# install +make install DESTDIR=../install/VP1LightExternals +``` + +##### Notes + +If you get errors like this one: + +``` +fatal error: 'stdlib.h' file not found +``` + +Then, probably you have to install or update the Xcode command line tools and the C++ headers (it is often necessary also after a major update of Xcode). + +At first, try this: + +``` +xcode-select --install +``` + +If that fixes the problem, that's enough. +If not, try this: + +``` +cd /Library/Developer/CommandLineTools/Packages/ +open macOS_SDK_headers_for_macOS_10.14.pkg +``` + +That will install the missing headers, which are somehow "hidden" on the latest macOS versions. + + +#### Build VP1Light on macOS + +After having built and installed `VP1LightExternals`, you can build and install `VP1Light` itself. + +_[please, replace `<your-platform>` with your actual platform]_ + +``` +git clone https://gitlab.cern.ch/rbianchi/athena.git +cd athena +git checkout master-vp1light-bundle +cd ../ + +mkdir build_vp1light +cd build_vp1light + +# source the Externals setup script +source ../install/VP1LightExternals/InstallArea/<your-platform>/setup.sh + +# run CMake +cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCTEST_USE_LAUNCHERS=TRUE ../athena/Projects/VP1Light/ + +# build +make -j 4 + +# install +make install DESTDIR=../install/VP1Light +``` + +Then, set the environment and launch: + +``` +source ../install/VP1Light/InstallArea/x86_64-mac1014-clang100-opt/setup.sh +vp1light +``` + +If you get errors, see the Notes below. + +##### Notes + +###### Qt RPATH + +While launching `vp1light`, if you get an error like this: + +``` +$ vp1light +dyld: Library not loaded: @rpath/QtCore.framework/Versions/5/QtCore + Referenced from: /Users/rbianchi/code_work_local/atlas/vp1light-bundle-MR-Apr2019/from_code/build_vp1light/x86_64-mac1014-clang100-opt/bin/vp1light + Reason: image not found +Abort trap: 6 +``` + +Then, it means Qt is not installed/configured properly. We will work on a solution to be embedded in the CMake setup; however, for the moment, as a temporary fix, you can manually add the Qt lib path as `rpath` to the `vp1light` executable, like this (please, adjust the Qt path and the vp1light executable paths to your setup): + +``` +install_name_tool -add_rpath /Users/rbianchi/Qt5.12.0/5.12.0/clang_64/lib ../install/VP1Light/InstallArea/x86_64-mac1014-clang100-opt/bin/vp1light +``` + +After that, you should be able to launch `vp1light` without any other problem. + +###### ROOT + +If you have a local installation of ROOT 6.14 (for example installed with `brew`, you might get errors due to the different versions of the ROOT header files found on the system. For example you could get an error like this: `error: use of undeclared identifier 'R__likely'`. Disinstalling the brew ROOT package should solve the problem (you can see the list of the packages installed on your machine by using `brew list`; then, you can uninstall the unwanted packages with by typing `brew uninstall <package-name>`). + +###### Blank 3D window on macOS Mojave + +If you use macOS Mojave, and you get a blank 3D window (i.e., you switch on a piece of geometry, and you don't get it in the 3D window of VP1Light), then you probably should update your macOS installation. Please, be sure you are running 10.14.4 with Xcode 10. + + +### Install VP1Light on Ubuntu + +Tested on Ubuntu 18.0.4 and 16.0.4 + +#### Pre-requisites + +**Note**: You can install the dependencies listed below one by one, by hand, or you can run [the provided script](SETUP_VP1Light_DEPENDENCIES_UBUNTU.sh); for that, just type: + +``` +source SETUP_VP1Light_DEPENDENCIES_UBUNTU.sh +``` + +If you used the script to install all the dependencies in one go, you can now jump [to the next section](#install-the-atlasexternals). + +##### Development Tools + + * Git: + + `sudo apt install git` + + * CMake: + + `sudo apt install cmake` + + *Note:* you need a fairly recent version of CMake (at least 3.9). On Ubuntu 16.0.4 the command below installs CMake 3.5 by default. In that case, please refer to the CMake website (<https://cmake.org/download/>), for a more recent version. Once downloaded, you can build and install it with: + + + tar -xvf <downloaded_package> + cd <cmake-xxx-folder> + ./configure + make + sudo make install + + When built and installed, open a new shell (otherwise you get errors from the old version of CMake), and try it the new version with: + + which cmake + cmake --version + + + + +##### Libraries + +###### `AthenaExternals` dependencies. + +**Please notice**: install these libraries **before** building the Externals, in order to avoid later problems (for example, if Qt does not see SSL libraries installed on the system, it will be built without SSL support, which then brakes the compilation of VP1Gui). + + * PythonLibs, needed by ROOT: + + `sudo apt-get install python-dev` + + * GLUT, needed by Coin3D: + + `sudo apt-get install freeglut3-dev` + + * ZLIB and OPENSSL, needed by XRootD: + + `sudo apt-get install zlib1g-dev` + `sudo apt-get install libssl-dev` + + * XPM and XFT, needed by ROOT: + + sudo apt-get install libgd-dev + sudo apt-get install libxft-dev + +###### `Athena` dependencies: + + * TBB, needed by xAODRootAccess: + + `sudo apt-get install libtbb-dev` + + * RPM, which installs `rpmbuild`, needed by CPack: + + `sudo apt-get install rpm` + + * UUID, needed by CxxUtils: + + `sudo apt-get install uuid-dev` + +###### Graphics Drivers + +Please, install the proper driver for your graphic card. See the section ["Notes on Antialiasing"](#notes-on-antialiasing). + + +#### Install the AtlasExternals + +##### 1. Get the code of the external packages + +Clone the repository and get the proper branch: + +``` +git clone https://gitlab.cern.ch/rbianchi/atlasexternals.git +cd atlasexternals/ +git checkout master-vp1light-new-externals-project-v2 +``` + +##### 2. Build the externals + +``` +cd ../ +mkdir buildax +cd buildax/ +cmake -DCMAKE_BUILD_TYPE=RelWithDebInfo -DCTEST_USE_LAUNCHERS=TRUE ../atlasexternals/Projects/VP1LightExternals/ +make +``` + +##### 3. Install the externals + +Now, you can setup the system to use the newly built VP1LightExternals. Please, replace `<platform>` with the correct string for your machine (_e.g._, `x86_64-ubuntu1604-gcc54-opt`) + +``` +make install DESTDIR=../build/install/VP1LightExternals/0.0.1 +source ../build/install/VP1LightExternals/0.0.1/InstallArea/<platform>/setup.sh +cd .. +``` + +#### Install VP1Light + +##### Get the code + +Clone the repository and get the proper branch: + +``` +git clone https://gitlab.cern.ch/rbianchi/athena +cd athena +git checkout master-vp1light-bundle +cd .. +``` + + +##### Build + +``` +cd athena/Projects/VP1Light +source build_env.sh +./build.sh +cd ../../../ +``` + +##### Setup + +Now, you can setup the system to use the newly built VP1Light. Please, replace `<platform>` with the correct string for your machine (_e.g._, `x86_64-ubuntu1604-gcc54-opt`) + +``` +cd build/install/VP1Light/0.0.1/InstallArea/<platform>/ +source setup.sh +``` + +#### Run + + +`./bin/vp1light` + +**Note:** If you get an error about Qt5 libraries, it is likely that the system tries to access the system libraries, even if you used a more recent version of Qt for the VP1Light compilation. In that case, before running `vplight`, try to set the `LD_LIBRARY_PATH` explicitely, by using: + +``` +export LD_LIBRARY_PATH=<path-to>/Qt/5.<version>/<platform>/lib:$LD_LIBRARY_PATH +``` + +Once VP1Light is opened, click on "Geometry studies", then load a `.db` file containing the geometry (see next section). + + +### Install VP1Light on CentOS7 and SLC6 + +``` +setupATLAS +asetup none,gcc8,cmakesetup + +``` + + + + +---- + +## Sample data + +To play with VP1Light, you can download a (draft) sample data containing the ATLAS geometry from here: + + * https://atlas-vp1.web.cern.ch/atlas-vp1/doc_new/sample_datafiles/geometry-ATLAS-R2-2016-01-00-01.db + +You can download the file from your web browser or, in the terminal, you can use `wget` by typing: + + wget https://atlas-vp1.web.cern.ch/atlas-vp1/doc_new/sample_datafiles/geometry-ATLAS-R2-2016-01-00-01.db + +---- + +## Notes on Antialiasing + +In VP1Light, you can turn on [antialiasing](https://en.wikipedia.org/wiki/Spatial_anti-aliasing) to smooth the lines in the render of the 3D image. + +Please notice, however, that antialiasing depends on the graphical drivers installed on the computer. +So, please install proper drivers on your machine, if you can, without relying on generic drivers. +For example, if you have a NVidia card installed on your machine, consider to [install proper NVidia drivers](http://www.nvidia.com/Download/index.aspx?lang=en-us), without relying on generic drivers (e.g. the MESA driver on Linux): this will let you fully exploit your hardware, and the antialiasing capabilities of VP1Light. diff --git a/Projects/VP1Light/SETUP_VP1Light_DEPENDENCIES_UBUNTU.sh b/Projects/VP1Light/SETUP_VP1Light_DEPENDENCIES_UBUNTU.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0a393b4f0019fec5eb615a3b6326bb37f9c1cc0 --- /dev/null +++ b/Projects/VP1Light/SETUP_VP1Light_DEPENDENCIES_UBUNTU.sh @@ -0,0 +1,16 @@ + +printf '\n\e[48;5;021m-->Installing all VP1Light dependences...\e[0m\n'; + +sudo apt-get -y install git \ + cmake \ + python-dev \ + freeglut3-dev \ + zlib1g-dev \ + libssl-dev \ + libgd-dev \ + libxft-dev \ + libtbb-dev \ + rpm \ + uuid-dev + +printf '\n\e[48;5;112m-->DONE! - All VP1Light dependecies installed!\e[0m\n'; diff --git a/Projects/VP1Light/VP1LightReleaseEnvironmentConfig.cmake b/Projects/VP1Light/VP1LightReleaseEnvironmentConfig.cmake new file mode 100644 index 0000000000000000000000000000000000000000..50b1f7a59846f0be907d436f649213dcb714ffc2 --- /dev/null +++ b/Projects/VP1Light/VP1LightReleaseEnvironmentConfig.cmake @@ -0,0 +1,48 @@ +# +# This file holds the compile and runtime environment configuration specific +# for the VP1Light release, based on the AnalysisBase release. +# + +# This is a standalone project, so set the appropriate compile flags: +add_definitions( -DROOTCORE ) +add_definitions( -DXAOD_STANDALONE ) +add_definitions( -DXAOD_ANALYSIS ) +add_definitions( -DROOTCORE_RELEASE_SERIES=25 ) +add_definitions( -DBUILDVP1LIGHT ) + +if(CMAKE_BUILD_TYPE MATCHES Release OR CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + add_definitions(-DQT_NO_DEBUG_OUTPUT) # comment if you want to get debug messages in Release +endif(CMAKE_BUILD_TYPE MATCHES Release OR CMAKE_BUILD_TYPE MATCHES RelWithDebInfo) + +# And the same variables for CMake as well: +set( ROOTCORE TRUE CACHE BOOL + "Flag specifying that this is a \"RootCore\" release" ) +set( XAOD_STANDALONE TRUE CACHE BOOL + "Flag specifying that this is a standalone build" ) +set( BUILDVP1LIGHT TRUE CACHE BOOL + "Flag specifying that this is a VP1Light release (based on an AnalysisBase release)" ) +set( XAOD_ANALYSIS TRUE CACHE BOOL + "Flag specifying that this is an analysis release" ) + + +# Get OS version +atlas_os_id( _os _isValid ) +if( NOT _isValid ) + message( WARNING "Could not determine OS name. VP1Light cannot be built!" ) + return() +endif() + +string(REGEX MATCH "mac|ubuntu|slc|centos" DIST ${_os}) +if( NOT ${_os} STREQUAL "" ) + set( BUILDVP1LIGHT_DIST ${DIST} CACHE STRING + "Label storing the detected platform" FORCE ) + message ( STATUS " >>> Building VP1Light on ${_os}" ) +else() + message(STATUS " >>>> Building VP1Light: WARNING! Detected an unsupported platform! <<<<") +endif() + + +# Variable that should be picked up by the environment creation code: +set( VP1LightReleaseEnvironment_ENVIRONMENT + SET ROOTCOREDIR \${VP1Light_DIR} + SET ROOTCOREBIN \${VP1Light_DIR} ) diff --git a/Projects/VP1Light/build.sh b/Projects/VP1Light/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..09f1bb4a1a9d7b0cabfd584fb1bf5ff0140a6cbe --- /dev/null +++ b/Projects/VP1Light/build.sh @@ -0,0 +1,160 @@ +#!/bin/bash +# +# Script for building the release on top of externals built using the +# script in this directory. +# + +# Function printing the usage information for the script +usage() { + echo "Usage: build.sh [-t type] [-b dir] [-g generator] [-c] [-m] [-i] [-p] [-a]" + echo "" + echo " General flags:" + echo " -t: The (optional) CMake build type to use." + echo " -b: The (optional) build directory to use." + echo " -g: The (optional) CMake generator to use." + echo " -a: Abort on error." + echo " Build step selection:" + echo " -c: Execute the CMake step." + echo " -m: Execute the make/build step." + echo " -i: Execute the install step." + echo " -p: Execute the CPack step." + echo "" + echo " If none of the c, m, i or p options are set then the script will do" + echo " *all* steps. Otherwise only the enabled steps are run - it's your" + echo " reponsibility to ensure that precusors are in good shape" +} + +# Parse the command line arguments: +BUILDDIR="" +BUILDTYPE="RelWithDebInfo" +GENERATOR="Unix Makefiles" +EXE_CMAKE="" +EXE_MAKE="" +EXE_INSTALL="" +EXE_CPACK="" +NIGHTLY=true +while getopts ":t:b:g:hcmipa" opt; do + case $opt in + t) + BUILDTYPE=$OPTARG + ;; + b) + BUILDDIR=$OPTARG + ;; + g) + GENERATOR=$OPTARG + ;; + c) + EXE_CMAKE="1" + ;; + m) + EXE_MAKE="1" + ;; + i) + EXE_INSTALL="1" + ;; + p) + EXE_CPACK="1" + ;; + a) + NIGHTLY=false + ;; + h) + usage + exit 0 + ;; + :) + echo "Argument -$OPTARG requires a parameter!" + usage + exit 1 + ;; + ?) + echo "Unknown argument: -$OPTARG" + usage + exit 1 + ;; + esac +done + +if [ -z "$EXE_CMAKE" -a -z "$EXE_MAKE" -a -z "$EXE_INSTALL" -a \ + -z "$EXE_CPACK" ]; then + EXE_CMAKE="1" + EXE_MAKE="1" + EXE_INSTALL="1" + EXE_CPACK="1" +fi + +# Stop on errors from here on out: +set -e + +# Source in our environment +VP1LightSrcDir=$(dirname ${BASH_SOURCE[0]}) +if [ -z "$BUILDDIR" ]; then + BUILDDIR=${VP1LightSrcDir}/../../../build +fi +mkdir -p ${BUILDDIR} +BUILDDIR=$(cd ${BUILDDIR} && pwd) +source $VP1LightSrcDir/build_env.sh -b $BUILDDIR + +# create the actual build directory +mkdir -p ${BUILDDIR}/build/VP1Light +cd ${BUILDDIR}/build/VP1Light + +# consider a pipe failed if ANY of the commands fails +set -o pipefail + +# CMake: +if [ -n "$EXE_CMAKE" ]; then + # Remove the CMakeCache.txt file, to force CMake to find externals + # from scratch in an incremental build. + rm -f CMakeCache.txt + + # The package specific log files can only be generated with the Makefile + # and Ninja generators. Very notably it doesn't work with IDEs in general. + USE_LAUNCHERS="" + if [ "${GENERATOR}" = "Ninja" ] || [ "${GENERATOR}" = "Unix Makefiles" ]; then + USE_LAUNCHERS=-DCTEST_USE_LAUNCHERS:BOOL=TRUE + fi + + # Now run the actual CMake configuration: + time cmake -G "${GENERATOR}" \ + -DCMAKE_BUILD_TYPE:STRING=${BUILDTYPE} \ + ${USE_LAUNCHERS} \ + ${VP1LightSrcDir} 2>&1 | tee cmake_config.log +fi + +# For nightly builds we want to get as far as we can: +if [ "$NIGHTLY" = true ]; then + # At this point stop worrying about errors: + set +e +fi + +# Run the build: +if [ -n "$EXE_MAKE" ]; then + if [ "$NIGHTLY" = true ]; then + # In order to build the project in a nightly setup, allowing for some + # build steps to fail while still continuing, we need to use "make" + # directly. Only allowing the usage of the Makefile generator. + time make -k 2>&1 | tee cmake_build.log + else + # However in a non-nightly setup we can just rely on CMake to start + # the build for us. In this case we can use any generator we'd like + # for the build. Notice however that the installation step can still + # be only done correctly by using GNU Make directly. + time cmake --build . 2>&1 | tee cmake_build.log + fi +fi + +# Install the results: +if [ -n "$EXE_INSTALL" ]; then + time make install/fast \ + DESTDIR=${BUILDDIR}/install/VP1Light/${NICOS_PROJECT_VERSION} \ + 2>&1 | tee cmake_install.log +fi + +# Build an RPM for the release: +if [ -n "$EXE_CPACK" ]; then + time cpack 2>&1 | tee cmake_cpack.log + FILES=$(ls VP1Light*.rpm VP1Light*.dmg VP1Light*.tar.gz) + cp ${FILES} ${BUILDDIR}/ +fi diff --git a/Projects/VP1Light/build_env.sh b/Projects/VP1Light/build_env.sh new file mode 100644 index 0000000000000000000000000000000000000000..f4f14797e3f9417bdb44f4c676c8227288e2ae16 --- /dev/null +++ b/Projects/VP1Light/build_env.sh @@ -0,0 +1,88 @@ +# This script sets up the build enironment for an VP1Light +# build, on top of a built set of externals. +# +# This script is kept separate from the build.sh +# wrapper so it can be sourced separately from it when +# clients want to manage their own build and just want +# to setup the build environment + +env_usage() { + echo "Usage: build_env.sh [-b build dir]" +} + +# This function actually sets up the environment for us +# (factorise it here in case it needs skipped) +env_setup() { + + # As this script can be sourced we need to support zsh and + # possibly other Bourne shells + if [ "x${BASH_SOURCE[0]}" = "x" ]; then + # This trick should do the right thing under ZSH: + thisdir=$(dirname `print -P %x`) + if [ $? != 0 ]; then + echo "ERROR: This script must be sourced from BASH or ZSH" + return 1 + fi + else + # The BASH solution is a bit more straight forward: + thisdir=$(dirname ${BASH_SOURCE[0]}) + fi + VP1LightSrcDir=$(cd ${thisdir};pwd) + + # The directory holding the helper scripts: + scriptsdir=${VP1LightSrcDir}/../../Build/AtlasBuildScripts + + # Check if the user specified any source/build directories: + if [ "$BUILDDIR" = "" ]; then + BUILDDIR=${VP1LightSrcDir}/../../../build + fi + + # Set up the environment for the build: + export NICOS_PROJECT_VERSION=`cat ${VP1LightSrcDir}/version.txt` + export NICOS_ATLAS_RELEASE=${NICOS_PROJECT_VERSION} + export NICOS_PROJECT_RELNAME=${NICOS_PROJECT_VERSION} + export NICOS_PROJECT_HOME=$(cd ${BUILDDIR}/install;pwd)/VP1Light + + # Set up the VP1LightExternals project: + extDir=${BUILDDIR}/install/VP1LightExternals/${NICOS_PROJECT_VERSION}/InstallArea + if [ ! -d ${extDir} ]; then + echo "Didn't find the VP1LightExternals project under ${extDir}" + fi + echo "Setting up VP1LightExternals from: ${extDir}" + source ${extDir}/*/setup.sh +} + +# we need to reset the option index as we are sourcing this script +# http://stackoverflow.com/questions/23581368/bug-in-parsing-args-with-getopts-in-bash +OPTIND=1 + +# Parse the command line arguments: +BUILDDIR="" +while getopts "b:h" opt; do + case $opt in + b) + BUILDDIR=$OPTARG + ;; + h) + env_usage + ABORT=1 + ;; + :) + echo "Argument -$OPTARG requires a parameter!" + env_usage + ABORT=1 + ;; + ?) + echo "Unknown argument: -$OPTARG" + env_usage + ABORT=1 + ;; + esac +done + +# Put a big wrapper around bad argument case, because +# a sourced script should not call "exit". This is quite +# annoying... +if [ -z "$ABORT" ]; then + env_setup +fi diff --git a/Projects/VP1Light/build_externals.sh b/Projects/VP1Light/build_externals.sh new file mode 100755 index 0000000000000000000000000000000000000000..07e534638949353a71d6618b64122838e40ed02e --- /dev/null +++ b/Projects/VP1Light/build_externals.sh @@ -0,0 +1,110 @@ +#!/bin/bash +# +# Script building all the externals necessary for the nightly build. +# + +# Stop on errors: +set -e + +# Function printing the usage information for the script +usage() { + echo "Usage: build_externals.sh [-t build_type] [-b build_dir] [-f] [-c]" + echo " -f: Force rebuild of externals, otherwise if script" + echo " finds an external build present it will simply exit" + echo " -c: Build the externals for the continuous integration (CI) system," + echo " skipping the build of the externals RPMs." + echo "If a build_dir is not given the default is '../build'" + echo "relative to the athena checkout" +} + +# Parse the command line arguments: +BUILDDIR="" +BUILDTYPE="RelWithDebInfo" +FORCE="" +CI="" +while getopts ":t:b:fch" opt; do + case $opt in + t) + BUILDTYPE=$OPTARG + ;; + b) + BUILDDIR=$OPTARG + ;; + f) + FORCE="1" + ;; + c) + CI="1" + ;; + h) + usage + exit 0 + ;; + :) + echo "Argument -$OPTARG requires a parameter!" + usage + exit 1 + ;; + ?) + echo "Unknown argument: -$OPTARG" + usage + exit 1 + ;; + esac +done + +# We are in BASH, get the path of this script in a simple way: +thisdir=$(dirname ${BASH_SOURCE[0]}) +thisdir=$(cd ${thisdir};pwd) + +# Go to the main directory of the repository: +cd ${thisdir}/../.. + +# Check if the user specified any source/build directories: +if [ "$BUILDDIR" = "" ]; then + BUILDDIR=${thisdir}/../../../build +fi +mkdir -p ${BUILDDIR} +BUILDDIR=$(cd $BUILDDIR; pwd) + +if [ "$FORCE" = "1" ]; then + echo "Force deleting existing build area..." + rm -fr ${BUILDDIR}/install/VP1LightExternals + rm -fr ${BUILDDIR}/src/VP1LightExternals + rm -fr ${BUILDDIR}/build/VP1LightExternals +fi + +# Create some directories: +mkdir -p ${BUILDDIR}/install + +# Set some environment variables that the builds use internally: +export NICOS_PROJECT_VERSION=`cat ${thisdir}/version.txt` +export NICOS_ATLAS_RELEASE=${NICOS_PROJECT_VERSION} +export NICOS_PROJECT_RELNAME=${NICOS_PROJECT_VERSION} + +# The directory holding the helper scripts: +scriptsdir=${thisdir}/../../Build/AtlasBuildScripts +scriptsdir=$(cd ${scriptsdir}; pwd) + +# Flag for triggering the build of RPMs for the externals: +RPMOPTIONS="-r ${BUILDDIR}" +if [ "$CI" = "1" ]; then + RPMOPTIONS= +fi + +# Read in the tag/branch to use for VP1LightExternals: +VP1LightExternalsVersion=$(awk '/^VP1LightExternalsVersion/{print $3}' ${thisdir}/externals.txt) + +# Check out VP1LightExternals from the right branch/tag: +${scriptsdir}/checkout_atlasexternals.sh \ + -t ${VP1LightExternalsVersion} \ + -s ${BUILDDIR}/src/VP1LightExternals + +# Build VP1LightExternals: +export NICOS_PROJECT_HOME=$(cd ${BUILDDIR}/install;pwd)/VP1LightExternals +${scriptsdir}/build_atlasexternals.sh \ + -s ${BUILDDIR}/src/VP1LightExternals \ + -b ${BUILDDIR}/build/VP1LightExternals \ + -i ${BUILDDIR}/install/VP1LightExternals/${NICOS_PROJECT_VERSION} \ + -p VP1LightExternals ${RPMOPTIONS} -t ${BUILDTYPE} \ + -v ${NICOS_PROJECT_VERSION} diff --git a/Projects/VP1Light/externals.txt b/Projects/VP1Light/externals.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1bd466a4589d85aaac34c1bf99f3cb7b2411537 --- /dev/null +++ b/Projects/VP1Light/externals.txt @@ -0,0 +1,9 @@ +# Versions of the various externals to build before starting the build of +# this project, when doing a full stack nightly build. +# +# Remember that when specifying the name of a branch, you *must* put +# an "origin/" prefix before it. For tags however this is explicitly +# forbidden. + +# The version of atlas/atlasexternals to use: +VP1LightExternalsVersion = 4be765b4 # TODO: replace it!!! diff --git a/Projects/VP1Light/modules/VP1LightFunctions.cmake b/Projects/VP1Light/modules/VP1LightFunctions.cmake new file mode 100644 index 0000000000000000000000000000000000000000..ed6b82b7ea35971ae10f2617bcd0d64b5b048907 --- /dev/null +++ b/Projects/VP1Light/modules/VP1LightFunctions.cmake @@ -0,0 +1,41 @@ +# +# This module collects CMake functions that are useful when setting up an +# analysis release. +# + +# Function generating a RootCore/Packages.h header +# +# This function should be called in the main CMakeLists.txt file of the +# project, after the atlas_project(...) call, in order to generate a header file +# called "RootCore/Packages.h", in the format that RootCore generates it in. +# With one define statement per package that was found in he release. +# +# Usage: vp1light_generate_release_header() +# +function( vp1light_generate_release_header ) + + # Get the list of packages that were found: + get_property( _packages GLOBAL PROPERTY ATLAS_EXPORTED_PACKAGES ) + + # Generate a "RootCore/Package.h" file, in the same format that + # RootCore does/did: + set( _packagesFileName + ${CMAKE_BINARY_DIR}/RootCore/include/RootCore/Packages.h ) + file( MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/RootCore/include/RootCore ) + file( WRITE ${_packagesFileName} + "// Auto-generated file, please do not edit\n" + "#ifndef ROOTCORE_PACKAGES_H\n" + "#define ROOTCORE_PACKAGES_H\n\n" ) + foreach( pkgname ${_packages} ) + file( APPEND ${_packagesFileName} + "#define ROOTCORE_PACKAGE_${pkgname}\n" ) + endforeach() + file( APPEND ${_packagesFileName} "\n#endif // not ROOTCORE_PACKAGES_H\n" ) + unset( _packagesFileName ) + unset( _packages ) + + # Install the header in the usual place: + install( DIRECTORY ${CMAKE_BINARY_DIR}/RootCore/include/ + DESTINATION RootCore/include ) + +endfunction( vp1light_generate_release_header ) diff --git a/Projects/VP1Light/package_filters.txt b/Projects/VP1Light/package_filters.txt new file mode 100644 index 0000000000000000000000000000000000000000..e2351eb6bd12a8d5a2c8ecc30f21e95caf665ca1 --- /dev/null +++ b/Projects/VP1Light/package_filters.txt @@ -0,0 +1,56 @@ +# +# Packages to build as part of VP1Light: +# +# GeoModel ++ DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager ++ DetectorDescription/GeoModel/GeoModelStandalone/GeoModelErrorHandler ++ DetectorDescription/GeoModel/GeoModelStandalone/GeoRead ++ DetectorDescription/GeoModel/GeoModelStandalone/GeoWrite ++ DetectorDescription/GeoModel/GeoModelExamples +#+ DetectorDescription/GeoModel/GeoModelKernel # moved to Externals ++ DetectorDescription/GeoModel/GeoModelStandalone/TFPersistification ++ DetectorDescription/GeoModel/GeoModelUtilities ++ DetectorDescription/GeoPrimitives +# +# Utility packages ++ AtlasTest/TestTools ++ Calorimeter/CaloGeoHelpers ++ Control/AthToolSupport/.* ++ Control/AthContainersInterfaces ++ Control/AthContainers ++ Control/AthLinksSA ++ Control/xAODRootAccess.* ++ Control/CxxUtils ++ Event/EventPrimitives ++ MuonSpectrometer/MuonIdHelpers ++ Generators/TruthUtils ++ Tools/PathResolver +# +# VP1/VP1Light packages ++ graphics/VP1/RunVP1Light ++ graphics/VP1/VP1Base ++ graphics/VP1/VP1Gui ++ graphics/VP1/VP1HEPVis ++ graphics/VP1/VP1Plugins/VP1GeometryPlugin ++ graphics/VP1/VP1Plugins/VP1AODPlugin ++ graphics/VP1/VP1Plugins/VP1LightPlugin ++ graphics/VP1/VP1Systems/VP1GeometrySystems ++ graphics/VP1/VP1Systems/VP1GuideLineSystems ++ graphics/VP1/VP1Systems/VP1AODSystems ++ graphics/VP1/VP1Utils ++ graphics/VP1/VP1UtilsBase +# +# xAOD packages +- Event/xAOD/.*AthenaPool ++ Event/xAOD/xAODMetaDataCnv +#+ Event/xAOD/xAODTriggerCnv +- Event/xAOD/xAODCaloRings +- Event/xAOD/.*Cnv ++ Event/xAOD/.* +# +# Trigger packages ++ Trigger/TrigConfiguration/TrigConfBase ++ Trigger/TrigConfiguration/TrigConfL1Data ++ Trigger/TrigConfiguration/TrigConfHLTData ++ Trigger/TrigEvent/TrigNavStructure +- .* diff --git a/Projects/VP1Light/scripts/load_packages.C.in b/Projects/VP1Light/scripts/load_packages.C.in new file mode 100644 index 0000000000000000000000000000000000000000..9d47dbba4f5e387d305f51263578180496e9ba73 --- /dev/null +++ b/Projects/VP1Light/scripts/load_packages.C.in @@ -0,0 +1,48 @@ +// +// This is a much simplified version of the RootCore script with the same +// name, basically just here to provide the existing scripts/tests with a +// file that they can use. +// + +// System include(s): +#include <stdexcept> + +// ROOT include(s): +#include <TSystem.h> +#include <TROOT.h> + +/// Function setting up interactive ROOT to use the analysis release +/// +/// In order to use macros or PyROOT scripts that make use of symbols +/// defined in the analysis release, the user has to execute this macro. +/// It takes care of setting up the compilation options of ACLiC, and +/// of calling xAOD::Init(). +/// +/// @param options An unused parameter, just to mimic the RootCore function +/// +void load_packages( const char* options = "" ) { + + // Make sure that some reasonable environment is set up: + const char* ROOTCOREDIR = gSystem->Getenv( "ROOTCOREDIR" ); + if( ! ROOTCOREDIR ) { + throw std::runtime_error( "ROOTCOREDIR not set, please set " + "the environment" ); + } + const std::string dir = ROOTCOREDIR; + + const char* ROOTCOREBIN = gSystem->Getenv( "ROOTCOREBIN" ); + if( ! ROOTCOREBIN ) { + throw std::runtime_error( "ROOTCOREBIN not set, please set " + "the environment"); + } + const std::string bin = ROOTCOREBIN; + + // Set the compilation options for ACLiC: + gSystem->AddIncludePath( "@CMAKE_CXX_FLAGS@" ); + + // Load the xAODRootAccess library, in a hard-coded way: + gSystem->Load( "libxAODRootAccess" ); + gROOT->ProcessLine( "xAOD::Init().ignore()" ); + + return; +} diff --git a/Projects/VP1Light/version.txt b/Projects/VP1Light/version.txt new file mode 100644 index 0000000000000000000000000000000000000000..8acdd82b765e8e0b8cd8787f7f18c7fe2ec52493 --- /dev/null +++ b/Projects/VP1Light/version.txt @@ -0,0 +1 @@ +0.0.1 diff --git a/Trigger/TrigConfiguration/TrigConfBase/CMakeLists.txt b/Trigger/TrigConfiguration/TrigConfBase/CMakeLists.txt index 18b007e9cf5ddf636f2d01b994ed96ea1c6e8e6e..fe1bd7d05bfe3e824c2a42af625edac0639dc1df 100644 --- a/Trigger/TrigConfiguration/TrigConfBase/CMakeLists.txt +++ b/Trigger/TrigConfiguration/TrigConfBase/CMakeLists.txt @@ -23,6 +23,7 @@ atlas_add_library( TrigConfBase atlas_install_joboptions( share/*.py ) # Tests: +if( NOT XAOD_STANDALONE ) atlas_add_component( TrigConfBaseTest test/TrigConfMsgAlg.cxx LINK_LIBRARIES TrigConfBase AthenaBaseComps ) @@ -33,3 +34,4 @@ atlas_add_test( trigconf_msg_standalone_test atlas_add_test( trigconf_msg_athena_test SCRIPT athena.py TrigConfBase/test_TrigConfMsgAlg.py ) +endif() # NOT XAOD_STANDALONE diff --git a/graphics/VP1/README.md b/graphics/VP1/README.md index 5ee56062fc10b2cffc985108dad8a785e147adb4..2b628215eaad271f7d0305a4332988825d04f633 100644 --- a/graphics/VP1/README.md +++ b/graphics/VP1/README.md @@ -24,7 +24,7 @@ User's support: for all requests and reports, feel free to file a JIRA ticket on Mailing list - feel free to send us any questions about VP1 and related topics: https://atlas-vp1.web.cern.ch/atlas-vp1/home/contacts/ - + ### Event display approvals -For event displays which are not part of any physics paper and which you want to use for public usage (press release, multimedia, conference, talk, ...), you can ask an express approval on this dedicated JIRA project: https://its.cern.ch/jira/projects/ATLDISPLAY/summary \ No newline at end of file +For event displays which are not part of any physics paper and which you want to use for public usage (press release, multimedia, conference, talk, ...), you can ask an express approval on this dedicated JIRA project: https://its.cern.ch/jira/projects/ATLDISPLAY/summary diff --git a/graphics/VP1/RunVP1Light/CMakeLists.txt b/graphics/VP1/RunVP1Light/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..52604369f72ba446b3e6329cf8c067dc684427af --- /dev/null +++ b/graphics/VP1/RunVP1Light/CMakeLists.txt @@ -0,0 +1,41 @@ +############################################################################### +# Package: RunVP1Light +################################################################################ +# Author: Riccardo Maria BIANCHI <rbianchi@cern.ch> +################################################################################ + +# Declare the package name: +atlas_subdir( RunVP1Light ) + +# Declare the package's dependencies: +atlas_depends_on_subdirs( + PUBLIC graphics/VP1/VP1Gui + PUBLIC graphics/VP1/VP1UtilsBase + ) + +# External dependencies: +find_package( Qt5 COMPONENTS Core OpenGL ) +find_package( Coin3D ) +find_package( SoQt ) + +#message( "QT5_ROOT: ${QT5_ROOT} - QTDIR: $ENV{QTDIR} - Qt5_FOUND: ${Qt5_FOUND} - QTLIB: $ENV{QTLIB} - QTINC: $ENV{QTINC}" ) + +if( APPLE ) + set(CMAKE_MACOSX_RPATH 1) +endif() + +# Component(s) in the package: +atlas_add_executable( vp1light RunVP1Light/*.h src/*.cxx + INCLUDE_DIRS ${SOQT_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} + LINK_LIBRARIES VP1Gui Qt5::Core VP1UtilsBase ${SOQT_LIBRARIES} ${COIN3D_LIBRARIES} ) + +# RPATH for AppImage +# if(UNIX AND NOT APPLE) +set_target_properties(vp1light PROPERTIES + INSTALL_RPATH "$ORIGIN/../lib:$$ORIGIN/" + INSTALL_RPATH_USE_LINK_PATH TRUE) +# endif() + +# Install files from the package: +##atlas_install_scripts( share/* ) # installs into bin/ +atlas_install_runtime( share/* ) # install into share/ diff --git a/graphics/VP1/RunVP1Light/RunVP1Light/VP1LightRun.h b/graphics/VP1/RunVP1Light/RunVP1Light/VP1LightRun.h new file mode 100755 index 0000000000000000000000000000000000000000..ad58b5a82a6b47b42e6e4a5906bc8ef8753ec3b8 --- /dev/null +++ b/graphics/VP1/RunVP1Light/RunVP1Light/VP1LightRun.h @@ -0,0 +1,57 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +///////////////////////////////////////////////////////////// +// // +// Header file for class VP1LightRun // +// // +// author: Riccardo-Maria BIANCHI <rbianchi@cern.ch> // +// 23 May 2014 // +// // +// This is the Athena algorithm starting a VP1Light GUI // +// // +///////////////////////////////////////////////////////////// + + +#ifndef VP1LIGHT_VP1RUN +#define VP1LIGHT_VP1RUN + +#include <string> +#include <vector> + +class VP1Gui; + +class VP1LightRun +{ + public: + // VP1LightRun(const std::string& name, ISvcLocator* pSvcLocator); + VP1LightRun(const std::string& name); + ~VP1LightRun(); + + bool initialize(); + bool execute(); + bool finalize(); + + // void handle(const Incident& inc); + void handle(); + + private: + // IToolSvc* m_toolSvc; + VP1Gui * m_vp1gui; + + std::vector<std::string> m_initialvp1files; + std::string m_initialCruiseMode;//"NONE", "EVENT", "TAB", "BOTH". + unsigned m_initialCruiseSeconds; + + bool m_noGui;//For testing job-options in RTT + + // Properties for multiple input files (mf) + bool m_mfOn; // Flag to turn multiple files ON/OFF. Default OFF + std::string m_mfSourceDir; // Directory to take event files from + std::string m_mfLocalCopyDir; // Directory to keep local copies of processed events. Default "." + int m_mfLimit; // Maximum number of local copies to keep + std::vector<std::string> m_mfAvailableLocalInputDirectories;//Will only be used if sourcedir is set and local +}; + +#endif diff --git a/graphics/VP1/RunVP1Light/python/VP1EvtFilter.py b/graphics/VP1/RunVP1Light/python/VP1EvtFilter.py new file mode 100644 index 0000000000000000000000000000000000000000..70004b097523725b1fe438df500e19feec5296d9 --- /dev/null +++ b/graphics/VP1/RunVP1Light/python/VP1EvtFilter.py @@ -0,0 +1,65 @@ +## +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +## + +def readFileSimplified(filename): + import os.path + if not os.path.exists(filename): return None + lines = [] + for l in open(filename): + if '#' in l: l = l[0:l.index('#')] #Remove comments + l=' '.join(l.split())#simplify whitespace + if l: lines += [l] + return lines + +def filterEntry(parts): + #parts is either [evt] or [run,evt]: + assert len(parts) in [1,2] + filter_run = int(parts[0]) if len(parts)==2 else None + filter_evt = int(parts[1]) if len(parts)==2 else int(parts[0]) + assert (filter_run==None or filter_run>=0) and filter_evt>=0 + return (filter_run,filter_evt) + +def readFiltersFromFile(filename): + lines = readFileSimplified(filename) + if lines==None: return None + filts=[] + for l in lines: + filts+=[filterEntry(l.replace(':',' ').split())] + return filts + +def parseFilterString(s): + import os.path + excludemode=False + if s.startswith('%'): + excludemode=True + s=s[1:] + try: + filters=[] + tmp=s + for filt in tmp.split(','): + if os.path.exists(filt): + #This is a file... + for filefilt in readFiltersFromFile(filt): + filters += [filefilt] + continue + filters += [filterEntry(filt.split(':'))] + except: + filters=[] + def vp1CfgErr(s): print "VP1 CONFIGURATION ERROR: %s" % s#fixme: should go in common utils module + vp1CfgErr("Badly formatted filter string '%s'" % str(s)) + raise + return (excludemode,filters) + +def installEventFilter(filters): + def vp1filter(run,evt): + print "vp1filter(%i,%i) called" %(run,evt) + for filter in filters[1]: + if evt==filter[1] and (filter[0]==None or filter[0]==run): return not filters[0] + return filters[0] + from AthenaCommon.AlgSequence import AthSequencer + seq = AthSequencer('AthFilterSeq') + from GaudiSequencer.PyComps import PyEvtFilter + seq += PyEvtFilter ('vp1filteralg') + seq.vp1filteralg.filter_fct = vp1filter + seq.vp1filteralg.evt_info = ''#To trigger keyless retrieve of the EventInfo diff --git a/graphics/VP1/RunVP1Light/share/clear-bash-hash-table-vp1 b/graphics/VP1/RunVP1Light/share/clear-bash-hash-table-vp1 new file mode 100644 index 0000000000000000000000000000000000000000..6d6c0df03cddd38a957705bb0813426b3e8040ba --- /dev/null +++ b/graphics/VP1/RunVP1Light/share/clear-bash-hash-table-vp1 @@ -0,0 +1,12 @@ +## +# Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +## + +#!/bin/bash +# Script which rebuilds the Bash hash table for the 'vp1' executable, +# after changing and recompiling the share/vp1 script +# +# Riccardo M. BIANCHI <rbianchi@cern.ch>, First version Jan 2016. + +echo "clear the Bash hash table for the 'vp1' executable +hash -d vp1 diff --git a/graphics/VP1/RunVP1Light/src/VP1LightRun.cxx b/graphics/VP1/RunVP1Light/src/VP1LightRun.cxx new file mode 100755 index 0000000000000000000000000000000000000000..bdd1c6c44dd40f8d945fa4b206bab91917747be0 --- /dev/null +++ b/graphics/VP1/RunVP1Light/src/VP1LightRun.cxx @@ -0,0 +1,231 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// Author: Riccardo.Maria.Bianchi@cern.ch, Apr 2017 +// Update: Apr 2019 + +#include "RunVP1Light/VP1LightRun.h" + +#include "VP1Gui/VP1Gui.h" +#include "VP1UtilsBase/VP1FileUtilities.h" + +// #include "EventInfo/EventInfo.h" +// #include "EventInfo/TriggerInfo.h" +// #include "EventInfo/EventID.h" +// #include "PathResolver/PathResolver.h" + +// C++ includes +#include <vector> +#include <stdexcept> +#include <iostream> +#include <iomanip> +#include <cstdint> // for uint64_t (unsigned long long) +#include <cstdlib> //For setenv +#include <chrono> +// #include <ctime> + +using namespace std; + + +class StoreGateSvc; +class ISvcLocator; +class IToolSvc; + +VP1LightRun::VP1LightRun(const std::string& name) : + m_vp1gui(0) +{ + std::cout << "VP1LightRun - name: " << name << std::endl; + m_noGui=false; + + // Pick up patched Coin + ::setenv("LCGPATCH_COINMULTISELECT","1",1); +} + +//____________________________________________________________________ +VP1LightRun::~VP1LightRun() +{ +} + +//____________________________________________________________________ +bool VP1LightRun::initialize() +{ + // msg(MSG::DEBUG) << " in initialize() " << endreq; + std::cout << " in initialize() " << std::endl; + + + + + std::vector<std::string>::iterator it, itE = m_initialvp1files.end(); + for (it = m_initialvp1files.begin();it!=itE;++it) { + } + + // dummy objects + StoreGateSvc* evtStore = nullptr; + StoreGateSvc* detStore = nullptr; + ISvcLocator* serviceLocator = nullptr; + IToolSvc* toolSvc = nullptr; + + // create VP1 GUI! + m_vp1gui = new VP1Gui( evtStore, detStore, serviceLocator, toolSvc, + m_initialvp1files, + m_initialCruiseMode,m_initialCruiseSeconds, + (m_mfOn ? m_mfSourceDir : ""), + (m_mfOn ? m_mfLocalCopyDir : ""), + m_mfLimit, + ( m_mfOn ? m_mfAvailableLocalInputDirectories : std::vector<std::string>() ) ); + +#ifdef JFBCOMMENTOUT + if (!m_vp1gui->argumentsAreValid()) { + std::cout << "arguments not valid..." << std::endl; + delete m_vp1gui; + m_vp1gui = 0; + exit(1);//Should we do this? It is kind of nice to not have to dig through the logfile to find the failure. + return false; // StatusCode::FAILURE; + } + std::cout << "OK! Returning TRUE..." << std::endl; +#endif + return true; //StatusCode::SUCCESS; +} + +//____________________________________________________________________ +bool VP1LightRun::execute() +{ + // msg(MSG::DEBUG) <<" in execute() " << endreq; + std::cout <<"VP1LightRun:: in execute() " << std::endl; + + // std::cout << "m_vp1gui: " << m_vp1gui << " - m_noGui: " << m_noGui << " - m_vp1gui->hasBeenInitialised(): " << m_vp1gui->hasBeenInitialised() << std::endl; + if (!m_vp1gui) { + std::cout << "no vp1gui. Returning..." << std::endl; + return false; //StatusCode::FAILURE; + } + + if ( !m_noGui && !m_vp1gui->hasBeenInitialised() ) { + std::cout << "Launching VP1...!!" << std::endl; + m_vp1gui->init();//Launch! + } + + // const EventInfo* evt; + // StatusCode status = evtStore()->retrieve(evt); + // if(status.isSuccess()) { + if(true) { + // Get run/event number: + const uint64_t eventNumber = 0; //evt->event_ID()->event_number(); + int runNumber = 0; //evt->event_ID()->run_number(); + // msg(MSG::DEBUG) << " Got run number = " << runNumber << ", event number = " << eventNumber << endreq; + std::cout << " Got run number = " << runNumber << ", event number = " << eventNumber << std::endl; + + // Get time stamp: + // unsigned time = evt->event_ID()->time_stamp();//0 means no info. + std::chrono::time_point<std::chrono::system_clock> now; + now = std::chrono::system_clock::now(); + unsigned time = std::chrono::duration_cast<std::chrono::seconds>( now.time_since_epoch() ).count(); + std::cout << " Got timestamp = " << time << std::endl; + + // Get L1 trigger type + // TriggerInfo* _trig = evt->trigger_info(); + // unsigned int trigType = _trig ? _trig->level1TriggerType() : 0; + unsigned int trigType = 0; //_trig ? _trig->level1TriggerType() : 0; + + if (m_noGui||m_vp1gui->executeNewEvent(runNumber,eventNumber,trigType,time)) { + return true; //StatusCode::SUCCESS; + } else { + // msg(MSG::INFO) << " Ending application gracefully." << endreq; + std::cout << " Ending application gracefully." << std::endl; + return false; //StatusCode::FAILURE; + } + }; + + // msg(MSG::WARNING) << " Unable to retrieve EventInfo from StoreGate. Skipping" << endreq; + + std::cout << "VP1LightRun::execute() returns TRUE..." << std::endl; + return true; //StatusCode::SUCCESS; + +} + +//____________________________________________________________________ +bool VP1LightRun::finalize() +{ + // msg(MSG::DEBUG) <<" in finalize() " << endreq; + std::cout << " in finalize() " << std::endl; + + if (!m_vp1gui) + return false; //StatusCode::FAILURE; + + if (!m_noGui) + m_vp1gui->cleanup(); + delete m_vp1gui; + + return true; // StatusCode::SUCCESS; +} + +//____________________________________________________________________ +void VP1LightRun::handle() +{ + std::cout << " in handle() " << std::endl; + + // msg(MSG::INFO) << "Handling incident '" << inc.type() << "'" << endreq; + + if (!m_vp1gui) { + // msg(MSG::INFO) << "Aborting due to null VP1Gui pointer." << endreq; + std::cout << "Aborting due to null VP1Gui pointer." << std::endl; + return; + } + + std::vector<std::string> vect; + // StringArrayProperty inputCollections("InputCollections", vect); + // + // sc = propertyServer->getProperty(&inputCollections); + // if(!sc.isSuccess()) { + // msg(MSG::INFO) << "Could not get InputCollections property" << endreq; + // return; + // } + // else + // msg(MSG::DEBUG) << " Got InputCollections property" << endreq; + // + // std::vector<std::string>::const_iterator iter = inputCollections.value().begin(); + // std::vector<std::string>::const_iterator last = inputCollections.value().end(); + // for(; iter != last; iter++) { + // if(*iter != fileInc->fileName()) + // vect.push_back(*iter); + // } + + if(m_mfOn) { + std::string strNewFileName = m_vp1gui->nextRequestedEventFile(); + + if (strNewFileName.empty()) + return; + if (!VP1FileUtilities::fileExistsAndReadable(strNewFileName)) { + // msg(MSG::WARNING) << " File requested by VP1 does not exists or is not readable: "<<strNewFileName<<". Ending." << endreq; + cout << " File requested by VP1 does not exists or is not readable: "<<strNewFileName<<". Ending." << endl; + return; + } + + vect.push_back(strNewFileName); + // msg(MSG::INFO) << " Setting next event file: " << strNewFileName<< endreq; + cout << " Setting next event file: " << strNewFileName<< endl; + } + else { + std::vector<std::string> strNewFileNames = m_vp1gui->userRequestedFiles(); + for(unsigned i=0; i<strNewFileNames.size(); ++i) { + const std::string& strNewFileName = strNewFileNames[i]; + if (strNewFileName.empty()) + continue; + if (!VP1FileUtilities::fileExistsAndReadable(strNewFileName)) { + // msg(MSG::WARNING) << " File requested by VP1 does not exists or is not readable: " << strNewFileName << endreq; + cout << " File requested by VP1 does not exists or is not readable: " << strNewFileName << endl; + continue; + } + vect.push_back(strNewFileName); + // msg(MSG::INFO) << " Setting next event file: " << strNewFileName<< endreq; + cout << " Setting next event file: " << strNewFileName<< endl; + } + } + + // StringArrayProperty newInputCollections("InputCollections", vect); + // + // if(propertyServer->setProperty(newInputCollections)!=StatusCode::SUCCESS) + // msg(MSG::WARNING) << "Could not set new InputCollections property" << endreq; + // else + // msg(MSG::DEBUG) << " InputCollections property set" << endreq; +} diff --git a/graphics/VP1/RunVP1Light/src/main.cxx b/graphics/VP1/RunVP1Light/src/main.cxx new file mode 100644 index 0000000000000000000000000000000000000000..bb39b3fa0181d7e625ec8ff509de3eb4e1d9cc8e --- /dev/null +++ b/graphics/VP1/RunVP1Light/src/main.cxx @@ -0,0 +1,96 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +// Author: Riccardo.Maria.Bianchi@cern.ch, Apr 2017 +// Update: Apr 2019 + +#include "RunVP1Light/VP1LightRun.h" + +// Qt includes +#include <QSettings> +#include <QString> +#include <QDir> +#include <QDebug> +// #include <QCoreApplication> +#include <QCommandLineParser> + +// C++ includes +#include <iostream> +#include <stdlib.h> +#include <fstream> + +int main(int argc, char** argv) +{ + QStringList arguments; + for (int i = 0; i<=argc; i++){ + arguments << argv[i]; + } + + QCommandLineParser parser; + + // An database directory option + QCommandLineOption databaseDirectoryOption(QStringList() << "d" << "database-directory", "Use geometry database <file>.", "default"); + parser.addOption(databaseDirectoryOption); + + // An AOD directory option + QCommandLineOption AODDirectoryOption(QStringList() << "x" << "xaod-directory", "Use xAOD file <file>.", "default"); + parser.addOption(AODDirectoryOption); + + // Print help + QCommandLineOption helpOption(QStringList() << "h" << "help", "Show help."); + parser.addOption(helpOption); + + // Process the command line arguments given by the user + parser.process(arguments); + + bool helpIsSet = parser.isSet(helpOption); + bool dbIsSet = parser.isSet(databaseDirectoryOption); + bool AODIsSet = parser.isSet(AODDirectoryOption); + QString dbDir = parser.value(databaseDirectoryOption); + QString aodDir = parser.value(AODDirectoryOption); + + //If help option is set, display help and exit VP1Light + if(helpIsSet){ + qInfo() << "Usage"; + qInfo() << " "; + qInfo() << " vp1light [options]"; + qInfo() << " "; + qInfo() << "Add path to geometry database or AOD file as options. Alternatively they can be set inside VP1Light."; + qInfo() << " "; + qInfo() << "Options:"; + qInfo() << " -h, --help = Show help."; + qInfo() << " -d, --database-directory <path-to-DB> = Specify geometry database file."; + qInfo() << " -x, --xaod-directory <path-to-xAOD> = Specify xAOD file."; + return 0; + } + + // Save settings + QSettings settings("ATLAS", "VP1Light"); + if(dbIsSet){ + settings.setValue("db/path", dbDir); + settings.setValue("db/dbByEnv", "1"); + } + else{ + settings.setValue("db/dbByEnv", ""); + } + if(AODIsSet){ + settings.setValue("aod/path", aodDir); + settings.setValue("aod/aodByEnv", "1"); + } + else{ + settings.setValue("aod/aodByEnv", ""); + } + + // Disable expert settings by default + if(settings.value("ExpertSettings/notFirstStart").toString().isEmpty()){ + settings.setValue("ExpertSettings/notFirstStart","1"); + settings.setValue("ExpertSettings/enableExpertSettings",""); + } + + + VP1LightRun vp1light("my first VP1Light test"); + + vp1light.initialize(); + while ( vp1light.execute()); +} diff --git a/graphics/VP1/VP1Algs/share/vp1 b/graphics/VP1/VP1Algs/share/vp1 index 9106ba9983e72a87e96c764076effe8c7b7c7a30..ccc7dad08d1b30c43f9ad4309add12d6fcd95e20 100755 --- a/graphics/VP1/VP1Algs/share/vp1 +++ b/graphics/VP1/VP1Algs/share/vp1 @@ -759,7 +759,7 @@ if [ "x$FLAG_HELP" != "x0" ]; then echo echo " -nsw : Enable the Muon New Small Wheel geometry (and disable the existing small wheel)." echo - echo " -slhc : Enable special configurations for SLHC studies." + echo " -slhc : Enable special configurations for SLHC studies." echo echo " -customgeom : Enable a custom geometry." echo diff --git a/graphics/VP1/VP1Base/CMakeLists.txt b/graphics/VP1/VP1Base/CMakeLists.txt index 6ab18d579e51ec5e1753e7e2c55e1d378847b6d4..cd295c6587b8e0bebbbb70f033e563e78588bc5f 100644 --- a/graphics/VP1/VP1Base/CMakeLists.txt +++ b/graphics/VP1/VP1Base/CMakeLists.txt @@ -9,9 +9,22 @@ atlas_subdir( VP1Base ) # Set up the package's dependencies: -atlas_depends_on_subdirs( - PUBLIC DetectorDescription/GeoPrimitives - PRIVATE graphics/VP1/VP1HEPVis ) +atlas_depends_on_subdirs( PUBLIC + DetectorDescription/GeoPrimitives + Event/xAOD/xAODBase + PRIVATE + graphics/VP1/VP1HEPVis ) + +# Get OS version +atlas_os_id( _os _isValid ) +if( NOT _isValid ) + message( WARNING "Could not determine OS name!" ) + return() +endif() +message ( STATUS " > Compiling on ${_os}" ) + +# Set up the build of Coin3D: +# Select which version to use: # Find the external dependencies: find_package( Qt5 COMPONENTS Core OpenGL Gui PrintSupport Widgets ) diff --git a/graphics/VP1/VP1Base/VP1Base/IVP1System.h b/graphics/VP1/VP1Base/VP1Base/IVP1System.h index 86db568aee33a650acd00ea6157ee5fbdae966c9..ac1b1fb81d0cb21ad175a9f9ce4fc54d28fab95c 100644 --- a/graphics/VP1/VP1Base/VP1Base/IVP1System.h +++ b/graphics/VP1/VP1Base/VP1Base/IVP1System.h @@ -19,6 +19,10 @@ #include <QObject> #include <QByteArray> +#ifdef BUILDVP1LIGHT + #include "xAODBase/IParticle.h" +#endif // BUILDVP1LIGHT + class IVP1ChannelWidget; class StoreGateSvc; class ISvcLocator; @@ -85,9 +89,20 @@ public: void messageDebug(const QString& addtostart, const QStringList&, const QString& addtoend = "") const; void messageVerbose(const QString& addtostart, const QStringList&, const QString& addtoend = "") const; +#ifdef BUILDVP1LIGHT + xAOD::TEvent* getEvent(); + void setEvent(xAOD::TEvent* event ); + QStringList getObjectList(xAOD::Type::ObjectType); // Pass the collection names + void setObjectList(QList<QStringList>); +#endif // BUILDVP1LIGHT + signals: void sysmessage(QString) const; +#ifdef BUILDVP1LIGHT + void signalLoadEvent(IVP1System*); +#endif // BUILDVP1LIGHT + public://Public for easier use in helper classes. void updateGUI();//Please call this occasionally if doing a lot of @@ -136,6 +151,12 @@ signals: private: static bool s_vp1verbose; + +#ifdef BUILDVP1LIGHT + QList<QStringList> m_list; + xAOD::TEvent* m_event; +#endif // BUILDVP1LIGHT + }; #endif diff --git a/graphics/VP1/VP1Base/VP1Base/VP1ControllerMacros.h b/graphics/VP1/VP1Base/VP1Base/VP1ControllerMacros.h index 4f05f9599f3b3324b6aa79f5cc6f9216c9ec55eb..8dde55b3209d8ea00aed40b683423bc972c06b71 100644 --- a/graphics/VP1/VP1Base/VP1Base/VP1ControllerMacros.h +++ b/graphics/VP1/VP1Base/VP1Base/VP1ControllerMacros.h @@ -2,6 +2,8 @@ Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ +#include "VP1Base/VP1Msg.h" + #ifndef VP1CONTROLLERMACROS_H #define VP1CONTROLLERMACROS_H @@ -15,7 +17,7 @@ #define VP1LASTVARNAME(x) VP1IMPVARNAME->last_##x #define POSSIBLECHANGE_IMP(x) void VP1SLOTNAME(x)() { \ if (changed( VP1LASTVARNAME(x) , x())) { \ - if (verbose()&&!initVarsMode()) messageVerbose("Emitting "+QString(VP1STRINGIFY(VP1SIGNALNAME(x)))+"( "+toString(VP1LASTVARNAME(x))+" )"); \ + if (VP1Msg::verbose()&&!initVarsMode()) messageVerbose("Emitting "+QString(VP1STRINGIFY(VP1SIGNALNAME(x)))+"( "+toString(VP1LASTVARNAME(x))+" )"); \ emit VP1SIGNALNAME(x)(VP1LASTVARNAME(x)); } } #endif diff --git a/graphics/VP1/VP1Base/VP1Base/VP1Deserialise.h b/graphics/VP1/VP1Base/VP1Base/VP1Deserialise.h index edab6348ea80f1160fbd3e6a4d540c8ac975e3c2..0b2d5ea8d9d245825e2a4930d2546e62d3f45218 100644 --- a/graphics/VP1/VP1Base/VP1Base/VP1Deserialise.h +++ b/graphics/VP1/VP1Base/VP1Base/VP1Deserialise.h @@ -18,6 +18,7 @@ #define VP1DESERIALISE_H #include "VP1Base/VP1HelperClassBase.h" +#include "VP1Base/VP1Msg.h" #include <typeinfo> class VP1EtaPhiCutWidget; class VP1DrawOptionsWidget; diff --git a/graphics/VP1/VP1Base/VP1Base/VP1Msg.h b/graphics/VP1/VP1Base/VP1Base/VP1Msg.h index a664a5f7b0e1fe1ac0d31b51cf0769c71e6fca10..1f0897865b2f422258dfaf9ec3523b76904acb7a 100644 --- a/graphics/VP1/VP1Base/VP1Base/VP1Msg.h +++ b/graphics/VP1/VP1Base/VP1Base/VP1Msg.h @@ -35,7 +35,14 @@ class IVP1System; class VP1Msg : public VP1String { public: - static bool verbose() { return s_verbose; } // Returns true if env var VP1_VERBOSE_OUTPUT=1 + static bool verbose() { return m_verbose; } // Returns true if env var VP1_VERBOSE_OUTPUT=1 + static bool debug() { return m_debug; } // Returns true if env var VP1_DEBUG_OUTPUT=1 + + #if defined BUILDVP1LIGHT + static void enableMsg(const QString&, const QString&); + #else + static void enableMsg(const QString&); + #endif static void message(const QString&, IVP1System*sys = 0);//Non-zero sys pointer to get message in GUI static void messageDebug(const QString&); @@ -60,7 +67,8 @@ public: private: VP1Msg(){} ~VP1Msg(){} - static bool s_verbose; + static bool m_verbose; + static bool m_debug; }; #endif diff --git a/graphics/VP1/VP1Base/VP1Base/VP1QtUtils.h b/graphics/VP1/VP1Base/VP1Base/VP1QtUtils.h index 8f61bcee4c9401095dd4bbbe5b28d56a2be2957f..c36ef22bf41bdf8d31d0964252774fa9e3dac2a1 100644 --- a/graphics/VP1/VP1Base/VP1Base/VP1QtUtils.h +++ b/graphics/VP1/VP1Base/VP1Base/VP1QtUtils.h @@ -28,6 +28,11 @@ public: // For getting/setting environment variables // //////////////////////////////////////////////////////////// + static bool expertSettingIsSet(const QString& type, const QString& name); + static QString expertSettingValue(const QString& type, const QString& name); + static bool expertSettingIsOn(const QString& type, const QString& name); + static void setExpertSetting(const QString& type, const QString& name, const QString& content); + static bool environmentVariableIsSet( const QString& name );//If variable is at all defined (returns true if variable has value "0") static QString environmentVariableValue( const QString& name );//Returns "" if not defined. static bool environmentVariableIsOn( const QString& name );//Returns false if undefined or value is "0", "", "false"/"off"/"no" (any capitalisation). Otherwise returns true. diff --git a/graphics/VP1/VP1Base/VP1Base/VP1Serialise.h b/graphics/VP1/VP1Base/VP1Base/VP1Serialise.h index a85bae0746de9370dca78841bb5455058ba9071d..17d215740beacaa39a28e32f15fb056799ced0d4 100644 --- a/graphics/VP1/VP1Base/VP1Base/VP1Serialise.h +++ b/graphics/VP1/VP1Base/VP1Base/VP1Serialise.h @@ -18,6 +18,7 @@ #define VP1PERSISTIFY_H #include "VP1Base/VP1HelperClassBase.h" +#include "VP1Base/VP1Msg.h" #include <typeinfo> #include <QDataStream> class VP1EtaPhiCutWidget; @@ -126,7 +127,7 @@ private: template <class T> void VP1Serialise::save(const T& t) {//Fallback template method - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Saving "+QString(typeid(T).name())+" via datastream operator"); *(stream()) << t; } diff --git a/graphics/VP1/VP1Base/VP1Base/VisibleObjectToMaterialHelper.icc b/graphics/VP1/VP1Base/VP1Base/VisibleObjectToMaterialHelper.icc index e35df20f8a01426c7e0a960cbdb113d226e9c35a..17bbf1b3ba3633789297f00041efd620c3b822be 100644 --- a/graphics/VP1/VP1Base/VP1Base/VisibleObjectToMaterialHelper.icc +++ b/graphics/VP1/VP1Base/VP1Base/VisibleObjectToMaterialHelper.icc @@ -13,6 +13,7 @@ //////////////////////////////////////////////////////////////// #include <QTimer> +#include "VP1Base/VP1Msg.h" //____________________________________________________________________ template <class objectT> @@ -39,7 +40,7 @@ inline void VisibleObjectToMaterialHelper<objectT>::setState( const objectT* t, message("setState WARNING: Called with null pointer"); return; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("setState Called"); typename std::map<const objectT*,SoMaterial*>::iterator it = m_visobjects.find(t); diff --git a/graphics/VP1/VP1Base/src/IVP13DStandardChannelWidget.cxx b/graphics/VP1/VP1Base/src/IVP13DStandardChannelWidget.cxx index 327ea8befd68e656332e2f5400ea1125c37663c2..32da32c5ca33be49675bae6ea4f10bfebb22abd8 100644 --- a/graphics/VP1/VP1Base/src/IVP13DStandardChannelWidget.cxx +++ b/graphics/VP1/VP1Base/src/IVP13DStandardChannelWidget.cxx @@ -294,7 +294,12 @@ void IVP13DStandardChannelWidget::Imp::autoSnapshot() unsigned long long eventnumber(0); channel->getRunEvtNumber(runnumber,eventnumber); - QString snapshotDirName = VP1QtUtils::environmentVariableValue("VP1_SCREENSHOTS_DIR"); + #if defined BUILDVP1LIGHT + QString snapshotDirName = VP1QtUtils::expertSettingValue("general","ExpertSettings/VP1_SCREENSHOTS_DIR"); + #else + QString snapshotDirName = VP1QtUtils::environmentVariableValue("VP1_SCREENSHOTS_DIR"); + #endif + QFileInfo snapshotDir(snapshotDirName); if(!snapshotDir.exists()||!snapshotDir.isDir()||!snapshotDir.isReadable()||!snapshotDir.isWritable()) { channel->message("The directory for storing VP1 snapshots "+snapshotDirName+" either does not exist or is not writable"); diff --git a/graphics/VP1/VP1Base/src/IVP13DSystemSimple.cxx b/graphics/VP1/VP1Base/src/IVP13DSystemSimple.cxx index a0e36b42ab5c3728f4f71f11018fadd595e300bf..5283ac3ad8e0b9094682384b9d7a7187c77099eb 100644 --- a/graphics/VP1/VP1Base/src/IVP13DSystemSimple.cxx +++ b/graphics/VP1/VP1Base/src/IVP13DSystemSimple.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ ///////////////////////////////////////////////////////////// @@ -14,6 +14,7 @@ #include "VP1Base/IVP13DSystemSimple.h" #include "VP1Base/SoCooperativeSelection.h" +#include "VP1Base/VP1Msg.h" #include "Inventor/SoPath.h" #include "Inventor/nodes/SoSeparator.h" #include <iostream> @@ -91,12 +92,15 @@ void IVP13DSystemSimple::ensureBuildController() if (m_d->controllerBuilt) return; m_d->controllerBuilt=true; - - messageVerbose("IVP13DSystemSimple build controller"); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple build controller"); + } QWidget * controller = buildController(); if (controller) registerController(controller); - messageVerbose("IVP13DSystemSimple controller was = "+str(controller)); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple controller was = "+str(controller)); + } } //___________________________________________________________________________________________________________ @@ -129,7 +133,9 @@ SoSeparator * IVP13DSystemSimple::getSceneGraph() const //___________________________________________________________ void IVP13DSystemSimple::create(StoreGateSvc* /*detstore*/) { - messageVerbose("IVP13DSystemSimple create"); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple create"); + } assert(!m_d->wasrefreshed); assert(!m_d->wascreated); ensureBuildController();//TODO: Move to refresh. @@ -144,7 +150,9 @@ void IVP13DSystemSimple::refresh(StoreGateSvc* sg) assert(!m_d->wasrefreshed); if (m_d->first) { - messageVerbose("IVP13DSystemSimple first refresh - so calling create methods (i.e. delayed create)."); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple first refresh - so calling create methods (i.e. delayed create)."); + } systemcreate(detectorStore()); m_d->first = false; m_d->root->removeChild(m_d->rootR); @@ -165,16 +173,19 @@ void IVP13DSystemSimple::refresh(StoreGateSvc* sg) //___________________________________________________________ void IVP13DSystemSimple::erase() { - messageVerbose("IVP13DSystemSimple::erase() start"); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple::erase() start"); + } assert(m_d->wascreated); assert(m_d->wasrefreshed); bool saveE = m_d->rootE->enableNotify(false); systemerase(); - messageVerbose("IVP13DSystemSimple::erase() Removing all event objects from scene"); - if (verbose()) + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple::erase() Removing all event objects from scene"); warnOnDisabledNotifications(); + } m_d->rootE->removeAllChildren(); if (saveE) { @@ -183,13 +194,18 @@ void IVP13DSystemSimple::erase() } m_d->wasrefreshed=false; - messageVerbose("IVP13DSystemSimple::erase() end"); + if(VP1Msg::verbose()){ + messageVerbose("IVP13DSystemSimple::erase() end"); + } } //___________________________________________________________ void IVP13DSystemSimple::uncreate() { - messageDebug("uncreate()..."); + + if(VP1Msg::verbose()){ + messageDebug("uncreate()..."); + } assert(m_d->wascreated); assert(!m_d->wasrefreshed); diff --git a/graphics/VP1/VP1Base/src/IVP1System.cxx b/graphics/VP1/VP1Base/src/IVP1System.cxx index fec29757367c58a3e2c7312607f2623c5e21bca0..2537ead3394ea2e5f24de98b77c0be8a0e107991 100644 --- a/graphics/VP1/VP1Base/src/IVP1System.cxx +++ b/graphics/VP1/VP1Base/src/IVP1System.cxx @@ -25,7 +25,7 @@ #include <cassert> #include <iostream> -bool IVP1System::s_vp1verbose = VP1QtUtils::environmentVariableIsOn("VP1_VERBOSE_OUTPUT"); +bool IVP1System::s_vp1verbose = VP1QtUtils::environmentVariableIsOn("VP1_VERBOSE_OUTPUT"); // TODO: is this used at all? class IVP1System::Imp { public: @@ -68,16 +68,19 @@ const QString& IVP1System::contact_info() const IVP1System::IVP1System(const QString & n, const QString & i, const QString & c) : m_d(new Imp(n,i,c)) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("IVP1System()"); + } setObjectName("IVP1System:"+n); + } //________________________________________________________ IVP1System::~IVP1System() { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("IVP1System() Destructor. Start..."); + } assert(m_d->state==UNCREATED||m_d->state==CONSTRUCTED); assert(!m_d->controller); @@ -92,7 +95,7 @@ IVP1System::~IVP1System() //_______________________________________________________ void IVP1System::setChannel(IVP1ChannelWidget*cw) { - if (verbose()) { + if (VP1Msg::verbose()) { messageVerbose("setChannel "); messageVerbose("setChannel m_d->state==CONSTRUCTED = "+QString(m_d->state==CONSTRUCTED?"true":"false")); messageVerbose("setChannel cw!=0 = "+QString(cw!=0?"true":"false")); @@ -112,8 +115,9 @@ bool IVP1System::isRefreshing() //________________________________________________________ void IVP1System::setRefreshing(const bool& b) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("setRefreshing() called with b="+QString(b?"true":"false")); + } if (b) { assert(m_d->state==ERASED); } else { @@ -189,7 +193,7 @@ void IVP1System::setActiveState(const ActiveState&s,const bool& donttriggererase //________________________________________________________ void IVP1System::uncreate() { - if (verbose()) { + if (VP1Msg::verbose()) { messageVerbose("uncreate() base implementation"); messageVerbose("registerController m_d->state==ERASED = "+QString(m_d->state==ERASED?"true":"false")); } @@ -198,7 +202,7 @@ void IVP1System::uncreate() //________________________________________________________ QWidget * IVP1System::controllerWidget() { - if (verbose()) { + if (VP1Msg::verbose()) { messageVerbose("controllerWidget()"); messageVerbose("registerController m_d->state==ERASED = "+QString(m_d->state==ERASED?"true":"false")); messageVerbose("registerController m_d->state==REFRESHED = "+QString(m_d->state==REFRESHED?"true":"false")); @@ -210,8 +214,9 @@ QWidget * IVP1System::controllerWidget() { //_______________________________________________________ void IVP1System::deleteController() { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("deleteController()"); + } if (m_d->controller) m_d->controller->deleteLater(); m_d->controller = 0; @@ -220,7 +225,7 @@ void IVP1System::deleteController() //________________________________________________________ void IVP1System::registerController(QWidget*w) { - if (verbose()) { + if (VP1Msg::verbose()) { messageVerbose("registerController "); messageVerbose("registerController m_d->canregistercontroller = "+QString(m_d->canregistercontroller?"true":"false")); messageVerbose("registerController m_d->state==CONSTRUCTED = "+QString(m_d->state==CONSTRUCTED?"true":"false")); @@ -271,8 +276,9 @@ void IVP1System::updateGUI() { //________________________________________________________ IVP1ChannelWidget * IVP1System::channel() const { - if (verbose()&&!m_d->channel) + if (VP1Msg::verbose()&&!m_d->channel){ messageVerbose("WARNING channel() returning NULL"); + } assert(m_d->channel); return m_d->channel; } @@ -280,23 +286,26 @@ IVP1ChannelWidget * IVP1System::channel() const //_______________________________________________________ void IVP1System::setCanRegisterController(const bool&c) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("setCanRegisterController called with"+QString(c?"true":"false")); + } m_d->canregistercontroller=c; } //_______________________________________________________ QByteArray IVP1System::saveState() { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("base saveState called [IVP1System]"); + } return QByteArray(); } //_______________________________________________________ void IVP1System::restoreFromState(QByteArray ba) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("base restoreFromState called"); + } if (!ba.isEmpty()) message("Error in IVP1System::restoreFromState: Received non-empty saved state."); } @@ -328,10 +337,12 @@ IToolSvc * IVP1System::toolSvc() const //_______________________________________________________ void IVP1System::message(const QString& str) const { - if (receivers(SIGNAL(sysmessage(QString))) > 0) + if (receivers(SIGNAL(sysmessage(QString))) > 0){ sysmessage(str); - else + } + else{ std::cout<<VP1Msg::prefix_msg()<<" ["<<m_d->name.toStdString()<<"]: "<<str.toStdString()<<std::endl; + } } //_______________________________________________________ @@ -343,7 +354,7 @@ void IVP1System::messageDebug(const QString& str) const //_______________________________________________________ void IVP1System::messageVerbose(const QString& str) const { - if (verbose()) + if (VP1Msg::verbose()) std::cout<<VP1Msg::prefix_verbose()<<" ["<<m_d->name.toStdString()<<"]: "<<str.toStdString()<<std::endl; } @@ -375,7 +386,7 @@ void IVP1System::messageDebug(const QStringList& l, const QString& addtoend ) co //____________________________________________________________________ void IVP1System::messageVerbose(const QStringList& l, const QString& addtoend ) const { - if (!verbose()) + if (!VP1Msg::verbose()) return; if (addtoend.isEmpty()) { foreach(QString s, l) @@ -421,7 +432,7 @@ void IVP1System::messageDebug(const QString& addtostart, const QStringList& l, c //____________________________________________________________________ void IVP1System::messageVerbose(const QString& addtostart, const QStringList& l, const QString& addtoend ) const { - if (!verbose()) + if (!VP1Msg::verbose()) return; if (addtostart.isEmpty()) { messageVerbose(l,addtoend); @@ -435,3 +446,52 @@ void IVP1System::messageVerbose(const QString& addtostart, const QStringList& l, messageVerbose(addtostart+s+addtoend); } } + +#ifdef BUILDVP1LIGHT +//____________________________________________________________________ +xAOD::TEvent* IVP1System::getEvent(){ + return m_event; +} + +void IVP1System::setEvent( xAOD::TEvent* event ){ + m_event = event; +} + +//____________________________________________________________________ +QStringList IVP1System::getObjectList(xAOD::Type::ObjectType type){ + if( type == xAOD::Type::Vertex ) { + + message("(((((((((())))))))))))))))"); + message(m_list[0]); + return m_list[0]; + } + else if ( type == xAOD::Type::Other ) { + return m_list[1]; + } + else if ( type == xAOD::Type::Jet ){ + return m_list[2]; + } + else if ( type == xAOD::Type::CaloCluster ) { + return m_list[3]; + } + else if ( type == xAOD::Type::TrackParticle ) { + return m_list[4]; + } + else if ( type == xAOD::Type::Muon ) { + return m_list[5]; + } + else if ( type == xAOD::Type::Electron ) { + return m_list[6]; + } + else { + message("Unknown xAOD type requested"); + return QStringList {}; + } +} + +void IVP1System::setObjectList(QList<QStringList> list){ + m_list = list; +} + + +#endif // BUILDVP1LIGHT diff --git a/graphics/VP1/VP1Base/src/PhiSectionWidget.cxx b/graphics/VP1/VP1Base/src/PhiSectionWidget.cxx index e635e5d125d40b6226eea282183979d99465c5d2..9fbff1d81051e0ddfb3da4e1a7a455d76bb5d7cb 100644 --- a/graphics/VP1/VP1Base/src/PhiSectionWidget.cxx +++ b/graphics/VP1/VP1Base/src/PhiSectionWidget.cxx @@ -96,7 +96,9 @@ PhiSectionWidget::PhiSectionWidget(QWidget * parent,IVP1System * sys) VP1HelperClassBase(sys,"PhiSectionWidget"), m_d(new Imp) { - messageVerbose("PhiSectionWidget constr"); + if(VP1Msg::verbose()){ + messageVerbose("PhiSectionWidget constr"); + } m_d->theclass = this; m_d->popup_menu = 0; @@ -149,11 +151,15 @@ PhiSectionWidget::~PhiSectionWidget() //____________________________________________________________________ void PhiSectionWidget::setNumberOfSectors(int nsectors,bool forceAllEnabled) { - messageDebug("setNumberOfSectors()"); + if(VP1Msg::debug()){ + messageDebug("setNumberOfSectors()"); + } if (nsectors<4||nsectors>99) { - messageDebug("nsectors<4||nsectors>99. Returning."); + if(VP1Msg::debug()){ + messageDebug("nsectors<4||nsectors>99. Returning."); + } return; } @@ -169,12 +175,16 @@ void PhiSectionWidget::setNumberOfSectors(int nsectors,bool forceAllEnabled) } nsectors = n>0 ? n : m_d->allowedNSectors.back(); } else if (!m_d->sectorstatus.isEmpty() && nsectors==static_cast<int>(m_d->sectorstatus.count())) { - messageDebug("!sectorstatus.isEmpty() && nsectors==sectorstatus.count(). Returning..."); + if(VP1Msg::debug()){ + messageDebug("!sectorstatus.isEmpty() && nsectors==sectorstatus.count(). Returning..."); + } return; } if ( m_d->sectorstatus.isEmpty() ) { - messageDebug("m_d->sectorstatus is Empty."); + if(VP1Msg::debug()){ + messageDebug("m_d->sectorstatus is Empty."); + } } // check if sectors have already been defined @@ -212,7 +222,9 @@ void PhiSectionWidget::setNumberOfSectors(int nsectors,bool forceAllEnabled) m_d->checkForChanges(); if ( m_d->sectorstatus.isEmpty() ) { - messageDebug("WARNING. m_d->sectorstatus is still Empty..."); + if(VP1Msg::debug()){ + messageDebug("WARNING. m_d->sectorstatus is still Empty..."); + } } } @@ -475,7 +487,9 @@ void PhiSectionWidget::Imp::wrap(QList<VP1Interval>& l) //____________________________________________________________________ QList<VP1Interval> PhiSectionWidget::Imp::enabledPhiRangesNoCache(const QVector<bool>& secstatus, bool& allOn, bool& allOff) const { - theclass->messageVerbose("enabledPhiRangesNoCache()"); + if(VP1Msg::verbose()){ + theclass->messageVerbose("enabledPhiRangesNoCache()"); + } QList<VP1Interval> l; allOn = true; allOff = true; @@ -483,7 +497,9 @@ QList<VP1Interval> PhiSectionWidget::Imp::enabledPhiRangesNoCache(const QVector< const unsigned int n = secstatus.count(); const double dphi = (2*M_PI)/n; - qDebug() << "n: " << n << " - dphi:" << dphi; + if(VP1Msg::debug()){ + qDebug() << "n: " << n << " - dphi:" << dphi; + } bool open(false); double tmp(-999); @@ -510,7 +526,9 @@ QList<VP1Interval> PhiSectionWidget::Imp::enabledPhiRangesNoCache(const QVector< l << VP1Interval(tmp,(2*M_PI)); wrap(l); - theclass->messageDebug("exiting enabledPhiRangesNoCache()..."); + if(VP1Msg::debug()){ + theclass->messageDebug("exiting enabledPhiRangesNoCache()..."); + } return l; } @@ -519,11 +537,15 @@ QList<VP1Interval> PhiSectionWidget::Imp::enabledPhiRangesNoCache(const QVector< //____________________________________________________________________ QList<VP1Interval> PhiSectionWidget::enabledPhiRanges() const { - messageDebug("enabledPhiRanges()"); + if(VP1Msg::debug()){ + messageDebug("enabledPhiRanges()"); + } if (!m_d->cacheValid) { - messageDebug("Cache not valid. Checking for changes..."); - m_d->checkForChanges(); + if(VP1Msg::debug()){ + messageDebug("Cache not valid. Checking for changes..."); + } + m_d->checkForChanges(); } return m_d->cachedRanges; } @@ -531,7 +553,9 @@ QList<VP1Interval> PhiSectionWidget::enabledPhiRanges() const //____________________________________________________________________ QList<VP1Interval> PhiSectionWidget::enabledPhiRanges(double phi_min,double phi_max) const { - messageDebug("enabledPhiRanges(double phi_min,double phi_max)"); + if(VP1Msg::debug()){ + messageDebug("enabledPhiRanges(double phi_min,double phi_max)"); + } if (phi_min>=phi_max) return QList<VP1Interval>(); @@ -603,7 +627,9 @@ QString PhiSectionWidget::enabledRangesToString() const //____________________________________________________________________ void PhiSectionWidget::Imp::checkForChanges() { - theclass->messageDebug("checkForChanges()"); + if(VP1Msg::debug()){ + theclass->messageDebug("checkForChanges()"); + } //Ensure caches are updated, and emit signal in case of any change: cacheValid = true; @@ -615,7 +641,7 @@ void PhiSectionWidget::Imp::checkForChanges() updateColors(); cachedRanges = r; - if (theclass->verbose()) { + if(VP1Msg::verbose()){ QString s; for(int i=0;i<r.count();++i) s+= r.at(i).toString()+(i==r.count()-1?"":", "); @@ -698,7 +724,9 @@ QByteArray PhiSectionWidget::state() const //____________________________________________________________________ void PhiSectionWidget::setState(QByteArray ba) { - this->messageVerbose("setState()"); + if(VP1Msg::verbose()){ + this->messageVerbose("setState()"); + } // ===> Setup stream for getting the contents of the byteArray: QBuffer buffer(&ba); buffer.open(QIODevice::ReadOnly); @@ -780,16 +808,22 @@ void PhiSectionWidget::dragLeaveEvent ( QDragLeaveEvent * ) //____________________________________________________________________ void PhiSectionWidget::setAllowedNumberOfSectors(QList<int> allowedNSectors, bool allowCustom) { - messageVerbose("setAllowedNumberOfSectors()"); + if(VP1Msg::verbose()){ + messageVerbose("setAllowedNumberOfSectors()"); + } //Check validity: if (allowedNSectors.isEmpty()) { - messageVerbose("allowedNSectors empty. Returning."); + if(VP1Msg::verbose()){ + messageVerbose("allowedNSectors empty. Returning."); + } return; } foreach(int s, allowedNSectors) { if (s<4) { - messageVerbose("allowedNSectors s < 4. Returning."); + if(VP1Msg::verbose()){ + messageVerbose("allowedNSectors s < 4. Returning."); + } return; } } @@ -815,6 +849,8 @@ void PhiSectionWidget::setAllowedNumberOfSectors(QList<int> allowedNSectors, boo int checkA = m_d->sectorstatus.isEmpty(); int checkB = m_d->sectorstatus.count(); - messageDebug("check - sectorstatus.isEmpty? " + str(checkA + checkB) ); + if(VP1Msg::debug()){ + messageDebug("check - sectorstatus.isEmpty? " + str(checkA + checkB) ); + } } diff --git a/graphics/VP1/VP1Base/src/VP1Deserialise.cxx b/graphics/VP1/VP1Base/src/VP1Deserialise.cxx index 56673bf15d7fe24e69872198786c7396cfcca7c5..1e61e093332b36d5a6167351c4a95bd5800c899c 100644 --- a/graphics/VP1/VP1Base/src/VP1Deserialise.cxx +++ b/graphics/VP1/VP1Base/src/VP1Deserialise.cxx @@ -154,7 +154,9 @@ QDataStream * VP1Deserialise::stream() //____________________________________________________________________ void VP1Deserialise::restore( SoMaterial* m ) { - messageDebug("VP1Deserialise::restore(SoMaterial)"); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(SoMaterial)"); + } QByteArray ba(restoreByteArray()); if (!m||ba.isEmpty()) return; @@ -164,7 +166,9 @@ void VP1Deserialise::restore( SoMaterial* m ) //____________________________________________________________________ void VP1Deserialise::restore(VP1MaterialButton* mb) { - messageDebug("VP1Deserialise::restore(VP1MaterialButton)"); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1MaterialButton)"); + } m_d->handle(mb); SoMaterial * m(0); QList<SoMaterial*> mats = mb ? mb->handledMaterials() : QList<SoMaterial*>(); @@ -188,8 +192,10 @@ QColor VP1Deserialise::restoreColor() { QColor c; (*(m_d->state)) >> c; - messageDebug("VP1Deserialise::restore(QColor) - name: " + c.name()); - if (verbose()) + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QColor) - name: " + c.name()); + } + if (VP1Msg::verbose()) messageVerbose("Restoring color "+str(c)); return c; } @@ -197,7 +203,9 @@ QColor VP1Deserialise::restoreColor() //____________________________________________________________________ void VP1Deserialise::restore(VP1ColorSelectButton*cb) { - messageDebug("VP1Deserialise::restore(VP1ColorSelectButton) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1ColorSelectButton) - name: " + cb->objectName()); + } m_d->handle(cb); QColor c = restoreColor(); if (c.isValid()&&cb&&cb->color()!=c) { @@ -210,7 +218,9 @@ void VP1Deserialise::restore(VP1ColorSelectButton*cb) //____________________________________________________________________ void VP1Deserialise::restore(PhiSectionWidget* phi) { - messageDebug("VP1Deserialise::restore(PhiSectionWidget) - name: " + phi->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(PhiSectionWidget) - name: " + phi->objectName()); + } m_d->handle(phi); QByteArray ba(restoreByteArray()); if (phi&&ba != QByteArray()) { @@ -225,26 +235,33 @@ QByteArray VP1Deserialise::restoreByteArray() { QByteArray ba; (*(m_d->state)) >> ba; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Restoring byte array (length = "+QString::number(ba.count())+")"); + } return ba; } //____________________________________________________________________ void VP1Deserialise::restore(QCheckBox *cb ) { - messageDebug("VP1Deserialise::restore(QCheckBox) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QCheckBox) - name: " + cb->objectName()); + } m_d->handle(cb); bool b = restoreBool(); - messageDebug("bool b: "+QString::number(b)); - messageDebug("bool cb: "+QString::number( cb->isChecked() )); + if(VP1Msg::debug()){ + messageDebug("bool b: "+QString::number(b)); + messageDebug("bool cb: "+QString::number( cb->isChecked() )); + } if (cb->isChecked()!=b) { m_d->block(cb); - messageDebug("setting - checked: "+QString::number( b )); + if(VP1Msg::debug()){ + messageDebug("setting - checked: "+QString::number( b )); + } cb->setChecked(b); m_d->unblock(); } @@ -252,8 +269,10 @@ void VP1Deserialise::restore(QCheckBox *cb ) //____________________________________________________________________ void VP1Deserialise::restore(QGroupBox*gb) -{ - messageDebug("VP1Deserialise::restore(QGroupBox) - name: " + gb->objectName()); +{ + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QGroupBox) - name: " + gb->objectName()); + } if (!gb->isCheckable()) message("WARNING: Asked to handled GroupBox which is not checkable: "+gb->objectName()); m_d->handle(gb); @@ -268,7 +287,9 @@ void VP1Deserialise::restore(QGroupBox*gb) //____________________________________________________________________ void VP1Deserialise::restore(QComboBox *cb) { - messageDebug("VP1Deserialise::restore(QComboBox) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QComboBox) - name: " + cb->objectName()); + } m_d->handle(cb); QString t = restoreString(); if (t.isEmpty()) @@ -286,7 +307,9 @@ void VP1Deserialise::restore(QComboBox *cb) //____________________________________________________________________ void VP1Deserialise::restore(QLineEdit* le) { - messageDebug("VP1Deserialise::restore(QLineEdit) - name: " + le->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QLineEdit) - name: " + le->objectName()); + } m_d->handle(le); QString s = restoreString(); if (s!=le->text()) { @@ -299,7 +322,9 @@ void VP1Deserialise::restore(QLineEdit* le) //____________________________________________________________________ void VP1Deserialise::restore(QDoubleSpinBox *sb, const double& unit ) { - messageDebug("VP1Deserialise::restore(QDoubleSpinBox) - name: " + sb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QDoubleSpinBox) - name: " + sb->objectName()); + } m_d->handle(sb); double dbl = (unit == 1.0 ? restoreDouble() : restoreDouble()/unit); dbl = std:: max(std::min(dbl,sb->maximum()),sb->minimum()); @@ -313,7 +338,9 @@ void VP1Deserialise::restore(QDoubleSpinBox *sb, const double& unit ) //____________________________________________________________________ void VP1Deserialise::restore(QSpinBox *sb) { - messageDebug("VP1Deserialise::restore(QSpinBox) - name: " + sb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QSpinBox) - name: " + sb->objectName()); + } m_d->handle(sb); qint32 i = restoreInt(); i = std:: max(std::min(i,sb->maximum()),sb->minimum()); @@ -327,7 +354,9 @@ void VP1Deserialise::restore(QSpinBox *sb) //____________________________________________________________________ void VP1Deserialise::restore(QSlider *s) { - messageDebug("VP1Deserialise::restore(QSlider) - name: " + s->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QSlider) - name: " + s->objectName()); + } m_d->handle(s); qint32 i = restoreInt(); i = std:: max(std::min(i,s->maximum()),s->minimum()); @@ -341,7 +370,9 @@ void VP1Deserialise::restore(QSlider *s) //____________________________________________________________________ void VP1Deserialise::restore(QToolBox *tb) { - messageDebug("VP1Deserialise::restore(QToolBox) - name: " + tb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QToolBox) - name: " + tb->objectName()); + } m_d->handle(tb); qint32 i = restoreInt(); if (i>=0&&i<tb->count()&&i!=tb->currentIndex()) { @@ -354,7 +385,9 @@ void VP1Deserialise::restore(QToolBox *tb) //____________________________________________________________________ void VP1Deserialise::restoreByTitle(QToolBox *tb) { - messageDebug("VP1Deserialise::restore(QToolBox) - name: " + tb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QToolBox) - name: " + tb->objectName()); + } m_d->handle(tb); QString s = restoreString(); int itarget (-1); @@ -377,8 +410,9 @@ QString VP1Deserialise::restoreString() { QString t; (*(m_d->state)) >> t; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Restoring string "+t); + } return t; } //____________________________________________________________________ @@ -386,8 +420,9 @@ bool VP1Deserialise::restoreBool() { bool b; (*(m_d->state)) >> b; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Restoring bool "+str(b)); + } return b; } //____________________________________________________________________ @@ -395,8 +430,9 @@ double VP1Deserialise::restoreDouble() { double dbl; (*(m_d->state)) >> dbl; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Restoring double "+str(dbl)); + } return dbl; } @@ -405,8 +441,9 @@ qint32 VP1Deserialise::restoreInt() { qint32 i; (*(m_d->state)) >> i; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Restoring int "+str(i)); + } return i; } @@ -427,7 +464,9 @@ void VP1Deserialise::restore( QRadioButton * rb0, l << rb0 << rb1 << rb2 << rb3 << rb4 << rb5 << rb6 << rb7 << rb8 << rb9; for (qint32 i = 0; i < l.count(); ++i) { if (l.at(i)) { - messageDebug("VP1Deserialise::restore(QRadioButton) - name: " + l.at(i)->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(QRadioButton) - name: " + l.at(i)->objectName()); + } m_d->handle(l.at(i)); } } @@ -447,8 +486,10 @@ void VP1Deserialise::restore( QRadioButton * rb0, //____________________________________________________________________ void VP1Deserialise::restore(VP1CollectionWidget*cw) { - messageDebug("VP1Deserialise::restore(VP1CollectionWidget) - name: " + cw->objectName()); - messageDebug("VP1Deserialise::restore(VP1CollectionWidget)- start..."); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1CollectionWidget) - name: " + cw->objectName()); + messageDebug("VP1Deserialise::restore(VP1CollectionWidget)- start..."); + } m_d->handle(cw); ignoreWidget(cw);//To ignore all children of the collection widget. QByteArray ba(restoreByteArray()); @@ -465,14 +506,18 @@ void VP1Deserialise::restore(VP1CollectionWidget*cw) m_d->block(cw); cw->addStateInfo(cwstates,true/*overwrite existing*/); m_d->unblock(); - messageDebug("VP1Deserialise::restore(VP1CollectionWidget)- end."); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1CollectionWidget)- end."); + } } //____________________________________________________________________ void VP1Deserialise::restore(VP1CollectionSettingsButtonBase*w) { - messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase) - name: " + w->objectName()); - messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase)- start..."); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase) - name: " + w->objectName()); + messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase)- start..."); + } m_d->handle(w); ignoreWidget(w);//To ignore all children of the widget. @@ -482,7 +527,9 @@ void VP1Deserialise::restore(VP1CollectionSettingsButtonBase*w) w->restoreFromState(ba); m_d->unblock(); } - messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase)- end."); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1CollectionSettingsButtonBase)- end."); + } } ////____________________________________________________________________ //void VP1Deserialise::restore(JetCollectionSettingsButton*w) @@ -503,7 +550,9 @@ void VP1Deserialise::restore(VP1CollectionSettingsButtonBase*w) //____________________________________________________________________ void VP1Deserialise::restore(VP1EtaPhiCutWidget*w) { - messageDebug("VP1Deserialise::restore(VP1EtaPhiCutWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1EtaPhiCutWidget) - name: " + w->objectName()); + } m_d->handle(w); ignoreWidget(w);//To ignore all children of the widget. @@ -521,7 +570,9 @@ void VP1Deserialise::restore(VP1EtaPhiCutWidget*w) //____________________________________________________________________ void VP1Deserialise::restore(VP1DrawOptionsWidget*w) { - messageDebug("VP1Deserialise::restore(VP1DrawOptionsWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::restore(VP1DrawOptionsWidget) - name: " + w->objectName()); + } m_d->handle(w); ignoreWidget(w);//To ignore all children of the widget. @@ -538,8 +589,9 @@ void VP1Deserialise::ignoreBool() { bool b; (*(m_d->state)) >> b; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring bool "+str(b)); + } } //____________________________________________________________________ @@ -547,8 +599,9 @@ void VP1Deserialise::ignoreInt() { qint32 i; (*(m_d->state)) >> i; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring int "+str(i)); + } } //____________________________________________________________________ @@ -556,8 +609,9 @@ void VP1Deserialise::ignoreDouble() { double dbl; (*(m_d->state)) >> dbl; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring double "+str(dbl)); + } } //____________________________________________________________________ @@ -565,8 +619,9 @@ void VP1Deserialise::ignoreString() { QString t; (*(m_d->state)) >> t; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring string "+t); + } } //____________________________________________________________________ @@ -574,8 +629,9 @@ void VP1Deserialise::ignoreByteArray() { QByteArray ba; (*(m_d->state)) >> ba; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring byte array (length = "+QString::number(ba.count())+")"); + } } //____________________________________________________________________ @@ -583,14 +639,17 @@ void VP1Deserialise::ignoreObsoletePhiSectionWidgetState() { QPair<int,QList<int> > state; (*(m_d->state)) >> state; - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Ignoring obsolete phi section widget state"); + } } //____________________________________________________________________ void VP1Deserialise::ignoreWidget(QWidget*w) { - messageDebug("VP1Deserialise::ignoreWidget(QWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Deserialise::ignoreWidget(QWidget) - name: " + w->objectName()); + } if (w) m_d->ignoredWidgets.insert(w); } @@ -651,10 +710,12 @@ void VP1Deserialise::warnUnrestored(QObject* object) QWidget * wid = static_cast<QWidget*>(object); if (!m_d->handledWidgets.contains(wid)&&m_d->expectsPersistification(wid)) { QString s("WARNING Unrestored widget of type: "+QString(wid->metaObject()->className())+" and object name = "+wid->objectName()); - if (verbose()) - message(s); - else - messageDebug(s); + if (VP1Msg::verbose()){ + message(s); + } + if(VP1Msg::debug()){ + messageDebug(s); + } } } //Call recursively on all "children": diff --git a/graphics/VP1/VP1Base/src/VP1EtaPhiCutWidget.cxx b/graphics/VP1/VP1Base/src/VP1EtaPhiCutWidget.cxx index f642c9a205894dc24915d773c3c06464fe9fa7a0..eec72f0013ac78d05679747450a813627438dca6 100644 --- a/graphics/VP1/VP1Base/src/VP1EtaPhiCutWidget.cxx +++ b/graphics/VP1/VP1Base/src/VP1EtaPhiCutWidget.cxx @@ -66,7 +66,9 @@ VP1EtaPhiCutWidget::~VP1EtaPhiCutWidget() //____________________________________________________________________ VP1Interval VP1EtaPhiCutWidget::allowedEta() const { - messageVerbose("VP1EtaPhiCutWidget::allowedEta()"); + if(VP1Msg::verbose()){ + messageVerbose("VP1EtaPhiCutWidget::allowedEta()"); + } // if "eta cut" is not set: we return an interval ]-inf,inf[, so all objects will pass the internal eta cut if (!m_d->ui.checkBox_cut_etarange->isChecked()) { @@ -83,7 +85,9 @@ VP1Interval VP1EtaPhiCutWidget::allowedEta() const // FIXME: checkBox_etacut_excludeRange is not actually used now, check and fix! // if "Exclude Eta range" is selected, we set the "excludeInterval" flag in the instance of the VP1Interval class if (m_d->ui.checkBox_etacut_excludeRange) { - messageVerbose("excludeRange=true"); + if(VP1Msg::verbose()){ + messageVerbose("excludeRange=true"); + } return VP1Interval(min, max, true, true, true); } return VP1Interval( min, max );//fixme: closed interval?? Ckeck! @@ -156,8 +160,9 @@ void VP1EtaPhiCutWidget::possibleChange_allowedEta() if ( m_d->last_allowedEta == newAllowedEta ) return; m_d->last_allowedEta = newAllowedEta; - if (verbose()) + if(VP1Msg::verbose()){ messageVerbose("Emitting allowedEtaChanged("+newAllowedEta.toString()+")"); + } emit allowedEtaChanged(newAllowedEta); } @@ -168,7 +173,7 @@ void VP1EtaPhiCutWidget::possibleChange_allowedPhi() if ( m_d->last_allowedPhi == newAllowedPhi ) return; m_d->last_allowedPhi = newAllowedPhi; - if (verbose()) { + if(VP1Msg::verbose()){ QString s; for(int i=0;i<newAllowedPhi.count();++i) s+= newAllowedPhi.at(i).toString()+(i==newAllowedPhi.count()-1?"":", "); diff --git a/graphics/VP1/VP1Base/src/VP1ExaminerViewer.cxx b/graphics/VP1/VP1Base/src/VP1ExaminerViewer.cxx index 58c924a87fa8ef43348f20c818540bdcdd0a89e8..cdf5f25ef019fe4e0b58ee00c382111aba3becb6 100644 --- a/graphics/VP1/VP1Base/src/VP1ExaminerViewer.cxx +++ b/graphics/VP1/VP1Base/src/VP1ExaminerViewer.cxx @@ -1661,7 +1661,17 @@ void VP1ExaminerViewer::setAntialiasing(SbBool smoothing, int numPasses) // glDisable(GL_MULTISAMPLE); bool printWarning = false; - const char* env_aa = std::getenv("VP1_ADVANCED_ANTIALIASING"); + const char* env_aa; + #ifndef BUILDVP1LIGHT + env_aa = std::getenv("VP1_ADVANCED_ANTIALIASING"); + #else + bool antialiasingIsOn = VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_ADVANCED_ANTIALIASING"); + if(antialiasingIsOn){ + env_aa = "1"; + } else { + env_aa = "0"; + } + #endif if (env_aa != NULL) { std::string env_aa_string( env_aa ); if(env_aa_string == "1") { diff --git a/graphics/VP1/VP1Base/src/VP1HelperClassBase.cxx b/graphics/VP1/VP1Base/src/VP1HelperClassBase.cxx index d91b747aed7bf626df050a0f0ad1ad99d0a564d7..333df19faab0e53a49f4ca16d410371def020669 100644 --- a/graphics/VP1/VP1Base/src/VP1HelperClassBase.cxx +++ b/graphics/VP1/VP1Base/src/VP1HelperClassBase.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ @@ -28,7 +28,7 @@ static std::map<VP1HelperClassBase*,QString> vp1helperclassbase_instanceMap;//in VP1HelperClassBase::VP1HelperClassBase(IVP1System * sys, QString helpername) : m_helpername(helpername), m_system(sys) { - if (verbose()) { + if(VP1Msg::verbose()){ messageVerbose("base constructor ("+str(this)+")"+(m_system?" system = "+m_system->name():QString(""))); vp1helperclassbase_instanceMap[this] = (m_system?m_system->name():QString("")); } @@ -37,7 +37,7 @@ VP1HelperClassBase::VP1HelperClassBase(IVP1System * sys, QString helpername) //____________________________________________________________________ VP1HelperClassBase::~VP1HelperClassBase() { - if (verbose()) { + if(VP1Msg::verbose()){ messageVerbose("base destructor ("+str(this)+")"+(m_system?" system = "+m_system->name():QString(""))); std::map<VP1HelperClassBase*,QString>::iterator it = vp1helperclassbase_instanceMap.find(this); if (it!=vp1helperclassbase_instanceMap.end()) @@ -63,7 +63,9 @@ void VP1HelperClassBase::message( const QString& str ) const //____________________________________________________________________ void VP1HelperClassBase::messageDebug( const QString& str ) const -{ +{ + if (!VP1Msg::debug()) + return; std::string sysstring(m_system ? " in "+m_system->name().toStdString() : std::string("")); if (m_helpername.isEmpty()) { std::cout<<VP1Msg::prefix_debug()<<" [helper"<<sysstring<<"]: "<<str.toStdString()<<std::endl; @@ -75,7 +77,7 @@ void VP1HelperClassBase::messageDebug( const QString& str ) const //____________________________________________________________________ void VP1HelperClassBase::messageVerbose( const QString& str ) const { - if (!verbose()) + if (!VP1Msg::verbose()) return; std::string sysstring(m_system ? " in "+m_system->name().toStdString() : std::string("")); if (m_helpername.isEmpty()) { @@ -100,6 +102,8 @@ void VP1HelperClassBase::message(const QStringList& l, const QString& addtoend ) //____________________________________________________________________ void VP1HelperClassBase::messageDebug(const QStringList& l, const QString& addtoend ) const { + if (!VP1Msg::debug()) + return; if (addtoend.isEmpty()) { foreach(QString s, l) messageDebug(s); @@ -112,7 +116,7 @@ void VP1HelperClassBase::messageDebug(const QStringList& l, const QString& addto //____________________________________________________________________ void VP1HelperClassBase::messageVerbose(const QStringList& l, const QString& addtoend ) const { - if (!verbose()) + if (!VP1Msg::verbose()) return; if (addtoend.isEmpty()) { foreach(QString s, l) @@ -142,6 +146,8 @@ void VP1HelperClassBase::message( const QString& addtostart, const QStringList& //____________________________________________________________________ void VP1HelperClassBase::messageDebug(const QString& addtostart, const QStringList& l, const QString& addtoend ) const { + if (!VP1Msg::debug()) + return; if (addtostart.isEmpty()) { messageDebug(l,addtoend); return; @@ -158,7 +164,7 @@ void VP1HelperClassBase::messageDebug(const QString& addtostart, const QStringLi //____________________________________________________________________ void VP1HelperClassBase::messageVerbose(const QString& addtostart, const QStringList& l, const QString& addtoend ) const { - if (!verbose()) + if (!VP1Msg::verbose()) return; if (addtostart.isEmpty()) { messageVerbose(l,addtoend); @@ -191,6 +197,7 @@ void VP1HelperClassBase::warnUndeletedInstances() void VP1HelperClassBase::setSystemBasePointer(IVP1System*sys) { m_system = sys; - if (verbose()) + if (VP1Msg::verbose()){ vp1helperclassbase_instanceMap[this] = (m_system?m_system->name():QString("")); + } } diff --git a/graphics/VP1/VP1Base/src/VP1MaterialButton.cxx b/graphics/VP1/VP1Base/src/VP1MaterialButton.cxx index 37efa3e1c8f771f0833e382e15345728da9f3fac..929fb13c504f26a929984bcbc4c2f589e05bea6f 100644 --- a/graphics/VP1/VP1Base/src/VP1MaterialButton.cxx +++ b/graphics/VP1/VP1Base/src/VP1MaterialButton.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ @@ -201,7 +201,7 @@ void VP1MaterialButton::Imp::adaptGuiAndMaterialsToLastApplied() { switchModeBasedOnLastApplied(); - if (theclass->verbose()) { + if (VP1Msg::verbose()) { theclass->messageVerbose("Copied values from material: " "diffuse="+str(lastapplied_diffuse) +", ambient="+str(lastapplied_ambient) @@ -213,8 +213,9 @@ void VP1MaterialButton::Imp::adaptGuiAndMaterialsToLastApplied() } if (editwindow) { - if (theclass->verbose()) + if (VP1Msg::verbose()){ theclass->messageVerbose(" => and updating preview."); + } blockGuiSignals(true); editwindow_ui.colbutton_ambient->setColor(lastapplied_ambient); editwindow_ui.colbutton_diffuse->setColor(lastapplied_diffuse); @@ -307,7 +308,9 @@ void VP1MaterialButton::Imp::initEditWindow() { if (editwindow) return; - theclass->messageVerbose("Initialising material editor dialog"); + if(VP1Msg::verbose()){ + theclass->messageVerbose("Initialising material editor dialog"); + } editwindow = new QWidget(0,Qt::WindowStaysOnTopHint); editwindow_ui.setupUi(editwindow); editwindow_ui.colbutton_ambient->setColor(lastapplied_ambient); @@ -324,7 +327,13 @@ void VP1MaterialButton::Imp::initEditWindow() editwindow_ui.label_num_simple_brightness->setNum(lastapplied_brightness); editwindow_ui.colbutton_simple_colour->setColor(lastapplied_diffuse); - if (!VP1QtUtils::environmentVariableIsOn("VP1_DISALLOW_MULTIPLE_CHANNELS")) { + #if defined BUILDVP1LIGHT + bool checkDisallowMultipleChannels = VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DISALLOW_MULTIPLE_CHANNELS"); + #else + bool checkDisallowMultipleChannels = VP1QtUtils::environmentVariableIsOn("VP1_DISALLOW_MULTIPLE_CHANNELS"); + #endif + + if (!checkDisallowMultipleChannels) { SoSeparator * userroot = new SoSeparator; SoComplexity * complexity = new SoComplexity; complexity->value = 1.0; @@ -651,9 +660,12 @@ void VP1MaterialButton::setText ( const QString & s ) //____________________________________________________________________ void VP1MaterialButton::updateButton() { - if (objectName().isEmpty()) + if (objectName().isEmpty()){ setObjectName("VP1MaterialButton"); - messageVerbose("setColButtonProperties: color=" + str(m_d->lastapplied_diffuse)); + } + if(VP1Msg::verbose()){ + messageVerbose("setColButtonProperties: color=" + str(m_d->lastapplied_diffuse)); + } VP1ColorSelectButton::setColButtonProperties(this,m_d->lastapplied_diffuse,m_d->dim); } diff --git a/graphics/VP1/VP1Base/src/VP1Msg.cxx b/graphics/VP1/VP1Base/src/VP1Msg.cxx index 278e6b77a6595dd327a30c9dfffe57150caa0fe3..ea0c75cf7e7d013213f920148cec3369a633bcc5 100644 --- a/graphics/VP1/VP1Base/src/VP1Msg.cxx +++ b/graphics/VP1/VP1Base/src/VP1Msg.cxx @@ -17,7 +17,14 @@ #include "VP1Base/VP1QtUtils.h" #include <iostream> -bool VP1Msg::s_verbose = VP1QtUtils::environmentVariableIsOn("VP1_VERBOSE_OUTPUT"); +#ifndef BUILDVP1LIGHT //TODO: Merge the two mechanisms, specifically for VP1 + bool VP1Msg::m_verbose = VP1QtUtils::environmentVariableIsOn("VP1_VERBOSE_OUTPUT"); + bool VP1Msg::m_debug = VP1QtUtils::environmentVariableIsOn("VP1_DEBUG_OUTPUT"); +#endif +#ifdef BUILDVP1LIGHT + bool VP1Msg::m_verbose = VP1QtUtils::expertSettingIsSet("general", "ExpertSettings/VP1_VERBOSE_OUTPUT"); + bool VP1Msg::m_debug = VP1QtUtils::expertSettingIsSet("general", "ExpertSettings/VP1_DEBUG_OUTPUT"); +#endif //____________________________________________________________________ void VP1Msg::message( const QString& str, IVP1System*sys ) @@ -31,6 +38,9 @@ void VP1Msg::message( const QString& str, IVP1System*sys ) //____________________________________________________________________ void VP1Msg::messageDebug( const QString& str ) { + if (!debug()){ + return; + } std::cout << prefix_debug() << ": "<< str.toStdString()<<std::endl; } @@ -66,8 +76,9 @@ void VP1Msg::messageWarningAllRed( const QString& str ) //____________________________________________________________________ void VP1Msg::messageVerbose( const QString& str ) { - if (!verbose()) + if (!verbose()){ return; + } std::cout<<prefix_verbose()<<": "<<str.toStdString()<<std::endl; } @@ -85,7 +96,10 @@ void VP1Msg::message(const QStringList& l, const QString& addtoend, IVP1System*s //____________________________________________________________________ void VP1Msg::messageDebug(const QStringList& l, const QString& addtoend ) -{ +{ + if (!debug()){ + return; + } if (addtoend.isEmpty()) { foreach(QString s, l) messageDebug(s); @@ -98,8 +112,9 @@ void VP1Msg::messageDebug(const QStringList& l, const QString& addtoend ) //____________________________________________________________________ void VP1Msg::messageVerbose(const QStringList& l, const QString& addtoend ) { - if (!verbose()) + if (!verbose()){ return; + } if (addtoend.isEmpty()) { foreach(QString s, l) messageVerbose(s); @@ -129,6 +144,9 @@ void VP1Msg::message(const QString& addtostart, const QStringList& l, //____________________________________________________________________ void VP1Msg::messageDebug(const QString& addtostart, const QStringList& l, const QString& addtoend ) { + if (!debug()){ + return; + } if (addtostart.isEmpty()) { messageDebug(l,addtoend); return; @@ -145,8 +163,9 @@ void VP1Msg::messageDebug(const QString& addtostart, const QStringList& l, const //____________________________________________________________________ void VP1Msg::messageVerbose(const QString& addtostart, const QStringList& l, const QString& addtoend ) { - if (!verbose()) + if (!verbose()){ return; + } if (addtostart.isEmpty()) { messageVerbose(l,addtoend); return; @@ -160,3 +179,20 @@ void VP1Msg::messageVerbose(const QString& addtostart, const QStringList& l, con } } +#if defined BUILDVP1LIGHT +void VP1Msg::enableMsg(const QString& type, const QString& name){ + if( name == "ExpertSettings/VP1_VERBOSE_OUTPUT"){ + VP1Msg::m_verbose = VP1QtUtils::expertSettingIsSet(type, name); +} else { + VP1Msg::m_debug = VP1QtUtils::expertSettingIsSet(type, name); +} +} +#else +void VP1Msg::enableMsg(const QString& name){ + if( name == "VP1_VERBOSE_OUTPUT"){ + VP1Msg::m_verbose = VP1QtUtils::environmentVariableIsSet(name); + } else { + VP1Msg::m_debug = VP1QtUtils::environmentVariableIsSet(name); + } +} +#endif \ No newline at end of file diff --git a/graphics/VP1/VP1Base/src/VP1QtUtils.cxx b/graphics/VP1/VP1Base/src/VP1QtUtils.cxx index b04b18f3858c4c3851e26060bfa26139f649e9d1..501a835596f3acd3bbb7917a1b762fe8cccbd98f 100644 --- a/graphics/VP1/VP1Base/src/VP1QtUtils.cxx +++ b/graphics/VP1/VP1Base/src/VP1QtUtils.cxx @@ -3,20 +3,106 @@ */ -//////////////////////////////////////////////////////////////// -// // -// Implementation of class VP1QtUtils // -// // -// Author: Thomas H. Kittelmann (Thomas.Kittelmann@cern.ch) // -// Initial version: April 2008 // -// // -//////////////////////////////////////////////////////////////// +////////////////////////////////////////////////////////////////// +// // +// Implementation of class VP1QtUtils // +// // +// Author: Thomas H. Kittelmann (Thomas.Kittelmann@cern.ch) // +// Initial version: April 2008 // +// Update: October 2017 // +// Sebastian A. Merkt (sebastian.andreas.merkt@cern.ch // +// // +////////////////////////////////////////////////////////////////// #include "VP1Base/VP1QtUtils.h" #include "VP1Base/VP1Msg.h" #include <cstdlib>//For setenv/unsetenv #include <QImage> #include <QColor> +#include <QSettings> +#include <QCoreApplication> + + +//____________________________________________________________________ +bool VP1QtUtils::expertSettingIsSet(const QString& type, const QString& name) +{ + bool set; + if(type=="general"){ + QSettings generalSettings("ATLAS", "VP1Light"); + set = !generalSettings.value(name).toString().isEmpty(); + } else { + QSettings expertSettings(QCoreApplication::applicationDirPath()+"/../vp1.ini", QSettings::NativeFormat); + set = !expertSettings.value(name).toString().isEmpty(); + } + if (VP1Msg::verbose()) + VP1Msg::messageVerbose("VP1QtUtils::expertSettingIsSet called for variable '"+name+"'. Returning "+VP1Msg::str(set)); + return set; +} + +//____________________________________________________________________ +QString VP1QtUtils::expertSettingValue(const QString& type, const QString& name) +{ + QString env; + if(type=="general"){ + QSettings generalSettings("ATLAS", "VP1Light"); + env = generalSettings.value(name).toString(); + } else { + QSettings expertSettings(QCoreApplication::applicationDirPath()+"/../vp1.ini", QSettings::NativeFormat); + env = expertSettings.value(name).toString(); + } + QString val(env.isNull() ? "" : env); + if (VP1Msg::verbose()) + VP1Msg::messageVerbose("VP1QtUtils::expertSettingValue called for variable '"+name+"'. Returning '"+ val+"'."); + return val; +} + +//____________________________________________________________________ +bool VP1QtUtils::expertSettingIsOn(const QString& type, const QString& name) +{ + QString env; + if(type=="general"){ + QSettings generalSettings("ATLAS", "VP1Light"); + env = generalSettings.value(name).toString(); + } else { + QSettings expertSettings(QCoreApplication::applicationDirPath()+"/../vp1.ini", QSettings::NativeFormat); + env = expertSettings.value(name).toString(); + } + QString val(env.isNull() ? "" : env ); + bool ison = true; + if (val==""||val=="0") + ison = false; + else if (0==QString::compare(val,"false",Qt::CaseInsensitive)) + ison = false; + else if (0==QString::compare(val,"off",Qt::CaseInsensitive)) + ison = false; + else if (0==QString::compare(val,"no",Qt::CaseInsensitive)) + ison = false; + if (VP1Msg::verbose()) + VP1Msg::messageVerbose("VP1QtUtils::expertSettingIsOn called for variable '"+name+"'. Returning "+ VP1Msg::str(ison)+"."); + return ison; +} + +//____________________________________________________________________ +void VP1QtUtils::setExpertSetting(const QString& type, const QString& name, const QString& content ) +{ + if (name.isEmpty()) { + VP1Msg::messageDebug("VP1QtUtils::setEnvironmentVariable WARNING: called with empty variable name!"); + return; + } + + if (VP1Msg::verbose()) + VP1Msg::messageVerbose("VP1QtUtils::setEnvironmentVariable: Setting variable '"+name+"' to value '"+content+"'."); + + if(type=="general"){ + QSettings generalSettings("ATLAS", "VP1Light"); + generalSettings.setValue(name, content); + } else { + QSettings expertSettings(QCoreApplication::applicationDirPath()+"/../vp1.ini", QSettings::NativeFormat); + expertSettings.setValue(name, content); + } +} + + //____________________________________________________________________ bool VP1QtUtils::environmentVariableIsSet(const QString& name) diff --git a/graphics/VP1/VP1Base/src/VP1Serialise.cxx b/graphics/VP1/VP1Base/src/VP1Serialise.cxx index a3eeefb62c814109e7027eca5e3889f2ba198933..f89e80a2c524d0b10ec58b9deed63bec8b991b82 100644 --- a/graphics/VP1/VP1Base/src/VP1Serialise.cxx +++ b/graphics/VP1/VP1Base/src/VP1Serialise.cxx @@ -53,7 +53,9 @@ public: QSet<const QWidget*> ignoredWidgets; void handle(QWidget*w) { if (!w) { - theclass->messageDebug("VP1Serialize::handle() - Returning..."); + if(VP1Msg::debug()){ + theclass->messageDebug("VP1Serialize::handle() - Returning..."); + } return; } if (handledWidgets.contains(w)) @@ -132,7 +134,9 @@ QByteArray VP1Serialise::result() //____________________________________________________________________ void VP1Serialise::save(QCheckBox*cb) { - messageDebug("VP1Serialise::save(QCheckBox) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Serialise::save(QCheckBox) - name: " + cb->objectName()); + } m_d->handle(cb); save(cb->isChecked()); } @@ -140,7 +144,9 @@ void VP1Serialise::save(QCheckBox*cb) //____________________________________________________________________ void VP1Serialise::save(QGroupBox*gb) { - messageDebug("VP1Serialise::save(QGroupBox) - name: " + gb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Serialise::save(QGroupBox) - name: " + gb->objectName()); + } if (!gb->isCheckable()) message("WARNING: Asked to handled GroupBox which is not checkable: "+gb->objectName()); m_d->handle(gb); @@ -150,7 +156,9 @@ void VP1Serialise::save(QGroupBox*gb) //____________________________________________________________________ void VP1Serialise::save(QComboBox*cb) { - messageDebug("VP1Serialise::save(QComboBox) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("VP1Serialise::save(QComboBox) - name: " + cb->objectName()); + } m_d->handle(cb); save( cb->count() > 0 ? cb->currentText() : QString() ); } @@ -158,7 +166,9 @@ void VP1Serialise::save(QComboBox*cb) //____________________________________________________________________ void VP1Serialise::save(QLineEdit* le) { - messageDebug("\nVP1Serialise::save(QLineEdit) - name: " + le->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QLineEdit) - name: " + le->objectName()); + } m_d->handle(le); save( le->text() ); } @@ -166,7 +176,9 @@ void VP1Serialise::save(QLineEdit* le) //____________________________________________________________________ void VP1Serialise::save(QDoubleSpinBox*sb,const double& unit) { - messageDebug("\nVP1Serialise::save(QDoubleSpinBox) - name: " + sb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QDoubleSpinBox) - name: " + sb->objectName()); + } m_d->handle(sb); save(unit==1.0 ? sb->value() : sb->value() * unit ); } @@ -174,7 +186,9 @@ void VP1Serialise::save(QDoubleSpinBox*sb,const double& unit) //____________________________________________________________________ void VP1Serialise::save(QSpinBox*sb) { - messageDebug("\nVP1Serialise::save(QSpinBox) - name: " + sb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QSpinBox) - name: " + sb->objectName()); + } m_d->handle(sb); save(sb->value()); } @@ -182,7 +196,9 @@ void VP1Serialise::save(QSpinBox*sb) //____________________________________________________________________ void VP1Serialise::save(QSlider*s) { - messageDebug("\nVP1Serialise::save(QSlider) - name: " + s->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QSlider) - name: " + s->objectName()); + } m_d->handle(s); save(s->value()); } @@ -190,47 +206,54 @@ void VP1Serialise::save(QSlider*s) //____________________________________________________________________ void VP1Serialise::save(bool b) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving bool "+str(b)); + } (*m_d->state) << b; } //____________________________________________________________________ void VP1Serialise::save(qint32 i) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving int "+str(i)); + } (*m_d->state) << i; } //____________________________________________________________________ void VP1Serialise::save(const double& dbl) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving double "+str(dbl)); + } (*(m_d->state)) << dbl; } //____________________________________________________________________ void VP1Serialise::save(const QString& s) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving string "+s); + } (*(m_d->state)) << s; } //____________________________________________________________________ void VP1Serialise::save(const QByteArray& ba) { - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving byte array (length = "+QString::number(ba.count())+")"); + } (*(m_d->state)) << ba; } //____________________________________________________________________ void VP1Serialise::save(QToolBox*tb) { - messageDebug("\nVP1Serialise::save(QToolBox) - name: " + tb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QToolBox) - name: " + tb->objectName()); + } m_d->handle(tb); save( tb && tb->count() > 0 ? tb->currentIndex() : -1 ); } @@ -238,7 +261,9 @@ void VP1Serialise::save(QToolBox*tb) //____________________________________________________________________ void VP1Serialise::saveByTitle(QToolBox* tb) { - messageDebug("\nVP1Serialise::save(QToolBox) - name: " + tb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QToolBox) - name: " + tb->objectName()); + } m_d->handle(tb); int i = tb ? tb->currentIndex() : -1; save( i>=0 && i<tb->count() ? tb->itemText(i) : QString() ); @@ -247,7 +272,9 @@ void VP1Serialise::saveByTitle(QToolBox* tb) //____________________________________________________________________ void VP1Serialise::save(SoMaterial* m) { - messageDebug("\nVP1Serialise::save(SoMaterial)"); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(SoMaterial)"); + } if (!m) { save(QByteArray()); return; @@ -260,7 +287,9 @@ void VP1Serialise::save(SoMaterial* m) //____________________________________________________________________ void VP1Serialise::save(const VP1MaterialButton*mb) { - messageDebug("\nVP1Serialise::save(VP1MaterialButton) - name: " + mb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1MaterialButton) - name: " + mb->objectName()); + } m_d->handle(mb); QList<SoMaterial*> mats = mb ? mb->handledMaterials() : QList<SoMaterial*>(); save(mats.isEmpty() ? 0 : mats.at(0)); @@ -269,16 +298,21 @@ void VP1Serialise::save(const VP1MaterialButton*mb) //____________________________________________________________________ void VP1Serialise::save(const QColor& c) { - messageDebug("\nVP1Serialise::save(QColor) - name: " + c.name()); - if (verbose()) + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QColor) - name: " + c.name()); + } + if (VP1Msg::verbose()){ messageVerbose("Saving color "+str(c)); + } (*m_d->state) << c; } //____________________________________________________________________ void VP1Serialise::save(VP1ColorSelectButton* cb) { - messageDebug("\nVP1Serialise::save(VP1ColorSelectButton) - name: " + cb->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1ColorSelectButton) - name: " + cb->objectName()); + } m_d->handle(cb); save(cb ? cb->color() : QColor()); } @@ -286,10 +320,13 @@ void VP1Serialise::save(VP1ColorSelectButton* cb) //____________________________________________________________________ void VP1Serialise::save(const PhiSectionWidget*phi) { - messageDebug("\nVP1Serialise::save(PhiSectionWidget) - name: " + phi->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(PhiSectionWidget) - name: " + phi->objectName()); + } m_d->handle(phi); - if (verbose()) + if (VP1Msg::verbose()){ messageVerbose("Saving phisection widget state"); + } (*(m_d->state)) << (phi ? phi->state() : QByteArray()); } @@ -309,7 +346,9 @@ void VP1Serialise::save( QRadioButton * rb0, l << rb0 << rb1 << rb2 << rb3 << rb4 << rb5 << rb6 << rb7 << rb8 << rb9; for (qint32 i = 0; i < l.count(); ++i) { if (l.at(i)) { - messageDebug("\nVP1Serialise::save(QRadioButton) - name: " + l.at(i)->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(QRadioButton) - name: " + l.at(i)->objectName()); + } m_d->handle(l.at(i)); } } @@ -326,8 +365,10 @@ void VP1Serialise::save( QRadioButton * rb0, //____________________________________________________________________ void VP1Serialise::save(const VP1CollectionWidget*cw) { - messageDebug("\nVP1Serialise::save(VP1CollectionWidget) - name: " + cw->objectName()); - messageDebug("VP1Serialise::save(VP1CollectionWidget)- start..."); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1CollectionWidget) - name: " + cw->objectName()); + messageDebug("VP1Serialise::save(VP1CollectionWidget)- start..."); + } m_d->handle(cw); ignoreWidget(cw);//To ignore all children of the collection widget. QByteArray ba; @@ -338,7 +379,9 @@ void VP1Serialise::save(const VP1CollectionWidget*cw) out << cw->states(); buffer.close(); save(ba); - messageDebug("VP1Serialise::save(VP1CollectionWidget)- end."); + if(VP1Msg::debug()){ + messageDebug("VP1Serialise::save(VP1CollectionWidget)- end."); + } } ////____________________________________________________________________ @@ -351,19 +394,25 @@ void VP1Serialise::save(const VP1CollectionWidget*cw) //____________________________________________________________________ void VP1Serialise::save(const VP1CollectionSettingsButtonBase* jcb) { - messageDebug("\nVP1Serialise::save(VP1CollectionSettingsButtonBase) - name: " + jcb->objectName()); - messageDebug("VP1Serialise::save(VP1CollectionSettingsButtonBase)- start..."); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1CollectionSettingsButtonBase) - name: " + jcb->objectName()); + messageDebug("VP1Serialise::save(VP1CollectionSettingsButtonBase)- start..."); + } m_d->handle(jcb); ignoreWidget(jcb);//To ignore all children of the etaphicut widget. save(jcb ? jcb->saveState() : QByteArray()); - messageDebug("VP1Serialise::save(VP1CollectionSettingsButtonBase)- end."); + if(VP1Msg::debug()){ + messageDebug("VP1Serialise::save(VP1CollectionSettingsButtonBase)- end."); + } } //____________________________________________________________________ void VP1Serialise::save(const VP1EtaPhiCutWidget*w) { - messageDebug("\nVP1Serialise::save(VP1EtaPhiCutWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1EtaPhiCutWidget) - name: " + w->objectName()); + } m_d->handle(w); ignoreWidget(w);//To ignore all children of the etaphicut widget. save(w ? w->saveState() : QByteArray()); @@ -372,7 +421,9 @@ void VP1Serialise::save(const VP1EtaPhiCutWidget*w) //____________________________________________________________________ void VP1Serialise::save(const VP1DrawOptionsWidget*w) { - messageDebug("\nVP1Serialise::save(VP1DrawOptionsWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::save(VP1DrawOptionsWidget) - name: " + w->objectName()); + } m_d->handle(w); ignoreWidget(w);//To ignore all children of the draw options widget. save(w ? w->state() : QByteArray()); @@ -381,7 +432,9 @@ void VP1Serialise::save(const VP1DrawOptionsWidget*w) //____________________________________________________________________ void VP1Serialise::ignoreWidget(const QWidget*w) { - messageDebug("\nVP1Serialise::ignoreWidget(QWidget) - name: " + w->objectName()); + if(VP1Msg::debug()){ + messageDebug("\nVP1Serialise::ignoreWidget(QWidget) - name: " + w->objectName()); + } if (w) m_d->ignoredWidgets.insert(w); } @@ -442,10 +495,12 @@ void VP1Serialise::warnUnsaved(const QObject* object) const QWidget * wid = static_cast<const QWidget*>(object); if (!m_d->handledWidgets.contains(wid)&&m_d->expectsPersistification(wid)) { QString s("WARNING Unsaved widget of type: "+QString(wid->metaObject()->className())+" and object name = "+wid->objectName()); - if (verbose()) + if (VP1Msg::verbose()){ message(s); - else + } + if(VP1Msg::debug()){ messageDebug(s); + } } } //Call recursively on all "children": diff --git a/graphics/VP1/VP1Base/src/VP1Settings.cxx b/graphics/VP1/VP1Base/src/VP1Settings.cxx index 84c7f230c5beb986df09b10f6b892b1c8469af2a..e1c360962111a74def85beef0e3df194b1a1c8c8 100644 --- a/graphics/VP1/VP1Base/src/VP1Settings.cxx +++ b/graphics/VP1/VP1Base/src/VP1Settings.cxx @@ -23,7 +23,11 @@ QString VP1Settings::defaultFileSelectDirectory() { static QString thedir; if (thedir.isEmpty()) { - thedir = VP1QtUtils::environmentVariableValue("VP1_FILESELECTDIR"); + #if defined BUILDVP1LIGHT + thedir = VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1_FILESELECTDIR"); + #else + thedir = VP1QtUtils::environmentVariableValue("VP1_FILESELECTDIR"); + #endif if (thedir.isEmpty()||!QFileInfo(thedir).isDir()||!QFileInfo(thedir).exists()) thedir = QDir::currentPath(); } diff --git a/graphics/VP1/VP1Base/src/VP1SoMaterialMixer.cxx b/graphics/VP1/VP1Base/src/VP1SoMaterialMixer.cxx index c692b51b5f8fbd11e8c2bc6c8e14224bb7071561..9ee64ec00507657362b4f9c9f7e8ff61c370dd76 100644 --- a/graphics/VP1/VP1Base/src/VP1SoMaterialMixer.cxx +++ b/graphics/VP1/VP1Base/src/VP1SoMaterialMixer.cxx @@ -100,12 +100,16 @@ VP1SoMaterialMixer::~VP1SoMaterialMixer() //optimal. if (m_d->matlists2mixedmats.size()+m_d->matlists2mixedmats_weighted.size()>100) - messageDebug("WARNING: Watched more than 100 (" - +str(m_d->matlists2mixedmats.size()+m_d->matlists2mixedmats_weighted.size()) - + ") different material combinations. Try to use fewer combinations for better performance!"); + if(VP1Msg::debug()){ + messageDebug("WARNING: Watched more than 100 (" + +str(m_d->matlists2mixedmats.size()+m_d->matlists2mixedmats_weighted.size()) + + ") different material combinations. Try to use fewer combinations for better performance!"); + } if (m_d->mat2sensors.size()>1000) - messageDebug("WARNING: Monitored more than 1000 (" +str(m_d->mat2sensors.size())+ - ") different materials. Try to lower this number for better performance!"); + if(VP1Msg::debug()){ + messageDebug("WARNING: Monitored more than 1000 (" +str(m_d->mat2sensors.size())+ + ") different materials. Try to lower this number for better performance!"); + } delete m_d; } @@ -210,11 +214,13 @@ void VP1SoMaterialMixer::Imp::setMaterialFieldsAsAverageOfMatList(SoMaterial*mat if (save) { mat->enableNotify(true); mat->touch(); - if (theclass->verbose()) + if (VP1Msg::verbose()){ theclass->messageVerbose("Material ("+str(mat)+") updated and touched"); + } } else { - if (theclass->verbose()) + if (VP1Msg::verbose()){ theclass->messageVerbose("Material ("+str(mat)+") updated but notifications were off"); + } } } @@ -253,11 +259,13 @@ void VP1SoMaterialMixer::Imp::setMaterialFieldsAsAverageOfMatList(SoMaterial*mat if (save) { mat->enableNotify(true); mat->touch(); - if (theclass->verbose()) + if (VP1Msg::verbose()){ theclass->messageVerbose("Material ("+str(mat)+") updated and touched"); + } } else { - if (theclass->verbose()) + if (VP1Msg::verbose()){ theclass->messageVerbose("Material ("+str(mat)+") updated but notifications were off"); + } } } diff --git a/graphics/VP1/VP1Gui/CMakeLists.txt b/graphics/VP1/VP1Gui/CMakeLists.txt index 73e9f8a7757977441bab0ae883cfe477adf82d71..3a52f61b291c9ca248065f5d590857ab36b09f0d 100644 --- a/graphics/VP1/VP1Gui/CMakeLists.txt +++ b/graphics/VP1/VP1Gui/CMakeLists.txt @@ -10,6 +10,7 @@ atlas_subdir( VP1Gui ) # Declare the package's dependencies: atlas_depends_on_subdirs( + PUBLIC Event/xAOD/xAODBase PUBLIC graphics/VP1/VP1Base PUBLIC graphics/VP1/VP1UtilsBase ) @@ -33,5 +34,10 @@ atlas_add_library( VP1Gui VP1Gui/*.h src/*.h src/*.cxx src/*.qrc ${CMAKE_CURRENT_BINARY_DIR} LINK_LIBRARIES VP1Base Qt5::Core Qt5::OpenGL Qt5::Gui VP1UtilsBase Qt5::PrintSupport - PRIVATE_LINK_LIBRARIES ${COIN3D_LIBRARIES} ${SOQT_LIBRARIES} Qt5::Network ) - + PRIVATE_LINK_LIBRARIES ${COIN3D_LIBRARIES} ${SOQT_LIBRARIES} PathResolver xAODBase + xAODRootAccess xAODEventInfo xAODRootAccessInterfaces Qt5::Network ) + +# Install files from the package: +##atlas_install_scripts( share/* ) # installs into bin/ +atlas_install_runtime( share/* ) # install into share/ //TODO: check if we still need this! + diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1AODSelection.h b/graphics/VP1/VP1Gui/VP1Gui/VP1AODSelection.h new file mode 100644 index 0000000000000000000000000000000000000000..4c8bc0faefac1ddaab443c64841baad8d2360706 --- /dev/null +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1AODSelection.h @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Header file for class VP1AODSelection // +// // +// Description: Dialog for the selection of a xAOD file // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: November 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#ifndef VP1AODSELECTION_H +#define VP1AODSELECTION_H + +#include <QDialog> +#include <QComboBox> +#include <QPushButton> +#include <QDialogButtonBox> + +class VP1AODSelection : public QDialog +{ + Q_OBJECT +public: + explicit VP1AODSelection(QWidget *parent = 0); + +private slots: + //Open the file selection dialog + void on_browseButton_clicked(); + + //Check and Save the settings + void loadDatabase(); + +public slots: + +private: + QString m_fileName; + QComboBox *m_directoryComboBox; + QPushButton *m_browseButton; + QPushButton *m_openButton; + QPushButton *m_cancelButton; + QDialogButtonBox *m_buttonBox; + + //Animate the click + void animateFindClick(); + + //Method to create the drop down combobox + QComboBox *createComboBox(const QString &text = QString()); +}; + +#endif // VP1AODSELECTION_H diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1Authenticator.h b/graphics/VP1/VP1Gui/VP1Gui/VP1Authenticator.h index 7eb9caf063c7d8f9235afc18612aaff15de4ef80..6d5b5952911d1c8253fc00a0bc8209d33dc4f78f 100644 --- a/graphics/VP1/VP1Gui/VP1Gui/VP1Authenticator.h +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1Authenticator.h @@ -21,7 +21,9 @@ #include <QNetworkReply> + class QNetworkAccessManager; +class QSslError; class VP1Authenticator : public QDialog, public Ui::dlgAuthentication { diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1ExecutionScheduler.h b/graphics/VP1/VP1Gui/VP1Gui/VP1ExecutionScheduler.h index dac9c6a0f891ee97aae97870d32467e93de6f85e..6eaf3be18716e2b8b588caad70ae69b7fa0b9c5b 100644 --- a/graphics/VP1/VP1Gui/VP1Gui/VP1ExecutionScheduler.h +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1ExecutionScheduler.h @@ -25,6 +25,10 @@ #include <QObject> #include <QStringList> +#ifdef BUILDVP1LIGHT + #include <TTree.h> + #include "xAODBase/IParticle.h" +#endif // BUILDVP1LIGHT class IVP1System; @@ -94,10 +98,20 @@ public: QString saveSnaphsotToFile(IVP1System* s, bool batch = false); + + #if defined BUILDVP1LIGHT + void loadEvent(); + QString split(const std::string& input, const std::string& regex); + int getEvtNr(){ return m_evtNr; }; + void setEvtNr(int evtNr){ m_evtNr = evtNr; }; + int getTotEvtNr(){ return m_totEvtNr; }; + #endif // BUILDVP1LIGHT + signals: void refreshingStatusChanged(bool); + private: class Imp; Imp * m_d; @@ -105,6 +119,16 @@ private: void eraseSystem(IVP1System*); void actualUncreateAndDelete(IVP1ChannelWidget*); + #if defined BUILDVP1LIGHT + xAOD::TEvent* m_event; + ::TFile* m_ifile; + QList<QStringList> m_list; + int m_evtNr = 0; + int m_totEvtNr = -1; + bool m_goBackFlag = false; + bool firstlaunch = true; + #endif // BUILDVP1LIGHT + private slots: void processSystemForRefresh(); void updateProgressBarDuringRefresh(); @@ -116,6 +140,10 @@ private slots: void performCruise(); //OPVASK: void abortCruise(); //Start + + #if defined BUILDVP1LIGHT + void passEvent(IVP1System*); + #endif // BUILDVP1LIGHT }; #endif diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1ExpertSettings.h b/graphics/VP1/VP1Gui/VP1Gui/VP1ExpertSettings.h new file mode 100644 index 0000000000000000000000000000000000000000..af550ca00727346dc781fe70777de118581b3f55 --- /dev/null +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1ExpertSettings.h @@ -0,0 +1,131 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Header file for class VP1ExpertSettings // +// // +// Description: Additional VP1 settings // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#ifndef VP1EXPERTSETTINGS_H +#define VP1EXPERTSETTINGS_H + +#include <QDialog> +#include <QComboBox> +#include <QPushButton> +#include <QDialogButtonBox> +#include <QCheckBox> + +class VP1ExpertSettings : public QDialog +{ + Q_OBJECT +public: + explicit VP1ExpertSettings(QWidget *parent = 0); + +public slots: + void setPluginPath(const QString &path); + void setFileSelectDir(const QString &path); + void setScreenshotDir(const QString &path); + void setAuthLog(const QString &path); + +private: + QString m_pluginPath; + QString m_fileSelectDir; + QString m_screenshotDir; + QString m_authLog; + QDialogButtonBox* m_buttonBox; + QTabWidget* m_tabWidget; + QPushButton* m_okButton; + + bool checkBoxState(); + void closeEvent(QCloseEvent *event); + void keyPressEvent(QKeyEvent *event); + void setExpertSetting(const QString &type, const QString &name); +}; + + + + + + +class GeneralTab : public QWidget +{ + Q_OBJECT + +public: + explicit GeneralTab(QWidget *parent = 0); + +private slots: + #if defined BUILDVP1LIGHT + void setExpertSetting(const QString &type, const QString &name); + #else + void setExpertSetting(const QString &name); + #endif + void on_browseButton1_clicked(); + void slotScreenshotDirChanged(const QString &path); + +signals: + void signalScreenshotDirChanged(const QString &path); + +private: + QCheckBox* m_checkboxVerbose; + QCheckBox* m_checkboxDebug; + QCheckBox* m_checkboxDisallowMultipleChannels; + QCheckBox* m_checkboxDisplayMouseClicks; + QCheckBox* m_checkboxEnableAskOnClose; + QCheckBox* m_checkboxGuidesSphereInsteadOfCoordaxes; + QCheckBox* m_checkboxAntiAliasing; + QPushButton* m_browseButton1; + QLineEdit* m_lineEdit1; +}; + + + + + + +class AdvancedTab : public QWidget +{ + Q_OBJECT + +public: + explicit AdvancedTab(QWidget *parent = 0); + +private slots: + void on_browseButton1_clicked(); + void on_browseButton2_clicked(); + void on_browseButton3_clicked(); + void slotPluginPathChanged(const QString &path); + void slotFileSelectDirChanged(const QString &path); + void slotAuthLogChanged(const QString &path); + #if defined BUILDVP1LIGHT + void setExpertSetting(const QString &type, const QString &name); + #else + void setExpertSetting(const QString &name); + #endif + +signals: + void signalPluginPathChanged(const QString &path); + void signalFileSelectDirChanged(const QString &path); + void signalAuthLogChanged(const QString &path); + +private: + QPushButton* m_browseButton1; + QPushButton* m_browseButton2; + QPushButton* m_browseButton3; + QCheckBox* m_checkboxEnableInformOnEndOfJob; + QCheckBox* m_checkboxHardExitAtEnd; + QCheckBox* m_checkboxDevelShowAllCruiseAndEventControls; + QLineEdit* m_lineEdit1; + QLineEdit* m_lineEdit2; + QLineEdit* m_lineEdit3; +}; + + +#endif // VP1EXPERTSETTINGS_H diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1GeoDBSelection.h b/graphics/VP1/VP1Gui/VP1Gui/VP1GeoDBSelection.h new file mode 100644 index 0000000000000000000000000000000000000000..f07ef556dc1be9eb6feb01998f9032f0eca25212 --- /dev/null +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1GeoDBSelection.h @@ -0,0 +1,54 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Header file for class VP1GeoDBSelection // +// // +// Description: Dialog for the selection of a geometry database // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#ifndef VP1GEODBSELECTION_H +#define VP1GEODBSELECTION_H + +#include <QDialog> +#include <QComboBox> +#include <QPushButton> +#include <QDialogButtonBox> + +class VP1GeoDBSelection : public QDialog +{ + Q_OBJECT +public: + explicit VP1GeoDBSelection(QWidget *parent = 0); + +private slots: + //Open the file selection dialog + void on_browseButton_clicked(); + + //Check and Save the settings + void loadDatabase(); + +public slots: + +private: + QString m_fileName; + QComboBox *m_directoryComboBox; + QPushButton *m_browseButton; + QPushButton *m_openButton; + QPushButton *m_cancelButton; + QDialogButtonBox *m_buttonBox; + + //Animate the click + void animateFindClick(); + + //Method to create the drop down combobox + QComboBox *createComboBox(const QString &text = QString()); +}; + +#endif // VP1GEODBSELECTION_H diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1MainWindow.h b/graphics/VP1/VP1Gui/VP1Gui/VP1MainWindow.h index 7507310dac57ad7e71aba72aa2e10da4594963cb..5ec6b30accc5a990d1bbc8b0dae3fd44e8765d1f 100644 --- a/graphics/VP1/VP1Gui/VP1Gui/VP1MainWindow.h +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1MainWindow.h @@ -98,6 +98,9 @@ public: public slots: void loadPluginFile(QString filename); + #ifdef BUILDVP1LIGHT + void request_expertSettings(); + #endif void request_addEmptyTab(); void request_channelInformation(); void request_printChannel(); @@ -131,6 +134,10 @@ public slots: //For use when going to a new event (this updates system lists and quit()'s the app): void goToNextEvent(); + #if defined BUILDVP1LIGHT + void goToPreviousEvent(); + void chooseEvent(); + #endif public: void setRunEvtNumber(const int& runnumber, const unsigned long long& eventnumber, const unsigned& triggerType = 0, const unsigned& time = 0, const bool& printmessage = true ); bool mustQuit() const; @@ -220,6 +227,7 @@ protected: QMenu * m_menu_changeStyle; QMenu * m_menu_changeFontSize; QAction * m_actionAdd_empty_tab; + QAction * m_actionEnableExpertSettings; QAction * m_actionSave_current_tabs; QAction* m_action_addEventFile; QAction* m_action_openUsersGuide; diff --git a/graphics/VP1/VP1Gui/VP1Gui/VP1SelectEvent.h b/graphics/VP1/VP1Gui/VP1Gui/VP1SelectEvent.h new file mode 100644 index 0000000000000000000000000000000000000000..e62b0b551b08c4994f65ae59c167e40870cfa73d --- /dev/null +++ b/graphics/VP1/VP1Gui/VP1Gui/VP1SelectEvent.h @@ -0,0 +1,42 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Header file for class VP1SelectEvent // +// // +// Description: Dialog for the selection of a specific event in a file // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2018 // +// // +////////////////////////////////////////////////////////////////////////// + +#ifndef VP1SELECTEVENT_H +#define VP1SELECTEVENT_H + +#include <QDialog> +#include <QPushButton> +#include <QDialogButtonBox> +#include <QSpinBox> + +class VP1SelectEvent : public QDialog +{ + Q_OBJECT +public: + explicit VP1SelectEvent(int totEvtNr, int evtNr, QWidget *parent = 0); + +public slots: + +private: + void passEvtNr(); + void reject(); + + QPushButton* m_cancelButton; + QPushButton* m_openButton; + QDialogButtonBox* m_buttonBox; + QSpinBox* m_spinBox; +}; + +#endif // VP1SELECTEVENT_H diff --git a/graphics/VP1/VP1Gui/src/VP1AODSelection.cxx b/graphics/VP1/VP1Gui/src/VP1AODSelection.cxx new file mode 100644 index 0000000000000000000000000000000000000000..a0a72c42c8efb01fa6d2f00d8980fe6c82619c50 --- /dev/null +++ b/graphics/VP1/VP1Gui/src/VP1AODSelection.cxx @@ -0,0 +1,129 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Header file for class VP1AODSelection // +// // +// Description: Dialog for the selection of a xAOD file // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: November 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#include "VP1Gui/VP1AODSelection.h" + +#include <QPushButton> +#include <QGridLayout> +#include <QLabel> +#include <QComboBox> +#include <QFileInfo> + +#include <QtWidgets> + +VP1AODSelection::VP1AODSelection(QWidget *parent) : QDialog(parent) +{ + //Set default dialog size + int nWidth = 800; + int nHeight = 220; + if (parent != NULL) + setGeometry(parent->x() + parent->width()/2 - nWidth/2, + parent->y() + parent->height()/2 - nHeight/2, + nWidth, nHeight); + else + resize(nWidth, nHeight); + + //Browse button to select database + m_browseButton = new QPushButton(tr("&Browse..."), this); + connect(m_browseButton, &QAbstractButton::clicked, this, &VP1AODSelection::on_browseButton_clicked); + + //Buttonbox to set Open, Cancel buttons + m_buttonBox = new QDialogButtonBox(this); + m_openButton = m_buttonBox->addButton(tr("&Open"), QDialogButtonBox::AcceptRole); + m_cancelButton = m_buttonBox->addButton(tr("&Cancel"),QDialogButtonBox::RejectRole); + connect(m_openButton, &QPushButton::clicked, this, &VP1AODSelection::loadDatabase); + connect(m_cancelButton, &QPushButton::clicked, this, &VP1AODSelection::reject); + + //Open QSettings to store path do database + QSettings settings("ATLAS", "VP1Light"); + QString text; + + //If no xAOD file has been provided via command line argument, the "xaod/path" value is "" + if(settings.value("aod/path").toString()==""){ + m_openButton->setEnabled(false); + text = "(*)"; + } else { //If a xAOD file has been provided show it in the combobox + text = settings.value("aod/path").toString(); + } + //Create the combobox + m_directoryComboBox = createComboBox(text); + + //Create the main layout + QGridLayout *mainLayout = new QGridLayout(this); + mainLayout->addWidget(new QLabel(tr("Select AOD file:")), 0, 0); + mainLayout->addWidget(m_directoryComboBox, 1, 0, 1, 2); + mainLayout->addWidget(m_browseButton, 1, 4); + mainLayout->addWidget(m_buttonBox, 3, 4); + + m_browseButton->setMinimumWidth(200); + m_buttonBox->setMinimumWidth(200); + m_browseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_buttonBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); +} + +//Method to create the drop down combobox +QComboBox *VP1AODSelection::createComboBox(const QString &text) +{ + QComboBox *comboBox = new QComboBox; + comboBox->setMinimumWidth(600); + comboBox->setEditable(false); + comboBox->addItem(text); + comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + return comboBox; +} + +//Animate the click +void VP1AODSelection::animateFindClick() +{ + m_openButton->animateClick(); +} + +//Open the file selection dialog +void VP1AODSelection::on_browseButton_clicked() +{ + m_fileName = QFileDialog::getOpenFileName(this, + tr("Select AOD file"), QDir::currentPath(), + tr("AOD Files (*)")); + + // Add the selected file to the combobox + if (!m_fileName.isEmpty()) { + if (m_directoryComboBox->findText(m_fileName) == -1) + m_directoryComboBox->addItem(m_fileName); + m_directoryComboBox->setCurrentIndex(m_directoryComboBox->findText(m_fileName)); + + //When valid a database is selected, enable the Open button to confirm + m_openButton->setEnabled(true); + } + +} + +//Check and Save the settings +void VP1AODSelection::loadDatabase(){ + + //Save xAOD path to settings + QSettings settings("ATLAS", "VP1Light"); + settings.setValue("aod/path", m_directoryComboBox->itemText(m_directoryComboBox->currentIndex())); + + //If the selected xAOD does not exists, go back + if (!QFileInfo::exists(m_directoryComboBox->itemText(m_directoryComboBox->currentIndex()))){ + QMessageBox msgBox; + msgBox.setWindowTitle("Virtual Point 1"); + msgBox.setText("AOD file does not exist. Please choose another file."); + msgBox.exec(); + return; + } + VP1AODSelection::setResult(1); + VP1AODSelection::accept(); +} diff --git a/graphics/VP1/VP1Gui/src/VP1Authenticator.cxx b/graphics/VP1/VP1Gui/src/VP1Authenticator.cxx index 7f725f9300fe51a4a86a8730f74cd9f320d4100b..c435e3f81e83a015ee54344683171c98a89c6fde 100644 --- a/graphics/VP1/VP1Gui/src/VP1Authenticator.cxx +++ b/graphics/VP1/VP1Gui/src/VP1Authenticator.cxx @@ -54,7 +54,13 @@ VP1Authenticator::Imp::Imp(VP1Authenticator* theClass , m_fileInfoUrl(fileInfoUrl) , m_loginServer("login.cern.ch") { - if(VP1QtUtils::environmentVariableIsOn("VP1_AUTH_ENABLELOG")) { + #if defined BUILDVP1LIGHT + bool checkAuthEnabled = VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/VP1_AUTH_ENABLELOG"); + #else + bool checkAuthEnabled = VP1QtUtils::environmentVariableIsOn("VP1_AUTH_ENABLELOG"); + #endif + + if(checkAuthEnabled) { QString logname("vp1live-auth.log"); if(QFileInfo(logname).exists() && !QFile(logname).remove()) std::cerr << "VP1Authenticator ERROR: Unable to remove old logfile" << std::endl; diff --git a/graphics/VP1/VP1Gui/src/VP1ExecutionScheduler.cxx b/graphics/VP1/VP1Gui/src/VP1ExecutionScheduler.cxx index ec8fb3174470386cc27d4ff9cd7dda83650bf4cd..bdcd76b75f3f628e35fe63a2cebd1804559f42bc 100644 --- a/graphics/VP1/VP1Gui/src/VP1ExecutionScheduler.cxx +++ b/graphics/VP1/VP1Gui/src/VP1ExecutionScheduler.cxx @@ -68,6 +68,7 @@ #include <QSet> #include <QStringList> #include <QMessageBox> +#include <QCommandLineParser> #include <Inventor/C/errors/debugerror.h> #include <Inventor/Qt/SoQt.h> @@ -93,6 +94,39 @@ std::vector<std::string> qstringlistToVecString(QStringList list) } +#ifdef BUILDVP1LIGHT + //Qt + #include <QSettings> + + // XAOD + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" + #include "xAODRootAccess/TStore.h" + #include "xAODRootAccess/tools/Message.h" + #include "xAODRootAccess/TAuxStore.h" + #include "xAODCore/AuxContainerBase.h" + #include "xAODCore/tools/ReadStats.h" + #include "xAODCore/tools/IOStats.h" + + // // For testing + #include "xAODEventInfo/EventInfo.h" + #include <QDebug> + #include "xAODRootAccessInterfaces/TActiveEvent.h" + #include "xAODRootAccessInterfaces/TVirtualEvent.h" + #include <TTree.h> + #include <regex> + #include <QString> + + // ROOT include(s): + #include <TTree.h> + #include <TFile.h> + #include <TError.h> + + template <typename... Args> inline void unused(Args&&...) {} // to declare unused variables (see executeNewEvent() ). +#endif // BUILDVP1LIGHT + + + //___________________________________________________________________ class VP1ExecutionScheduler::Imp { public: @@ -243,7 +277,9 @@ VP1ExecutionScheduler::VP1ExecutionScheduler( QObject * parent, // check if 'batch mode' bool batchMode = VP1QtUtils::environmentVariableIsSet("VP1_BATCHMODE"); // ::getenv("VP1_BATCHMODE"); - qDebug() << "VP1ExecutionScheduler:: Do we run in 'batch' mode?" << batchMode; + if(VP1Msg::debug()){ + qDebug() << "VP1ExecutionScheduler:: Do we run in 'batch' mode?" << batchMode; + } if (batchMode) { VP1Msg::messageWarningAllRed("User has run VP1 in 'batch-mode', so the main window of the program will not be shown."); m_d->batchMode = true; @@ -270,7 +306,13 @@ VP1ExecutionScheduler::VP1ExecutionScheduler( QObject * parent, connect(m_d->cruisetimer, SIGNAL(timeout()), this, SLOT(performCruise())); m_d->cruisetab_waitingtoproceed=false; - if (VP1QtUtils::environmentVariableIsOn("VP1_DISPLAY_MOUSE_CLICKS")) { + #if defined BUILDVP1LIGHT + bool checkDisplayMouseClicks = VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DISPLAY_MOUSE_CLICKS"); + #else + bool checkDisplayMouseClicks = VP1QtUtils::environmentVariableIsOn("VP1_DISPLAY_MOUSE_CLICKS"); + #endif + + if (checkDisplayMouseClicks) { m_d->globalEventFilter = new Imp::GlobalEventFilter; qApp->installEventFilter(m_d->globalEventFilter); } else { @@ -363,7 +405,11 @@ VP1ExecutionScheduler* VP1ExecutionScheduler::init( StoreGateSvc* eventStore, new VP1QtApplication(argc, argv); } QCoreApplication::setOrganizationName("ATLAS"); - QCoreApplication::setApplicationName("VP1"); + #if defined BUILDVP1LIGHT + QCoreApplication::setApplicationName("VP1Light"); + #else + QCoreApplication::setApplicationName("VP1"); + #endif VP1AvailEvents * availEvents(0); if (!singleEventSource.isEmpty()&&!singleEventLocalTmpDir.isEmpty()) { @@ -455,8 +501,13 @@ VP1ExecutionScheduler* VP1ExecutionScheduler::init( StoreGateSvc* eventStore, //___________________________________________________________________ void VP1ExecutionScheduler::cleanup(VP1ExecutionScheduler*scheduler) { - if (VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_INFORM_ON_END_OF_JOB") - && ( !scheduler||!(scheduler->m_d->mainwindow->userRequestedExit()) ) ) + #if defined BUILDVP1LIGHT + bool checkEnableInformOnEndOfJob = VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/VP1_ENABLE_INFORM_ON_END_OF_JOB"); + #else + bool checkEnableInformOnEndOfJob = VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_INFORM_ON_END_OF_JOB"); + #endif + + if (checkEnableInformOnEndOfJob && ( !scheduler||!(scheduler->m_d->mainwindow->userRequestedExit()) ) ) QMessageBox::information(0, "End of job reached",Qt::convertFromPlainText("Job about to end.\n\nThis is most" " likely since there are no more available events to process."),QMessageBox::Ok,QMessageBox::Ok); @@ -473,8 +524,17 @@ void VP1ExecutionScheduler::cleanup(VP1ExecutionScheduler*scheduler) SoQt::done(); } + + const QString quickExitEnv("VP1_HARD_EXIT_AT_END"); - if (VP1QtUtils::environmentVariableIsOn(quickExitEnv)) { + + #if defined BUILDVP1LIGHT + bool checkHardExitAtEnd = VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/"+quickExitEnv); + #else + bool checkHardExitAtEnd = VP1QtUtils::environmentVariableIsOn(quickExitEnv); + #endif + + if (checkHardExitAtEnd) { VP1Msg::message("Hard job exit (unset "+quickExitEnv+" to disable this behaviour)."); exit(0); } @@ -529,7 +589,33 @@ bool VP1ExecutionScheduler::executeNewEvent(const int& runnumber, const unsigned m_d->nextRequestedEvent=""; +#if defined BUILDVP1LIGHT + unused(runnumber,eventnumber,triggerType,time); // silences the "unused parameter" warnings when building VP1Light. In this case, in fact, those variables will be used later in loadEvent(). + if ( !firstlaunch ) { + if ( (getEvtNr() >= 0) && (getEvtNr() < m_totEvtNr) ) { // If selected event number is available in file + loadEvent(); + //Pass the event to the AOD System + std::set<IVP1System *>::iterator itsys, itsysE = m_d->mainwindow->tabManager()->selectedChannelWidget()->systems().end(); + for (itsys = m_d->mainwindow->tabManager()->selectedChannelWidget()->systems().begin();itsys!=itsysE;++itsys) { + if((*itsys)->name()=="Analysis"){ + passEvent(*itsys); + } + } + } + else if ( (getEvtNr() < 0) && (getEvtNr() >= m_totEvtNr) ) { + QMessageBox msgBox; + msgBox.setWindowTitle("No more events"); + msgBox.setText("There are no more events in this file. Returning to previous event."); + msgBox.setIcon(QMessageBox::Icon::Information); + msgBox.exec(); + } + } + else{ + firstlaunch = false; + } +#else m_d->mainwindow->setRunEvtNumber(runnumber, eventnumber, triggerType, time, !m_d->skipEvent); +#endif m_d->goingtonextevent = false; m_d->calctimethisevent=0; @@ -676,10 +762,15 @@ void VP1ExecutionScheduler::channelCreated(IVP1ChannelWidget* cw) { std::set<IVP1System*>::const_iterator it, itE = cw->systems().end(); for (it=cw->systems().begin();it!=itE;++it) { + qInfo() << "System name:" << (*it)->name(); connect(*it,SIGNAL(inactiveSystemTurnedActive()),this,SLOT(startRefreshQueueIfAppropriate())); connect(*it,SIGNAL(needErase()),this,SLOT(systemNeedErase())); + #ifdef BUILDVP1LIGHT + connect(*it,SIGNAL(signalLoadEvent(IVP1System*)),this,SLOT(passEvent(IVP1System*))); + #endif // BUILDVP1LIGHT } startRefreshQueueIfAppropriate(); + } //___________________________________________________________________ @@ -1103,6 +1194,7 @@ bool VP1ExecutionScheduler::hasAllActiveSystemsRefreshed( IVP1ChannelWidget* cw i++; } + return true; } @@ -1278,3 +1370,126 @@ QStringList VP1ExecutionScheduler::userRequestedFiles() //Actually: Floating widgets from other tabs should get docked anyway when going FS-tab when in cruise-TAB mode... + +//___________________________________________________________________ +#ifdef BUILDVP1LIGHT +void VP1ExecutionScheduler::loadEvent(){ + // Get the name of the application: + const char* appName = "VP1Light"; + + // Initialize the environment: + if( !xAOD::Init( appName ).isSuccess() ) { + ::Error( appName, XAOD_MESSAGE( "Failed to execute xAOD::Init" ) ); + return; + } + + m_event = new xAOD::TEvent( xAOD::TEvent::kAthenaAccess ); + + // Get local xAOD and set valid xAOD path + QSettings settings("ATLAS", "VP1Light"); + std::string path = settings.value("aod/path").toString().toStdString(); + + // Open xAOD file and read it in + m_ifile = ::TFile::Open( path.c_str(), "READ" ); + if( ! m_ifile ) { + ::Error( appName, XAOD_MESSAGE( "File %s couldn't be opened..." ), + path.c_str() ); + return; + } + if( !m_event->readFrom( m_ifile ).isSuccess() ) { + ::Error( appName, XAOD_MESSAGE( "Failed to read from xAOD file %s" ), + path.c_str() ); + return; + } + + // Check if file is empty: + if( m_event->getEntry( 0 ) < 0 ) { + ::Error( appName, XAOD_MESSAGE( "Couldn't load entry 0 from file %s" ), + path.c_str() ); + return; + } + + //Load the current event + m_event->getEntry( m_evtNr ); + + // List for available collections + QStringList jetList; + QStringList vertexList; + QStringList otherList; + QStringList caloClusterList; + QStringList trackParticleList; + QStringList muonList; + QStringList electronList; + + + // // Loop over all entries in the CollectionTree + TTree* ct = (TTree*)m_ifile->Get("CollectionTree"); + m_totEvtNr = ct->GetEntriesFast(); + for (int i = 0; i<ct->GetListOfBranches()->GetEntries();i++){ + std::string className = ct->GetBranch(ct->GetListOfBranches()->At(i)->GetName())->GetClassName(); + + // Store collections in their respective QStringList + if(split(className,"_v[1-9]")=="DataVector<xAOD::Vertex>"){ + vertexList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="xAOD::MissingETContainer"){ + otherList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="DataVector<xAOD::Jet>"){ + jetList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="DataVector<xAOD::CaloCluster>"){ + caloClusterList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="DataVector<xAOD::TrackParticle>"){ + trackParticleList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="DataVector<xAOD::Muon>"){ + muonList << ct->GetListOfBranches()->At(i)->GetName(); + } + if(split(className,"_v[1-9]")=="DataVector<xAOD::Electron>"){ + electronList << ct->GetListOfBranches()->At(i)->GetName(); + } + } + + //Fill the collection lists + m_list.append(vertexList); + m_list.append(otherList); + m_list.append(jetList); + m_list.append(caloClusterList); + m_list.append(trackParticleList); + m_list.append(muonList); + m_list.append(electronList); + + // Get the event info: + const xAOD::EventInfo *eventInfo = nullptr; + if( !m_event->retrieve (eventInfo, "EventInfo").isSuccess() ) { + VP1Msg::messageWarningRed("Failed to retrieve EventInfo"); + return; + } + // Save Event info + m_d->mainwindow->setRunEvtNumber(eventInfo->runNumber(),eventInfo->eventNumber(),eventInfo->level1TriggerType(),eventInfo->timeStamp()); + + // Update the GUI event counter + QString currentEvt = "Event: " + QString::number(getEvtNr()+1) + "/" + QString::number(getTotEvtNr()); + m_d->mainwindow->pushButton_eventselect->setText(currentEvt); +} + +//____________________________________________________________________ +void VP1ExecutionScheduler::passEvent(IVP1System* sys){ + sys->setEvent(m_event); + sys->setObjectList(m_list); +} + +//____________________________________________________________________ +QString VP1ExecutionScheduler::split(const std::string& input, const std::string& regex) { + std::regex re(regex); + std::sregex_token_iterator first{input.begin(), input.end(), re, -1}, last; + std::vector<std::string> vec = {first, last}; + QStringList list; + for (unsigned int i=0;i<vec.size();i++){ + list << QString::fromStdString(vec[i]); + } + return list.join(""); +} +#endif // BUILDVP1LIGHT diff --git a/graphics/VP1/VP1Gui/src/VP1ExpertSettings.cxx b/graphics/VP1/VP1Gui/src/VP1ExpertSettings.cxx new file mode 100644 index 0000000000000000000000000000000000000000..dc2c4d24464bfdc301a1b0858f8c227150d71b16 --- /dev/null +++ b/graphics/VP1/VP1Gui/src/VP1ExpertSettings.cxx @@ -0,0 +1,551 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Source file for class VP1ExpertSettings // +// // +// Description: Additional VP1 settings // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#include "VP1Gui/VP1ExpertSettings.h" +#include "VP1Base/VP1QtUtils.h" +#include "VP1Base/VP1Msg.h" + +#include <QPushButton> +#include <QGridLayout> +#include <QLabel> +#include <QComboBox> +#include <QCheckBox> +#include <QDir> +#include <QKeyEvent> + +#include <QtWidgets> + + +template <typename... Args> inline void unused(Args&&...) {} // to declare variables as 'unused' + + + +VP1ExpertSettings::VP1ExpertSettings(QWidget *parent) : QDialog(parent) +{ + + m_tabWidget = new QTabWidget; + GeneralTab *generalTab = new GeneralTab(); + AdvancedTab *advancedTab = new AdvancedTab(); + m_tabWidget->addTab(generalTab, tr("Settings")); + connect(generalTab, &GeneralTab::signalScreenshotDirChanged, this, &VP1ExpertSettings::setScreenshotDir); + + #if defined BUILDVP1LIGHT + QString pluginPath=VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1PLUGINPATH"); + QString fileSelectDir=VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1_FILESELECTDIR"); + QString screenshotDir=VP1QtUtils::expertSettingValue("general","ExpertSettings/VP1_SCREENSHOTS_DIR"); + QString authLog=VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1_AUTH_ENABLELOG"); + + if(VP1QtUtils::expertSettingIsOn("general", "ExpertSettings/enableExpertSettings")){ + m_tabWidget->addTab(advancedTab, tr("Advanced")); + connect(advancedTab, &AdvancedTab::signalPluginPathChanged, this, &VP1ExpertSettings::setPluginPath); + connect(advancedTab, &AdvancedTab::signalFileSelectDirChanged, this, &VP1ExpertSettings::setFileSelectDir); + connect(advancedTab, &AdvancedTab::signalAuthLogChanged, this, &VP1ExpertSettings::setAuthLog); + } + #else + QString pluginPath=VP1QtUtils::environmentVariableValue("VP1PLUGINPATH"); + QString fileSelectDir=VP1QtUtils::environmentVariableValue("VP1_FILESELECTDIR"); + QString screenshotDir=VP1QtUtils::environmentVariableValue("VP1_SCREENSHOTS_DIR"); + QString authLog=VP1QtUtils::environmentVariableValue("VP1_AUTH_ENABLELOG"); + + // Always enable Advanced settings for VP1 + m_tabWidget->addTab(advancedTab, tr("Advanced")); + connect(advancedTab, &AdvancedTab::signalPluginPathChanged, this, &VP1ExpertSettings::setPluginPath); + connect(advancedTab, &AdvancedTab::signalFileSelectDirChanged, this, &VP1ExpertSettings::setFileSelectDir); + connect(advancedTab, &AdvancedTab::signalAuthLogChanged, this, &VP1ExpertSettings::setAuthLog); + #endif + + m_buttonBox = new QDialogButtonBox(QDialogButtonBox::Ok); + + connect(m_buttonBox, &QDialogButtonBox::accepted, this, &QDialog::close); + // connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(m_tabWidget); + mainLayout->addWidget(m_buttonBox); + setLayout(mainLayout); + + this->setWindowTitle(tr("VP1 Settings")); + + +} + +void VP1ExpertSettings::closeEvent(QCloseEvent *event) +{ + //Update settings + #if defined BUILDVP1LIGHT + VP1Msg::enableMsg("general", "ExpertSettings/VP1_VERBOSE_OUTPUT"); + VP1Msg::enableMsg("general", "ExpertSettings/VP1_DEBUG_OUTPUT"); + #else + VP1Msg::enableMsg("VP1_VERBOSE_OUTPUT"); + VP1Msg::enableMsg("VP1_DEBUG_OUTPUT"); + #endif + + // if(QDir(pluginPath).exists()||pluginPath==""){ + #if defined BUILDVP1LIGHT + VP1QtUtils::setExpertSetting("expert","ExpertSettings/VP1PLUGINPATH", m_pluginPath); + VP1QtUtils::setExpertSetting("expert","ExpertSettings/VP1_FILESELECTDIR", m_fileSelectDir); + VP1QtUtils::setExpertSetting("expert","ExpertSettings/VP1_AUTH_ENABLELOG", m_authLog); + VP1QtUtils::setExpertSetting("general","ExpertSettings/VP1_SCREENSHOTS_DIR", m_screenshotDir); + #else + VP1QtUtils::setEnvironmentVariable("VP1PLUGINPATH", m_pluginPath); + VP1QtUtils::setEnvironmentVariable("VP1_FILESELECTDIR", m_fileSelectDir); + VP1QtUtils::setEnvironmentVariable("VP1_AUTH_ENABLELOG", m_authLog); + VP1QtUtils::setEnvironmentVariable("VP1_SCREENSHOTS_DIR", m_screenshotDir); + #endif + + #if defined BUILDVP1LIGHT + QMessageBox msgBox; + QCheckBox *cb = new QCheckBox("Don't ask again."); + msgBox.setWindowTitle("Settings"); + msgBox.setText("Some settings may require a restart of VP1."); + msgBox.setIcon(QMessageBox::Icon::Information); + msgBox.setCheckBox(cb); + + if(VP1QtUtils::expertSettingIsOn("general","Configuration/enableCloseSettingsReminder")){ + cb->setChecked(true); + } + connect(cb, &QCheckBox::toggled, [this](){VP1ExpertSettings::setExpertSetting("general","Configuration/enableCloseSettingsReminder");}); + + if(cb->checkState()==Qt::Unchecked){ + msgBox.exec(); + } + + event->accept(); + #else + unused(event); + #endif + + +} + +void VP1ExpertSettings::keyPressEvent(QKeyEvent *event){ + if(event->key() == Qt::Key_Escape) + VP1ExpertSettings::close(); +} + +void VP1ExpertSettings::setPluginPath(const QString &path){ + m_pluginPath = path; +} + +void VP1ExpertSettings::setFileSelectDir(const QString &path){ + m_fileSelectDir = path; +} + +void VP1ExpertSettings::setScreenshotDir(const QString &path){ + m_screenshotDir = path; +} + +void VP1ExpertSettings::setAuthLog(const QString &path){ + m_authLog = path; +} + +void VP1ExpertSettings::setExpertSetting(const QString &type, const QString &name){ + if(!VP1QtUtils::expertSettingIsOn(type, name)){ + VP1QtUtils::setExpertSetting(type, name, "1"); + } else { + VP1QtUtils::setExpertSetting(type, name, ""); + } +} + +GeneralTab::GeneralTab(QWidget *parent) + : QWidget(parent) +{ + + QGroupBox *generalGroup = new QGroupBox(tr("General settings")); + + m_checkboxVerbose = new QCheckBox("&Verbose output", this); + m_checkboxVerbose->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Enable A LOT more verbose output to stdout from VP1. It is very useful if you run with this before sending us logfiles for bug reports.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_VERBOSE_OUTPUT")){ + m_checkboxVerbose->setChecked(true); + } + connect(m_checkboxVerbose, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_VERBOSE_OUTPUT");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_VERBOSE_OUTPUT")){ + m_checkboxVerbose->setChecked(true); + } + connect(m_checkboxVerbose, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_VERBOSE_OUTPUT");}); + #endif + + m_checkboxDebug = new QCheckBox("&Debug output", this); + m_checkboxDebug->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Enable A LOT more debug output to stdout from VP1. It is very useful if you run with this before sending us logfiles for bug reports.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DEBUG_OUTPUT")){ + m_checkboxDebug->setChecked(true); + } + connect(m_checkboxDebug, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_DEBUG_OUTPUT");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_DEBUG_OUTPUT")){ + m_checkboxDebug->setChecked(true); + } + connect(m_checkboxDebug, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_DEBUG_OUTPUT");}); + #endif + + m_checkboxDisallowMultipleChannels = new QCheckBox("D&isallow multiple channels", this); + m_checkboxDisallowMultipleChannels->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">This variable exists to help users whose graphics drivers are broken in such a way as to make VP1 crash when showing multiple 3D widgets. Setting this variable will thus ensure that the user can only ever open one channel, and it will remove the little 3D preview window normally shown when editing a material.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DISALLOW_MULTIPLE_CHANNELS")){ + m_checkboxDisallowMultipleChannels->setChecked(true); + } + connect(m_checkboxDisallowMultipleChannels, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_DISALLOW_MULTIPLE_CHANNELS");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_DISALLOW_MULTIPLE_CHANNELS")){ + m_checkboxDisallowMultipleChannels->setChecked(true); + } + connect(m_checkboxDisallowMultipleChannels, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_DISALLOW_MULTIPLE_CHANNELS");}); + #endif + + m_checkboxDisplayMouseClicks = new QCheckBox("Dis&play mouse clicks", this); + m_checkboxDisplayMouseClicks->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Makes a small popup window appear whenever the user clicks a mouse-button in VP1. Basically this feature exists since it is used when producing the movies (screencasts) on this webpage.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DISPLAY_MOUSE_CLICKS")){ + m_checkboxDisplayMouseClicks->setChecked(true); + } + connect(m_checkboxDisplayMouseClicks, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_DISPLAY_MOUSE_CLICKS");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_DISPLAY_MOUSE_CLICKS")){ + m_checkboxDisplayMouseClicks->setChecked(true); + } + connect(m_checkboxDisplayMouseClicks, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_DISPLAY_MOUSE_CLICKS");}); + #endif + + m_checkboxEnableAskOnClose = new QCheckBox("&Ask on close", this); + m_checkboxEnableAskOnClose->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">By default, closing the VP1 window immediately results in the job being finished. Setting this variable will instead make VP1 ask the user if it should really close.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_ENABLE_ASK_ON_CLOSE")){ + m_checkboxEnableAskOnClose->setChecked(true); + } + connect(m_checkboxEnableAskOnClose, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_ENABLE_ASK_ON_CLOSE");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_ASK_ON_CLOSE")){ + m_checkboxEnableAskOnClose->setChecked(true); + } + connect(m_checkboxEnableAskOnClose, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_ENABLE_ASK_ON_CLOSE");}); + #endif + + + m_checkboxGuidesSphereInsteadOfCoordaxes = new QCheckBox("G&uides sphere instead of coordinate axes", this); + m_checkboxGuidesSphereInsteadOfCoordaxes->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Replaces the coordinate axes with a red sphere.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES")){ + m_checkboxGuidesSphereInsteadOfCoordaxes->setChecked(true); + } + connect(m_checkboxGuidesSphereInsteadOfCoordaxes, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES")){ + m_checkboxGuidesSphereInsteadOfCoordaxes->setChecked(true); + } + connect(m_checkboxGuidesSphereInsteadOfCoordaxes, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES");}); + #endif + + + m_checkboxAntiAliasing = new QCheckBox("Advanced Anti-Aliasing", this); + m_checkboxAntiAliasing->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Switches on advanced Anti-Aliasing. WARNING: May cause issues with certain graphics drivers.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_ADVANCED_ANTIALIASING")){ + m_checkboxAntiAliasing->setChecked(true); + } + connect(m_checkboxAntiAliasing, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("general","ExpertSettings/VP1_ADVANCED_ANTIALIASING");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_ADVANCED_ANTIALIASING")){ + m_checkboxAntiAliasing->setChecked(true); + } + connect(m_checkboxAntiAliasing, &QCheckBox::toggled, [this](){GeneralTab::setExpertSetting("VP1_ADVANCED_ANTIALIASING");}); + #endif + + + + QGroupBox *directoryGroup = new QGroupBox(tr("Directory settings")); + + m_browseButton1 = new QPushButton(tr("&Browse..."), this); + connect(m_browseButton1, &QAbstractButton::clicked, this, &GeneralTab::on_browseButton1_clicked); + #if defined BUILDVP1LIGHT + m_lineEdit1 = new QLineEdit(VP1QtUtils::expertSettingValue("general","ExpertSettings/VP1_SCREENSHOTS_DIR"), this); + #else + m_lineEdit1 = new QLineEdit(VP1QtUtils::environmentVariableValue("VP1_SCREENSHOTS_DIR"), this); + #endif + m_lineEdit1->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Turns on the automatic generation of screen-shots for all channels at every event. The value must be a valid writable directory, where all generated screenshot files will be stored.</div>" + " </html>", 0 + )); + connect(m_lineEdit1, &QLineEdit::textChanged, this, &GeneralTab::slotScreenshotDirChanged); + + + QVBoxLayout *generalLayout = new QVBoxLayout; + generalLayout->addWidget(m_checkboxVerbose); + generalLayout->addWidget(m_checkboxDebug); + generalLayout->addWidget(m_checkboxDisallowMultipleChannels); + generalLayout->addWidget(m_checkboxDisplayMouseClicks); + generalLayout->addWidget(m_checkboxEnableAskOnClose); + generalLayout->addWidget(m_checkboxGuidesSphereInsteadOfCoordaxes); + generalLayout->addWidget(m_checkboxAntiAliasing); + generalGroup->setLayout(generalLayout); + + QGridLayout *gridLayout = new QGridLayout(this); + gridLayout->addWidget(new QLabel(tr("Screenshots directory:")), 0, 0); + gridLayout->addWidget(m_lineEdit1,1,0); + gridLayout->addWidget(m_browseButton1,1,1); + directoryGroup->setLayout(gridLayout); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(generalGroup); + mainLayout->addWidget(directoryGroup); + mainLayout->addStretch(1); + setLayout(mainLayout); + +} + +#if defined BUILDVP1LIGHT +void GeneralTab::setExpertSetting(const QString &type, const QString &name){ + if(!VP1QtUtils::expertSettingIsOn(type, name)){ + VP1QtUtils::setExpertSetting(type, name, "1"); + } else { + VP1QtUtils::setExpertSetting(type, name, ""); + } +} +#else +void GeneralTab::setExpertSetting(const QString &name){ + if(!VP1QtUtils::environmentVariableIsOn(name)){ + VP1QtUtils::setEnvironmentVariable(name, "1"); + } else { + VP1QtUtils::unsetEnvironmentVariable(name); + } +} +#endif + +void GeneralTab::on_browseButton1_clicked(){ + QString fileName = QFileDialog::getExistingDirectory(this, + tr("Select screenshot directory"), QDir::currentPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + + m_lineEdit1->setText(fileName); +} + +void GeneralTab::slotScreenshotDirChanged(const QString &path){ + emit signalScreenshotDirChanged(path); +} + + +AdvancedTab::AdvancedTab(QWidget *parent) + : QWidget(parent) +{ + QGroupBox *checkBoxGroup = new QGroupBox(tr("Advanced settings")); + + m_checkboxEnableInformOnEndOfJob = new QCheckBox("&Enable inform on end of job", this); + m_checkboxEnableInformOnEndOfJob->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">By default, VP1 simply exits at the end of the ATHENA job, which might be confusing to some. When this variable is set, VP1 will show an dialog, letting the user know that the end of the job has been reached.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/VP1_ENABLE_INFORM_ON_END_OF_JOB")){ + m_checkboxEnableInformOnEndOfJob->setChecked(true); + } + connect(m_checkboxEnableInformOnEndOfJob, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("expert","ExpertSettings/VP1_ENABLE_INFORM_ON_END_OF_JOB");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_INFORM_ON_END_OF_JOB")){ + m_checkboxEnableInformOnEndOfJob->setChecked(true); + } + connect(m_checkboxEnableInformOnEndOfJob, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("VP1_ENABLE_INFORM_ON_END_OF_JOB");}); + #endif + + m_checkboxHardExitAtEnd = new QCheckBox("&Hard exit at end", this); + m_checkboxHardExitAtEnd->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">By default, the VP1 algorithm simply tells ATHENA to end the job when VP1 is being closed. This means that ATHENA will shut down with its usual procedure, calling finalise on algorithms, generating summaries, etc. If this variable is set, then VP1 will make the process end immediately and abrubtly instead - saving the user some time.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/VP1_HARD_EXIT_AT_END")){ + m_checkboxHardExitAtEnd->setChecked(true); + } + connect(m_checkboxHardExitAtEnd, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("expert","ExpertSettings/VP1_HARD_EXIT_AT_END");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_HARD_EXIT_AT_END")){ + m_checkboxHardExitAtEnd->setChecked(true); + } + connect(m_checkboxHardExitAtEnd, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("VP1_HARD_EXIT_AT_END");}); + #endif + + m_checkboxDevelShowAllCruiseAndEventControls = new QCheckBox("&Show all cruise and event controls", this); + m_checkboxDevelShowAllCruiseAndEventControls->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Use to enable a few controls related to VP1 cruise-mode, which have presently been disabled.</div>" + " </html>", 0 + )); + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingIsOn("expert","ExpertSettings/VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS")){ + m_checkboxDevelShowAllCruiseAndEventControls->setChecked(true); + } + connect(m_checkboxDevelShowAllCruiseAndEventControls, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("expert","ExpertSettings/VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS");}); + #else + if(VP1QtUtils::environmentVariableIsOn("VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS")){ + m_checkboxDevelShowAllCruiseAndEventControls->setChecked(true); + } + connect(m_checkboxDevelShowAllCruiseAndEventControls, &QCheckBox::toggled, [this](){AdvancedTab::setExpertSetting("VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS");}); + #endif + + + QGroupBox *directoryGroup = new QGroupBox(tr("Directory settings")); + + m_browseButton1 = new QPushButton(tr("&Browse..."), this); + connect(m_browseButton1, &QAbstractButton::clicked, this, &AdvancedTab::on_browseButton1_clicked); + m_lineEdit1 = new QLineEdit("", this); + + #if defined BUILDVP1LIGHT + if(VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1PLUGINPATH")==""){ + #ifdef MACBUNDLE + m_lineEdit1->setText(QCoreApplication::applicationDirPath()+"/../Frameworks"); + #else + m_lineEdit1->setText(QCoreApplication::applicationDirPath()+"/../lib"); + #endif + } else { + m_lineEdit1->setText(VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1PLUGINPATH")); + } + #else + if(VP1QtUtils::environmentVariableValue("VP1PLUGINPATH")==""){ + m_lineEdit1->setText(QCoreApplication::applicationDirPath()+"/../lib"); + } else { + m_lineEdit1->setText(VP1QtUtils::environmentVariableValue("VP1PLUGINPATH")); + } + #endif + m_lineEdit1->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Select the directory that contains the plugin libraries.</div>" + " </html>", 0 + )); + connect(m_lineEdit1, &QLineEdit::textChanged, this, &AdvancedTab::slotPluginPathChanged); + + m_browseButton2 = new QPushButton(tr("B&rowse..."), this); + connect(m_browseButton2, &QAbstractButton::clicked, this, &AdvancedTab::on_browseButton2_clicked); + #if defined BUILDVP1LIGHT + m_lineEdit2 = new QLineEdit(VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1_FILESELECTDIR"), this); + #else + m_lineEdit2 = new QLineEdit(VP1QtUtils::environmentVariableValue("VP1_FILESELECTDIR"), this); + #endif + m_lineEdit2->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">By default, the various VP1 file selectors starts in the job run-directory. Setting this variable to a directory ensures that that directory is used by default instead.</div>" + " </html>", 0 + )); + connect(m_lineEdit2, &QLineEdit::textChanged, this, &AdvancedTab::slotFileSelectDirChanged); + + m_browseButton3 = new QPushButton(tr("Br&owse..."), this); + connect(m_browseButton3, &QAbstractButton::clicked, this, &AdvancedTab::on_browseButton3_clicked); + #if defined BUILDVP1LIGHT + m_lineEdit3 = new QLineEdit(VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1_AUTH_ENABLELOG"), this); + #else + m_lineEdit3 = new QLineEdit(VP1QtUtils::environmentVariableValue("VP1_AUTH_ENABLELOG"), this); + #endif + m_lineEdit3->setToolTip( QApplication::translate(__FUNCTION__, " <html>\n" + " <div style=\"width: 300px;\">Enables creation of an authentication log file for VP1 live.</div>" + " </html>", 0 + )); + connect(m_lineEdit3, &QLineEdit::textChanged, this, &AdvancedTab::slotAuthLogChanged); + + + QVBoxLayout *checkBoxLayout = new QVBoxLayout; + checkBoxLayout->addWidget(m_checkboxEnableInformOnEndOfJob); + checkBoxLayout->addWidget(m_checkboxHardExitAtEnd); + checkBoxLayout->addWidget(m_checkboxDevelShowAllCruiseAndEventControls); + checkBoxGroup->setLayout(checkBoxLayout); + + QGridLayout *gridLayout = new QGridLayout(this); + gridLayout->addWidget(new QLabel(tr("Plugin path:")), 0, 0); + gridLayout->addWidget(m_lineEdit1,1,0); + gridLayout->addWidget(m_browseButton1,1,1); + gridLayout->addWidget(new QLabel(tr("File selection directory:")), 2, 0); + gridLayout->addWidget(m_lineEdit2,3,0); + gridLayout->addWidget(m_browseButton2,3,1); + gridLayout->addWidget(new QLabel(tr("Authentication log directory:")), 4, 0); + gridLayout->addWidget(m_lineEdit3,5,0); + gridLayout->addWidget(m_browseButton3,5,1); + directoryGroup->setLayout(gridLayout); + + QVBoxLayout *mainLayout = new QVBoxLayout; + mainLayout->addWidget(checkBoxGroup); + mainLayout->addWidget(directoryGroup); + mainLayout->addStretch(1); + setLayout(mainLayout); +} + +void AdvancedTab::on_browseButton1_clicked() +{ + QString fileName = QFileDialog::getExistingDirectory(this, + tr("Select Plugin Path"), QDir::currentPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + + m_lineEdit1->setText(fileName); +} + +void AdvancedTab::on_browseButton2_clicked() +{ + QString fileName = QFileDialog::getExistingDirectory(this, + tr("Select file directory"), QDir::currentPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + + m_lineEdit2->setText(fileName); +} + +void AdvancedTab::on_browseButton3_clicked() +{ + QString fileName = QFileDialog::getExistingDirectory(this, + tr("Select authentication directory"), QDir::currentPath(), QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + + m_lineEdit3->setText(fileName); +} + +void AdvancedTab::slotPluginPathChanged(const QString &path){ + emit signalPluginPathChanged(path); +} + +void AdvancedTab::slotFileSelectDirChanged(const QString &path){ + emit signalFileSelectDirChanged(path); +} + +void AdvancedTab::slotAuthLogChanged(const QString &path){ + emit signalAuthLogChanged(path); +} + +#if defined BUILDVP1LIGHT +void AdvancedTab::setExpertSetting(const QString &type, const QString &name){ + if(!VP1QtUtils::expertSettingIsOn(type, name)) { + VP1QtUtils::setExpertSetting(type, name, "1"); + } else { + VP1QtUtils::setExpertSetting(type, name, ""); + } +} +#else +void AdvancedTab::setExpertSetting(const QString &name){ + if(!VP1QtUtils::environmentVariableIsOn(name)) { + VP1QtUtils::setEnvironmentVariable(name, "1"); + } else { + VP1QtUtils::unsetEnvironmentVariable(name); + } +} +#endif diff --git a/graphics/VP1/VP1Gui/src/VP1GeoDBSelection.cxx b/graphics/VP1/VP1Gui/src/VP1GeoDBSelection.cxx new file mode 100644 index 0000000000000000000000000000000000000000..bd4d7713a3de349b92e2a5509b20903718d6821a --- /dev/null +++ b/graphics/VP1/VP1Gui/src/VP1GeoDBSelection.cxx @@ -0,0 +1,129 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Source file for class VP1GeoDBSelection // +// // +// Description: Dialog for the selection of a geometry database // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2017 // +// // +////////////////////////////////////////////////////////////////////////// + +#include "VP1Gui/VP1GeoDBSelection.h" + +#include <QPushButton> +#include <QGridLayout> +#include <QLabel> +#include <QComboBox> +#include <QFileInfo> + +#include <QtWidgets> + +VP1GeoDBSelection::VP1GeoDBSelection(QWidget *parent) : QDialog(parent) +{ + //Set default dialog size + int nWidth = 800; + int nHeight = 220; + if (parent != NULL) + setGeometry(parent->x() + parent->width()/2 - nWidth/2, + parent->y() + parent->height()/2 - nHeight/2, + nWidth, nHeight); + else + resize(nWidth, nHeight); + + //Browse button to select database + m_browseButton = new QPushButton(tr("&Browse..."), this); + connect(m_browseButton, &QAbstractButton::clicked, this, &VP1GeoDBSelection::on_browseButton_clicked); + + //Buttonbox to set Open, Cancel buttons + m_buttonBox = new QDialogButtonBox(this); + m_openButton = m_buttonBox->addButton(tr("&Open"), QDialogButtonBox::AcceptRole); + m_cancelButton = m_buttonBox->addButton(tr("&Cancel"),QDialogButtonBox::RejectRole); + connect(m_openButton, &QPushButton::clicked, this, &VP1GeoDBSelection::loadDatabase); + connect(m_cancelButton, &QPushButton::clicked, this, &VP1GeoDBSelection::reject); + + //Open QSettings to store path do database + QSettings settings("ATLAS", "VP1Light"); + QString text; + + //If no db file has been provided via command line argument, the "db/path" value is "" + if(settings.value("db/path").toString()==""){ + m_openButton->setEnabled(false); + text = "(*.db)"; + } else { //If a db file has been provided show it in the combobox + text = settings.value("db/path").toString(); + } + //Create the combobox + m_directoryComboBox = createComboBox(text); + + //Create the main layout + QGridLayout *mainLayout = new QGridLayout(this); + mainLayout->addWidget(new QLabel(tr("Select Geometry Database:")), 0, 0); + mainLayout->addWidget(m_directoryComboBox, 1, 0, 1, 2); + mainLayout->addWidget(m_browseButton, 1, 4); + mainLayout->addWidget(m_buttonBox, 3, 4); + + m_browseButton->setMinimumWidth(200); + m_buttonBox->setMinimumWidth(200); + m_browseButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + m_buttonBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); +} + +//Method to create the drop down combobox +QComboBox *VP1GeoDBSelection::createComboBox(const QString &text) +{ + QComboBox *comboBox = new QComboBox; + comboBox->setMinimumWidth(600); + comboBox->setEditable(false); + comboBox->addItem(text); + comboBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); + return comboBox; +} + +//Animate the click +void VP1GeoDBSelection::animateFindClick() +{ + m_openButton->animateClick(); +} + +//Open the file selection dialog +void VP1GeoDBSelection::on_browseButton_clicked() +{ + m_fileName = QFileDialog::getOpenFileName(this, + tr("Select Database"), QDir::currentPath(), + tr("DB Files (*.db)")); + + // Add the selected file to the combobox + if (!m_fileName.isEmpty()) { + if (m_directoryComboBox->findText(m_fileName) == -1) + m_directoryComboBox->addItem(m_fileName); + m_directoryComboBox->setCurrentIndex(m_directoryComboBox->findText(m_fileName)); + + //When valid a database is selected, enable the Open button to confirm + m_openButton->setEnabled(true); + } + +} + +//Check and Save the settings +void VP1GeoDBSelection::loadDatabase(){ + + //Save DB path to settings + QSettings settings("ATLAS", "VP1Light"); + settings.setValue("db/path", m_directoryComboBox->itemText(m_directoryComboBox->currentIndex())); + + //If the selected DB does not exists, go back + if (!QFileInfo::exists(m_directoryComboBox->itemText(m_directoryComboBox->currentIndex()))){ + QMessageBox msgBox; + msgBox.setWindowTitle("Virtual Point 1"); + msgBox.setText("Database does not exist. Please choose another database file."); + msgBox.exec(); + return; + } + VP1GeoDBSelection::setResult(1); + VP1GeoDBSelection::accept(); +} diff --git a/graphics/VP1/VP1Gui/src/VP1Gui.cxx b/graphics/VP1/VP1Gui/src/VP1Gui.cxx index 920f95ddbd20e93d6fa4f914cfee09408812f264..f65d92bbe1956620d8cedbbb0fa6bdbe9b5fe28f 100644 --- a/graphics/VP1/VP1Gui/src/VP1Gui.cxx +++ b/graphics/VP1/VP1Gui/src/VP1Gui.cxx @@ -133,7 +133,7 @@ bool VP1Gui::argumentsAreValid() const // For the https mode check if the platform supports SSL if(m_d->singleEventSource.startsWith("https://") - && !QSslSocket::supportsSsl()) { + && ! (QSslSocket::supportsSsl()) ) { VP1Msg::message("VP1ExecutionScheduler::init ERROR: Unable to retrieve events over Https. The platform does not support SSL"); return false; } @@ -209,8 +209,6 @@ bool VP1Gui::executeNewEvent( const int& run, const uint64_t& event, const unsig { VP1Msg::messageDebug("Examining new event ( run# "+QString::number(run)+", event# "+QString::number(event)+" )"); - - bool b = m_d->the_scheduler->executeNewEvent(run,event,triggerType,time); // NOTE: diff --git a/graphics/VP1/VP1Gui/src/VP1MainWindow.cxx b/graphics/VP1/VP1Gui/src/VP1MainWindow.cxx index 341509dbe8471c50a431597402e31baba2e83246..a6073985b67b1ef8beb8f4eff8701d8948655c11 100644 --- a/graphics/VP1/VP1Gui/src/VP1MainWindow.cxx +++ b/graphics/VP1/VP1Gui/src/VP1MainWindow.cxx @@ -24,6 +24,13 @@ #include "VP1Gui/VP1AvailEvtsLocalDir.h" #include "VP1StreamMenuUpdater.h" +#ifdef BUILDVP1LIGHT + #include "VP1Gui/VP1ExpertSettings.h" + #include "VP1Gui/VP1GeoDBSelection.h" + #include "VP1Gui/VP1AODSelection.h" + #include "VP1Gui/VP1SelectEvent.h" +#endif + #include "VP1UtilsBase/VP1FileUtilities.h" #include "VP1Base/IVP1ChannelWidget.h" @@ -55,6 +62,8 @@ #include <QGraphicsView> #include <QGraphicsScene> #include <QtGui> +#include <QSettings> +#include <QScrollBar> @@ -99,7 +108,13 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi setupStatusBar(); // - if (!VP1QtUtils::environmentVariableIsOn("VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS")) { + #if defined BUILDVP1LIGHT + bool checkShowAllCruiseAndEventControls = VP1QtUtils::expertSettingIsSet("expert","ExpertSettings/VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS"); + #else + bool checkShowAllCruiseAndEventControls = VP1QtUtils::environmentVariableIsOn("VP1_DEVEL_SHOW_ALL_CRUISE_AND_EVENT_CONTROLS"); + #endif + + if (!checkShowAllCruiseAndEventControls) { pushButton_eventseek->setVisible(false); groupBox_cruise->setVisible(false); } @@ -120,6 +135,31 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi connect(m_action_addEventFile,SIGNAL(triggered(bool)),this,SLOT(addEventFile())); } + #ifndef BUILDVP1LIGHT + pushButton_previousevent->setVisible(false); + pushButton_eventselect->setVisible(false); + #else + pushButton_eventselect->setVisible(true); + pushButton_eventselect->setText("Event: 0/0"); + pushButton_eventselect->setEnabled(false); + pushButton_previousevent->setEnabled(false); + //Disable all controls that are not available in VP1Light + // pushButton_quicksetup_3dcocktail->setEnabled(false); + // pushButton_quicksetup_3dcocktail->setToolTip("Not available in VP1Light"); + pushButton_quicksetup_trackingstudies->setEnabled(false); + pushButton_quicksetup_trackingstudies->setToolTip("Not available in VP1Light"); + pushButton_quicksetup_calostudies->setEnabled(false); + pushButton_quicksetup_calostudies->setToolTip("Not available in VP1Light"); + action_quicklaunch_Tracking_studies->setEnabled(false); + action_quicklaunch_Tracking_studies->setToolTip("Not available in VP1Light"); + action_quicklaunch_Calo_studies->setEnabled(false); + action_quicklaunch_Calo_studies->setToolTip("Not available in VP1Light"); + action_quicklaunch_Storegate_browser->setEnabled(false); + action_quicklaunch_Storegate_browser->setToolTip("Not available in VP1Light"); + action_quicklaunch_trackcalo_commis->setEnabled(false); + action_quicklaunch_trackcalo_commis->setToolTip("Not available in VP1Light"); + m_action_addEventFile->setEnabled(false); + #endif //////////////////////////////////////////////////// //Do we need a menu for multiple input directories? @@ -200,9 +240,13 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi frame_instructions->setFrameShape(QFrame::StyledPanel); // textBrowser_intro1->setStyleSheet("QTextBrowser#textBrowser_intro1 { background-color: rgba(0, 0, 0, 0%) } "); // textBrowser_intro2->setStyleSheet("QTextBrowser#textBrowser_intro2 { background-color: rgba(0, 0, 0, 0%) } "); - connect(pushButton_quicksetup_3dcocktail,SIGNAL( clicked()),this,SLOT(quickSetupTriggered())); + #ifndef BUILDVP1LIGHT + connect(pushButton_quicksetup_3dcocktail,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); + #else + connect(pushButton_quicksetup_3dcocktail,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); + #endif connect(pushButton_quicksetup_trackingstudies,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); - connect(pushButton_quicksetup_calostudies,SIGNAL( clicked()),this,SLOT(quickSetupTriggered())); + connect(pushButton_quicksetup_calostudies,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); connect(pushButton_quicksetup_geometrystudies,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); connect(pushButton_quicksetup_analysisstudies,SIGNAL(clicked()),this,SLOT(quickSetupTriggered())); @@ -237,6 +281,7 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi connect(action_quicklaunch_Tracking_studies,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); connect(action_quicklaunch_Calo_studies,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); connect(action_quicklaunch_Geometry_studies,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); + connect(action_quicklaunch_analysisstudies,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); connect(action_quicklaunch_Storegate_browser,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); connect(action_quicklaunch_3dcocktail,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); connect(action_quicklaunch_trackcalo_commis,SIGNAL(triggered(bool)),this,SLOT(quickSetupTriggered())); @@ -260,7 +305,7 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi QAction * laststyleact(0); bool foundplastique=false; QSettings s(m_settingsfile,QSettings::IniFormat); - QString defaultstyle=s.value("style/defaultstyle", "Plastique").toString(); + QString defaultstyle=s.value("style/defaultstyle", "Fusion").toString(); foreach (QString style, QStyleFactory::keys() ) { QAction * act = m_menu_changeStyle->addAction(style); act->setStatusTip("Change application style to "+style); @@ -326,8 +371,20 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi connect(m_actionAdd_empty_tab,SIGNAL(triggered(bool)),this,SLOT(request_addEmptyTab())); connect(m_actionSave_current_tabs,SIGNAL(triggered(bool)),this,SLOT(request_saveasConfig())); + //ExpertSettings + #ifdef BUILDVP1LIGHT + menuConfiguration->addSeparator(); + m_actionEnableExpertSettings = menuConfiguration->addAction ( "&Settings" ); + m_actionEnableExpertSettings->setStatusTip("Open additional settings"); + connect(m_actionEnableExpertSettings, &QAction::triggered, this, &VP1MainWindow::request_expertSettings); + #endif + //Event navigation: connect(pushButton_nextevent,SIGNAL(clicked()),this,SLOT(goToNextEvent())); + #ifdef BUILDVP1LIGHT + connect(pushButton_previousevent,SIGNAL(clicked()),this,SLOT(goToPreviousEvent())); + connect(pushButton_eventselect,SIGNAL(clicked()),this,SLOT(chooseEvent())); + #endif //Listen for external requests: connect(&m_tcpserver,SIGNAL(receivedExternalRequest(VP1ExternalRequest)),this,SLOT(receivedExternalRequest(VP1ExternalRequest))); @@ -366,7 +423,9 @@ VP1MainWindow::VP1MainWindow(VP1ExecutionScheduler*sched,VP1AvailEvents * ae,QWi connect(m_action_openAbout,SIGNAL(triggered(bool)),this,SLOT(help_openAbout())); // FIXME: enabling menubar again. It's part of a quickfix, described here: https://its.cern.ch/jira/browse/ATLASVPONE-120 - menubar->setEnabled(false); + #ifndef BUILDVP1LIGHT + menubar->setEnabled(false); + #endif } //_________________________________________________________________________________ @@ -724,10 +783,22 @@ QMap<QString,QString> VP1MainWindow::availableFiles(const QString& extension, qDebug() << "VP1MainWindow::availableFiles()"; qDebug() << "extension:" << extension << "pathvar:" << pathvar << "instareasubdir:" << instareasubdir << "extradirenvvar:" << extradirenvvar << "currentdir:" << currentdir; - //Add directories from extradirenvvar (e.g. $VP1PlUGINPATH) - QStringList vp1pluginpath = extradirenvvar.isEmpty() ? QStringList() : QString(::getenv(extradirenvvar.toStdString().c_str())).split(":",QString::SkipEmptyParts); - qDebug() << "extradirenvvar:" << extradirenvvar << "vp1pluginpath:" << vp1pluginpath; + //Add directories from extradirenvvar (e.g. $VP1PLUGINPATH) + QStringList vp1pluginpath = extradirenvvar.isEmpty() ? QStringList() : QString(::getenv(extradirenvvar.toStdString().c_str())).split(":",QString::SkipEmptyParts); + if(VP1Msg::debug()){ + qDebug() << "extradirenvvar:" << extradirenvvar; + qDebug() << "vp1pluginpath:" << vp1pluginpath; + } + + #ifdef BUILDVP1LIGHT + //Add dir from Expert Settings + if(VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1PLUGINPATH")==""){ + vp1pluginpath<<QCoreApplication::applicationDirPath()+"/../lib"; + } else{ + vp1pluginpath<<VP1QtUtils::expertSettingValue("expert","ExpertSettings/VP1PLUGINPATH"); + } + #endif //Currentdir: if (currentdir) { @@ -774,6 +845,8 @@ QMap<QString,QString> VP1MainWindow::availableFiles(const QString& extension, //_________________________________________________________________________________ QMap<QString,QString> VP1MainWindow::availablePluginFiles() const { +VP1Msg::messageDebug("VP1MainWindow::availablePluginFiles()"); + #ifdef __APPLE__ QString sharedlibsuffix = "dylib"; #else @@ -836,8 +909,8 @@ bool VP1MainWindow::okToProceedToNextEvent() const //_________________________________________________________________________________ void VP1MainWindow::nextEvent() { m_betweenevents=true; - if (m_availEvents) { - QList<VP1EventFile> evts = m_availEvents->freshEvents(); + if (m_availEvents) { + QList<VP1EventFile> evts = m_availEvents->freshEvents(); if (evts.empty()) { addToMessageBox("ERROR: Going to next event, but one is not available!"); m_scheduler->setNextRequestedEventFile(""); @@ -850,16 +923,57 @@ void VP1MainWindow::nextEvent() { //_________________________________________________________________________________ void VP1MainWindow::goToNextEvent() { + #if defined BUILDVP1LIGHT + std::cout << "goToNextEvent: \n" + << "m_scheduler->getEvtNr()+2: " << m_scheduler->getEvtNr()+2 + << "\nm_scheduler->getTotEvtNr(): " << m_scheduler->getTotEvtNr() << std::endl; + if ( m_scheduler->getEvtNr()+2 < m_scheduler->getTotEvtNr() ) { + std::cout << "First case" << std::endl; + m_scheduler->setEvtNr(m_scheduler->getEvtNr()+1); + nextEvent(); + qApp->quit(); + } + else if( m_scheduler->getEvtNr()+2 == m_scheduler->getTotEvtNr() ) { + std::cout << "Second case" << std::endl; + m_scheduler->setEvtNr(m_scheduler->getEvtNr()+1); + nextEvent(); + qApp->quit(); + } + #else nextEvent(); - qApp->quit(); + qApp->quit(); + #endif } +#if defined BUILDVP1LIGHT +//_________________________________________________________________________________ +void VP1MainWindow::goToPreviousEvent() { + if ( m_scheduler->getEvtNr()-1 > 0 ) { + m_scheduler->setEvtNr(m_scheduler->getEvtNr()-1); + nextEvent(); + qApp->quit(); + } + else if( m_scheduler->getEvtNr()-1 == 0 ) { + m_scheduler->setEvtNr(m_scheduler->getEvtNr()-1); + nextEvent(); + qApp->quit(); + } +} +#endif + //_________________________________________________________________________________ void VP1MainWindow::closeEvent(QCloseEvent * event) { VP1Msg::messageDebug("VP1MainWindow::closeEvent()"); - if (VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_ASK_ON_CLOSE")) { + bool checkEnableAskOnClose; + #if defined BUILDVP1LIGHT + checkEnableAskOnClose = VP1QtUtils::expertSettingIsSet("general","ExpertSettings/VP1_ENABLE_ASK_ON_CLOSE"); + #else + checkEnableAskOnClose = VP1QtUtils::environmentVariableIsOn("VP1_ENABLE_ASK_ON_CLOSE"); + #endif + + if (checkEnableAskOnClose) { int ret = QMessageBox::warning(this, "Close VP1?", "You are about to close VP1 and end the job.\nProceed?", @@ -910,7 +1024,13 @@ void VP1MainWindow::setRunEvtNumber(const int& r, const unsigned long long& e, c + QString(trighex.isEmpty()?QString(""):", triggerType: "+trighex) + QString(time>0 ? ", time: "+QDateTime::fromTime_t(time).toString(Qt::ISODate).replace('T',' ') : "") + QString(m_currentStream.isEmpty()?"":", "+m_currentStream); - setWindowTitle("Virtual Point 1 ["+expandedevtstr+"]"); + + #ifdef BUILDVP1LIGHT + setWindowTitle("VP1Light ["+expandedevtstr+"]"); + #else + setWindowTitle("VP1 (Virtual Point 1) ["+expandedevtstr+"]"); + #endif // BUILDVP1LIGHT + groupBox_event->setTitle("Event [loaded]"); label_run_event->setText("["+evtstr+"]"); @@ -937,6 +1057,7 @@ void VP1MainWindow::addToMessageBox( const QString& m, const QString& extrastyle textBrowser_channelmessages->append(titlepart + ( extrastyleopts.isEmpty() ? m : "<span style=\"font-style:italic;"+extrastyleopts+";\">"+m+"</span>")); + textBrowser_channelmessages->verticalScrollBar()->setSliderPosition(textBrowser_channelmessages->verticalScrollBar()->maximum()); } //_________________________________________________________________________________ @@ -1289,7 +1410,6 @@ QString VP1MainWindow::request_saveChannelSnapshot(QString xLabel) return QString(); pm.save(filename); - return filename; } @@ -1331,7 +1451,7 @@ void VP1MainWindow::listenOnTcp() { QString err; if (!m_tcpserver.listen(err)) { - qDebug(err.toStdString().c_str()); + qDebug("%s", err.toStdString().c_str()); } } @@ -1452,10 +1572,11 @@ void VP1MainWindow::showMenu_loadConfFile() QMap<QString,QString> conffile2fullpath = availableFiles( ".vp1", "DATAPATH", "", "VP1CONFIGFILEPATH", true ); - if (conffile2fullpath.empty()) { - m_menu_loadConfFile->addAction("No .vp1 config files found")->setEnabled(false); - return; - } + #ifndef BUILDVP1LIGHT + if (conffile2fullpath.empty()) { + m_menu_loadConfFile->addAction("No .vp1 config files found")->setEnabled(false); + return; + } QStringList filelist(conffile2fullpath.keys()); filelist.sort(); @@ -1468,6 +1589,7 @@ void VP1MainWindow::showMenu_loadConfFile() act->setStatusTip(fullpath); connect(act,SIGNAL(triggered(bool)),this,SLOT(showMenu_loadConfFileItemSelected())); } + #endif m_menu_loadConfFile->addSeparator(); QAction * act_browse = m_menu_loadConfFile->addAction("&Browse..."); @@ -1560,9 +1682,22 @@ void VP1MainWindow::quickSetupTriggered() { VP1Msg::messageVerbose("VP1MainWindow::quickSetupTriggered()"); + QSettings settings("ATLAS", "VP1Light"); + QString plugfile, channelname, tabname; if (sender()==pushButton_quicksetup_geometrystudies||sender()==action_quicklaunch_Geometry_studies) { + + //Open geometry database selection dialog for VP1Light + #ifdef BUILDVP1LIGHT + if(settings.value("db/dbByEnv").toString().isEmpty()){ + VP1GeoDBSelection dbSelection; + dbSelection.exec(); + if(!dbSelection.result()) + return; + } + #endif // BUILDVP1LIGHT + plugfile="libVP1GeometryPlugin.so"; channelname="Geometry"; tabname = "Geometry"; @@ -1579,14 +1714,49 @@ void VP1MainWindow::quickSetupTriggered() channelname="Banks"; tabname = "StoreGate"; } else if (sender()==pushButton_quicksetup_3dcocktail||sender()==action_quicklaunch_3dcocktail) { - plugfile="libVP13DCocktailPlugin.so"; - channelname="3DCocktail"; - tabname = "3D Cocktail"; + #ifndef BUILDVP1LIGHT + plugfile="libVP13DCocktailPlugin.so"; + channelname="3DCocktail"; + tabname = "3D Cocktail"; + #else + //Open Geometry DB and AOD file selection dialog for VP1Light + if(settings.value("aod/aodByEnv").toString().isEmpty()){ + VP1AODSelection aodSelection; + aodSelection.exec(); + if(!aodSelection.result()) + return; + } + if(settings.value("db/dbByEnv").toString().isEmpty()){ + VP1GeoDBSelection dbSelection; + dbSelection.exec(); + if(!dbSelection.result()) + return; + } + m_scheduler->loadEvent(); + + pushButton_eventselect->setEnabled(true); + plugfile="libVP1LightPlugin.so"; + channelname="VP1Light"; + tabname = "Geometry/AOD"; + #endif // BUILDVP1LIGHT } else if (sender()==action_quicklaunch_trackcalo_commis) { plugfile="libVP13DCocktailPlugin.so"; channelname="TrackCalo"; tabname = "Track/Calo"; - } else if (sender()==pushButton_quicksetup_analysisstudies) { + } else if (sender()==pushButton_quicksetup_analysisstudies||sender()==action_quicklaunch_analysisstudies) { + + //Open AOD file selection dialog for VP1Light + #ifdef BUILDVP1LIGHT + if(settings.value("aod/aodByEnv").toString().isEmpty()){ + VP1AODSelection aodSelection; + aodSelection.exec(); + if(!aodSelection.result()) + return; + } + m_scheduler->loadEvent(); + pushButton_eventselect->setEnabled(true); + #endif // BUILDVP1LIGHT + plugfile="libVP1AODPlugin.so"; channelname="AOD"; tabname = "Analysis"; @@ -1595,14 +1765,18 @@ void VP1MainWindow::quickSetupTriggered() return; } -#ifdef __APPLE__ - if (plugfile.endsWith(".so")) - plugfile = plugfile.left(plugfile.count()-3)+".dylib"; -#endif + #ifdef __APPLE__ + if (plugfile.endsWith(".so")) + plugfile = plugfile.left(plugfile.count()-3)+".dylib"; + #endif //Check that the plugin is available: QMap<QString,QString> plugins2fullpath = availablePluginFiles(); + if(VP1Msg::debug()){ + qDebug() << "plugins2fullpath: " << plugins2fullpath; + } + if (!plugins2fullpath.contains(plugfile)) { QMessageBox::critical(0, "Error - could not locate plugin file: "+plugfile, "could not locate plugin file: " @@ -1663,14 +1837,15 @@ void VP1MainWindow::quickSetupTriggered() setUpdatesEnabled(save); - - } //_________________________________________________________________________________ void VP1MainWindow::updateEventControls() { pushButton_nextevent->setEnabled(okToProceedToNextEvent()); + #if defined BUILDVP1LIGHT + pushButton_previousevent->setEnabled(okToProceedToNextEvent()); + #endif } //_________________________________________________________________________________ @@ -1741,3 +1916,24 @@ void VP1MainWindow::addEventFile() newEventFile + " either does not exist or is not readable", QMessageBox::Ok,QMessageBox::Ok); } + +//_________________________________________________________________________________ +#ifdef BUILDVP1LIGHT +void VP1MainWindow::request_expertSettings(){ + VP1ExpertSettings es; + es.exec(); +} + +void VP1MainWindow::chooseEvent(){ + //Open event selection dialog for VP1Light + VP1SelectEvent selectEvent(m_scheduler->getTotEvtNr(), m_scheduler->getEvtNr()); + selectEvent.exec(); + int newEvtNr = selectEvent.result()-1; + + if( (newEvtNr >= 0) && (newEvtNr <= m_scheduler->getTotEvtNr()-1) ){ + m_scheduler->setEvtNr(newEvtNr); + nextEvent(); + qApp->quit(); + } +} +#endif // BUILDVP1LIGHT diff --git a/graphics/VP1/VP1Gui/src/VP1SelectEvent.cxx b/graphics/VP1/VP1Gui/src/VP1SelectEvent.cxx new file mode 100644 index 0000000000000000000000000000000000000000..6a811896a9e72ecae423153a2a45ed8cc702ad78 --- /dev/null +++ b/graphics/VP1/VP1Gui/src/VP1SelectEvent.cxx @@ -0,0 +1,68 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +////////////////////////////////////////////////////////////////////////// +// // +// Source file for class VP1SelectEvent // +// // +// Description: Dialog for the selection of a specific event in a file // +// // +// Author: Sebastian Andreas Merkt (sebastian.andreas.merkt@cern.ch) // +// Initial version: August 2018 // +// // +////////////////////////////////////////////////////////////////////////// + +#include "VP1Gui/VP1SelectEvent.h" + +#include <QPushButton> +#include <QGridLayout> + +#include <QtWidgets> +#include <QString> + +VP1SelectEvent::VP1SelectEvent(int totEvtNr, int evtNr, QWidget *parent) : QDialog(parent) +{ + //Set default dialog size + int nWidth = 400; + int nHeight = 200; + if (parent != NULL) + setGeometry(parent->x() + parent->width()/2 - nWidth/2, + parent->y() + parent->height()/2 - nHeight/2, + nWidth, nHeight); + else + resize(nWidth, nHeight); + + //Buttonbox to set Open, Cancel buttons + m_buttonBox = new QDialogButtonBox(this); + m_openButton = m_buttonBox->addButton(tr("&Select"), QDialogButtonBox::AcceptRole); + m_cancelButton = m_buttonBox->addButton(tr("&Cancel"),QDialogButtonBox::RejectRole); + connect(m_openButton, &QPushButton::clicked, this, &VP1SelectEvent::passEvtNr); + connect(m_cancelButton, &QPushButton::clicked, this, &VP1SelectEvent::reject); + + + m_spinBox = new QSpinBox(); + m_spinBox->setRange(1, totEvtNr); + m_spinBox->setSingleStep(1); + m_spinBox->setValue(evtNr+1); + + const QString line2 = QString::number(totEvtNr) + " events in file."; + + //Create the main layout + QGridLayout *mainLayout = new QGridLayout(this); + mainLayout->addWidget(new QLabel(tr("Select event:")), 0, 0); + mainLayout->addWidget(m_spinBox, 0, 1); + mainLayout->addWidget(new QLabel(line2), 1, 0); + mainLayout->addWidget(m_buttonBox, 2, 1); + +} + +void VP1SelectEvent::passEvtNr(){ + if( m_spinBox->value() != 0 ) { + VP1SelectEvent::done(m_spinBox->value()); + } +} + +void VP1SelectEvent::reject(){ + VP1SelectEvent::done(-1); +} diff --git a/graphics/VP1/VP1Gui/src/VP1TabManager.cxx b/graphics/VP1/VP1Gui/src/VP1TabManager.cxx index c72b69ef6b37057fc498e3fba58458b50b4bc83a..5cdd9e735c542027621827293f896bf197542096 100644 --- a/graphics/VP1/VP1Gui/src/VP1TabManager.cxx +++ b/graphics/VP1/VP1Gui/src/VP1TabManager.cxx @@ -469,7 +469,13 @@ IVP1ChannelWidget* VP1TabManager::selectedChannelWidget() const { //_______________________________________________________________________ IVP1ChannelWidget * VP1TabManager::addChannelToTab(QString channelbasename,QString tabname) { - if (m_d->channelwidget_2_dockwidget.size()&&VP1QtUtils::environmentVariableIsOn("VP1_DISALLOW_MULTIPLE_CHANNELS")) { + #if defined BUILDVP1LIGHT + bool checkDisallowMultipleChannels = VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_DISALLOW_MULTIPLE_CHANNELS"); + #else + bool checkDisallowMultipleChannels = VP1QtUtils::environmentVariableIsOn("VP1_DISALLOW_MULTIPLE_CHANNELS"); + #endif + + if (m_d->channelwidget_2_dockwidget.size()&&checkDisallowMultipleChannels) { QMessageBox::critical(0, "Error - Not allowed to open channel", "The possibility to launch multiple channels has been disabled by the environment variable VP1_DISALLOW_MULTIPLE_CHANNELS." " This was likely set since some badly written 3D drivers have been known to cause crashes when showing multiple 3D views." diff --git a/graphics/VP1/VP1Gui/src/vp1mainwindow.ui b/graphics/VP1/VP1Gui/src/vp1mainwindow.ui index 080aba0ec67858f2f0c8fecb772ab4c415da5afa..39fff7d9a5beef7ceefb3c994fac9e1a43473057 100644 --- a/graphics/VP1/VP1Gui/src/vp1mainwindow.ui +++ b/graphics/VP1/VP1Gui/src/vp1mainwindow.ui @@ -6,8 +6,8 @@ <rect> <x>0</x> <y>0</y> - <width>1002</width> - <height>650</height> + <width>1281</width> + <height>913</height> </rect> </property> <property name="windowTitle"> @@ -336,6 +336,30 @@ </item> <item> <layout class="QHBoxLayout" name="horizontalLayout_3"> + <item> + <widget class="QPushButton" name="pushButton_previousevent"> + <property name="toolTip"> + <string>Go back to previous event [Ctrl-P]</string> + </property> + <property name="text"> + <string/> + </property> + <property name="icon"> + <iconset resource="../src/vp1.qrc"> + <normaloff>:/vp1/icons/icons/back_32x32.png</normaloff>:/vp1/icons/icons/back_32x32.png</iconset> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_eventselect"> + <property name="toolTip"> + <string>Select an event in the current AOD file.</string> + </property> + <property name="enabled"> + <bool>true</bool> + </property> + </widget> + </item> <item> <widget class="QPushButton" name="pushButton_nextevent"> <property name="toolTip"> @@ -706,22 +730,21 @@ p, li { white-space: pre-wrap; } <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } -</style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> +</style></head><body style=" font-family:'Cantarell'; font-size:11pt; font-weight:400; font-style:normal;"> <table border="0" style="-qt-table-type: root; margin-top:4px; margin-bottom:4px; margin-left:4px; margin-right:4px;"> <tr> <td style="border: none;"> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"><br /></p> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> <p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans'; font-size:10pt;"><br /></p> -<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><br /></p></td></tr></table></body></html></string> +<p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:'Sans Serif'; font-size:9pt;"><br /></p></td></tr></table></body></html></string> </property> <property name="textInteractionFlags"> <set>Qt::TextSelectableByMouse</set> @@ -737,8 +760,8 @@ p, li { white-space: pre-wrap; } <rect> <x>0</x> <y>0</y> - <width>1002</width> - <height>22</height> + <width>1281</width> + <height>42</height> </rect> </property> <widget class="QMenu" name="menuConfiguration"> @@ -761,6 +784,7 @@ p, li { white-space: pre-wrap; } <addaction name="action_quicklaunch_Calo_studies"/> <addaction name="action_quicklaunch_Geometry_studies"/> <addaction name="action_quicklaunch_trackcalo_commis"/> + <addaction name="action_quicklaunch_analysisstudies"/> <addaction name="action_quicklaunch_Storegate_browser"/> <addaction name="separator"/> <addaction name="action_exit_VP1"/> @@ -868,6 +892,19 @@ p, li { white-space: pre-wrap; } <string>&Add event file ...</string> </property> </action> + <action name="actionEnableExpertSettings"> + <property name="text"> + <string>&EnableExpertSettings</string> + </property> + <property name="toolTip"> + <string>Open additional settings</string> + </property> + </action> + <action name="action_quicklaunch_analysisstudies"> + <property name="text"> + <string>A&nalysis Studies</string> + </property> + </action> </widget> <customwidgets> <customwidget> diff --git a/graphics/VP1/VP1HEPVis/CMakeLists.txt b/graphics/VP1/VP1HEPVis/CMakeLists.txt index e3b82cf22067978d458d99900d051e8360f2470e..cef68e6843ada257e717af52f02ad31a358f697b 100644 --- a/graphics/VP1/VP1HEPVis/CMakeLists.txt +++ b/graphics/VP1/VP1HEPVis/CMakeLists.txt @@ -10,13 +10,24 @@ atlas_subdir( VP1HEPVis ) # External dependencies: find_package( Coin3D ) -find_package( OpenGL ) +#find_package( OpenGL ) # not needed for SLC6. But is it needed for Ubuntu? +if ( APPLE ) + find_package(OpenGL REQUIRED) +endif() #message("VP1HEPVis: '${COIN3D_FOUND}' '${COIN3D_INCLUDE_DIRS}' #'${COIN3D_LIBRARIES}' '${COIN3D_LIBRARY}' '${COIN3D_INCLUDE_DIR}' ") # Component(s) in the package: -atlas_add_library( VP1HEPVis src/*.cxx - PUBLIC_HEADERS VP1HEPVis - INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} - LINK_LIBRARIES ${COIN3D_LIBRARIES} ${OPENGL_LIBRARIES} GL ) +if ( APPLE ) + atlas_add_library( VP1HEPVis src/*.cxx + PUBLIC_HEADERS VP1HEPVis + INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} + LINK_LIBRARIES ${COIN3D_LIBRARIES} ${OPENGL_LIBRARIES} ${OPENGL_gl_LIBRARY} ) +endif() +if ( UNIX AND NOT APPLE) + atlas_add_library( VP1HEPVis src/*.cxx + PUBLIC_HEADERS VP1HEPVis + INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} + LINK_LIBRARIES ${COIN3D_LIBRARIES} ${OPENGL_LIBRARIES} GL ) +endif() diff --git a/graphics/VP1/VP1Plugins/VP1GeometryPlugin/CMakeLists.txt b/graphics/VP1/VP1Plugins/VP1GeometryPlugin/CMakeLists.txt index 0de3845a215a617a22bfb41a8b578f1dbcce192f..0dd2daee87882aeb3feaddf0a314d19de01454cb 100644 --- a/graphics/VP1/VP1Plugins/VP1GeometryPlugin/CMakeLists.txt +++ b/graphics/VP1/VP1Plugins/VP1GeometryPlugin/CMakeLists.txt @@ -20,6 +20,15 @@ find_package( Qt5 COMPONENTS Core ) set( CMAKE_AUTOMOC TRUE ) # Build the library. +#<<<<<<< HEAD +#atlas_add_library( ${pkgName} ${pkgName}/*.h src/*.cxx src/*.qrc +# PUBLIC_HEADERS ${pkgName} +# INCLUDE_DIRS ${SOQT_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${QT5_INCLUDE_DIRS} +# PRIVATE_INCLUDE_DIRS tmpqt_extraheaders/ ${CMAKE_CURRENT_BINARY_DIR} ${ROOT_INCLUDE_DIRS} +# LINK_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets ${SOQT_LIBRARIES} ${COIN3D_LIBRARIES} GeoPrimitives TFPersistification +# PRIVATE_LINK_LIBRARIES VP1GuideLineSystems VP1GeometrySystems +#) +#======= atlas_add_library( VP1GeometryPlugin VP1GeometryPlugin/*.h src/*.cxx PUBLIC_HEADERS VP1GeometryPlugin diff --git a/graphics/VP1/VP1Plugins/VP1LightPlugin/CMakeLists.txt b/graphics/VP1/VP1Plugins/VP1LightPlugin/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..9f8f5395dce49697068a60f89fffb127203e0be5 --- /dev/null +++ b/graphics/VP1/VP1Plugins/VP1LightPlugin/CMakeLists.txt @@ -0,0 +1,39 @@ +################################################################################ +# Package: VP1LightPlugin +################################################################################ + +# Declare the package name: +atlas_subdir( VP1LightPlugin ) + +# Declare the package's dependencies: +atlas_depends_on_subdirs( PRIVATE + graphics/VP1/VP1Systems/VP1GeometrySystems + graphics/VP1/VP1Systems/VP1GuideLineSystems + graphics/VP1/VP1Systems/VP1AODSystems ) + +# Install files from the package: +atlas_install_headers( VP1LightPlugin ) + +# External dependencies: +find_package( Qt5 COMPONENTS Core OpenGL Gui Widgets HINTS ${QT5_ROOT} ) +find_package( SoQt ) +find_package( Coin3D ) + +# Generate UI files automatically: +set( CMAKE_AUTOUIC TRUE ) +# Generate MOC files automatically: +set( CMAKE_AUTOMOC TRUE ) + +# get the package name into the variable 'pkgName', to be used below +atlas_get_package_name( pkgName ) + + +# Build the library. +atlas_add_library( ${pkgName} ${pkgName}/*.h src/*.cxx src/*.qrc + PUBLIC_HEADERS ${pkgName} + INCLUDE_DIRS ${SOQT_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} ${QT5_INCLUDE_DIRS} + PRIVATE_INCLUDE_DIRS tmpqt_extraheaders/ ${CMAKE_CURRENT_BINARY_DIR} ${ROOT_INCLUDE_DIRS} + LINK_LIBRARIES Qt5::Core Qt5::Gui Qt5::Widgets ${SOQT_LIBRARIES} ${COIN3D_LIBRARIES} GeoPrimitives + PRIVATE_LINK_LIBRARIES VP1GuideLineSystems VP1GeometrySystems VP1AODSystems +) + diff --git a/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightChannel.h b/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightChannel.h new file mode 100755 index 0000000000000000000000000000000000000000..b8ec0eef816313654e2c4b6d25c7e3834ca27e3a --- /dev/null +++ b/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightChannel.h @@ -0,0 +1,32 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +///////////////////////////////////////////////////////////////// +// // +// Header file for class VP1LightChannel // +// // +// Author: Sebastian Merkt <sebastian.andreas.merkt@cern.ch> // +// // +// Initial version: December 2017 // +// // +///////////////////////////////////////////////////////////////// + +#ifndef VP1LIGHTCHANNEL_H +#define VP1LIGHTCHANNEL_H + +#include "VP1Base/IVP13DStandardChannelWidget.h" + +class VP1LightChannel : public IVP13DStandardChannelWidget { + + Q_OBJECT + +public: + + VP1LightChannel(); + void init(); + virtual ~VP1LightChannel(){} + +}; + +#endif // VP1LIGHTCHANNEL_H diff --git a/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightPlugin_VP1AutoFactory.h b/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightPlugin_VP1AutoFactory.h new file mode 100644 index 0000000000000000000000000000000000000000..94bfe87d67deb7eba0d97ce7e26cad64d7f17ed6 --- /dev/null +++ b/graphics/VP1/VP1Plugins/VP1LightPlugin/VP1LightPlugin/VP1LightPlugin_VP1AutoFactory.h @@ -0,0 +1,31 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef VP1LIGHTPlugin_VP1AutoFactory_H +#define VP1LIGHTPlugin_VP1AutoFactory_H + +#include <QObject> +#include <QStringList> + +#include "VP1Base/IVP1ChannelWidgetFactory.h" + +class VP1LightPlugin_VP1AutoFactory : public QObject, public IVP1ChannelWidgetFactory +{ + Q_OBJECT + + #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) + // Q_PLUGIN_METADATA(IID "VP1GeometryPlugin" FILE "") // apparently, FILE can be empty + Q_PLUGIN_METADATA(IID "VP1LightPlugin") // FILE can not be empty + # else + Q_EXPORT_PLUGIN2(pnp_vp1lightplugin_vp1autofactory, VP1LightPlugin_VP1AutoFactory) + #endif + + Q_INTERFACES(IVP1ChannelWidgetFactory) + +public: + virtual QStringList channelWidgetsProvided() const; + virtual IVP1ChannelWidget * getChannelWidget(const QString & channelwidget); +}; + +#endif diff --git a/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightChannel.cxx b/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightChannel.cxx new file mode 100755 index 0000000000000000000000000000000000000000..db09ae85b30b9b4f3f8acd549b54449c343d1b5b --- /dev/null +++ b/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightChannel.cxx @@ -0,0 +1,36 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +///////////////////////////////////////////////////////////////// +// // +// Header file for class VP1LightChannel // +// // +// Author: Sebastian Merkt <sebastian.andreas.merkt@cern.ch> // +// // +// Initial version: December 2017 // +// // +///////////////////////////////////////////////////////////////// + +#include "VP1LightPlugin/VP1LightChannel.h" +#include "VP1GeometrySystems/VP1GeometrySystem.h" +#include "VP1GuideLineSystems/VP1GuideLineSystem.h" +#include "VP1AODSystems/VP1AODSystem.h" +#include "VP1Base/VP1QtUtils.h" + +VP1LightChannel::VP1LightChannel() + : IVP13DStandardChannelWidget(VP1CHANNELNAMEINPLUGIN(VP1LightChannel,"VP1Light"), + "This channel displays the geometry and Analysis Objects (AOD).", + "Riccardo.Maria.Bianchi@cern.ch;Sebastian.Andreas.Merkt@cern.ch") +{ +} + +void VP1LightChannel::init() +{ + addSystem(new VP1GuideLineSystem); + addSystem(new VP1GeometrySystem); + addSystem(new VP1AODSystem); + if (VP1QtUtils::environmentVariableIsOn("VP1_SECOND_GEOMSYS")){ + addSystem(new VP1GeometrySystem(VP1GeoFlags::None,"AltGeo"),IVP13DStandardChannelWidget::StartDisabled); + } +} diff --git a/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightPlugin_VP1AutoFactory.cxx b/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightPlugin_VP1AutoFactory.cxx new file mode 100644 index 0000000000000000000000000000000000000000..cc31ab18c280e898a39168879abd9672e9f9fa84 --- /dev/null +++ b/graphics/VP1/VP1Plugins/VP1LightPlugin/src/VP1LightPlugin_VP1AutoFactory.cxx @@ -0,0 +1,22 @@ +/* + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration +*/ + +#include <QtPlugin> +#include "VP1LightPlugin/VP1LightPlugin_VP1AutoFactory.h" +#include "VP1LightPlugin/VP1LightChannel.h" + +QStringList VP1LightPlugin_VP1AutoFactory::channelWidgetsProvided() const +{ + return QStringList() + << "VP1Light" + ; +} + +IVP1ChannelWidget * VP1LightPlugin_VP1AutoFactory::getChannelWidget(const QString & channelwidget) +{ + if (channelwidget == "VP1Light") + return new VP1LightChannel(); + + return 0; +} diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/CMakeLists.txt b/graphics/VP1/VP1Systems/VP1AODSystems/CMakeLists.txt index 1778393339363b612063e142c8972a069d6239de..6ca48abd8e5d0db30066b5bfe8820d7002999736 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/CMakeLists.txt +++ b/graphics/VP1/VP1Systems/VP1AODSystems/CMakeLists.txt @@ -9,6 +9,7 @@ atlas_subdir( VP1AODSystems ) atlas_depends_on_subdirs( PUBLIC Event/xAOD/xAODMuon + Event/xAOD/xAODEgamma Event/xAOD/xAODTracking GaudiKernel graphics/VP1/VP1Base @@ -36,16 +37,30 @@ set( CMAKE_AUTOUIC TRUE ) # Generate MOC files automatically: set( CMAKE_AUTOMOC TRUE ) -# Component(s) in the package: -atlas_add_library( VP1AODSystems - VP1AODSystems/*.h src/*.h src/*.cxx - PUBLIC_HEADERS VP1AODSystems - PRIVATE_INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} - LINK_LIBRARIES xAODMuon xAODTracking GaudiKernel VP1Base StoreGateLib - Qt5::Core Qt5::Gui - PRIVATE_LINK_LIBRARIES ${COIN3D_LIBRARIES} GeoPrimitives EventPrimitives - xAODBase xAODCaloEvent xAODJet xAODMissingET PathResolver TrkExInterfaces - VP1HEPVis VP1Utils Qt5::Gui ) +if(NOT BUILDVP1LIGHT) + # Component(s) in the package: + atlas_add_library( VP1AODSystems + VP1AODSystems/*.h src/*.h src/*.cxx + PUBLIC_HEADERS VP1AODSystems + PRIVATE_INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} + LINK_LIBRARIES xAODMuon xAODEgamma xAODTracking GaudiKernel VP1Base StoreGateLib + Qt5::Core Qt5::Gui + PRIVATE_LINK_LIBRARIES ${COIN3D_LIBRARIES} GeoPrimitives EventPrimitives + xAODBase xAODCaloEvent xAODJet xAODMissingET PathResolver TrkExInterfaces + VP1HEPVis VP1Utils Qt5::Gui ) +endif() +if(BUILDVP1LIGHT) + # Component(s) in the package: + atlas_add_library( VP1AODSystems + src/*.h VP1AODSystems/*.h src/*cxx + PUBLIC_HEADERS VP1AODSystems + PRIVATE_INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} ${CMAKE_CURRENT_BINARY_DIR} + LINK_LIBRARIES xAODMuon xAODEgamma xAODTracking VP1Base + Qt5::Core Qt5::Gui + PRIVATE_LINK_LIBRARIES ${COIN3D_LIBRARIES} GeoPrimitives EventPrimitives + xAODBase xAODCaloEvent xAODJet xAODMissingET PathResolver xAODEventInfo + VP1HEPVis VP1Utils Qt5::Gui ) +endif() # Install files from the package: atlas_install_runtime( textures/*.png ) diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/AODSystemController.h b/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/AODSystemController.h index 2d4795481ca9f01c433238fab4e691fad1b08b45..bdf92aca504d91bf02c6edbdfefd458fc95b80d7 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/AODSystemController.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/AODSystemController.h @@ -20,7 +20,9 @@ #include "VP1Base/VP1Controller.h" #include <QFlags> -#include "GaudiKernel/ServiceHandle.h" +#ifndef BUILDVP1LIGHT + #include "GaudiKernel/ServiceHandle.h" +#endif class SoMaterial; class SoDrawStyle; diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/VP1AODSystem.h b/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/VP1AODSystem.h index 2052f90c4f1a2981348b448e2359a954cfcaea9a..2897a5dcab119f238ea5c9731d0a2f04563a81dc 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/VP1AODSystem.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/VP1AODSystems/VP1AODSystem.h @@ -16,8 +16,6 @@ #include "VP1Base/IVP13DSystemSimple.h" -#include "GaudiKernel/SystemOfUnits.h" - #include <QList> #include <vector> @@ -26,6 +24,7 @@ class SoMaterial; class SoCooperativeSelection; + #ifndef Q_MOC_RUN #include "xAODTracking/TrackParticleFwd.h" // #include "xAODCaloEvent/CaloClusterContainer.h" @@ -61,9 +60,11 @@ public: public slots: // FIXME - might be best to make a helper tool to do this, so we don't need to expose the xAOD objects in the interface here. // (Of course, that means we would then need to think of an alternate design to fill the collections in the system...) +#ifndef BUILDVP1LIGHT void updateAssociatedObjects(const QList<const xAOD::TrackParticle*>&); // void updateAssociatedObjects(QList<xAOD::CaloCluster*>&); void updateAssociatedObjects(const QList<const xAOD::MuonSegment*>&); +#endif // BUILDVP1LIGHT void dumpToJSON(); @@ -71,6 +72,7 @@ private slots: void visibleObjectsChanged(); void updateSelectionMode(); void updateShownTotMomentum(); + private: class Imp; diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/AODCollHandleBase.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/AODCollHandleBase.cxx index 0fd36c06745fd348aedbaa9f426082092a3ca29b..c8ead88e7301fbf9648a0ceec9bd424b93439d67 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/AODCollHandleBase.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/AODCollHandleBase.cxx @@ -28,6 +28,7 @@ #include "VP1Base/VP1QtInventorUtils.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" //SoCoin #include <Inventor/nodes/SoSeparator.h> @@ -223,7 +224,7 @@ void AODCollHandleBase::update3DObjectsOfAllHandles() { if (!isLoaded()) return; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("update3DObjectsOfAllHandles start"); largeChangesBegin(); handleIterationBegin(); @@ -391,7 +392,7 @@ QString AODCollHandleBase::provideSectionToolTip() const { //____________________________________________________________________ void AODCollHandleBase::collVisibilityChanged(bool vis) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("AODCollHandleBase::collVisibilityChanged => "+str(vis)); if (!m_sephelper) diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/AODSystemController.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/AODSystemController.cxx index 87ecfd83e988599be86eedfc3b6546d0ed01e578..b0f7c7b8126d258a04b495de51a6131cf3c48f45 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/AODSystemController.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/AODSystemController.cxx @@ -29,9 +29,11 @@ // VP1 #include "VP1Utils/VP1AvailableToolsHelper.h" -#include "VP1Utils/VP1ToolAccessHelper.h" -#include "VP1Utils/VP1JobConfigInfo.h" -#include "VP1Utils/VP1ParticleData.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1ToolAccessHelper.h" + #include "VP1Utils/VP1JobConfigInfo.h" + #include "VP1Utils/VP1ParticleData.h" +#endif #include "VP1Base/VP1QtUtils.h" #include "VP1Base/IVP1System.h" #include "VP1Base/VP1Serialise.h" diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/CaloClusterCollectionSettingsButton.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/CaloClusterCollectionSettingsButton.cxx index 42ef0212603e8ede155351fe73770e6fa932a8fc..a7c10c3b0a8284ccb91e15b6edcde72ffbba5ff8 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/CaloClusterCollectionSettingsButton.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/CaloClusterCollectionSettingsButton.cxx @@ -36,8 +36,14 @@ #include <QMimeData> #include <QDrag> -// ATLAS -#include "GaudiKernel/SystemOfUnits.h" +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif // Misc #include <iostream> @@ -726,7 +732,7 @@ QPair<bool,double> CaloClusterCollectionSettingsButton::scale() const const bool relative = m_d->ui_customsettings.radioButton_relativeScale->isChecked(); const bool logscale = m_d->ui_customsettings.checkBox_logscale->isChecked(); - double highestvisibleenergy=0*Gaudi::Units::eV; + double highestvisibleenergy=0*SYSTEM_OF_UNITS::eV; //// foreach(VP1StdCollection* stdcol, m_d->collWidget->visibleStdCollections()) { //// VP1CaloClusterCollection* col = dynamic_cast<VP1CaloClusterCollection*>(stdcol); @@ -750,17 +756,16 @@ QPair<bool,double> CaloClusterCollectionSettingsButton::scale() const //// } - if (m_d->gui_mostEnergetic!=highestvisibleenergy) { m_d->gui_mostEnergetic=highestvisibleenergy; - m_d->ui_customsettings.label_current_most_energetic->setText("Current value: "+QString::number(m_d->gui_mostEnergetic/Gaudi::Units::GeV,'f',2)+" GeV"); + m_d->ui_customsettings.label_current_most_energetic->setText("Current value: "+QString::number(m_d->gui_mostEnergetic/SYSTEM_OF_UNITS::GeV,'f',2)+" GeV"); } - const double length = (relative ? m_d->ui_customsettings.doubleSpinBox_lengthOfMostEnergetic->value()*Gaudi::Units::m - : m_d->ui_customsettings.doubleSpinBox_lengthOf10GeV->value()*Gaudi::Units::m ); - const double energy = relative ? highestvisibleenergy : 10*Gaudi::Units::GeV; - const double minscale = 1*Gaudi::Units::mm/(1*Gaudi::Units::GeV); - const double maxscale = 1*Gaudi::Units::m/(1*Gaudi::Units::MeV); + const double length = (relative ? m_d->ui_customsettings.doubleSpinBox_lengthOfMostEnergetic->value()*SYSTEM_OF_UNITS::m + : m_d->ui_customsettings.doubleSpinBox_lengthOf10GeV->value()*SYSTEM_OF_UNITS::m ); + const double energy = relative ? highestvisibleenergy : 10*SYSTEM_OF_UNITS::GeV; + const double minscale = 1*SYSTEM_OF_UNITS::mm/(1*SYSTEM_OF_UNITS::GeV); + const double maxscale = 1*SYSTEM_OF_UNITS::m/(1*SYSTEM_OF_UNITS::MeV); double scl; if (energy<=0) scl = maxscale; diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.cxx new file mode 100644 index 0000000000000000000000000000000000000000..bb7a2f724097f82221bdc5a921d98c9bc9ee8d6c --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.cxx @@ -0,0 +1,626 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +// Local +#include "VP1Base/VP1ColorSelectButton.h" +#include "ElectronCollectionSettingsButton.h" +#include "ui_perelectroncollectionsettings_form.h" +#include "ui_settings_cuts_form.h" + +//VP1 +#include "VP1Base/VP1QtInventorUtils.h" +#include "VP1Base/VP1Serialise.h" +#include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1QtInventorUtils.h" + +//SoCoin + +#include "Inventor/nodes/SoDrawStyle.h" +#include "Inventor/nodes/SoLightModel.h" +#include "Inventor/nodes/SoMaterial.h" + +// Qt +#include <QTimer> +#include <QByteArray> +#include <QBuffer> +#include <QDataStream> +#include <QMouseEvent> +#include <QDragEnterEvent> +#include <QDropEvent> +#include <QShortcut> +#include <QMimeData> +#include <QDrag> + +// Misc +#include <iostream> + +//____________________________________________________________________ +class ElectronCollectionSettingsButton::Imp { +public: + Imp():theclass(0),editwindow(0),matButton(0), defaultParametersMatButton(nullptr), + trackDrawStyle(0), trackLightModel(0),last_trackTubeRadius(0.0),last_cutOnlyVertexAssocTracks{}, + last_useDefaultCuts{},dim(0){ + //nop + } + ElectronCollectionSettingsButton * theclass; + QWidget * editwindow; + Ui::ElectronCollectionSettingsForm editwindow_ui; + + VP1MaterialButton* matButton;// main collection colour + VP1MaterialButton* defaultParametersMatButton; + + QList<VP1MaterialButton*> parameterTypeMatButtons;// enum used to access the specific button + + SoDrawStyle * trackDrawStyle; + SoLightModel * trackLightModel; + + //GUI - last values + double last_trackTubeRadius; + VP1Interval last_cutAllowedPt; + VP1Interval last_cutAllowedP; + VP1Interval last_cutAllowedEta; + QList<VP1Interval> last_cutAllowedPhi; + QList<unsigned> last_cutRequiredNHits; + bool last_cutOnlyVertexAssocTracks; + bool last_useDefaultCuts; + + int dim; + QPoint dragStartPosition; + + void initEditWindow(); +}; + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::Imp::initEditWindow() +{ + if (editwindow) + return; + theclass->messageVerbose("Initialising material editor dialog"); + editwindow = new QWidget(0,Qt::WindowStaysOnTopHint); + editwindow_ui.setupUi(editwindow); + matButton = editwindow_ui.pushButton_matButton; + + defaultParametersMatButton = editwindow_ui.matButton_parametersDefaultColour; + SoMaterial* defParamMat = new SoMaterial; // Default (for the moment) + defaultParametersMatButton->setMaterial(defParamMat); + editwindow_ui.frame_parameterTypeColours->hide(); + + // Set the default colours for the "colour by parameter type" section + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_2); + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_3); + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_4); + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_5); + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_6); + parameterTypeMatButtons.append(editwindow_ui.pushButton_matButton_parameters_default_colour_7); + QList<QColor> colours; + colours.append(QColor(0.0, 170.0, 255.0)); + colours.append(QColor(170, 85, 255)); + colours.append(QColor(255, 85, 0)); + colours.append(QColor(170, 0, 127)); + colours.append(QColor(170, 255, 0)); + colours.append(QColor(85, 0, 255)); + + for (unsigned int i=0; i<6;++i){ + SoMaterial * mat = VP1MaterialButton::createMaterial(colours.at(i)); + (parameterTypeMatButtons.at(i))->setMaterial(mat); + } +} + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::setMaterialText(const QString& t) +{ + if (m_d->editwindow) + m_d->editwindow->setWindowTitle(t); + setToolTip(t); +} + +//____________________________________________________________________ +ElectronCollectionSettingsButton::ElectronCollectionSettingsButton(QWidget * parent,int _dim) + : VP1MaterialButtonBase(parent,0,"VP1MaterialButton"), m_d(new Imp) +{ + m_d->dim = _dim; + + m_d->theclass = this; + m_d->initEditWindow(); + + //Draw Styles / Complexity: + VP1QtInventorUtils::setLimitsLineWidthSlider(m_d->editwindow_ui.horizontalSlider_trackWidth); + VP1QtInventorUtils::setValueLineWidthSlider(m_d->editwindow_ui.horizontalSlider_trackWidth,1.0); + + m_d->trackDrawStyle = new SoDrawStyle; + m_d->trackDrawStyle->setName("ElectronDrawStyle"); + m_d->trackDrawStyle->pointSize=5.0; + m_d->trackDrawStyle->ref(); + updateTrackDrawStyle(); + connect(m_d->editwindow_ui.horizontalSlider_trackWidth,SIGNAL(valueChanged(int)),this,SLOT(updateTrackDrawStyle())); + m_d->last_trackTubeRadius=trackTubeRadius(); + connect(m_d->editwindow_ui.checkBox_trackTubes,SIGNAL(toggled(bool)),this,SLOT(updateTrackTubeRadius())); + connect(m_d->editwindow_ui.doubleSpinBox_trackTubesRadiusMM,SIGNAL(valueChanged(double)),this,SLOT(updateTrackTubeRadius())); + + + m_d->trackLightModel = new SoLightModel; + m_d->trackLightModel->setName("ElectronLightModel"); + m_d->trackLightModel->ref(); + updateTrackLightModel(false); + connect(m_d->editwindow_ui.checkBox_tracksUseBaseLightModel,SIGNAL(toggled(bool)),this,SLOT(updateTrackLightModel(bool))); + connect(m_d->editwindow_ui.checkBox_hideactualpaths,SIGNAL(toggled(bool)),this,SLOT(updateHideActualTrackPath(bool))); + + #if defined BUILDVP1LIGHT + m_d->editwindow_ui.radioButton_existingParameters->setChecked(true); + m_d->editwindow_ui.radioButton_existingParameters->setEnabled(true); + m_d->editwindow_ui.radioButton_extrapolate->setChecked(false); + m_d->editwindow_ui.radioButton_extrapolate->setEnabled(false); + m_d->editwindow_ui.radioButton_extrapolate->setToolTip("Not available in VP1 Light"); + m_d->editwindow_ui.horizontalSlider_numBezierSteps->setValue(10); + m_d->editwindow_ui.horizontalSlider_numBezierSteps->setSliderPosition(10); + #endif //BUILDVP1LIGHT + + + // Propagation - for all of these, just emit the propagationOptionsChanged() signal and rely on clients checking to see what has changed. + connect(m_d->editwindow_ui.radioButton_existingParameters, SIGNAL(toggled(bool)), this, SIGNAL(propagationOptionsChanged())); + connect(m_d->editwindow_ui.radioButton_extrapolate, SIGNAL(toggled(bool)), this, SIGNAL(propagationOptionsChanged())); + connect(m_d->editwindow_ui.horizontalSlider_numBezierSteps,SIGNAL(valueChanged(int)),this, SIGNAL(propagationOptionsChanged())); + + // -> parameters + connect(m_d->editwindow_ui.checkBox_showparameters,SIGNAL(toggled(bool)),this,SLOT(possibleChange_showParameters())); + connect(m_d->editwindow_ui.checkBox_parameters_colourByType,SIGNAL(toggled(bool)),this,SLOT(possibleChange_parameterColours())); + + // -> cutAllowedP/Pt + connect(m_d->editwindow_ui.checkBox_cut_minpt,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutAllowedPt())); + connect(m_d->editwindow_ui.checkBox_cut_maxpt,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutAllowedPt())); + connect(m_d->editwindow_ui.doubleSpinBox_cut_minpt_gev,SIGNAL(valueChanged(double)),this,SLOT(possibleChange_cutAllowedPt())); + connect(m_d->editwindow_ui.doubleSpinBox_cut_maxpt_gev,SIGNAL(valueChanged(double)),this,SLOT(possibleChange_cutAllowedPt())); + connect(m_d->editwindow_ui.checkBox_cut_minpt,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutAllowedPt())); + connect(m_d->editwindow_ui.comboBox_momtype,SIGNAL(currentIndexChanged(int)),this,SLOT(possibleChange_cutAllowedPt())); + + // -> cutAllowedEta + connect(m_d->editwindow_ui.etaPhiCutWidget,SIGNAL(allowedEtaChanged(const VP1Interval&)),this,SLOT(possibleChange_cutAllowedEta())); + + // -> cutAllowedPhi + connect(m_d->editwindow_ui.etaPhiCutWidget,SIGNAL(allowedPhiChanged(const QList<VP1Interval>&)),this,SLOT(possibleChange_cutAllowedPhi())); + + // -> cutRequiredNHits(); + connect(m_d->editwindow_ui.checkBox_cut_nhits_pixel,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.checkBox_cut_nhits_sct,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.checkBox_cut_nhits_trt,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.checkBox_cut_nhits_muon,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.spinBox_cut_nhits_pixel,SIGNAL(valueChanged(int)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.spinBox_cut_nhits_sct,SIGNAL(valueChanged(int)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.spinBox_cut_nhits_trt,SIGNAL(valueChanged(int)),this,SLOT(possibleChange_cutRequiredNHits())); + connect(m_d->editwindow_ui.spinBox_cut_nhits_muon,SIGNAL(valueChanged(int)),this,SLOT(possibleChange_cutRequiredNHits())); + + // -> cutOnlyVertexAssocTracks + connect(m_d->editwindow_ui.checkBox_vertexAssociated,SIGNAL(toggled(bool)),this,SLOT(possibleChange_cutOnlyVertexAssocTracks())); + + connect(this,SIGNAL(clicked()),this,SLOT(showEditMaterialDialog())); + connect(m_d->editwindow_ui.pushButton_close,SIGNAL(clicked()),this,SLOT(showEditMaterialDialog())); + connect(m_d->matButton,SIGNAL(lastAppliedChanged()),this,SLOT(updateButton())); + connect(m_d->matButton,SIGNAL(lastAppliedChanged()),this,SIGNAL(lastAppliedChanged())); + setAcceptDrops(true); + + QTimer::singleShot(0, this, SLOT(updateButton())); + +} + +// QWidget& ElectronCollectionSettingsButton::editWindow() { +// if (!m_d->editwindow) +// initEditWindow(); +// return *(m_d->editwindow);color +// } +ElectronCollectionSettingsButton::~ElectronCollectionSettingsButton() +{ + delete m_d->editwindow; + m_d->trackDrawStyle->unref(); + m_d->trackLightModel->unref(); + delete m_d; +} + +void ElectronCollectionSettingsButton::updateButton() +{ + if (objectName().isEmpty()) + setObjectName("ElectronCollectionSettingsButton"); + messageVerbose("setColButtonProperties: color=" + str(m_d->matButton->lastAppliedDiffuseColour())); + VP1ColorSelectButton::setColButtonProperties(this,m_d->matButton->lastAppliedDiffuseColour(),m_d->dim); +} + +void ElectronCollectionSettingsButton::setDimension(int dim) +{ + if (m_d->dim == dim) + return; + m_d->dim = dim; + updateButton(); +} + +void ElectronCollectionSettingsButton::showEditMaterialDialog() +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + + if (m_d->editwindow->isHidden()) + m_d->editwindow->show(); + else + m_d->editwindow->hide(); +} + +bool ElectronCollectionSettingsButton::setMaterial(SoMaterial*mat) +{ + // std::cout<<"ElectronCollectionSettingsButton::setMaterial with mat="<<mat<<std::endl; + if (!m_d->matButton) m_d->initEditWindow(); + m_d->matButton->setMaterial(mat); + return true; +} + +void ElectronCollectionSettingsButton::copyValuesFromMaterial(SoMaterial*mat) +{ + if (!m_d->matButton) m_d->initEditWindow(); + m_d->matButton->setMaterial(mat); +} +double ElectronCollectionSettingsButton::lastAppliedTransparency() const +{ + if (!m_d->matButton) m_d->initEditWindow(); + return m_d->matButton->lastAppliedTransparency(); +} +double ElectronCollectionSettingsButton::lastAppliedShininess() const +{ + if (!m_d->matButton) m_d->initEditWindow(); + return m_d->matButton->lastAppliedShininess(); +} +double ElectronCollectionSettingsButton::lastAppliedBrightness() const +{ + if (!m_d->matButton) m_d->initEditWindow(); + return m_d->matButton->lastAppliedBrightness(); +} + +double ElectronCollectionSettingsButton::trackTubeRadius() const +{ + return m_d->editwindow_ui.checkBox_trackTubes->isChecked() ? + m_d->editwindow_ui.doubleSpinBox_trackTubesRadiusMM->value() : 0.0; +} + +void ElectronCollectionSettingsButton::updateTrackTubeRadius() +{ + if (m_d->last_trackTubeRadius==trackTubeRadius()) return; + m_d->last_trackTubeRadius=trackTubeRadius(); + messageVerbose("TrackTubeRadius changed to "+str(m_d->last_trackTubeRadius)); + emit trackTubeRadiusChanged(m_d->last_trackTubeRadius); + return; +} + +void ElectronCollectionSettingsButton::updateTrackDrawStyle() +{ + double val = VP1QtInventorUtils::getValueLineWidthSlider(m_d->editwindow_ui.horizontalSlider_trackWidth); + if (m_d->trackDrawStyle->lineWidth.getValue()!=val) + m_d->trackDrawStyle->lineWidth = val; +} + +void ElectronCollectionSettingsButton::updateTrackLightModel(bool base) +{ + if (m_d->trackLightModel->model.getValue()!=(base?SoLightModel::BASE_COLOR:SoLightModel::PHONG)) { + messageVerbose("TrackLightModel changed (base = "+str(base)); + if (base) + m_d->trackLightModel->model.setValue(SoLightModel::BASE_COLOR); + else + m_d->trackLightModel->model.setValue(SoLightModel::PHONG); + } +} + +void ElectronCollectionSettingsButton::updateHideActualTrackPath(bool hide) +{ + emit hideActualTrackPathChanged(hide); +} + + +SoDrawStyle * ElectronCollectionSettingsButton::trackDrawStyle() const +{ + return m_d->trackDrawStyle; +} + +SoLightModel * ElectronCollectionSettingsButton::trackLightModel() const +{ + return m_d->trackLightModel; +} + +bool ElectronCollectionSettingsButton::useExistingParameters() const{ + return m_d->editwindow_ui.radioButton_existingParameters->isChecked(); +} + +int ElectronCollectionSettingsButton::numOfStepsForInterpolation() const { + return m_d->editwindow_ui.horizontalSlider_numBezierSteps->value(); +} + +SoMaterial* ElectronCollectionSettingsButton::defaultParameterMaterial() const { + return m_d->defaultParametersMatButton->handledMaterials().at(0);// Only have one material per button. +} +SoMaterial* ElectronCollectionSettingsButton::parameterMaterial( xAOD::ParameterPosition position) const{ + return (m_d->parameterTypeMatButtons.at(static_cast<unsigned int>(position)))->handledMaterials().at(0);// Only have one material per button. +} + +// void setDefaultParameterMaterial(SoMaterial* mat) { +// // m_d->defaultParametersMatButton->setObjectName("matButton_default"); +// // m_d->defaultParametersMatButton->setToolTip(matButtonToolTip()); +// m_d->defaultParametersMatButton->setMaterial(mat); +// // connect(m_d->matButton,SIGNAL(lastAppliedChanged()),this,SLOT(possibleChangeMatTranspOrBrightness())); +// } +// +// void ElectronCollectionSettingsButton::setParameterMaterial(SoMaterial*, xAOD::ParameterPosition){ +// // FIXME! +// } + +bool ElectronCollectionSettingsButton::hideActualTrackPath() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + return m_d->editwindow_ui.checkBox_hideactualpaths->isChecked(); +} + +bool ElectronCollectionSettingsButton::showParameters() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + messageVerbose("ElectronCollectionSettingsButton::showParameters returning "+str(m_d->editwindow_ui.checkBox_showparameters->isChecked())); + return m_d->editwindow_ui.checkBox_showparameters->isChecked(); +} + +bool ElectronCollectionSettingsButton::colourParametersByType() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + messageVerbose("ElectronCollectionSettingsButton::colourParametersByType returning "+str(m_d->editwindow_ui.checkBox_parameters_colourByType->isChecked())); + return m_d->editwindow_ui.checkBox_parameters_colourByType->isChecked(); +} + + +bool ElectronCollectionSettingsButton::cutOnlyVertexAssocTracks() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + return m_d->editwindow_ui.checkBox_vertexAssociated->isChecked(); +} + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::mousePressEvent(QMouseEvent *event) +{ + if (event->button() == Qt::LeftButton) + m_d->dragStartPosition = event->pos(); + QPushButton::mousePressEvent(event); +} + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::dragEnterEvent(QDragEnterEvent *event) +{ + if (event->source()!=this && event->mimeData()->hasFormat("vp1/material")) + event->acceptProposedAction(); +} + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::mouseMoveEvent(QMouseEvent *event) +{ + if (!(event->buttons() & Qt::LeftButton)) + return; + if ((event->pos() - m_d->dragStartPosition).manhattanLength() + < QApplication::startDragDistance()) + return; + + QDrag *drag = new QDrag(this); + QMimeData *mimeData = new QMimeData; + + ///////////////////////////////////////////////////// + // For dragging state onto other material buttons: // + ///////////////////////////////////////////////////// + + QByteArray byteArray = saveState(); + + // buffer.close(); + mimeData->setData("vp1/material", byteArray); + + // //////////////////////////////////////////////////////// + // // For dragging c++ code for defining this material // + // // into e.g. an editor: // + // //////////////////////////////////////////////////////// + // + // QString s = "SoMaterial * mat = new SoMaterial;\n"; + // QString str_ambient = m_d->toSbColTxt(m_d->lastapplied_ambient); + // if (str_ambient!="SbColor(0.2,0.2,0.2)") + // s += "mat->ambientColor.setValue("+str_ambient+");\n"; + // QString str_diffuse = m_d->toSbColTxt(m_d->lastapplied_diffuse); + // if (str_diffuse!="SbColor(0.8,0.8,0.8)") + // s += "mat->diffuseColor.setValue("+str_diffuse+");\n"; + // QString str_specular = m_d->toSbColTxt(m_d->lastapplied_specular); + // if (str_specular!="SbColor(0,0,0)") + // s += "mat->specularColor.setValue("+str_specular+");\n"; + // QString str_emissive = m_d->toSbColTxt(m_d->lastapplied_emissive); + // if (str_emissive!="SbColor(0,0,0)") + // s += "mat->emissiveColor.setValue("+str_emissive+");\n"; + // QString str_shininess = m_d->printFloat(m_d->lastapplied_shininess/100.0); + // if (str_shininess!="0.2") + // s += "mat->shininess.setValue("+str_shininess+");\n"; + // QString str_transparency = m_d->printFloat(m_d->lastapplied_transparency/100.0); + // if (str_transparency!="0") + // s += "mat->transparency.setValue("+str_transparency+");\n"; + // mimeData->setText(s); + + //Execute drag: + drag->setMimeData(mimeData);//drag assumes ownership of mimeData + drag->exec(Qt::CopyAction | Qt::MoveAction); +} + +//____________________________________________________________________ +void ElectronCollectionSettingsButton::dropEvent(QDropEvent *event) +{ + QByteArray data = event->mimeData()->data("vp1/material"); + event->acceptProposedAction(); + restoreFromState(data); +} + + +QByteArray ElectronCollectionSettingsButton::saveState() const{ + // messageVerbose("getState"); + // if (m_d->editwindow_ui.checkBox_tracksUseBaseLightModel->isChecked()) messageVerbose("checked!"); + VP1Serialise serialise(1/*version*/); + + serialise.save(m_d->matButton); + // serialise.disableUnsavedChecks(); + serialise.save(m_d->editwindow_ui.horizontalSlider_trackWidth); + serialise.save(m_d->editwindow_ui.checkBox_trackTubes); + serialise.save(m_d->editwindow_ui.doubleSpinBox_trackTubesRadiusMM); + serialise.save(m_d->editwindow_ui.checkBox_tracksUseBaseLightModel); + serialise.save(m_d->editwindow_ui.checkBox_hideactualpaths); + + // Parameters + serialise.save(m_d->editwindow_ui.checkBox_showparameters); + serialise.save(m_d->editwindow_ui.checkBox_parameters_colourByType); + + serialise.widgetHandled(this); + serialise.warnUnsaved(this); + return serialise.result(); +} + +void ElectronCollectionSettingsButton::restoreFromState( const QByteArray& ba){ + + VP1Deserialise state(ba,systemBase()); + if (state.version()<0||state.version()>1) + return;//Ignore silently + state.restore(m_d->matButton); + state.restore(m_d->editwindow_ui.horizontalSlider_trackWidth); + state.restore(m_d->editwindow_ui.checkBox_trackTubes); + state.restore(m_d->editwindow_ui.doubleSpinBox_trackTubesRadiusMM); + state.restore(m_d->editwindow_ui.checkBox_tracksUseBaseLightModel); + state.restore(m_d->editwindow_ui.checkBox_hideactualpaths); + + // Parameters + state.restore(m_d->editwindow_ui.checkBox_showparameters); + state.restore(m_d->editwindow_ui.checkBox_parameters_colourByType); + + state.widgetHandled(this); + state.warnUnrestored(this); + + updateTrackTubeRadius(); + updateTrackLightModel(m_d->editwindow_ui.checkBox_tracksUseBaseLightModel); + updateButton(); + //FIXME - anything else need updating? +} + +//____________________________________________________________________ +VP1Interval ElectronCollectionSettingsButton::cutAllowedPt() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + if (!m_d->editwindow_ui.checkBox_cut_minpt) + return VP1Interval(); + + // will set range to negative if we have momcut=P + // if minCut unset then min=-inf + // if minCut set, and Pt selected, then min=-minCut + // if minCut set, and P selected, then min=-maxCut + // etc + bool isPCut = m_d->editwindow_ui.comboBox_momtype->currentText()=="P"; + + const double minFromInterface=m_d->editwindow_ui.doubleSpinBox_cut_minpt_gev->value()*1000; + const double maxFromInterface=m_d->editwindow_ui.doubleSpinBox_cut_maxpt_gev->value()*1000; + + double min=0.0,max=0.0; + if (!isPCut) { + //Pt cut + min = (m_d->editwindow_ui.checkBox_cut_minpt->isChecked() ? minFromInterface : -std::numeric_limits<double>::infinity()); + max = (m_d->editwindow_ui.checkBox_cut_maxpt->isChecked() ? maxFromInterface : std::numeric_limits<double>::infinity()); + } else { + min = (m_d->editwindow_ui.checkBox_cut_maxpt->isChecked() ? -maxFromInterface : -std::numeric_limits<double>::infinity()); + max = (m_d->editwindow_ui.checkBox_cut_minpt->isChecked() ? -minFromInterface : std::numeric_limits<double>::infinity()); + } + + //message("cutAllowedPt: min,max="+QString::number(min)+","+QString::number(max)); + + if (max<min) + return VP1Interval(); + + return VP1Interval( min, max );//fixme: closed interval?? +} + +//____________________________________________________________________ +VP1Interval ElectronCollectionSettingsButton::cutAllowedEta() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + return m_d->editwindow_ui.etaPhiCutWidget->allowedEta(); +} + +//____________________________________________________________________ +QList<VP1Interval> ElectronCollectionSettingsButton::cutAllowedPhi() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + return m_d->editwindow_ui.etaPhiCutWidget->allowedPhi(); +} + +//____________________________________________________________________ +QList<unsigned> ElectronCollectionSettingsButton::cutRequiredNHits() const +{ + if (!m_d->editwindow) + m_d->initEditWindow(); + unsigned npixel = m_d->editwindow_ui.checkBox_cut_nhits_pixel->isChecked() ? m_d->editwindow_ui.spinBox_cut_nhits_pixel->value() : 0; + unsigned nsct = m_d->editwindow_ui.checkBox_cut_nhits_sct->isChecked() ? m_d->editwindow_ui.spinBox_cut_nhits_sct->value() : 0; + unsigned ntrt = m_d->editwindow_ui.checkBox_cut_nhits_trt->isChecked() ? m_d->editwindow_ui.spinBox_cut_nhits_trt->value() : 0; + unsigned nmuon = m_d->editwindow_ui.checkBox_cut_nhits_muon->isChecked() ? m_d->editwindow_ui.spinBox_cut_nhits_muon->value() : 0; + QList<unsigned> l; + if (!npixel&&!nsct&&!ntrt&&!nmuon) + return l; + l << npixel << nsct << ntrt << nmuon; + return l; +} + + +void ElectronCollectionSettingsButton::possibleChange_cutAllowedPt() +{ + messageVerbose("possibleChange_cutAllowedPt() "); + + if (m_d->last_cutAllowedPt==cutAllowedPt()) return; + messageVerbose("cutAllowedPt() changed"); + m_d->last_cutAllowedPt= cutAllowedPt(); + emit cutAllowedPtChanged(m_d->last_cutAllowedPt); +} + +void ElectronCollectionSettingsButton::possibleChange_cutAllowedEta() +{ + if (m_d->last_cutAllowedEta==cutAllowedEta()) return; + messageVerbose("cutAllowedEta() changed"); + m_d->last_cutAllowedEta=cutAllowedEta(); + emit cutAllowedEtaChanged(m_d->last_cutAllowedEta); +} + +void ElectronCollectionSettingsButton::possibleChange_cutAllowedPhi() +{ + if (m_d->last_cutAllowedPhi==cutAllowedPhi()) return; + messageVerbose("cutAllowedPhi() changed"); + m_d->last_cutAllowedPhi=cutAllowedPhi(); + emit cutAllowedPhiChanged(m_d->last_cutAllowedPhi); +} + +void ElectronCollectionSettingsButton::possibleChange_cutRequiredNHits() +{ + if (m_d->last_cutRequiredNHits!=cutRequiredNHits()) return; + messageVerbose("cutRequiredNHits() changed"); + m_d->last_cutRequiredNHits=cutRequiredNHits(); + emit cutRequiredNHitsChanged(m_d->last_cutRequiredNHits); +} + +void ElectronCollectionSettingsButton::possibleChange_cutOnlyVertexAssocTracks() +{ + if (m_d->last_cutOnlyVertexAssocTracks!=cutOnlyVertexAssocTracks()) return; + messageVerbose("cutOnlyVertexAssocTracks() changed"); + m_d->last_cutOnlyVertexAssocTracks=cutOnlyVertexAssocTracks(); + emit cutOnlyVertexAssocTracksChanged(m_d->last_cutOnlyVertexAssocTracks); +} + +void ElectronCollectionSettingsButton::possibleChange_showParameters() +{ + messageVerbose("ElectronCollectionSettingsButton::possibleChange_showParameters emitting showParametersChanged "); + emit showParametersChanged(m_d->editwindow_ui.checkBox_showparameters->isChecked()); +} + +void ElectronCollectionSettingsButton::possibleChange_parameterColours() +{ + messageVerbose("ElectronCollectionSettingsButton::possibleChange_parameterColours emitting colourParametersByTypeChanged "); + emit colourParametersByTypeChanged(m_d->editwindow_ui.checkBox_parameters_colourByType->isChecked()); +} + diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.h new file mode 100644 index 0000000000000000000000000000000000000000..b6e660248eb20fcdbd130bbf23a673a9f728a271 --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/ElectronCollectionSettingsButton.h @@ -0,0 +1,116 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +#ifndef VP1AODSYSTEMS_ELECTRONCOLLSETTINGSBUTTON_H +#define VP1AODSYSTEMS_ELECTRONCOLLSETTINGSBUTTON_H + +#include "VP1Base/VP1MaterialButton.h" +#include "xAODTracking/TrackingPrimitives.h" + +class SoDrawStyle; +class SoLightModel; + +class ElectronCollectionSettingsButton : public VP1MaterialButtonBase { + + Q_OBJECT + +public: + + ElectronCollectionSettingsButton(QWidget * parent = 0, int dim = 25);//dim<=0 => Won't change sizepolicy + virtual ~ElectronCollectionSettingsButton(); + + void setDimension(int dim); + + // The below are necessary to fulfill the interface, but will just be passed onto the VP1MaterialButton owned by the ElectronCollectionSettingsButton form + virtual bool setMaterial(SoMaterial*); + virtual void copyValuesFromMaterial(SoMaterial*); + virtual double lastAppliedTransparency() const ; + virtual double lastAppliedShininess() const ; + virtual double lastAppliedBrightness() const; + + // GUI for track lines... + double trackTubeRadius() const;//0 => don't show tubes for tracks + bool hideActualTrackPath() const; + + // GUI for propagation + bool useExistingParameters() const; /// Returns true if the propagation should use the parameters already on the particle, or false if we should extrapolate from the 1st parameter + int numOfStepsForInterpolation() const; /// Returns the number of steps to use when interpolating between paramters (0 is no interpolation.) + + + // GUI for parameters + bool showParameters() const; + bool colourParametersByType() const; + + + // GUI for cuts + bool cutOnlyVertexAssocTracks() const; //!< Return true if this collection should only should tracks associated to a vertex + VP1Interval cutAllowedPt() const; + VP1Interval cutAllowedEta() const; + QList<VP1Interval> cutAllowedPhi() const;//All off: empty list. All on: list with one entry: ]-inf,inf[ + //Cuts for number of hits per subsystem: + QList<unsigned> cutRequiredNHits() const;//Empty list: no requirements. Otherwise a list + // with a length of four (pixel,sct,trt,muon) + + //Overall drawstyles, complexities and light models: + SoDrawStyle * trackDrawStyle() const; + SoLightModel * trackLightModel() const; + + // Parameters + SoMaterial* defaultParameterMaterial() const; + SoMaterial* parameterMaterial( xAOD::ParameterPosition) const; + + QByteArray saveState() const; //!< fill out with the state of the object (used for drag and drop etc) + void restoreFromState( const QByteArray& ); + + signals: + void trackTubeRadiusChanged(const double&); + void lastAppliedChanged(); // emitted when something related to material changes + void hideActualTrackPathChanged(bool); + + void showParametersChanged(bool); + void colourParametersByTypeChanged(bool); + + void cutAllowedPtChanged(const VP1Interval&); + void cutAllowedEtaChanged(const VP1Interval&); + void cutAllowedPhiChanged(const QList<VP1Interval>&); + void cutRequiredNHitsChanged(const QList<unsigned>&); + void cutOnlyVertexAssocTracksChanged(bool); + void propagationOptionsChanged(); + + public slots: + void showEditMaterialDialog(); + void setMaterialText(const QString&); + + protected slots: + void updateButton(); + +protected: + // void initEditWindow();//!< Make sure that edit window is constructed + void mousePressEvent(QMouseEvent *event); + void mouseMoveEvent(QMouseEvent *event); + void dropEvent(QDropEvent *event); + void dragEnterEvent(QDragEnterEvent *event); +private: + + class Imp; + Imp *m_d; + + private slots: + void updateTrackDrawStyle(); + void updateTrackLightModel(bool); + void updateTrackTubeRadius(); + void updateHideActualTrackPath(bool); + void possibleChange_cutAllowedPt(); + void possibleChange_cutAllowedEta(); + void possibleChange_cutAllowedPhi(); + void possibleChange_cutRequiredNHits(); + void possibleChange_cutOnlyVertexAssocTracks(); + void possibleChange_showParameters(); + void possibleChange_parameterColours(); + +}; + +#endif + + diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.cxx index 04375ddd61b8e8400376fef1b853d056f0ecf323..778cd0d5dbcbf9ba3b10880cb58ee6b8b0842ade 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration */ @@ -23,8 +23,10 @@ #include "VP1Base/VP1Msg.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif //Qt #include <QStringList> @@ -32,25 +34,40 @@ //xAOD #include "xAODCaloEvent/CaloClusterContainer.h" - // Coin3D #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoSwitch.h> #include <Inventor/nodes/SoMaterial.h> -//#include "Inventor/nodes/SoDrawStyle.h" -//#include "Inventor/nodes/SoLightModel.h" #include <Inventor/nodes/SoTexture2.h> - +// Athena #include "PathResolver/PathResolver.h" -#include "GaudiKernel/SystemOfUnits.h" + +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // so we will get, e.g., 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // so we will get, e.g., 'Gaudi::Units::cm' +#endif // BUILDVP1LIGHT //____________________________________________________________________ -QStringList IParticleCollHandle_CaloCluster::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::CaloClusterContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList IParticleCollHandle_CaloCluster::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::CaloCluster); + } +#else + QStringList IParticleCollHandle_CaloCluster::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::CaloClusterContainer>(); + + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ class IParticleCollHandle_CaloCluster::Imp { @@ -76,6 +93,9 @@ public: double last_highestEnergy; // double calculateHighestVisibleClusterEnergy() const; + #ifdef BUILDVP1LIGHT + QStringList caloClusterList; + #endif // BUILDVP1LIGHT double calo_start_r = theclass->calo_start_r; double calo_start_z = theclass-> calo_start_z; @@ -92,8 +112,8 @@ public: * DEFINITIONS */ //Fixme: Just some approximate values for now: -double IParticleCollHandle_CaloCluster::calo_start_r = 1.1*Gaudi::Units::m + 0.05*Gaudi::Units::m; -double IParticleCollHandle_CaloCluster::calo_start_z = 3.671*Gaudi::Units::m + 0.05*Gaudi::Units::m; +double IParticleCollHandle_CaloCluster::calo_start_r = 1.1*SYSTEM_OF_UNITS::m + 0.05*SYSTEM_OF_UNITS::m; +double IParticleCollHandle_CaloCluster::calo_start_z = 3.671*SYSTEM_OF_UNITS::m + 0.05*SYSTEM_OF_UNITS::m; double IParticleCollHandle_CaloCluster::calo_crack_eta = fabs(log(tan(0.5*atan(calo_start_r/calo_start_z)))); @@ -216,7 +236,7 @@ double IParticleCollHandle_CaloCluster::energyToLength(const double&energy) cons { VP1Msg::messageDebug("IParticleCollHandle_CaloCluster::energyToLength()"); - return std::max(1*Gaudi::Units::mm, m_d->scale.second*(m_d->scale.first?log(1+fabs(energy)):energy)); + return std::max(1*SYSTEM_OF_UNITS::mm, m_d->scale.second*(m_d->scale.first?log(1+fabs(energy)):energy)); } //____________________________________________________________________ @@ -412,11 +432,30 @@ bool IParticleCollHandle_CaloCluster::load() messageVerbose("loading CaloCluster collection"); //Get collection: - const xAOD::CaloClusterContainer * coll(0); - if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { - message("Error: Could not retrieve collection with key="+name()); - return false; - } + const xAOD::CaloClusterContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // // Get the name of the application: + // const char* appName = "VP1Light"; + + // // Initialize the environment: + // if( !xAOD::Init( appName ).isSuccess() ) { + // message("Failed to execute xAOD::Init"); + // return false; + // } + + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + QString errMsg = "Failed to retrieve " + name(); + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #endif // BUILDVP1LIGHT // // Retrieve the xAOD particles: // const xAOD::JetContainer* xaod = evtStore()->retrieve<const xAOD::JetContainer>( m_JetCollection ); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.h index 59f8971ae4224267c2cacc99af0de80e90e7acdb..e10ca03dd0d1ed9b50d46daf1c222d79c70a2ab6 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_CaloCluster.h @@ -25,9 +25,6 @@ // xAOD #include "xAODBase/ObjectType.h" - - - // FWD declarations //class SoMaterial; class CaloClusterCollectionSettingsButton; @@ -44,7 +41,8 @@ public: static QStringList availableCollections(IVP1System*);//For the collection widget. IParticleCollHandle_CaloCluster( AODSysCommonData *, - const QString& name, xAOD::Type::ObjectType type ); + const QString& name, xAOD::Type::ObjectType type ); + virtual ~IParticleCollHandle_CaloCluster(); virtual void init(VP1MaterialButtonBase* matBut=0);//reimplementations must start with a call to this. diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.cxx new file mode 100644 index 0000000000000000000000000000000000000000..171d3cabd4cbaa2cfd7a4d0534b8ea3376165e23 --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.cxx @@ -0,0 +1,266 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + + +//////////////////////////////////////////////////////////////// +// // +// Implementation of class IParticleCollHandle_Electron // +// // +// // +//////////////////////////////////////////////////////////////// + +//Local +#include "IParticleCollHandle_Electron.h" +#include "IParticleHandle_Electron.h" +#include "ElectronCollectionSettingsButton.h" +#include "AODSysCommonData.h" + +//xAOD +#include "xAODEgamma/ElectronContainer.h" + +//VP1 +#include "VP1Base/IVP1System.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif // BUILDVP1LIGHT + +//Qt +#include <QStringList> + +// SoCoin +#include <Inventor/C/errors/debugerror.h> +#include <Inventor/nodes/SoSeparator.h> +#include <Inventor/nodes/SoSwitch.h> +#include <Inventor/nodes/SoMaterial.h> +#include "Inventor/nodes/SoDrawStyle.h" +#include "Inventor/nodes/SoLightModel.h" + +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +#if defined BUILDVP1LIGHT + QStringList IParticleCollHandle_Electron::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::Electron); + } +#else + QStringList IParticleCollHandle_Electron::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::ElectronContainer>(); + } +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +class IParticleCollHandle_Electron::Imp { +public: + IParticleCollHandle_Electron * theclass; + int updateGUICounter; + ElectronCollectionSettingsButton* collSettingsButton; + bool shouldLoad; + + void possiblyUpdateGUI() {//Fixme: to IParticleCollHandleBase + if (!((updateGUICounter++)%50)) { + theclass->systemBase()->updateGUI(); + } + } +}; + +//____________________________________________________________________ +IParticleCollHandle_Electron::IParticleCollHandle_Electron(AODSysCommonData * cd, + const QString& name, xAOD::Type::ObjectType type, bool shouldLoad) + : IParticleCollHandleBase(cd,name,type), m_d(new Imp) +{ + m_d->theclass = this; + m_d->updateGUICounter = 0; + m_d->collSettingsButton=0; + m_d->shouldLoad = shouldLoad; + + //The object names should not contain all sorts of funky chars (mat button style sheets wont work for instance): + QString safetext(text()); + safetext.replace(' ','_'); + safetext.replace('[','_'); + safetext.replace(']','_'); + safetext.replace('/','_'); + safetext.replace('.','_'); + safetext.replace(',','_'); + safetext.replace('<','_'); + safetext.replace('>','_'); + safetext.replace('&','_'); + + // SoMaterial* mat + // = m_d->collSettingsButton->defaultParameterMaterial(); + // mat->setName(("IParticleCollHandle_Electron"+safetext).toStdString().c_str()); // Useful for debugging + // m_d->collSettingsButton->setDefaultParameterMaterial(m_d->defaultParametersMaterial); FIXME +} + +//____________________________________________________________________ +IParticleCollHandle_Electron::~IParticleCollHandle_Electron() +{ + delete m_d; + // FIXME - check that we're not leaking handles if (!m_d->shouldLoad){ + +} + +//____________________________________________________________________ +void IParticleCollHandle_Electron::init(VP1MaterialButtonBase*) +{ + // std::cout<<"IParticleCollHandle_Electron::init 1"<<std::endl; + m_d->collSettingsButton = new ElectronCollectionSettingsButton; + m_d->collSettingsButton->setMaterialText(name()); + // std::cout<<"Calling VP1StdCollection::init with m_d->collSettingsButton (ElectronCollectionSettingsButton)="<<m_d->collSettingsButton<<std::endl; + VP1StdCollection::init(m_d->collSettingsButton);//this call is required. Passing in m_d->collSettingsButton means we have the more complex button. + setupSettingsFromController(common()->controller()); + connect(this,SIGNAL(visibilityChanged(bool)),this,SLOT(collVisibilityChanged(bool))); + + // std::cout<<"IParticleCollHandle_Electron::init 2"<<std::endl; + // std::cout<<"swi: "<<collSwitch()<<std::endl; + // std::cout<<"sep: "<<collSep()<<std::endl; + // std::cout<<"mat: "<<material()<<std::endl; + + collSwitch()->addChild(m_d->collSettingsButton->trackLightModel()); + collSwitch()->addChild(m_d->collSettingsButton->trackDrawStyle()); +} + +void IParticleCollHandle_Electron::setupSettingsFromControllerSpecific(AODSystemController*) { + //cuts + connect(m_d->collSettingsButton,SIGNAL(cutAllowedPtChanged(const VP1Interval&)),this,SLOT(setCutAllowedPt(const VP1Interval&))); + setCutAllowedPt(m_d->collSettingsButton->cutAllowedPt()); + // + + connect(m_d->collSettingsButton,SIGNAL(cutAllowedEtaChanged(const VP1Interval&)),this,SLOT(setCutAllowedEta(const VP1Interval&))); + setCutAllowedEta(m_d->collSettingsButton->cutAllowedEta()); + // + + connect(m_d->collSettingsButton,SIGNAL(cutAllowedPhiChanged(const QList<VP1Interval>&)),this,SLOT(setCutAllowedPhi(const QList<VP1Interval>&))); + setCutAllowedPhi(m_d->collSettingsButton->cutAllowedPhi()); + + // Propagation + connect(m_d->collSettingsButton,SIGNAL(propagationOptionsChanged()), this,SLOT(propagationOptionsChanged())); + + // Parameters + connect(m_d->collSettingsButton,SIGNAL(showParametersChanged(bool)), this,SLOT(showParametersChanged(bool))); + connect(m_d->collSettingsButton,SIGNAL(colourParametersByTypeChanged(bool)),this,SLOT(showParametersChanged(bool))); + // Just reusing the same slot, since it doesn + +} + +void IParticleCollHandle_Electron::resetCachedValuesCuts() +{ + // TODO: it is not used so far! Check Other collections and update accordingly + + // kinetic cuts + setCutAllowedPt(m_d->collSettingsButton->cutAllowedPt()); + setCutAllowedEta(m_d->collSettingsButton->cutAllowedEta()); + setCutAllowedPhi(m_d->collSettingsButton->cutAllowedPhi()); + + // TODO: adding "propagation" and "parameters" settings as well?? +} + + +const ElectronCollectionSettingsButton& IParticleCollHandle_Electron::collSettingsButton() const { + if (!m_d->collSettingsButton){ + messageVerbose("No collSettingsButton set! Can't call init(), so crash is imminent..."); + } + return *m_d->collSettingsButton; +} + +//____________________________________________________________________ +bool IParticleCollHandle_Electron::load() +{ + if (!m_d->shouldLoad){ + messageVerbose("not loading Electron collection - contains associated objects."); + return true; + } + messageVerbose("loading Electron collection"); + + //Get collection: + const xAOD::ElectronContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + QString errMsg = "Failed to retrieve " + name(); + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve track particle collection with key="+name()); + return false; + } + #endif // BUILDVP1LIGHT + + // // Retrieve the xAOD particles: + // const xAOD::ElectronContainer* xaod = evtStore()->retrieve<const xAOD::ElectronContainer>( m_ElectronCollection ); + + // Check that the auxiliary store association was made successfully: + if( ! coll->hasStore() ) { + message("No auxiliary store got associated to the Electron container with key: " +name()); + } + + // This is needed for now, until the issues around the DV code are + // sorted out... + const_cast< xAOD::ElectronContainer* >( coll )->setStore( + ( SG::IAuxStore* ) coll->getConstStore() ); + + //Make appropriate trk::track handles: + // hintNumberOfTracksInEvent(coll->size()); + xAOD::ElectronContainer::const_iterator it, itEnd = coll->end(); + for ( it = coll->begin() ; it != itEnd; ++it) { + m_d->possiblyUpdateGUI(); + if (!*it) { + messageDebug("WARNING: Ignoring null Electron pointer."); + continue; + } + if ((*it)->charge()==0.0) { + messageDebug("WARNING: Ignoring Electron which claims to be neutral (charge()==0.0)."); + continue; + } + addHandle(new IParticleHandle_Electron(this,*it)); + } + + return true; +} + +//____________________________________________________________________ +bool IParticleCollHandle_Electron::cut(AODHandleBase* handle) +{ + messageVerbose("IParticleCollHandle_Electron::cut()"); + + if (!IParticleCollHandleBase::cut(handle)) + return false; + + //FIXME - add cuts on tracksummary etc. + + return true; +} + +void IParticleCollHandle_Electron::showParametersChanged(bool val) { + messageVerbose("IParticleCollHandle_Electron::showParametersChanged to "+str(val)); + update3DObjectsOfAllHandles(); +} + +void IParticleCollHandle_Electron::propagationOptionsChanged() { + messageVerbose("IParticleCollHandle_Electron::propagationOptionsChanged"); + update3DObjectsOfAllHandles(); +} + +void IParticleCollHandle_Electron::dumpToJSON( std::ofstream& str) const { + str << "\""<<name().toLatin1().data()<<"\":{"; + + unsigned int num=0; + for (auto handle : getHandlesList() ) { + if (handle->visible()) { + if (num) str <<",\n"; + handle->dumpToJSON(str); + } + } + + str << "}"; +} diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.h new file mode 100644 index 0000000000000000000000000000000000000000..5c6ee4c4c555c338be5cf7bfaf1c03b368e420c6 --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Electron.h @@ -0,0 +1,67 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + +//////////////////////////////////////////////////////////////// +// // +// Header file for class IParticleCollHandle_Electron // +// // +// Description: Collection handle for electron // +// // +// // +//////////////////////////////////////////////////////////////// + +#ifndef IPARTICLECOLLHANDLE_ELECTRON_H +#define IPARTICLECOLLHANDLE_ELECTRON_H + +#include "IParticleCollHandleBase.h" +#include "VP1AODSystems/VP1AODSystem.h" +#include "xAODBase/ObjectType.h" +#include "xAODTracking/TrackingPrimitives.h" + + +class SoMaterial; +class ElectronCollectionSettingsButton; + +class IParticleCollHandle_Electron : public IParticleCollHandleBase { + + Q_OBJECT + +public: + + static QStringList availableCollections(IVP1System*);//For the collection widget. + + /// shouldLoad is used to disable the call to load if the collhandle is for temporary (read: associated) electrons. + IParticleCollHandle_Electron( AODSysCommonData *, + const QString& name, xAOD::Type::ObjectType type, bool shouldLoad=true ); + + virtual ~IParticleCollHandle_Electron(); + + virtual void init(VP1MaterialButtonBase* matBut=0);//reimplementations must start with a call to this. + virtual void setupSettingsFromControllerSpecific(AODSystemController*); + virtual void dumpToJSON( std::ofstream& ) const ; + + const ElectronCollectionSettingsButton& collSettingsButton() const; + + // SoMaterial* defaultParameterMaterial() const; // Just forwards to CollSettingsButton, but avoids exposing it in interface. + // SoMaterial* parameterMaterial( xAOD::ParameterPosition) const; // Just forwards to CollSettingsButton, but avoids exposing it in interface. + + +protected: + virtual bool load(); + virtual bool cut(AODHandleBase*); + virtual QColor defaultColor() const { return QColor::fromRgbF(1.0f, 1.0f, 0.5f); } + +private slots: + void showParametersChanged(bool); + void propagationOptionsChanged(); + void resetCachedValuesCuts(); + +private: + + class Imp; + Imp *m_d; + +}; + +#endif diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.cxx index 95f34ab32809e62ca3df79ad63fd092078170d77..7df5c2b1d96c233476cde9d98b897474f3f61fbd 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.cxx @@ -23,8 +23,10 @@ #include "VP1Base/VP1Msg.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif // BUILDVP1LIGHT //Qt #include <QStringList> @@ -42,16 +44,35 @@ //#include "Inventor/nodes/SoLightModel.h" #include <Inventor/nodes/SoTexture2.h> - #include "PathResolver/PathResolver.h" - +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif //____________________________________________________________________ -QStringList IParticleCollHandle_Jet::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::JetContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList IParticleCollHandle_Jet::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::Jet); + } +#else + QStringList IParticleCollHandle_Jet::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::JetContainer>(); + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ class IParticleCollHandle_Jet::Imp { @@ -67,6 +88,9 @@ public: IParticleCollHandle_Jet * theclass; int updateGUICounter; JetCollectionSettingsButton* collSettingsButton; + #ifdef BUILDVP1LIGHT + QStringList jetList; + #endif // BUILDVP1LIGHT // settings double scale = 1.0; // dummy value. The actual default value is set in the IParticleHandle_Jet::Imp class definition. @@ -278,16 +302,16 @@ void IParticleCollHandle_Jet::setScale(const double& sca) if (m_d->scale == sca) return; - m_d->scale = std::max(1*Gaudi::Units::mm/(100*Gaudi::Units::GeV), - std::min(99*Gaudi::Units::m/(1*Gaudi::Units::MeV), + m_d->scale = std::max(1*SYSTEM_OF_UNITS::mm/(100*SYSTEM_OF_UNITS::GeV), + std::min(99*SYSTEM_OF_UNITS::m/(1*SYSTEM_OF_UNITS::MeV), // m_d->collSettingsButton->lengthOf100GeV() * Gaudi::Units::m/(100.0*Gaudi::Units::GeV))); - sca * Gaudi::Units::m/(100.0*Gaudi::Units::GeV))); + sca * SYSTEM_OF_UNITS::m/(100.0*SYSTEM_OF_UNITS::GeV))); if (!isLoaded()) return; - messageVerbose("Scale change: to "+str(m_d->scale/(Gaudi::Units::m/(100.0 * Gaudi::Units::GeV)))+" m/100GeV. Updating "+str(getHandlesList().count())+" jets"); - std::cout << "Scale change: d->scale/(Gaudi::Units::m/(100.0*Gaudi::Units::GeV)))" << "m/100GeV. Updating " << getHandlesList().count() << " jets" << std::endl; + messageVerbose("Scale change: to "+str(m_d->scale/(SYSTEM_OF_UNITS::m/(100.0 * SYSTEM_OF_UNITS::GeV)))+" m/100GeV. Updating "+str(getHandlesList().count())+" jets"); + std::cout << "Scale change: d->scale/(SYSTEM_OF_UNITS::m/(100.0*SYSTEM_OF_UNITS::GeV)))" << "m/100GeV. Updating " << getHandlesList().count() << " jets" << std::endl; largeChangesBegin(); handleIterationBegin(); @@ -442,13 +466,32 @@ bool IParticleCollHandle_Jet::load() messageVerbose("loading Jet collection"); //Get collection: - const xAOD::JetContainer * coll(0); + const xAOD::JetContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // // Get the name of the application: + // const char* appName = "VP1Light"; + + // // Initialize the environment: + // if( !xAOD::Init( appName ).isSuccess() ) { + // message("Failed to execute xAOD::Init"); + // return false; + // } + + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + QString errMsg = "Failed to retrieve " + name(); + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { message("Error: Could not retrieve Jet collection with key="+name()); return false; } else { messageDebug("Jet collection '"+name()+"' loaded"); } + #endif // BUILDVP1LIGHT // // Retrieve the xAOD particles: diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.h index 7a4a1052a6200f80c1445e9e85f97ecf16774daf..bc67edbf77ac10f68c5e8eb6d737486ca4c1c250 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Jet.h @@ -33,11 +33,12 @@ public: IParticleCollHandle_Jet( AODSysCommonData *, const QString& name, xAOD::Type::ObjectType type ); + virtual ~IParticleCollHandle_Jet(); virtual void init(VP1MaterialButtonBase* matBut=0);//reimplementations must start with a call to this. virtual void setupSettingsFromControllerSpecific(AODSystemController*); - virtual void dumpToJSON( std::ofstream& ) const ; + virtual void dumpToJSON( std::ofstream& ) const ; const JetCollectionSettingsButton& collSettingsButton() const; bool isRandomColors() const; diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Muon.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Muon.cxx index b0809c22b979fbe9bec8e75927e3361faed3bdc8..d5f14306542727a26c770c56603d61ec79245d5c 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Muon.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_Muon.cxx @@ -22,8 +22,10 @@ //VP1 #include "VP1Base/IVP1System.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif // BUILDVP1LIGHT //Qt #include <QStringList> @@ -36,11 +38,24 @@ #include "Inventor/nodes/SoDrawStyle.h" #include "Inventor/nodes/SoLightModel.h" +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + //____________________________________________________________________ -QStringList IParticleCollHandle_Muon::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::MuonContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList IParticleCollHandle_Muon::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::Muon); + } +#else + QStringList IParticleCollHandle_Muon::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::MuonContainer>(); + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ class IParticleCollHandle_Muon::Imp { @@ -164,11 +179,21 @@ bool IParticleCollHandle_Muon::load() messageVerbose("loading Muon collection"); //Get collection: - const xAOD::MuonContainer * coll(0); - if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { - message("Error: Could not retrieve Muon collection with key="+name()); - return false; - } + const xAOD::MuonContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve Muon collection with key="+name()); + return false; + } + #endif // BUILDVP1LIGHT // // Retrieve the xAOD particles: // const xAOD::MuonContainer* xaod = evtStore()->retrieve<const xAOD::MuonContainer>( m_MuonCollection ); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_TrackParticle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_TrackParticle.cxx index e6ed8a1d3aeef2e4186422a39704635d1b140d83..821b445f239c170f3879228267bc21e9ef154fb3 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_TrackParticle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleCollHandle_TrackParticle.cxx @@ -21,8 +21,10 @@ //VP1 #include "VP1Base/IVP1System.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif // BUILDVP1LIGHT //Qt #include <QStringList> @@ -35,11 +37,24 @@ #include "Inventor/nodes/SoDrawStyle.h" #include "Inventor/nodes/SoLightModel.h" +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + //____________________________________________________________________ -QStringList IParticleCollHandle_TrackParticle::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::TrackParticleContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList IParticleCollHandle_TrackParticle::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::TrackParticle); + } +#else + QStringList IParticleCollHandle_TrackParticle::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::TrackParticleContainer>(); + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ class IParticleCollHandle_TrackParticle::Imp { @@ -165,11 +180,20 @@ bool IParticleCollHandle_TrackParticle::load() messageVerbose("loading TrackParticle collection"); //Get collection: - const xAOD::TrackParticleContainer * coll(0); - if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { - message("Error: Could not retrieve track particle collection with key="+name()); - return false; - } + const xAOD::TrackParticleContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve track particle collection with key="+name()); + return false; + } + #endif // BUILDVP1LIGHT // // Retrieve the xAOD particles: // const xAOD::TrackParticleContainer* xaod = evtStore()->retrieve<const xAOD::TrackParticleContainer>( m_TrackParticleCollection ); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_CaloCluster.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_CaloCluster.cxx index 3599f8ad56b087fec5a99c8ac189249db1f4a0f2..7d4a3e0d457c0028fb568d2bc4c0138b79dd915e 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_CaloCluster.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_CaloCluster.cxx @@ -34,7 +34,14 @@ #include <Inventor/nodes/SoSwitch.h> #include <SoDebug.h> // it's stored at /afs/cern.ch/sw/lcg/external/coin3d/3.1.3p2/x86_64-slc6-gcc47-opt/include/SoDebug.h - +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif //____________________________________________________________________ @@ -121,7 +128,8 @@ bool IParticleHandle_CaloCluster::isConsiderTransverseEnergies() const //void IParticleHandle_CaloCluster::setScale( const double& sc) { m_d->scale = sc; } //____________________________________________________________________ -//void IParticleHandle_CaloCluster::setMaxR(const double& maxR) { m_d->maxR = maxR * Gaudi::Units::m; } +//void IParticleHandle_CaloCluster::setMaxR(const double& maxR) { m_d->maxR = maxR * SYSTEM_OF_UNITS::m; } + //____________________________________________________________________ //void IParticleHandle_CaloCluster::rerandomiseMaterial() {m_d->rerandomiseMaterial(); } @@ -230,6 +238,7 @@ void IParticleHandle_CaloCluster::Imp::createShapeFromParameters(const IParticle VP1Msg::messageVerbose("IParticleHandle_CaloCluster::Imp::createShapeFromParameters()"); if (!m_genericBox) { + SoGenericBox::initClass(); m_genericBox = new SoGenericBox(); m_genericBox->drawEdgeLines = coll_handle->showOutlines(); m_genericBox->forceEdgeLinesInBaseColour = true; @@ -403,12 +412,12 @@ QStringList IParticleHandle_CaloCluster::clicked() const // they go in the "Information" column in the Browser window // see: http://acode-browser.usatlas.bnl.gov/lxr/source/atlas/Event/xAOD/xAODCaloEvent/xAODCaloEvent/versions/CaloCluster_v1.h // - l +=" - pt: " + QString::number(m_d->m_cluster->pt() / Gaudi::Units::GeV) +" [GeV]"; - l +=" - et: " + QString::number(m_d->et() / Gaudi::Units::GeV) +" [GeV]"; + l +=" - pt: " + QString::number(m_d->m_cluster->pt() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; + l +=" - et: " + QString::number(m_d->et() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; l +=" - eta: " + QString::number(m_d->eta()); l +=" - phi: " + QString::number(m_d->phi()); - l +=" - m: " + QString::number(m_d->m_cluster->m() / Gaudi::Units::GeV) +" [GeV] (invariant mass of the particle)"; - l +=" - e: " + QString::number(m_d->m_cluster->e() / Gaudi::Units::GeV) +" [GeV] (total energy of the particle)"; + l +=" - m: " + QString::number(m_d->m_cluster->m() / SYSTEM_OF_UNITS::GeV) +" [GeV] (invariant mass of the particle)"; + l +=" - e: " + QString::number(m_d->m_cluster->e() / SYSTEM_OF_UNITS::GeV) +" [GeV] (total energy of the particle)"; l +=" - rapidity: " + QString::number(m_d->m_cluster->rapidity()); l +=" - type: " + QString::number(m_d->m_cluster->type()); l +=" - ClusterSize: " + QString::number(m_d->m_cluster->clusterSize()); @@ -473,10 +482,10 @@ QString IParticleHandle_CaloCluster::shortInfo() const // info and parameters, // they go in the "Information" column in the Browser window dParameters +="pt: "; - dParameters += QString::number(m_d->m_cluster->pt() / Gaudi::Units::GeV); + dParameters += QString::number(m_d->m_cluster->pt() / SYSTEM_OF_UNITS::GeV); dParameters +=", et: "; - dParameters += QString::number(m_d->m_cluster->et() / Gaudi::Units::GeV); + dParameters += QString::number(m_d->m_cluster->et() / SYSTEM_OF_UNITS::GeV); dParameters +=", eta: "; dParameters += QString::number(m_d->m_cluster->eta()); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.cxx new file mode 100644 index 0000000000000000000000000000000000000000..13b6ffa31cb116e006c9dce103aa6d58b0f6635a --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.cxx @@ -0,0 +1,614 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + + +//////////////////////////////////////////////////////////////// +// // +// Implementation of class IParticleHandle_Electron // +// // +// // +//////////////////////////////////////////////////////////////// + +// Local +#include "IParticleHandle_Electron.h" +#include "IParticleCollHandle_Electron.h" +#include "AODSysCommonData.h" +#include "ElectronCollectionSettingsButton.h" + +//VP1 +#include "VP1Base/VP1Msg.h" + +//SoCoin +#include <Inventor/C/errors/debugerror.h> +#include <Inventor/nodes/SoLineSet.h> +#include <Inventor/nodes/SoPointSet.h> +#include <Inventor/nodes/SoVertexProperty.h> +#include <Inventor/nodes/SoMaterial.h> +#include <Inventor/nodes/SoCone.h> +#include <Inventor/nodes/SoSeparator.h> +#include <Inventor/nodes/SoTranslation.h> +#include <Inventor/nodes/SoRotationXYZ.h> + +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // so we will get, e.g., 'GeoModelKernelUnits::cm' +#else + //Athena + #include "TrkExInterfaces/IExtrapolationEngine.h" + #define SYSTEM_OF_UNITS Gaudi::Units // so we will get, e.g., 'Gaudi::Units::cm' +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +class IParticleHandle_Electron::Imp { +public: + IParticleHandle_Electron * theclass; + const xAOD::Electron * electron; + IParticleCollHandle_Electron* collHandle; + + SoSeparator * sep; // everything hangs from this. + SoLineSet * line;//This represents the line(s) representing the electron. Can be interpolated. + QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> > parametersAndPositions; // cache - do we really need this? + QList< Amg::Vector3D > positionsToWrite; // FIXME - this is just a quick hack so we can easily dump the points used in the lines to JSON + +}; + +//____________________________________________________________________ +IParticleHandle_Electron::IParticleHandle_Electron(IParticleCollHandleBase* ch, const xAOD::Electron *tp) + : IParticleHandleBase(ch), m_d(new Imp) +{ + m_d->theclass = this; + m_d->electron = tp; + m_d->collHandle = dynamic_cast<IParticleCollHandle_Electron*>(ch); + m_d->sep=0; + m_d->line=0; +} + +//____________________________________________________________________ +IParticleHandle_Electron::~IParticleHandle_Electron() +{ + if (m_d->line) m_d->line->unref(); + if (m_d->sep) m_d->sep->unref(); + delete m_d; +} + +bool IParticleHandle_Electron::has3DObjects(){ + return 0!=m_d->sep; +} +void IParticleHandle_Electron::clear3DObjects(){ + VP1Msg::messageVerbose("IParticleHandle_Electron::clear3DObjects()"); + + if (m_d->line) { + m_d->line->unref(); + m_d->line=0; + } + if (m_d->sep) { + m_d->sep->unref(); + m_d->sep=0; + } + + // Wipe caches + m_d->positionsToWrite.clear(); + m_d->parametersAndPositions.clear(); +} + +SoNode* IParticleHandle_Electron::nodes(){ + VP1Msg::messageVerbose("IParticleHandle_Electron::nodes with m_d->sep="+VP1Msg::str(m_d->sep)); + + if (m_d->sep) { + VP1Msg::messageVerbose("IParticleHandle_Electron::nodes() - already have sep so not doing anything."); + return m_d->sep; + } + if (!m_d->sep) { + m_d->sep = new SoSeparator(); + m_d->sep->ref(); + } + + bool fromTrack=m_d->collHandle->collSettingsButton().useExistingParameters(); + + if (fromTrack) { + addLine_FromElectron(); + } else { + #ifndef BUILDVP1LIGHT + VP1Msg::messageVerbose( "addLine_Extrapolated()" ); + addLine_Extrapolated(); + #endif // BUILDVP1LIGHT + } + + if (m_d->collHandle->collSettingsButton().showParameters()) + addParameterShapes(); + + return m_d->sep; +} + +void IParticleHandle_Electron::addParameterShapes(){ + // Points: + SoPointSet* parameterPoints = 0; + SoVertexProperty * vertices2 = 0; + + // std::cout<<"showing parameters... have "<<m_d->electron->numberOfParameters()+1<<" to draw"<<std::endl; + + // Okay. so let's make the containers to hold them... + parameterPoints = new SoPointSet; + vertices2 = new SoVertexProperty; + + int i = 0; + bool colourByParamType = m_d->collHandle->collSettingsButton().colourParametersByType(); + QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> > parAndPoses = parametersAndPositions(); + + std::pair<xAOD::ParameterPosition, Amg::Vector3D> parpos; + foreach (parpos, parAndPoses ) { + Amg::Vector3D pos = parpos.second; + + if (colourByParamType) { + // Okay, so we treat each point separately & add materials as we go... + m_d->sep->addChild(m_d->collHandle->collSettingsButton().parameterMaterial(parpos.first)); + vertices2->vertex.set1Value(0,pos.x(),pos.y(),pos.z()); + parameterPoints->numPoints=1; + parameterPoints->vertexProperty = vertices2; + m_d->sep->addChild(parameterPoints); + parameterPoints = new SoPointSet; // reset for next point + vertices2 = new SoVertexProperty; + } else { // Not colouring by type + vertices2->vertex.set1Value(i++,pos.x(),pos.y(),pos.z()); + } + } + + if (colourByParamType) { + // In this case, we don't need the last Nodes created in the loop. + parameterPoints->unref(); + vertices2->unref(); + + } else { + parameterPoints->numPoints=i; + parameterPoints->vertexProperty = vertices2; + m_d->sep->addChild(static_cast<IParticleCollHandle_Electron*>(collHandle())->collSettingsButton().defaultParameterMaterial()); + m_d->sep->addChild(parameterPoints); + } +} + +void IParticleHandle_Electron::addLine_FromElectron(){ + + std::vector<Amg::Vector3D> positions, momenta; + + const xAOD::TrackParticle* trackparticle = m_d->electron->trackParticle(); + if (!trackparticle) { + VP1Msg::message("ERROR : no primary track particle associated with this Electron. Can't visualise it."); + return; + } + +#if defined BUILDVP1LIGHT + positions.push_back(position()); + momenta. push_back(momentum()); +#else + const Trk::Perigee& peri = trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... + + positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); // TODO: move to position()? + momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); + // std::cout<<"i:"<<0<<"/"<<m_d->electron->numberOfParameters()+1<<": ("<<peri.position().x()<<","<<peri.position().y()<<","<<peri.position().z()<<")"<<std::endl; +#endif // BUILDVP1LIGHT + + VP1Msg::messageVerbose("IParticleHandle_Electron::addLine_FromElectron - has "+QString::number(trackparticle->numberOfParameters())+" extra parameters."); + for (unsigned int i=0; i<trackparticle->numberOfParameters() ; ++i){ + // std::cout<<"i:"<<i+1<<"/"<<m_d->electron->numberOfParameters()+1<<": ("<<m_d->electron->parameterX(i)<<","<<m_d->electron->parameterY(i)<<","<<m_d->electron->parameterZ(i)<<")"<<std::endl; + + positions.push_back(Amg::Vector3D(trackparticle->parameterX(i), + trackparticle->parameterY(i), + trackparticle->parameterZ(i))); + momenta.push_back(Amg::Vector3D( trackparticle->parameterPX(i), + trackparticle->parameterPY(i), + trackparticle->parameterPZ(i))); + } // end of loop. + + // if ( positions.size()<2 ) VP1Msg::messageVerbose("IParticleHandle_Electron::addLine_FromElectron - WARNING - not enough points to make a line."); + + fillLineFromSplineFit(positions, momenta); + + // std::cout<<"About to add "<<collHandleTrk->material()<<std::endl; + m_d->sep->addChild(m_d->collHandle->material()); + // ^^ FIXME - should rearrange so we don't need to reset material + + m_d->sep->addChild(m_d->line); +} + +void IParticleHandle_Electron::linear(Amg::Vector3D& output, Amg::Vector3D& a, Amg::Vector3D& b, float t){ + float x = a.x() + (b.x()-a.x())*t; + float y = a.y() + (b.y()-a.y())*t; + float z = a.z() + (b.z()-a.z())*t; + output = Amg::Vector3D(x,y,z); +} + +void IParticleHandle_Electron::bezier(Amg::Vector3D& output, Amg::Vector3D& a, Amg::Vector3D& b, Amg::Vector3D& c, Amg::Vector3D& d, float t){ + // DeCasteljau subdivision + Amg::Vector3D ab,bc,cd,abbc,bccd; + linear(ab, a,b,t); // point between a and b (green) + linear(bc, b,c,t); // point between b and c (green) + linear(cd, c,d,t); // point between c and d (green) + linear(abbc, ab,bc,t); // point between ab and bc (blue) + linear(bccd, bc,cd,t); // point between bc and cd (blue) + linear(output, abbc,bccd,t); // point on the bezier-curve (black) +} + +void IParticleHandle_Electron::fillLineFromSplineFit(const std::vector<Amg::Vector3D>& positions, const std::vector<Amg::Vector3D>&momenta){ + int iver(0); + unsigned int npointsused(0); + // Create new lineset etc + m_d->line = new SoLineSet(); + m_d->line->ref(); + + // For the moment, lets just draw the lines. + SoVertexProperty * vertices = new SoVertexProperty(); + + // std::cout<<"About to loop over "<<positions.size()<<" points to make line"<<std::endl; + // for (unsigned int i=0; i<positions.size(); ++i){ + // std::cout<<"i: "<<i<<" at ("<<positions[i].x()<<","<<positions[i].y()<<","<<positions[i].z()<<")"<<" \tmom = ("<<momenta[i].x()<<","<<momenta[i].y()<<","<<momenta[i].z()<<")"<<std::endl; + // } + + // std::cout<<"Now do interpolations."<<std::endl; + + bool useExistingParams = m_d->collHandle->collSettingsButton().useExistingParameters(); + + for (unsigned int i=1; i<positions.size(); ++i){ + // std::cout<<"i: "<<i<<" at ("<<positions[i].x()<<","<<positions[i].y()<<","<<positions[i].z()<<")"<<" \tmom = ("<<momenta[i].x()<<","<<momenta[i].y()<<","<<momenta[i].z()<<")"<<std::endl; + + if (useExistingParams){ + float scale = ( (positions[i]-positions[i-1]).mag() )/3.0; // want to split curve into three parts + Amg::Vector3D p0(positions[i-1]); // first position + Amg::Vector3D p1(positions[i-1]+(scale * momenta[i-1].unit() ) ); // move 1/3 or the way towards next point, but following momentum direction + Amg::Vector3D p2(positions[i] -(scale * momenta[i].unit() ) ); // back 1/3 from second point, but following momentum direction + Amg::Vector3D p3(positions[i]); + // std::cout<<"p0: ("<<p0[0]<<", "<<p0[1]<<", "<<p0[2]<<") "<<std::endl; + // std::cout<<"p1: ("<<p1[0]<<", "<<p1[1]<<", "<<p1[2]<<") "<<std::endl; + // std::cout<<"p2: ("<<p2[0]<<", "<<p2[1]<<", "<<p2[2]<<") "<<std::endl; + // std::cout<<"p3: ("<<p3[0]<<", "<<p3[1]<<", "<<p3[2]<<") "<<std::endl; + + unsigned int maxCount=m_d->collHandle->collSettingsButton().numOfStepsForInterpolation(); + for (unsigned int count=1; count<=maxCount;++count){ + float t=static_cast<float>(count)/static_cast<float>(maxCount); + Amg::Vector3D pos; + bezier(pos, p0, p1, p2, p3, t); + // std::cout<<"j: "<<count<<" \tat ("<<pos.x()<<","<<pos.y()<<","<<pos.z()<<")"<<std::endl; + + // pos = pos + momdelta; + vertices->vertex.set1Value(iver++,pos.x(),pos.y(),pos.z()); + m_d->positionsToWrite.append(pos); + + npointsused++; + } + } else { + vertices->vertex.set1Value(iver++,positions[i].x(),positions[i].y(),positions[i].z()); + m_d->positionsToWrite.append(positions[i]); + npointsused++; + } + } + + // Add final point. + + + + // Add to SoLine set + m_d->line->numVertices.set1Value(0,npointsused); + m_d->line->vertexProperty = vertices; + +} + +#ifndef BUILDVP1LIGHT +void IParticleHandle_Electron::addLine_Extrapolated(){ + VP1Msg::messageVerbose("IParticleHandle_Electron::addLine_Extrapolated()."); + + const Trk::Perigee& peri = m_d->electron->trackParticle()->perigeeParameters(); // FIXME - I'd quite like not to use anything which requires Athena ... + + Trk::CurvilinearParameters startParameters(peri.position(),peri.momentum(),peri.charge()); + Trk::ExtrapolationCell<Trk::TrackParameters> ecc(startParameters); + // ecc.addConfigurationMode(Trk::ExtrapolationMode::StopAtBoundary); + ecc.addConfigurationMode(Trk::ExtrapolationMode::CollectPassive); + ecc.addConfigurationMode(Trk::ExtrapolationMode::CollectSensitive); + + // we want to extrapolate outwards only for muon tracks + if (getNMuonPrecisionLayers()==0 && getNMuonPhiLayers()==0 ) + ecc.addConfigurationMode(Trk::ExtrapolationMode::StopAtBoundary); + + // call the extrapolation engine + Trk::IExtrapolationEngine * engine = collHandle()->common()->extrapolator(); + if (!engine) { + VP1Msg::messageVerbose("No extrapolator engine available. Aborting."); + return; + } + + std::vector<Amg::Vector3D> positions; + std::vector<Amg::Vector3D> momenta; + + // Add start positions + positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); // TODO: move to position()? + momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); + + + Trk::ExtrapolationCode eCode = engine->extrapolate(ecc); + + // end the parameters if there + if (eCode.isSuccess()){ + // loop over the collected information + for (auto& es : ecc.extrapolationSteps){ + + // continue if we have parameters + const Trk::TrackParameters* parameters = es.parameters; + if (parameters){ + // take what you need -> position etc + + // finally delete the parameters + Amg::Vector3D pos = parameters->position(); + Amg::Vector3D mom = parameters->momentum(); + positions.push_back(pos); + momenta.push_back(mom); + + delete parameters; + } + }// + + Amg::Vector3D pos = ecc.endParameters->position(); + Amg::Vector3D mom = ecc.endParameters->momentum(); + positions.push_back(pos); + momenta.push_back(mom); + // and delete the final parameter + delete ecc.endParameters; + } else { + VP1Msg::messageVerbose("IParticleHandle_Electron::addLine_Extrapolated() - extrapolation failed."); + } + fillLineFromSplineFit(positions, momenta); + // std::cout<<"About to add "<<collHandleTrk->material()<<std::endl; + m_d->sep->addChild(m_d->collHandle->material()); + // ^^ FIXME - should rearrange so we don't need to reset material + + + m_d->sep->addChild(m_d->line); +} +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +QStringList IParticleHandle_Electron::clicked() const +{ + QStringList l; + l << "Electron:"; + l << IParticleHandleBase::baseInfo(); + return l; +} + +//____________________________________________________________________ +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_Electron::momentum() const + { + double phi = m_d->electron->trackParticle()->phi0(); + double theta = m_d->electron->trackParticle()->theta(); + + // decide the sign of the charge + double qop = m_d->electron->trackParticle()->qOverP(); + // if(qop < 0.) + // m_chargeDef->setCharge(-1.); + // else + // m_chargeDef->setCharge(1.); + static constexpr double INVALID_P(10e9); + static constexpr double INVALID_QOP(10e-9); + + // check qoverp is physical + double p = 0.; + if(qop != 0.) + p = fabs(1./qop); + else + { + // qop is unphysical. No momentum measurement. + p = INVALID_P; + qop = INVALID_QOP; + } + + const Amg::Vector3D mom = Amg::Vector3D(p*cos(phi)*sin(theta), p*sin(phi)*sin(theta), p*cos(theta)); + + return mom; + } +#else + Amg::Vector3D IParticleHandle_Electron::momentum() const + { + const Trk::Perigee& p = m_d->electron->trackParticle()->perigeeParameters(); + return p.momentum(); + } +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_Electron::position() const + { + double d0 = m_d->electron->trackParticle()->d0(); + double z0 = m_d->electron->trackParticle()->z0(); + double phi = m_d->electron->trackParticle()->phi0(); + + // glopos[Amg::x] = - locpos[Trk::d0]*sin(phi); + // glopos[Amg::y] = locpos[Trk::d0]*cos(phi); + // glopos[Amg::z] = locpos[Trk::z0]; + + + const Amg::Vector3D pos = Amg::Vector3D(- d0*sin(phi), d0*cos(phi), z0); + + return pos; + } +#else + Amg::Vector3D IParticleHandle_Electron::position() const + { + const Trk::Perigee& p = m_d->electron->trackParticle()->perigeeParameters(); + return p.position(); // TODO: check what this returns + } +#endif + + + +//____________________________________________________________________ +const xAOD::IParticle& IParticleHandle_Electron::iParticle() const +{ + return *(m_d->electron); +} + +//____________________________________________________________________ +double IParticleHandle_Electron::charge() const +{ + return m_d->electron->charge(); +} + +//____________________________________________________________________ +unsigned IParticleHandle_Electron::summaryValue(xAOD::SummaryType type) const +{ + uint8_t num = 0; + if (m_d->electron->trackParticle()->summaryValue(num,type)){ + return num; + } + // else... + VP1Msg::message("IParticleHandle_Electron::getSummaryValue - unable to retrieve the requested enum: "+VP1Msg::str(type)); + return 999999; +} + +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNPixelHits() const +{ + return summaryValue(xAOD::numberOfPixelHits); +} + +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNSCTHits() const +{ + return summaryValue(xAOD::numberOfSCTHits); +} +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNTRTHits() const +{ + return summaryValue(xAOD::numberOfTRTHits); +} +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNMuonPrecisionLayers() const +{ + return summaryValue(xAOD::numberOfPrecisionLayers); +} +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNMuonPrecisionHoleLayers() const +{ + return summaryValue(xAOD::numberOfPrecisionHoleLayers); +} +//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNMuonPhiLayers() const +{ + return summaryValue(xAOD::numberOfPhiLayers); + +}//____________________________________________________________________ +unsigned IParticleHandle_Electron::getNMuonPhiHoleLayers() const +{ + return summaryValue(xAOD::numberOfPhiHoleLayers); +} + +QString IParticleHandle_Electron::shortInfo() const +{ + QString l("|P|="+VP1Msg::str(momentum().mag()/SYSTEM_OF_UNITS::GeV)+" [GeV], "); + l+= "Pix["+QString::number(getNPixelHits())+"], SCT["+QString::number(getNSCTHits())+"], TRT["+QString::number(getNTRTHits()) + +"], Muon prec. layers/holes ["+QString::number(getNMuonPrecisionLayers())+"/"+QString::number(getNMuonPrecisionHoleLayers())+"]"; + return l; +} + +void IParticleHandle_Electron::fillObjectBrowser( QList<QTreeWidgetItem *>& listOfItems) +{ + IParticleHandleBase::fillObjectBrowser(listOfItems); // Obligatory! + + QTreeWidgetItem* TSOSitem = new QTreeWidgetItem(browserTreeItem()); + TSOSitem->setText(0, QString("Def. Parameters " ) ); + QString dParameters("("); + dParameters+=QString::number(m_d->electron->trackParticle()->d0()); + dParameters+=", "; + dParameters+=QString::number(m_d->electron->trackParticle()->z0()); + dParameters+=", "; + dParameters+=QString::number(m_d->electron->trackParticle()->phi0()); + dParameters+=", "; + dParameters+=QString::number(m_d->electron->trackParticle()->theta()); + dParameters+=", "; + dParameters+=QString::number(m_d->electron->trackParticle()->qOverP()); + dParameters+=")"; + TSOSitem->setText(1, dParameters ); + + for (unsigned int i=0; i<m_d->electron->trackParticle()->numberOfParameters() ; ++i){ + QTreeWidgetItem* TSOSitem = new QTreeWidgetItem(browserTreeItem()); + TSOSitem->setText(0, QString("Parameter "+QString::number( i+1 ) ) ); + QString pos(", Position = ("); + pos+=QString::number(m_d->electron->trackParticle()->parameterX(i)); + pos+=", "; + pos+=QString::number(m_d->electron->trackParticle()->parameterY(i)); + pos+=", "; + pos+=QString::number(m_d->electron->trackParticle()->parameterZ(i)); + pos+=")"; + + switch (m_d->electron->trackParticle()->parameterPosition(i)){ + case xAOD::BeamLine: + TSOSitem->setText(1, QString("BeamLine" )+pos ); + break; + case xAOD::FirstMeasurement: + TSOSitem->setText(1, QString("FirstMeasurement")+pos ); + break; + case xAOD::LastMeasurement: + TSOSitem->setText(1, QString("LastMeasurement" )+pos ); + break; + case xAOD::CalorimeterEntrance: + TSOSitem->setText(1, QString("CalorimeterEntrance")+pos ); + break; + case xAOD::CalorimeterExit: + TSOSitem->setText(1, QString("CalorimeterExit" )+pos ); + break; + case xAOD::MuonSpectrometerEntrance: + TSOSitem->setText(1, QString("MuonSpectrometerEntrance")+pos ); + break; + default: + TSOSitem->setText(1, QString("Undefined")+pos ); + } + } + + // TODO - add more. +} + +const QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> >& IParticleHandle_Electron::parametersAndPositions() const { + // 1st position + if (!m_d->parametersAndPositions.isEmpty()) + return m_d->parametersAndPositions; + + typedef std::pair<xAOD::ParameterPosition, Amg::Vector3D> paramAndPos; + +#if defined BUILDVP1LIGHT + m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, position() ) ); +#else + const Trk::Perigee& peri = m_d->electron->trackParticle()->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... + m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z()) ) ); // TODO: move to position()? +#endif // BUILDVP1LIGHT + + float x,y,z; + for (unsigned int i=0; i<m_d->electron->trackParticle()->numberOfParameters() ; ++i){ + x = m_d->electron->trackParticle()->parameterX(i); + y = m_d->electron->trackParticle()->parameterY(i); + z = m_d->electron->trackParticle()->parameterZ(i); + + m_d->parametersAndPositions.append(paramAndPos(m_d->electron->trackParticle()->parameterPosition(i), Amg::Vector3D(x,y,z))); + } + VP1Msg::messageVerbose("Electron parametersAndPositions() - returning this many positions : "+VP1Msg::str(m_d->parametersAndPositions.size()) ); + return m_d->parametersAndPositions; +} + +void IParticleHandle_Electron::dumpToJSON( std::ofstream& str) const { + str << "\"chi2\":"<<m_d->electron->trackParticle()->chiSquared () <<", "; + str << "\"dof\":" <<m_d->electron->trackParticle()->numberDoF () <<", "; + str << "\"dparams\": [" + << m_d->electron->trackParticle()->d0() <<", " + << m_d->electron->trackParticle()->z0() <<", " + << m_d->electron->trackParticle()->phi0() <<", " + << m_d->electron->trackParticle()->theta() <<", " + << m_d->electron->trackParticle()->qOverP() + << "], \"pos\": ["; + bool first = true; + for (auto pos: m_d->positionsToWrite){ + if (first){ + first = false; + } else { + str <<","; + } + str << "["<<pos.x()<<","<<pos.y()<<","<<pos.z()<<"]"; + } + str << "] "; +} diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.h new file mode 100644 index 0000000000000000000000000000000000000000..3f5e9db95cdccd3e444d73e81b916acc8b1d7885 --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Electron.h @@ -0,0 +1,85 @@ +/* + Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration +*/ + + +//////////////////////////////////////////////////////////////// +// // +// Header file for class IParticleHandle_Electron // +// // +// Description: Handles for track particles. // +// // +// // +//////////////////////////////////////////////////////////////// + +#ifndef IPARTICLEHANDLE_ELECTRON_H +#define IPARTICLEHANDLE_ELECTRON_H + +#include "IParticleHandleBase.h" + +#include "xAODEgamma/Electron.h" +#include "xAODTracking/TrackingPrimitives.h" +#include "GeoPrimitives/GeoPrimitives.h" +#include <QList> + +class SoLineSet; + +class IParticleHandle_Electron : public IParticleHandleBase { +public: + + IParticleHandle_Electron(IParticleCollHandleBase*, const xAOD::Electron * ); + virtual ~IParticleHandle_Electron(); + + virtual bool has3DObjects(); + virtual void clear3DObjects(); + virtual SoNode* nodes(); + void addParameterShapes(); + /// Make the line, but only using information on the track (a spline fit will be done from the parameters) + void addLine_FromElectron(); + #ifndef BUILDVP1LIGHT + /// Extrapolate the initial track parameters to get the line (a spline fit is done between the extrapolated parameters) + void addLine_Extrapolated(); + #endif // BUILDVP1LIGHT + /// Fill d->line with a SoLineSet made from a spline fit between the information in positions and momenta. + void fillLineFromSplineFit( const std::vector<Amg::Vector3D>& positions, + const std::vector<Amg::Vector3D>& momenta); + void linear(Amg::Vector3D& output, Amg::Vector3D& a, Amg::Vector3D& b, float t); + + void bezier(Amg::Vector3D& output, Amg::Vector3D& a, Amg::Vector3D& b, Amg::Vector3D& c, Amg::Vector3D& d, float t); + + virtual QStringList clicked() const; + virtual Amg::Vector3D momentum() const; + virtual Amg::Vector3D position() const; + const xAOD::IParticle& iParticle() const; + virtual double charge() const ;//!< Returns unknown() in case of trouble. + + virtual unsigned summaryValue(xAOD::SummaryType type) const; + virtual unsigned getNPixelHits() const; + virtual unsigned getNSCTHits() const; + virtual unsigned getNTRTHits() const; + virtual unsigned getNMuonPrecisionLayers() const; + virtual unsigned getNMuonPrecisionHoleLayers() const; + virtual unsigned getNMuonPhiLayers() const; + virtual unsigned getNMuonPhiHoleLayers() const; + + virtual QString type() const { return QString("Electron"); } //!< return very short word with type (maybe link with collection type?) + + /// This returns the information shown about the object in the object browser + QString shortInfo() const; + + void fillObjectBrowser( QList<QTreeWidgetItem *>& listOfItems) ; + + // Some specific stuff used by base collection to draw tracks + const QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> >& parametersAndPositions() const; + + virtual void dumpToJSON( std::ofstream& ) const ; + +private: + + class Imp; + Imp *m_d; + void ensureInitSubSysHitInfo() const; + +}; + +#endif diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Jet.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Jet.cxx index d7e255a456cb04e08fdb80cdd48431f842aad50f..55fb437bea832ac128a8930659330eecca7e606a 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Jet.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Jet.cxx @@ -34,7 +34,14 @@ #include <Inventor/nodes/SoSwitch.h> #include <SoDebug.h> // it's stored at /afs/cern.ch/sw/lcg/external/coin3d/3.1.3p2/x86_64-slc6-gcc47-opt/include/SoDebug.h - +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif //____________________________________________________________________ @@ -70,8 +77,8 @@ public: //Settings: bool considerTransverseEnergies = true; // TODO: update with button connection "E/Et" (see VP1JetCollection.cxx) double coneRPar = -1; // FIXME: add calculation of coneRPar, like in the old VP1 Jet - double scale = (10.0 * Gaudi::Units::m) / (100.0*Gaudi::Units::GeV); // the default scale of all jets: 10m/100GeV - double maxR = 0.0 * Gaudi::Units::m; // default value for maxR is 0.0 + double scale = (10.0 * SYSTEM_OF_UNITS::m) / (100.0*SYSTEM_OF_UNITS::GeV); // the default scale of all jets: 10m/100GeV + double maxR = 0.0 * SYSTEM_OF_UNITS::m; // default value for maxR is 0.0 // SoLineSet * line;//This represents the line(s) representing the trackparticle. Can be interpolated. // SoPointSet * points;//This represents the points(s) representing the trackparticle's parameters. @@ -142,7 +149,7 @@ IParticleHandle_Jet::~IParticleHandle_Jet() void IParticleHandle_Jet::setScale( const double& sc) { m_d->scale = sc; } //____________________________________________________________________ -void IParticleHandle_Jet::setMaxR(const double& maxR) { m_d->maxR = maxR * Gaudi::Units::m; } +void IParticleHandle_Jet::setMaxR(const double& maxR) { m_d->maxR = maxR * SYSTEM_OF_UNITS::m; } //____________________________________________________________________ void IParticleHandle_Jet::rerandomiseMaterial() {m_d->rerandomiseMaterial(); } @@ -721,6 +728,15 @@ double IParticleHandle_Jet::getBTaggingWeight(std::string tagger) + // const xAOD::BTagging * myBTag = nullptr; + // myBTag = d->m_jet->btagging(); + + // if (myBTag == nullptr) { + // VP1Msg::messageWarningRed("It was not possible to access the pointer to b-tagging info, for the selected collection! Returning 'weight': 0.0"); //("It was not possible to access the tagger '"+ tagger +"' for the selected collection: " + d->m_jet->getInputType() + d->m_jet->getAlgorithmType() ); + // return weight; + // } + + // TODO: add the other taggers // if (tagger == "MV1") diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.cxx index 0669d0c5d7bbdd434a1ae6b317935843b6d524c1..c8e8882ab7c9fbe6ebb89d170caeeb8bb2a65c32 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.cxx @@ -30,7 +30,18 @@ #include <Inventor/nodes/SoTranslation.h> #include <Inventor/nodes/SoRotationXYZ.h> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" +#endif // BUILDVP1LIGHT + +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif //AOD //____________________________________________________________________ @@ -214,12 +225,16 @@ void IParticleHandle_Muon::addLine_FromTrackParticle(){ VP1Msg::message("ERROR : no primary track particle associated with this Muon. Can't visualise it."); return; } - - const Trk::Perigee& peri = trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... +#if defined BUILDVP1LIGHT + positions.push_back(position()); + momenta. push_back(momentum()); +#else + const Trk::Perigee& peri = trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... - positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); - momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); - VP1Msg::messageVerbose("IParticleHandle_Muon::addLine_FromTrackParticle - has "+QString::number(trackparticle->numberOfParameters())+" extra parameters."); + positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); + momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); + VP1Msg::messageVerbose("IParticleHandle_Muon::addLine_FromTrackParticle - has "+QString::number(trackparticle->numberOfParameters())+" extra parameters."); + #endif // BUILDVP1LIGHT for (unsigned int i=0; i<trackparticle->numberOfParameters() ; ++i){ // std::cout<<"i:"<<i<<"/"<<m_d->trackparticle->numberOfParameters()+1<<std::endl; @@ -350,11 +365,69 @@ QStringList IParticleHandle_Muon::clicked() const } //____________________________________________________________________ -Amg::Vector3D IParticleHandle_Muon::momentum() const -{ - const Trk::Perigee& p = m_d->muon->primaryTrackParticle()->perigeeParameters(); - return p.momentum(); -} +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_Muon::momentum() const + { + double phi = m_d->muon->primaryTrackParticle()->phi0(); + double theta = m_d->muon->primaryTrackParticle()->theta(); + + // decide the sign of the charge + double qop = m_d->muon->primaryTrackParticle()->qOverP(); + // if(qop < 0.) + // m_chargeDef->setCharge(-1.); + // else + // m_chargeDef->setCharge(1.); + static constexpr double INVALID_P(10e9); + static constexpr double INVALID_QOP(10e-9); + + // check qoverp is physical + double p = 0.; + if(qop != 0.) + p = fabs(1./qop); + else + { + // qop is unphysical. No momentum measurement. + p = INVALID_P; + qop = INVALID_QOP; + } + + const Amg::Vector3D mom = Amg::Vector3D(p*cos(phi)*sin(theta), p*sin(phi)*sin(theta), p*cos(theta)); + + return mom; + } +#else + Amg::Vector3D IParticleHandle_Muon::momentum() const + { + const Trk::Perigee& p = m_d->muon->primaryTrackParticle()->perigeeParameters(); + return p.momentum(); + } +#endif // + +//____________________________________________________________________ +// TODO: probably, we can move this function to the common base class for all trackparticles +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_Muon::position() const + { + double d0 = m_d->muon->primaryTrackParticle()->d0(); + double z0 = m_d->muon->primaryTrackParticle()->z0(); + double phi = m_d->muon->primaryTrackParticle()->phi0(); + + // glopos[Amg::x] = - locpos[Trk::d0]*sin(phi); + // glopos[Amg::y] = locpos[Trk::d0]*cos(phi); + // glopos[Amg::z] = locpos[Trk::z0]; + + + const Amg::Vector3D pos = Amg::Vector3D(- d0*sin(phi), d0*cos(phi), z0); + + return pos; + } +#else + Amg::Vector3D IParticleHandle_Muon::position() const + { + const Trk::Perigee& p = m_d->muon->primaryTrackParticle()->perigeeParameters(); + return p.position(); // TODO: check what this returns + } +#endif //____________________________________________________________________ const xAOD::IParticle& IParticleHandle_Muon::iParticle() const @@ -426,7 +499,7 @@ QString IParticleHandle_Muon::qualityString() const{ QString IParticleHandle_Muon::shortInfo() const { - QString l("|P|="+VP1Msg::str(momentum().mag()/Gaudi::Units::GeV)+" [GeV], " +muonTypeString() + ", "+qualityString() ); + QString l("|P|="+VP1Msg::str(momentum().mag()/SYSTEM_OF_UNITS::GeV)+" [GeV], " +muonTypeString() + ", "+qualityString() ); return l; } @@ -494,9 +567,12 @@ const QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> >& IParticleHandle return m_d->parametersAndPositions; typedef std::pair<xAOD::ParameterPosition, Amg::Vector3D> paramAndPos; - - const Trk::Perigee& peri = m_d->muon->primaryTrackParticle()->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... - m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z()) ) ); + #if defined BUILDVP1LIGHT + m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, position() ) ); + #else + const Trk::Perigee& peri = m_d->muon->primaryTrackParticle()->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... + m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z()) ) ); + #endif // BUILDVP1LIGHT float x,y,z; for (unsigned int i=0; i<m_d->muon->primaryTrackParticle()->numberOfParameters() ; ++i){ diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.h index def99732a897aa64a394d001e225a9cd4fa26c34..200ad2c536f186f0a36a6c7ed3df7e5f9b8220a5 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_Muon.h @@ -38,6 +38,7 @@ public: virtual QStringList clicked() const; virtual Amg::Vector3D momentum() const; + virtual Amg::Vector3D position() const; const xAOD::IParticle& iParticle() const; virtual double charge() const ;//!< Returns unknown() in case of trouble. diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.cxx index 6226fb3e741a09c1e4d00e197b517bcac68c2720..36fd22b1b228cb9bc00b8c0c22c1b9c093215efe 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.cxx @@ -30,9 +30,19 @@ #include <Inventor/nodes/SoTranslation.h> #include <Inventor/nodes/SoRotationXYZ.h> -//Athena -#include "TrkExInterfaces/IExtrapolationEngine.h" -#include "GaudiKernel/SystemOfUnits.h" +#ifndef BUILDVP1LIGHT + #include "TrkExInterfaces/IExtrapolationEngine.h" +#endif + +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif + //____________________________________________________________________ class IParticleHandle_TrackParticle::Imp { @@ -101,10 +111,13 @@ SoNode* IParticleHandle_TrackParticle::nodes(){ bool fromTrack=m_d->collHandle->collSettingsButton().useExistingParameters(); - if (fromTrack) + if (fromTrack) { addLine_FromTrackParticle(); - else - addLine_Extrapolated(); + } else { + #ifndef BUILDVP1LIGHT + addLine_Extrapolated(); + #endif // BUILDVP1LIGHT + } if (m_d->collHandle->collSettingsButton().showParameters()) addParameterShapes(); @@ -162,13 +175,18 @@ void IParticleHandle_TrackParticle::addLine_FromTrackParticle(){ std::vector<Amg::Vector3D> positions, momenta; - +#if defined BUILDVP1LIGHT + positions.push_back(position()); + momenta. push_back(momentum()); +#else const Trk::Perigee& peri = m_d->trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); // std::cout<<"i:"<<0<<"/"<<m_d->trackparticle->numberOfParameters()+1<<": ("<<peri.position().x()<<","<<peri.position().y()<<","<<peri.position().z()<<")"<<std::endl; - +#endif // BUILDVP1LIGHT + + VP1Msg::messageVerbose("IParticleHandle_TrackParticle::addLine_FromTrackParticle - has "+QString::number(m_d->trackparticle->numberOfParameters())+" extra parameters."); for (unsigned int i=0; i<m_d->trackparticle->numberOfParameters() ; ++i){ // std::cout<<"i:"<<i+1<<"/"<<m_d->trackparticle->numberOfParameters()+1<<": ("<<m_d->trackparticle->parameterX(i)<<","<<m_d->trackparticle->parameterY(i)<<","<<m_d->trackparticle->parameterZ(i)<<")"<<std::endl; @@ -179,6 +197,7 @@ void IParticleHandle_TrackParticle::addLine_FromTrackParticle(){ momenta.push_back(Amg::Vector3D( m_d->trackparticle->parameterPX(i), m_d->trackparticle->parameterPY(i), m_d->trackparticle->parameterPZ(i))); + } // end of loop. // if ( positions.size()<2 ) VP1Msg::messageVerbose("IParticleHandle_TrackParticle::addLine_FromTrackParticle - WARNING - not enough points to make a line."); @@ -273,8 +292,10 @@ void IParticleHandle_TrackParticle::fillLineFromSplineFit(const std::vector<Amg: } +#ifndef BUILDVP1LIGHT void IParticleHandle_TrackParticle::addLine_Extrapolated(){ VP1Msg::messageVerbose("IParticleHandle_TrackParticle::addLine_Extrapolated()."); + const Trk::Perigee& peri = m_d->trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... Trk::CurvilinearParameters startParameters(peri.position(),peri.momentum(),peri.charge()); @@ -296,10 +317,11 @@ void IParticleHandle_TrackParticle::addLine_Extrapolated(){ std::vector<Amg::Vector3D> positions; std::vector<Amg::Vector3D> momenta; - + // Add start positions positions.push_back(Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z())); momenta. push_back(Amg::Vector3D(peri.momentum().x(),peri.momentum().y(),peri.momentum().z())); + Trk::ExtrapolationCode eCode = engine->extrapolate(ecc); @@ -340,6 +362,7 @@ void IParticleHandle_TrackParticle::addLine_Extrapolated(){ m_d->sep->addChild(m_d->line); } +#endif // BUILDVP1LIGHT //____________________________________________________________________ QStringList IParticleHandle_TrackParticle::clicked() const @@ -351,11 +374,70 @@ QStringList IParticleHandle_TrackParticle::clicked() const } //____________________________________________________________________ -Amg::Vector3D IParticleHandle_TrackParticle::momentum() const -{ - const Trk::Perigee& p = m_d->trackparticle->perigeeParameters(); - return p.momentum(); -} +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_TrackParticle::momentum() const + { + double phi = m_d->trackparticle->phi0(); + double theta = m_d->trackparticle->theta(); + + // decide the sign of the charge + double qop = m_d->trackparticle->qOverP(); + // if(qop < 0.) + // m_chargeDef->setCharge(-1.); + // else + // m_chargeDef->setCharge(1.); + static constexpr double INVALID_P(10e9); + static constexpr double INVALID_QOP(10e-9); + + // check qoverp is physical + double p = 0.; + if(qop != 0.) + p = fabs(1./qop); + else + { + // qop is unphysical. No momentum measurement. + p = INVALID_P; + qop = INVALID_QOP; + } + + const Amg::Vector3D mom = Amg::Vector3D(p*cos(phi)*sin(theta), p*sin(phi)*sin(theta), p*cos(theta)); + + return mom; + } +#else + Amg::Vector3D IParticleHandle_TrackParticle::momentum() const + { + const Trk::Perigee& p = m_d->trackparticle->perigeeParameters(); + return p.momentum(); + } +#endif // BUILDVP1LIGHT + +//____________________________________________________________________ +// TODO: probably, we can move this function to the common base class for all trackparticles +#if defined BUILDVP1LIGHT + Amg::Vector3D IParticleHandle_TrackParticle::position() const + { + double d0 = m_d->trackparticle->d0(); + double z0 = m_d->trackparticle->z0(); + double phi = m_d->trackparticle->phi0(); + + // glopos[Amg::x] = - locpos[Trk::d0]*sin(phi); + // glopos[Amg::y] = locpos[Trk::d0]*cos(phi); + // glopos[Amg::z] = locpos[Trk::z0]; + + + const Amg::Vector3D pos = Amg::Vector3D(- d0*sin(phi), d0*cos(phi), z0); + + return pos; + } +#else + Amg::Vector3D IParticleHandle_TrackParticle::position() const + { + const Trk::Perigee& p = m_d->trackparticle->perigeeParameters(); + return p.position(); // TODO: check what this returns + } +#endif + //____________________________________________________________________ const xAOD::IParticle& IParticleHandle_TrackParticle::iParticle() const @@ -420,7 +502,7 @@ unsigned IParticleHandle_TrackParticle::getNMuonPhiHoleLayers() const QString IParticleHandle_TrackParticle::shortInfo() const { - QString l("|P|="+VP1Msg::str(momentum().mag()/Gaudi::Units::GeV)+" [GeV], "); + QString l("|P|="+VP1Msg::str(momentum().mag()/SYSTEM_OF_UNITS::GeV)+" [GeV], "); l+= "Pix["+QString::number(getNPixelHits())+"], SCT["+QString::number(getNSCTHits())+"], TRT["+QString::number(getNTRTHits()) +"], Muon prec. layers/holes ["+QString::number(getNMuonPrecisionLayers())+"/"+QString::number(getNMuonPrecisionHoleLayers())+"]"; return l; @@ -490,8 +572,12 @@ const QList<std::pair<xAOD::ParameterPosition, Amg::Vector3D> >& IParticleHandle typedef std::pair<xAOD::ParameterPosition, Amg::Vector3D> paramAndPos; +#if defined BUILDVP1LIGHT + m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, position() ) ); +#else const Trk::Perigee& peri = m_d->trackparticle->perigeeParameters (); // FIXME - I'd quite like not to use anything which requires Athena ... m_d->parametersAndPositions.append(paramAndPos(xAOD::BeamLine, Amg::Vector3D(peri.position().x(),peri.position().y(),peri.position().z()) ) ); +#endif // BUILDVP1LIGHT float x,y,z; for (unsigned int i=0; i<m_d->trackparticle->numberOfParameters() ; ++i){ @@ -526,3 +612,4 @@ void IParticleHandle_TrackParticle::dumpToJSON( std::ofstream& str) const { } str << "] "; } + diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.h index 5c086aa7807480166a4858d9597b8985fbc01fd3..07e775f8f2e78c5cf934e43790feea428d366d78 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/IParticleHandle_TrackParticle.h @@ -36,8 +36,10 @@ public: void addParameterShapes(); /// Make the line, but only using information on the track (a spline fit will be done from the parameters) void addLine_FromTrackParticle(); - /// Extrapolate the initial track parameters to get the line (a spline fit is done between the extrapolated parameters) - void addLine_Extrapolated(); + #ifndef BUILDVP1LIGHT + /// Extrapolate the initial track parameters to get the line (a spline fit is done between the extrapolated parameters) + void addLine_Extrapolated(); + #endif // BUILDVP1LIGHT /// Fill d->line with a SoLineSet made from a spline fit between the information in positions and momenta. void fillLineFromSplineFit( const std::vector<Amg::Vector3D>& positions, const std::vector<Amg::Vector3D>& momenta); @@ -47,6 +49,7 @@ public: virtual QStringList clicked() const; virtual Amg::Vector3D momentum() const; + virtual Amg::Vector3D position() const; const xAOD::IParticle& iParticle() const; virtual double charge() const ;//!< Returns unknown() in case of trouble. diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtCollHandle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtCollHandle.cxx index 09c70145608d6ce3cbb9bde1ec24ce8888621a8f..ad00376de24cb93dcfff77b49225bf51584c815d 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtCollHandle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtCollHandle.cxx @@ -30,8 +30,10 @@ #include "VP1Base/VP1Interval.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif //Qt #include <QStringList> @@ -47,12 +49,25 @@ //#include "Inventor/nodes/SoDrawStyle.h" //#include "Inventor/nodes/SoLightModel.h" +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + //____________________________________________________________________ -QStringList MissingEtCollHandle::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::MissingETContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList MissingEtCollHandle::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::Other); + } +#else + QStringList MissingEtCollHandle::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::MissingETContainer>(); + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ class MissingEtCollHandle::Imp { @@ -380,11 +395,21 @@ bool MissingEtCollHandle::load() messageVerbose("loading MissingEt collection"); //Get collection: - const xAOD::MissingETContainer * coll(0); - if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { - message("Error: Could not retrieve MET collection with key="+name()); - return false; - } + const xAOD::MissingETContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + QString errMsg = "Failed to retrieve " + name(); + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve MET collection with key="+name()); + return false; + } + #endif // BUILDVP1LIGHT // // Retrieve the xAOD particles: // const xAOD::MissingETContainer* xaod = evtStore()->retrieve<const xAOD::MissingETContainer>( m_JetCollection ); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtHandle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtHandle.cxx index 41c44f5f831a4a28180b4e23a87584bf13b41a86..80ac3e32e3e2ce9f1e8bb6517fa54ca7c71ad85e 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtHandle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/MissingEtHandle.cxx @@ -38,6 +38,15 @@ #include "MissingEtCollectionSettingsButton.h" #include "MissingEtCollHandle.h" +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif + //double MissingEtHandle::thickness = 1.0; //double MissingEtHandle::scale = 1.0; //bool MissingEtHandle::shape = true; @@ -229,10 +238,10 @@ void MissingEtHandle::Imp::createShapeFromJetParameters() { VP1Msg::messageVerbose("MissingEtHandle::Imp::createShapeFromJetParameters()"); - //double length = m_met->met() * (200.0 * Gaudi::Units::cm /(100.0 * Gaudi::Units::GeV ));//Fixme: Make scale factor (and thickness) adjustable. + //double length = m_met->met() * (200.0 * SYSTEM_OF_UNITS::cm /(100.0 * SYSTEM_OF_UNITS::GeV ));//Fixme: Make scale factor (and thickness) adjustable. // Set length of MET: 200 cm for 100 GeV - double length = m_met->met() * (200.0 * Gaudi::Units::cm /(100.0 * Gaudi::Units::GeV )); + double length = m_met->met() * (200.0 * SYSTEM_OF_UNITS::cm /(100.0 * SYSTEM_OF_UNITS::GeV )); this->length = length; // Set scale factor for MET length, from user's settings in the GUI @@ -368,11 +377,11 @@ QStringList MissingEtHandle::clicked() const // see: http://acode-browser.usatlas.bnl.gov/lxr/source/atlas/Event/xAOD/xAODMissingET/xAODMissingET/versions/MissingET_v1.h // l +=" - Name: " + m_d->name(); - l +=" - MissingEt: " + QString::number(m_d->met() / Gaudi::Units::GeV) +" [GeV]"; + l +=" - MissingEt: " + QString::number(m_d->met() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; l +=" - Phi: " + QString::number(m_d->phi()); - l +=" - SumEt: " + QString::number(m_d->sumet() / Gaudi::Units::GeV) +" [GeV]"; - l +=" - mpx: " + QString::number(m_d->mpx() / Gaudi::Units::GeV) +" [GeV]" ; - l +=" - mpy: " + QString::number(m_d->mpy() / Gaudi::Units::GeV) +" [GeV]"; + l +=" - SumEt: " + QString::number(m_d->sumet() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; + l +=" - mpx: " + QString::number(m_d->mpx() / SYSTEM_OF_UNITS::GeV) +" [GeV]" ; + l +=" - mpy: " + QString::number(m_d->mpy() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; return l; } @@ -432,7 +441,7 @@ QString MissingEtHandle::shortInfo() const QString l; l += m_d->name(); - l += ", met: " + QString::number(m_d->met() / Gaudi::Units::GeV) +" [GeV]"; + l += ", met: " + QString::number(m_d->met() / SYSTEM_OF_UNITS::GeV) +" [GeV]"; l += ", phi: " + QString::number(m_d->phi()); return l; diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/TrackParticleCollectionSettingsButton.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/TrackParticleCollectionSettingsButton.cxx index 0a7e55a506c2e4dc6fa9494162c45d3c80b5dc3a..e0ed3d2f26df19653e9b73940e6e59ccf9e51bf7 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/TrackParticleCollectionSettingsButton.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/TrackParticleCollectionSettingsButton.cxx @@ -146,6 +146,16 @@ TrackParticleCollectionSettingsButton::TrackParticleCollectionSettingsButton(QWi connect(m_d->editwindow_ui.checkBox_tracksUseBaseLightModel,SIGNAL(toggled(bool)),this,SLOT(updateTrackLightModel(bool))); connect(m_d->editwindow_ui.checkBox_hideactualpaths,SIGNAL(toggled(bool)),this,SLOT(updateHideActualTrackPath(bool))); + #if defined BUILDVP1LIGHT + m_d->editwindow_ui.radioButton_existingParameters->setChecked(true); + m_d->editwindow_ui.radioButton_existingParameters->setEnabled(true); + m_d->editwindow_ui.radioButton_extrapolate->setChecked(false); + m_d->editwindow_ui.radioButton_extrapolate->setEnabled(false); + m_d->editwindow_ui.radioButton_extrapolate->setToolTip("Not available in VP1 Light"); + m_d->editwindow_ui.horizontalSlider_numBezierSteps->setValue(10); + m_d->editwindow_ui.horizontalSlider_numBezierSteps->setSliderPosition(10); + #endif //BUILDVP1LIGHT + // Propagation - for all of these, just emit the propagationOptionsChanged() signal and rely on clients checking to see what has changed. connect(m_d->editwindow_ui.radioButton_existingParameters, SIGNAL(toggled(bool)), this, SIGNAL(propagationOptionsChanged())); connect(m_d->editwindow_ui.radioButton_extrapolate, SIGNAL(toggled(bool)), this, SIGNAL(propagationOptionsChanged())); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/VP1AODSystem.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/VP1AODSystem.cxx index b79aedabc0c1faa0b0c08b54493e0b7e2a015e28..11116056829045c9f6e54739629bebcfc4b1358e 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/VP1AODSystem.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/VP1AODSystem.cxx @@ -15,11 +15,14 @@ #include "VP1AODSystems/AODSystemController.h" #include "IParticleCollHandleBase.h" #include "AODCollHandleBase.h" +#ifndef BUILDVP1LIGHT + #include "IParticleHandle_TrackParticle.h" +#endif +#include "IParticleCollHandle_Electron.h" +#include "IParticleCollHandle_Muon.h" #include "IParticleCollHandle_TrackParticle.h" -#include "IParticleHandle_TrackParticle.h" +#include "IParticleCollHandle_CaloCluster.h" #include "IParticleCollHandle_Jet.h" -#include "IParticleCollHandle_Muon.h" -#include "IParticleCollHandle_CaloCluster.h" #include "MissingEtCollHandle.h" #include "VertexCollHandle.h" #include "AODSysCommonData.h" @@ -32,8 +35,10 @@ #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" #include "VP1Utils/VP1DetInfo.h" -#include "VP1Utils/VP1AvailableToolsHelper.h" -#include "VP1Utils/VP1ToolAccessHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1AvailableToolsHelper.h" + #include "VP1Utils/VP1ToolAccessHelper.h" +#endif // SoCoin (see if we can shift this to external file?) #include <Inventor/nodes/SoSeparator.h> @@ -52,13 +57,28 @@ #include <sstream> #include <typeinfo> -// Athena -#include "StoreGate/StoreGateSvc.h" -#include "TrkExInterfaces/IExtrapolationEngine.h" +#ifndef BUILDVP1LIGHT + // Athena + #include "StoreGate/StoreGateSvc.h" + #include "TrkExInterfaces/IExtrapolationEngine.h" +#endif // Qt #include <QTreeWidget> +// XAOD +#include "xAODRootAccess/Init.h" +#include "xAODRootAccess/TEvent.h" +#include "xAODRootAccess/TStore.h" +#include "xAODRootAccess/tools/Message.h" +#include "xAODRootAccess/TAuxStore.h" +#include "xAODCore/AuxContainerBase.h" +#include "xAODCore/tools/ReadStats.h" +#include "xAODCore/tools/IOStats.h" + +// ROOT include(s): +#include <TFile.h> +#include <TError.h> class VP1AODSystem::Imp { @@ -73,6 +93,7 @@ public: Amg::Vector3D totmomgev; double totmass; + // TrackCommonFlags::SELECTIONMODE selMode; //Return value is number of track handles used for input (e.g. those without valid momentum info are ignored) @@ -91,11 +112,11 @@ public: template <class T> QList<AODCollHandleBase*> createSpecificCollections(xAOD::Type::ObjectType type) { QList<AODCollHandleBase*> l; - foreach (QString name, T::availableCollections(theclass)) { - T * col = new T(common,name,type); - col->init(); - l << col; - } + foreach (QString name, T::availableCollections(theclass)) { + T * col = new T(common,name,type); + col->init(); + l << col; + } return l; } @@ -108,12 +129,13 @@ public: */ QList<AODCollHandleBase*> createCollections() { QList<AODCollHandleBase*> l; - l << createSpecificCollections<IParticleCollHandle_TrackParticle>(xAOD::Type::TrackParticle); - l << createSpecificCollections<IParticleCollHandle_Jet>(xAOD::Type::Jet); - l << createSpecificCollections<IParticleCollHandle_Muon>(xAOD::Type::Muon); - l << createSpecificCollections<IParticleCollHandle_CaloCluster>(xAOD::Type::CaloCluster); // Calorimeter Clusters - l << createSpecificCollections<MissingEtCollHandle>(xAOD::Type::Other); - l << createSpecificCollections<VertexCollHandle>(xAOD::Type::Vertex); + l << createSpecificCollections<IParticleCollHandle_TrackParticle>(xAOD::Type::TrackParticle); + l << createSpecificCollections<IParticleCollHandle_Jet>(xAOD::Type::Jet); + l << createSpecificCollections<IParticleCollHandle_Muon>(xAOD::Type::Muon); + l << createSpecificCollections<IParticleCollHandle_Electron>(xAOD::Type::Electron); + l << createSpecificCollections<IParticleCollHandle_CaloCluster>(xAOD::Type::CaloCluster); // Calorimeter Clusters + l << createSpecificCollections<MissingEtCollHandle>(xAOD::Type::Other); + l << createSpecificCollections<VertexCollHandle>(xAOD::Type::Vertex); return l; } }; @@ -122,7 +144,8 @@ public: VP1AODSystem::VP1AODSystem(QString name) : IVP13DSystemSimple(name, "System showing all (x)AOD objects.", -"Edward.Moyse@cern.ch, Riccardo.maria.bianchi@cern.ch"), m_d(new Imp) +"Edward.Moyse@cern.ch, Riccardo.maria.bianchi@cern.ch, Sebastian.Andreas.Merkt@cern.ch"), m_d(new Imp) + { m_d->theclass = this; m_d->selObjects = 0; @@ -153,6 +176,7 @@ void VP1AODSystem::systemcreate(StoreGateSvc* /*detstore*/) messageVerbose("systemcreate"); ensureBuildController(); +#ifndef BUILDVP1LIGHT //Get available extrapolators: QString tooltype("Trk::ExtrapolationEngine"); VP1AvailableToolsHelper availTools(this); @@ -162,11 +186,16 @@ void VP1AODSystem::systemcreate(StoreGateSvc* /*detstore*/) foreach (QString value, existingExtrapolators) messageVerbose(value); - VP1ToolAccessHelper toolaccess(this); Trk::IExtrapolationEngine * extrapolator = toolaccess.getToolPointer<Trk::IExtrapolationEngine>("Trk::ExtrapolationEngine/AtlasExtrapolation",false/*silent*/,true/*create if not exists*/); m_d->common->setExtrapolator(extrapolator); +#endif +#ifdef BUILDVP1LIGHT + // Load event from xAOD once AODSystem is created + emit signalLoadEvent(this); +#endif // BUILDVP1LIGHT + // m_d->common->controller()->initTools(); } @@ -648,6 +677,8 @@ void VP1AODSystem::userChangedSelection(SoCooperativeSelection* sel, QSet<SoNode // updateShownTotMomentum(); } +#ifndef BUILDVP1LIGHT +//____________________________________________________________________ void VP1AODSystem::updateAssociatedObjects(const QList<const xAOD::TrackParticle*>& trackparticles) { messageVerbose("updateAssociatedObjects TrackParticle"); @@ -683,6 +714,7 @@ void VP1AODSystem::updateAssociatedObjects(const QList<const xAOD::TrackParticle messageVerbose("updateAssociatedObjects TrackParticle end"); } +#endif // BUILDVP1LIGHT // void VP1AODSystem::updateAssociatedObjects(QList<xAOD::CaloCluster*>& clusters) // { @@ -690,14 +722,17 @@ void VP1AODSystem::updateAssociatedObjects(const QList<const xAOD::TrackParticle // std::cout<<"Got "<<clusters.size() << " from " <<typeid(sender()).name()<<std::endl; // // } - +#ifndef BUILDVP1LIGHT +//____________________________________________________________________ void VP1AODSystem::updateAssociatedObjects(const QList<const xAOD::MuonSegment*>& segments) { messageVerbose("updateAssociatedObjects Segment"); std::cout<<"Got "<<segments.size() << " from " <<typeid(sender()).name()<<std::endl; } +#endif // BUILDVP1LIGHT +//____________________________________________________________________ void VP1AODSystem::dumpToJSON() { @@ -753,7 +788,3 @@ void VP1AODSystem::dumpToJSON() } message("Wrote visible objects to \'EventDump.json\'"); } - - - - diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.cxx index 70f7e932c6a8f75eb362a11d4e35aec7a088ade9..4e0768c7feb99956d326a095e84779fdb544ff72 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.cxx @@ -27,8 +27,10 @@ #include "VP1Base/VP1QtInventorUtils.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" -#include "VP1Utils/VP1SGAccessHelper.h" -#include "VP1Utils/VP1SGContentsHelper.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1SGAccessHelper.h" + #include "VP1Utils/VP1SGContentsHelper.h" +#endif //SoCoin #include <Inventor/nodes/SoSeparator.h> @@ -50,6 +52,14 @@ #include <qdatetime.h> #include <vector> #include <QString> +#include <QDebug> + +#ifdef BUILDVP1LIGHT + #include <QSettings> + #include "xAODRootAccess/Init.h" + #include "xAODRootAccess/TEvent.h" +#endif // BUILDVP1LIGHT + //____________________________________________________________________ class VertexCollHandle::Imp { @@ -112,7 +122,9 @@ VertexCollHandle::~VertexCollHandle() messageVerbose("destructor start"); // clean the vector<handle> - cleanupPtrContainer(m_d->handles); + #ifndef BUILDVP1LIGHT + cleanupPtrContainer(m_d->handles); + #endif // delete the Imp instance delete m_d; @@ -121,10 +133,17 @@ VertexCollHandle::~VertexCollHandle() } //____________________________________________________________________ -QStringList VertexCollHandle::availableCollections( IVP1System*sys ) -{ - return VP1SGContentsHelper(sys).getKeys<xAOD::VertexContainer>(); -} +#if defined BUILDVP1LIGHT + QStringList VertexCollHandle::availableCollections( IVP1System*sys ) + { + return sys->getObjectList(xAOD::Type::Vertex); + } +#else + QStringList VertexCollHandle::availableCollections( IVP1System*sys ) + { + return VP1SGContentsHelper(sys).getKeys<xAOD::VertexContainer>(); + } +#endif // BUILDVP1LIGHT //____________________________________________________________________ @@ -182,11 +201,29 @@ bool VertexCollHandle::load() messageVerbose("loading Vertex collection"); //Get collection: - const xAOD::VertexContainer * coll(0); - if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { - message("Error: Could not retrieve vertex collection with key="+name()); - return false; - } + const xAOD::VertexContainer * coll(nullptr); + + #if defined BUILDVP1LIGHT + // // Get the name of the application: + // const char* appName = "VP1Light"; + + // // Initialize the environment: + // if( !xAOD::Init( appName ).isSuccess() ) { + // message("Failed to execute xAOD::Init"); + // return false; + // } + + // Retrieve objects from the event + if( !(systemBase()->getEvent())->retrieve( coll, name().toStdString()).isSuccess() ) { + message("Error: Could not retrieve collection with key="+name()); + return false; + } + #else + if (!VP1SGAccessHelper(systemBase()).retrieve(coll, name())) { + message("Error: Could not retrieve vertex collection with key="+name()); + return false; + } + #endif //BUILDVP1LIGHT // // Retrieve the xAOD particles: // const xAOD::VertexContainer* xaod = evtStore()->retrieve<const xAOD::VertexContainer>( m_VertexCollection ); @@ -200,6 +237,9 @@ bool VertexCollHandle::load() // sorted out... const_cast< xAOD::VertexContainer* >( coll )->setStore( ( SG::IAuxStore* ) coll->getConstStore() ); + for (auto vertex : *coll) { + qInfo() << " (x, y, z) = (" << vertex->x() << ", " << vertex->y() << ", " << vertex->z() << ")"; // just to print out something + } // end for loop over vertices //Make appropriate vertex handles: xAOD::VertexContainer::const_iterator it, itEnd = coll->end(); @@ -212,7 +252,6 @@ bool VertexCollHandle::load() } addHandle(new VertexHandle(this,*it)); } - return true; } diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.h b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.h index bba9b06d9f474bb2a274e371b5407ec89320c86f..2e36aba5ddfcd071a9de1d6f8716d390fc803fdc 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.h +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexCollHandle.h @@ -26,6 +26,8 @@ //xAOD #include "xAODBase/IParticle.h" +#include "xAODRootAccess/TEvent.h" +#include "xAODRootAccessInterfaces/TVirtualEvent.h" // Qt #include <QtGui/QColor> @@ -34,6 +36,7 @@ //Misc #include <iostream> + class AODSysCommonData; class VertexHandle; class SoSeparator; @@ -54,8 +57,8 @@ public: VertexCollHandle(AODSysCommonData *, const QString& name, - xAOD::Type::ObjectType); - + xAOD::Type::ObjectType); + virtual void init(VP1MaterialButtonBase* matBut=0);//reimplementations must start with a call to VP1StdCollection::init. virtual ~VertexCollHandle(); diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexHandle.cxx b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexHandle.cxx index 0f7032c5fd29989c94901f6050cc80d1004a69ab..810e88dc48008d8d87ecdad51bff3e3dca23e795 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexHandle.cxx +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/VertexHandle.cxx @@ -211,11 +211,13 @@ QStringList VertexHandle::clicked() const QStringList l; l << "--Vertex:"; l << VertexHandle::baseInfo(); - try { - l<< "Has "<<VP1Msg::str(m_d->vertex->vxTrackAtVertex ().size()) <<" associated tracks."; - } catch ( SG::ExcBadAuxVar& ) { - l<<"Vertex is missing links to tracks!"; - } + #ifndef BUILDVP1LIGHT + try { + l<< "Has "<<VP1Msg::str(m_d->vertex->vxTrackAtVertex ().size()) <<" associated tracks."; + } catch ( SG::ExcBadAuxVar& ) { + l<<"Vertex is missing links to tracks!"; + } + #endif return l; } diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/perelectroncollectionsettings_form.ui b/graphics/VP1/VP1Systems/VP1AODSystems/src/perelectroncollectionsettings_form.ui new file mode 100644 index 0000000000000000000000000000000000000000..a703897c2d60159297e911c7b27f4272944bff02 --- /dev/null +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/perelectroncollectionsettings_form.ui @@ -0,0 +1,906 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ElectronCollectionSettingsForm</class> + <widget class="QWidget" name="ElectronCollectionSettingsForm"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>829</width> + <height>1851</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_5"> + <item> + <widget class="QGroupBox" name="groupBox_4"> + <property name="title"> + <string>Electron line options</string> + </property> + <property name="checkable"> + <bool>false</bool> + </property> + <layout class="QVBoxLayout" name="verticalLayout_3"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QLabel" name="label_4"> + <property name="text"> + <string>Track line widths:</string> + </property> + </widget> + </item> + <item> + <widget class="QSlider" name="horizontalSlider_trackWidth"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>100</width> + <height>0</height> + </size> + </property> + <property name="maximum"> + <number>100</number> + </property> + <property name="singleStep"> + <number>10</number> + </property> + <property name="value"> + <number>20</number> + </property> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QCheckBox" name="checkBox_trackTubes"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Display lines with cylinders</string> + </property> + </widget> + </item> + <item> + <widget class="QDoubleSpinBox" name="doubleSpinBox_trackTubesRadiusMM"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="prefix"> + <string>r = </string> + </property> + <property name="suffix"> + <string> mm</string> + </property> + <property name="minimum"> + <double>0.010000000000000</double> + </property> + <property name="value"> + <double>5.000000000000000</double> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </item> + </layout> + </item> + <item> + <widget class="Line" name="line"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_3"> + <item> + <widget class="QCheckBox" name="checkBox_tracksUseBaseLightModel"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Use a less advanced light model for the tracks. This might lead to more clearly visible tracks (but transparency will not be taken into account)</string> + </property> + <property name="text"> + <string>Use base lighting</string> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="checkBox_hideactualpaths"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>Do not display the actual tracks. Projections and other track details (measurements, errors, ...) will still be shown.</string> + </property> + <property name="text"> + <string>Hide line</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox_2"> + <property name="title"> + <string>Propagation</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_9"> + <item> + <layout class="QVBoxLayout" name="verticalLayout_8"> + <item> + <widget class="QRadioButton" name="radioButton_existingParameters"> + <property name="enabled"> + <bool>true</bool> + </property> + <property name="toolTip"> + <string>Try to use a simpler method to draw tracks</string> + </property> + <property name="text"> + <string>Use existing track parameters </string> + </property> + </widget> + </item> + <item> + <widget class="QRadioButton" name="radioButton_extrapolate"> + <property name="text"> + <string>Extrapolate from 1st parameter</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_17"> + <item> + <widget class="QLabel" name="label_2"> + <property name="text"> + <string># steps in interpolation</string> + </property> + </widget> + </item> + <item> + <widget class="QSlider" name="horizontalSlider_numBezierSteps"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="minimumSize"> + <size> + <width>100</width> + <height>0</height> + </size> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10</number> + </property> + <property name="singleStep"> + <number>1</number> + </property> + <property name="value"> + <number>1</number> + </property> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + </widget> + </item> + <item> + <widget class="QLabel" name="label_numBezierSteps"> + <property name="text"> + <string>1</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_11"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Parameters</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_6"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_14"> + <item> + <widget class="QCheckBox" name="checkBox_showparameters"> + <property name="text"> + <string>Show parameters</string> + </property> + </widget> + </item> + <item> + <widget class="QCheckBox" name="checkBox_parameters_colourByType"> + <property name="text"> + <string>Colour parameters by type</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <widget class="QFrame" name="frame_defaultParameterColour"> + <property name="enabled"> + <bool>true</bool> + </property> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Plain</enum> + </property> + <property name="lineWidth"> + <number>0</number> + </property> + <layout class="QHBoxLayout" name="horizontalLayout_16"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_7"> + <item> + <widget class="VP1MaterialButton" name="matButton_parametersDefaultColour"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_7"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>63</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour"> + <property name="text"> + <string>Parameter colour</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_15"> + <item> + <widget class="QFrame" name="frame_parameterTypeColours"> + <property name="enabled"> + <bool>true</bool> + </property> + <property name="frameShape"> + <enum>QFrame::NoFrame</enum> + </property> + <property name="frameShadow"> + <enum>QFrame::Plain</enum> + </property> + <property name="lineWidth"> + <number>0</number> + </property> + <layout class="QVBoxLayout" name="verticalLayout_7"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_8"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_2"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_3"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_2"> + <property name="text"> + <string>Beamline</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_9"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_3"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_4"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_3"> + <property name="text"> + <string>First measurement</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_10"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_4"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_5"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_4"> + <property name="text"> + <string>Last measurement</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_11"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_5"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_6"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_5"> + <property name="text"> + <string>Calorimeter Entrance</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_12"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_6"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_8"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_6"> + <property name="text"> + <string>Calorimeter Exit</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_13"> + <item> + <widget class="VP1MaterialButton" name="pushButton_matButton_parameters_default_colour_7"> + <property name="text"> + <string>Material</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_9"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QLabel" name="label_parameterColour_7"> + <property name="text"> + <string>Muon Entrance</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_10"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QWidget" name="cuts" native="true"> + <property name="enabled"> + <bool>true</bool> + </property> + <layout class="QVBoxLayout" name="verticalLayout_4"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> + <number>0</number> + </property> + <item> + <widget class="QGroupBox" name="groupBox_cuts_momentum"> + <property name="enabled"> + <bool>true</bool> + </property> + <property name="title"> + <string>Momentum cuts</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_2"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_5"> + <item> + <layout class="QGridLayout" name="_5"> + <property name="verticalSpacing"> + <number>4</number> + </property> + <item row="0" column="0"> + <widget class="QCheckBox" name="checkBox_cut_minpt"> + <property name="text"> + <string>Min</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_cut_minpt_gev"> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + <property name="suffix"> + <string> GeV</string> + </property> + <property name="maximum"> + <double>999.990000000000009</double> + </property> + <property name="singleStep"> + <double>0.100000000000000</double> + </property> + <property name="value"> + <double>0.500000000000000</double> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QCheckBox" name="checkBox_cut_maxpt"> + <property name="text"> + <string>Max</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_cut_maxpt_gev"> + <property name="alignment"> + <set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set> + </property> + <property name="suffix"> + <string> GeV</string> + </property> + <property name="maximum"> + <double>999.990000000000009</double> + </property> + <property name="singleStep"> + <double>0.100000000000000</double> + </property> + <property name="value"> + <double>100.000000000000000</double> + </property> + </widget> + </item> + </layout> + </item> + <item> + <widget class="QComboBox" name="comboBox_momtype"> + <item> + <property name="text"> + <string>Pt</string> + </property> + </item> + <item> + <property name="text"> + <string>P</string> + </property> + </item> + </widget> + </item> + <item> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>13</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <widget class="VP1EtaPhiCutWidget" name="etaPhiCutWidget" native="true"/> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox_cuts_summary"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="title"> + <string>Summary cuts</string> + </property> + <layout class="QHBoxLayout" name="horizontalLayout_6"> + <property name="topMargin"> + <number>4</number> + </property> + <property name="rightMargin"> + <number>7</number> + </property> + <property name="bottomMargin"> + <number>4</number> + </property> + <item> + <layout class="QGridLayout" name="gridLayout_lala"> + <property name="spacing"> + <number>1</number> + </property> + <item row="1" column="0"> + <widget class="QCheckBox" name="checkBox_cut_nhits_pixel"> + <property name="toolTip"> + <string>Hide tracks without this many pixel hits. Only applies to tracks with ID information.</string> + </property> + <property name="text"> + <string>Require Pixel hits:</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QSpinBox" name="spinBox_cut_nhits_pixel"/> + </item> + <item row="2" column="0"> + <widget class="QCheckBox" name="checkBox_cut_nhits_sct"> + <property name="toolTip"> + <string>Hide tracks without this many SCT hits. Only applies to tracks with ID information.</string> + </property> + <property name="text"> + <string>Require SCT hits:</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="QSpinBox" name="spinBox_cut_nhits_sct"> + <property name="value"> + <number>1</number> + </property> + </widget> + </item> + <item row="3" column="0"> + <widget class="QCheckBox" name="checkBox_cut_nhits_trt"> + <property name="toolTip"> + <string>Hide tracks without this many TRT hits. Only applies to tracks with ID information.</string> + </property> + <property name="text"> + <string>Require TRT hits:</string> + </property> + </widget> + </item> + <item row="3" column="1"> + <widget class="QSpinBox" name="spinBox_cut_nhits_trt"/> + </item> + <item row="4" column="0"> + <widget class="QCheckBox" name="checkBox_cut_nhits_muon"> + <property name="text"> + <string>Require Muon hits:</string> + </property> + </widget> + </item> + <item row="4" column="1"> + <widget class="QSpinBox" name="spinBox_cut_nhits_muon"/> + </item> + </layout> + </item> + <item> + <widget class="QLabel" name="label"> + <property name="autoFillBackground"> + <bool>false</bool> + </property> + <property name="text"> + <string>ID requirements only apply to tracks with ID hits (i.e. not MS standalone tracks)</string> + </property> + <property name="wordWrap"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_2"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>14</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QCheckBox" name="checkBox_vertexAssociated"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="toolTip"> + <string>The vertex system must be enabled for this to be usable.</string> + </property> + <property name="text"> + <string>Only show Vertex associated tracks</string> + </property> + <property name="checked"> + <bool>false</bool> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="_2"> + <item> + <spacer> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="pushButton_close"> + <property name="text"> + <string>&Close</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <customwidgets> + <customwidget> + <class>VP1MaterialButton</class> + <extends>QPushButton</extends> + <header>VP1Base/VP1MaterialButton.h</header> + </customwidget> + <customwidget> + <class>VP1EtaPhiCutWidget</class> + <extends>QWidget</extends> + <header>VP1Base/VP1EtaPhiCutWidget.h</header> + <container>1</container> + </customwidget> + </customwidgets> + <resources/> + <connections> + <connection> + <sender>checkBox_parameters_colourByType</sender> + <signal>toggled(bool)</signal> + <receiver>frame_parameterTypeColours</receiver> + <slot>setVisible(bool)</slot> + <hints> + <hint type="sourcelabel"> + <x>214</x> + <y>201</y> + </hint> + <hint type="destinationlabel"> + <x>214</x> + <y>371</y> + </hint> + </hints> + </connection> + <connection> + <sender>checkBox_parameters_colourByType</sender> + <signal>toggled(bool)</signal> + <receiver>frame_defaultParameterColour</receiver> + <slot>setHidden(bool)</slot> + <hints> + <hint type="sourcelabel"> + <x>214</x> + <y>201</y> + </hint> + <hint type="destinationlabel"> + <x>214</x> + <y>239</y> + </hint> + </hints> + </connection> + <connection> + <sender>horizontalSlider_numBezierSteps</sender> + <signal>valueChanged(int)</signal> + <receiver>label_numBezierSteps</receiver> + <slot>setNum(int)</slot> + <hints> + <hint type="sourcelabel"> + <x>312</x> + <y>207</y> + </hint> + <hint type="destinationlabel"> + <x>416</x> + <y>207</y> + </hint> + </hints> + </connection> + </connections> +</ui> diff --git a/graphics/VP1/VP1Systems/VP1AODSystems/src/pertrackparticlecollectionsettings_form.ui b/graphics/VP1/VP1Systems/VP1AODSystems/src/pertrackparticlecollectionsettings_form.ui index 300dc4bc7e2230638a5ef6910309de8911ff1f4b..bcc39de29a523df79a2e99d018c3f651c210ea58 100644 --- a/graphics/VP1/VP1Systems/VP1AODSystems/src/pertrackparticlecollectionsettings_form.ui +++ b/graphics/VP1/VP1Systems/VP1AODSystems/src/pertrackparticlecollectionsettings_form.ui @@ -6,8 +6,8 @@ <rect> <x>0</x> <y>0</y> - <width>430</width> - <height>892</height> + <width>829</width> + <height>1851</height> </rect> </property> <property name="windowTitle"> @@ -169,6 +169,9 @@ <property name="text"> <string>Use existing track parameters </string> </property> + <property name="checked"> + <bool>false</bool> + </property> </widget> </item> <item> @@ -551,7 +554,16 @@ <bool>true</bool> </property> <layout class="QVBoxLayout" name="verticalLayout_4"> - <property name="margin"> + <property name="leftMargin"> + <number>0</number> + </property> + <property name="topMargin"> + <number>0</number> + </property> + <property name="rightMargin"> + <number>0</number> + </property> + <property name="bottomMargin"> <number>0</number> </property> <item> diff --git a/graphics/VP1/VP1Systems/VP1GeometrySystems/CMakeLists.txt b/graphics/VP1/VP1Systems/VP1GeometrySystems/CMakeLists.txt index 72a59b24ebb2974cfff8b0a9fce276b932b2ef58..732553073e1ee4b5c0610a638f5bfa371ba140fd 100644 --- a/graphics/VP1/VP1Systems/VP1GeometrySystems/CMakeLists.txt +++ b/graphics/VP1/VP1Systems/VP1GeometrySystems/CMakeLists.txt @@ -16,14 +16,20 @@ atlas_depends_on_subdirs( graphics/VP1/VP1Base PRIVATE DetectorDescription/GeoModel/GeoModelUtilities + DetectorDescription/GeoModel/GeoModelExamples + DetectorDescription/GeoModel/GeoModelStandalone/GeoModelDBManager + DetectorDescription/GeoModel/GeoModelStandalone/GeoRead graphics/VP1/VP1HEPVis graphics/VP1/VP1Utils ) # External dependencies: find_package( CLHEP ) find_package( Coin3D ) -find_package( Qt5 COMPONENTS Core Gui Widgets ) +find_package( Qt5 COMPONENTS Core Gui Widgets Sql ) find_package( GeoModel ) +if( APPLE ) + find_package(OpenGL REQUIRED) +endif() # Find includes in corresponding build directories set(CMAKE_INCLUDE_CURRENT_DIR ON) @@ -40,6 +46,7 @@ set( CMAKE_AUTORCC ON ) # CMAKE_CURRENT_BINARY_DIR, so it needs to be added explicitly to the # declaration of PRIVATE_INCLUDE_DIRS. +if(NOT BUILDVP1LIGHT) atlas_add_library( VP1GeometrySystems VP1GeometrySystems/*.h src/*.cxx PUBLIC_HEADERS VP1GeometrySystems @@ -48,3 +55,48 @@ atlas_add_library( VP1GeometrySystems PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS} LINK_LIBRARIES ${COIN3D_LIBRARIES} ${GEOMODEL_LIBRARIES} MuonReadoutGeometry TruthUtils xAODTruth VP1Base GL Qt5::Core Qt5::Widgets PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} GeoModelUtilities VP1HEPVis VP1Utils Qt5::Gui ) +endif() +if(BUILDVP1LIGHT) +# Files +file(GLOB SOURCES src/DumpShape.cxx + src/VP1GeomUtils.cxx + src/VolumeTreeModel.cxx + src/GeoSysController.cxx + src/VP1GeometrySystem.cxx + src/ZappedVolumeListModel.cxx + src/PhiSectorManager.cxx + src/VisAttributes.cxx + src/VP1GeoFlags.cxx + src/VolumeHandle.cxx + src/VP1GeoTreeView.cxx + src/VolumeHandleSharedData.cxx + ) +file(GLOB HEADERS VP1GeometrySystems/PhiSectorManager.h + VP1GeometrySystems/ZappedVolumeListModel.h + VP1GeometrySystems/GeoSysController.h + VP1GeometrySystems/VP1GeometrySystem.h + VP1GeometrySystems/VP1GeoTreeView.h + VP1GeometrySystems/VolumeTreeModel.h +) + +if( APPLE ) + atlas_add_library( VP1GeometrySystems + ${HEADERS} ${SOURCES} + PUBLIC_HEADERS VP1GeometrySystems + INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} + PRIVATE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} + PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS} + LINK_LIBRARIES ${COIN3D_LIBRARIES} ${GEOMODEL_LIBRARIES} GeoModelDBManager GeoRead TruthUtils xAODTruth VP1Base ${OPENGL_gl_LIBRARY} Qt5::Core Qt5::Widgets + PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} GeoModelUtilities GeoModelExamplesLib VP1HEPVis VP1Utils Qt5::Gui Qt5::Sql ) +endif() +if( UNIX AND NOT APPLE ) + atlas_add_library( VP1GeometrySystems + ${HEADERS} ${SOURCES} + PUBLIC_HEADERS VP1GeometrySystems + INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} + PRIVATE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} + PRIVATE_DEFINITIONS ${CLHEP_DEFINITIONS} + LINK_LIBRARIES ${COIN3D_LIBRARIES} ${GEOMODEL_LIBRARIES} GeoModelDBManager GeoRead TruthUtils xAODTruth VP1Base GL Qt5::Core Qt5::Widgets + PRIVATE_LINK_LIBRARIES ${CLHEP_LIBRARIES} GeoModelUtilities GeoModelExamplesLib VP1HEPVis VP1Utils Qt5::Gui Qt5::Sql ) +endif() +endif() diff --git a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/GeoSysController.cxx b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/GeoSysController.cxx index 633fb90912fa3ebc69e287a0344e385a0296b306..4cbb3eeaced4760bc6781431c821adc2a43c6014 100644 --- a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/GeoSysController.cxx +++ b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/GeoSysController.cxx @@ -20,7 +20,9 @@ #include "VP1Base/VP1Deserialise.h" #include "VP1Base/VP1Settings.h" #include "VP1Base/IVP1System.h" -#include "VP1Utils/VP1JobConfigInfo.h" +#ifndef BUILDVP1LIGHT + #include "VP1Utils/VP1JobConfigInfo.h" +#endif #include "ui_geometrysystemcontroller.h" #include "ui_settings_display_form.h" @@ -87,6 +89,7 @@ GeoSysController::GeoSysController(IVP1System * sys) m_d->pickStyle = new SoPickStyle; m_d->pickStyle->ref(); + #ifndef BUILDVP1LIGHT //Possibly hide parts of gui, depending on job configuration: if (!VP1JobConfigInfo::hasGeoModelExperiment()) { m_d->ui.groupBox_innerdetector->setVisible(false); @@ -114,6 +117,7 @@ GeoSysController::GeoSysController(IVP1System * sys) m_d->ui_muon.groupBox_muonchamberconfig->setVisible(VP1JobConfigInfo::hasMuonGeometry()); m_d->ui_int.checkBox_AutomaticMuonChamberEndViews->setVisible(VP1JobConfigInfo::hasMuonGeometry()); } + #endif m_d->zappedVolumeListModel = new ZappedVolumeListModel(m_d->ui_iconisedvols.listView_iconisedvolumes); diff --git a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VP1GeometrySystem.cxx b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VP1GeometrySystem.cxx index 8ce1c04fdc7e5c5c71de0ef849fda6c24a2a258b..1f7c680abfc32b0e39621e74d6d35e70f1a90cdf 100644 --- a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VP1GeometrySystem.cxx +++ b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VP1GeometrySystem.cxx @@ -20,7 +20,6 @@ #include "VP1GeometrySystems/VP1GeoTreeView.h" #include "VP1GeometrySystems/VolumeHandle.h" -#include "VP1GeometrySystems/MuonVolumeHandle.h" #include "VP1GeometrySystems/VolumeHandleSharedData.h" #include "VP1GeometrySystems/VolumeTreeModel.h" #include "VP1GeometrySystems/VP1GeomUtils.h" @@ -28,15 +27,13 @@ #include "VP1GeometrySystems/DumpShape.h" #include "VP1GeometrySystems/PhiSectorManager.h" -#include "VP1Utils/VP1JobConfigInfo.h" -#include "VP1Utils/VP1SGAccessHelper.h" #include "VP1Utils/VP1LinAlgUtils.h" -#include "VP1Utils/VP1DetInfo.h" #include "VP1Base/VP1CameraHelper.h" #include "VP1Base/VP1QtInventorUtils.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoSwitch.h> #include <Inventor/events/SoKeyboardEvent.h> @@ -50,6 +47,11 @@ #include "GeoModelKernel/GeoPrintGraphAction.h" #include "GeoModelUtilities/GeoModelExperiment.h" +#ifndef BUILDVP1LIGHT +#include "VP1GeometrySystems/MuonVolumeHandle.h" +#include "VP1Utils/VP1JobConfigInfo.h" +#include "VP1Utils/VP1SGAccessHelper.h" +#include "VP1Utils/VP1DetInfo.h" #include "MuonReadoutGeometry/MuonDetectorManager.h" #include "MuonReadoutGeometry/MdtReadoutElement.h" #include "MuonReadoutGeometry/CscReadoutElement.h" @@ -57,7 +59,25 @@ #include "MuonReadoutGeometry/RpcReadoutElement.h" #include "MuonReadoutGeometry/MuonReadoutElement.h" #include "MuonReadoutGeometry/MuonStation.h" +#endif + +#ifdef BUILDVP1LIGHT +#include "GeoModelKernel/GeoBox.h" +#include "GeoModelKernel/GeoCountVolAction.h" +#include "GeoModelKernel/GeoAccessVolumeAction.h" +#include "GeoModelDBManager/GMDBManager.h" +#include "GeoRead/GReadIn.h" +// #include "GeoModelExamples/ToyDetectorFactory.h" +//#include "GeoModelExamples/SimplestToyDetectorFactory.h" + +#include <QStack> +#include <QString> +#include <QSettings> +#endif // BUILDVP1LIGHT + + +#include <QDebug> #include <QRegExp> #include <QByteArray> #include <QTimer> @@ -71,12 +91,15 @@ class VP1GeometrySystem::Imp { public: - Imp (VP1GeometrySystem*gs,const VP1GeoFlags::SubSystemFlags& ssf) + Imp (VP1GeometrySystem*gs, const VP1GeoFlags::SubSystemFlags& ssf) : theclass(gs), sceneroot(0), detVisAttributes(0), matVisAttributes(0), volVisAttributes(0), initialSubSystemsTurnedOn(ssf),controller(0),phisectormanager(0), volumetreemodel(0),kbEvent(0),previousAlignedChamberHandle(0), - last_appropriatemdtprojections(-1),pv2MuonStationInit(false),m_textSep(0) + last_appropriatemdtprojections(-1),m_textSep(0) + #ifndef BUILDVP1LIGHT + ,pv2MuonStationInit(false) + #endif { const unsigned n_chamber_t0_sources=2; for (unsigned i=0;i<n_chamber_t0_sources;++i) @@ -89,6 +112,14 @@ public: std::map<SoSeparator*,VolumeHandle*> sonodesep2volhandle; //Might be needed later: std::map<GeoPVConstLink,VolumeHandle*> pv2volhandle; + #ifdef BUILDVP1LIGHT + GeoModelExperiment* getGeometry(); + GeoModelExperiment* createTheExperiment(GeoPhysVol* world = nullptr); + GeoModelExperiment* getGeometryFromLocalDB(); + GeoModelExperiment* getDummyGeometry(); + #endif + + class SubSystemInfo { public: // "geomodellocation" contains name of tree tops, or possible a @@ -167,8 +198,11 @@ public: } bool grandchildrenRegExpNameCompatible(const std::string& volname) const { - //std::cout << "volname: " << volname << " - regexpr: " << geomodelgrandchildrenregexp.pattern().toStdString() << std::endl; - return negategrandchildrenregexp!=geomodelgrandchildrenregexp.exactMatch(volname.c_str()); + if(VP1Msg::debug()){ + std::cout << "volname: " << volname << " - regexpr: " << geomodelgrandchildrenregexp.pattern().toStdString() << std::endl; + std::cout << "negategrandchildrenregexp: " << negategrandchildrenregexp << std::endl; + } + return negategrandchildrenregexp!=geomodelgrandchildrenregexp.exactMatch(volname.c_str()); } void dump() const { @@ -235,11 +269,15 @@ public: void changeStateOfVisibleNonStandardVolumesRecursively(VolumeHandle*,VP1GeoFlags::VOLSTATE); void expandVisibleVolumesRecursively(VolumeHandle*,const QRegExp&,bool bymatname); - std::map<GeoPVConstLink,const MuonGM::MuonStation*> pv2MuonStation; - bool pv2MuonStationInit; - void ensureInitPV2MuonStationMap(); - void updatePV2MuonStationMap(const MuonGM::MuonReadoutElement* elem); - QStringList stationInfo(const MuonGM::MuonStation*); + SoSeparator* m_textSep;//!< Separator used to hold all visible labels. + + #ifndef BUILDVP1LIGHT + std::map<GeoPVConstLink,const MuonGM::MuonStation*> pv2MuonStation; + bool pv2MuonStationInit; + void ensureInitPV2MuonStationMap(); + void updatePV2MuonStationMap(const MuonGM::MuonReadoutElement* elem); + QStringList stationInfo(const MuonGM::MuonStation*); + #endif void showPixelModules(VolumeHandle*); void showSCTBarrelModules(VolumeHandle*); @@ -253,7 +291,6 @@ public: // path entries (top level volumes, python envelopes) depending on the subsystem of the selected volume void createPathExtras(const VolumeHandle*, QString&, QStack<QString>&); - SoSeparator* m_textSep;//!< Separator used to hold all visible labels. QList<const std::map<GeoPVConstLink, float>*> chamberT0s; }; @@ -261,7 +298,7 @@ public: VP1GeometrySystem::VP1GeometrySystem( const VP1GeoFlags::SubSystemFlags& SubSystemsTurnedOn, QString name ) : IVP13DSystemSimple(name, "This system displays the geometry as defined by GeoModel.", - "Thomas.Kittelmann@cern.ch"), + "Riccardo.Maria.Bianchi@cern.ch"), m_d(new Imp(this,SubSystemsTurnedOn)) { } @@ -325,7 +362,7 @@ void VP1GeometrySystem::Imp::addSubSystem(const VP1GeoFlags::SubSystemFlag& f, const std::string& matname, bool negatetreetopregexp, bool negatechildrenregexp, const QString& grandchildrenregexp, bool negategrandchildrenregexp) { - theclass->message("VP1GeometrySystem::Imp::addSubSystem - "+str(matname.c_str()) ); + theclass->message("VP1GeometrySystem::Imp::addSubSystem - flag: '" + QString(f) + "' - matName: '" + str(matname.c_str()) + "'." ); QCheckBox * cb = controller->subSystemCheckBox(f); if (!cb) { @@ -464,18 +501,23 @@ void VP1GeometrySystem::buildPermanentSceneGraph(StoreGateSvc*/*detstore*/, SoSe { m_d->sceneroot = root; - if (!VP1JobConfigInfo::hasGeoModelExperiment()) { - message("Error: GeoModel not configured properly in job."); - return; - } + #ifndef BUILDVP1LIGHT + if (!VP1JobConfigInfo::hasGeoModelExperiment()) { + message("Error: GeoModel not configured properly in job."); + return; + } - //Get the world volume: - const GeoModelExperiment * theExpt; - if (!VP1SGAccessHelper(this,true).retrieve(theExpt,"ATLAS")) { - message("Error: Could not retrieve the ATLAS GeoModelExperiment from detector store"); - return; - } - + //Get the world volume: + const GeoModelExperiment * theExpt; + if (!VP1SGAccessHelper(this,true).retrieve(theExpt,"ATLAS")) { + message("Error: Could not retrieve the ATLAS GeoModelExperiment from detector store"); + return; + } + #endif + + #ifdef BUILDVP1LIGHT + GeoModelExperiment* theExpt = m_d->getGeometry(); + #endif PVConstLink world(theExpt->getPhysVol()); if (!m_d->m_textSep) { @@ -503,10 +545,13 @@ void VP1GeometrySystem::buildPermanentSceneGraph(StoreGateSvc*/*detstore*/, SoSe root->addChild(m_d->controller->drawOptions()); root->addChild(m_d->controller->pickStyle()); + if(VP1Msg::debug()){ + qDebug() << "Configuring the default systems... - subsysInfoList len:" << (m_d->subsysInfoList).length(); + } // we switch on the systems flagged to be turned on at start foreach (Imp::SubSystemInfo * subsys, m_d->subsysInfoList) { - messageDebug("Switching on this system: " + QString::fromStdString(subsys->matname) + " - " + subsys->flag); + VP1Msg::messageDebug("Switching on this system: " + QString::fromStdString(subsys->matname) + " - " + subsys->flag); bool on(m_d->initialSubSystemsTurnedOn & subsys->flag); subsys->checkbox->setChecked( on ); subsys->checkbox->setEnabled(false); @@ -518,14 +563,19 @@ void VP1GeometrySystem::buildPermanentSceneGraph(StoreGateSvc*/*detstore*/, SoSe QCheckBox * checkBoxOther = m_d->controller->subSystemCheckBox(VP1GeoFlags::AllUnrecognisedVolumes); + if(VP1Msg::debug()){ + qDebug() << "Looping on volumes from the input GeoModel..."; + } GeoVolumeCursor av(world); while (!av.atEnd()) { std::string name = av.getName(); - + if(VP1Msg::debug()){ + qDebug() << "volume name:" << QString::fromStdString(name); + } // DEBUG - messageDebug("DEBUG: Found GeoModel treetop: "+QString(name.c_str())); + VP1Msg::messageDebug("DEBUG: Found GeoModel treetop: "+QString(name.c_str())); //Let us see if we recognize this volume: bool found = false; @@ -536,7 +586,11 @@ void VP1GeometrySystem::buildPermanentSceneGraph(StoreGateSvc*/*detstore*/, SoSe continue;//The "other" subsystem has a wildcard which matches everything - but we only want stuff that is nowhere else. } - found = true; + if(VP1Msg::debug()){ + qDebug() << (subsys->geomodeltreetopregexp).pattern() << subsys->geomodeltreetopregexp.exactMatch(name.c_str()) << subsys->negatetreetopregexp; + qDebug() << "setting 'found' to TRUE for pattern:" << (subsys->geomodeltreetopregexp).pattern(); + } + found = true; //We did... now, time to extract info: subsys->treetopinfo.resize(subsys->treetopinfo.size()+1); subsys->treetopinfo.back().pV = av.getVolume(); @@ -599,6 +653,111 @@ void VP1GeometrySystem::buildPermanentSceneGraph(StoreGateSvc*/*detstore*/, SoSe QTimer::singleShot(0, this, SLOT(emit_appropriateMDTProjectionsChanged())); } +#ifdef BUILDVP1LIGHT +//_____________________________________________________________________________________ +GeoModelExperiment* VP1GeometrySystem::Imp::getGeometry() +{ + // return getDummyGeometry(); // for test + return getGeometryFromLocalDB(); // for production +} +#endif + +#ifdef BUILDVP1LIGHT +//_____________________________________________________________________________________ +GeoModelExperiment* VP1GeometrySystem::Imp::createTheExperiment(GeoPhysVol* world) +{ + if (world == nullptr) + { + // Setup the 'World' volume from which everything else will be suspended + double densityOfAir=0.1; + const GeoMaterial* worldMat = new GeoMaterial("std::Air", densityOfAir); + const GeoBox* worldBox = new GeoBox(1000*CLHEP::cm, 1000*CLHEP::cm, 1000*CLHEP::cm); + const GeoLogVol* worldLog = new GeoLogVol("WorldLog", worldBox, worldMat); + // GeoPhysVol* worldPhys = new GeoPhysVol(worldLog); + world = new GeoPhysVol(worldLog); + } + // Setup the 'Experiment' manager + GeoModelExperiment* theExperiment = new GeoModelExperiment(world); + return theExperiment; +} + + +//_____________________________________________________________________________________ +GeoModelExperiment* VP1GeometrySystem::Imp::getDummyGeometry() +{ + // create the world volume container and its manager + GeoModelExperiment* theExperiment = createTheExperiment(); + //GeoPhysVol* world = theExperiment->getPhysVol(); + +// // we create the 'detector' geometry and we add it to the world volume +// ToyDetectorFactory factory(NULL); // more complex geometry example +// // SimplestToyDetectorFactory factory(NULL); // more complex geometry example +// factory.create(world); +// std::cout << "treetop numbers: " << factory.getDetectorManager()->getNumTreeTops() << std::endl; + VP1Msg::messageDebug("Method VP1GeometrySystem::Imp::getDummyGeometry() has to be ported to the new GeoModel structure."); + + return theExperiment; +} + + +//_____________________________________________________________________________________ +GeoModelExperiment* VP1GeometrySystem::Imp::getGeometryFromLocalDB() +{ + + // GET GEOMETRY FROM LOCAL DB + // Set valid db path before first run + // static const QString path = "../../local/data/geometry.db"; + QSettings settings("ATLAS", "VP1Light"); + QString path = settings.value("db/path").toString(); + if(VP1Msg::debug()){ + qDebug() << "Using this DB file:" << path; + } + + + // check if DB file exists. If not, return + if (! QFileInfo(path).exists() ) { + qWarning() << "ERROR!! DB '" << path << "' does not exist!!"; + qWarning() << "Returning..." << "\n"; + // return; + throw; + } + // open the DB + GMDBManager* db = new GMDBManager(path); + /* Open database */ + if (db->isOpen()) { + if(VP1Msg::debug()){ + qDebug() << "OK! Database is open!"; + } + } + else { + if(VP1Msg::debug()){ + qDebug() << "Database is not open!"; + } + // return; + throw; + } + + /* setup the GeoModel reader */ + GeoModelPers::GReadIn readInGeo = GeoModelPers::GReadIn(db); + if(VP1Msg::debug()){ + qDebug() << "GReadIn set."; + } + + /* build the GeoModel geometry */ + GeoPhysVol* dbPhys = readInGeo.buildGeoModel(); // builds the whole GeoModel tree in memory + // GeoPhysVol* worldPhys = readInGeo.getGeoModelHandle(); // get only the root volume and its first-level children + if(VP1Msg::debug()){ + qDebug() << "GReadIn::buildGeoModel() done."; + } + // create the world volume container and its manager + GeoModelExperiment* theExperiment = createTheExperiment(dbPhys); + // GeoPhysVol* world = theExperiment->getPhysVol(); + + return theExperiment; + +} +#endif + //_____________________________________________________________________________________ void VP1GeometrySystem::checkboxChanged() { @@ -664,7 +823,7 @@ void VP1GeometrySystem::userPickedNode(SoNode* , SoPath *pickedPath) // soshape node represents the volume). - messageDebug("VP1GeometrySystem::userPickedNode()"); + VP1Msg::messageDebug("VP1GeometrySystem::userPickedNode()"); if (pickedPath->getNodeFromTail(0)->getTypeId()==SoCylinder::getClassTypeId()) pickedPath->pop(); @@ -865,6 +1024,7 @@ void VP1GeometrySystem::userPickedNode(SoNode* , SoPath *pickedPath) if (m_d->controller->printInfoOnClick_MuonStationInfo()&&volhandle->isInMuonChamber()) { PVConstLink pvlink = volhandle->topLevelParent()->geoPVConstLink(); std::map<PVConstLink,VolumeHandle*>::const_iterator itChamber = m_d->muonchambers_pv2handles.find(pvlink); + #ifndef BUILDVP1LIGHT if (itChamber!=m_d->muonchambers_pv2handles.end()) { m_d->ensureInitPV2MuonStationMap(); std::map<GeoPVConstLink,const MuonGM::MuonStation*>::const_iterator itStation(m_d->pv2MuonStation.find(pvlink)); @@ -873,6 +1033,7 @@ void VP1GeometrySystem::userPickedNode(SoNode* , SoPath *pickedPath) message(" ",m_d->stationInfo(itStation->second)); } } + #endif } ////////////////////////////////////////////// @@ -919,7 +1080,7 @@ void VP1GeometrySystem::userPickedNode(SoNode* , SoPath *pickedPath) //_____________________________________________________________________________________ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) { - theclass->messageDebug("VP1GeometrySystem::Imp::buildSystem()" ); + VP1Msg::messageDebug("VP1GeometrySystem::Imp::buildSystem()" ); if (!si||si->isbuilt) return; @@ -927,11 +1088,13 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) int ichild(0); ensureInitVisAttributes(); - ensureInitPV2MuonStationMap(); // Needed for Muon Station names. + #ifndef BUILDVP1LIGHT + ensureInitPV2MuonStationMap(); // Needed for Muon Station names. + #endif // // DEBUG // foreach(Imp::SubSystemInfo*si,m_d->subsysInfoList) { -// theclass->messageDebug("vol: " + QString((si->flag).str_c()) ); +// VP1Msg::messageDebug("vol: " + QString((si->flag).str_c()) ); // } assert(si->soswitch); @@ -947,7 +1110,7 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) std::vector<SubSystemInfo::TreetopInfo>::const_iterator it, itE = si->treetopinfo.end(); for (it=si->treetopinfo.begin();it!=itE;++it) { - theclass->messageDebug("toptree vol: " + QString(it->volname.c_str()) ); + VP1Msg::messageDebug("toptree vol: " + QString(it->volname.c_str()) ); //Find material: SoMaterial*m = detVisAttributes->get(it->volname); @@ -968,7 +1131,7 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) std::vector<SubSystemInfo::TreetopInfo>::const_iterator it, itE = si->treetopinfo.end(); for (it=si->treetopinfo.begin();it!=itE;++it) { - theclass->messageDebug("group name: " + QString(si->matname.c_str()) ); + VP1Msg::messageDebug("group name: " + QString(si->matname.c_str()) ); //NB: Here we use the si->matname. Above we use the si->volname. Historical reasons! @@ -989,7 +1152,7 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) while (!av.atEnd()) { // DEBUG -// theclass->messageDebug("child vol: " + QString(av.getName().c_str()) ); +// VP1Msg::messageDebug("child vol: " + QString(av.getName().c_str()) ); //Use the childrenregexp to select the correct child volumes: if (si->childrenRegExpNameCompatible(av.getName().c_str())) { @@ -1001,9 +1164,16 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) // si->dump(); // std::cout<<"---"<<std::endl; if (hasMuonChambers){ + #ifndef BUILDVP1LIGHT vh = new MuonVolumeHandle(volhandle_subsysdata,0,pVD,ichild++,VolumeHandle::MUONCHAMBER_DIRTY,matr,pv2MuonStation[pVD],chamberT0s); - muonchambers_pv2handles[pVD] = vh; - // std::cout<<"Has muon chamber VH="<<vh<<std::endl; + #endif + #ifdef BUILDVP1LIGHT + vh = new VolumeHandle(volhandle_subsysdata,0,pVD,ichild++,VolumeHandle::MUONCHAMBER_DIRTY,matr); + #endif + muonchambers_pv2handles[pVD] = vh; + if(VP1Msg::debug()){ + std::cout<<"Has muon chamber VH="<<vh<<std::endl; + } } else { @@ -1013,7 +1183,7 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) } // DEBUG -// theclass->messageDebug("granchild vol: " + vh->getName() + " - " + vh->getDescriptiveName() ); +// VP1Msg::messageDebug("granchild vol: " + vh->getName() + " - " + vh->getDescriptiveName() ); if (si->geomodelgrandchildrenregexp.isEmpty()) { // append the volume to the current list @@ -1021,9 +1191,9 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) si->vollist.push_back(vh); } else { - theclass->messageDebug("filtering at grandchild level..."); + VP1Msg::messageDebug("filtering at grandchild level..."); if (si->grandchildrenRegExpNameCompatible(vh->getName().toStdString() ) ) { - theclass->messageDebug("filtered grandchild inserted : " + vh->getDescriptiveName() + " - " + vh->getName() ); + VP1Msg::messageDebug("filtered grandchild inserted : " + vh->getDescriptiveName() + " - " + vh->getName() ); // append the volume to the current list si->vollist.push_back(vh); } else { @@ -1040,26 +1210,36 @@ void VP1GeometrySystem::Imp::buildSystem(SubSystemInfo* si) } } - // std::cout<<"volumetreemodel->addSubSystem"<<std::endl; + + si->dump(); + + VP1Msg::messageDebug("volumetreemodel->addSubSystem..."); volumetreemodel->addSubSystem( si->flag, si->vollist ); //NB: We let the destructor of volumetreemodel take care of deleting //our (top) volume handles, since it has to keep a list of them //anyway. + //Perform auto expansion of all ether volumes (needed for muon dead material): + VP1Msg::messageDebug("Perform auto expansion of all ether volumes (needed for muon dead material)"); VolumeHandle::VolumeHandleListItr it, itE(si->vollist.end()); + //int idx=0; // for debug for (it = si->vollist.begin(); it!=itE; ++it){ + //VP1Msg::messageDebug("\nexpanding idx: " + QString::number(++idx)); (*it)->expandMothersRecursivelyToNonEther(); + //VP1Msg::messageDebug("expand DONE."); } + + VP1Msg::messageDebug("addChild..."); phisectormanager->updateRepresentationsOfVolsAroundZAxis(); phisectormanager->largeChangesEnd(); si->soswitch->addChild(subsystemsep); si->soswitch->enableNotify(save); if (save) si->soswitch->touch(); - theclass->messageDebug("END of VP1GeometrySystem::Imp::buildSystem() " ); + VP1Msg::messageDebug("END of VP1GeometrySystem::Imp::buildSystem() " ); } //_____________________________________________________________________________________ @@ -1538,11 +1718,11 @@ void VP1GeometrySystem::Imp::updateTouchedMuonChamber(VolumeHandle * chamberhand //_____________________________________________________________________________________ VP1GeometrySystem::Imp::SubSystemInfo * VP1GeometrySystem::Imp::chamberPVToMuonSubSystemInfo(const GeoPVConstLink& chamberPV) { - theclass->messageDebug("VP1GeometrySystem::Imp::chamberPVToMuonSubSystemInfo()"); + VP1Msg::messageDebug("VP1GeometrySystem::Imp::chamberPVToMuonSubSystemInfo()"); std::string name = chamberPV->getLogVol()->getName(); - theclass->messageDebug("name: " + QString::fromStdString(name) ); + VP1Msg::messageDebug("name: " + QString::fromStdString(name) ); foreach (SubSystemInfo * subsys, subsysInfoList) { if (!subsys->hasMuonChambers()) @@ -1851,7 +2031,7 @@ void VP1GeometrySystem::actionOnAllNonStandardVolumes(bool zap) void VP1GeometrySystem::autoExpandByVolumeOrMaterialName(bool bymatname,QString targetname) { if (targetname.isEmpty()) { - messageDebug("targetname is empty."); + VP1Msg::messageDebug("targetname is empty."); return; } @@ -1905,6 +2085,7 @@ void VP1GeometrySystem::Imp::expandVisibleVolumesRecursively(VolumeHandle* handl expandVisibleVolumesRecursively(*it,selregexp,bymatname); } +#ifndef BUILDVP1LIGHT //_____________________________________________________________________________________ void VP1GeometrySystem::Imp::updatePV2MuonStationMap(const MuonGM::MuonReadoutElement* elem) { @@ -1923,7 +2104,7 @@ void VP1GeometrySystem::Imp::updatePV2MuonStationMap(const MuonGM::MuonReadoutEl void VP1GeometrySystem::Imp::ensureInitPV2MuonStationMap() { if (pv2MuonStationInit) { - theclass->messageDebug("MuonStation map already initialized."); + VP1Msg::messageDebug("MuonStation map already initialized."); return; } pv2MuonStationInit = true; @@ -1931,7 +2112,7 @@ void VP1GeometrySystem::Imp::ensureInitPV2MuonStationMap() const MuonGM::MuonDetectorManager * mgr = VP1DetInfo::muonDetMgr(); if (!mgr) { - theclass->message("WARNING: Could not get muon detector manager to construct volume -> muon station map!"); + VP1Msg::message("WARNING: Could not get muon detector manager to construct volume -> muon station map!"); return; } @@ -1944,7 +2125,7 @@ void VP1GeometrySystem::Imp::ensureInitPV2MuonStationMap() for (unsigned i = 0; i < mgr->TgcRElMaxHash; ++i) updatePV2MuonStationMap(mgr->getTgcReadoutElement(i)); - theclass->messageDebug("Initialised physical volume link -> MuonStation map. Found "+str(pv2MuonStation.size())+" stations."); + VP1Msg::messageDebug("Initialised physical volume link -> MuonStation map. Found "+str(pv2MuonStation.size())+" stations."); } @@ -1960,12 +2141,15 @@ QStringList VP1GeometrySystem::Imp::stationInfo(const MuonGM::MuonStation* stati l << "(Eta,Phi) index: ("+str(station->getEtaIndex())+", "+str(station->getPhiIndex())+")"; return l; } +#endif //_____________________________________________________________________________________ void VP1GeometrySystem::autoAdaptPixelsOrSCT(bool pixel,bool brl, bool ecA, bool ecC, bool bcmA, bool bcmC) { - if (!(pixel?VP1JobConfigInfo::hasPixelGeometry():VP1JobConfigInfo::hasSCTGeometry())) - return; + #ifndef BUILDVP1LIGHT + if (!(pixel?VP1JobConfigInfo::hasPixelGeometry():VP1JobConfigInfo::hasSCTGeometry())) + return; + #endif VP1GeoFlags::SubSystemFlag subSysFlag(pixel?VP1GeoFlags::Pixel:VP1GeoFlags::SCT); bool bcm(bcmA||bcmC); @@ -1989,7 +2173,7 @@ void VP1GeometrySystem::autoAdaptPixelsOrSCT(bool pixel,bool brl, bool ecA, bool //////////////////////////////////////////////////////////////// //Abort if corresponding subsystem is not built: if (!subsys->isbuilt) { - messageDebug("AutoAdaptPixelsOrSCT: Aborting since subsystem geometry not built yet"); + VP1Msg::messageDebug("AutoAdaptPixelsOrSCT: Aborting since subsystem geometry not built yet"); return;//Disabling now due to phi-sector problems if "click some phi sectors"->"adapt pixel"->"turn on pixel" } bool save = m_d->sceneroot->enableNotify(false); @@ -2056,7 +2240,7 @@ void VP1GeometrySystem::autoAdaptPixelsOrSCT(bool pixel,bool brl, bool ecA, bool //_____________________________________________________________________________________ void VP1GeometrySystem::Imp::showPixelModules(VolumeHandle* h) { - theclass->messageDebug("VP1GeometrySystem::Imp::showPixelModules()"); + VP1Msg::messageDebug("VP1GeometrySystem::Imp::showPixelModules()"); h->initialiseChildren(); VolumeHandle::VolumeHandleListItr it(h->childrenBegin()),itE(h->childrenEnd()); for (;it!=itE;++it) { @@ -2092,7 +2276,7 @@ void VP1GeometrySystem::Imp::showPixelModules(VolumeHandle* h) //_____________________________________________________________________________________ void VP1GeometrySystem::Imp::showSCTBarrelModules(VolumeHandle*h) { - theclass->messageDebug("VP1GeometrySystem::Imp::showSCTBarrelModules()"); + VP1Msg::messageDebug("VP1GeometrySystem::Imp::showSCTBarrelModules()"); h->initialiseChildren(); VolumeHandle::VolumeHandleListItr it(h->childrenBegin()),itE(h->childrenEnd()); for (;it!=itE;++it) { @@ -2160,7 +2344,7 @@ void VP1GeometrySystem::Imp::showSCTBarrelModules(VolumeHandle*h) //_____________________________________________________________________________________ void VP1GeometrySystem::Imp::showSCTEndcapModules(VolumeHandle*h) { - theclass->messageDebug("VP1GeometrySystem::Imp::showSCTEndcapModules()"); + VP1Msg::messageDebug("VP1GeometrySystem::Imp::showSCTEndcapModules()"); h->initialiseChildren(); VolumeHandle::VolumeHandleListItr it(h->childrenBegin()),itE(h->childrenEnd()); for (;it!=itE;++it) { diff --git a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandle.cxx b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandle.cxx index eeaa2ae73cf846e7f5c5e809a87d9a0caf969fd4..d33eba63d6eede998590ed5fe8dcc7e42b4b48e0 100644 --- a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandle.cxx +++ b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandle.cxx @@ -1,5 +1,5 @@ /* - Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration + Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ #include "VP1GeometrySystems/VolumeHandle.h" @@ -10,6 +10,7 @@ #include "VP1GeometrySystems/GeoSysController.h" #include "VP1Base/VP1ExtraSepLayerHelper.h" +#include "VP1Base/VP1Msg.h" // #include "VP1Base/VP1QtInventorUtils.h" #include "VP1Utils/VP1LinAlgUtils.h" #include "VP1HEPVis/nodes/SoTransparency.h" @@ -139,11 +140,13 @@ void VolumeHandle::initialiseChildren() unsigned ichild(0); GeoVolumeCursor av(m_d->pV); while (!av.atEnd()) { + //Add transformation between parent and child to find the complete transformation of the child: SbMatrix matr; VP1LinAlgUtils::transformToMatrix(Amg::EigenTransformToCLHEP(av.getTransform()), matr); matr.multRight(m_d->accumTrans); m_children.push_back(new VolumeHandle(m_d->commondata,this,av.getVolume(),ichild++,(isInMuonChamber()?MUONCHAMBERCHILD:NONMUONCHAMBER),matr)); + //std::cout << "initialised: " << av.getName() << " - " << m_children.back()->getName().toStdString() << " - " << m_children.back() << std::endl; av.next(); } @@ -229,6 +232,7 @@ SoSeparator * VolumeHandle::nodeSoSeparator() const //____________________________________________________________________ void VolumeHandle::ensureBuildNodeSep() { + VP1Msg::messageDebug("VolumeHandle::ensureBuildNodeSep()"); if (m_d->nodesep && m_d->label_sep) return; @@ -243,6 +247,7 @@ void VolumeHandle::ensureBuildNodeSep() //Transform: m_d->nodesep->addChild(VP1LinAlgUtils::toSoTransform(m_d->accumTrans)); + //VP1Msg::messageDebug("calling toShapeNode()..."); SoNode * shape = m_d->commondata->toShapeNode(m_d->pV);//NB: Ignore contained transformation of GeoShapeShifts. if (!shape) { m_d->nodesep->removeAllChildren(); @@ -254,14 +259,20 @@ void VolumeHandle::ensureBuildNodeSep() int iphi = m_d->commondata->phiSectorManager()->getVolumeType(m_d->accumTrans, shape); if (iphi>=-1 ) { + //VP1Msg::messageDebug("Cylinders [iphi >= -1]..."); //Substitute shapes that are essentially cylinders with such. This //can be done safely since this tube won't need //phi-slicing and is done to gain render performance. - if ( m_d->pV->getLogVol()->getShape()->typeID()==GeoTube::getClassTypeID() ) { + if ( m_d->pV->getLogVol()->getShape()->typeID()==GeoTube::getClassTypeID() ) + { + //VP1Msg::messageDebug("GeoTube..."); const GeoTube * geotube = static_cast<const GeoTube*>(m_d->pV->getLogVol()->getShape()); if (geotube->getRMin()==0.0) shape = m_d->commondata->getSoCylinderOrientedLikeGeoTube(geotube->getRMax(),geotube->getZHalfLength()); - } else if ( m_d->pV->getLogVol()->getShape()->typeID()==GeoTubs::getClassTypeID() ) { + } + else if ( m_d->pV->getLogVol()->getShape()->typeID()==GeoTubs::getClassTypeID() ) + { + //VP1Msg::messageDebug("GeoTubs..."); const GeoTubs * geotubs = static_cast<const GeoTubs*>(m_d->pV->getLogVol()->getShape()); if (geotubs->getRMin()==0.0 && geotubs->getDPhi() >= 2*M_PI-1.0e-6) shape = m_d->commondata->getSoCylinderOrientedLikeGeoTube(geotubs->getRMax(),geotubs->getZHalfLength()); @@ -293,21 +304,28 @@ void VolumeHandle::ensureBuildNodeSep() //NB: "shape" might be shared between several volumes, so we use the separator above for the actual link! //(this must be done last as it also sets outline defaults) m_d->commondata->registerNodeSepForVolumeHandle(m_d->nodesep,this); + + //VP1Msg::messageDebug("VolumeHandle::ensureBuildNodeSep() - DONE."); } //____________________________________________________________________ void VolumeHandle::Imp::attach(VolumeHandle*vh) { + VP1Msg::messageDebug("VolumeHandle::Imp::attach() - name: " + vh->getName()); if (!isattached) { vh->ensureBuildNodeSep(); - if (attachsepHelper) + if (attachsepHelper) { + VP1Msg::messageDebug("adding node..."); attachsepHelper->addNodeUnderMaterial(nodesep,vh->material()); - if (attachlabelSepHelper) + } + if (attachlabelSepHelper) { + VP1Msg::messageDebug("adding label..."); attachlabelSepHelper->addNode(label_sep); + } isattached=true; commondata->volumeBrowser()->scheduleUpdateOfAllNonHiddenIndices();//Browser need to change e.g. colour for this volume } - + //VP1Msg::messageDebug("attach: DONE."); } //____________________________________________________________________ @@ -493,17 +511,22 @@ bool VolumeHandle::isEther() const //____________________________________________________________________ void VolumeHandle::expandMothersRecursivelyToNonEther() { - // std::cout<<" VolumeHandle::expandMothersRecursivelyToNonEther() for "<<this<<std::endl; - if (!nChildren()||!isEther()) + //std::cout<<"VolumeHandle::expandMothersRecursivelyToNonEther() for "<<this->getNameStdString() << " [" <<this<< "]" << " - n. children: " << nChildren() << std::endl; + + if (!nChildren()||!isEther()) { + //VP1Msg::messageDebug("====> no children or not 'Ether' material. Skipping & returning."); return; + } + setState(VP1GeoFlags::ZAPPED); initialiseChildren(); VolumeHandleListItr childItrE = m_children.end(); for (VolumeHandleListItr childItr = m_children.begin(); childItr!=childItrE; ++childItr) { + //std::cout << "\t-->expanding child " << (*childItr)->getNameStdString() << " - " << (*childItr) << std::endl ; (*childItr)->expandMothersRecursivelyToNonEther(); } setState(VP1GeoFlags::EXPANDED); - // std::cout<<" VolumeHandle::expandMothersRecursivelyToNonEther() for "<<this<<" DONE"<<std::endl; + //std::cout<<"VolumeHandle::expandMothersRecursivelyToNonEther() for "<<this->getNameStdString() << " [" <<this<< "]" <<" DONE.\n\n"<<std::endl; } diff --git a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandleSharedData.cxx b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandleSharedData.cxx index d215be6f37f8bcfd4b2d2f1cdea8d1379882104c..d07a173d044d5126689667b0ad3e3626bcb44d8d 100644 --- a/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandleSharedData.cxx +++ b/graphics/VP1/VP1Systems/VP1GeometrySystems/src/VolumeHandleSharedData.cxx @@ -164,11 +164,13 @@ SoNode * VolumeHandleSharedData::toShapeNode(const GeoPVConstLink& pV) { const GeoLogVol * logVolume = pV->getLogVol(); + // if shape already stored for this volume, return that SoShape * shape (0); std::map<const GeoLogVol *, SoShape *>::iterator itShape = m_d->logvol2shape.find(logVolume); if (itShape!=m_d->logvol2shape.end()) { return itShape->second; } + const GeoShape * geoshape = logVolume->getShape(); m_d->visaction.reset(); diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/CMakeLists.txt b/graphics/VP1/VP1Systems/VP1GuideLineSystems/CMakeLists.txt index a95c964b11433241bb23793ddd5e3d166a2a257f..ecd38c072d4ac7b9670b7c28b1ec6a302a00976d 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/CMakeLists.txt +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/CMakeLists.txt @@ -25,6 +25,7 @@ set( CMAKE_AUTOUIC TRUE ) # Generate MOC files automatically: set( CMAKE_AUTOMOC TRUE ) +if(NOT BUILDVP1LIGHT) # Component(s) in the package: atlas_add_library( VP1GuideLineSystems VP1GuideLineSystems/*.h src/*.cxx PUBLIC_HEADERS VP1GuideLineSystems @@ -33,3 +34,14 @@ atlas_add_library( VP1GuideLineSystems VP1GuideLineSystems/*.h src/*.cxx Qt5::Core Qt5::Gui PRIVATE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} PRIVATE_LINK_LIBRARIES GaudiKernel VP1HEPVis ) +endif() +if(BUILDVP1LIGHT) +# Component(s) in the package: +atlas_add_library( VP1GuideLineSystems VP1GuideLineSystems/*.h src/*.cxx + PUBLIC_HEADERS VP1GuideLineSystems + INCLUDE_DIRS ${COIN3D_INCLUDE_DIRS} + LINK_LIBRARIES ${COIN3D_LIBRARIES} GeoPrimitives VP1Base VP1Utils + Qt5::Core Qt5::Gui + PRIVATE_INCLUDE_DIRS ${CMAKE_CURRENT_BINARY_DIR} + PRIVATE_LINK_LIBRARIES VP1HEPVis ) +endif() diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/GuideSysController.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/GuideSysController.cxx index 5032e37a52b3103194cb21fe46ed4e91c84093a7..a8059e8e8f9f1f71c1abf479688e60ef0159ee63 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/GuideSysController.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/GuideSysController.cxx @@ -26,7 +26,16 @@ #include "ui_guides_settings_lines_form.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" -#include "GaudiKernel/SystemOfUnits.h" + +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif + #include <cmath> //____________________________________________________________________ @@ -370,19 +379,19 @@ SbColor4f GuideSysController::floorColourAndTransp() const //____________________________________________________________________ double GuideSysController::floorExtent() const { - return m_d->ui_floorandletters.doubleSpinBox_floorextent->value()*Gaudi::Units::m; + return m_d->ui_floorandletters.doubleSpinBox_floorextent->value()*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ double GuideSysController::floorSpacing() const { - return m_d->ui_floorandletters.doubleSpinBox_floorspacing->value()*Gaudi::Units::m; + return m_d->ui_floorandletters.doubleSpinBox_floorspacing->value()*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ double GuideSysController::floorHeight() const { - return m_d->ui_floorandletters.doubleSpinBox_floorheight->value()*Gaudi::Units::m; + return m_d->ui_floorandletters.doubleSpinBox_floorheight->value()*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ @@ -399,7 +408,7 @@ double GuideSysController::lettersZPos() const int nmax; double distmax; if (!VP1Floor::calcParsFromExtentAndSpacing( (VP1HelperClassBase*)this, floorExtent(), floorSpacing(), VP1Floor::nMax(), nmax, distmax )) { nmax = 10; - distmax = 10*Gaudi::Units::m; + distmax = 10*SYSTEM_OF_UNITS::m; message("lettersZPos ERROR: Problems calculating floor nmax/distmax."); } return distmax*1.1; @@ -408,7 +417,7 @@ double GuideSysController::lettersZPos() const //____________________________________________________________________ double GuideSysController::lettersVerticalPos() const { - return floorHeight()+1.5*Gaudi::Units::m; + return floorHeight()+1.5*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ @@ -420,17 +429,16 @@ bool GuideSysController::showAxes() const //____________________________________________________________________ double GuideSysController::axesLength() const { - return m_d->ui_axes.doubleSpinBox_axes_lengths_m->value()*Gaudi::Units::m * + return m_d->ui_axes.doubleSpinBox_axes_lengths_m->value()*SYSTEM_OF_UNITS::m * (m_d->ui_axes.checkBox_axes_shownegativeparts->isChecked()?-1.0:1.0); } //____________________________________________________________________ SbVec3f GuideSysController::axesPosition() const { - return SbVec3f(m_d->ui_axes.doubleSpinBox_axes_xpos_m->value()*Gaudi::Units::m, - m_d->ui_axes.doubleSpinBox_axes_ypos_m->value()*Gaudi::Units::m, - m_d->ui_axes.doubleSpinBox_axes_zpos_m->value()*Gaudi::Units::m); - + return SbVec3f(m_d->ui_axes.doubleSpinBox_axes_xpos_m->value()*SYSTEM_OF_UNITS::m, + m_d->ui_axes.doubleSpinBox_axes_ypos_m->value()*SYSTEM_OF_UNITS::m, + m_d->ui_axes.doubleSpinBox_axes_zpos_m->value()*SYSTEM_OF_UNITS::m); } //____________________________________________________________________ @@ -462,13 +470,13 @@ SbColor4f GuideSysController::gridColourAndTransp() const //____________________________________________________________________ double GuideSysController::gridSpacing() const { - return m_d->ui_grid.doubleSpinBox_gridspacing->value()*Gaudi::Units::m; + return m_d->ui_grid.doubleSpinBox_gridspacing->value()*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ double GuideSysController::gridExtent() const { - return m_d->ui_grid.doubleSpinBox_gridextent->value()*Gaudi::Units::m; + return m_d->ui_grid.doubleSpinBox_gridextent->value()*SYSTEM_OF_UNITS::m; } //____________________________________________________________________ @@ -513,7 +521,7 @@ double GuideSysController::etaConeValue3() const //____________________________________________________________________ double GuideSysController::etaExtent() const { - return m_d->ui_etacones.doubleSpinBox_etaconeextent->value() * Gaudi::Units::m + return m_d->ui_etacones.doubleSpinBox_etaconeextent->value() * SYSTEM_OF_UNITS::m * (m_d->ui_etacones.radioButton_etaconeextentisr->isChecked() ? 1.0 : -1.0); } @@ -537,7 +545,7 @@ SbVec3f GuideSysController::lineDirection() const //____________________________________________________________________ double GuideSysController::lineLength() const { - return m_d->ui_lines.doubleSpinBox_length->value() * Gaudi::Units::m; + return m_d->ui_lines.doubleSpinBox_length->value() * SYSTEM_OF_UNITS::m; } //_____________________________________________________________________________________ diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/InDetProjHelper.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/InDetProjHelper.cxx index 9297694b014b8d346ef7bec20c65ecf82651c567..58d99bbf5f952c2b6d7945bb4065400c8001fcc9 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/InDetProjHelper.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/InDetProjHelper.cxx @@ -18,7 +18,13 @@ #include "GeoPrimitives/GeoPrimitives.h" -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //Fixme: Epsilon in projections! (at least take surface thickness into account!) @@ -278,7 +284,7 @@ void InDetProjHelper::clipPath( const std::vector<Amg::Vector3D >& path, Amg::SetVectorVector3D& resulting_subpaths_endcapA, Amg::SetVectorVector3D& resulting_subpaths_endcapC ) const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("clipPath(..) called. Input path has "+QString::number(path.size())+" points."); resulting_subpaths_barrelA.clear(); @@ -288,12 +294,12 @@ void InDetProjHelper::clipPath( const std::vector<Amg::Vector3D >& path, //Fixme: If verbose - perform sanity check of input data (check for NAN's). if (m_d->parts == InDetProjFlags::NoProjections ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("All projections currently off."); return; } if ( path.size()<2 ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Input path too short."); return; } @@ -308,7 +314,7 @@ void InDetProjHelper::clipPath( const std::vector<Amg::Vector3D >& path, m_d->covercyl_zmin, m_d->covercyl_zmax ); if (paths_clipped.empty()) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Path entirely outside clip volumes."); return; } @@ -322,25 +328,25 @@ void InDetProjHelper::clipPath( const std::vector<Amg::Vector3D >& path, if ( ( (enabled_brlA?1:0) + (enabled_brlC?1:0) + (enabled_ecA?1:0) + (enabled_ecC?1:0) ) == 1 ) { if (enabled_brlA) { resulting_subpaths_barrelA = paths_clipped; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("clipPath(..) only brlA enabled. Returning."); return; } if (enabled_brlC) { resulting_subpaths_barrelC = paths_clipped; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("clipPath(..) only brlC enabled. Returning."); return; } if (enabled_ecA) { resulting_subpaths_endcapA = paths_clipped; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("clipPath(..) only ecA enabled. Returning."); return; } if (enabled_ecC) { resulting_subpaths_endcapC = paths_clipped; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("clipPath(..) only ecC enabled. Returning."); return; } @@ -497,13 +503,13 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, //We might be inside inner wall: if (ar2 <= rmin2 && br2 <= rmin2 ) { // seg2_a=seg2_b; -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder Segment entirely inside rmin."); return false; } //Some fast checks for being outside: if ( (a.x()<=-rmax&&b.x()<=-rmax) || (a.x()>=rmax&&b.x()>=rmax) || (a.y()<=-rmax&&b.y()<=-rmax)|| (a.y()>=rmax&&b.y()>=rmax) ) { -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder Segment clearly entirely outside outside rmax."); // seg2_a=seg2_b; return false; @@ -515,7 +521,7 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, const double rmax2 = rmax*rmax; if (dx==0.0&&dy==0.0) { //Apparently a==b (apart from perhaps z coord). -// if (theclass->verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder a==b."); return ar2<=rmax2; } @@ -525,7 +531,7 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, const double py = ( u <= 0 ? a.y() : ( u >= 1 ? b.y() : a.y()+u*dy ) ); const double pr2 = px*px+py*py; if (pr2>=rmax2) { -// if (theclass->verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder segment entirely outside rmax."); // seg2_a=seg2_b; return false; @@ -537,7 +543,7 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, if (pr2>=rmin2&&ar2<=rmax2&&br2<=rmax2) { //We are actually already entirely inside the clip volume. -// if (theclass->verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder segment entirely inside clip volume." // " (pr="+QString::number(sqrt(pr2))+", ar="+QString::number(sqrt(ar2)) // +", br="+QString::number(sqrt(br2))+")"); @@ -560,19 +566,19 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, if (u1>0&&u1<1) { //move a to a+u1*(b-a) a = a+u1*(b-a); -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder sliding a towards b, at the rmax circle."); } if (u2>0&&u2<1) { //move b to a+u2*(b-a) b = asave+u2*(b-asave); -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder sliding b towards a, at the rmax circle."); } } if (pr2>=rmin2) { -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder remaining segment is now entirely inside."); return true; } @@ -588,7 +594,7 @@ bool InDetProjHelper::Imp::clipSegmentToInfiniteHollowCylinder( Amg::Vector3D&a, seg2_b = b; b = a+u1*(seg2_b-a); seg2_a=a+u2*(seg2_b-a); -// if (verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToInfiniteHollowCylinder Two resulting segments!."); return true; } @@ -611,7 +617,7 @@ bool InDetProjHelper::Imp::clipSegmentToHollowCylinder( Amg::Vector3D&a, Amg::Ve Amg::Vector3D&seg2_a, Amg::Vector3D&seg2_b ) const { // seg2_a = seg2_b;//test -// if (theclass->verbose()) { +// if (VP1Msg::verbose()) { // theclass->messageVerbose("clipSegmentToHollowCylinder called with:"); // theclass->messageVerbose(" rmin = "+QString::number(rmin)); // theclass->messageVerbose(" rmax = "+QString::number(rmax)); @@ -622,11 +628,11 @@ bool InDetProjHelper::Imp::clipSegmentToHollowCylinder( Amg::Vector3D&a, Amg::Ve // } if (!clipSegmentToZInterval(a,b,zmin,zmax)) { // seg2_a = seg2_b; -// if (theclass->verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToHollowCylinder segment outside z-interval."); return false; } -// if (theclass->verbose()) { +// if (VP1Msg::verbose()) { // theclass->messageVerbose("clipSegmentToHollowCylinder parameters after clipSegmentToZInterval:"); // if (a.z()<zmin||a.z()>zmax) // theclass->messageVerbose("clipSegmentToHollowCylinder ERROR in clipSegmentToZInterval call (a_z wrong)."); @@ -637,11 +643,11 @@ bool InDetProjHelper::Imp::clipSegmentToHollowCylinder( Amg::Vector3D&a, Amg::Ve // } if (!clipSegmentToInfiniteHollowCylinder(a,b,rmin,rmax,seg2_a,seg2_b)) { // seg2_a = seg2_b; -// if (theclass->verbose()) +// if (VP1Msg::verbose()) // theclass->messageVerbose("clipSegmentToHollowCylinder segment outside infinite hollow cylinder."); return false; } -// if (theclass->verbose()) { +// if (VP1Msg::verbose()) { // theclass->messageVerbose("clipSegmentToHollowCylinder parameters after clipSegmentToInfiniteHollowCylinder:"); // theclass->messageVerbose(" a = ("+QString::number(a.x())+", "+QString::number(a.y())+", "+QString::number(a.z())+")"); // theclass->messageVerbose(" b = ("+QString::number(b.x())+", "+QString::number(b.y())+", "+QString::number(b.z())+")"); @@ -664,7 +670,7 @@ void InDetProjHelper::Imp::clipPathToHollowCylinder( const std::vector<Amg::Vect const double& rmin, const double& rmax, const double& zmin, const double& zmax ) const { -// if (theclass->verbose()) { +// if (VP1Msg::verbose()) { // theclass->messageVerbose("clipPathToHollowCylinder called"); // theclass->messageVerbose(" ===> rmin = "+QString::number(rmin)); // theclass->messageVerbose(" ===> rmax = "+QString::number(rmax)); @@ -823,7 +829,7 @@ void InDetProjHelper::projectPath( const std::vector<Amg::Vector3D >& path, Amg::SetVectorVector3D& resulting_projections_endcapA, Amg::SetVectorVector3D& resulting_projections_endcapC ) const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("projectPath(..) called. Input path has "+QString::number(path.size())+" points."); resulting_projections_barrelA.clear(); @@ -833,12 +839,12 @@ void InDetProjHelper::projectPath( const std::vector<Amg::Vector3D >& path, //Fixme: If verbose - perform sanity check of input data (check for NAN's). if (m_d->parts == InDetProjFlags::NoProjections ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("All projections currently off."); return; } if ( path.size()<2 ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Input path too short."); return; } @@ -853,7 +859,7 @@ void InDetProjHelper::projectPath( const std::vector<Amg::Vector3D >& path, //Fixme: The dependence on surface thickness and epsilon below is very preliminary. const double eps = m_d->data_disttosurface_epsilon; - const double endcapeps(-5*Gaudi::Units::mm);//fixme hardcoding.. + const double endcapeps(-5*SYSTEM_OF_UNITS::mm);//fixme hardcoding.. Amg::SetVectorVector3D::const_iterator it,itE; @@ -919,7 +925,7 @@ void InDetProjHelper::projectPath( const std::vector<Amg::Vector3D >& path, //____________________________________________________________________ InDetProjHelper::PartsFlags InDetProjHelper::touchedParts( const std::vector<Amg::Vector3D >& path ) const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("touchedParts(..) called. Input path has "+QString::number(path.size())+" points."); PartsFlags touchedparts = NoParts; if ( m_d->touchesHollowCylinder(path,m_d->barrel_inner_radius, m_d->barrel_outer_radius, 0, m_d->barrel_posneg_z) ) diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/ProjectionSurfacesHelper.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/ProjectionSurfacesHelper.cxx index d87de4ada93188bc358f0866de71ab39e9e93f1b..f586758b0782edeae6ca8a5116d752fd7a12b21a 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/ProjectionSurfacesHelper.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/ProjectionSurfacesHelper.cxx @@ -5,6 +5,7 @@ #include "VP1GuideLineSystems/ProjectionSurfacesHelper.h" #include "VP1GuideLineSystems/InDetProjParams.h" #include "VP1HEPVis/nodes/SoTubs.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/nodes/SoMaterial.h> #include <Inventor/nodes/SoSeparator.h> @@ -230,7 +231,7 @@ ProjectionSurfacesHelper::~ProjectionSurfacesHelper() //____________________________________________________________________ InDetProjFlags::InDetProjPartsFlags ProjectionSurfacesHelper::shownParts() const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("shownParts"); return m_d->parts; } @@ -364,7 +365,7 @@ void ProjectionSurfacesHelper::Imp::initPartsSep(float zpos, SoSeparator*&sep, S //____________________________________________________________________ SoMaterial * ProjectionSurfacesHelper::material() { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("material"); return m_d->material; } @@ -449,7 +450,7 @@ SoShape * ProjectionSurfacesHelper::Imp::endcapZAsRCylShape() //____________________________________________________________________ void ProjectionSurfacesHelper::Imp::ensureDetached(SoSeparator*s) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("ensureDetached"); if (!sep||!s) return; @@ -460,7 +461,7 @@ void ProjectionSurfacesHelper::Imp::ensureDetached(SoSeparator*s) //____________________________________________________________________ void ProjectionSurfacesHelper::Imp::ensureAttached(SoSeparator*s) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("ensureAttached"); if (!s) return; @@ -475,6 +476,6 @@ void ProjectionSurfacesHelper::Imp::ensureAttached(SoSeparator*s) attachsep->addChild(sep); } sep->addChild(s); - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("ensureAttached done"); } diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CartesianGrid.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CartesianGrid.cxx index f61def4411cd1e041f6f5739081accf3c799e38a..13bd2bbf342e198438e9e0dcc004b101472d0306 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CartesianGrid.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CartesianGrid.cxx @@ -20,7 +20,13 @@ #include <Inventor/nodes/SoLineSet.h> #include <Inventor/SbColor4f.h> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //____________________________________________________________________ class VP1CartesianGrid::Imp { @@ -83,7 +89,7 @@ void VP1CartesianGrid::Imp::rebuild3DObjects() int nmax; double distmax; if (!VP1Floor::calcParsFromExtentAndSpacing( theclass, extent, spacing, 40/*max lines*/, nmax, distmax )) { nmax = 10; - distmax = 10*Gaudi::Units::m; + distmax = 10*SYSTEM_OF_UNITS::m; theclass->message("ERROR: Problems calculating nmax/distmax."); } diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CoordinateAxes.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CoordinateAxes.cxx index b584b921638a5116718af26bb531bee7f12779da..e478bef1134b5fdc63b480db89d120d038d4abc0 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CoordinateAxes.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CoordinateAxes.cxx @@ -108,7 +108,13 @@ void VP1CoordinateAxes::Imp::ensureInit3DObjects() overall_translation = new SoTranslation; sep->addChild(overall_translation); - const bool alternativeRep = VP1QtUtils::environmentVariableIsOn("VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES"); + + #if defined BUILDVP1LIGHT + const bool alternativeRep = VP1QtUtils::expertSettingIsOn("general","ExpertSettings/VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES"); + #else + const bool alternativeRep = VP1QtUtils::environmentVariableIsOn("VP1_GUIDES_SPHERE_INSTEAD_OF_COORDAXES"); + #endif + if (alternativeRep) { sep->addChild(materialXAxis); alternative_Sphere = new SoSphere; diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CylindricalGrid.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CylindricalGrid.cxx index b91729e70e4c1e3fc6401f5bdcedb9c8d445f55c..6d7b6a01ff6f0bad52d25596b41989f1cb5ac967 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CylindricalGrid.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1CylindricalGrid.cxx @@ -23,7 +23,13 @@ #include <Inventor/nodes/SoPackedColor.h> #include <Inventor/SbColor4f.h> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //____________________________________________________________________ class VP1CylindricalGrid::Imp { @@ -90,7 +96,7 @@ void VP1CylindricalGrid::Imp::rebuild3DObjects() int nmax; double distmax; if (!VP1Floor::calcParsFromExtentAndSpacing( theclass, extent, spacing, 20/*max lines*/, nmax, distmax )) { nmax = 10; - distmax = 10*Gaudi::Units::m; + distmax = 10*SYSTEM_OF_UNITS::m; theclass->message("ERROR: Problems calculating nmax/distmax."); } diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1EtaCone.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1EtaCone.cxx index 96e373b27b6b6ac48505f160af9940358f25db01..0eb8fac72b4d729b801ab2ededec52b9284c38f5 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1EtaCone.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1EtaCone.cxx @@ -21,7 +21,13 @@ #include <Inventor/nodes/SoTranslation.h> #include <Inventor/nodes/SoRotationXYZ.h> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //____________________________________________________________________ class VP1EtaCone::Imp { @@ -96,7 +102,7 @@ void VP1EtaCone::Imp::ensureInit3DObjects() for ( int i = 0;i<2;++i){ SoRotationXYZ * xf = new SoRotationXYZ(); xf->axis=SoRotationXYZ::X; - xf->angle = i==0 ? 90.0*Gaudi::Units::deg : -90*Gaudi::Units::deg; + xf->angle = i==0 ? 90.0*SYSTEM_OF_UNITS::deg : -90*SYSTEM_OF_UNITS::deg; SoTranslation * xl = new SoTranslation(); SoCone * cone = new SoCone(); SoTranslation * innerxl = new SoTranslation(); @@ -165,7 +171,7 @@ void VP1EtaCone::Imp::updateFields() innercone2->bottomRadius = bottomRadius; innercone2->height = -coneHeight; //To avoid render flicker from the overlapping cones, we move the inner cone slightly away from origo: - const double epsilon = 0.50*Gaudi::Units::mm; + const double epsilon = 0.50*SYSTEM_OF_UNITS::mm; innertrans1->translation.setValue(0, coneHeight/2+1.001*coneHeight/2+epsilon, 0); innertrans2->translation.setValue(0, coneHeight/2+1.001*coneHeight/2+epsilon, 0); diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Floor.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Floor.cxx index 0648efba969bcc8579308480e0b6f96a9e99c9fc..a59f465f687c953bf2c7925ed30467eb06706911 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Floor.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Floor.cxx @@ -18,7 +18,13 @@ #include <Inventor/nodes/SoLineSet.h> #include <Inventor/SbColor4f.h> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //____________________________________________________________________ bool VP1Floor::calcParsFromExtentAndSpacing( VP1HelperClassBase*helper,const double& extent, const double& spacing, const int& nmaxlimit, int& nmax, double& distmax ) @@ -98,7 +104,7 @@ void VP1Floor::Imp::rebuild3DObjects() int nmax; double distmax; if (!calcParsFromExtentAndSpacing( theclass, extent, spacing, VP1Floor::nMax(), nmax, distmax )) { nmax = 10; - distmax = 10*Gaudi::Units::m; + distmax = 10*SYSTEM_OF_UNITS::m; theclass->message("ERROR: Problems calculating nmax/distmax."); } diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1GuideLineSystem.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1GuideLineSystem.cxx index 7f3900c6cc5bab0f3c2fba7d15d31491d23ac545..03d0b51953222b9715f5050a59334755073ed446 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1GuideLineSystem.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1GuideLineSystem.cxx @@ -27,6 +27,7 @@ #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/nodes/SoSeparator.h> #include <Inventor/nodes/SoPickStyle.h> @@ -108,7 +109,9 @@ void VP1GuideLineSystem::buildEventSceneGraph(StoreGateSvc*, SoSeparator *) //_____________________________________________________________________________________ void VP1GuideLineSystem::buildPermanentSceneGraph(StoreGateSvc* /*detstore*/, SoSeparator *root) { - messageVerbose("buildPermanentSceneGraph"); + if(VP1Msg::verbose()){ + messageVerbose("buildPermanentSceneGraph"); + } //No guidelines are pickable: SoPickStyle *pickStyle = new SoPickStyle; pickStyle->style=SoPickStyle::UNPICKABLE; @@ -309,8 +312,10 @@ void VP1GuideLineSystem::setIDDetTypesUsingProjections( InDetProjFlags::DetTypeF ensureBuildController(); if (!m_d->controller) return;//if receiving signals after uncreate - messageVerbose("Signal received in setIDDetTypesUsingProjections("+str(f)+") slot (from " - +QString(sender()?sender()->objectName():"NULL sender")+")"); + if(VP1Msg::verbose()){ + messageVerbose("Signal received in setIDDetTypesUsingProjections("+str(f)+") slot (from " + +QString(sender()?sender()->objectName():"NULL sender")+")"); + } m_d->sender2iddettypeswithprojs[sender()] = f; InDetProjFlags::DetTypeFlags used(InDetProjFlags::NoDet); std::map<QObject*,InDetProjFlags::DetTypeFlags>::iterator it, itE = m_d->sender2iddettypeswithprojs.end(); @@ -333,7 +338,8 @@ void VP1GuideLineSystem::possiblyEmit_ApplicableProjectionsChanged() m_d->lastemit_pixel=new_pixel; m_d->lastemit_sct=new_sct; m_d->lastemit_trt=new_trt; - if (verbose()) + if(VP1Msg::verbose()){ messageVerbose("Emitting applicableProjectionsChanged("+str(m_d->lastemit_pixel)+", "+str(m_d->lastemit_sct)+", "+str(m_d->lastemit_trt)+")"); + } emit applicableProjectionsChanged( m_d->lastemit_pixel,m_d->lastemit_sct,m_d->lastemit_trt ); } diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Letters.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Letters.cxx index ae67f019cf12cefeccaedd1b44e42455366638d1..e532b3e1d6eed9092421ee618fff5b72eb74d91b 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Letters.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Letters.cxx @@ -23,7 +23,13 @@ #include <algorithm> #include <vector> -#include "GaudiKernel/SystemOfUnits.h" +#ifdef BUILDVP1LIGHT + #include "CLHEP/Units/SystemOfUnits.h" + #define SYSTEM_OF_UNITS CLHEP +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units +#endif //____________________________________________________________________ class VP1Letters::Imp { @@ -200,7 +206,7 @@ SoNode * VP1Letters::Imp::createLetter(const std::vector<double>& x, const std:: SoPolyhedron::initClass(); // SbPolyhedron * sbpoly = static_cast<SbPolyhedron*>(new SbPolyhedronPolygonXSect(x,y,0.3*m)); // SoPolyhedron * poly = new SoPolyhedron(sbpoly); - SoPolyhedron * poly = new SoPolyhedron(SbPolyhedronPolygonXSect(x,y,0.3*Gaudi::Units::m)); + SoPolyhedron * poly = new SoPolyhedron(SbPolyhedronPolygonXSect(x,y,0.3*SYSTEM_OF_UNITS::m)); return poly; } @@ -216,10 +222,10 @@ void VP1Letters::Imp::ensureInit3DObjects() //Create letters: std::vector<double> x,y; createLetterAData(x,y); - normalizeLetterData(x,y,2*Gaudi::Units::m); + normalizeLetterData(x,y,2*SYSTEM_OF_UNITS::m); SoNode * letterA = createLetter(x,y); createLetterCData(x,y); - normalizeLetterData(x,y,2*Gaudi::Units::m); + normalizeLetterData(x,y,2*SYSTEM_OF_UNITS::m); SoNode * letterC = createLetter(x,y); transA = new SoTranslation; @@ -229,7 +235,7 @@ void VP1Letters::Imp::ensureInit3DObjects() SoRotationXYZ * xf = new SoRotationXYZ(); xf->axis=SoRotationXYZ::Z; - xf->angle = 180*Gaudi::Units::deg; + xf->angle = 180*SYSTEM_OF_UNITS::deg; sep->addChild(transC); sep->addChild(letterC); diff --git a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Lines.cxx b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Lines.cxx index aaffe29ccab6e20888d9b605f5eda805eeb2876a..bfcb92a627be4dbca92050f25a20a784f11f90df 100644 --- a/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Lines.cxx +++ b/graphics/VP1/VP1Systems/VP1GuideLineSystems/src/VP1Lines.cxx @@ -9,8 +9,6 @@ #include <Inventor/nodes/SoLineSet.h> #include <Inventor/SbColor4f.h> -#include "GaudiKernel/SystemOfUnits.h" - //____________________________________________________________________ class VP1Lines::Imp { diff --git a/graphics/VP1/VP1Systems/VP1LegoSystems/src/VP1HVLegoSystem.cxx b/graphics/VP1/VP1Systems/VP1LegoSystems/src/VP1HVLegoSystem.cxx index 3d65bf776b8ac08d87631a1e43dde9d286ee5bf2..0fab337f43dfb2bbda3138b7016d10ad515d64ae 100755 --- a/graphics/VP1/VP1Systems/VP1LegoSystems/src/VP1HVLegoSystem.cxx +++ b/graphics/VP1/VP1Systems/VP1LegoSystems/src/VP1HVLegoSystem.cxx @@ -17,6 +17,7 @@ #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" #include "VP1Utils/VP1SGAccessHelper.h" #include "VP1Utils/VP1JobConfigInfo.h" @@ -135,7 +136,7 @@ void VP1HVLegoSystem::buildPermanentSceneGraph(StoreGateSvc */*detStore*/, SoSep message("ERROR: Cannot access LArElectrodeID"); } else { - if (verbose()) { + if (VP1Msg::verbose()) { std::vector<HWIdentifier>::const_iterator begin=elecId->electrode_begin(), end=elecId->electrode_end(), e; for (e=begin;e!=end;e++) { if (elecId->detector(*e) ==0) { diff --git a/graphics/VP1/VP1Systems/VP1PRDSystems/src/PRDCollHandleBase.cxx b/graphics/VP1/VP1Systems/VP1PRDSystems/src/PRDCollHandleBase.cxx index ab2da4275af9250337ee0bcfbf36988ad902a78e..390d56ecd54398fe48eca6defeba0e4e8c0eecfc 100644 --- a/graphics/VP1/VP1Systems/VP1PRDSystems/src/PRDCollHandleBase.cxx +++ b/graphics/VP1/VP1Systems/VP1PRDSystems/src/PRDCollHandleBase.cxx @@ -15,6 +15,7 @@ #include "VP1Base/VP1QtInventorUtils.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" #include "InDetPrepRawData/PixelClusterContainer.h" #include "InDetPrepRawData/SCT_ClusterContainer.h" @@ -213,7 +214,7 @@ bool PRDCollHandleBase::load() { //____________________________________________________________________ void PRDCollHandleBase::collVisibilityChanged(bool vis) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("TrackCollHandleBase::collVisibilityChanged => "+str(vis)); if (vis) recheckCutStatusOfAllNotVisibleHandles();//Fixme -> ofallhandles? All must be not visible anyway... diff --git a/graphics/VP1/VP1Systems/VP1RawDataSystems/src/VP1RawDataCollBase.cxx b/graphics/VP1/VP1Systems/VP1RawDataSystems/src/VP1RawDataCollBase.cxx index 1a7cc740e0fb0d5d025ad961e8a64385f96aaabe..5229bbc63bc2f6ad4dab7ac5406b3c8cdd94c8e6 100644 --- a/graphics/VP1/VP1Systems/VP1RawDataSystems/src/VP1RawDataCollBase.cxx +++ b/graphics/VP1/VP1Systems/VP1RawDataSystems/src/VP1RawDataCollBase.cxx @@ -18,6 +18,7 @@ #include "VP1RawDataSystems/VP1RawDataSysController.h" #include "VP1Base/VP1ExtraSepLayerHelper.h" #include "VP1Base/IVP13DSystem.h" +#include "VP1Base/VP1Msg.h" #include "GeoPrimitives/GeoPrimitives.h" #include "EventPrimitives/EventPrimitives.h" @@ -94,7 +95,7 @@ QString VP1RawDataCollBase::provideText() const //____________________________________________________________________ void VP1RawDataCollBase::collVisibilityChanged(bool vis) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("TrackCollHandleBase::collVisibilityChanged => "+str(vis)); if (vis) recheckCutStatusOfAllNotVisibleHandles();//Fixme -> ofallhandles? All must be not visible anyway... diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/AscObjSelectionManager.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/AscObjSelectionManager.cxx index af74aa9e4956fcda96529de4da390d8760111241..23fbae044ce1255787c47a41880500dbe528328d 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/AscObjSelectionManager.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/AscObjSelectionManager.cxx @@ -18,6 +18,7 @@ #include "VP1Base/IVP13DSystem.h" #include "VP1Base/SoCooperativeSelection.h" #include "VP1Base/VP1QtInventorUtils.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/nodes/SoSeparator.h> #include <Inventor/SoPath.h> #include <QApplication> @@ -136,7 +137,7 @@ SoSeparator * AscObjSelectionManager::getAscObjAttachSep() const //____________________________________________________________________ void AscObjSelectionManager::registerAscObj(SoSeparator*simple,SoSeparator *detailed,AssociatedObjectHandleBase*handle) { - if (verbose()) { + if (VP1Msg::verbose()) { if (!simple||!detailed||!handle) { message("registerAscObj ERROR: Received null pointer!"); return; @@ -160,7 +161,7 @@ void AscObjSelectionManager::registerAscObj(SoSeparator*simple,SoSeparator *deta //____________________________________________________________________ void AscObjSelectionManager::unregisterAscObj(SoSeparator*simple,SoSeparator *detailed) { - if (verbose()) { + if (VP1Msg::verbose()) { if (!simple||!detailed) { message("unregisterAscObj ERROR: Received null pointer!"); return; diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandleBase.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandleBase.cxx index 22184c08761069865f0ab31059ad3a6086b30b96..f6c008a56d15486cf8093164ec29b10f1f336d4d 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandleBase.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandleBase.cxx @@ -27,6 +27,7 @@ #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" #include "VP1Base/VP1CustomTourEditor.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/nodes/SoSeparator.h> @@ -435,7 +436,7 @@ void TrackCollHandleBase::update3DObjectsOfAllHandles(bool onlythosetouchingmuon { if (!isLoaded()) return; - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("update3DObjectsOfAllHandles start (onlythosetouchingmuonchambers = " +str(onlythosetouchingmuonchambers)+", invalidatePropagatedPoints = " +str(invalidatePropagatedPoints)+")"); @@ -1047,7 +1048,7 @@ void TrackCollHandleBase::collVisibilityChanged(bool vis) if (!m_sephelper) m_sephelper = new VP1ExtraSepLayerHelper(collSep()); - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("TrackCollHandleBase::collVisibilityChanged => "+str(vis)); if (vis){ recheckCutStatusOfAllNotVisibleHandles();//Fixme -> ofallhandles? All must be not visible anyway... diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_SimulationTracks.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_SimulationTracks.cxx index 3f75978c51acab176969b8c4fa3f22e21ea7d2d6..138c49e52df1eda46e0371fddea808cfe46b4c46 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_SimulationTracks.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_SimulationTracks.cxx @@ -19,6 +19,7 @@ #include "VP1TrackSystems/SimBarCode.h" #include "VP1TrackSystems/TrackSystemController.h" #include "VP1Base/IVP1System.h" +#include "VP1Base/VP1Msg.h" #include "VP1Utils/VP1JobConfigInfo.h" #include "VP1Utils/VP1ParticleData.h" @@ -182,7 +183,7 @@ bool TrackCollHandle_SimulationTracks::Imp::loadHitLists(std::map<SimBarCode,Sim theclass->messageVerbose( "Searching " + str( hitLists.size() ) + " lists of sim. hits."); addHitCollections<SimulationHitCollection>(hitLists); - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose( "Found " + str( hitLists.size() ) + " lists of sim. hits."); //Time to assign all simhits with known pdg code a charge: diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_TruthTracks.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_TruthTracks.cxx index dca12c3d770553d5ba8068e0696e02328244af0a..d3784c4c13f9a45bfc69edd4784c8279929cb77e 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_TruthTracks.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackCollHandle_TruthTracks.cxx @@ -21,6 +21,7 @@ #include "VP1TrackSystems/SimBarCode.h" #include "VP1TrackSystems/TrackSystemController.h" #include "VP1Base/IVP1System.h" +#include "VP1Base/VP1Msg.h" #include "VP1Utils/VP1JobConfigInfo.h" #include "VP1Utils/VP1ParticleData.h" @@ -229,7 +230,7 @@ void TrackCollHandle_TruthTracks::Imp::addHitCollections(std::map<SimBarCode,Sim if (trackID.isNonUniqueSecondary()) { double absmom = handle->momentum(); if (absmom>=0&&absmom<1.0*CLHEP::MeV) {//Fixme: Useful? Put it higher?? - // if (theclass->verbose()) + // if (VP1Msg::verbose()) // theclass->messageVerbose("Ignoring low momentum sim hit for non. unique secondary particle"); delete handle; continue; @@ -263,7 +264,7 @@ bool TrackCollHandle_TruthTracks::Imp::loadHitLists(std::map<SimBarCode,SimHitLi if (VP1JobConfigInfo::hasPixelGeometry() && VP1JobConfigInfo::hasSCTGeometry()) addHitCollections<SiHitCollection>(hitLists); - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose( "Found " + str( hitLists.size() ) + " lists of sim. hits."); //Time to assign all simhits with known pdg code a charge: @@ -630,7 +631,7 @@ void TrackCollHandle_TruthTracks::Imp::createSecondaryHitLists(const SimBarCode& sort(itActualOutList->second.begin(),itActualOutList->second.end()); } - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("Grouped "+str(ntothitinput)+" secondaries with pdgCode = " +str(pdgCode)+" into "+str(outHandleLists.size()) +" tracks ("+str(ntothitinput-totused)+" went unused)."); diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackHandle_TrkSegment.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackHandle_TrkSegment.cxx index 832cc1e7a5d8606828271c9ff192e5817d2addc4..71c7525165c13f608495240fb30c0abac4223024 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackHandle_TrkSegment.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackHandle_TrkSegment.cxx @@ -16,6 +16,7 @@ #include "VP1TrackSystems/TrackSystemController.h" #include "VP1TrackSystems/TrackCollHandle_TrkSegment.h" #include "VP1Utils/VP1JobConfigInfo.h" +#include "VP1Base/VP1Msg.h" #include "VP1PRDSystems/MuonChamberProjectionHelper.h" #include "TrkSegment/Segment.h" #include "TrkSurfaces/Surface.h" @@ -67,7 +68,7 @@ QStringList TrackHandle_TrkSegment::clicked() const void TrackHandle_TrkSegment::ensureTouchedMuonChambersInitialised() const { if (!VP1JobConfigInfo::hasMuonGeometry()) { - if (VP1HelperClassBase::verbose()) + if (VP1Msg::verbose()) collHandle()->messageVerbose(""); return; } @@ -161,7 +162,7 @@ const std::vector< Amg::Vector3D > * TrackHandle_TrkSegment::provide_pathInfoPoi m_points->push_back(pointA); m_points->push_back(pointB); } else if (m_points->size()>2) { - if (VP1HelperClassBase::verbose()) + if (VP1Msg::verbose()) collHandle()->messageVerbose("Combining segment points into a single line!"); (*m_points)[1] = m_points->back(); m_points->resize(2); diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackLODManager.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackLODManager.cxx index 53218f98014ab246256c7005af2585d396c8f14b..fb8b80f21df50a6f9f4c59d433f7eb6b2621b1a9 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackLODManager.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackLODManager.cxx @@ -110,7 +110,7 @@ void TrackLODManager::Imp::updateAttachmentForDetailLevel(TrackCommonFlags::DETA //____________________________________________________________________ void TrackLODManager::setDetailLevel(TrackCommonFlags::DETAILLEVEL dl) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("signal received in setDetailLevel (old = "+TrackCommonFlags::toString(m_d->detailLevel)+", new = "+TrackCommonFlags::toString(dl)); if ( m_d->detailLevel == dl ) return; diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackPropagationHelper.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackPropagationHelper.cxx index 7e8bb6a37d53b54cd2d9cfe8671de543937935bb..412096de2903acdf2ae5369150f5dfc666925550 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackPropagationHelper.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackPropagationHelper.cxx @@ -29,6 +29,7 @@ #include "CLHEP/Units/PhysicalConstants.h" #include "VP1Base/VP1QtUtils.h" +#include "VP1Base/VP1Msg.h" #include <limits> //____________________________________________________________________ @@ -152,7 +153,7 @@ TrackPropagationHelper::~TrackPropagationHelper() //____________________________________________________________________ bool TrackPropagationHelper::makePointsNeutral( std::vector<Amg::Vector3D >& points, const Trk::Track* track ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("makePointsNeutral start"); points.clear(); @@ -197,7 +198,7 @@ bool TrackPropagationHelper::makePointsNeutral( std::vector<Amg::Vector3D >& poi } } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("makePointsNeutral_SinglePar end"); return true; } @@ -205,7 +206,7 @@ bool TrackPropagationHelper::makePointsNeutral( std::vector<Amg::Vector3D >& poi //____________________________________________________________________ bool TrackPropagationHelper::Imp::makePointsNeutral_SinglePar( std::vector<Amg::Vector3D >& points, const Trk::Track* track ) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("makePointsNeutral_SinglePar start"); points.clear(); const Trk::TrackParameters * par = *(track->trackParameters()->begin()); @@ -232,7 +233,7 @@ bool TrackPropagationHelper::Imp::makePointsNeutral_SinglePar( std::vector<Amg:: points.reserve(2); points.push_back(a); points.push_back(b); - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("makePointsNeutral_SinglePar (single track parameter) end"); return true; } @@ -241,7 +242,7 @@ bool TrackPropagationHelper::Imp::makePointsNeutral_SinglePar( std::vector<Amg:: bool TrackPropagationHelper::makePointsCharged( std::vector<Amg::Vector3D >& points, const Trk::Track* track, Trk::IExtrapolator * extrapolator, Trk::ParticleHypothesis hypo, bool useMEOT,const Trk::Volume* volume ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("makePointsCharged start with hypo="+str(hypo)+", useMEOT="+str(useMEOT)+", volume=" +str(volume)); // if (volume) std::cout<<volume->volumeBounds()<<std::endl; /////////////////////////////////////////////////////////////// @@ -325,7 +326,7 @@ bool TrackPropagationHelper::makePointsCharged( std::vector<Amg::Vector3D >& poi messageDebug("WARNING: Problems encountered getting boundary surfaces from Volume"); } } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("makePointsCharged end with "+str(points.size())+"points"); return true; } @@ -433,7 +434,7 @@ bool TrackPropagationHelper::showExtrapolationSurfaces() const { bool TrackPropagationHelper::Imp::makePointsCharged_SinglePar( std::vector<Amg::Vector3D >& points, const Trk::Track* track, Trk::IExtrapolator * extrapolator, Trk::ParticleHypothesis hypo ) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("makePointsCharged_SinglePar start"); points.clear(); if (!extrapolator) { @@ -485,7 +486,7 @@ bool TrackPropagationHelper::Imp::makePointsCharged_SinglePar( std::vector<Amg:: if (prevpars!=par) delete prevpars; - if (verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("makePointsCharged_SinglePar end"); return true; @@ -515,14 +516,14 @@ bool TrackPropagationHelper::Imp::addPointsBetweenParameters_Charged( std::vecto // theclass->messageVerbose("distadded: "+str(distadded)+", distance left="+str(sqrt((prevpars->position()-p2).mag2()))+", jump="+str(maxPointDistSq(prevpars->position()))); const Trk::TrackParameters * newpars = extrapolateToNewPar( extrapolator, trk, prevpars, hypo, maxPointDistSq(prevpars->position()) ); if (!newpars){ - if (verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("TrackPropagationHelper::Imp::addPointsBetweenParameters_Charged: Extrapolation failed."); return false; } const double distsq = (par2->position()-newpars->position()).mag2(); if (distsq>olddistsq) { delete newpars; - if (verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("TrackPropagationHelper::Imp::addPointsBetweenParameters_Charged: distq("+str(distsq)+")>olddistsq ("+str(olddistsq)+") so overshot?"); return false; } diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackSysCommonData.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackSysCommonData.cxx index 95c103cbff682eb22b7c8aea41e1cad0a37a0c01..f1e5b87b0f7d75f8d933f04f91194793dd3424a0 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackSysCommonData.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/TrackSysCommonData.cxx @@ -29,6 +29,7 @@ #include "VP1GuideLineSystems/InDetProjHelper.h" #include "VP1Base/VisibleObjectToMaterialHelper.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/C/errors/debugerror.h> #include <Inventor/nodes/SoVertexProperty.h> @@ -123,7 +124,7 @@ void TrackSysCommonData::clearEventData() //____________________________________________________________________ void TrackSysCommonData::registerTrack(SoNode*node,TrackHandleBase*handle) { - if (verbose()) { + if (VP1Msg::verbose()) { if (!node||!handle) { message("registerTrack ERROR: Received null pointer!"); return; @@ -138,7 +139,7 @@ void TrackSysCommonData::registerTrack(SoNode*node,TrackHandleBase*handle) //____________________________________________________________________ void TrackSysCommonData::unregisterTrack(SoNode*node) { - if (verbose()) { + if (VP1Msg::verbose()) { if (!node) { message("unregisterTrack ERROR: Received null pointer!"); return; diff --git a/graphics/VP1/VP1Systems/VP1TrackSystems/src/VP1TrackSystem.cxx b/graphics/VP1/VP1Systems/VP1TrackSystems/src/VP1TrackSystem.cxx index 94a0931ad7e3db788d8bfa954e471a818e2a9c0c..878133b3c2c9c8c8652f514ee927bb1a8daaa2e5 100644 --- a/graphics/VP1/VP1Systems/VP1TrackSystems/src/VP1TrackSystem.cxx +++ b/graphics/VP1/VP1Systems/VP1TrackSystems/src/VP1TrackSystem.cxx @@ -55,6 +55,7 @@ #include "VP1Base/SoCooperativeSelection.h" #include "VP1Base/VP1Serialise.h" #include "VP1Base/VP1Deserialise.h" +#include "VP1Base/VP1Msg.h" #include "VP1Utils/VP1DetInfo.h" @@ -393,7 +394,7 @@ void VP1TrackSystem::systemerase() m_d->totmomgev = Amg::Vector3D(0,0,0); - if (verbose()) { + if (VP1Msg::verbose()) { if (AssociatedObjectHandleBase::numberOfInstances()!=0) message("Warning: "+str(AssociatedObjectHandleBase::numberOfInstances()) +" instances of AssociatedObjectHandleBase alive at end of systemerase(). " diff --git a/graphics/VP1/VP1Systems/VP1VertexSystems/src/VP1VertexCollection.cxx b/graphics/VP1/VP1Systems/VP1VertexSystems/src/VP1VertexCollection.cxx index 9c6e6b42b46269d9e9e083b3fcc3014533b0f055..9039d66160a28e1663b355c7de4a4e74a771a3f7 100644 --- a/graphics/VP1/VP1Systems/VP1VertexSystems/src/VP1VertexCollection.cxx +++ b/graphics/VP1/VP1Systems/VP1VertexSystems/src/VP1VertexCollection.cxx @@ -22,6 +22,7 @@ #include "VP1Base/IVP13DSystem.h" #include "VP1Base/VP1CameraHelper.h" #include "VP1Base/VP1MaterialButton.h" +#include "VP1Base/VP1Msg.h" #include <QStringList> #include <QComboBox> @@ -545,7 +546,7 @@ QStringList VP1VertexCollection::infoOnClicked(SoPath* pickedPath) //____________________________________________________________________ void VP1VertexCollection::collVisibilityChanged(bool vis) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("VP1VertexCollection::collVisibilityChanged => "+str(vis)); if (vis) { recheckAllCuts(); diff --git a/graphics/VP1/VP1Utils/CMakeLists.txt b/graphics/VP1/VP1Utils/CMakeLists.txt index 7af012dbc4b225ba067178a340a17384481db838..2fe3f22da454c1027c543f470cfa91ca3b935b49 100644 --- a/graphics/VP1/VP1Utils/CMakeLists.txt +++ b/graphics/VP1/VP1Utils/CMakeLists.txt @@ -38,7 +38,7 @@ atlas_depends_on_subdirs( graphics/VP1/VP1HEPVis ) # External dependencies: -find_package( CLHEP ) +find_package( CLHEP ) # TODO: to be removed when fully migrated to Eigen-based GeoTrf find_package( Coin3D ) find_package( Eigen ) find_package( HepPDT ) @@ -48,6 +48,7 @@ find_package( GeoModel ) # Generate MOC files automatically: set( CMAKE_AUTOMOC TRUE ) +if (NOT BUILDVP1LIGHT) # Component(s) in the package: atlas_add_library( VP1Utils VP1Utils/*.h src/*.cxx src/*.cpp PUBLIC_HEADERS VP1Utils @@ -64,3 +65,35 @@ atlas_add_library( VP1Utils VP1Utils/*.h src/*.cxx src/*.cpp InDetReadoutGeometry InDetRIO_OnTrack LArReadoutGeometry MuonReadoutGeometry MuonRIO_OnTrack TileDetDescr TrkSurfaces TrkRIO_OnTrack VP1HEPVis ) +endif() +if(BUILDVP1LIGHT) +# Files +file(GLOB SOURCES src/HitsSoNodeManager.cxx + src/SoTools.cpp + src/InDetProjFlags.cxx + src/SoVisualizeAction.cxx + src/SbPolyhedrizeAction.cxx + src/VP1LinAlgUtils.cxx +) +file(GLOB HEADERS ${module_dir}/HitsSoNodeManager.h + ${module_dir}/SoTools.h + ${module_dir}/InDetProjFlags.h + ${module_dir}/SbPolyhedrizeAction.h + ${module_dir}/VP1LinAlgUtils.h + ${module_dir}/SoVisualizeAction.h +) + +# Component(s) in the package: +atlas_add_library( VP1Utils ${SOURCES} ${HEADERS} + PUBLIC_HEADERS VP1Utils + INCLUDE_DIRS ${CLHEP_INCLUDE_DIRS} + PRIVATE_INCLUDE_DIRS ${HEPPDT_INCLUDE_DIRS} ${COIN3D_INCLUDE_DIRS} + ${EIGEN_INCLUDE_DIRS} + LINK_LIBRARIES ${CLHEP_LIBRARIES} EventPrimitives ${GEOMODEL_LIBRARIES} + VP1Base + GeoPrimitives Qt5::Core + PRIVATE_LINK_LIBRARIES ${HEPPDT_LIBRARIES} ${COIN3D_LIBRARIES} + ${EIGEN_LIBRARIES} CxxUtils + GeoModelUtilities + VP1HEPVis ) +endif() diff --git a/graphics/VP1/VP1Utils/VP1Utils/SoVisualizeAction.h b/graphics/VP1/VP1Utils/VP1Utils/SoVisualizeAction.h index 9f57ceb0dc56daa427d065238c3230cbe6ca881c..da5c355ddef148f0e82760422cd9a6bf1c93c5ad 100644 --- a/graphics/VP1/VP1Utils/VP1Utils/SoVisualizeAction.h +++ b/graphics/VP1/VP1Utils/VP1Utils/SoVisualizeAction.h @@ -40,7 +40,9 @@ public: virtual void handleTubs(const GeoTubs *tubs); - virtual void handleLArCustom(const LArCustomShape *); + #ifndef BUILDVP1LIGHT + virtual void handleLArCustom(const LArCustomShape *); + #endif virtual void handleSimplePolygonBrep(const GeoSimplePolygonBrep *); diff --git a/graphics/VP1/VP1Utils/VP1Utils/VP1SGAccessHelper.icc b/graphics/VP1/VP1Utils/VP1Utils/VP1SGAccessHelper.icc index 13b2e3f46aa737fe94be3e90b7f0bc70a29b4612..165c43416e9aecbff45178eafa4ea9162cb9ceb5 100644 --- a/graphics/VP1/VP1Utils/VP1Utils/VP1SGAccessHelper.icc +++ b/graphics/VP1/VP1Utils/VP1Utils/VP1SGAccessHelper.icc @@ -2,11 +2,12 @@ Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ +#include "VP1Base/VP1Msg.h" template <typename T> inline const T* VP1SGAccessHelper::retrieve( const QString& key ) const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("retrieve(..) called with key = "+key+" for type "+QString(typeid(T).name())); if (!storeGate()) { @@ -43,7 +44,7 @@ inline const T* VP1SGAccessHelper::retrieve( const QString& key ) const message("ERROR: Failed StoreGateSvc::retrieve(..) with key="+key+" claimed to be succesful, but resulted in NULL pointer."); return 0; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Succesfully retrieved collection "+key); return t; } @@ -59,7 +60,7 @@ template <typename T> inline bool VP1SGAccessHelper::retrieve(const DataHandle<T>& begin, const DataHandle<T>& end, const bool&silent ) { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("retrieve(DataHandle<"+QString(typeid(T).name())+">,DataHandle<" +QString(typeid(T).name())+">) called."); if (!storeGate()) { @@ -91,7 +92,7 @@ inline bool VP1SGAccessHelper::retrieve(const DataHandle<T>& begin, const DataHa return false; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Successfully retrieved datahandles to "+QString(typeid(T).name())+"."); return true; } diff --git a/graphics/VP1/VP1Utils/VP1Utils/VP1ToolAccessHelper.icc b/graphics/VP1/VP1Utils/VP1Utils/VP1ToolAccessHelper.icc index efaeba337472e55a69130b83d89e768f3153a8b3..ab6fcbe7ccece84df7311faa43c612ed8791b964 100644 --- a/graphics/VP1/VP1Utils/VP1Utils/VP1ToolAccessHelper.icc +++ b/graphics/VP1/VP1Utils/VP1Utils/VP1ToolAccessHelper.icc @@ -2,6 +2,7 @@ Copyright (C) 2002-2018 CERN for the benefit of the ATLAS collaboration */ +#include "VP1Base/VP1Msg.h" template <class toolT> inline toolT * VP1ToolAccessHelper::getToolPointer( const QString& tooltypeandname, bool silent, bool createIfNotExists ) @@ -11,7 +12,7 @@ inline toolT * VP1ToolAccessHelper::getToolPointer( const QString& tooltypeandna //keep correct pointers and avoid dynamic casts to null! QString typeidstr(typeid(toolT*).name()); - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("getToolPointer(..) called with tool type/name = "+tooltypeandname +", with return typeid = "+typeidstr); if (!m_toolsvc) { @@ -72,13 +73,13 @@ inline toolT * VP1ToolAccessHelper::getToolPointer( const QString& tooltypeandna message("getToolPointer(..) ERROR: Tool retrieved is not a valid interface!"); thetool = 0; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("Returning "+str(thetool)+" tool pointer."); //We need the cast to void ptr to work around some WEIRD pointer //values introduced by a more straight-forward casting: void* voidptr = static_cast<void*>(thetool); IAlgTool* algptr = static_cast<IAlgTool*>(voidptr); - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("getToolPointer(..) Storing ptr = "+str(algptr)); m_toolname2pointer[id] = algptr; return thetool; @@ -95,7 +96,7 @@ inline toolT * VP1ToolAccessHelper::getToolPointer( const QString& tooltypeandna +" to type "+QString(typeid(toolT*).name())+". Returning 0."); return 0; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("getToolPointer(..) Retrieved tool pointer ("+str(pointer)+") succesfully"); return pointer; } diff --git a/graphics/VP1/VP1Utils/src/HitToSodeNode.cxx b/graphics/VP1/VP1Utils/src/HitToSodeNode.cxx index 6a2b2f121eebf2679cef971b0699cb11ff3d25b4..e57d8c06abe1e0e18eca8acdc142e42678464023 100644 --- a/graphics/VP1/VP1Utils/src/HitToSodeNode.cxx +++ b/graphics/VP1/VP1Utils/src/HitToSodeNode.cxx @@ -5,6 +5,8 @@ // Update: Riccardo Maria BIANCHI rbianchi@cern.ch Feb 2014 // +#ifndef BUILDVP1LIGHT + #include "VP1Utils/HitToSoNode.h" #include "VP1Utils/HitsSoNodeManager.h" #include "VP1Utils/VP1LinAlgUtils.h" @@ -524,3 +526,5 @@ void HitToSoNode::fillSiValues(Identifier& id, const Trk::TrkDetElementBase* bas stripThickness = detEl->thickness()/10.0; } + +#endif // BUILDVP1LIGHT diff --git a/graphics/VP1/VP1Utils/src/HitsSoNodeManager.cxx b/graphics/VP1/VP1Utils/src/HitsSoNodeManager.cxx index 07c612984a5b7ed17bec1712be59e4ecda1f95c3..0c59f2826bd8e1a9dc871fafe7abd7ab92dfce16 100644 --- a/graphics/VP1/VP1Utils/src/HitsSoNodeManager.cxx +++ b/graphics/VP1/VP1Utils/src/HitsSoNodeManager.cxx @@ -3,6 +3,7 @@ */ #include "VP1Utils/HitsSoNodeManager.h" +#include "VP1Base/VP1Msg.h" #include <Inventor/C/errors/debugerror.h> #include <Inventor/nodes/SoVertexProperty.h> @@ -54,7 +55,7 @@ public: } if ( x <= 1.0e-5 ) { if ( x < 0.0 ) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("sanitiseParameterValue WARNING - received negative parameter. Flipping sign."); x = - x; } @@ -72,7 +73,7 @@ public: } if ( x <= 1.0e-5 ) { if ( x < 0.0 ) { - if (theclass->verbose()) + if (VP1Msg::verbose()) theclass->messageVerbose("sanitiseParameterValue WARNING - received negative parameter. Flipping sign."); x = - x; } @@ -101,7 +102,7 @@ void HitsSoNodeManager::Imp::summarise(unsigned n,const QString& shapename) cons { if (n>100) theclass->messageDebug(" WARNING: Created more than 100 ("+QString::number(n)+") different "+shapename+" shapes."); - else if (theclass->verbose()) + else if (VP1Msg::verbose()) theclass->messageVerbose("Created "+QString::number(n)+" different "+shapename+" shapes."); } diff --git a/graphics/VP1/VP1Utils/src/SoVisualizeAction.cxx b/graphics/VP1/VP1Utils/src/SoVisualizeAction.cxx index 7a1985019af76488602901d270d67e08de7936cc..c2034f652169aa7a3cc1715025e9a46b3bd932e6 100644 --- a/graphics/VP1/VP1Utils/src/SoVisualizeAction.cxx +++ b/graphics/VP1/VP1Utils/src/SoVisualizeAction.cxx @@ -14,8 +14,10 @@ #include "GeoModelKernel/GeoTessellatedSolid.h" #include "GeoModelKernel/GeoFacet.h" #include "GeoModelKernel/GeoGenericTrap.h" -#include "GeoSpecialShapes/LArCustomShape.h" -#include "GeoSpecialShapes/LArWheelCalculator.h" +#ifndef BUILDVP1LIGHT + #include "GeoSpecialShapes/LArCustomShape.h" + #include "GeoSpecialShapes/LArWheelCalculator.h" +#endif #include "VP1HEPVis/nodes/SoTubs.h" #include "VP1HEPVis/nodes/SoCons.h" #include "VP1HEPVis/nodes/SoGenericBox.h" @@ -26,7 +28,17 @@ #include "VP1HEPVis/nodes/SoPolyhedron.h" #include "VP1HEPVis/VP1HEPVisUtils.h" #include "VP1Utils/SbPolyhedrizeAction.h" -#include "GaudiKernel/SystemOfUnits.h" + +// System of units +#ifdef BUILDVP1LIGHT + #include "GeoModelKernel/Units.h" + #define SYSTEM_OF_UNITS GeoModelKernelUnits // --> 'GeoModelKernelUnits::cm' +#else + #include "GaudiKernel/SystemOfUnits.h" + #define SYSTEM_OF_UNITS Gaudi::Units // --> 'Gaudi::Units::cm' +#endif + +#include <iostream> SoVisualizeAction::SoVisualizeAction() : m_shape(0) @@ -42,6 +54,7 @@ SoVisualizeAction::~SoVisualizeAction() void SoVisualizeAction::handleShape(const GeoShape *shape) { + //qDebug() << "SoVisualizeAction::handleShape"; // We don't recognize it. Try to polyhedrize it! SbPolyhedrizeAction a; shape->exec(&a); @@ -55,6 +68,7 @@ void SoVisualizeAction::handleShape(const GeoShape *shape) void SoVisualizeAction::handleBox(const GeoBox *box) { + //qDebug() << "SoVisualizeAction::handleBox"; SoGenericBox * gb = new SoGenericBox; gb->setParametersForBox( box->getXHalfLength(),box->getYHalfLength(),box->getZHalfLength() ); m_shape=gb; @@ -62,6 +76,7 @@ void SoVisualizeAction::handleBox(const GeoBox *box) void SoVisualizeAction::handleCons(const GeoCons *cons) { + //qDebug() << "SoVisualizeAction::handleCons"; SoCons::initClass(); SoCons *socons= new SoCons; socons->fRmin1 =cons->getRMin1(); @@ -78,6 +93,7 @@ void SoVisualizeAction::handleCons(const GeoCons *cons) void SoVisualizeAction::handlePcon(const GeoPcon *pcon) { + //qDebug() << "SoVisualizeAction::handlePcon"; //Set up temporary data arrays for profile: float *z = new float[pcon->getNPlanes()]; @@ -109,6 +125,7 @@ void SoVisualizeAction::handlePcon(const GeoPcon *pcon) void SoVisualizeAction::handleTrap(const GeoTrap *trap) { + //qDebug() << "SoVisualizeAction::handleTrap"; SoGenericBox * gb = new SoGenericBox; gb->setParametersForTrapezoid(trap->getZHalfLength(), trap->getTheta(), trap->getPhi(), trap->getDydzn(), trap->getDxdyndzn(), trap->getDxdypdzn(), @@ -119,6 +136,7 @@ void SoVisualizeAction::handleTrap(const GeoTrap *trap) void SoVisualizeAction::handleTrd(const GeoTrd *trd) { + //qDebug() << "SoVisualizeAction::handleTrd"; SoGenericBox * gb = new SoGenericBox; gb->setParametersForTrd( trd->getXHalfLength1(), trd->getXHalfLength2(), trd->getYHalfLength1(), trd->getYHalfLength2(), @@ -128,6 +146,7 @@ void SoVisualizeAction::handleTrd(const GeoTrd *trd) void SoVisualizeAction::handleTube(const GeoTube *tube) { + //qDebug() << "SoVisualizeAction::handleTube"; SoTubs *sotubs= new SoTubs; sotubs->pRMin= tube->getRMin(); sotubs->pRMax= tube->getRMax(); @@ -139,6 +158,7 @@ void SoVisualizeAction::handleTube(const GeoTube *tube) void SoVisualizeAction::handleTubs(const GeoTubs *tubs) { + //qDebug() << "SoVisualizeAction::handleTubs"; SoTubs *sotubs= new SoTubs; sotubs->pRMin= tubs->getRMin(); sotubs->pRMax= tubs->getRMax(); @@ -148,18 +168,20 @@ void SoVisualizeAction::handleTubs(const GeoTubs *tubs) m_shape=sotubs; } +#ifndef BUILDVP1LIGHT void SoVisualizeAction::handleLArCustom(const LArCustomShape *custom) { + //qDebug() << "SoVisualizeAction::handleLArCustom"; static const double eta_hi = 3.2; static const double eta_mid = 2.5; static const double eta_low = 1.375; - // static const double zWheelRefPoint = 3689.5*Gaudi::Units::mm; //=endg_z0 - static const double dMechFocaltoWRP = 3691. *Gaudi::Units::mm; //=endg_z1 - // static const double dElecFocaltoWRP = 3689. *Gaudi::Units::mm; //=endg_dcf - static const double dWRPtoFrontFace = 11. *Gaudi::Units::mm; - static const double rOuterCutoff = 2034. *Gaudi::Units::mm; //=endg_rlimit + // static const double zWheelRefPoint = 3689.5*SYSTEM_OF_UNITS::mm; //=endg_z0 + static const double dMechFocaltoWRP = 3691. *SYSTEM_OF_UNITS::mm; //=endg_z1 + // static const double dElecFocaltoWRP = 3689. *SYSTEM_OF_UNITS::mm; //=endg_dcf + static const double dWRPtoFrontFace = 11. *SYSTEM_OF_UNITS::mm; + static const double rOuterCutoff = 2034. *SYSTEM_OF_UNITS::mm; //=endg_rlimit SoLAr::initClass(); @@ -182,7 +204,7 @@ void SoVisualizeAction::handleLArCustom(const LArCustomShape *custom) rInner[1] = zWheelBackFace * tanThetaInner; // Note that there is a 3mm gap between the outer surface of the // inner wheel and the inner surface of the outer wheel. - double HalfGapBetweenWheels = 0.15*Gaudi::Units::cm; // In DB EMECGEOMETRY.DCRACK + double HalfGapBetweenWheels = 0.15*SYSTEM_OF_UNITS::cm; // In DB EMECGEOMETRY.DCRACK rOuter[0] = zWheelFrontFace * tanThetaMid - HalfGapBetweenWheels; rOuter[1] = zWheelBackFace * tanThetaMid - HalfGapBetweenWheels; solar->fRmin.setValues(0,2,rInner); @@ -202,7 +224,7 @@ void SoVisualizeAction::handleLArCustom(const LArCustomShape *custom) double zWheelBackFace = zWheelFrontFace + calc->GetWheelThickness(); // Note that there is a 3mm gap between the outer surface of the // inner wheel and the inner surface of the outer wheel. - double HalfGapBetweenWheels = 0.15*Gaudi::Units::cm; // In DB! (EMECGEOMETRY.DCRACK); + double HalfGapBetweenWheels = 0.15*SYSTEM_OF_UNITS::cm; // In DB! (EMECGEOMETRY.DCRACK); rInner[0] = zWheelFrontFace * tanThetaMid + HalfGapBetweenWheels; rInner[2] = zWheelBackFace * tanThetaMid + HalfGapBetweenWheels; rOuter[0] = zWheelFrontFace * tanThetaOuter; @@ -233,10 +255,11 @@ void SoVisualizeAction::handleLArCustom(const LArCustomShape *custom) solar->fDPhi= 2*M_PI; m_shape=solar; } - +#endif void SoVisualizeAction::handleSimplePolygonBrep(const GeoSimplePolygonBrep *brep) { + //qDebug() << "SoVisualizeAction::handleSimplePolygonBrep"; //Fixme: Detect if order of vertices is the wrong way around... and reorder if necessary. double dz = brep->getDZ(); @@ -254,6 +277,7 @@ void SoVisualizeAction::handleSimplePolygonBrep(const GeoSimplePolygonBrep *brep void SoVisualizeAction::handleTessellatedSolid (const GeoTessellatedSolid* geoTessellated) { + //qDebug() << "SoVisualizeAction::handleTessellatedSolid"; SoTessellated * soTessellated = new SoTessellated; for(size_t i=0; i<geoTessellated->getNumberOfFacets();++i) { @@ -298,6 +322,7 @@ void SoVisualizeAction::handleTessellatedSolid (const GeoTessellatedSolid* geoTe void SoVisualizeAction::handleGenericTrap(const GeoGenericTrap *gentrap) { + //qDebug() << "SoVisualizeAction::handleGenericTrap"; SoGenericBox * gb = new SoGenericBox; const GeoGenericTrapVertices& trapVertices = gentrap->getVertices(); double dZ = gentrap->getZHalfLength(); diff --git a/graphics/VP1/VP1Utils/src/VP1AvailableToolsHelper.cxx b/graphics/VP1/VP1Utils/src/VP1AvailableToolsHelper.cxx index 631d59f3a4f199fa55c0463b49d52e6748938572..83480dbfe885c45dcc0179a94e57607ba9c670e2 100644 --- a/graphics/VP1/VP1Utils/src/VP1AvailableToolsHelper.cxx +++ b/graphics/VP1/VP1Utils/src/VP1AvailableToolsHelper.cxx @@ -14,6 +14,7 @@ #include "VP1Utils/VP1AvailableToolsHelper.h" #include "VP1Base/IVP1System.h" +#include "VP1Base/VP1Msg.h" #include "GaudiKernel/IToolSvc.h" #include <QComboBox> @@ -171,7 +172,7 @@ QStringList VP1AvailableToolsHelper::Imp::actualCurrentlyAvailableTools() foreach ( QString tooltype, monitoredTypes ) { std::vector<std::string> instances; instances = toolsvc->getInstances( tooltype.toStdString() ); - if (!silent&&theclass->verbose()) + if (!silent&&VP1Msg::verbose()) theclass->messageVerbose("Used toolsvc->getInstances(..) to find "+QString::number(instances.size())+" public tools of type "+tooltype ); for (unsigned i = 0; i < instances.size(); ++i ) { QString instance(instances.at(i).c_str()); @@ -188,15 +189,15 @@ QStringList VP1AvailableToolsHelper::Imp::actualCurrentlyAvailableTools() } } if (ignore) { - if (!silent&&theclass->verbose()) + if (!silent&&VP1Msg::verbose()) theclass->messageVerbose(" --> Found but ignoring "+instance ); continue; } } - if (!silent&&theclass->verbose()) + if (!silent&&VP1Msg::verbose()) theclass->messageVerbose(" --> Found "+instance ); l << tooltype+"/"+instance; - if (!silent&&theclass->verbose()) + if (!silent&&VP1Msg::verbose()) theclass->messageVerbose(" --> Appended "+tooltype+"/"+instance+" to list" ); } } diff --git a/graphics/VP1/VP1Utils/src/VP1SGContentsHelper.cxx b/graphics/VP1/VP1Utils/src/VP1SGContentsHelper.cxx index c45bafabe116968a9070c73dd1ccaf85fe186118..e6ae17aaf588de8fa4c89f8df6840833361ce932 100644 --- a/graphics/VP1/VP1Utils/src/VP1SGContentsHelper.cxx +++ b/graphics/VP1/VP1Utils/src/VP1SGContentsHelper.cxx @@ -14,6 +14,7 @@ #include "VP1Utils/VP1SGContentsHelper.h" #include "VP1Base/IVP1System.h" +#include "VP1Base/VP1Msg.h" #include "StoreGate/StoreGateSvc.h" // #include <stdexcept> #include <QStringList> @@ -41,7 +42,7 @@ VP1SGContentsHelper::VP1SGContentsHelper( StoreGateSvc * sg ) //____________________________________________________________________ bool VP1SGContentsHelper::contains( const CLID& id, const QString& key ) const { - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("contains(..) called for key = "+key); if (!m_sg) { message("ERROR: Does not have StoreGate pointer - returning false."); @@ -63,7 +64,7 @@ bool VP1SGContentsHelper::contains( const CLID& id, const QString& key ) const message("ERROR: Exception thrown during call to StoreGateSvc::contains(..). Returning false."); return false; } - if (verbose()) + if (VP1Msg::verbose()) messageVerbose("contains(..) returning "+QString(contains?"true":"false")); return contains; } @@ -97,11 +98,11 @@ QStringList VP1SGContentsHelper::getKeys(const CLID& id) const continue; if (contains(id,it->c_str())) l << it->c_str(); - else if (verbose()) + else if (VP1Msg::verbose()) messageVerbose("NB: StoreGateSvc::keys() included '"+QString(it->c_str()) +"' but StoreGateSvc::contains("+QString(it->c_str())+") returns false." ); } - if (verbose()) { + if (VP1Msg::verbose()) { messageVerbose("returning "+QString::number(l.count())+" keys:"); messageVerbose(" => ",l); } diff --git a/graphics/VP1/VP1UtilsBase/src/VP1FileUtilities.cxx b/graphics/VP1/VP1UtilsBase/src/VP1FileUtilities.cxx index 307a12129b18498af1e34be27b6945df7d9a9412..9c89cd4b61ad0f165cf68c44a5788be9d1f1e65e 100644 --- a/graphics/VP1/VP1UtilsBase/src/VP1FileUtilities.cxx +++ b/graphics/VP1/VP1UtilsBase/src/VP1FileUtilities.cxx @@ -21,6 +21,7 @@ #include <QFileInfoList> #include <QThread> +#include <string> #include <sstream> #include <iomanip> #include <iostream> diff --git a/graphics/VP1/VP1UtilsBase/src/VP1TimeUtilities.cxx b/graphics/VP1/VP1UtilsBase/src/VP1TimeUtilities.cxx index 14b7697aa7e7775e18f0c5c4cec6e858b7189a17..ab983a1936fd7bc2fdad6e11a71459ee5b42e042 100644 --- a/graphics/VP1/VP1UtilsBase/src/VP1TimeUtilities.cxx +++ b/graphics/VP1/VP1UtilsBase/src/VP1TimeUtilities.cxx @@ -19,6 +19,7 @@ #include <iomanip> #include <string> #include <iostream> +#include <sstream> // for std::ostringstream std::string VP1TimeUtilities::getHumanReadableTimestamp(time_t t_timestamp) @@ -37,4 +38,3 @@ std::string VP1TimeUtilities::getHumanReadableTimestamp(time_t t_timestamp) //std::cout << "'human readable' timestamp: " << m_humanTimestamp << std::endl; return humanTimestamp; } -