text
stringlengths
54
60.6k
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkStreamingImageFilter_hxx #define itkStreamingImageFilter_hxx #include "itkStreamingImageFilter.h" #include "itkCommand.h" #include "itkImageAlgorithm.h" #include "itkImageRegionSplitterSlowDimension.h" namespace itk { /** * */ template< typename TInputImage, typename TOutputImage > StreamingImageFilter< TInputImage, TOutputImage > ::StreamingImageFilter() { // default to 10 divisions m_NumberOfStreamDivisions = 10; // create default region splitter m_RegionSplitter = ImageRegionSplitterSlowDimension::New(); } /** * */ template< typename TInputImage, typename TOutputImage > StreamingImageFilter< TInputImage, TOutputImage > ::~StreamingImageFilter() {} /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Number of stream divisions: " << m_NumberOfStreamDivisions << std::endl; if ( m_RegionSplitter ) { os << indent << "Region splitter:" << m_RegionSplitter << std::endl; } else { os << indent << "Region splitter: (none)" << std::endl; } } /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::PropagateRequestedRegion(DataObject *output) { /** * check flag to avoid executing forever if there is a loop */ if ( this->m_Updating ) { return; } /** * Give the subclass a chance to indicate that it will provide * more data then required for the output. This can happen, for * example, when a source can only produce the whole output. * Although this is being called for a specific output, the source * may need to enlarge all outputs. */ this->EnlargeOutputRequestedRegion(output); /** * Give the subclass a chance to define how to set the requested * regions for each of its outputs, given this output's requested * region. The default implementation is to make all the output * requested regions the same. A subclass may need to override this * method if each output is a different resolution. */ this->GenerateOutputRequestedRegion(output); // we don't call GenerateInputRequestedRegion since the requested // regions are manage when the pipeline is execute // we don't call inputs PropagateRequestedRegion either // because the pipeline managed later } /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::UpdateOutputData( DataObject *itkNotUsed(output) ) { unsigned int idx; /** * prevent chasing our tail */ if ( this->m_Updating ) { return; } /** * Prepare all the outputs. This may deallocate previous bulk data. */ this->PrepareOutputs(); /** * Make sure we have the necessary inputs */ const itk::ProcessObject::DataObjectPointerArraySizeType &ninputs = this->GetNumberOfValidRequiredInputs(); if ( ninputs < this->GetNumberOfRequiredInputs() ) { itkExceptionMacro( << "At least " << static_cast< unsigned int >( this->GetNumberOfRequiredInputs() ) << " inputs are required but only " << ninputs << " are specified."); return; } /** * Tell all Observers that the filter is starting, before emiting * the 0.0 Progress event */ this->InvokeEvent( StartEvent() ); this->SetAbortGenerateData(0); this->UpdateProgress(0.0); this->m_Updating = true; /** * Allocate the output buffer. */ OutputImageType *outputPtr = this->GetOutput(0); const OutputImageRegionType outputRegion = outputPtr->GetRequestedRegion(); outputPtr->SetBufferedRegion(outputRegion); outputPtr->Allocate(); /** * Grab the input */ InputImageType * inputPtr = const_cast< InputImageType * >( this->GetInput(0) ); /** * Determine of number of pieces to divide the input. This will be the * minimum of what the user specified via SetNumberOfStreamDivisions() * and what the Splitter thinks is a reasonable value. */ unsigned int numDivisions, numDivisionsFromSplitter; numDivisions = m_NumberOfStreamDivisions; numDivisionsFromSplitter = m_RegionSplitter ->GetNumberOfSplits(outputRegion, m_NumberOfStreamDivisions); if ( numDivisionsFromSplitter < numDivisions ) { numDivisions = numDivisionsFromSplitter; } /** * Loop over the number of pieces, execute the upstream pipeline on each * piece, and copy the results into the output image. */ unsigned int piece=0; for (; piece < numDivisions && !this->GetAbortGenerateData(); piece++ ) { InputImageRegionType streamRegion = outputRegion; m_RegionSplitter->GetSplit(piece, numDivisions, streamRegion); inputPtr->SetRequestedRegion(streamRegion); inputPtr->PropagateRequestedRegion(); inputPtr->UpdateOutputData(); // copy the result to the proper place in the output. the input // requested region determined by the RegionSplitter (as opposed // to what the pipeline might have enlarged it to) is used to // copy the regions from the input to output ImageAlgorithm::Copy( inputPtr, outputPtr, streamRegion, streamRegion ); this->UpdateProgress( static_cast<float>(piece) / static_cast<float>(numDivisions) ); } /** * If we ended due to aborting, push the progress up to 1.0 (since * it probably didn't end there) */ if ( !this->GetAbortGenerateData() ) { this->UpdateProgress(1.0); } // Notify end event observers this->InvokeEvent( EndEvent() ); /** * Now we have to mark the data as up to data. */ for ( idx = 0; idx < this->GetNumberOfOutputs(); ++idx ) { if ( this->GetOutput(idx) ) { this->GetOutput(idx)->DataHasBeenGenerated(); } } /** * Release any inputs if marked for release */ this->ReleaseInputs(); // Mark that we are no longer updating the data in this filter this->m_Updating = false; } } // end namespace itk #endif <commit_msg>ENH: Use PrinSelfObjectMacro<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkStreamingImageFilter_hxx #define itkStreamingImageFilter_hxx #include "itkStreamingImageFilter.h" #include "itkCommand.h" #include "itkImageAlgorithm.h" #include "itkImageRegionSplitterSlowDimension.h" namespace itk { /** * */ template< typename TInputImage, typename TOutputImage > StreamingImageFilter< TInputImage, TOutputImage > ::StreamingImageFilter() { // default to 10 divisions m_NumberOfStreamDivisions = 10; // create default region splitter m_RegionSplitter = ImageRegionSplitterSlowDimension::New(); } /** * */ template< typename TInputImage, typename TOutputImage > StreamingImageFilter< TInputImage, TOutputImage > ::~StreamingImageFilter() {} /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Number of stream divisions: " << m_NumberOfStreamDivisions << std::endl; itkPrintSelfObjectMacro( RegionSplitter ); } /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::PropagateRequestedRegion(DataObject *output) { /** * check flag to avoid executing forever if there is a loop */ if ( this->m_Updating ) { return; } /** * Give the subclass a chance to indicate that it will provide * more data then required for the output. This can happen, for * example, when a source can only produce the whole output. * Although this is being called for a specific output, the source * may need to enlarge all outputs. */ this->EnlargeOutputRequestedRegion(output); /** * Give the subclass a chance to define how to set the requested * regions for each of its outputs, given this output's requested * region. The default implementation is to make all the output * requested regions the same. A subclass may need to override this * method if each output is a different resolution. */ this->GenerateOutputRequestedRegion(output); // we don't call GenerateInputRequestedRegion since the requested // regions are manage when the pipeline is execute // we don't call inputs PropagateRequestedRegion either // because the pipeline managed later } /** * */ template< typename TInputImage, typename TOutputImage > void StreamingImageFilter< TInputImage, TOutputImage > ::UpdateOutputData( DataObject *itkNotUsed(output) ) { unsigned int idx; /** * prevent chasing our tail */ if ( this->m_Updating ) { return; } /** * Prepare all the outputs. This may deallocate previous bulk data. */ this->PrepareOutputs(); /** * Make sure we have the necessary inputs */ const itk::ProcessObject::DataObjectPointerArraySizeType &ninputs = this->GetNumberOfValidRequiredInputs(); if ( ninputs < this->GetNumberOfRequiredInputs() ) { itkExceptionMacro( << "At least " << static_cast< unsigned int >( this->GetNumberOfRequiredInputs() ) << " inputs are required but only " << ninputs << " are specified."); return; } /** * Tell all Observers that the filter is starting, before emiting * the 0.0 Progress event */ this->InvokeEvent( StartEvent() ); this->SetAbortGenerateData(0); this->UpdateProgress(0.0); this->m_Updating = true; /** * Allocate the output buffer. */ OutputImageType *outputPtr = this->GetOutput(0); const OutputImageRegionType outputRegion = outputPtr->GetRequestedRegion(); outputPtr->SetBufferedRegion(outputRegion); outputPtr->Allocate(); /** * Grab the input */ InputImageType * inputPtr = const_cast< InputImageType * >( this->GetInput(0) ); /** * Determine of number of pieces to divide the input. This will be the * minimum of what the user specified via SetNumberOfStreamDivisions() * and what the Splitter thinks is a reasonable value. */ unsigned int numDivisions, numDivisionsFromSplitter; numDivisions = m_NumberOfStreamDivisions; numDivisionsFromSplitter = m_RegionSplitter ->GetNumberOfSplits(outputRegion, m_NumberOfStreamDivisions); if ( numDivisionsFromSplitter < numDivisions ) { numDivisions = numDivisionsFromSplitter; } /** * Loop over the number of pieces, execute the upstream pipeline on each * piece, and copy the results into the output image. */ unsigned int piece=0; for (; piece < numDivisions && !this->GetAbortGenerateData(); piece++ ) { InputImageRegionType streamRegion = outputRegion; m_RegionSplitter->GetSplit(piece, numDivisions, streamRegion); inputPtr->SetRequestedRegion(streamRegion); inputPtr->PropagateRequestedRegion(); inputPtr->UpdateOutputData(); // copy the result to the proper place in the output. the input // requested region determined by the RegionSplitter (as opposed // to what the pipeline might have enlarged it to) is used to // copy the regions from the input to output ImageAlgorithm::Copy( inputPtr, outputPtr, streamRegion, streamRegion ); this->UpdateProgress( static_cast<float>(piece) / static_cast<float>(numDivisions) ); } /** * If we ended due to aborting, push the progress up to 1.0 (since * it probably didn't end there) */ if ( !this->GetAbortGenerateData() ) { this->UpdateProgress(1.0); } // Notify end event observers this->InvokeEvent( EndEvent() ); /** * Now we have to mark the data as up to data. */ for ( idx = 0; idx < this->GetNumberOfOutputs(); ++idx ) { if ( this->GetOutput(idx) ) { this->GetOutput(idx)->DataHasBeenGenerated(); } } /** * Release any inputs if marked for release */ this->ReleaseInputs(); // Mark that we are no longer updating the data in this filter this->m_Updating = false; } } // end namespace itk #endif <|endoftext|>
<commit_before>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { allocation_mtx.lock(); exception_from_the_event_thread = nullptr; event_lock = nullptr; calling_lock = nullptr; calling_lock = new std::unique_lock<std::mutex>(mtx); allocation_mtx.unlock(); exception_from_the_event_thread = nullptr; event_cleanup = [](){}; // empty function auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ allocation_mtx.lock(); event_lock = new std::unique_lock<std::mutex>(mtx); allocation_mtx.unlock(); calling_waiter.notify_one(); event_waiter.wait(*event_lock); std::this_thread::yield(); try { func([&](){switchToCallingThread();}); if (require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ allocation_mtx.lock(); exception_from_the_event_thread = new std::runtime_error(e); allocation_mtx.unlock(); calling_waiter.notify_one(); std::this_thread::yield(); } allocation_mtx.lock(); delete event_lock; event_lock = nullptr; allocation_mtx.unlock(); event_cleanup(); }; event_thread = std::thread(event); std::this_thread::yield(); calling_waiter.wait(*calling_lock); std::this_thread::yield(); } EventThreader::~EventThreader() { } void EventThreader::deallocate() { allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (calling_lock != nullptr) { delete calling_lock; calling_lock = nullptr; } if (event_lock != nullptr) { delete event_lock; event_lock = nullptr; } allocation_mtx.unlock(); } void EventThreader::switchToCallingThread() { if (!require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } require_switch_from_event = false; /* switch to calling */ calling_waiter.notify_one(); std::this_thread::yield(); event_waiter.wait(*(event_lock)); std::this_thread::yield(); /* back from calling */ } void EventThreader::switchToEventThread() { } void EventThreader::join() { allocation_mtx.lock(); delete calling_lock; // remove lock on this thread, allow event to run calling_lock = nullptr; allocation_mtx.unlock(); if (event_lock != nullptr) { event_waiter.notify_one(); std::this_thread::yield(); } event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; allocation_mtx.unlock(); throw e_copy; } deallocate(); } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); // class variables // class functions auto deallocate = [&]() { et.deallocate(); }; auto join = [&]() { et.join(); }; auto switchToCallingThread = [&]() { et.switchToCallingThread(); }; auto switchToEventThread= [&]() { if (et.require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } et.require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (et.require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ join(); } }; // Start construction // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); deallocate(); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <commit_msg>constructor func<commit_after>#include "catch.hpp" #include <iostream> #include <exception> // std::bad_function_call, std::runtime_error #include <thread> // std::thread, std::this_thread::yield #include <mutex> // std::mutex, std::unique_lock #include <condition_variable> // std::condition_variable #include <functional> // std::function class EventThreader { public: std::condition_variable event_waiter; std::condition_variable calling_waiter; std::unique_lock<std::mutex>* event_lock = nullptr; std::unique_lock<std::mutex>* calling_lock = nullptr; std::mutex mtx; std::mutex allocation_mtx; std::thread event_thread; void switchToCallingThread(); bool require_switch_from_event = false; std::function<void(void)> event_cleanup; std::runtime_error* exception_from_the_event_thread = nullptr; void deallocate(); public: EventThreader(std::function<void (std::function<void (void)>)> func); ~EventThreader(); void switchToEventThread(); void join(); void setEventCleanup(std::function<void(void)>); }; EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) { allocation_mtx.lock(); calling_lock = new std::unique_lock<std::mutex>(mtx); allocation_mtx.unlock(); } EventThreader::~EventThreader() { } void EventThreader::deallocate() { allocation_mtx.lock(); if (exception_from_the_event_thread != nullptr) { delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; } if (calling_lock != nullptr) { delete calling_lock; calling_lock = nullptr; } if (event_lock != nullptr) { delete event_lock; event_lock = nullptr; } allocation_mtx.unlock(); } void EventThreader::switchToCallingThread() { if (!require_switch_from_event) { throw std::runtime_error("switch to calling not matched with a switch to event"); } require_switch_from_event = false; /* switch to calling */ calling_waiter.notify_one(); std::this_thread::yield(); event_waiter.wait(*(event_lock)); std::this_thread::yield(); /* back from calling */ } void EventThreader::switchToEventThread() { } void EventThreader::join() { allocation_mtx.lock(); delete calling_lock; // remove lock on this thread, allow event to run calling_lock = nullptr; allocation_mtx.unlock(); if (event_lock != nullptr) { event_waiter.notify_one(); std::this_thread::yield(); } event_thread.join(); if (exception_from_the_event_thread != nullptr) { /* an exception occured */ std::runtime_error e_copy(exception_from_the_event_thread->what()); allocation_mtx.lock(); delete exception_from_the_event_thread; exception_from_the_event_thread = nullptr; allocation_mtx.unlock(); throw e_copy; } deallocate(); } void EventThreader::setEventCleanup(std::function<void(void)> cleanup) { event_cleanup = cleanup; } TEST_CASE( "EventThreader", "[EventThreader]" ) { std::stringstream ss; SECTION("Finding the error") { /* Example of most basic use */ auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et([](std::function<void(void)> f){}); // class functions auto deallocate = [&]() { et.deallocate(); }; auto join = [&]() { et.join(); }; auto switchToCallingThread = [&]() { et.switchToCallingThread(); }; auto switchToEventThread= [&]() { if (et.require_switch_from_event) { throw std::runtime_error("switch to event not matched with a switch to calling"); } et.require_switch_from_event = true; /* switch to event */ et.event_waiter.notify_one(); std::this_thread::yield(); et.calling_waiter.wait(*et.calling_lock); std::this_thread::yield(); /* back from event */ if (et.require_switch_from_event) { /* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */ join(); } }; std::function<void (std::function<void (void)>)> func = f; // Start construction et.event_cleanup = [](){}; // empty function auto event = [&](){ /* mtx force switch to calling - blocked by the mutex */ et.allocation_mtx.lock(); et.event_lock = new std::unique_lock<std::mutex>(et.mtx); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); et.event_waiter.wait(*(et.event_lock)); std::this_thread::yield(); try { func([&](){switchToCallingThread();}); if (et.require_switch_from_event) { // the event has ended, but not ready to join // rejoin the calling thread after dealing with this exception throw std::runtime_error("switch to event not matched with a switch to calling"); } } catch (const std::runtime_error &e) { /* report the exception to the calling thread */ et.allocation_mtx.lock(); et.exception_from_the_event_thread = new std::runtime_error(e); et.allocation_mtx.unlock(); et.calling_waiter.notify_one(); std::this_thread::yield(); } et.allocation_mtx.lock(); delete et.event_lock; et.event_lock = nullptr; et.allocation_mtx.unlock(); et.event_cleanup(); }; et.event_thread = std::thread(event); std::this_thread::yield(); et.calling_waiter.wait(*(et.calling_lock)); std::this_thread::yield(); // End constuction //EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); /* Generate what the result should look like */ std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); deallocate(); } /* SECTION("Abitrary use") { // Example of most basic use auto f = [&ss](std::function<void(void)> switchToMainThread){ for(int i = 0; i < 100; i++) { ss << "*"; } switchToMainThread(); for(int i = 0; i < 50; i++) { ss << "*"; } switchToMainThread(); }; EventThreader et(f); switchToEventThread(); for(int i = 0; i < 75; i++) { ss << "$"; } switchToEventThread(); for(int i = 0; i < 25; i++) { ss << "$"; } join(); // Generate what the result should look like std::string requirement; for(int i = 0; i < 100; i++) { requirement += "*"; } for(int i = 0; i < 75; i++) { requirement += "$"; } for(int i = 0; i < 50; i++) { requirement += "*"; } for(int i = 0; i < 25; i++) { requirement += "$"; } REQUIRE( requirement == ss.str()); } */ } <|endoftext|>
<commit_before> #include "InverseKinematicsStudy.h" #include "OpenSenseUtilities.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/TimeSeriesTable.h> #include <OpenSim/Common/TableSource.h> #include <OpenSim/Common/STOFileAdapter.h> #include <OpenSim/Common/TRCFileAdapter.h> #include <OpenSim/Common/Reporter.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h> #include <OpenSim/Simulation/InverseKinematicsSolver.h> #include <OpenSim/Simulation/OrientationsReference.h> #include "ExperimentalMarker.h" #include "ExperimentalFrame.h" using namespace OpenSim; using namespace SimTK; using namespace std; InverseKinematicsStudy::InverseKinematicsStudy() { constructProperties(); } InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile) : Object(setupFile, true) { constructProperties(); updateFromXMLDocument(); } InverseKinematicsStudy::~InverseKinematicsStudy() { } void InverseKinematicsStudy::constructProperties() { constructProperty_accuracy(1e-6); constructProperty_constraint_weight(Infinity); Array<double> range{ Infinity, 2}; constructProperty_time_range(range); constructProperty_model_file_name(""); constructProperty_marker_file_name(""); constructProperty_orientations_file_name(""); constructProperty_results_directory(""); } void InverseKinematicsStudy:: previewExperimentalData(const TimeSeriesTableVec3& markers, const TimeSeriesTable_<SimTK::Rotation>& orientations) const { Model previewWorld; // Load the marker data into a TableSource that has markers // as its output which each markers occupying its own channel TableSourceVec3* markersSource = new TableSourceVec3(markers); // Add the markersSource Component to the model previewWorld.addComponent(markersSource); // Get the underlying Table backing the the marker Source so we // know how many markers we have and their names const auto& markerData = markersSource->getTable(); auto& times = markerData.getIndependentColumn(); auto startEnd = getTimeRangeInUse(times); // Create an ExperimentalMarker Component for every column in the markerData for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) { auto marker = new ExperimentalMarker(); marker->setName(markerData.getColumnLabel(i)); // markers are owned by the model previewWorld.addComponent(marker); // the time varying location of the marker comes from the markersSource // Component marker->updInput("location_in_ground").connect( markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i))); } previewWorld.setUseVisualizer(true); SimTK::State& state = previewWorld.initSystem(); state.updTime() = times[0]; previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); char c; std::cout << "press any key to visualize experimental marker data ..." << std::endl; std::cin >> c; for (size_t j =startEnd.get(0); j <= startEnd.get(1); j=j+10) { std::cout << "time: " << times[j] << "s" << std::endl; state.setTime(times[j]); previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); } } void InverseKinematicsStudy:: runInverseKinematicsWithOrientationsFromFile(Model& model, const std::string& orientationsFileName) { // Add a reporter to get IK computed coordinate values out TableReporter* ikReporter = new TableReporter(); ikReporter->setName("ik_reporter"); auto coordinates = model.updComponentList<Coordinate>(); std::vector<std::string> transCoordNames; // Hookup reporter inputs to the individual coordinate outputs // and keep track of coordinates that are translations for (auto& coord : coordinates) { ikReporter->updInput("inputs").connect( coord.getOutput("value"), coord.getName()); if (coord.getMotionType() == Coordinate::Translational) { transCoordNames.push_back(coord.getName()); coord.set_locked(true); } } model.addComponent(ikReporter); TimeSeriesTable_<SimTK::Quaternion> quatTable = STOFileAdapter_<SimTK::Quaternion>::read(orientationsFileName); std::cout << "Loading orientations as quaternions from " << orientationsFileName << std::endl; auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn()); TimeSeriesTable_<SimTK::Rotation> orientationsData = OpenSenseUtilities::convertQuaternionsToRotations(quatTable, startEnd); OrientationsReference oRefs(orientationsData); MarkersReference mRefs{}; SimTK::Array_<CoordinateReference> coordinateReferences; // visualize for debugging model.setUseVisualizer(true); SimTK::State& s0 = model.initSystem(); double t0 = s0.getTime(); // create the solver given the input data const double accuracy = 1e-4; InverseKinematicsSolver ikSolver(model, mRefs, oRefs, coordinateReferences); ikSolver.setAccuracy(accuracy); auto& times = oRefs.getTimes(); s0.updTime() = times[0]; ikSolver.assemble(s0); model.getVisualizer().show(s0); model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true); for (auto time : times) { s0.updTime() = time; ikSolver.track(s0); model.getVisualizer().show(s0); // realize to report to get reporter to pull values from model model.realizeReport(s0); } auto report = ikReporter->getTable(); auto eix = orientationsFileName.rfind("_"); if (eix == std::string::npos) { eix = orientationsFileName.rfind("."); } auto stix = orientationsFileName.rfind("/") + 1; IO::makeDir(get_results_directory()); std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix); std::string outputFile = get_results_directory() + "/" + outName; // Convert to degrees to compare with marker-based IK // but ignore translational coordinates for (size_t i = 0; i < report.getNumColumns(); ++i) { auto it = find( transCoordNames.begin(), transCoordNames.end(), report.getColumnLabel(i) ); if (it == transCoordNames.end()) { // not found = not translational auto repVec = report.updDependentColumnAtIndex(i); repVec *= SimTK::Real(SimTK_RTD); } } report.updTableMetaData().setValueForKey<string>("name", outName); report.updTableMetaData().setValueForKey<size_t>("nRows", report.getNumRows()); // getNumColumns returns the number of dependent columns, but Storage expects time report.updTableMetaData().setValueForKey<size_t>("nColumns", report.getNumColumns()+1); report.updTableMetaData().setValueForKey<string>("inDegrees","yes"); STOFileAdapter_<double>::write(report, outputFile + ".mot"); std::cout << "Wrote IK with IMU tracking results to: '" << outputFile << "'." << std::endl; } // main driver bool InverseKinematicsStudy::run() { bool correct_offsets = false; // Supply offset corrections due to incorrect placement, etc... as X, Y, Z body fixed rotation // Corrections are premultiplied. [C]*[R] std::map<std::string, SimTK::Vec3> imu_corections{ {"back_imu", {0, 0, 90}}, {"pelvis_imu", {0, 0, 90}} }; Model modelWithIMUs(get_model_file_name()); if (correct_offsets) { for (auto it : imu_corections) { auto* offset = modelWithIMUs.findComponent<PhysicalOffsetFrame>(it.first); SimTK::Transform transform = offset->getOffsetTransform(); Vec3 seq = it.second; Rotation correction{ SimTK::BodyOrSpaceType::BodyRotationSequence, double(SimTK_DEGREE_TO_RADIAN*seq[0]), SimTK::XAxis, double(SimTK_DEGREE_TO_RADIAN*seq[1]), SimTK::YAxis, double(SimTK_DEGREE_TO_RADIAN*seq[2]), SimTK::ZAxis }; transform.updR() = correction*transform.R(); modelWithIMUs.updComponent<PhysicalOffsetFrame>(offset->getAbsolutePath()) .setOffsetTransform(transform); } } runInverseKinematicsWithOrientationsFromFile(modelWithIMUs, get_orientations_file_name()); return true; } OpenSim::Array<int> InverseKinematicsStudy::getTimeRangeInUse( const std::vector<double>& times ) const { size_t nt = times.size(); size_t startIx = 0; size_t endIx = nt-1; for (size_t i = 0; i < nt; ++i) { if (times[i] <= get_time_range(0)) { startIx = i; } else { break; } } for (size_t i = nt - 1; i > 0; --i) { if (times[i] >= get_time_range(1)) { endIx= i; } else { break; } } OpenSim::Array<int> retArray; retArray.append(startIx); retArray.append(endIx); return retArray; } TimeSeriesTable_<SimTK::Vec3> InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile) { auto markers = TRCFileAdapter::read(markerFile); std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers " << " and " << markers.getNumRows() << " rows of data." << std::endl; if (markers.hasTableMetaDataKey("Units")) { std::cout << markerFile << " has Units meta data." << std::endl; auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; if (value.getValue<std::string>() == "mm") { std::cout << "Marker data in mm, converting to m." << std::endl; for (size_t i = 0; i < markers.getNumRows(); ++i) { markers.updRowAtIndex(i) *= 0.001; } markers.updTableMetaData().removeValueForKey("Units"); markers.updTableMetaData().setValueForKey<std::string>("Units", "m"); } } auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; return markers; }<commit_msg>Fix warnings converting size_t to int<commit_after> #include "InverseKinematicsStudy.h" #include "OpenSenseUtilities.h" #include <OpenSim/Common/IO.h> #include <OpenSim/Common/TimeSeriesTable.h> #include <OpenSim/Common/TableSource.h> #include <OpenSim/Common/STOFileAdapter.h> #include <OpenSim/Common/TRCFileAdapter.h> #include <OpenSim/Common/Reporter.h> #include <OpenSim/Simulation/Model/Model.h> #include <OpenSim/Simulation/Model/PhysicalOffsetFrame.h> #include <OpenSim/Simulation/InverseKinematicsSolver.h> #include <OpenSim/Simulation/OrientationsReference.h> #include "ExperimentalMarker.h" #include "ExperimentalFrame.h" using namespace OpenSim; using namespace SimTK; using namespace std; InverseKinematicsStudy::InverseKinematicsStudy() { constructProperties(); } InverseKinematicsStudy::InverseKinematicsStudy(const std::string& setupFile) : Object(setupFile, true) { constructProperties(); updateFromXMLDocument(); } InverseKinematicsStudy::~InverseKinematicsStudy() { } void InverseKinematicsStudy::constructProperties() { constructProperty_accuracy(1e-6); constructProperty_constraint_weight(Infinity); Array<double> range{ Infinity, 2}; constructProperty_time_range(range); constructProperty_model_file_name(""); constructProperty_marker_file_name(""); constructProperty_orientations_file_name(""); constructProperty_results_directory(""); } void InverseKinematicsStudy:: previewExperimentalData(const TimeSeriesTableVec3& markers, const TimeSeriesTable_<SimTK::Rotation>& orientations) const { Model previewWorld; // Load the marker data into a TableSource that has markers // as its output which each markers occupying its own channel TableSourceVec3* markersSource = new TableSourceVec3(markers); // Add the markersSource Component to the model previewWorld.addComponent(markersSource); // Get the underlying Table backing the the marker Source so we // know how many markers we have and their names const auto& markerData = markersSource->getTable(); auto& times = markerData.getIndependentColumn(); auto startEnd = getTimeRangeInUse(times); // Create an ExperimentalMarker Component for every column in the markerData for (int i = 0; i < int(markerData.getNumColumns()) ; ++i) { auto marker = new ExperimentalMarker(); marker->setName(markerData.getColumnLabel(i)); // markers are owned by the model previewWorld.addComponent(marker); // the time varying location of the marker comes from the markersSource // Component marker->updInput("location_in_ground").connect( markersSource->getOutput("column").getChannel(markerData.getColumnLabel(i))); } previewWorld.setUseVisualizer(true); SimTK::State& state = previewWorld.initSystem(); state.updTime() = times[0]; previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); char c; std::cout << "press any key to visualize experimental marker data ..." << std::endl; std::cin >> c; for (size_t j =startEnd.get(0); j <= startEnd.get(1); j=j+10) { std::cout << "time: " << times[j] << "s" << std::endl; state.setTime(times[j]); previewWorld.realizePosition(state); previewWorld.getVisualizer().show(state); } } void InverseKinematicsStudy:: runInverseKinematicsWithOrientationsFromFile(Model& model, const std::string& orientationsFileName) { // Add a reporter to get IK computed coordinate values out TableReporter* ikReporter = new TableReporter(); ikReporter->setName("ik_reporter"); auto coordinates = model.updComponentList<Coordinate>(); std::vector<std::string> transCoordNames; // Hookup reporter inputs to the individual coordinate outputs // and keep track of coordinates that are translations for (auto& coord : coordinates) { ikReporter->updInput("inputs").connect( coord.getOutput("value"), coord.getName()); if (coord.getMotionType() == Coordinate::Translational) { transCoordNames.push_back(coord.getName()); coord.set_locked(true); } } model.addComponent(ikReporter); TimeSeriesTable_<SimTK::Quaternion> quatTable = STOFileAdapter_<SimTK::Quaternion>::read(orientationsFileName); std::cout << "Loading orientations as quaternions from " << orientationsFileName << std::endl; auto startEnd = getTimeRangeInUse(quatTable.getIndependentColumn()); TimeSeriesTable_<SimTK::Rotation> orientationsData = OpenSenseUtilities::convertQuaternionsToRotations(quatTable, startEnd); OrientationsReference oRefs(orientationsData); MarkersReference mRefs{}; SimTK::Array_<CoordinateReference> coordinateReferences; // visualize for debugging model.setUseVisualizer(true); SimTK::State& s0 = model.initSystem(); double t0 = s0.getTime(); // create the solver given the input data const double accuracy = 1e-4; InverseKinematicsSolver ikSolver(model, mRefs, oRefs, coordinateReferences); ikSolver.setAccuracy(accuracy); auto& times = oRefs.getTimes(); s0.updTime() = times[0]; ikSolver.assemble(s0); model.getVisualizer().show(s0); model.getVisualizer().getSimbodyVisualizer().setShowSimTime(true); for (auto time : times) { s0.updTime() = time; ikSolver.track(s0); model.getVisualizer().show(s0); // realize to report to get reporter to pull values from model model.realizeReport(s0); } auto report = ikReporter->getTable(); auto eix = orientationsFileName.rfind("_"); if (eix == std::string::npos) { eix = orientationsFileName.rfind("."); } auto stix = orientationsFileName.rfind("/") + 1; IO::makeDir(get_results_directory()); std::string outName = "ik_" + orientationsFileName.substr(stix, eix-stix); std::string outputFile = get_results_directory() + "/" + outName; // Convert to degrees to compare with marker-based IK // but ignore translational coordinates for (size_t i = 0; i < report.getNumColumns(); ++i) { auto it = find( transCoordNames.begin(), transCoordNames.end(), report.getColumnLabel(i) ); if (it == transCoordNames.end()) { // not found = not translational auto repVec = report.updDependentColumnAtIndex(i); repVec *= SimTK::Real(SimTK_RTD); } } report.updTableMetaData().setValueForKey<string>("name", outName); report.updTableMetaData().setValueForKey<size_t>("nRows", report.getNumRows()); // getNumColumns returns the number of dependent columns, but Storage expects time report.updTableMetaData().setValueForKey<size_t>("nColumns", report.getNumColumns()+1); report.updTableMetaData().setValueForKey<string>("inDegrees","yes"); STOFileAdapter_<double>::write(report, outputFile + ".mot"); std::cout << "Wrote IK with IMU tracking results to: '" << outputFile << "'." << std::endl; } // main driver bool InverseKinematicsStudy::run() { bool correct_offsets = false; // Supply offset corrections due to incorrect placement, etc... as X, Y, Z body fixed rotation // Corrections are premultiplied. [C]*[R] std::map<std::string, SimTK::Vec3> imu_corections{ {"back_imu", {0, 0, 90}}, {"pelvis_imu", {0, 0, 90}} }; Model modelWithIMUs(get_model_file_name()); if (correct_offsets) { for (auto it : imu_corections) { auto* offset = modelWithIMUs.findComponent<PhysicalOffsetFrame>(it.first); SimTK::Transform transform = offset->getOffsetTransform(); Vec3 seq = it.second; Rotation correction{ SimTK::BodyOrSpaceType::BodyRotationSequence, double(SimTK_DEGREE_TO_RADIAN*seq[0]), SimTK::XAxis, double(SimTK_DEGREE_TO_RADIAN*seq[1]), SimTK::YAxis, double(SimTK_DEGREE_TO_RADIAN*seq[2]), SimTK::ZAxis }; transform.updR() = correction*transform.R(); modelWithIMUs.updComponent<PhysicalOffsetFrame>(offset->getAbsolutePath()) .setOffsetTransform(transform); } } runInverseKinematicsWithOrientationsFromFile(modelWithIMUs, get_orientations_file_name()); return true; } OpenSim::Array<int> InverseKinematicsStudy::getTimeRangeInUse( const std::vector<double>& times ) const { int nt = static_cast<int>(times.size()); int startIx = 0; int endIx = nt-1; for (int i = 0; i < nt; ++i) { if (times[i] <= get_time_range(0)) { startIx = i; } else { break; } } for (int i = nt - 1; i > 0; --i) { if (times[i] >= get_time_range(1)) { endIx= i; } else { break; } } OpenSim::Array<int> retArray; retArray.append(startIx); retArray.append(endIx); return retArray; } TimeSeriesTable_<SimTK::Vec3> InverseKinematicsStudy::loadMarkersFile(const std::string& markerFile) { auto markers = TRCFileAdapter::read(markerFile); std::cout << markerFile << " loaded " << markers.getNumColumns() << " markers " << " and " << markers.getNumRows() << " rows of data." << std::endl; if (markers.hasTableMetaDataKey("Units")) { std::cout << markerFile << " has Units meta data." << std::endl; auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; if (value.getValue<std::string>() == "mm") { std::cout << "Marker data in mm, converting to m." << std::endl; for (size_t i = 0; i < markers.getNumRows(); ++i) { markers.updRowAtIndex(i) *= 0.001; } markers.updTableMetaData().removeValueForKey("Units"); markers.updTableMetaData().setValueForKey<std::string>("Units", "m"); } } auto& value = markers.getTableMetaData().getValueForKey("Units"); std::cout << markerFile << " Units are " << value.getValue<std::string>() << std::endl; return markers; }<|endoftext|>
<commit_before>/** @file @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "tscore/RbTree.h" namespace ts { namespace detail { /// Equality. /// @note If @a n is @c NULL it is treated as having the color @c BLACK. /// @return @c true if @a c and the color of @a n are the same. inline bool operator==(RBNode *n, RBNode::Color c) { return c == (n ? n->getColor() : RBNode::BLACK); } /// Equality. /// @note If @a n is @c NULL it is treated as having the color @c BLACK. /// @return @c true if @a c and the color of @a n are the same. inline bool operator==(RBNode::Color c, RBNode *n) { return n == c; } RBNode * RBNode::getChild(Direction d) const { return d == RIGHT ? _right : d == LEFT ? _left : nullptr; } RBNode * RBNode::rotate(Direction d) { self *parent = _parent; // Cache because it can change before we use it. Direction child_dir = _parent ? _parent->getChildDirection(this) : NONE; Direction other_dir = this->flip(d); self *child = this; if (d != NONE && this->getChild(other_dir)) { child = this->getChild(other_dir); this->clearChild(other_dir); this->setChild(child->getChild(d), other_dir); child->clearChild(d); child->setChild(this, d); child->structureFixup(); this->structureFixup(); if (parent) { parent->clearChild(child_dir); parent->setChild(child, child_dir); } else { child->_parent = nullptr; } } return child; } RBNode * RBNode::setChild(self *n, Direction d) { if (n) { n->_parent = this; } if (d == RIGHT) { _right = n; } else if (d == LEFT) { _left = n; } return n; } // Returns the root node RBNode * RBNode::rippleStructureFixup() { self *root = this; // last node seen, root node at the end self *p = this; while (p) { p->structureFixup(); root = p; p = root->_parent; } return root; } void RBNode::replaceWith(self *n) { n->_color = _color; if (_parent) { Direction d = _parent->getChildDirection(this); _parent->setChild(nullptr, d); if (_parent != n) { _parent->setChild(n, d); } } else { n->_parent = nullptr; } n->_left = n->_right = nullptr; if (_left && _left != n) { n->setChild(_left, LEFT); } if (_right && _right != n) { n->setChild(_right, RIGHT); } _left = _right = nullptr; } /* Rebalance the tree. This node is the unbalanced node. */ RBNode * RBNode::rebalanceAfterInsert() { self *x(this); // the node with the imbalance while (x && x->_parent == RED) { Direction child_dir = NONE; if (x->_parent->_parent) { child_dir = x->_parent->_parent->getChildDirection(x->_parent); } else { break; } Direction other_dir(flip(child_dir)); self *y = x->_parent->_parent->getChild(other_dir); if (y == RED) { x->_parent->_color = BLACK; y->_color = BLACK; x = x->_parent->_parent; x->_color = RED; } else { if (x->_parent->getChild(other_dir) == x) { x = x->_parent; x->rotate(child_dir); } // Note setting the parent color to BLACK causes the loop to exit. x->_parent->_color = BLACK; x->_parent->_parent->_color = RED; x->_parent->_parent->rotate(other_dir); } } // every node above this one has a subtree structure change, // so notify it. serendipitously, this makes it easy to return // the new root node. self *root = this->rippleStructureFixup(); root->_color = BLACK; return root; } // Returns new root node RBNode * RBNode::remove() { self *root = nullptr; // new root node, returned to caller /* Handle two special cases first. - This is the only node in the tree, return a new root of NIL - This is the root node with only one child, return that child as new root */ if (!_parent && !(_left && _right)) { if (_left) { _left->_parent = nullptr; root = _left; root->_color = BLACK; } else if (_right) { _right->_parent = nullptr; root = _right; root->_color = BLACK; } // else that was the only node, so leave @a root @c NULL. return root; } /* The node to be removed from the tree. If @c this (the target node) has both children, we remove its successor, which cannot have a left child and put that node in place of the target node. Otherwise this node has at most one child, so we can remove it. Note that the successor of a node with a right child is always a right descendant of the node. Therefore, remove_node is an element of the tree rooted at this node. Because of the initial special case checks, we know that remove_node is @b not the root node. */ self *remove_node(_left && _right ? _right->leftmostDescendant() : this); // This is the color of the node physically removed from the tree. // Normally this is the color of @a remove_node Color remove_color = remove_node->_color; // Need to remember the direction from @a remove_node to @a splice_node Direction d(NONE); // The child node that will be promoted to replace the removed node. // The choice of left or right is irrelevant, as remove_node has at // most one child (and splice_node may be NIL if remove_node has no // children). self *splice_node(remove_node->_left ? remove_node->_left : remove_node->_right); if (splice_node) { // @c replace_with copies color so in this case the actual color // lost is that of the splice_node. remove_color = splice_node->_color; remove_node->replaceWith(splice_node); } else { // No children on remove node so we can just clip it off the tree // We update splice_node to maintain the invariant that it is // the node where the physical removal occurred. splice_node = remove_node->_parent; // Keep @a d up to date. d = splice_node->getChildDirection(remove_node); splice_node->setChild(nullptr, d); } // If the node to pull out of the tree isn't this one, // then replace this node in the tree with that removed // node in liu of copying the data over. if (remove_node != this) { // Don't leave @a splice_node referring to a removed node if (splice_node == this) { splice_node = remove_node; } this->replaceWith(remove_node); } root = splice_node->rebalanceAfterRemove(remove_color, d); root->_color = BLACK; return root; } /** * Rebalance tree after a deletion * Called on the spliced in node or its parent, whichever is not NIL. * This modifies the tree structure only if @a c is @c BLACK. */ RBNode * RBNode::rebalanceAfterRemove(Color c, //!< The color of the removed node Direction d //!< Direction of removed node from its parent ) { self *root; if (BLACK == c) { // only rebalance if too much black self *n = this; self *parent = n->_parent; // If @a direction is set, then we need to start at a leaf pseudo-node. // This is why we need @a parent, otherwise we could just use @a n. if (NONE != d) { parent = n; n = nullptr; } while (parent) { // @a n is not the root // If the current node is RED, we can just recolor and be done if (n && n == RED) { n->_color = BLACK; break; } else { // Parameterizing the rebalance logic on the directions. We // write for the left child case and flip directions for the // right child case Direction near(LEFT), far(RIGHT); if ((NONE == d && parent->getChildDirection(n) == RIGHT) || RIGHT == d) { near = RIGHT; far = LEFT; } self *w = parent->getChild(far); // sibling(n) if (w->_color == RED) { w->_color = BLACK; parent->_color = RED; parent->rotate(near); w = parent->getChild(far); } self *wfc = w->getChild(far); if (w->getChild(near) == BLACK && wfc == BLACK) { w->_color = RED; n = parent; parent = n->_parent; d = NONE; // Cancel any leaf node logic } else { if (wfc->_color == BLACK) { w->getChild(near)->_color = BLACK; w->_color = RED; w->rotate(far); w = parent->getChild(far); wfc = w->getChild(far); // w changed, update far child cache. } w->_color = parent->_color; parent->_color = BLACK; wfc->_color = BLACK; parent->rotate(near); break; } } } } root = this->rippleStructureFixup(); return root; } /** Ensure that the local information associated with each node is correct globally This should only be called on debug builds as it breaks any efficiencies we have gained from our tree structure. */ int RBNode::validate() { #if 0 int black_ht = 0; int black_ht1, black_ht2; if (_left) { black_ht1 = _left->validate(); } else black_ht1 = 1; if (black_ht1 > 0 && _right) black_ht2 = _right->validate(); else black_ht2 = 1; if (black_ht1 == black_ht2) { black_ht = black_ht1; if (this->_color == BLACK) ++black_ht; else { // No red-red if (_left == RED) black_ht = 0; else if (_right == RED) black_ht = 0; if (black_ht == 0) std::cout << "Red-red child\n"; } } else { std::cout << "Height mismatch " << black_ht1 << " " << black_ht2 << "\n"; } if (black_ht > 0 && !this->structureValidate()) black_ht = 0; return black_ht; #else return 0; #endif } } // namespace detail } // namespace ts <commit_msg>RBTree - fix potential nullptr dereference<commit_after>/** @file @section license License Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "tscore/RbTree.h" namespace ts { namespace detail { /// Equality. /// @note If @a n is @c NULL it is treated as having the color @c BLACK. /// @return @c true if @a c and the color of @a n are the same. inline bool operator==(RBNode *n, RBNode::Color c) { return c == (n ? n->getColor() : RBNode::BLACK); } /// Equality. /// @note If @a n is @c NULL it is treated as having the color @c BLACK. /// @return @c true if @a c and the color of @a n are the same. inline bool operator==(RBNode::Color c, RBNode *n) { return n == c; } RBNode * RBNode::getChild(Direction d) const { return d == RIGHT ? _right : d == LEFT ? _left : nullptr; } RBNode * RBNode::rotate(Direction d) { self *parent = _parent; // Cache because it can change before we use it. Direction child_dir = _parent ? _parent->getChildDirection(this) : NONE; Direction other_dir = this->flip(d); self *child = this; if (d != NONE && this->getChild(other_dir)) { child = this->getChild(other_dir); this->clearChild(other_dir); this->setChild(child->getChild(d), other_dir); child->clearChild(d); child->setChild(this, d); child->structureFixup(); this->structureFixup(); if (parent) { parent->clearChild(child_dir); parent->setChild(child, child_dir); } else { child->_parent = nullptr; } } return child; } RBNode * RBNode::setChild(self *n, Direction d) { if (n) { n->_parent = this; } if (d == RIGHT) { _right = n; } else if (d == LEFT) { _left = n; } return n; } // Returns the root node RBNode * RBNode::rippleStructureFixup() { self *root = this; // last node seen, root node at the end self *p = this; while (p) { p->structureFixup(); root = p; p = root->_parent; } return root; } void RBNode::replaceWith(self *n) { n->_color = _color; if (_parent) { Direction d = _parent->getChildDirection(this); _parent->setChild(nullptr, d); if (_parent != n) { _parent->setChild(n, d); } } else { n->_parent = nullptr; } n->_left = n->_right = nullptr; if (_left && _left != n) { n->setChild(_left, LEFT); } if (_right && _right != n) { n->setChild(_right, RIGHT); } _left = _right = nullptr; } /* Rebalance the tree. This node is the unbalanced node. */ RBNode * RBNode::rebalanceAfterInsert() { self *x(this); // the node with the imbalance while (x && x->_parent == RED) { Direction child_dir = NONE; if (x->_parent->_parent) { child_dir = x->_parent->_parent->getChildDirection(x->_parent); } else { break; } Direction other_dir(flip(child_dir)); self *y = x->_parent->_parent->getChild(other_dir); if (y == RED) { x->_parent->_color = BLACK; y->_color = BLACK; x = x->_parent->_parent; x->_color = RED; } else { if (x->_parent->getChild(other_dir) == x) { x = x->_parent; x->rotate(child_dir); } // Note setting the parent color to BLACK causes the loop to exit. x->_parent->_color = BLACK; x->_parent->_parent->_color = RED; x->_parent->_parent->rotate(other_dir); } } // every node above this one has a subtree structure change, // so notify it. serendipitously, this makes it easy to return // the new root node. self *root = this->rippleStructureFixup(); root->_color = BLACK; return root; } // Returns new root node RBNode * RBNode::remove() { self *root = nullptr; // new root node, returned to caller /* Handle two special cases first. - This is the only node in the tree, return a new root of NIL - This is the root node with only one child, return that child as new root */ if (!_parent && !(_left && _right)) { if (_left) { _left->_parent = nullptr; root = _left; root->_color = BLACK; } else if (_right) { _right->_parent = nullptr; root = _right; root->_color = BLACK; } // else that was the only node, so leave @a root @c NULL. return root; } /* The node to be removed from the tree. If @c this (the target node) has both children, we remove its successor, which cannot have a left child and put that node in place of the target node. Otherwise this node has at most one child, so we can remove it. Note that the successor of a node with a right child is always a right descendant of the node. Therefore, remove_node is an element of the tree rooted at this node. Because of the initial special case checks, we know that remove_node is @b not the root node. */ self *remove_node(_left && _right ? _right->leftmostDescendant() : this); // This is the color of the node physically removed from the tree. // Normally this is the color of @a remove_node Color remove_color = remove_node->_color; // Need to remember the direction from @a remove_node to @a splice_node Direction d(NONE); // The child node that will be promoted to replace the removed node. // The choice of left or right is irrelevant, as remove_node has at // most one child (and splice_node may be NIL if remove_node has no // children). self *splice_node(remove_node->_left ? remove_node->_left : remove_node->_right); if (splice_node) { // @c replace_with copies color so in this case the actual color // lost is that of the splice_node. remove_color = splice_node->_color; remove_node->replaceWith(splice_node); } else { // No children on remove node so we can just clip it off the tree // We update splice_node to maintain the invariant that it is // the node where the physical removal occurred. splice_node = remove_node->_parent; // Keep @a d up to date. d = splice_node->getChildDirection(remove_node); splice_node->setChild(nullptr, d); } // If the node to pull out of the tree isn't this one, // then replace this node in the tree with that removed // node in liu of copying the data over. if (remove_node != this) { // Don't leave @a splice_node referring to a removed node if (splice_node == this) { splice_node = remove_node; } this->replaceWith(remove_node); } root = splice_node->rebalanceAfterRemove(remove_color, d); root->_color = BLACK; return root; } /** * Rebalance tree after a deletion * Called on the spliced in node or its parent, whichever is not NIL. * This modifies the tree structure only if @a c is @c BLACK. */ RBNode * RBNode::rebalanceAfterRemove(Color c, //!< The color of the removed node Direction d //!< Direction of removed node from its parent ) { self *root; if (BLACK == c) { // only rebalance if too much black self *n = this; self *parent = n->_parent; // If @a direction is set, then we need to start at a leaf pseudo-node. // This is why we need @a parent, otherwise we could just use @a n. if (NONE != d) { parent = n; n = nullptr; } while (parent) { // @a n is not the root // If the current node is RED, we can just recolor and be done if (n && n == RED) { n->_color = BLACK; break; } else { // Parameterizing the rebalance logic on the directions. We // write for the left child case and flip directions for the // right child case Direction near(LEFT), far(RIGHT); if ((NONE == d && parent->getChildDirection(n) == RIGHT) || RIGHT == d) { near = RIGHT; far = LEFT; } self *w = parent->getChild(far); // sibling(n) if (w->_color == RED) { w->_color = BLACK; parent->_color = RED; parent->rotate(near); w = parent->getChild(far); } self *wfc = w->getChild(far); if (w->getChild(near) == BLACK && wfc == BLACK) { w->_color = RED; n = parent; parent = n->_parent; d = NONE; // Cancel any leaf node logic } else { if (wfc == BLACK) { w->getChild(near)->_color = BLACK; w->_color = RED; w->rotate(far); w = parent->getChild(far); wfc = w->getChild(far); // w changed, update far child cache. } w->_color = parent->_color; parent->_color = BLACK; wfc->_color = BLACK; parent->rotate(near); break; } } } } root = this->rippleStructureFixup(); return root; } /** Ensure that the local information associated with each node is correct globally This should only be called on debug builds as it breaks any efficiencies we have gained from our tree structure. */ int RBNode::validate() { #if 0 int black_ht = 0; int black_ht1, black_ht2; if (_left) { black_ht1 = _left->validate(); } else black_ht1 = 1; if (black_ht1 > 0 && _right) black_ht2 = _right->validate(); else black_ht2 = 1; if (black_ht1 == black_ht2) { black_ht = black_ht1; if (this->_color == BLACK) ++black_ht; else { // No red-red if (_left == RED) black_ht = 0; else if (_right == RED) black_ht = 0; if (black_ht == 0) std::cout << "Red-red child\n"; } } else { std::cout << "Height mismatch " << black_ht1 << " " << black_ht2 << "\n"; } if (black_ht > 0 && !this->structureValidate()) black_ht = 0; return black_ht; #else return 0; #endif } } // namespace detail } // namespace ts <|endoftext|>
<commit_before>#ifndef CTHREADRINGBUF #define CTHREADRINGBUF #include<condition_variable> #include<memory> //allocator #include<mutex> #include<queue> #include<utility> //forward, move, move_if_noexcept, pair #include"CAtomic_stack.hpp" #include"../algorithm/algorithm.hpp" //for_each_val namespace nThread { //a fixed-sized and cannot overwrite when buffer is full template<class T> class CThreadRingBuf { public: using allocator_type=std::allocator<T>; using size_type=typename std::allocator<T>::size_type; using value_type=T; private: using pointer=typename std::allocator<T>::pointer; static allocator_type alloc_; const pointer begin_; const size_type size_; std::mutex mut_; std::queue<pointer> queue_; std::condition_variable read_cv_; CAtomic_stack<std::pair<bool,pointer>> stack_; public: explicit CThreadRingBuf(const size_type size) :begin_{alloc_.allocate(size)},size_{size} { nAlgorithm::for_each_val(begin_,begin_+size,[this](const auto p){ stack_.emplace_not_ts(false,p); }); } inline bool empty() const noexcept { return queue_.empty(); } inline size_type available() const noexcept { return static_cast<size_type>(queue_.size()); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety value_type read() { std::unique_lock<std::mutex> lock{mut_}; read_cv_.wait(lock,[this]() noexcept{return available();}); const pointer p{queue_.front()}; //1. if move constructor is noexcept, it is exception safety //2. if move constructor is not noexcept and copy constructor exists, it is exception safety //3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety const auto temp{std::move_if_noexcept(*p)}; queue_.pop(); lock.unlock(); stack_.emplace(true,p); return temp; } inline size_type size() const noexcept { return size_; } //can only be used when your write will not overwrite the data template<class ... Args> void write(Args &&...args) { std::pair<bool,pointer> p{stack_.pop()}; if(p.first) { alloc_.destroy(p.second); p.first=false; } try { alloc_.construct(p.second,std::forward<decltype(args)>(args)...); }catch(...) { stack_.emplace(p); throw ; } std::lock_guard<std::mutex> lock{mut_}; queue_.emplace(p.second); if(queue_.size()==1) read_cv_.notify_all(); } ~CThreadRingBuf() { while(!stack_.empty()) { const std::pair<bool,pointer> p{stack_.pop()}; if(p.first) alloc_.destroy(p.second); } while(available()) { alloc_.destroy(queue_.front()); queue_.pop(); } alloc_.deallocate(begin_,size()); } }; template<class T> typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_; } #endif<commit_msg>not exception safety, add comment<commit_after>#ifndef CTHREADRINGBUF #define CTHREADRINGBUF #include<condition_variable> #include<memory> //allocator #include<mutex> #include<queue> #include<utility> //forward, move, move_if_noexcept, pair #include"CAtomic_stack.hpp" #include"../algorithm/algorithm.hpp" //for_each_val namespace nThread { //a fixed-sized and cannot overwrite when buffer is full template<class T> class CThreadRingBuf { public: using allocator_type=std::allocator<T>; using size_type=typename std::allocator<T>::size_type; using value_type=T; private: using pointer=typename std::allocator<T>::pointer; static allocator_type alloc_; const pointer begin_; const size_type size_; std::mutex mut_; std::queue<pointer> queue_; std::condition_variable read_cv_; CAtomic_stack<std::pair<bool,pointer>> stack_; public: explicit CThreadRingBuf(const size_type size) :begin_{alloc_.allocate(size)},size_{size} { nAlgorithm::for_each_val(begin_,begin_+size,[this](const auto p){ stack_.emplace_not_ts(false,p); }); } inline bool empty() const noexcept { return queue_.empty(); } inline size_type available() const noexcept { return static_cast<size_type>(queue_.size()); } //if constructor or assignment operator you use here is not noexcept, it may not be exception safety value_type read() { std::unique_lock<std::mutex> lock{mut_}; read_cv_.wait(lock,[this]() noexcept{return available();}); const pointer p{queue_.front()}; //1. if move constructor is noexcept, it is exception safety //2. if move constructor is not noexcept and copy constructor exists, it is exception safety //3. if move constructor is not noexcept and copy constructor does not exist, it may not be exception safety const auto temp{std::move_if_noexcept(*p)}; queue_.pop(); lock.unlock(); stack_.emplace(true,p); return temp; } inline size_type size() const noexcept { return size_; } //can only be used when your write will not overwrite the data template<class ... Args> void write(Args &&...args) { std::pair<bool,pointer> p{stack_.pop()}; if(p.first) { alloc_.destroy(p.second); p.first=false; } try { alloc_.construct(p.second,std::forward<decltype(args)>(args)...); }catch(...) { stack_.emplace(p); //what will happen if it throws bad_alloc? throw ; } std::lock_guard<std::mutex> lock{mut_}; queue_.emplace(p.second); if(queue_.size()==1) read_cv_.notify_all(); } ~CThreadRingBuf() { while(!stack_.empty()) { const std::pair<bool,pointer> p{stack_.pop()}; if(p.first) alloc_.destroy(p.second); } while(available()) { alloc_.destroy(queue_.front()); queue_.pop(); } alloc_.deallocate(begin_,size()); } }; template<class T> typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_; } #endif<|endoftext|>
<commit_before>/* rdrwdsk.cpp class RedrawDesktop */ /* Revision: 1.09 07.12.2001 $ */ /* Modify: 07.12.2001 SVS + RedrawDesktop . - - , Opt.ShowKeyBar Opt.ShowMenuBar , " " - Alt-F9. 12.11.2001 SVS ! 30.05.2001 OT - / 21.05.2001 OT ! " " 11.05.2001 OT ! Background 06.05.2001 DJ ! #include 29.04.2001 + NWZ 28.02.2001 IS ! "CtrlObject->CmdLine." -> "CtrlObject->CmdLine->" 25.06.2000 SVS ! Master Copy ! */ #include "headers.hpp" #pragma hdrstop #include "manager.hpp" #include "keys.hpp" #include "rdrwdsk.hpp" #include "global.hpp" #include "filepanels.hpp" #include "panel.hpp" #include "cmdline.hpp" #include "ctrlobj.hpp" RedrawDesktop::RedrawDesktop(BOOL IsHidden) { CtrlObject->CmdLine->ShowBackground(); CtrlObject->CmdLine->Show(); LeftVisible=CtrlObject->Cp()->LeftPanel->IsVisible(); RightVisible=CtrlObject->Cp()->RightPanel->IsVisible(); KeyBarVisible=Opt.ShowKeyBar;//CtrlObject->MainKeyBar->IsVisible(); TopMenuBarVisible=Opt.ShowMenuBar;//CtrlObject->TopMenuBar->IsVisible(); if(IsHidden) { CtrlObject->Cp()->LeftPanel->CloseFile(); CtrlObject->Cp()->RightPanel->CloseFile(); CtrlObject->Cp()->LeftPanel->Hide(); CtrlObject->Cp()->RightPanel->Hide(); CtrlObject->MainKeyBar->Hide(); CtrlObject->TopMenuBar->Hide(); Opt.ShowKeyBar=0; Opt.ShowMenuBar=0; } } RedrawDesktop::~RedrawDesktop() { Opt.ShowKeyBar=KeyBarVisible; Opt.ShowMenuBar=TopMenuBarVisible; CtrlObject->CmdLine->SaveBackground(); CtrlObject->CmdLine->Show(); if (KeyBarVisible) CtrlObject->MainKeyBar->Show(); if (TopMenuBarVisible) CtrlObject->TopMenuBar->Show(); int RightType=CtrlObject->Cp()->RightPanel->GetType(); if (RightVisible && RightType!=QVIEW_PANEL) //CtrlObject->Cp()->RightPanel->Show(); CtrlObject->Cp()->RightPanel->SetVisible(TRUE); if (LeftVisible) // CtrlObject->Cp()->LeftPanel->Show(); CtrlObject->Cp()->LeftPanel->SetVisible(TRUE); if (RightVisible && RightType==QVIEW_PANEL) // CtrlObject->Cp()->RightPanel->Show(); CtrlObject->Cp()->RightPanel->SetVisible(TRUE); // ! // ... FrameManager->ProcessKey(KEY_CONSOLE_BUFFER_RESIZE); } <commit_msg>FAR patch 01271.Redraw Дата : 04.03.2002 Сделал : Valentin Skirdin Описание : Лечим багу с прорисовкой... Измененные файлы : rdrwdsk.cpp Новые файлы : Удаленные файлы : Состав : 01271.Redraw.txt rdrwdsk.cpp.1271.diff Основан на патче : 1270 Дополнение :<commit_after>/* rdrwdsk.cpp class RedrawDesktop */ /* Revision: 1.10 04.03.2002 $ */ /* Modify: 04.03.2002 SVS ! ... 07.12.2001 SVS + RedrawDesktop . - - , Opt.ShowKeyBar Opt.ShowMenuBar , " " - Alt-F9. 12.11.2001 SVS ! 30.05.2001 OT - / 21.05.2001 OT ! " " 11.05.2001 OT ! Background 06.05.2001 DJ ! #include 29.04.2001 + NWZ 28.02.2001 IS ! "CtrlObject->CmdLine." -> "CtrlObject->CmdLine->" 25.06.2000 SVS ! Master Copy ! */ #include "headers.hpp" #pragma hdrstop #include "manager.hpp" #include "keys.hpp" #include "rdrwdsk.hpp" #include "global.hpp" #include "filepanels.hpp" #include "panel.hpp" #include "cmdline.hpp" #include "ctrlobj.hpp" RedrawDesktop::RedrawDesktop(BOOL IsHidden) { CtrlObject->CmdLine->ShowBackground(); CtrlObject->CmdLine->Show(); LeftVisible=CtrlObject->Cp()->LeftPanel->IsVisible(); RightVisible=CtrlObject->Cp()->RightPanel->IsVisible(); KeyBarVisible=Opt.ShowKeyBar;//CtrlObject->MainKeyBar->IsVisible(); TopMenuBarVisible=Opt.ShowMenuBar;//CtrlObject->TopMenuBar->IsVisible(); if(IsHidden) { CtrlObject->Cp()->LeftPanel->CloseFile(); CtrlObject->Cp()->RightPanel->CloseFile(); // ! ! // , ! if(CtrlObject->Cp()->ActivePanel == CtrlObject->Cp()->LeftPanel) { CtrlObject->Cp()->LeftPanel->Hide(); CtrlObject->Cp()->RightPanel->Hide(); } else { CtrlObject->Cp()->RightPanel->Hide(); CtrlObject->Cp()->LeftPanel->Hide(); } CtrlObject->MainKeyBar->Hide(); CtrlObject->TopMenuBar->Hide(); Opt.ShowKeyBar=0; Opt.ShowMenuBar=0; } } RedrawDesktop::~RedrawDesktop() { Opt.ShowKeyBar=KeyBarVisible; Opt.ShowMenuBar=TopMenuBarVisible; CtrlObject->CmdLine->SaveBackground(); CtrlObject->CmdLine->Show(); if (KeyBarVisible) CtrlObject->MainKeyBar->Show(); if (TopMenuBarVisible) CtrlObject->TopMenuBar->Show(); int RightType=CtrlObject->Cp()->RightPanel->GetType(); if (RightVisible && RightType!=QVIEW_PANEL) //CtrlObject->Cp()->RightPanel->Show(); CtrlObject->Cp()->RightPanel->SetVisible(TRUE); if (LeftVisible) // CtrlObject->Cp()->LeftPanel->Show(); CtrlObject->Cp()->LeftPanel->SetVisible(TRUE); if (RightVisible && RightType==QVIEW_PANEL) // CtrlObject->Cp()->RightPanel->Show(); CtrlObject->Cp()->RightPanel->SetVisible(TRUE); // ! // ... FrameManager->ProcessKey(KEY_CONSOLE_BUFFER_RESIZE); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file collision_checker.cpp **/ #include "modules/planning/constraint_checker/collision_checker.h" #include <array> #include <cmath> #include <utility> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/log.h" #include "modules/common/math/path_matcher.h" #include "modules/planning/common/planning_gflags.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; CollisionChecker::CollisionChecker( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<PathPoint>& discretized_reference_line) { BuildPredictedEnvironment(obstacles, ego_vehicle_s, ego_vehicle_d, discretized_reference_line); } bool CollisionChecker::InCollision( const DiscretizedTrajectory& discretized_trajectory) { CHECK_LE(discretized_trajectory.NumOfPoints(), predicted_bounding_rectangles_.size()); const auto& vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double ego_length = vehicle_config.vehicle_param().length(); double ego_width = vehicle_config.vehicle_param().width(); for (std::size_t i = 0; i < discretized_trajectory.NumOfPoints(); ++i) { const auto& trajectory_point = discretized_trajectory.TrajectoryPointAt(i); Box2d ego_box( {trajectory_point.path_point().x(), trajectory_point.path_point().y()}, trajectory_point.path_point().theta(), ego_length, ego_width); for (const auto& obstacle_box : predicted_bounding_rectangles_[i]) { if (ego_box.HasOverlap(obstacle_box)) { return true; } } } return false; } void CollisionChecker::BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<PathPoint>& discretized_reference_line) { CHECK(predicted_bounding_rectangles_.empty()); // If the ego vehicle is in lane, // then, ignore all obstacles from the same lane. bool ego_vehicle_in_lane = IsEgoVehicleInLane(ego_vehicle_d); std::vector<const Obstacle*> obstacles_considered; for (const Obstacle* obstacle : obstacles) { if (obstacle->IsVirtual()) { continue; } if (ego_vehicle_in_lane && ShouldIgnore(obstacle, ego_vehicle_s, discretized_reference_line)) { continue; } obstacles_considered.push_back(obstacle); } double relative_time = 0.0; while (relative_time < FLAGS_trajectory_time_length) { std::vector<Box2d> predicted_env; for (const Obstacle* obstacle : obstacles_considered) { // If an obstacle has no trajectory, it is considered as static. // Obstacle::GetPointAtTime has handled this case. TrajectoryPoint point = obstacle->GetPointAtTime(relative_time); Box2d box = obstacle->GetBoundingBox(point); predicted_env.push_back(std::move(box)); } predicted_bounding_rectangles_.push_back(std::move(predicted_env)); relative_time += FLAGS_trajectory_time_resolution; } } bool CollisionChecker::IsEgoVehicleInLane(const double ego_vehicle_d) { return std::abs(ego_vehicle_d) < FLAGS_default_reference_line_width * 0.5; } bool CollisionChecker::ShouldIgnore( const Obstacle* obstacle, const double ego_vehicle_s, const std::vector<PathPoint>& discretized_reference_line) { double half_lane_width = FLAGS_default_reference_line_width * 0.5; TrajectoryPoint point = obstacle->GetPointAtTime(0.0); auto obstacle_reference_line_position = PathMatcher::GetPathFrenetCoordinate( discretized_reference_line, point.path_point().x(), point.path_point().y()); if (obstacle_reference_line_position.first < ego_vehicle_s && std::abs(obstacle_reference_line_position.second) < half_lane_width) { ADEBUG << "Ignore obstacle [" << obstacle->Id() << "]"; return true; } return false; } } // namespace planning } // namespace apollo <commit_msg>Planning: adjust ego vehicle bounding box<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file collision_checker.cpp **/ #include "modules/planning/constraint_checker/collision_checker.h" #include <array> #include <cmath> #include <utility> #include "modules/common/configs/vehicle_config_helper.h" #include "modules/common/log.h" #include "modules/common/math/path_matcher.h" #include "modules/common/math/vec2d.h" #include "modules/planning/common/planning_gflags.h" #include "modules/prediction/proto/prediction_obstacle.pb.h" namespace apollo { namespace planning { using apollo::common::PathPoint; using apollo::common::TrajectoryPoint; using apollo::common::math::Box2d; using apollo::common::math::Vec2d; CollisionChecker::CollisionChecker( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<PathPoint>& discretized_reference_line) { BuildPredictedEnvironment(obstacles, ego_vehicle_s, ego_vehicle_d, discretized_reference_line); } bool CollisionChecker::InCollision( const DiscretizedTrajectory& discretized_trajectory) { CHECK_LE(discretized_trajectory.NumOfPoints(), predicted_bounding_rectangles_.size()); const auto& vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double ego_length = vehicle_config.vehicle_param().length(); double ego_width = vehicle_config.vehicle_param().width(); for (std::size_t i = 0; i < discretized_trajectory.NumOfPoints(); ++i) { const auto& trajectory_point = discretized_trajectory.TrajectoryPointAt(i); double ego_theta = trajectory_point.path_point().theta(); Box2d ego_box( {trajectory_point.path_point().x(), trajectory_point.path_point().y()}, ego_theta, ego_length, ego_width); double shift_distance = ego_length / 2.0 - vehicle_config.vehicle_param().back_edge_to_center(); Vec2d shift_vec{shift_distance * std::cos(ego_theta), shift_distance * std::sin(ego_theta)}; ego_box.Shift(shift_vec); for (const auto& obstacle_box : predicted_bounding_rectangles_[i]) { if (ego_box.HasOverlap(obstacle_box)) { return true; } } } return false; } void CollisionChecker::BuildPredictedEnvironment( const std::vector<const Obstacle*>& obstacles, const double ego_vehicle_s, const double ego_vehicle_d, const std::vector<PathPoint>& discretized_reference_line) { CHECK(predicted_bounding_rectangles_.empty()); // If the ego vehicle is in lane, // then, ignore all obstacles from the same lane. bool ego_vehicle_in_lane = IsEgoVehicleInLane(ego_vehicle_d); std::vector<const Obstacle*> obstacles_considered; for (const Obstacle* obstacle : obstacles) { if (obstacle->IsVirtual()) { continue; } if (ego_vehicle_in_lane && ShouldIgnore(obstacle, ego_vehicle_s, discretized_reference_line)) { continue; } obstacles_considered.push_back(obstacle); } double relative_time = 0.0; while (relative_time < FLAGS_trajectory_time_length) { std::vector<Box2d> predicted_env; for (const Obstacle* obstacle : obstacles_considered) { // If an obstacle has no trajectory, it is considered as static. // Obstacle::GetPointAtTime has handled this case. TrajectoryPoint point = obstacle->GetPointAtTime(relative_time); Box2d box = obstacle->GetBoundingBox(point); predicted_env.push_back(std::move(box)); } predicted_bounding_rectangles_.push_back(std::move(predicted_env)); relative_time += FLAGS_trajectory_time_resolution; } } bool CollisionChecker::IsEgoVehicleInLane(const double ego_vehicle_d) { return std::abs(ego_vehicle_d) < FLAGS_default_reference_line_width * 0.5; } bool CollisionChecker::ShouldIgnore( const Obstacle* obstacle, const double ego_vehicle_s, const std::vector<PathPoint>& discretized_reference_line) { double half_lane_width = FLAGS_default_reference_line_width * 0.5; TrajectoryPoint point = obstacle->GetPointAtTime(0.0); auto obstacle_reference_line_position = PathMatcher::GetPathFrenetCoordinate( discretized_reference_line, point.path_point().x(), point.path_point().y()); if (obstacle_reference_line_position.first < ego_vehicle_s && std::abs(obstacle_reference_line_position.second) < half_lane_width) { ADEBUG << "Ignore obstacle [" << obstacle->Id() << "]"; return true; } return false; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before><commit_msg>coverity#735554 Dead default in switch<commit_after><|endoftext|>
<commit_before>#ifndef CTHREADRINGBUF #define CTHREADRINGBUF #include<atomic> #include<memory> //allocator #include<vector> #include<utility> //forward, move #include"CSemaphore.hpp" #include"../algorithm/algorithm.hpp" //for_each_val namespace nThread { //a fixed-sized and cannot overwrite when buffer is full //T must meet the requirements of MoveAssignable and MoveConstructible template<class T> class CThreadRingBuf { public: using allocator_type=std::allocator<T>; using size_type=typename std::allocator<T>::size_type; using value_type=T; private: using pointer=typename std::allocator<T>::pointer; static allocator_type alloc_; const pointer begin_; std::vector<std::atomic<bool>> complete_; std::atomic<size_type> read_subscript_; CSemaphore sema_; size_type size_; std::atomic<size_type> use_construct_; std::atomic<size_type> write_subscript_; //can only be used when your write will not overwrite the data template<class TFwdRef> void write_(TFwdRef &&val) { sema_.signal(); const auto write{write_subscript_++}; if(write<size()&&use_construct_++<size()) alloc_.construct(begin_+write,std::forward<TFwdRef>(val)); else begin_[write%size()]=std::forward<TFwdRef>(val); complete_[write%size()].store(true,std::memory_order_release); } public: explicit CThreadRingBuf(const size_type size) :begin_{alloc_.allocate(size)},complete_(size),size_{size},read_subscript_{0},use_construct_{0},write_subscript_{0}{} inline size_type available() const noexcept { return static_cast<size_type>(sema_.count()); } value_type read() { sema_.wait(); const auto read{(read_subscript_++)%size()}; while(!complete_[read].load(std::memory_order_acquire)) ; complete_[read]=false; return std::move(begin_[read]); } inline size_type size() const noexcept { return size_; } inline void write(const T &val) { write_(val); } inline void write(T &&val) { write_(std::move(val)); } ~CThreadRingBuf() { nAlgorithm::for_each_val(begin_,begin_+size(),[&](const auto p){alloc_.destroy(p);}); alloc_.deallocate(begin_,size()); } }; template<class T> typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_; } #endif<commit_msg>use default constructor of atomic<commit_after>#ifndef CTHREADRINGBUF #define CTHREADRINGBUF #include<atomic> #include<memory> //allocator #include<vector> #include<utility> //forward, move #include"CSemaphore.hpp" #include"../algorithm/algorithm.hpp" //for_each_val namespace nThread { //a fixed-sized and cannot overwrite when buffer is full //T must meet the requirements of MoveAssignable and MoveConstructible template<class T> class CThreadRingBuf { public: using allocator_type=std::allocator<T>; using size_type=typename std::allocator<T>::size_type; using value_type=T; private: using pointer=typename std::allocator<T>::pointer; static allocator_type alloc_; const pointer begin_; std::vector<std::atomic<bool>> complete_; std::atomic<size_type> read_subscript_; CSemaphore sema_; size_type size_; std::atomic<size_type> use_construct_; std::atomic<size_type> write_subscript_; //can only be used when your write will not overwrite the data template<class TFwdRef> void write_(TFwdRef &&val) { sema_.signal(); const auto write{write_subscript_++}; if(write<size()&&use_construct_++<size()) alloc_.construct(begin_+write,std::forward<TFwdRef>(val)); else begin_[write%size()]=std::forward<TFwdRef>(val); complete_[write%size()].store(true,std::memory_order_release); } public: explicit CThreadRingBuf(const size_type size) :begin_{alloc_.allocate(size)},complete_(size),size_{size}{} inline size_type available() const noexcept { return static_cast<size_type>(sema_.count()); } value_type read() { sema_.wait(); const auto read{(read_subscript_++)%size()}; while(!complete_[read].load(std::memory_order_acquire)) ; complete_[read]=false; return std::move(begin_[read]); } inline size_type size() const noexcept { return size_; } inline void write(const T &val) { write_(val); } inline void write(T &&val) { write_(std::move(val)); } ~CThreadRingBuf() { nAlgorithm::for_each_val(begin_,begin_+size(),[&](const auto p){alloc_.destroy(p);}); alloc_.deallocate(begin_,size()); } }; template<class T> typename CThreadRingBuf<T>::allocator_type CThreadRingBuf<T>::alloc_; } #endif<|endoftext|>
<commit_before>#include "gtest/gtest.h" #include <yarp/sig/all.h> #include "RdImageManager.hpp" #include "RdMockupImageManager.hpp" #include "RdMockupImageEventListener.hpp" #include "RdMentalMap.hpp" #include "RdProcessorImageEventListener.hpp" using namespace rd; //-- Class for the setup of each test //-------------------------------------------------------------------------------------- class RdProcessorImageEventListenerTest : public testing::Test { public: virtual void SetUp() { RdMockupImageManager::RegisterManager(); imageManager = RdImageManager::getImageManager(RdMockupImageManager::id); imageManager->addImageEventListener(&processor); mentalMap = RdMentalMap::getMentalMap(); //-- Load test image yarp::sig::file::read(test_image, image_filename); } virtual void TearDown() { RdImageManager::destroyImageManager(); imageManager = NULL; RdMentalMap::destroyMentalMap(); mentalMap = NULL; } static const std::string image_filename; protected: RdImageManager * imageManager; RdMentalMap * mentalMap; RdProcessorImageEventListener processor; RdImage test_image; }; const std::string RdProcessorImageEventListenerTest::image_filename = "../../share/images/test_target.ppm"; TEST_F(RdProcessorImageEventListenerTest, TargetDetectionWorks) { } <commit_msg>Complete test for testRdProcessorImageEventListener<commit_after>#include "gtest/gtest.h" #include <yarp/sig/all.h> #include <yarp/os/Time.h> #include "RdImageManager.hpp" #include "RdMockupImageManager.hpp" #include "RdMockupImageEventListener.hpp" #include "RdMentalMap.hpp" #include "RdProcessorImageEventListener.hpp" using namespace rd; //-- Class for the setup of each test //-------------------------------------------------------------------------------------- class RdProcessorImageEventListenerTest : public testing::Test { public: virtual void SetUp() { RdMockupImageManager::RegisterManager(); imageManager = RdImageManager::getImageManager(RdMockupImageManager::id); ASSERT_NE((RdImageManager*)NULL, imageManager); imageManager->addImageEventListener(&processor); mentalMap = RdMentalMap::getMentalMap(); ASSERT_NE((RdMentalMap*)NULL, mentalMap); //-- Load test image yarp::sig::file::read(test_image, image_filename); ASSERT_NE(0, test_image.width()); ASSERT_NE(0, test_image.height()); } virtual void TearDown() { RdImageManager::destroyImageManager(); imageManager = NULL; RdMentalMap::destroyMentalMap(); mentalMap = NULL; } static const std::string image_filename; protected: RdImageManager * imageManager; RdMentalMap * mentalMap; RdProcessorImageEventListener processor; RdImage test_image; }; const std::string RdProcessorImageEventListenerTest::image_filename = "../../share/images/test_target.ppm"; void compare_targets(RdTarget target1, RdTarget target2) { ASSERT_EQ(target1.getPlayerId(), target2.getPlayerId()); ASSERT_NEAR(target1.getPos().x, target2.getPos().x, 10); ASSERT_NEAR(target1.getPos().y, target2.getPos().y, 10); ASSERT_NEAR(target1.getDimensions().x, target2.getDimensions().x, 10); ASSERT_NEAR(target1.getDimensions().y, target2.getDimensions().y, 10); } TEST_F(RdProcessorImageEventListenerTest, TargetDetectionWorks) { //-- Expected targets: RdTarget target1(1, RdVector2d(200, 200), RdVector2d(220,220)); RdTarget target2(2, RdVector2d(500, 100), RdVector2d(150, 150)); //-- Send image to image manager ASSERT_TRUE(imageManager->start()); ASSERT_TRUE(((RdMockupImageManager *)imageManager)->receiveImage(test_image)); yarp::os::Time::delay(0.5); //-- Check detected targets: std::vector<RdTarget> targets_detected = RdProcessorImageEventListenerTest::mentalMap->getTargets(); ASSERT_EQ(2, targets_detected.size()); if (targets_detected[0].getPlayerId() == target1.getPlayerId()) { compare_targets(target1, targets_detected[0]); compare_targets(target2, targets_detected[1]); } else { compare_targets(target1, targets_detected[1]); compare_targets(target2, targets_detected[0]); } } <|endoftext|>
<commit_before>/*----------------------------------------------------------------------+ | | | Copyright (C) 2010 Nokia Corporation. | | | | Author: Ilya Dogolazky <[email protected]> | | | | This file is part of Iodata | | | | Iodata is free software; you can redistribute it and/or modify | | it under the terms of the GNU Lesser General Public License | | version 2.1 as published by the Free Software Foundation. | | | | Iodata is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Lesser General Public License for more details. | | | | You should have received a copy of the GNU Lesser General Public | | License along with Iodata. If not, see http://www.gnu.org/licenses/ | | | +----------------------------------------------------------------------*/ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <vector> #include <string> #include <sstream> using namespace std ; #include <qmlog> #include <iodata/iodata> #include <iodata/validator> #include <iodata/storage> using namespace iodata ; storage::storage() { data_source = -1 ; type_validator = NULL ; validator_owned = false ; } storage::~storage() { if (validator_owned and type_validator) delete type_validator ; } void storage::set_primary_path(const string &file) { log_assert(path.size()==0, "primary path '%s' already defined", path[0].c_str()) ; path.push_back(file) ; } void storage::set_secondary_path(const string &file) { log_assert(path.size()<2, "secondary path '%s' already defined", path[1].c_str()) ; log_assert(path.size()>0, "can't set secondary path, because primary path not set") ; log_assert(path.size()==1) ; path.push_back(file) ; } void storage::set_validator(const string &path, const string &name) { log_assert(!name.empty()) ; log_assert(type_validator==NULL) ; type_name = name ; type_validator = validator::from_file(path.c_str()) ; validator_owned = true ; } void storage::set_validator(validator *v, const string &name) { log_assert(!name.empty()) ; log_assert(type_validator==NULL) ; type_name = name ; type_validator = v ; } record *storage::load() { log_assert(path.size()>0, "no path defined, where do you want to read from?") ; const char *path_0 = path[0].c_str() ; for(unsigned i=0; i<path.size(); ++i) { // reading data file const char *path_i = path[i].c_str() ; int res = read_file_to_string(path_i, data_cached) ; if(res<0) { log_warning("can't read '%s': %m", path_i) ; continue ; } // read success // parsing iodata structure string message ; record *tree = parse_string_to_tree(message) ; if(tree==NULL) { log_warning("can't parse data in '%s': %s", path_i, message.c_str()) ; continue ; } // parse success // validate the data if(type_validator) { try { log_debug() ; type_validator->check_record_after_read(tree, type_name) ; log_debug() ; } catch(const iodata::exception &e) { log_debug() ; log_warning("data in '%s' isn't valid: %s", path_i, e.info().c_str()) ; delete tree ; continue ; } } // data is validated, empty fields are set to default values data_source = i ; log_info("read data from '%s'", path_i) ; return tree ; } // no correct data on the disk data_source = -1 ; data_cached = "" ; if(type_validator==NULL) { log_error("no type information for data in '%s' known, give up", path_0) ; return NULL ; } // let's try to use default values record *tree = new record ; try { type_validator->check_record_after_read(tree, type_name) ; } catch(iodata::exception &e) { log_error("no default values for data in '%s' known: %s; give up", path_0, e.info().c_str()) ; delete tree ; return NULL ; } // success: using default values log_info("using default values for data in '%s'", path_0) ; data_cached = ".\n" ; // empty record return tree ; } // this function can throw validator::exception // if (and only if) the data tree contains rubbish int storage::save(record *rec) { log_assert(path.size()>0, "no path defined, where do you want to write to?") ; const char *path_0 = path[0].c_str() ; // check record and reduce default values if(type_validator) type_validator->check_record_before_write(rec, type_name) ; // serialize the record ostringstream os ; output out(os) ; out.output_record(rec) ; string new_data = os.str() ; if(data_cached==new_data) { log_debug("do not write the same data to '%s' again", path[data_source].c_str()) ; return data_source ; } // *) no valid data on the disk or // *) no secondary file or // *) data read from the secondary // => just write to the primary file bool no_data_on_disk = data_source<0 ; bool no_secondary = path.size()==1 ; bool data_in_secondary = data_source == 1 ; if(no_data_on_disk || no_secondary || data_in_secondary) { int res = write_string(0, new_data) ; if(res<0) { log_critical("can't write data to '%s': %m", path_0) ; if(data_source==0) // data destroyed by write attempt { data_source = -1 ; data_cached = "" ; } } else { log_info("data written to '%s'", path_0) ; data_source = 0 ; data_cached = new_data ; } return data_source ; } log_assert(0<=data_source) ; // old data is on disk log_assert(path.size()>1) ; // secondary path is given log_assert(data_source==0) ; // old data is in the primary file const char *path_1 = path[1].c_str() ; int index = 0 ; // we want to save the data to primary file if(move_files(0,1) < 0) { log_critical("can't rename files: '%s'->'%s': %m", path_0, path_1) ; index = 1 ; // let's write to the secondary then } const char *path_i = index==0 ? path_0 : path_1 ; int res = write_string(index, new_data) ; if(res<0) { log_critical("can't write data to '%s': %m", path_i) ; data_source = -1 ; data_cached = "" ; } else { log_info("data written to '%s'", path_i) ; // we have to get rid of primary file, if written to secondary if(index > 0 && unlink(path_0)<0) { // that's the mega paranoia! log_critical("written data will be lost, because can't remove '%s': %m", path_0) ; data_source = -1 ; data_cached = "" ; } else { if(index > 0) // it means we can't move primary->secondary { // but maybe it's possible to move it back ? if(move_files(1, 0) < 0) log_warning("can't move secondary to primary '%s' (%m), but never mind: data is saved", path_0) ; else index = 0 ; // yahoo, it's a miracle !! } // we're happy data_source = index ; data_cached = new_data ; } } return data_source ; } bool storage::fix_files(bool force) { if(data_cached.empty()) return false ; log_assert(path.size()>0, "primary storage file not defined") ; const char *path_0 = path[0].c_str() ; if(!force && data_source==0) // may be it's enough to read { string in_file ; if(read_file_to_string(path_0, in_file)==0 && data_cached==in_file) return true ; log_info("primary file '%s' doesn't match cached data", path_0) ; } // now we have to write cached data to primary file if(force && data_source==0 && path.size()>1) // primary file should be backed up { if(move_files(0,1) < 0) return false ; } // now just write the cached data to primary if(write_string(0, data_cached)<0) return false ; data_source = 0 ; #if 0 // now we do not need the secondary file // so we are trying to remove it // but if we can't, it doesn't matter: // a warning is enough if(path.size() > 1) { const char *path_1 = path[1].c_str() ; if(unlink(path_1) < 0) log_warning("can't unlink the secondary file '%s': %m", path_1) ; } commented out this piece, because as a matter of fact we do need the secondary: it is a kind of place holder for the future 'disk full' situation #endif return true ; } int storage::move_files(int from, int to) { const char *path_from = path[from].c_str() ; const char *path_to = path[to].c_str() ; return rename(path_from, path_to) ; } int storage::write_string(int index, const string &data) { const char *file = path[index].c_str() ; return write_string_to_file(file, data) ; } int storage::write_string_to_file(const char *file, const string &data) { int fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, 0666) ; if(fd < 0) return -1 ; int size = data.length(), done = 0 ; const char *start = data.c_str() ; while(done < size) { ssize_t bytes = write (fd, start + done, size - done) ; if(bytes>0) done += bytes ; else if(bytes==0 || errno!=EINTR) // try again only if interrupted break ; // write(2) man page says: "zero indicates nothing was written" // So we're not trying to write again (probably in an infinite loop) // But it's still not clear, what kind of condition indicates bytes=0 :-( } if(done < size || fsync(fd) < 0 || close(fd) < 0) // that's it { int errno_copy = errno ; close(fd) ; // don't care about result, even if it's already closed errno = errno_copy ; return -1 ; } return 0 ; } int storage::read_file_to_string(const char *file, string &input) { int fd = open(file, O_RDONLY) ; if(fd < 0) return -1 ; struct stat st ; if(fstat(fd, &st) < 0) { int errno_copy = errno ; close(fd) ; errno = errno_copy ; return -1 ; } int size = st.st_size ; if(size<=0) { close(fd) ; errno = EIO ; // TODO find a better one? return -1 ; } int done = 0 ; char *buffer = new char[size+1] ; log_assert(buffer) ; while(done < size) { ssize_t bytes = read (fd, buffer + done, size - done) ; if(bytes>0) done += bytes ; else if(bytes==0 || errno!=EINTR) // EOF or error (not interrupt) break ; else if(lseek(fd, done, SEEK_SET)!=done) // fix the position, if interrupted break ; // read(2) man page is self contratictory: // on the one side bytes=0 means EOF: "zero indicates end of file" // on the other side it states "It is not an error if this number is // smaller than the number of bytes requested; this may happen for example // [...] because read() was interrupted by a signal". As zero is smaller // than the number of bytes requested, it may indicate an interrupt then. // As we can't distinguish between "zero because of EOF" and "zero because // of interrupt" let's assume the first to be paranoid (if someone has // truncated our file during we're reading it and we assume interrupt, we // would remain in an infinite loop). // In the case of an interrupt (bytes<0 and errno=EINTR) "it is left // unspecified whether the file position [...] changes". That's the // reason for the weird lseek() call. } int errno_copy = errno ; close(fd) ; // failed? who cares, we got data already if(done < size) { delete[] buffer ; errno = errno_copy ; return -1 ; } buffer[size] = '\0' ; if(strlen(buffer)!=(unsigned)size) // some '\0' inside ? { delete[] buffer ; errno = EILSEQ ; return -1 ; } input = buffer ; delete[] buffer ; return 0 ; } record * storage::parse_string_to_tree(std::string &message) { record *rec = NULL ; try { istringstream in(data_cached) ; parser p(in) ; p.parse() ; rec = p.detach() ; } catch(iodata::exception &e) { message = e.info() ; return NULL ; } return rec ; } <commit_msg>reading empty file<commit_after>/*----------------------------------------------------------------------+ | | | Copyright (C) 2010 Nokia Corporation. | | | | Author: Ilya Dogolazky <[email protected]> | | | | This file is part of Iodata | | | | Iodata is free software; you can redistribute it and/or modify | | it under the terms of the GNU Lesser General Public License | | version 2.1 as published by the Free Software Foundation. | | | | Iodata is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Lesser General Public License for more details. | | | | You should have received a copy of the GNU Lesser General Public | | License along with Iodata. If not, see http://www.gnu.org/licenses/ | | | +----------------------------------------------------------------------*/ #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <vector> #include <string> #include <sstream> using namespace std ; #include <qmlog> #include <iodata/iodata> #include <iodata/validator> #include <iodata/storage> using namespace iodata ; storage::storage() { data_source = -1 ; type_validator = NULL ; validator_owned = false ; } storage::~storage() { if (validator_owned and type_validator) delete type_validator ; } void storage::set_primary_path(const string &file) { log_assert(path.size()==0, "primary path '%s' already defined", path[0].c_str()) ; path.push_back(file) ; } void storage::set_secondary_path(const string &file) { log_assert(path.size()<2, "secondary path '%s' already defined", path[1].c_str()) ; log_assert(path.size()>0, "can't set secondary path, because primary path not set") ; log_assert(path.size()==1) ; path.push_back(file) ; } void storage::set_validator(const string &path, const string &name) { log_assert(!name.empty()) ; log_assert(type_validator==NULL) ; type_name = name ; type_validator = validator::from_file(path.c_str()) ; validator_owned = true ; } void storage::set_validator(validator *v, const string &name) { log_assert(!name.empty()) ; log_assert(type_validator==NULL) ; type_name = name ; type_validator = v ; } record *storage::load() { log_assert(path.size()>0, "no path defined, where do you want to read from?") ; const char *path_0 = path[0].c_str() ; for(unsigned i=0; i<path.size(); ++i) { // reading data file const char *path_i = path[i].c_str() ; int res = read_file_to_string(path_i, data_cached) ; if(res<0) { log_warning("can't read '%s': %m", path_i) ; continue ; } // read success // parsing iodata structure string message ; record *tree = parse_string_to_tree(message) ; if(tree==NULL) { log_warning("can't parse data in '%s': %s", path_i, message.c_str()) ; continue ; } // parse success // validate the data if(type_validator) { try { log_debug() ; type_validator->check_record_after_read(tree, type_name) ; log_debug() ; } catch(const iodata::exception &e) { log_debug() ; log_warning("data in '%s' isn't valid: %s", path_i, e.info().c_str()) ; delete tree ; continue ; } } // data is validated, empty fields are set to default values data_source = i ; log_info("read data from '%s'", path_i) ; return tree ; } // no correct data on the disk data_source = -1 ; data_cached = "" ; if(type_validator==NULL) { log_error("no type information for data in '%s' known, give up", path_0) ; return NULL ; } // let's try to use default values record *tree = new record ; try { type_validator->check_record_after_read(tree, type_name) ; } catch(iodata::exception &e) { log_error("no default values for data in '%s' known: %s; give up", path_0, e.info().c_str()) ; delete tree ; return NULL ; } // success: using default values log_info("using default values for data in '%s'", path_0) ; data_cached = ".\n" ; // empty record return tree ; } // this function can throw validator::exception // if (and only if) the data tree contains rubbish int storage::save(record *rec) { log_assert(path.size()>0, "no path defined, where do you want to write to?") ; const char *path_0 = path[0].c_str() ; // check record and reduce default values if(type_validator) type_validator->check_record_before_write(rec, type_name) ; // serialize the record ostringstream os ; output out(os) ; out.output_record(rec) ; string new_data = os.str() ; if(data_cached==new_data) { log_debug("do not write the same data to '%s' again", path[data_source].c_str()) ; return data_source ; } // *) no valid data on the disk or // *) no secondary file or // *) data read from the secondary // => just write to the primary file bool no_data_on_disk = data_source<0 ; bool no_secondary = path.size()==1 ; bool data_in_secondary = data_source == 1 ; if(no_data_on_disk || no_secondary || data_in_secondary) { int res = write_string(0, new_data) ; if(res<0) { log_critical("can't write data to '%s': %m", path_0) ; if(data_source==0) // data destroyed by write attempt { data_source = -1 ; data_cached = "" ; } } else { log_info("data written to '%s'", path_0) ; data_source = 0 ; data_cached = new_data ; } return data_source ; } log_assert(0<=data_source) ; // old data is on disk log_assert(path.size()>1) ; // secondary path is given log_assert(data_source==0) ; // old data is in the primary file const char *path_1 = path[1].c_str() ; int index = 0 ; // we want to save the data to primary file if(move_files(0,1) < 0) { log_critical("can't rename files: '%s'->'%s': %m", path_0, path_1) ; index = 1 ; // let's write to the secondary then } const char *path_i = index==0 ? path_0 : path_1 ; int res = write_string(index, new_data) ; if(res<0) { log_critical("can't write data to '%s': %m", path_i) ; data_source = -1 ; data_cached = "" ; } else { log_info("data written to '%s'", path_i) ; // we have to get rid of primary file, if written to secondary if(index > 0 && unlink(path_0)<0) { // that's the mega paranoia! log_critical("written data will be lost, because can't remove '%s': %m", path_0) ; data_source = -1 ; data_cached = "" ; } else { if(index > 0) // it means we can't move primary->secondary { // but maybe it's possible to move it back ? if(move_files(1, 0) < 0) log_warning("can't move secondary to primary '%s' (%m), but never mind: data is saved", path_0) ; else index = 0 ; // yahoo, it's a miracle !! } // we're happy data_source = index ; data_cached = new_data ; } } return data_source ; } bool storage::fix_files(bool force) { if(data_cached.empty()) return false ; log_assert(path.size()>0, "primary storage file not defined") ; const char *path_0 = path[0].c_str() ; if(!force && data_source==0) // may be it's enough to read { string in_file ; if(read_file_to_string(path_0, in_file)==0 && data_cached==in_file) return true ; log_info("primary file '%s' doesn't match cached data", path_0) ; } // now we have to write cached data to primary file if(force && data_source==0 && path.size()>1) // primary file should be backed up { if(move_files(0,1) < 0) return false ; } // now just write the cached data to primary if(write_string(0, data_cached)<0) return false ; data_source = 0 ; #if 0 // now we do not need the secondary file // so we are trying to remove it // but if we can't, it doesn't matter: // a warning is enough if(path.size() > 1) { const char *path_1 = path[1].c_str() ; if(unlink(path_1) < 0) log_warning("can't unlink the secondary file '%s': %m", path_1) ; } commented out this piece, because as a matter of fact we do need the secondary: it is a kind of place holder for the future 'disk full' situation #endif return true ; } int storage::move_files(int from, int to) { const char *path_from = path[from].c_str() ; const char *path_to = path[to].c_str() ; return rename(path_from, path_to) ; } int storage::write_string(int index, const string &data) { const char *file = path[index].c_str() ; return write_string_to_file(file, data) ; } int storage::write_string_to_file(const char *file, const string &data) { int fd = open(file, O_WRONLY|O_CREAT|O_TRUNC, 0666) ; if(fd < 0) return -1 ; int size = data.length(), done = 0 ; const char *start = data.c_str() ; while(done < size) { ssize_t bytes = write (fd, start + done, size - done) ; if(bytes>0) done += bytes ; else if(bytes==0 || errno!=EINTR) // try again only if interrupted break ; // write(2) man page says: "zero indicates nothing was written" // So we're not trying to write again (probably in an infinite loop) // But it's still not clear, what kind of condition indicates bytes=0 :-( } if(done < size || fsync(fd) < 0 || close(fd) < 0) // that's it { int errno_copy = errno ; close(fd) ; // don't care about result, even if it's already closed errno = errno_copy ; return -1 ; } return 0 ; } int storage::read_file_to_string(const char *file, string &input) { int fd = open(file, O_RDONLY) ; if(fd < 0) return -1 ; struct stat st ; if(fstat(fd, &st) < 0) { int errno_copy = errno ; close(fd) ; errno = errno_copy ; return -1 ; } int size = st.st_size ; if (size==0) { input.resize(0) ; return 0 ; } if(size<0) { close(fd) ; errno = EIO ; // TODO find a better one? return -1 ; } int done = 0 ; char *buffer = new char[size+1] ; log_assert(buffer) ; while(done < size) { ssize_t bytes = read (fd, buffer + done, size - done) ; if(bytes>0) done += bytes ; else if(bytes==0 || errno!=EINTR) // EOF or error (not interrupt) break ; else if(lseek(fd, done, SEEK_SET)!=done) // fix the position, if interrupted break ; // read(2) man page is self contratictory: // on the one side bytes=0 means EOF: "zero indicates end of file" // on the other side it states "It is not an error if this number is // smaller than the number of bytes requested; this may happen for example // [...] because read() was interrupted by a signal". As zero is smaller // than the number of bytes requested, it may indicate an interrupt then. // As we can't distinguish between "zero because of EOF" and "zero because // of interrupt" let's assume the first to be paranoid (if someone has // truncated our file during we're reading it and we assume interrupt, we // would remain in an infinite loop). // In the case of an interrupt (bytes<0 and errno=EINTR) "it is left // unspecified whether the file position [...] changes". That's the // reason for the weird lseek() call. } int errno_copy = errno ; close(fd) ; // failed? who cares, we got data already if(done < size) { delete[] buffer ; errno = errno_copy ; return -1 ; } buffer[size] = '\0' ; if(strlen(buffer)!=(unsigned)size) // some '\0' inside ? { delete[] buffer ; errno = EILSEQ ; return -1 ; } input = buffer ; delete[] buffer ; return 0 ; } record * storage::parse_string_to_tree(std::string &message) { record *rec = NULL ; try { istringstream in(data_cached) ; parser p(in) ; p.parse() ; rec = p.detach() ; } catch(iodata::exception &e) { message = e.info() ; return NULL ; } return rec ; } <|endoftext|>
<commit_before>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QTimer> #include <QStackedWidget> #include <QSortFilterProxyModel> #include <QLineEdit> #include "seafile-applet.h" #include "account-mgr.h" #include "repo-service.h" #include "repo-tree-view.h" #include "repo-tree-model.h" #include "repo-item-delegate.h" #include "api/requests.h" #include "api/server-repo.h" #include "rpc/local-repo.h" #include "loading-view.h" #include "repos-tab.h" namespace { const char *kLoadingFaieldLabelName = "loadingFailedText"; enum { INDEX_LOADING_VIEW = 0, INDEX_LOADING_FAILED_VIEW, INDEX_REPOS_VIEW }; } // namespace ReposTab::ReposTab(QWidget *parent) : TabView(parent) { createRepoTree(); createLoadingView(); createLoadingFailedView(); filter_text_ = new QLineEdit; filter_text_->setPlaceholderText(tr("Search libraries...")); filter_text_->setObjectName("repoNameFilter"); // This property was introduced in Qt 5.2. #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)) filter_text_->setClearButtonEnabled(true); #endif #ifdef Q_OS_MAC filter_text_->setAttribute(Qt::WA_MacShowFocusRect, 0); #endif connect(filter_text_, SIGNAL(textChanged(const QString&)), this, SLOT(onFilterTextChanged(const QString&))); QVBoxLayout *vlayout = (QVBoxLayout *)layout(); vlayout->insertWidget(0, filter_text_); mStack->insertWidget(INDEX_LOADING_VIEW, loading_view_); mStack->insertWidget(INDEX_LOADING_FAILED_VIEW, loading_failed_view_); mStack->insertWidget(INDEX_REPOS_VIEW, repos_tree_); RepoService *svc = RepoService::instance(); connect(svc, SIGNAL(refreshSuccess(const std::vector<ServerRepo>&)), this, SLOT(refreshRepos(const std::vector<ServerRepo>&))); connect(svc, SIGNAL(refreshFailed(const ApiError&)), this, SLOT(refreshReposFailed(const ApiError&))); refresh(); } void ReposTab::createRepoTree() { repos_tree_ = new RepoTreeView(this); repos_model_ = new RepoTreeModel(this); repos_model_->setTreeView(repos_tree_); filter_model_ = new RepoFilterProxyModel(this); filter_model_->setSourceModel(repos_model_); filter_model_->setDynamicSortFilter(true); repos_tree_->setModel(filter_model_); repos_tree_->setItemDelegate(new RepoItemDelegate); } void ReposTab::createLoadingView() { loading_view_ = new LoadingView; static_cast<LoadingView*>(loading_view_)->setQssStyleForTab(); } void ReposTab::createLoadingFailedView() { loading_failed_view_ = new QWidget(this); QVBoxLayout *layout = new QVBoxLayout; loading_failed_view_->setLayout(layout); QLabel *label = new QLabel; label->setObjectName(kLoadingFaieldLabelName); QString link = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("retry")); QString label_text = tr("Failed to get libraries information<br/>" "Please %1").arg(link); label->setText(label_text); label->setAlignment(Qt::AlignCenter); connect(label, SIGNAL(linkActivated(const QString&)), this, SLOT(refresh())); layout->addWidget(label); } void ReposTab::refreshRepos(const std::vector<ServerRepo>& repos) { repos_model_->setRepos(repos); onFilterTextChanged(filter_text_->text()); filter_text_->setVisible(true); mStack->setCurrentIndex(INDEX_REPOS_VIEW); } void ReposTab::refreshReposFailed(const ApiError& error) { qDebug("failed to refresh repos"); if (mStack->currentIndex() == INDEX_LOADING_VIEW) { mStack->setCurrentIndex(INDEX_LOADING_FAILED_VIEW); } } std::vector<QAction*> ReposTab::getToolBarActions() { return repos_tree_->getToolBarActions(); } void ReposTab::showLoadingView() { filter_text_->setVisible(false); mStack->setCurrentIndex(INDEX_LOADING_VIEW); } void ReposTab::refresh() { filter_text_->clear(); showLoadingView(); RepoService::instance()->refresh(true); } void ReposTab::startRefresh() { RepoService::instance()->start(); } void ReposTab::stopRefresh() { RepoService::instance()->stop(); } void ReposTab::onFilterTextChanged(const QString& text) { repos_model_->onFilterTextChanged(text); filter_model_->setFilterText(text.trimmed()); filter_model_->sort(0); if (text.isEmpty()) { repos_tree_->restoreExpandedCategries(); } else { repos_tree_->expandAll(); } } <commit_msg>require a refresh once repo tab is shown<commit_after>#include <QtGlobal> #if (QT_VERSION >= QT_VERSION_CHECK(5, 0, 0)) #include <QtWidgets> #else #include <QtGui> #endif #include <QTimer> #include <QStackedWidget> #include <QSortFilterProxyModel> #include <QLineEdit> #include "seafile-applet.h" #include "account-mgr.h" #include "repo-service.h" #include "repo-tree-view.h" #include "repo-tree-model.h" #include "repo-item-delegate.h" #include "api/requests.h" #include "api/server-repo.h" #include "rpc/local-repo.h" #include "loading-view.h" #include "repos-tab.h" namespace { const char *kLoadingFaieldLabelName = "loadingFailedText"; enum { INDEX_LOADING_VIEW = 0, INDEX_LOADING_FAILED_VIEW, INDEX_REPOS_VIEW }; } // namespace ReposTab::ReposTab(QWidget *parent) : TabView(parent) { createRepoTree(); createLoadingView(); createLoadingFailedView(); filter_text_ = new QLineEdit; filter_text_->setPlaceholderText(tr("Search libraries...")); filter_text_->setObjectName("repoNameFilter"); // This property was introduced in Qt 5.2. #if (QT_VERSION >= QT_VERSION_CHECK(5, 2, 0)) filter_text_->setClearButtonEnabled(true); #endif #ifdef Q_OS_MAC filter_text_->setAttribute(Qt::WA_MacShowFocusRect, 0); #endif connect(filter_text_, SIGNAL(textChanged(const QString&)), this, SLOT(onFilterTextChanged(const QString&))); QVBoxLayout *vlayout = (QVBoxLayout *)layout(); vlayout->insertWidget(0, filter_text_); mStack->insertWidget(INDEX_LOADING_VIEW, loading_view_); mStack->insertWidget(INDEX_LOADING_FAILED_VIEW, loading_failed_view_); mStack->insertWidget(INDEX_REPOS_VIEW, repos_tree_); RepoService *svc = RepoService::instance(); connect(svc, SIGNAL(refreshSuccess(const std::vector<ServerRepo>&)), this, SLOT(refreshRepos(const std::vector<ServerRepo>&))); connect(svc, SIGNAL(refreshFailed(const ApiError&)), this, SLOT(refreshReposFailed(const ApiError&))); refresh(); } void ReposTab::createRepoTree() { repos_tree_ = new RepoTreeView(this); repos_model_ = new RepoTreeModel(this); repos_model_->setTreeView(repos_tree_); filter_model_ = new RepoFilterProxyModel(this); filter_model_->setSourceModel(repos_model_); filter_model_->setDynamicSortFilter(true); repos_tree_->setModel(filter_model_); repos_tree_->setItemDelegate(new RepoItemDelegate); } void ReposTab::createLoadingView() { loading_view_ = new LoadingView; static_cast<LoadingView*>(loading_view_)->setQssStyleForTab(); } void ReposTab::createLoadingFailedView() { loading_failed_view_ = new QWidget(this); QVBoxLayout *layout = new QVBoxLayout; loading_failed_view_->setLayout(layout); QLabel *label = new QLabel; label->setObjectName(kLoadingFaieldLabelName); QString link = QString("<a style=\"color:#777\" href=\"#\">%1</a>").arg(tr("retry")); QString label_text = tr("Failed to get libraries information<br/>" "Please %1").arg(link); label->setText(label_text); label->setAlignment(Qt::AlignCenter); connect(label, SIGNAL(linkActivated(const QString&)), this, SLOT(refresh())); layout->addWidget(label); } void ReposTab::refreshRepos(const std::vector<ServerRepo>& repos) { repos_model_->setRepos(repos); onFilterTextChanged(filter_text_->text()); filter_text_->setVisible(true); mStack->setCurrentIndex(INDEX_REPOS_VIEW); } void ReposTab::refreshReposFailed(const ApiError& error) { qDebug("failed to refresh repos"); if (mStack->currentIndex() == INDEX_LOADING_VIEW) { mStack->setCurrentIndex(INDEX_LOADING_FAILED_VIEW); } } std::vector<QAction*> ReposTab::getToolBarActions() { return repos_tree_->getToolBarActions(); } void ReposTab::showLoadingView() { filter_text_->setVisible(false); mStack->setCurrentIndex(INDEX_LOADING_VIEW); } void ReposTab::refresh() { filter_text_->clear(); showLoadingView(); RepoService::instance()->refresh(true); } void ReposTab::startRefresh() { RepoService::instance()->start(); RepoService::instance()->refresh(true); } void ReposTab::stopRefresh() { RepoService::instance()->stop(); } void ReposTab::onFilterTextChanged(const QString& text) { repos_model_->onFilterTextChanged(text); filter_model_->setFilterText(text.trimmed()); filter_model_->sort(0); if (text.isEmpty()) { repos_tree_->restoreExpandedCategries(); } else { repos_tree_->expandAll(); } } <|endoftext|>
<commit_before><commit_msg>increased error threshold in matrix-solve test (ticket #496)<commit_after><|endoftext|>
<commit_before>#include <agency/new_executor_traits.hpp> #include <cassert> #include <iostream> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { // void -> void executor_type exec; auto void_future = agency::when_all(); int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&] { set_me_to_thirteen = 13; }, void_future); f.wait(); assert(set_me_to_thirteen == 13); assert(exec.valid()); } { // void -> int executor_type exec; auto void_future = agency::when_all(); auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [] { return 13; }, void_future); assert(f.get() == 13); assert(exec.valid()); } { // int -> void executor_type exec; auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13); int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x) { set_me_to_thirteen = x; }, int_future); f.wait(); assert(set_me_to_thirteen == 13); assert(exec.valid()); } { // int -> float executor_type exec; auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13); auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x) { return float(x) + 1.f; }, int_future); assert(f.get() == 14.f); assert(exec.valid()); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); std::cout << "OK" << std::endl; return 0; } <commit_msg>Test multi_agent_async_execute_returning_user_specified_container_executor with test_single_agent_then_execute.cpp<commit_after>#include <agency/new_executor_traits.hpp> #include <cassert> #include <iostream> #include "test_executors.hpp" template<class Executor> void test() { using executor_type = Executor; { // void -> void executor_type exec; auto void_future = agency::when_all(); int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&] { set_me_to_thirteen = 13; }, void_future); f.wait(); assert(set_me_to_thirteen == 13); assert(exec.valid()); } { // void -> int executor_type exec; auto void_future = agency::when_all(); auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [] { return 13; }, void_future); assert(f.get() == 13); assert(exec.valid()); } { // int -> void executor_type exec; auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13); int set_me_to_thirteen = 0; auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [&](int& x) { set_me_to_thirteen = x; }, int_future); f.wait(); assert(set_me_to_thirteen == 13); assert(exec.valid()); } { // int -> float executor_type exec; auto int_future = agency::new_executor_traits<executor_type>::template make_ready_future<int>(exec, 13); auto f = agency::new_executor_traits<executor_type>::then_execute(exec, [](int &x) { return float(x) + 1.f; }, int_future); assert(f.get() == 14.f); assert(exec.valid()); } } int main() { using namespace test_executors; test<empty_executor>(); test<single_agent_when_all_execute_and_select_executor>(); test<multi_agent_when_all_execute_and_select_executor>(); test<single_agent_then_execute_executor>(); test<multi_agent_execute_returning_user_defined_container_executor>(); test<multi_agent_execute_returning_default_container_executor>(); test<multi_agent_execute_returning_void_executor>(); test<multi_agent_async_execute_returning_user_defined_container_executor>(); std::cout << "OK" << std::endl; return 0; } <|endoftext|>
<commit_before>/* * ============================================================================ * * Filename: trim.cc * Description: Trim reads using the windowed quality trimming algorithm * License: LGPL-3+ * Author: Kevin Murray, [email protected] * * ============================================================================ */ /* Copyright (c) 2015 Kevin Murray * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include "qcpp.hh" #include "qc-qualtrim.hh" #include "qc-measure.hh" #if 0 #include <thread> std::mutex _cout_mutex; void parse_and_print(qcpp::ProcessedReadStream *stream) { qcpp::ReadPair rp; bool not_at_end = stream->parse_read_pair(rp); while (not_at_end) { std::string rp_str = rp.str(); { std::lock_guard<std::mutex> lg(_cout_mutex); std::cout << rp_str; } not_at_end = stream->parse_read_pair(rp); } } int main (int argc, char *argv[]) { qcpp::ProcessedReadStream stream; std::vector<std::thread> threads; unsigned int n_threads = std::thread::hardware_concurrency() - 1; if (argc != 2) { std::cerr << "USAGE: " << argv[0] << " <read_file>" << std::endl; return EXIT_FAILURE; } stream.open(argv[1]); //stream.append_processor<qcpp::PerBaseQuality>("Before QC"); stream.append_processor<qcpp::WindowedQualTrim>("Qual Trim", 33, 20, 4); //stream.append_processor<qcpp::PerBaseQuality>("after qc"); for (size_t i = 0; i < n_threads; i++) { threads.push_back(std::thread(parse_and_print, &stream)); } for (size_t i = 0; i < n_threads; i++) { threads[i].join(); } std::cerr << stream.report(); return EXIT_SUCCESS; } #else int main (int argc, char *argv[]) { qcpp::ProcessedReadStream stream; qcpp::ReadPair rp; if (argc != 2) { std::cerr << "USAGE: " << argv[0] << " <read_file>" << std::endl; return EXIT_FAILURE; } stream.open(argv[1]); //stream.append_processor<qcpp::PerBaseQuality>("Before QC"); stream.append_processor<qcpp::WindowedQualTrim>("Qual Trim", 33, 20, 4); //stream.append_processor<qcpp::PerBaseQuality>("after qc"); while (stream.parse_read_pair(rp)) { std::cout << rp.str(); } std::cerr << stream.report(); return EXIT_SUCCESS; } #endif <commit_msg>Remove old qualtrim code<commit_after><|endoftext|>
<commit_before><commit_msg>INTEGRATION: CWS warnings01 (1.38.8); FILE MERGED 2006/05/23 17:54:43 sb 1.38.8.5: RESYNC: (1.40-1.41); FILE MERGED 2006/04/20 14:47:02 sb 1.38.8.4: #i53898# Made code warning-free again after resync to SRC680m162. 2006/04/07 17:51:40 sb 1.38.8.3: RESYNC: (1.38-1.40); FILE MERGED 2005/10/27 12:29:12 sb 1.38.8.2: #i53898# Made code warning-free. 2005/10/14 11:19:39 sb 1.38.8.1: #i53898# Made code warning-free; cleanup.<commit_after><|endoftext|>
<commit_before>// vim: set sts=2 sw=2 et: // encoding: utf-8 // // Copyleft 2011 RIME Developers // License: GPLv3 // // 2011-12-07 GONG Chen <[email protected]> // #include <string> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <rime/candidate.h> #include <rime/common.h> #include <rime/composition.h> #include <rime/context.h> #include <rime/key_event.h> #include <rime/menu.h> #include <rime/processor.h> #include <rime/schema.h> #include <rime/switcher.h> #include <rime/translation.h> namespace rime { static const char *kRightArrow = " \xe2\x86\x92 "; class SwitcherOption : public Candidate { public: SwitcherOption(Schema *schema) : Candidate("schema", 0, 0), text_(schema->schema_name()), comment_(), value_(schema->schema_id()), auto_save_(true) {} SwitcherOption(const std::string &current_state_label, const std::string &next_state_label, const std::string &option_name, bool current_state, bool auto_save) : Candidate(current_state ? "switch_off" : "switch_on", 0, 0), text_(current_state_label + kRightArrow + next_state_label), value_(option_name), auto_save_(auto_save) {} void Apply(Engine *target_engine, Config *user_config); const std::string& text() const { return text_; } const std::string comment() const { return comment_; } protected: std::string text_; std::string comment_; std::string value_; bool auto_save_; }; void SwitcherOption::Apply(Engine *target_engine, Config *user_config) { if (type() == "schema") { const std::string &current_schema_id(target_engine->schema()->schema_id()); if (value_ != current_schema_id) { target_engine->set_schema(new Schema(value_)); } if (auto_save_ && user_config) { user_config->SetString("var/previously_selected_schema", value_); } return; } if (type() == "switch_off" || type() == "switch_on") { bool option_is_on = (type() == "switch_on"); target_engine->context()->set_option(value_, option_is_on); if (auto_save_ && user_config) { user_config->SetBool("var/option/" + value_, option_is_on); } return; } } Switcher::Switcher() : Engine(new Schema), target_engine_(NULL), active_(false) { EZDBGONLYLOGGERFUNCTRACKER; // receive context notifications context_->select_notifier().connect( boost::bind(&Switcher::OnSelect, this, _1)); user_config_.reset(Config::Require("config")->Create("user")); InitializeSubProcessors(); LoadSettings(); } Switcher::~Switcher() { EZDBGONLYLOGGERFUNCTRACKER; } void Switcher::Attach(Engine *engine) { target_engine_ = engine; // restore saved options if (user_config_) { BOOST_FOREACH(const std::string& option_name, save_options_) { bool value = false; if (user_config_->GetBool("var/option/" + option_name, &value)) { engine->context()->set_option(option_name, value); } } } } bool Switcher::ProcessKeyEvent(const KeyEvent &key_event) { EZDBGONLYLOGGERVAR(key_event); BOOST_FOREACH(const KeyEvent &hotkey, hotkeys_) { if (key_event == hotkey) { if (!active_ && target_engine_) Activate(); else if (active_) Deactivate(); return true; } } if (active_) { BOOST_FOREACH(shared_ptr<Processor> &p, processors_) { if (Processor::kNoop != p->ProcessKeyEvent(key_event)) return true; } if (key_event.release() || key_event.ctrl() || key_event.alt()) return true; int ch = key_event.keycode(); if (ch == XK_space || ch == XK_Return) { context_->ConfirmCurrentSelection(); } else if (ch == XK_Escape) { Deactivate(); } return true; } return false; } Schema* Switcher::CreateSchema() { Config *config = schema_->config(); if (!config) return NULL; ConfigListPtr schema_list = config->GetList("schema_list"); if (!schema_list) return NULL; std::string previous; if (user_config_) { user_config_->GetString("var/previously_selected_schema", &previous); } std::string recent; for (size_t i = 0; i < schema_list->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(schema_list->GetAt(i)); if (!item) continue; ConfigValuePtr schema_property = item->GetValue("schema"); if (!schema_property) continue; const std::string &schema_id(schema_property->str()); if (previous.empty() || previous == schema_id) { recent = schema_id; break; } if (recent.empty()) recent = schema_id; } if (recent.empty()) return NULL; else return new Schema(recent); } void Switcher::OnSelect(Context *ctx) { EZLOGGERFUNCTRACKER; Segment &seg(ctx->composition()->back()); shared_ptr<SwitcherOption> option = As<SwitcherOption>(seg.GetSelectedCandidate()); if (!option) return; if (target_engine_) { option->Apply(target_engine_, user_config_.get()); } Deactivate(); } void Switcher::Activate() { EZLOGGERFUNCTRACKER; Config *config = schema_->config(); if (!config) return; ConfigListPtr schema_list = config->GetList("schema_list"); if (!schema_list) return; shared_ptr<FifoTranslation> switcher_options(new FifoTranslation); Schema *current_schema = NULL; // current schema comes first if (target_engine_ && target_engine_->schema()) { current_schema = target_engine_->schema(); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(current_schema))); // add custom switches Config *custom = current_schema->config(); if (custom) { ConfigListPtr switches = custom->GetList("switches"); if (switches) { Context *context = target_engine_->context(); for (size_t i = 0; i < switches->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(switches->GetAt(i)); if (!item) continue; ConfigValuePtr name_property = item->GetValue("name"); if (!name_property) continue; ConfigListPtr states = As<ConfigList>(item->Get("states")); if (!states || states->size() != 2) continue; bool current_state = context->get_option(name_property->str()); bool auto_save = (save_options_.find(name_property->str()) != save_options_.end()); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(states->GetValueAt(current_state)->str(), states->GetValueAt(1 - current_state)->str(), name_property->str(), current_state, auto_save))); } } } } // load schema list for (size_t i = 0; i < schema_list->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(schema_list->GetAt(i)); if (!item) continue; ConfigValuePtr schema_property = item->GetValue("schema"); if (!schema_property) continue; const std::string &schema_id(schema_property->str()); if (current_schema && schema_id == current_schema->schema_id()) continue; scoped_ptr<Schema> schema(new Schema(schema_id)); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(schema.get()))); } // assign menu to switcher's context Composition *comp = context_->composition(); if (comp->empty()) { context_->set_prompt(caption_); context_->set_input(" "); Segment seg(0, 0); comp->AddSegment(seg); } shared_ptr<Menu> menu(new Menu); comp->back().menu = menu; menu->AddTranslation(switcher_options); // activated! active_ = true; } void Switcher::Deactivate() { context_->Clear(); active_ = false; } void Switcher::LoadSettings() { EZDBGONLYLOGGERFUNCTRACKER; Config *config = schema_->config(); if (!config) return; if (!config->GetString("switcher/caption", &caption_) || caption_.empty()) { caption_ = ":-)"; } ConfigListPtr hotkeys = config->GetList("switcher/hotkeys"); if (!hotkeys) return; hotkeys_.clear(); for (size_t i = 0; i < hotkeys->size(); ++i) { ConfigValuePtr value = hotkeys->GetValueAt(i); if (!value) continue; hotkeys_.push_back(KeyEvent(value->str())); } ConfigListPtr options = config->GetList("switcher/save_options"); if (!options) return; save_options_.clear(); for (ConfigList::Iterator it = options->begin(); it != options->end(); ++it) { ConfigValuePtr option_name = As<ConfigValue>(*it); if (!option_name) continue; save_options_.insert(option_name->str()); } } void Switcher::InitializeSubProcessors() { EZDBGONLYLOGGERFUNCTRACKER; processors_.clear(); { Processor::Component *c = Processor::Require("key_binder"); if (!c) { EZLOGGERPRINT("Warning: key_binder not available."); } else { shared_ptr<Processor> p(c->Create(this)); processors_.push_back(p); } } { Processor::Component *c = Processor::Require("selector"); if (!c) { EZLOGGERPRINT("Warning: selector not available."); } else { shared_ptr<Processor> p(c->Create(this)); processors_.push_back(p); } } } } // namespace rime <commit_msg>Highlight the next switcher option by pressing the hotkey more times.<commit_after>// vim: set sts=2 sw=2 et: // encoding: utf-8 // // Copyleft 2011 RIME Developers // License: GPLv3 // // 2011-12-07 GONG Chen <[email protected]> // #include <string> #include <boost/bind.hpp> #include <boost/foreach.hpp> #include <rime/candidate.h> #include <rime/common.h> #include <rime/composition.h> #include <rime/context.h> #include <rime/key_event.h> #include <rime/menu.h> #include <rime/processor.h> #include <rime/schema.h> #include <rime/switcher.h> #include <rime/translation.h> namespace rime { static const char *kRightArrow = " \xe2\x86\x92 "; class SwitcherOption : public Candidate { public: SwitcherOption(Schema *schema) : Candidate("schema", 0, 0), text_(schema->schema_name()), comment_(), value_(schema->schema_id()), auto_save_(true) {} SwitcherOption(const std::string &current_state_label, const std::string &next_state_label, const std::string &option_name, bool current_state, bool auto_save) : Candidate(current_state ? "switch_off" : "switch_on", 0, 0), text_(current_state_label + kRightArrow + next_state_label), value_(option_name), auto_save_(auto_save) {} void Apply(Engine *target_engine, Config *user_config); const std::string& text() const { return text_; } const std::string comment() const { return comment_; } protected: std::string text_; std::string comment_; std::string value_; bool auto_save_; }; void SwitcherOption::Apply(Engine *target_engine, Config *user_config) { if (type() == "schema") { const std::string &current_schema_id(target_engine->schema()->schema_id()); if (value_ != current_schema_id) { target_engine->set_schema(new Schema(value_)); } if (auto_save_ && user_config) { user_config->SetString("var/previously_selected_schema", value_); } return; } if (type() == "switch_off" || type() == "switch_on") { bool option_is_on = (type() == "switch_on"); target_engine->context()->set_option(value_, option_is_on); if (auto_save_ && user_config) { user_config->SetBool("var/option/" + value_, option_is_on); } return; } } Switcher::Switcher() : Engine(new Schema), target_engine_(NULL), active_(false) { EZDBGONLYLOGGERFUNCTRACKER; // receive context notifications context_->select_notifier().connect( boost::bind(&Switcher::OnSelect, this, _1)); user_config_.reset(Config::Require("config")->Create("user")); InitializeSubProcessors(); LoadSettings(); } Switcher::~Switcher() { EZDBGONLYLOGGERFUNCTRACKER; } void Switcher::Attach(Engine *engine) { target_engine_ = engine; // restore saved options if (user_config_) { BOOST_FOREACH(const std::string& option_name, save_options_) { bool value = false; if (user_config_->GetBool("var/option/" + option_name, &value)) { engine->context()->set_option(option_name, value); } } } } bool Switcher::ProcessKeyEvent(const KeyEvent &key_event) { EZDBGONLYLOGGERVAR(key_event); BOOST_FOREACH(const KeyEvent &hotkey, hotkeys_) { if (key_event == hotkey) { if (!active_ && target_engine_) { Activate(); } else if (active_ && key_event.keycode() != XK_Down) { // move cursor down to the next item ProcessKeyEvent(KeyEvent(XK_Down, 0)); } return true; } } if (active_) { BOOST_FOREACH(shared_ptr<Processor> &p, processors_) { if (Processor::kNoop != p->ProcessKeyEvent(key_event)) return true; } if (key_event.release() || key_event.ctrl() || key_event.alt()) return true; int ch = key_event.keycode(); if (ch == XK_space || ch == XK_Return) { context_->ConfirmCurrentSelection(); } else if (ch == XK_Escape) { Deactivate(); } return true; } return false; } Schema* Switcher::CreateSchema() { Config *config = schema_->config(); if (!config) return NULL; ConfigListPtr schema_list = config->GetList("schema_list"); if (!schema_list) return NULL; std::string previous; if (user_config_) { user_config_->GetString("var/previously_selected_schema", &previous); } std::string recent; for (size_t i = 0; i < schema_list->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(schema_list->GetAt(i)); if (!item) continue; ConfigValuePtr schema_property = item->GetValue("schema"); if (!schema_property) continue; const std::string &schema_id(schema_property->str()); if (previous.empty() || previous == schema_id) { recent = schema_id; break; } if (recent.empty()) recent = schema_id; } if (recent.empty()) return NULL; else return new Schema(recent); } void Switcher::OnSelect(Context *ctx) { EZLOGGERFUNCTRACKER; Segment &seg(ctx->composition()->back()); shared_ptr<SwitcherOption> option = As<SwitcherOption>(seg.GetSelectedCandidate()); if (!option) return; if (target_engine_) { option->Apply(target_engine_, user_config_.get()); } Deactivate(); } void Switcher::Activate() { EZLOGGERFUNCTRACKER; Config *config = schema_->config(); if (!config) return; ConfigListPtr schema_list = config->GetList("schema_list"); if (!schema_list) return; shared_ptr<FifoTranslation> switcher_options(new FifoTranslation); Schema *current_schema = NULL; // current schema comes first if (target_engine_ && target_engine_->schema()) { current_schema = target_engine_->schema(); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(current_schema))); // add custom switches Config *custom = current_schema->config(); if (custom) { ConfigListPtr switches = custom->GetList("switches"); if (switches) { Context *context = target_engine_->context(); for (size_t i = 0; i < switches->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(switches->GetAt(i)); if (!item) continue; ConfigValuePtr name_property = item->GetValue("name"); if (!name_property) continue; ConfigListPtr states = As<ConfigList>(item->Get("states")); if (!states || states->size() != 2) continue; bool current_state = context->get_option(name_property->str()); bool auto_save = (save_options_.find(name_property->str()) != save_options_.end()); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(states->GetValueAt(current_state)->str(), states->GetValueAt(1 - current_state)->str(), name_property->str(), current_state, auto_save))); } } } } // load schema list for (size_t i = 0; i < schema_list->size(); ++i) { ConfigMapPtr item = As<ConfigMap>(schema_list->GetAt(i)); if (!item) continue; ConfigValuePtr schema_property = item->GetValue("schema"); if (!schema_property) continue; const std::string &schema_id(schema_property->str()); if (current_schema && schema_id == current_schema->schema_id()) continue; scoped_ptr<Schema> schema(new Schema(schema_id)); switcher_options->Append( shared_ptr<Candidate>(new SwitcherOption(schema.get()))); } // assign menu to switcher's context Composition *comp = context_->composition(); if (comp->empty()) { context_->set_prompt(caption_); context_->set_input(" "); Segment seg(0, 0); comp->AddSegment(seg); } shared_ptr<Menu> menu(new Menu); comp->back().menu = menu; menu->AddTranslation(switcher_options); // activated! active_ = true; } void Switcher::Deactivate() { context_->Clear(); active_ = false; } void Switcher::LoadSettings() { EZDBGONLYLOGGERFUNCTRACKER; Config *config = schema_->config(); if (!config) return; if (!config->GetString("switcher/caption", &caption_) || caption_.empty()) { caption_ = ":-)"; } ConfigListPtr hotkeys = config->GetList("switcher/hotkeys"); if (!hotkeys) return; hotkeys_.clear(); for (size_t i = 0; i < hotkeys->size(); ++i) { ConfigValuePtr value = hotkeys->GetValueAt(i); if (!value) continue; hotkeys_.push_back(KeyEvent(value->str())); } ConfigListPtr options = config->GetList("switcher/save_options"); if (!options) return; save_options_.clear(); for (ConfigList::Iterator it = options->begin(); it != options->end(); ++it) { ConfigValuePtr option_name = As<ConfigValue>(*it); if (!option_name) continue; save_options_.insert(option_name->str()); } } void Switcher::InitializeSubProcessors() { EZDBGONLYLOGGERFUNCTRACKER; processors_.clear(); { Processor::Component *c = Processor::Require("key_binder"); if (!c) { EZLOGGERPRINT("Warning: key_binder not available."); } else { shared_ptr<Processor> p(c->Create(this)); processors_.push_back(p); } } { Processor::Component *c = Processor::Require("selector"); if (!c) { EZLOGGERPRINT("Warning: selector not available."); } else { shared_ptr<Processor> p(c->Create(this)); processors_.push_back(p); } } } } // namespace rime <|endoftext|>
<commit_before>// 8 september 2015 #include "uipriv_windows.hpp" #include "area.hpp" static LRESULT CALLBACK areaWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { uiArea *a; CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; RECT client; WINDOWPOS *wp = (WINDOWPOS *) lParam; LRESULT lResult; a = (uiArea *) GetWindowLongPtrW(hwnd, GWLP_USERDATA); if (a == NULL) { if (uMsg == WM_CREATE) { a = (uiArea *) (cs->lpCreateParams); // assign a->hwnd here so we can use it immediately a->hwnd = hwnd; SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) a); } // fall through to DefWindowProcW() anyway return DefWindowProcW(hwnd, uMsg, wParam, lParam); } // always recreate the render target if necessary if (a->rt == NULL) a->rt = makeHWNDRenderTarget(a->hwnd); if (areaDoDraw(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; if (uMsg == WM_WINDOWPOSCHANGED) { if ((wp->flags & SWP_NOSIZE) != 0) return DefWindowProcW(hwnd, uMsg, wParam, lParam); uiWindowsEnsureGetClientRect(a->hwnd, &client); areaDrawOnResize(a, &client); areaScrollOnResize(a, &client); return 0; } if (areaDoScroll(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; if (areaDoEvents(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; // nothing done return DefWindowProc(hwnd, uMsg, wParam, lParam); } // control implementation uiWindowsControlAllDefaults(uiArea) static void uiAreaMinimumSize(uiWindowsControl *c, int *width, int *height) { // TODO *width = 0; *height = 0; } ATOM registerAreaClass(HICON hDefaultIcon, HCURSOR hDefaultCursor) { WNDCLASSW wc; ZeroMemory(&wc, sizeof (WNDCLASSW)); wc.lpszClassName = areaClass; wc.lpfnWndProc = areaWndProc; wc.hInstance = hInstance; wc.hIcon = hDefaultIcon; wc.hCursor = hDefaultCursor; wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); // this is just to be safe; see the InvalidateRect() call in the WM_WINDOWPOSCHANGED handler for more details wc.style = CS_HREDRAW | CS_VREDRAW; return RegisterClassW(&wc); } void unregisterArea(void) { if (UnregisterClassW(areaClass, hInstance) == 0) logLastError(L"error unregistering uiArea window class"); } void uiAreaSetSize(uiArea *a, int width, int height) { a->scrollWidth = width; a->scrollHeight = height; areaUpdateScroll(a); } void uiAreaQueueRedrawAll(uiArea *a) { // don't erase the background; we do that ourselves in doPaint() invalidateRect(a->hwnd, NULL, FALSE); } void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height) { // TODO } void uiAreaBeginUserWindowMove(uiArea *a) { HWND toplevel; // TODO restrict execution // TODO release capture toplevel = xxxx(a->hwnd); if (toplevel == NULL) { // TODO return; } // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 SendMessageW(toplevel, WM_SYSCOMMAND, SC_MOVE | 2, 0); } void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge) { HWND toplevel; WPARAM wParam; // TODO restrict execution // TODO release capture toplevel = parentToplevel(a->hwnd); if (toplevel == NULL) { // TODO return; } // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 wParam = SC_SIZE; switch (edge) { case uiWindowResizeEdgeLeft, wParam |= 1; break case uiWindowResizeEdgeTop, wParam |= 3; break case uiWindowResizeEdgeRight, wParam |= 2; break case uiWindowResizeEdgeBottom, wParam |= 6; break case uiWindowResizeEdgeTopLeft, wParam |= 4; break case uiWindowResizeEdgeTopRight, wParam |= 5; break case uiWindowResizeEdgeBottomLeft, wParam |= 7; break case uiWindowResizeEdgeBottomRight: wParam |= 8; break } SendMessageW(toplevel, WM_SYSCOMMAND, wParam, 0); } uiArea *uiNewArea(uiAreaHandler *ah) { uiArea *a; uiWindowsNewControl(uiArea, a); a->ah = ah; a->scrolling = FALSE; clickCounterReset(&(a->cc)); // a->hwnd is assigned in areaWndProc() uiWindowsEnsureCreateControlHWND(0, areaClass, L"", 0, hInstance, a, FALSE); return a; } uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height) { uiArea *a; uiWindowsNewControl(uiArea, a); a->ah = ah; a->scrolling = TRUE; a->scrollWidth = width; a->scrollHeight = height; clickCounterReset(&(a->cc)); // a->hwnd is assigned in areaWndProc() uiWindowsEnsureCreateControlHWND(0, areaClass, L"", WS_HSCROLL | WS_VSCROLL, hInstance, a, FALSE); // set initial scrolling parameters areaUpdateScroll(a); return a; } <commit_msg>Fixed the new Windows uiArea functions.<commit_after>// 8 september 2015 #include "uipriv_windows.hpp" #include "area.hpp" static LRESULT CALLBACK areaWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { uiArea *a; CREATESTRUCTW *cs = (CREATESTRUCTW *) lParam; RECT client; WINDOWPOS *wp = (WINDOWPOS *) lParam; LRESULT lResult; a = (uiArea *) GetWindowLongPtrW(hwnd, GWLP_USERDATA); if (a == NULL) { if (uMsg == WM_CREATE) { a = (uiArea *) (cs->lpCreateParams); // assign a->hwnd here so we can use it immediately a->hwnd = hwnd; SetWindowLongPtrW(hwnd, GWLP_USERDATA, (LONG_PTR) a); } // fall through to DefWindowProcW() anyway return DefWindowProcW(hwnd, uMsg, wParam, lParam); } // always recreate the render target if necessary if (a->rt == NULL) a->rt = makeHWNDRenderTarget(a->hwnd); if (areaDoDraw(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; if (uMsg == WM_WINDOWPOSCHANGED) { if ((wp->flags & SWP_NOSIZE) != 0) return DefWindowProcW(hwnd, uMsg, wParam, lParam); uiWindowsEnsureGetClientRect(a->hwnd, &client); areaDrawOnResize(a, &client); areaScrollOnResize(a, &client); return 0; } if (areaDoScroll(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; if (areaDoEvents(a, uMsg, wParam, lParam, &lResult) != FALSE) return lResult; // nothing done return DefWindowProc(hwnd, uMsg, wParam, lParam); } // control implementation uiWindowsControlAllDefaults(uiArea) static void uiAreaMinimumSize(uiWindowsControl *c, int *width, int *height) { // TODO *width = 0; *height = 0; } ATOM registerAreaClass(HICON hDefaultIcon, HCURSOR hDefaultCursor) { WNDCLASSW wc; ZeroMemory(&wc, sizeof (WNDCLASSW)); wc.lpszClassName = areaClass; wc.lpfnWndProc = areaWndProc; wc.hInstance = hInstance; wc.hIcon = hDefaultIcon; wc.hCursor = hDefaultCursor; wc.hbrBackground = (HBRUSH) (COLOR_BTNFACE + 1); // this is just to be safe; see the InvalidateRect() call in the WM_WINDOWPOSCHANGED handler for more details wc.style = CS_HREDRAW | CS_VREDRAW; return RegisterClassW(&wc); } void unregisterArea(void) { if (UnregisterClassW(areaClass, hInstance) == 0) logLastError(L"error unregistering uiArea window class"); } void uiAreaSetSize(uiArea *a, int width, int height) { a->scrollWidth = width; a->scrollHeight = height; areaUpdateScroll(a); } void uiAreaQueueRedrawAll(uiArea *a) { // don't erase the background; we do that ourselves in doPaint() invalidateRect(a->hwnd, NULL, FALSE); } void uiAreaScrollTo(uiArea *a, double x, double y, double width, double height) { // TODO } void uiAreaBeginUserWindowMove(uiArea *a) { HWND toplevel; // TODO restrict execution ReleaseCapture(); // TODO use properly and reset internal data structures toplevel = parentToplevel(a->hwnd); if (toplevel == NULL) { // TODO return; } // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 SendMessageW(toplevel, WM_SYSCOMMAND, SC_MOVE | 2, 0); } void uiAreaBeginUserWindowResize(uiArea *a, uiWindowResizeEdge edge) { HWND toplevel; WPARAM wParam; // TODO restrict execution ReleaseCapture(); // TODO use properly and reset internal data structures toplevel = parentToplevel(a->hwnd); if (toplevel == NULL) { // TODO return; } // see http://stackoverflow.com/questions/40249940/how-do-i-initiate-a-user-mouse-driven-move-or-resize-for-custom-window-borders-o#40250654 wParam = SC_SIZE; switch (edge) { case uiWindowResizeEdgeLeft: wParam |= 1; break; case uiWindowResizeEdgeTop: wParam |= 3; break; case uiWindowResizeEdgeRight: wParam |= 2; break; case uiWindowResizeEdgeBottom: wParam |= 6; break; case uiWindowResizeEdgeTopLeft: wParam |= 4; break; case uiWindowResizeEdgeTopRight: wParam |= 5; break; case uiWindowResizeEdgeBottomLeft: wParam |= 7; break; case uiWindowResizeEdgeBottomRight: wParam |= 8; break; } SendMessageW(toplevel, WM_SYSCOMMAND, wParam, 0); } uiArea *uiNewArea(uiAreaHandler *ah) { uiArea *a; uiWindowsNewControl(uiArea, a); a->ah = ah; a->scrolling = FALSE; clickCounterReset(&(a->cc)); // a->hwnd is assigned in areaWndProc() uiWindowsEnsureCreateControlHWND(0, areaClass, L"", 0, hInstance, a, FALSE); return a; } uiArea *uiNewScrollingArea(uiAreaHandler *ah, int width, int height) { uiArea *a; uiWindowsNewControl(uiArea, a); a->ah = ah; a->scrolling = TRUE; a->scrollWidth = width; a->scrollHeight = height; clickCounterReset(&(a->cc)); // a->hwnd is assigned in areaWndProc() uiWindowsEnsureCreateControlHWND(0, areaClass, L"", WS_HSCROLL | WS_VSCROLL, hInstance, a, FALSE); // set initial scrolling parameters areaUpdateScroll(a); return a; } <|endoftext|>
<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/file_system_provider/request_manager.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace file_system_provider { namespace { const char kExtensionId[] = "mbflcebpggnecokmikipoihdbecnjfoj"; const int kFileSystemId = 1; // Logs calls of the success and error callbacks on requests. class EventLogger { public: class SuccessEvent { public: SuccessEvent(scoped_ptr<base::DictionaryValue> result, bool has_next) : result_(result.Pass()), has_next_(has_next) {} ~SuccessEvent() {} base::DictionaryValue* result() { return result_.get(); } bool has_next() { return has_next_; } private: scoped_ptr<base::DictionaryValue> result_; bool has_next_; }; class ErrorEvent { public: explicit ErrorEvent(base::File::Error error) : error_(error) {} ~ErrorEvent() {} base::File::Error error() { return error_; } private: base::File::Error error_; }; EventLogger() : weak_ptr_factory_(this) {} virtual ~EventLogger() {} void OnSuccess(scoped_ptr<base::DictionaryValue> result, bool has_next) { success_events_.push_back(new SuccessEvent(result.Pass(), has_next)); } void OnError(base::File::Error error) { error_events_.push_back(new ErrorEvent(error)); } ScopedVector<SuccessEvent>& success_events() { return success_events_; } ScopedVector<ErrorEvent>& error_events() { return error_events_; } base::WeakPtr<EventLogger> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: ScopedVector<SuccessEvent> success_events_; ScopedVector<ErrorEvent> error_events_; base::WeakPtrFactory<EventLogger> weak_ptr_factory_; }; } // namespace class FileSystemProviderRequestManagerTest : public testing::Test { protected: FileSystemProviderRequestManagerTest() {} virtual ~FileSystemProviderRequestManagerTest() {} virtual void SetUp() OVERRIDE { request_manager_.reset(new RequestManager()); } scoped_ptr<RequestManager> request_manager_; }; TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulFill) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); scoped_ptr<base::DictionaryValue> response(new base::DictionaryValue()); const bool has_next = false; response->SetString("path", "i-like-vanilla"); bool result = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); EventLogger::SuccessEvent* event = logger.success_events()[0]; ASSERT_TRUE(event->result()); std::string response_test_string; EXPECT_TRUE(event->result()->GetString("path", &response_test_string)); EXPECT_EQ("i-like-vanilla", response_test_string); EXPECT_EQ(has_next, event->has_next()); // Confirm, that the request is removed. Basically, fulfilling again for the // same request, should fail. { scoped_ptr<base::DictionaryValue> response; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_FALSE(retry); } // Rejecting should also fail. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, base::File::FILE_ERROR_FAILED); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulFill_WithHasNext) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); scoped_ptr<base::DictionaryValue> response; const bool has_next = true; bool result = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); EventLogger::SuccessEvent* event = logger.success_events()[0]; EXPECT_FALSE(event->result()); EXPECT_EQ(has_next, event->has_next()); // Confirm, that the request is not removed (since it has has_next == true). // Basically, fulfilling again for the same request, should not fail. { bool new_has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), new_has_next); EXPECT_TRUE(retry); } // Since |new_has_next| is false, then the request should be removed. To check // it, try to fulfill again, what should fail. { bool new_has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), new_has_next); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndReject) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); EventLogger::ErrorEvent* event = logger.error_events()[0]; EXPECT_EQ(error, event->error()); // Confirm, that the request is removed. Basically, fulfilling again for the // same request, should fail. { scoped_ptr<base::DictionaryValue> response; bool has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_FALSE(retry); } // Rejecting should also fail. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulfillWithWrongRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id + 1, error); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by rejecting it correctly. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndRejectWithWrongRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id + 1, error); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by rejecting it correctly. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulfillWithUnownedRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); scoped_ptr<base::DictionaryValue> response; const bool has_next = false; bool result = request_manager_->FulfillRequest(kExtensionId, 2, // file_system_id request_id, response.Pass(), has_next); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by fulfilling it again, but // with a correct file system. { bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, UniqueIds) { EventLogger logger; int first_request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); int second_request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, first_request_id); EXPECT_EQ(2, second_request_id); } } // namespace file_system_provider } // namespace chromeos <commit_msg>Fix broken build. Literal 'false' cannot be passed as the first argument of EXPECT_EQ().<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <string> #include "base/bind.h" #include "base/files/file.h" #include "base/files/file_path.h" #include "base/memory/scoped_ptr.h" #include "base/memory/scoped_vector.h" #include "base/memory/weak_ptr.h" #include "base/values.h" #include "chrome/browser/chromeos/file_system_provider/request_manager.h" #include "testing/gtest/include/gtest/gtest.h" namespace chromeos { namespace file_system_provider { namespace { const char kExtensionId[] = "mbflcebpggnecokmikipoihdbecnjfoj"; const int kFileSystemId = 1; // Logs calls of the success and error callbacks on requests. class EventLogger { public: class SuccessEvent { public: SuccessEvent(scoped_ptr<base::DictionaryValue> result, bool has_next) : result_(result.Pass()), has_next_(has_next) {} ~SuccessEvent() {} base::DictionaryValue* result() { return result_.get(); } bool has_next() { return has_next_; } private: scoped_ptr<base::DictionaryValue> result_; bool has_next_; }; class ErrorEvent { public: explicit ErrorEvent(base::File::Error error) : error_(error) {} ~ErrorEvent() {} base::File::Error error() { return error_; } private: base::File::Error error_; }; EventLogger() : weak_ptr_factory_(this) {} virtual ~EventLogger() {} void OnSuccess(scoped_ptr<base::DictionaryValue> result, bool has_next) { success_events_.push_back(new SuccessEvent(result.Pass(), has_next)); } void OnError(base::File::Error error) { error_events_.push_back(new ErrorEvent(error)); } ScopedVector<SuccessEvent>& success_events() { return success_events_; } ScopedVector<ErrorEvent>& error_events() { return error_events_; } base::WeakPtr<EventLogger> GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } private: ScopedVector<SuccessEvent> success_events_; ScopedVector<ErrorEvent> error_events_; base::WeakPtrFactory<EventLogger> weak_ptr_factory_; }; } // namespace class FileSystemProviderRequestManagerTest : public testing::Test { protected: FileSystemProviderRequestManagerTest() {} virtual ~FileSystemProviderRequestManagerTest() {} virtual void SetUp() OVERRIDE { request_manager_.reset(new RequestManager()); } scoped_ptr<RequestManager> request_manager_; }; TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulFill) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); scoped_ptr<base::DictionaryValue> response(new base::DictionaryValue()); const bool has_next = false; response->SetString("path", "i-like-vanilla"); bool result = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); EventLogger::SuccessEvent* event = logger.success_events()[0]; ASSERT_TRUE(event->result()); std::string response_test_string; EXPECT_TRUE(event->result()->GetString("path", &response_test_string)); EXPECT_EQ("i-like-vanilla", response_test_string); EXPECT_FALSE(event->has_next()); // Confirm, that the request is removed. Basically, fulfilling again for the // same request, should fail. { scoped_ptr<base::DictionaryValue> response; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_FALSE(retry); } // Rejecting should also fail. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, base::File::FILE_ERROR_FAILED); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulFill_WithHasNext) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); scoped_ptr<base::DictionaryValue> response; const bool has_next = true; bool result = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); EventLogger::SuccessEvent* event = logger.success_events()[0]; EXPECT_FALSE(event->result()); EXPECT_TRUE(event->has_next()); // Confirm, that the request is not removed (since it has has_next == true). // Basically, fulfilling again for the same request, should not fail. { bool new_has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), new_has_next); EXPECT_TRUE(retry); } // Since |new_has_next| is false, then the request should be removed. To check // it, try to fulfill again, what should fail. { bool new_has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), new_has_next); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndReject) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(result); // Validate if the callback has correct arguments. ASSERT_EQ(1u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); EventLogger::ErrorEvent* event = logger.error_events()[0]; EXPECT_EQ(error, event->error()); // Confirm, that the request is removed. Basically, fulfilling again for the // same request, should fail. { scoped_ptr<base::DictionaryValue> response; bool has_next = false; bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_FALSE(retry); } // Rejecting should also fail. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_FALSE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulfillWithWrongRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id + 1, error); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by rejecting it correctly. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndRejectWithWrongRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); EXPECT_EQ(0u, logger.success_events().size()); EXPECT_EQ(0u, logger.error_events().size()); base::File::Error error = base::File::FILE_ERROR_NO_MEMORY; bool result = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id + 1, error); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by rejecting it correctly. { bool retry = request_manager_->RejectRequest( kExtensionId, kFileSystemId, request_id, error); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, CreateAndFulfillWithUnownedRequestId) { EventLogger logger; int request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, request_id); scoped_ptr<base::DictionaryValue> response; const bool has_next = false; bool result = request_manager_->FulfillRequest(kExtensionId, 2, // file_system_id request_id, response.Pass(), has_next); EXPECT_FALSE(result); // Callbacks should not be called. EXPECT_EQ(0u, logger.error_events().size()); EXPECT_EQ(0u, logger.success_events().size()); // Confirm, that the request hasn't been removed, by fulfilling it again, but // with a correct file system. { bool retry = request_manager_->FulfillRequest( kExtensionId, kFileSystemId, request_id, response.Pass(), has_next); EXPECT_TRUE(retry); } } TEST_F(FileSystemProviderRequestManagerTest, UniqueIds) { EventLogger logger; int first_request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); int second_request_id = request_manager_->CreateRequest( kExtensionId, kFileSystemId, base::Bind(&EventLogger::OnSuccess, logger.GetWeakPtr()), base::Bind(&EventLogger::OnError, logger.GetWeakPtr())); EXPECT_EQ(1, first_request_id); EXPECT_EQ(2, second_request_id); } } // namespace file_system_provider } // namespace chromeos <|endoftext|>
<commit_before>/* Copyright 2016 Mitchell Young Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "geometry_output.hpp" #include <fstream> #include <string> #include "pugixml.hpp" #include "error.hpp" using std::ofstream; using std::endl; using std::string; namespace mocc { namespace aux { void output_geometry( const pugi::xml_node &input, const CoreMesh &mesh ) { if( input.empty() ){ throw EXCEPT("No input for geometry output."); } if( input.attribute("file").empty() ) { throw EXCEPT("No \"file\" attribute specified."); } string file = input.attribute("file").value(); int plane = input.attribute("plane").as_int(0); if( (plane < 0) || (plane >= (int)mesh.nz() ) ) { throw EXCEPT("Invalid plane specified."); } ofstream out(file); // boilerplate out << "import cairo as cr" << endl; out << "import math" << endl; out << "import rays" << endl; out << endl; out << "twopi = math.pi*2" << endl; out << endl; out << "# set this to whichever angle of ray you want to show." " Negative value to disable." << endl; out << "angle = -1" << endl; out << endl; out << "mesh_lines = []" << endl; out << endl; out << "core_dims = [" << mesh.hx_core() << ", " << mesh.hy_core() << "]" << endl; out << "" << endl; out << "surface = cr.PDFSurface(\"geometry.pdf\", 720, 720)" << endl; out << "ctx = cr.Context(surface)" << endl; out << "ctx.scale(720/core_dims[0], -720/core_dims[1])" << endl; out << "ctx.translate(0, -core_dims[1])" << endl; out << "" << endl; // do all of the mesh stuff out << "ctx.set_line_width(0.001)" << endl; out << "" << endl; out << "ctx.set_source_rgb(0, 0, 0)" << endl; out << "" << endl; for( auto l: mesh.lines() ) { out << "mesh_lines.append(" << l << ")" << endl; } // Draw the core lines out << "" << endl; out << "for l in mesh_lines:" << endl; out << " p1 = l[0]" << endl; out << " p2 = l[1]" << endl; out << " ctx.move_to(p1[0], p1[1])" << endl; out << " ctx.line_to(p2[0], p2[1])" << endl; out << endl; // Draw the pin meshes int ipin = 0; for( auto pin=mesh.begin( plane ); pin!=mesh.end( plane ); ++pin ) { out << "print \"drawing pin \" + str(" << ipin << ")" << endl; const PinMesh &pm = (*pin)->mesh(); Point2 origin = mesh.pin_origin(ipin); out << "ctx.translate(" << origin.x << ", " << origin.y << ")" << endl; out << pm.draw() << endl; out << "ctx.translate(" << -origin.x << ", " << -origin.y << ")" << endl << endl; ipin++; } out << endl; // Do ray output out << "if angle >= 0:" << endl; out << " ctx.set_source_rgb(0, 0, 1)" << endl; out << " rays.draw_rays(ctx, angle)" << endl; out << "" << endl; out << "surface.finish()" << endl; out << "" << endl; return; } } } // namespaces <commit_msg>Add default file for geometry_output<commit_after>/* Copyright 2016 Mitchell Young Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "geometry_output.hpp" #include <fstream> #include <string> #include "pugixml.hpp" #include "error.hpp" using std::ofstream; using std::endl; using std::string; namespace mocc { namespace aux { void output_geometry( const pugi::xml_node &input, const CoreMesh &mesh ) { if( input.empty() ){ throw EXCEPT("No input for geometry output."); } string file; if( input.attribute("file").empty() ) { file = "geom.py"; } else { file = input.attribute("file").value(); } int plane = input.attribute("plane").as_int(0); if( (plane < 0) || (plane >= (int)mesh.nz() ) ) { throw EXCEPT("Invalid plane specified."); } ofstream out(file); // boilerplate out << "import cairo as cr" << endl; out << "import math" << endl; out << "import rays" << endl; out << endl; out << "twopi = math.pi*2" << endl; out << endl; out << "# set this to whichever angle of ray you want to show." " Negative value to disable." << endl; out << "angle = -1" << endl; out << endl; out << "mesh_lines = []" << endl; out << endl; out << "core_dims = [" << mesh.hx_core() << ", " << mesh.hy_core() << "]" << endl; out << "" << endl; out << "surface = cr.PDFSurface(\"geometry.pdf\", 720, 720)" << endl; out << "ctx = cr.Context(surface)" << endl; out << "ctx.scale(720/core_dims[0], -720/core_dims[1])" << endl; out << "ctx.translate(0, -core_dims[1])" << endl; out << "" << endl; // do all of the mesh stuff out << "ctx.set_line_width(0.001)" << endl; out << "" << endl; out << "ctx.set_source_rgb(0, 0, 0)" << endl; out << "" << endl; for( auto l: mesh.lines() ) { out << "mesh_lines.append(" << l << ")" << endl; } // Draw the core lines out << "" << endl; out << "for l in mesh_lines:" << endl; out << " p1 = l[0]" << endl; out << " p2 = l[1]" << endl; out << " ctx.move_to(p1[0], p1[1])" << endl; out << " ctx.line_to(p2[0], p2[1])" << endl; out << endl; // Draw the pin meshes int ipin = 0; for( auto pin=mesh.begin( plane ); pin!=mesh.end( plane ); ++pin ) { out << "print \"drawing pin \" + str(" << ipin << ")" << endl; const PinMesh &pm = (*pin)->mesh(); Point2 origin = mesh.pin_origin(ipin); out << "ctx.translate(" << origin.x << ", " << origin.y << ")" << endl; out << pm.draw() << endl; out << "ctx.translate(" << -origin.x << ", " << -origin.y << ")" << endl << endl; ipin++; } out << endl; // Do ray output out << "if angle >= 0:" << endl; out << " ctx.set_source_rgb(0, 0, 1)" << endl; out << " rays.draw_rays(ctx, angle)" << endl; out << "" << endl; out << "surface.finish()" << endl; out << "" << endl; return; } } } // namespaces <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <cmath> #include <fstream> #include <numeric> #include "modules/prediction/evaluator/vehicle/mlp_evaluator.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/common/math/math_utils.h" #include "modules/prediction/common/prediction_util.h" namespace apollo { namespace prediction { void MLPEvaluator::Clear() { obstacle_feature_values_map_.clear(); } void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) { Clear(); if (obstacle_ptr == nullptr) { AERROR << "Invalid obstacle."; return; } int id = obstacle_ptr->id(); Feature latest_feature = obstacle_ptr->latest_feature(); if (!latest_feature.IsInitialized()) { ADEBUG << "Obstacle [" << id << "] has no latest feature."; return; } Lane* lane_ptr = latest_feature.mutable_lane(); if (!latest_feature.has_lane() || lane_ptr == nullptr) { ADEBUG << "Obstacle [" << id << "] has no lane feature."; return; } LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph(); if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) { ADEBUG << "Obstacle [" << id << "] has no lane graph."; return; } if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) { ADEBUG << "Obstacle [" << id << "] has no lane sequences."; return; } for (int i = 0; i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) { LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i); CHECK(lane_sequence_ptr != nullptr); ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr); } } void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr) { feature_values_.clear(); int id = obstacle_ptr->id(); std::vector<double> obstacle_feature_values; if (obstacle_feature_values_map_.find(id) == obstacle_feature_values_map_.end()) { SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values); } else { obstacle_feature_values = obstacle_feature_values_map_[id]; } if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected obstacle feature_values " << obstacle_feature_values.size() << "."; return; } std::vector<double> lane_feature_values; SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values); if (lane_feature_values.size() != LANE_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected lane feature_values" << lane_feature_values.size() << "."; return; } feature_values_.insert(feature_values_.end(), lane_feature_values.begin(), lane_feature_values.end()); feature_values_.insert(feature_values_.end(), lane_feature_values.begin(), lane_feature_values.end()); } void MLPEvaluator::SetObstacleFeatureValues( Obstacle* obstacle_ptr, std::vector<double>* feature_values) { feature_values->clear(); feature_values->reserve(OBSTACLE_FEATURE_SIZE); std::vector<double> thetas; std::vector<double> lane_ls; std::vector<double> dist_lbs; std::vector<double> dist_rbs; std::vector<int> lane_types; std::vector<double> speeds; std::vector<double> timestamps; double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration; int count = 0; for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) { const Feature& feature = obstacle_ptr->feature(i); if (!feature.IsInitialized()) { continue; } if (apollo::common::math::DoubleCompare( feature.timestamp(), duration) < 0) { break; } if (feature.has_lane() && feature.lane().has_lane_feature()) { thetas.push_back(feature.lane().lane_feature().angle_diff()); lane_ls.push_back(feature.lane().lane_feature().lane_l()); dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary()); dist_rbs.push_back( feature.lane().lane_feature().dist_to_right_boundary()); lane_types.push_back(feature.lane().lane_feature().lane_turn_type()); timestamps.push_back(feature.timestamp()); if (FLAGS_enable_kf_tracking) { speeds.push_back(feature.t_speed()); } else { speeds.push_back(feature.speed()); } ++count; } } if (count <= 0) { return; } double theta_mean = std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size(); double theta_filtered = (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0]; double lane_l_mean = std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size(); double lane_l_filtered = (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0]; double speed_mean = std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size(); double speed_lateral = sin(theta_filtered) * speed_mean; double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0; double time_to_lb = (abs(speed_lateral) > 0.05) ? dist_lbs[0] / speed_lateral : 20 * dist_lbs[0] * speed_sign; double time_to_rb = (abs(speed_lateral) > 0.05) ? -1 * dist_rbs[0] / speed_lateral : -20 * dist_rbs[0] * speed_sign; double time_diff = timestamps.front() - timestamps.back(); double dist_lb_rate = (timestamps.size() > 1) ? (dist_lbs.front() - dist_lbs.back()) / time_diff : 0.0; double dist_rb_rate = (timestamps.size() > 1) ? (dist_rbs.front() - dist_rbs.back()) / time_diff : 0.0; // setup obstacle feature values feature_values->push_back(theta_filtered); feature_values->push_back(theta_mean); feature_values->push_back(theta_filtered - theta_mean); feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1] : thetas[0]); feature_values->push_back(lane_l_filtered); feature_values->push_back(lane_l_mean); feature_values->push_back(lane_l_filtered - lane_l_mean); feature_values->push_back(speed_mean); feature_values->push_back(dist_lbs.front()); feature_values->push_back(dist_lb_rate); feature_values->push_back(time_to_lb); feature_values->push_back(dist_rbs.front()); feature_values->push_back(dist_rb_rate); feature_values->push_back(time_to_rb); // feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0 // : 0.0); } void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) { feature_values->clear(); feature_values->reserve(LANE_FEATURE_SIZE); const Feature& feature = obstacle_ptr->latest_feature(); if (!feature.IsInitialized()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature."; return; } else if (!feature.has_position()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position."; return; } double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading() : feature.theta(); for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) { if (feature_values->size() >= LANE_FEATURE_SIZE) { break; } const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i); for (int j = 0; j < lane_segment.lane_point_size(); ++j) { if (feature_values->size() >= LANE_FEATURE_SIZE) { break; } const LanePoint& lane_point = lane_segment.lane_point(j); if (!lane_point.has_position()) { AERROR << "Lane point has no position."; continue; } double diff_x = lane_point.position().x() - feature.position().x(); double diff_y = lane_point.position().y() - feature.position().y(); double angle = std::atan2(diff_x, diff_y); feature_values->push_back(std::sin(angle - heading)); feature_values->push_back(lane_point.relative_l()); feature_values->push_back(lane_point.heading()); feature_values->push_back(lane_point.angle_diff()); } } std::size_t size = feature_values->size(); while (size >= 4 && size < LANE_FEATURE_SIZE) { double heading_diff = feature_values->operator[](size - 4); double lane_l_diff = feature_values->operator[](size - 3); double heading = feature_values->operator[](size - 2); double angle_diff = feature_values->operator[](size - 1); feature_values->push_back(heading_diff); feature_values->push_back(lane_l_diff); feature_values->push_back(heading); feature_values->push_back(angle_diff); size = feature_values->size(); } } void MLPEvaluator::LoadModel(const std::string& model_file) { model_ptr_.reset(new FnnVehicleModel()); CHECK(model_ptr_ != nullptr); std::fstream file_stream(model_file, std::ios::in | std::ios::binary); if (!file_stream.good()) { AERROR << "Unable to open the model file: " << model_file << "."; return; } if (!model_ptr_->ParseFromIstream(&file_stream)) { AERROR << "Unable to load the model file: " << model_file << "."; return; } ADEBUG << "Succeeded in loading the model file: " << model_file << "."; } double MLPEvaluator::ComputeProbability() { CHECK(model_ptr_.get() != nullptr); double probability = 0.0; if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) { AERROR << "Model feature size not consistent with model proto definition."; return probability; } std::vector<double> layer_input; layer_input.reserve(model_ptr_->dim_input()); std::vector<double> layer_output; // normalization for (int i = 0; i < model_ptr_->dim_input(); ++i) { double mean = model_ptr_->samples_mean().columns(i); double std = model_ptr_->samples_std().columns(i); layer_input.push_back( apollo::prediction::util::Normalize(feature_values_[i], mean, std)); } for (int i = 0; i < model_ptr_->num_layer(); ++i) { if (i > 0) { layer_input.clear(); layer_output.swap(layer_output); } const Layer& layer = model_ptr_->layer(i); for (int col = 0; col < layer.layer_output_dim(); ++col) { double neuron_output = layer.layer_bias().columns(col); for (int row = 0; row < layer.layer_input_dim(); ++row) { double weight = layer.layer_input_weight().rows(row).columns(col); neuron_output += (layer_input[row] * weight); } if (layer.layer_activation_type() == "relu") { neuron_output = apollo::prediction::util::Relu(neuron_output); } else if (layer.layer_activation_type() == "sigmoid") { neuron_output = apollo::prediction::util::Sigmoid(neuron_output); } else if (layer.layer_activation_type() == "tanh") { neuron_output = std::tanh(neuron_output); } else { LOG(ERROR) << "Undefined activation func: " << layer.layer_activation_type() << ", and default sigmoid will be used instead."; neuron_output = apollo::prediction::util::Sigmoid(neuron_output); } layer_output.push_back(neuron_output); } } if (layer_output.size() != 1) { AERROR << "Model output layer has incorrect # outputs: " << layer_output.size(); } else { probability = layer_output[0]; } return probability; } } // namespace prediction } // namespace apollo <commit_msg>add writing back the lane sequence probability to the feature proto<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <cmath> #include <fstream> #include <numeric> #include "modules/prediction/evaluator/vehicle/mlp_evaluator.h" #include "modules/prediction/common/prediction_gflags.h" #include "modules/common/math/math_utils.h" #include "modules/prediction/common/prediction_util.h" namespace apollo { namespace prediction { void MLPEvaluator::Clear() { obstacle_feature_values_map_.clear(); } void MLPEvaluator::Evaluate(Obstacle* obstacle_ptr) { Clear(); if (obstacle_ptr == nullptr) { AERROR << "Invalid obstacle."; return; } int id = obstacle_ptr->id(); Feature latest_feature = obstacle_ptr->latest_feature(); if (!latest_feature.IsInitialized()) { ADEBUG << "Obstacle [" << id << "] has no latest feature."; return; } Lane* lane_ptr = latest_feature.mutable_lane(); if (!latest_feature.has_lane() || lane_ptr == nullptr) { ADEBUG << "Obstacle [" << id << "] has no lane feature."; return; } LaneGraph* lane_graph_ptr = lane_ptr->mutable_lane_graph(); if (!latest_feature.lane().has_lane_graph() || lane_graph_ptr == nullptr) { ADEBUG << "Obstacle [" << id << "] has no lane graph."; return; } if (latest_feature.lane().lane_graph().lane_sequence_size() == 0) { ADEBUG << "Obstacle [" << id << "] has no lane sequences."; return; } for (int i = 0; i < latest_feature.lane().lane_graph().lane_sequence_size(); ++i) { LaneSequence* lane_sequence_ptr = lane_graph_ptr->mutable_lane_sequence(i); CHECK(lane_sequence_ptr != nullptr); ExtractFeatureValues(obstacle_ptr, lane_sequence_ptr); double probability = ComputeProbability(); lane_sequence_ptr->set_probability(probability); } } void MLPEvaluator::ExtractFeatureValues(Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr) { feature_values_.clear(); int id = obstacle_ptr->id(); std::vector<double> obstacle_feature_values; if (obstacle_feature_values_map_.find(id) == obstacle_feature_values_map_.end()) { SetObstacleFeatureValues(obstacle_ptr, &obstacle_feature_values); } else { obstacle_feature_values = obstacle_feature_values_map_[id]; } if (obstacle_feature_values.size() != OBSTACLE_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected obstacle feature_values " << obstacle_feature_values.size() << "."; return; } std::vector<double> lane_feature_values; SetLaneFeatureValues(obstacle_ptr, lane_sequence_ptr, &lane_feature_values); if (lane_feature_values.size() != LANE_FEATURE_SIZE) { ADEBUG << "Obstacle [" << id << "] has fewer than " << "expected lane feature_values" << lane_feature_values.size() << "."; return; } feature_values_.insert(feature_values_.end(), lane_feature_values.begin(), lane_feature_values.end()); feature_values_.insert(feature_values_.end(), lane_feature_values.begin(), lane_feature_values.end()); } void MLPEvaluator::SetObstacleFeatureValues( Obstacle* obstacle_ptr, std::vector<double>* feature_values) { feature_values->clear(); feature_values->reserve(OBSTACLE_FEATURE_SIZE); std::vector<double> thetas; std::vector<double> lane_ls; std::vector<double> dist_lbs; std::vector<double> dist_rbs; std::vector<int> lane_types; std::vector<double> speeds; std::vector<double> timestamps; double duration = obstacle_ptr->timestamp() - FLAGS_prediction_duration; int count = 0; for (std::size_t i = 0; i < obstacle_ptr->history_size(); ++i) { const Feature& feature = obstacle_ptr->feature(i); if (!feature.IsInitialized()) { continue; } if (apollo::common::math::DoubleCompare( feature.timestamp(), duration) < 0) { break; } if (feature.has_lane() && feature.lane().has_lane_feature()) { thetas.push_back(feature.lane().lane_feature().angle_diff()); lane_ls.push_back(feature.lane().lane_feature().lane_l()); dist_lbs.push_back(feature.lane().lane_feature().dist_to_left_boundary()); dist_rbs.push_back( feature.lane().lane_feature().dist_to_right_boundary()); lane_types.push_back(feature.lane().lane_feature().lane_turn_type()); timestamps.push_back(feature.timestamp()); if (FLAGS_enable_kf_tracking) { speeds.push_back(feature.t_speed()); } else { speeds.push_back(feature.speed()); } ++count; } } if (count <= 0) { return; } double theta_mean = std::accumulate(thetas.begin(), thetas.end(), 0.0) / thetas.size(); double theta_filtered = (thetas.size() > 1) ? (thetas[0] + thetas[1]) / 2.0 : thetas[0]; double lane_l_mean = std::accumulate(lane_ls.begin(), lane_ls.end(), 0.0) / lane_ls.size(); double lane_l_filtered = (lane_ls.size() > 1) ? (lane_ls[0] + lane_ls[1]) / 2.0 : lane_ls[0]; double speed_mean = std::accumulate(speeds.begin(), speeds.end(), 0.0) / speeds.size(); double speed_lateral = sin(theta_filtered) * speed_mean; double speed_sign = (speed_lateral > 0) ? 1.0 : -1.0; double time_to_lb = (abs(speed_lateral) > 0.05) ? dist_lbs[0] / speed_lateral : 20 * dist_lbs[0] * speed_sign; double time_to_rb = (abs(speed_lateral) > 0.05) ? -1 * dist_rbs[0] / speed_lateral : -20 * dist_rbs[0] * speed_sign; double time_diff = timestamps.front() - timestamps.back(); double dist_lb_rate = (timestamps.size() > 1) ? (dist_lbs.front() - dist_lbs.back()) / time_diff : 0.0; double dist_rb_rate = (timestamps.size() > 1) ? (dist_rbs.front() - dist_rbs.back()) / time_diff : 0.0; // setup obstacle feature values feature_values->push_back(theta_filtered); feature_values->push_back(theta_mean); feature_values->push_back(theta_filtered - theta_mean); feature_values->push_back((thetas.size() > 1) ? thetas[0] - thetas[1] : thetas[0]); feature_values->push_back(lane_l_filtered); feature_values->push_back(lane_l_mean); feature_values->push_back(lane_l_filtered - lane_l_mean); feature_values->push_back(speed_mean); feature_values->push_back(dist_lbs.front()); feature_values->push_back(dist_lb_rate); feature_values->push_back(time_to_lb); feature_values->push_back(dist_rbs.front()); feature_values->push_back(dist_rb_rate); feature_values->push_back(time_to_rb); // feature_values->push_back(lane_types.front() == HDMapLane::NO_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::LEFT_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::RIGHT_TURN ? 1.0 // : 0.0); // feature_values->push_back(lane_types.front() == HDMapLane::U_TURN ? 1.0 // : 0.0); } void MLPEvaluator::SetLaneFeatureValues(Obstacle* obstacle_ptr, LaneSequence* lane_sequence_ptr, std::vector<double>* feature_values) { feature_values->clear(); feature_values->reserve(LANE_FEATURE_SIZE); const Feature& feature = obstacle_ptr->latest_feature(); if (!feature.IsInitialized()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no latest feature."; return; } else if (!feature.has_position()) { ADEBUG << "Obstacle [" << obstacle_ptr->id() << "] has no position."; return; } double heading = FLAGS_enable_kf_tracking ? feature.t_velocity_heading() : feature.theta(); for (int i = 0; i < lane_sequence_ptr->lane_segment_size(); ++i) { if (feature_values->size() >= LANE_FEATURE_SIZE) { break; } const LaneSegment& lane_segment = lane_sequence_ptr->lane_segment(i); for (int j = 0; j < lane_segment.lane_point_size(); ++j) { if (feature_values->size() >= LANE_FEATURE_SIZE) { break; } const LanePoint& lane_point = lane_segment.lane_point(j); if (!lane_point.has_position()) { AERROR << "Lane point has no position."; continue; } double diff_x = lane_point.position().x() - feature.position().x(); double diff_y = lane_point.position().y() - feature.position().y(); double angle = std::atan2(diff_x, diff_y); feature_values->push_back(std::sin(angle - heading)); feature_values->push_back(lane_point.relative_l()); feature_values->push_back(lane_point.heading()); feature_values->push_back(lane_point.angle_diff()); } } std::size_t size = feature_values->size(); while (size >= 4 && size < LANE_FEATURE_SIZE) { double heading_diff = feature_values->operator[](size - 4); double lane_l_diff = feature_values->operator[](size - 3); double heading = feature_values->operator[](size - 2); double angle_diff = feature_values->operator[](size - 1); feature_values->push_back(heading_diff); feature_values->push_back(lane_l_diff); feature_values->push_back(heading); feature_values->push_back(angle_diff); size = feature_values->size(); } } void MLPEvaluator::LoadModel(const std::string& model_file) { model_ptr_.reset(new FnnVehicleModel()); CHECK(model_ptr_ != nullptr); std::fstream file_stream(model_file, std::ios::in | std::ios::binary); if (!file_stream.good()) { AERROR << "Unable to open the model file: " << model_file << "."; return; } if (!model_ptr_->ParseFromIstream(&file_stream)) { AERROR << "Unable to load the model file: " << model_file << "."; return; } ADEBUG << "Succeeded in loading the model file: " << model_file << "."; } double MLPEvaluator::ComputeProbability() { CHECK(model_ptr_.get() != nullptr); double probability = 0.0; if (model_ptr_->dim_input() != static_cast<int>(feature_values_.size())) { AERROR << "Model feature size not consistent with model proto definition."; return probability; } std::vector<double> layer_input; layer_input.reserve(model_ptr_->dim_input()); std::vector<double> layer_output; // normalization for (int i = 0; i < model_ptr_->dim_input(); ++i) { double mean = model_ptr_->samples_mean().columns(i); double std = model_ptr_->samples_std().columns(i); layer_input.push_back( apollo::prediction::util::Normalize(feature_values_[i], mean, std)); } for (int i = 0; i < model_ptr_->num_layer(); ++i) { if (i > 0) { layer_input.clear(); layer_output.swap(layer_output); } const Layer& layer = model_ptr_->layer(i); for (int col = 0; col < layer.layer_output_dim(); ++col) { double neuron_output = layer.layer_bias().columns(col); for (int row = 0; row < layer.layer_input_dim(); ++row) { double weight = layer.layer_input_weight().rows(row).columns(col); neuron_output += (layer_input[row] * weight); } if (layer.layer_activation_type() == "relu") { neuron_output = apollo::prediction::util::Relu(neuron_output); } else if (layer.layer_activation_type() == "sigmoid") { neuron_output = apollo::prediction::util::Sigmoid(neuron_output); } else if (layer.layer_activation_type() == "tanh") { neuron_output = std::tanh(neuron_output); } else { LOG(ERROR) << "Undefined activation func: " << layer.layer_activation_type() << ", and default sigmoid will be used instead."; neuron_output = apollo::prediction::util::Sigmoid(neuron_output); } layer_output.push_back(neuron_output); } } if (layer_output.size() != 1) { AERROR << "Model output layer has incorrect # outputs: " << layer_output.size(); } else { probability = layer_output[0]; } return probability; } } // namespace prediction } // namespace apollo <|endoftext|>
<commit_before>// // Test Suite for geos::operation::valid::IsValidOp class // Ported from JTS junit/operation/valid/IsValidTest.java rev. 1.1 #include <tut/tut.hpp> // geos #include <geos/constants.h> // for std::isnan #include <geos/operation/valid/IsValidOp.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/Dimension.h> #include <geos/geom/Geometry.h> #include <geos/geom/LineString.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/PrecisionModel.h> #include <geos/io/WKTReader.h> #include <geos/operation/valid/TopologyValidationError.h> // std #include <cmath> #include <string> #include <memory> using namespace geos::geom; using namespace geos::operation::valid; namespace tut { // // Test Group // struct test_isvalidop_data { geos::io::WKTReader wktreader; typedef std::unique_ptr<Geometry> GeomPtr; typedef geos::geom::GeometryFactory GeometryFactory; geos::geom::PrecisionModel pm_; GeometryFactory::Ptr factory_; test_isvalidop_data() : pm_(1), factory_(GeometryFactory::create(&pm_, 0)) {} }; typedef test_group<test_isvalidop_data> group; typedef group::object object; group test_isvalidop_group("geos::operation::valid::IsValidOp"); // // Test Cases // // 1 - testInvalidCoordinate template<> template<> void object::test<1> () { CoordinateArraySequence* cs = new CoordinateArraySequence(); cs->add(Coordinate(0.0, 0.0)); cs->add(Coordinate(1.0, geos::DoubleNotANumber)); GeomPtr line(factory_->createLineString(cs)); IsValidOp isValidOp(line.get()); bool valid = isValidOp.isValid(); TopologyValidationError* err = isValidOp.getValidationError(); ensure(nullptr != err); const Coordinate& errCoord = err->getCoordinate(); ensure_equals(err->getErrorType(), TopologyValidationError::eInvalidCoordinate); ensure(0 != std::isnan(errCoord.y)); ensure_equals(valid, false); } template<> template<> void object::test<2> () { std::string wkt0("POLYGON((25495445.625 6671632.625,25495445.625 6671711.375,25495555.375 6671711.375,25495555.375 6671632.625,25495445.625 6671632.625),(25495368.0441 6671726.9312,25495368.3959388 6671726.93601515,25495368.7478 6671726.9333,25495368.0441 6671726.9312))"); GeomPtr g0(wktreader.read(wkt0)); IsValidOp isValidOp(g0.get()); bool valid = isValidOp.isValid(); TopologyValidationError* err = isValidOp.getValidationError(); ensure(nullptr != err); const Coordinate& errCoord = err->getCoordinate(); ensure_equals(err->getErrorType(), TopologyValidationError::eHoleOutsideShell); ensure(0 == std::isnan(errCoord.y)); ensure(0 == std::isnan(errCoord.x)); ensure(fabs(errCoord.y - 6671726.9) < 1.0); ensure(fabs(errCoord.x - 25495368.0) < 1.0); ensure_equals(valid, false); } template<> template<> void object::test<3> () { std::string wkt("POLYGON (( -86.3958130146539250 114.3482370100377900, 64.7285128575111490 156.9678884302379600, 138.3490775437400700 43.1639042523018260, 87.9271046586986810 -10.5302909001479570, 87.9271046586986810 -10.5302909001479530, 55.7321237336437390 -44.8146215164960250, -86.3958130146539250 114.3482370100377900))"); auto g = wktreader.read(wkt); ensure(g->isValid()); auto g_rev = g->reverse(); ensure(g_rev->isValid()); } } // namespace tut <commit_msg>Add comment referring to ticket<commit_after>// // Test Suite for geos::operation::valid::IsValidOp class // Ported from JTS junit/operation/valid/IsValidTest.java rev. 1.1 #include <tut/tut.hpp> // geos #include <geos/constants.h> // for std::isnan #include <geos/operation/valid/IsValidOp.h> #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateArraySequence.h> #include <geos/geom/Dimension.h> #include <geos/geom/Geometry.h> #include <geos/geom/LineString.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/PrecisionModel.h> #include <geos/io/WKTReader.h> #include <geos/operation/valid/TopologyValidationError.h> // std #include <cmath> #include <string> #include <memory> using namespace geos::geom; using namespace geos::operation::valid; namespace tut { // // Test Group // struct test_isvalidop_data { geos::io::WKTReader wktreader; typedef std::unique_ptr<Geometry> GeomPtr; typedef geos::geom::GeometryFactory GeometryFactory; geos::geom::PrecisionModel pm_; GeometryFactory::Ptr factory_; test_isvalidop_data() : pm_(1), factory_(GeometryFactory::create(&pm_, 0)) {} }; typedef test_group<test_isvalidop_data> group; typedef group::object object; group test_isvalidop_group("geos::operation::valid::IsValidOp"); // // Test Cases // // 1 - testInvalidCoordinate template<> template<> void object::test<1> () { CoordinateArraySequence* cs = new CoordinateArraySequence(); cs->add(Coordinate(0.0, 0.0)); cs->add(Coordinate(1.0, geos::DoubleNotANumber)); GeomPtr line(factory_->createLineString(cs)); IsValidOp isValidOp(line.get()); bool valid = isValidOp.isValid(); TopologyValidationError* err = isValidOp.getValidationError(); ensure(nullptr != err); const Coordinate& errCoord = err->getCoordinate(); ensure_equals(err->getErrorType(), TopologyValidationError::eInvalidCoordinate); ensure(0 != std::isnan(errCoord.y)); ensure_equals(valid, false); } template<> template<> void object::test<2> () { std::string wkt0("POLYGON((25495445.625 6671632.625,25495445.625 6671711.375,25495555.375 6671711.375,25495555.375 6671632.625,25495445.625 6671632.625),(25495368.0441 6671726.9312,25495368.3959388 6671726.93601515,25495368.7478 6671726.9333,25495368.0441 6671726.9312))"); GeomPtr g0(wktreader.read(wkt0)); IsValidOp isValidOp(g0.get()); bool valid = isValidOp.isValid(); TopologyValidationError* err = isValidOp.getValidationError(); ensure(nullptr != err); const Coordinate& errCoord = err->getCoordinate(); ensure_equals(err->getErrorType(), TopologyValidationError::eHoleOutsideShell); ensure(0 == std::isnan(errCoord.y)); ensure(0 == std::isnan(errCoord.x)); ensure(fabs(errCoord.y - 6671726.9) < 1.0); ensure(fabs(errCoord.x - 25495368.0) < 1.0); ensure_equals(valid, false); } template<> template<> void object::test<3> () { // https://trac.osgeo.org/geos/ticket/588 std::string wkt("POLYGON (( -86.3958130146539250 114.3482370100377900, 64.7285128575111490 156.9678884302379600, 138.3490775437400700 43.1639042523018260, 87.9271046586986810 -10.5302909001479570, 87.9271046586986810 -10.5302909001479530, 55.7321237336437390 -44.8146215164960250, -86.3958130146539250 114.3482370100377900))"); auto g = wktreader.read(wkt); ensure(g->isValid()); auto g_rev = g->reverse(); ensure(g_rev->isValid()); } } // namespace tut <|endoftext|>
<commit_before>// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "exegesis/base/cpu_info.h" #include <initializer_list> #include "exegesis/base/cpuid_x86.h" #include "exegesis/proto/cpuid.pb.h" #include "exegesis/proto/microarchitecture.pb.h" #include "exegesis/proto/x86/cpuid.pb.h" #include "exegesis/util/proto_util.h" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "strings/string_view.h" #include "strings/string_view_utils.h" #include "util/task/status.h" namespace exegesis { namespace { using ::exegesis::util::StatusOr; using ::exegesis::x86::CpuIdDump; using ::testing::UnorderedElementsAreArray; TEST(CpuInfoTest, SupportsFeature) { const CpuInfo cpu_info(ParseProtoFromStringOrDie<CpuInfoProto>(R"( model_id: "doesnotexist" feature_names: "ADX" feature_names: "SSE" feature_names: "LZCNT" )")); EXPECT_TRUE(cpu_info.SupportsFeature("ADX")); EXPECT_TRUE(cpu_info.SupportsFeature("SSE")); EXPECT_TRUE(cpu_info.SupportsFeature("LZCNT")); EXPECT_FALSE(cpu_info.SupportsFeature("AVX")); EXPECT_TRUE(cpu_info.SupportsFeature("ADX || AVX")); EXPECT_FALSE(cpu_info.SupportsFeature("ADX && AVX")); } } // namespace } // namespace exegesis <commit_msg>Removed useless includes and using statements.<commit_after>// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "exegesis/base/cpu_info.h" #include <initializer_list> #include "exegesis/proto/cpuid.pb.h" #include "exegesis/util/proto_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" namespace exegesis { namespace { TEST(CpuInfoTest, SupportsFeature) { const CpuInfo cpu_info(ParseProtoFromStringOrDie<CpuInfoProto>(R"( model_id: "doesnotexist" feature_names: "ADX" feature_names: "SSE" feature_names: "LZCNT" )")); EXPECT_TRUE(cpu_info.SupportsFeature("ADX")); EXPECT_TRUE(cpu_info.SupportsFeature("SSE")); EXPECT_TRUE(cpu_info.SupportsFeature("LZCNT")); EXPECT_FALSE(cpu_info.SupportsFeature("AVX")); EXPECT_TRUE(cpu_info.SupportsFeature("ADX || AVX")); EXPECT_FALSE(cpu_info.SupportsFeature("ADX && AVX")); } } // namespace } // namespace exegesis <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef __FILTER_CONFIG_TYPEDETECTION_HXX_ #define __FILTER_CONFIG_TYPEDETECTION_HXX_ //_______________________________________________ // includes #include "basecontainer.hxx" #include <com/sun/star/document/XTypeDetection.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <comphelper/mediadescriptor.hxx> #include <cppuhelper/implbase1.hxx> //_______________________________________________ // namespace namespace filter{ namespace config{ namespace css = ::com::sun::star; //_______________________________________________ // definitions //_______________________________________________ /** @short implements the service <type scope="com.sun.star.document">TypeDetection</type>. */ class TypeDetection : public ::cppu::ImplInheritanceHelper1< BaseContainer , css::document::XTypeDetection > { //------------------------------------------- // native interface public: //--------------------------------------- // ctor/dtor /** @short standard ctor to connect this interface wrapper to the global filter cache instance ... @param xSMGR reference to the uno service manager, which created this service instance. */ TypeDetection(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); //--------------------------------------- /** @short standard dtor. */ virtual ~TypeDetection(); //------------------------------------------- // private helper private: //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForType(const ::rtl::OUString& sPreSelType, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForFilter(const ::rtl::OUString& sPreSelFilter, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForDocumentService(const ::rtl::OUString& sPreSelDocumentService, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** @short check if a filter or a type was preselected inside the given MediaDescriptor and validate this information. @descr Only in case the preselected filter exists and its type registration seems to be usefully, it would be used realy as valid type detection result. This method doesnt make any deep detection here. It checks only if the preselection match to the URL by an URLPattern. This information has to be added to the given rFlatTypes list too. The outside code can use it to supress a deep detection then in general. Because pattern are defined as non detectable at all! @param pDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed. @param rFlatTypes the preselected type (or the registered type of a preselected filter) will be added here as first(!) element. Further we have to provide the information, if this type match to the given URL by its URLPattern registration. */ void impl_getPreselection(const css::util::URL& aParsedURL , ::comphelper::MediaDescriptor& rDescriptor, FlatDetection& rFlatTypes ); //--------------------------------------- /** @short make a combined flat/deep type detection @descr It steps over all flat detected types (given by the parameter lFlatTypes), try it and search for most suitable one. The specified MediaDescriptor will be patched, so it contain the right values everytime. Using of any deep detection service can be enabled/disabled. And last but not least: If the results wont be realy clear (because a flat detected type has no deep detection service), a "sugested" type name will be returned as "rLastChance". It can be used after e.g. all well known deep detection services was used without getting any result. Then this "last-chance-type" should be returned. Of course using of it can fail too ... but its a try :-) As an optimization - this method collects the names of all used deep detection services. This information can be usefull inside the may be afterwards called method "impl_detectTypeDeepOnly()"! @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed from it. @param lFlatTypes a list of all flat detected types, which should be checked here. No other types are allowed here! @param rLastChance the internal name of a "suggested type" ... (see before) Note: it will be reseted to an empty string everytimes. So a set value of "rLastChance" can be detected outside very easy. @param rUsedDetectors used as [out] parameter. It contains a list of names of all deep detection services, which was used inside this method. Such detectors can be ignored later if "impl_detectTypeDeepOnly()" is called. @param bAllowDeep enable/disable using of a might existing deep detection service. @return The internal name of a detected type. An empty value if detection failed. .... but see rLastChance for additional returns! */ ::rtl::OUString impl_detectTypeFlatAndDeep( ::comphelper::MediaDescriptor& rDescriptor , const FlatDetection& lFlatTypes , sal_Bool bAllowDeep , OUStringList& rUsedDetectors, ::rtl::OUString& rLastChance ); //--------------------------------------- /** @short make a deep type detection only @descr It steps over all well known deep detection services and check her results. The first positive result will be used for return. Its more a "try and error" algorithm then a real type detection and will be used if a flat detection cant work realy ... e.g. if the extension of an URL is missing or wrong. @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed from it. @param rUsedDetectors It contains a list of names of all deep detection services, which was already used inside the method "impl_detectTypeFlatAndDeep()"! Such detectors must be ignored here! @return The internal name of a detected type. An empty value if detection failed. */ ::rtl::OUString impl_detectTypeDeepOnly( ::comphelper::MediaDescriptor& rDescriptor , const OUStringList& rUsedDetectors); //--------------------------------------- /** @short seek a might existing stream to position 0. @descr This is an optinal action to be more robust in case any detect service doesnt make this seek ... Normaly it's part of any called detect service or filter ... but sometimes it's not done there. @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. */ void impl_seekStreamToZero(comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short make deep type detection for a specified detect service (threadsafe!). @descr It creates the right uno service, prepare the needed MediaDescriptor, call ths right interfaces, and return the results. @attention The results (means type and corresponding filter) are already part of the in/out parameter pDescriptor. (in case they was valid). @param sDetectService uno service name of the detect service. @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. */ ::rtl::OUString impl_askDetectService(const ::rtl::OUString& sDetectService, ::comphelper::MediaDescriptor& rDescriptor ); //--------------------------------------- /** @short try to find an interaction handler and ask him to select a possible filter for this unknown format. @descr If the user select a filter, it will be used as return value without further checking against the given file content! @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. @return [string] a valid type name or an empty string if user canceled interaction. */ ::rtl::OUString impl_askUserForTypeAndFilterIfAllowed(::comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short check if an input stream is already part of the given MediaDesciptor and creates a new one if neccessary. @attention This method does further something special! <ul> <li> If the given URL seem to be a streamable content, but creation of the stream failed (might by an IOException), this method throws an exception. (May be an existing interaction handler must be called here too ...) The whole detection must be interrupted then and the interface method queryTypeByDescriptor() must return an empty type name value. That prevent us against multiple handling of the same error more then ones (e.g. if we ask all detect services as fallback ...). </li> <li> In case the stream already exists inside the descriptor this method does nothing. </li> <li> In case the stream does not exists but can be created successfully, the stream will be added to the descriptor. </li> </ul> @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The stream will be added to it. @throw Any suitable exception if stream should be opened but operation was not sucessfull. Note: If an interactionHandler is part of the given descriptor too, it was already used. Means: let the exception pass trough the top most interface method! */ void impl_openStream(::comphelper::MediaDescriptor& rDescriptor) throw (css::uno::Exception); //--------------------------------------- /** @short validate the specified type and its relation ships and set all needed informations related to this type in the specified descriptor. @descr Related informations are: - corresponding filter - media type - ... @param rDescriptor provides access to the outside MediaDescriptor. @param sType the name of the type, which should be set on the descriptor. Can be empty to remove any related value from the descriptor! @return TRUE the specified type and its registrations was valid(!) and could be set on the descriptor. */ sal_Bool impl_validateAndSetTypeOnDescriptor( ::comphelper::MediaDescriptor& rDescriptor, const ::rtl::OUString& sType ); //--------------------------------------- /** @short validate the specified filter and its relation ships and set all needed informations related to this filter in the specified descriptor. @descr Related informations are: - corresponding type - ... @param rDescriptor provides access to the outside MediaDescriptor. @param sFilter the name of the filter, which should be set on the descriptor. Can be empty to remove any related value from the descriptor! @return TRUE the specified type and its registrations was valid(!) and could be set on the descriptor. */ sal_Bool impl_validateAndSetFilterOnDescriptor( ::comphelper::MediaDescriptor& rDescriptor, const ::rtl::OUString& sFilter ); //--------------------------------------- /** @short remove anythimng related to a TYPE/FILTER entry from the specified MediaDescriptor. @descr This method works together with impl_validateAndSetTypeOnDescriptor()/ impl_validateAndSetFilterOnDescriptor(). All informations, which can be set by these two operations must be "removable" by this method. @param rDescriptor reference to the MediaDescriptor (represented by an easy-to-use stl interface!), which should be patched. */ void impl_removeTypeFilterFromDescriptor(::comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short search the best suitable filter for the given type and add it into the media descriptor. @descr Normaly this is a type detection only ... but for some special features we must overwrite our detection because a file must be loaded into a special (means preselected) application. E.g. CSV/TXT format are sometimes ugly to handle .-) Note: If the descriptor already include a filter (may be selected by a FilterSelect interaction or preselected by the user itself) ... we dont change that here ! @param rDescriptor reference to the MediaDescriptor (represented by an easy-to-use stl interface!), which should be patched. @param sType the internal type name, where we search a filter for. Used as IN/OUT parameter so we can overrule the detection result for types too ! @note #i60158# sometimes our text ascii and our csv filter cant work together. Then we overwrite our detection hardly. sType param is used as out parameter then too ... and rDescriptor will be changed by selecting another filter. (see code) */ void impl_checkResultsAndAddBestFilter(::comphelper::MediaDescriptor& rDescriptor, ::rtl::OUString& sType ); //------------------------------------------- // uno interface public: //--------------------------------------- // XTypeDetection virtual ::rtl::OUString SAL_CALL queryTypeByURL(const ::rtl::OUString& sURL) throw (css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL queryTypeByDescriptor(css::uno::Sequence< css::beans::PropertyValue >& lDescriptor, sal_Bool bAllowDeep ) throw (css::uno::RuntimeException); //------------------------------------------- // static uno helper! public: //--------------------------------------- /** @short return the uno implementation name of this class. @descr Because this information is used at several places (and mostly an object instance of this class is not possible) its implemented as a static function! @return The fix uno implementation name of this class. */ static ::rtl::OUString impl_getImplementationName(); //--------------------------------------- /** @short return the list of supported uno services of this class. @descr Because this information is used at several places (and mostly an object instance of this class is not possible) its implemented as a static function! @return The fix list of uno services supported by this class. */ static css::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames(); //--------------------------------------- /** @short return a new intsnace of this class. @descr This method is used by the uno service manager, to create a new instance of this service if needed. @param xSMGR reference to the uno service manager, which require this new instance. It should be passed to the new object so it can be used internaly to create own needed uno resources. @return The new instance of this service as an uno reference. */ static css::uno::Reference< css::uno::XInterface > impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); }; } // namespace config } // namespace filter #endif // __FILTER_CONFIG_TYPEDETECTION_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Reduce indentation.<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef __FILTER_CONFIG_TYPEDETECTION_HXX_ #define __FILTER_CONFIG_TYPEDETECTION_HXX_ //_______________________________________________ // includes #include "basecontainer.hxx" #include <com/sun/star/document/XTypeDetection.hpp> #include <com/sun/star/lang/XSingleServiceFactory.hpp> #include <comphelper/mediadescriptor.hxx> #include <cppuhelper/implbase1.hxx> //_______________________________________________ // namespace namespace filter{ namespace config { namespace css = ::com::sun::star; //_______________________________________________ // definitions //_______________________________________________ /** @short implements the service <type scope="com.sun.star.document">TypeDetection</type>. */ class TypeDetection : public ::cppu::ImplInheritanceHelper1< BaseContainer , css::document::XTypeDetection > { //------------------------------------------- // native interface public: //--------------------------------------- // ctor/dtor /** @short standard ctor to connect this interface wrapper to the global filter cache instance ... @param xSMGR reference to the uno service manager, which created this service instance. */ TypeDetection(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); //--------------------------------------- /** @short standard dtor. */ virtual ~TypeDetection(); //------------------------------------------- // private helper private: //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForType(const ::rtl::OUString& sPreSelType, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForFilter(const ::rtl::OUString& sPreSelFilter, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** TODO document me */ sal_Bool impl_getPreselectionForDocumentService(const ::rtl::OUString& sPreSelDocumentService, const css::util::URL& aParsedURL , FlatDetection& rFlatTypes ); //--------------------------------------- /** @short check if a filter or a type was preselected inside the given MediaDescriptor and validate this information. @descr Only in case the preselected filter exists and its type registration seems to be usefully, it would be used realy as valid type detection result. This method doesnt make any deep detection here. It checks only if the preselection match to the URL by an URLPattern. This information has to be added to the given rFlatTypes list too. The outside code can use it to supress a deep detection then in general. Because pattern are defined as non detectable at all! @param pDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed. @param rFlatTypes the preselected type (or the registered type of a preselected filter) will be added here as first(!) element. Further we have to provide the information, if this type match to the given URL by its URLPattern registration. */ void impl_getPreselection(const css::util::URL& aParsedURL , ::comphelper::MediaDescriptor& rDescriptor, FlatDetection& rFlatTypes ); //--------------------------------------- /** @short make a combined flat/deep type detection @descr It steps over all flat detected types (given by the parameter lFlatTypes), try it and search for most suitable one. The specified MediaDescriptor will be patched, so it contain the right values everytime. Using of any deep detection service can be enabled/disabled. And last but not least: If the results wont be realy clear (because a flat detected type has no deep detection service), a "sugested" type name will be returned as "rLastChance". It can be used after e.g. all well known deep detection services was used without getting any result. Then this "last-chance-type" should be returned. Of course using of it can fail too ... but its a try :-) As an optimization - this method collects the names of all used deep detection services. This information can be usefull inside the may be afterwards called method "impl_detectTypeDeepOnly()"! @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed from it. @param lFlatTypes a list of all flat detected types, which should be checked here. No other types are allowed here! @param rLastChance the internal name of a "suggested type" ... (see before) Note: it will be reseted to an empty string everytimes. So a set value of "rLastChance" can be detected outside very easy. @param rUsedDetectors used as [out] parameter. It contains a list of names of all deep detection services, which was used inside this method. Such detectors can be ignored later if "impl_detectTypeDeepOnly()" is called. @param bAllowDeep enable/disable using of a might existing deep detection service. @return The internal name of a detected type. An empty value if detection failed. .... but see rLastChance for additional returns! */ ::rtl::OUString impl_detectTypeFlatAndDeep( ::comphelper::MediaDescriptor& rDescriptor , const FlatDetection& lFlatTypes , sal_Bool bAllowDeep , OUStringList& rUsedDetectors, ::rtl::OUString& rLastChance ); //--------------------------------------- /** @short make a deep type detection only @descr It steps over all well known deep detection services and check her results. The first positive result will be used for return. Its more a "try and error" algorithm then a real type detection and will be used if a flat detection cant work realy ... e.g. if the extension of an URL is missing or wrong. @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The type/filter entries of it will be actualized or removed from it. @param rUsedDetectors It contains a list of names of all deep detection services, which was already used inside the method "impl_detectTypeFlatAndDeep()"! Such detectors must be ignored here! @return The internal name of a detected type. An empty value if detection failed. */ ::rtl::OUString impl_detectTypeDeepOnly( ::comphelper::MediaDescriptor& rDescriptor , const OUStringList& rUsedDetectors); //--------------------------------------- /** @short seek a might existing stream to position 0. @descr This is an optinal action to be more robust in case any detect service doesnt make this seek ... Normaly it's part of any called detect service or filter ... but sometimes it's not done there. @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. */ void impl_seekStreamToZero(comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short make deep type detection for a specified detect service (threadsafe!). @descr It creates the right uno service, prepare the needed MediaDescriptor, call ths right interfaces, and return the results. @attention The results (means type and corresponding filter) are already part of the in/out parameter pDescriptor. (in case they was valid). @param sDetectService uno service name of the detect service. @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. */ ::rtl::OUString impl_askDetectService(const ::rtl::OUString& sDetectService, ::comphelper::MediaDescriptor& rDescriptor ); //--------------------------------------- /** @short try to find an interaction handler and ask him to select a possible filter for this unknown format. @descr If the user select a filter, it will be used as return value without further checking against the given file content! @param rDescriptor a stl representation of the MediaDescriptor as in/out parameter. @return [string] a valid type name or an empty string if user canceled interaction. */ ::rtl::OUString impl_askUserForTypeAndFilterIfAllowed(::comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short check if an input stream is already part of the given MediaDesciptor and creates a new one if neccessary. @attention This method does further something special! <ul> <li> If the given URL seem to be a streamable content, but creation of the stream failed (might by an IOException), this method throws an exception. (May be an existing interaction handler must be called here too ...) The whole detection must be interrupted then and the interface method queryTypeByDescriptor() must return an empty type name value. That prevent us against multiple handling of the same error more then ones (e.g. if we ask all detect services as fallback ...). </li> <li> In case the stream already exists inside the descriptor this method does nothing. </li> <li> In case the stream does not exists but can be created successfully, the stream will be added to the descriptor. </li> </ul> @param rDescriptor provides any easy-to-use stl interface to the MediaDescriptor. Note : Its content will be adapted to returned result of this method. Means: The stream will be added to it. @throw Any suitable exception if stream should be opened but operation was not sucessfull. Note: If an interactionHandler is part of the given descriptor too, it was already used. Means: let the exception pass trough the top most interface method! */ void impl_openStream(::comphelper::MediaDescriptor& rDescriptor) throw (css::uno::Exception); //--------------------------------------- /** @short validate the specified type and its relation ships and set all needed informations related to this type in the specified descriptor. @descr Related informations are: - corresponding filter - media type - ... @param rDescriptor provides access to the outside MediaDescriptor. @param sType the name of the type, which should be set on the descriptor. Can be empty to remove any related value from the descriptor! @return TRUE the specified type and its registrations was valid(!) and could be set on the descriptor. */ sal_Bool impl_validateAndSetTypeOnDescriptor( ::comphelper::MediaDescriptor& rDescriptor, const ::rtl::OUString& sType ); //--------------------------------------- /** @short validate the specified filter and its relation ships and set all needed informations related to this filter in the specified descriptor. @descr Related informations are: - corresponding type - ... @param rDescriptor provides access to the outside MediaDescriptor. @param sFilter the name of the filter, which should be set on the descriptor. Can be empty to remove any related value from the descriptor! @return TRUE the specified type and its registrations was valid(!) and could be set on the descriptor. */ sal_Bool impl_validateAndSetFilterOnDescriptor( ::comphelper::MediaDescriptor& rDescriptor, const ::rtl::OUString& sFilter ); //--------------------------------------- /** @short remove anythimng related to a TYPE/FILTER entry from the specified MediaDescriptor. @descr This method works together with impl_validateAndSetTypeOnDescriptor()/ impl_validateAndSetFilterOnDescriptor(). All informations, which can be set by these two operations must be "removable" by this method. @param rDescriptor reference to the MediaDescriptor (represented by an easy-to-use stl interface!), which should be patched. */ void impl_removeTypeFilterFromDescriptor(::comphelper::MediaDescriptor& rDescriptor); //--------------------------------------- /** @short search the best suitable filter for the given type and add it into the media descriptor. @descr Normaly this is a type detection only ... but for some special features we must overwrite our detection because a file must be loaded into a special (means preselected) application. E.g. CSV/TXT format are sometimes ugly to handle .-) Note: If the descriptor already include a filter (may be selected by a FilterSelect interaction or preselected by the user itself) ... we dont change that here ! @param rDescriptor reference to the MediaDescriptor (represented by an easy-to-use stl interface!), which should be patched. @param sType the internal type name, where we search a filter for. Used as IN/OUT parameter so we can overrule the detection result for types too ! @note #i60158# sometimes our text ascii and our csv filter cant work together. Then we overwrite our detection hardly. sType param is used as out parameter then too ... and rDescriptor will be changed by selecting another filter. (see code) */ void impl_checkResultsAndAddBestFilter(::comphelper::MediaDescriptor& rDescriptor, ::rtl::OUString& sType ); //------------------------------------------- // uno interface public: //--------------------------------------- // XTypeDetection virtual ::rtl::OUString SAL_CALL queryTypeByURL(const ::rtl::OUString& sURL) throw (css::uno::RuntimeException); virtual ::rtl::OUString SAL_CALL queryTypeByDescriptor(css::uno::Sequence< css::beans::PropertyValue >& lDescriptor, sal_Bool bAllowDeep ) throw (css::uno::RuntimeException); //------------------------------------------- // static uno helper! public: //--------------------------------------- /** @short return the uno implementation name of this class. @descr Because this information is used at several places (and mostly an object instance of this class is not possible) its implemented as a static function! @return The fix uno implementation name of this class. */ static ::rtl::OUString impl_getImplementationName(); //--------------------------------------- /** @short return the list of supported uno services of this class. @descr Because this information is used at several places (and mostly an object instance of this class is not possible) its implemented as a static function! @return The fix list of uno services supported by this class. */ static css::uno::Sequence< ::rtl::OUString > impl_getSupportedServiceNames(); //--------------------------------------- /** @short return a new intsnace of this class. @descr This method is used by the uno service manager, to create a new instance of this service if needed. @param xSMGR reference to the uno service manager, which require this new instance. It should be passed to the new object so it can be used internaly to create own needed uno resources. @return The new instance of this service as an uno reference. */ static css::uno::Reference< css::uno::XInterface > impl_createInstance(const css::uno::Reference< css::lang::XMultiServiceFactory >& xSMGR); }; }} #endif // __FILTER_CONFIG_TYPEDETECTION_HXX_ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before>#include "StableHeaders.h" #include "Framework.h" #include "EventDataInterface.h" #include "EventManager.h" #include "ModuleManager.h" #include "Poco/DOM/DOMParser.h" #include "Poco/DOM/Element.h" #include "Poco/DOM/Attr.h" #include "Poco/DOM/NamedNodeMap.h" #include "Poco/SAX/InputSource.h" #include <algorithm> namespace Foundation { EventManager::EventManager(Framework *framework) : framework_(framework), next_category_id_(1), event_subscriber_root_(EventSubscriberPtr(new EventSubscriber())) { } EventManager::~EventManager() { event_subscriber_root_.reset(); } Core::event_category_id_t EventManager::RegisterEventCategory(const std::string& name) { if (event_category_map_.find(name) == event_category_map_.end()) { event_category_map_[name] = next_category_id_; next_category_id_++; } else { Foundation::RootLogWarning("Event category " + name + " is already registered"); } return event_category_map_[name]; } Core::event_category_id_t EventManager::QueryEventCategory(const std::string& name) const { EventCategoryMap::const_iterator i = event_category_map_.find(name); if (i != event_category_map_.end()) return i->second; else return 0; } const std::string& EventManager::QueryEventCategoryName(Core::event_category_id_t id) const { EventCategoryMap::const_iterator i = event_category_map_.begin(); static std::string empty; while (i != event_category_map_.end()) { if (i->second == id) return i->first; ++i; } return empty; } void EventManager::SendEvent(Core::event_category_id_t category_id, Core::event_id_t event_id, EventDataInterface* data) const { SendEvent(event_subscriber_root_.get(), category_id, event_id, data); } bool EventManager::SendEvent(EventSubscriber* node, Core::event_category_id_t category_id, Core::event_id_t event_id, EventDataInterface* data) const { if (node->module_) { if (node->module_->HandleEvent(category_id, event_id, data)) return true; } EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { if (SendEvent((*i).get(), category_id, event_id, data)) return true; ++i; } return false; } bool ComparePriority(EventManager::EventSubscriberPtr const& e1, EventManager::EventSubscriberPtr const& e2) { return e1.get()->priority_ < e2.get()->priority_; } bool EventManager::RegisterEventSubscriber(ModuleInterface* module, int priority, ModuleInterface* parent) { assert (module); if (FindNodeWithModule(event_subscriber_root_.get(), module)) { Foundation::RootLogWarning(module->Name() + " is already added as event subscriber"); return false; } EventSubscriber* node = FindNodeWithModule(event_subscriber_root_.get(), parent); if (!node) { if (parent) Foundation::RootLogWarning("Could not add module " + module->Name() + " as event subscriber, parent module " + parent->Name() + " not found"); return false; } EventSubscriberPtr new_node = EventSubscriberPtr(new EventSubscriber()); new_node->module_ = module; new_node->priority_ = priority; node->children_.push_back(new_node); std::sort(node->children_.rbegin(), node->children_.rend(), ComparePriority); return true; } bool EventManager::UnregisterEventSubscriber(ModuleInterface* module) { assert (module); EventSubscriber* node = FindNodeWithChild(event_subscriber_root_.get(), module); if (!node) { Foundation::RootLogWarning("Could not remove event subscriber " + module->Name() + ", not found"); return false; } EventSubscriberVector::iterator i = node->children_.begin(); while (i != node->children_.end()) { if ((*i)->module_ == module) { node->children_.erase(i); return true; } ++i; } return false; // should not happen } bool EventManager::HasEventSubscriber(ModuleInterface* module) { assert (module); return (FindNodeWithChild(event_subscriber_root_.get(), module) != NULL); } EventManager::EventSubscriber* EventManager::FindNodeWithModule(EventSubscriber* node, ModuleInterface* module) const { if (node->module_ == module) return node; EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { EventSubscriber* result = FindNodeWithModule((*i).get(), module); if (result) return result; ++i; } return 0; } EventManager::EventSubscriber* EventManager::FindNodeWithChild(EventSubscriber* node, ModuleInterface* module) const { EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { if ((*i)->module_ == module) return node; EventSubscriber* result = FindNodeWithChild((*i).get(), module); if (result) return result; ++i; } return 0; } void EventManager::LoadEventSubscriberTree(const std::string& filename) { Foundation::RootLogInfo("Loading event subscriber tree from " + filename); try { Poco::XML::InputSource source(filename); Poco::XML::DOMParser parser; Poco::XML::Document* document = parser.parse(&source); Poco::XML::Node* node = document->firstChild(); if (node) { BuildTreeFromNode(node, ""); } } catch (Poco::Exception& e) { Foundation::RootLogError("Could not load event subscriber tree from " + filename + ": " + e.what()); } } void EventManager::BuildTreeFromNode(Poco::XML::Node* node, const std::string parent_name) { while (node) { std::string new_parent_name = parent_name; Poco::XML::NamedNodeMap* attributes = node->attributes(); if (attributes) { Poco::XML::Attr* module_attr = static_cast<Poco::XML::Attr*>(attributes->getNamedItem("module")); Poco::XML::Attr* priority_attr = static_cast<Poco::XML::Attr*>(attributes->getNamedItem("priority")); if ((module_attr) && (priority_attr)) { const std::string& module_name = module_attr->getValue(); int priority = boost::lexical_cast<int>(priority_attr->getValue()); new_parent_name = module_name; ModuleInterface* module = framework_->GetModuleManager()->GetModule(module_name); if (module) { if (parent_name.empty()) { RegisterEventSubscriber(module, priority, NULL); } else { ModuleInterface* parent = framework_->GetModuleManager()->GetModule(parent_name); if (parent) { RegisterEventSubscriber(module, priority, parent); } else { Foundation::RootLogWarning("Parent module " + parent_name + " not found for module " + module_name); } } } else { Foundation::RootLogWarning("Module " + module_name + " not found"); } } } if (node->firstChild()) { BuildTreeFromNode(node->firstChild(), new_parent_name); } node = node->nextSibling(); } } }<commit_msg>Fixed EventManager memory leak.<commit_after>#include "StableHeaders.h" #include "Framework.h" #include "EventDataInterface.h" #include "EventManager.h" #include "ModuleManager.h" #include "Poco/DOM/DOMParser.h" #include "Poco/DOM/Element.h" #include "Poco/DOM/Attr.h" #include "Poco/DOM/NamedNodeMap.h" #include "Poco/DOM/AutoPtr.h" #include "Poco/SAX/InputSource.h" #include <algorithm> namespace Foundation { EventManager::EventManager(Framework *framework) : framework_(framework), next_category_id_(1), event_subscriber_root_(EventSubscriberPtr(new EventSubscriber())) { } EventManager::~EventManager() { event_subscriber_root_.reset(); } Core::event_category_id_t EventManager::RegisterEventCategory(const std::string& name) { if (event_category_map_.find(name) == event_category_map_.end()) { event_category_map_[name] = next_category_id_; next_category_id_++; } else { Foundation::RootLogWarning("Event category " + name + " is already registered"); } return event_category_map_[name]; } Core::event_category_id_t EventManager::QueryEventCategory(const std::string& name) const { EventCategoryMap::const_iterator i = event_category_map_.find(name); if (i != event_category_map_.end()) return i->second; else return 0; } const std::string& EventManager::QueryEventCategoryName(Core::event_category_id_t id) const { EventCategoryMap::const_iterator i = event_category_map_.begin(); static std::string empty; while (i != event_category_map_.end()) { if (i->second == id) return i->first; ++i; } return empty; } void EventManager::SendEvent(Core::event_category_id_t category_id, Core::event_id_t event_id, EventDataInterface* data) const { SendEvent(event_subscriber_root_.get(), category_id, event_id, data); } bool EventManager::SendEvent(EventSubscriber* node, Core::event_category_id_t category_id, Core::event_id_t event_id, EventDataInterface* data) const { if (node->module_) { if (node->module_->HandleEvent(category_id, event_id, data)) return true; } EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { if (SendEvent((*i).get(), category_id, event_id, data)) return true; ++i; } return false; } bool ComparePriority(EventManager::EventSubscriberPtr const& e1, EventManager::EventSubscriberPtr const& e2) { return e1.get()->priority_ < e2.get()->priority_; } bool EventManager::RegisterEventSubscriber(ModuleInterface* module, int priority, ModuleInterface* parent) { assert (module); if (FindNodeWithModule(event_subscriber_root_.get(), module)) { Foundation::RootLogWarning(module->Name() + " is already added as event subscriber"); return false; } EventSubscriber* node = FindNodeWithModule(event_subscriber_root_.get(), parent); if (!node) { if (parent) Foundation::RootLogWarning("Could not add module " + module->Name() + " as event subscriber, parent module " + parent->Name() + " not found"); return false; } EventSubscriberPtr new_node = EventSubscriberPtr(new EventSubscriber()); new_node->module_ = module; new_node->priority_ = priority; node->children_.push_back(new_node); std::sort(node->children_.rbegin(), node->children_.rend(), ComparePriority); return true; } bool EventManager::UnregisterEventSubscriber(ModuleInterface* module) { assert (module); EventSubscriber* node = FindNodeWithChild(event_subscriber_root_.get(), module); if (!node) { Foundation::RootLogWarning("Could not remove event subscriber " + module->Name() + ", not found"); return false; } EventSubscriberVector::iterator i = node->children_.begin(); while (i != node->children_.end()) { if ((*i)->module_ == module) { node->children_.erase(i); return true; } ++i; } return false; // should not happen } bool EventManager::HasEventSubscriber(ModuleInterface* module) { assert (module); return (FindNodeWithChild(event_subscriber_root_.get(), module) != NULL); } EventManager::EventSubscriber* EventManager::FindNodeWithModule(EventSubscriber* node, ModuleInterface* module) const { if (node->module_ == module) return node; EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { EventSubscriber* result = FindNodeWithModule((*i).get(), module); if (result) return result; ++i; } return 0; } EventManager::EventSubscriber* EventManager::FindNodeWithChild(EventSubscriber* node, ModuleInterface* module) const { EventSubscriberVector::const_iterator i = node->children_.begin(); while (i != node->children_.end()) { if ((*i)->module_ == module) return node; EventSubscriber* result = FindNodeWithChild((*i).get(), module); if (result) return result; ++i; } return 0; } void EventManager::LoadEventSubscriberTree(const std::string& filename) { Foundation::RootLogInfo("Loading event subscriber tree from " + filename); try { Poco::XML::InputSource source(filename); Poco::XML::DOMParser parser; Poco::XML::AutoPtr<Poco::XML::Document> document = parser.parse(&source); if (!document.isNull()) { Poco::XML::Node* node = document->firstChild(); if (node) { BuildTreeFromNode(node, ""); } } else { Foundation::RootLogError("Could not load event subscriber tree from " + filename); } } catch (Poco::Exception& e) { Foundation::RootLogError("Could not load event subscriber tree from " + filename + ": " + e.what()); } } void EventManager::BuildTreeFromNode(Poco::XML::Node* node, const std::string parent_name) { while (node) { std::string new_parent_name = parent_name; Poco::XML::AutoPtr<Poco::XML::NamedNodeMap> attributes = node->attributes(); if (!attributes.isNull()) { Poco::XML::Attr* module_attr = static_cast<Poco::XML::Attr*>(attributes->getNamedItem("module")); Poco::XML::Attr* priority_attr = static_cast<Poco::XML::Attr*>(attributes->getNamedItem("priority")); if ((module_attr) && (priority_attr)) { const std::string& module_name = module_attr->getValue(); int priority = boost::lexical_cast<int>(priority_attr->getValue()); new_parent_name = module_name; ModuleInterface* module = framework_->GetModuleManager()->GetModule(module_name); if (module) { if (parent_name.empty()) { RegisterEventSubscriber(module, priority, NULL); } else { ModuleInterface* parent = framework_->GetModuleManager()->GetModule(parent_name); if (parent) { RegisterEventSubscriber(module, priority, parent); } else { Foundation::RootLogWarning("Parent module " + parent_name + " not found for module " + module_name); } } } else { Foundation::RootLogWarning("Module " + module_name + " not found"); } } } if (node->firstChild()) { BuildTreeFromNode(node->firstChild(), new_parent_name); } node = node->nextSibling(); } } }<|endoftext|>
<commit_before>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation // NMatrix is Copyright (c) 2012, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == common.cpp // // Code for the STORAGE struct that is common to all storage types. /* * Standard Includes */ /* * Project Includes */ #include "common.h" /* * Macros */ /* * Global Variables */ /* * Forward Declarations */ /* * Functions */ /* * Calculate the number of elements in the dense storage structure, based on * shape and rank. */ size_t storage_count_max_elements(const STORAGE* storage) { unsigned int i; size_t count = 1; for (i = storage->rank; i-- > 0;) { count *= storage->shape[i]; } return count; } <commit_msg>Inconsequential spacing change that I'm committing just to get it out of the modified list.<commit_after>///////////////////////////////////////////////////////////////////// // = NMatrix // // A linear algebra library for scientific computation in Ruby. // NMatrix is part of SciRuby. // // NMatrix was originally inspired by and derived from NArray, by // Masahiro Tanaka: http://narray.rubyforge.org // // == Copyright Information // // SciRuby is Copyright (c) 2010 - 2012, Ruby Science Foundation // NMatrix is Copyright (c) 2012, Ruby Science Foundation // // Please see LICENSE.txt for additional copyright notices. // // == Contributing // // By contributing source code to SciRuby, you agree to be bound by // our Contributor Agreement: // // * https://github.com/SciRuby/sciruby/wiki/Contributor-Agreement // // == common.cpp // // Code for the STORAGE struct that is common to all storage types. /* * Standard Includes */ /* * Project Includes */ #include "common.h" /* * Macros */ /* * Global Variables */ /* * Forward Declarations */ /* * Functions */ /* * Calculate the number of elements in the dense storage structure, based on * shape and rank. */ size_t storage_count_max_elements(const STORAGE* storage) { unsigned int i; size_t count = 1; for (i = storage->rank; i-- > 0;) { count *= storage->shape[i]; } return count; } <|endoftext|>
<commit_before>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ============================================================ // // ApplicationContext.cpp // // // Implements the ApplicationContext class // // ============================================================ #ifndef FEATURE_CORESYSTEM #define DISABLE_BINDER_DEBUG_LOGGING #endif #include "applicationcontext.hpp" #include "stringarraylist.h" #include "loadcontext.hpp" #include "propertymap.hpp" #include "failurecache.hpp" #include "assemblyidentitycache.hpp" #ifdef FEATURE_VERSIONING_LOG #include "debuglog.hpp" #endif // FEATURE_VERSIONING_LOG #include "utils.hpp" #include "variables.hpp" #include "ex.h" namespace BINDER_SPACE { STDMETHODIMP ApplicationContext::QueryInterface(REFIID riid, void **ppv) { HRESULT hr = S_OK; if (ppv == NULL) { hr = E_POINTER; } else { if (IsEqualIID(riid, IID_IUnknown)) { AddRef(); *ppv = static_cast<IUnknown *>(this); } else { *ppv = NULL; hr = E_NOINTERFACE; } } return hr; } STDMETHODIMP_(ULONG) ApplicationContext::AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) ApplicationContext::Release() { ULONG ulRef = InterlockedDecrement(&m_cRef); if (ulRef == 0) { delete this; } return ulRef; } ApplicationContext::ApplicationContext() { m_cRef = 1; m_dwAppDomainId = 0; m_pExecutionContext = NULL; m_pInspectionContext = NULL; m_pFailureCache = NULL; m_contextCS = NULL; m_pTrustedPlatformAssemblyMap = nullptr; m_pFileNameHash = nullptr; } ApplicationContext::~ApplicationContext() { SAFE_RELEASE(m_pExecutionContext); SAFE_RELEASE(m_pInspectionContext); SAFE_DELETE(m_pFailureCache); if (m_contextCS != NULL) { ClrDeleteCriticalSection(m_contextCS); } if (m_pTrustedPlatformAssemblyMap != nullptr) { delete m_pTrustedPlatformAssemblyMap; } if (m_pFileNameHash != nullptr) { delete m_pFileNameHash; } } HRESULT ApplicationContext::Init() { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::Init")); BINDER_LOG_POINTER(W("this"), this); ReleaseHolder<ExecutionContext> pExecutionContext; ReleaseHolder<InspectionContext> pInspectionContext; PropertyMap *pPropertyMap = NULL; FailureCache *pFailureCache = NULL; // Allocate context objects SAFE_NEW(pExecutionContext, ExecutionContext); SAFE_NEW(pInspectionContext, InspectionContext); SAFE_NEW(pFailureCache, FailureCache); m_contextCS = ClrCreateCriticalSection( CrstFusionAppCtx, CRST_REENTRANCY); if (!m_contextCS) { SAFE_DELETE(pPropertyMap); SAFE_DELETE(pFailureCache); hr = E_OUTOFMEMORY; } else { m_pExecutionContext = pExecutionContext.Extract(); m_pInspectionContext = pInspectionContext.Extract(); m_pFailureCache = pFailureCache; } #if defined(FEATURE_HOST_ASSEMBLY_RESOLVER) m_fCanExplicitlyBindToNativeImages = false; #endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER) Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::Init"), hr); return hr; } HRESULT GetNextPath(SString& paths, SString::Iterator& startPos, SString& outPath) { HRESULT hr = S_OK; bool wrappedWithQuotes = false; // Skip any leading spaces or path separators while (paths.Skip(startPos, W(' ')) || paths.Skip(startPos, PATH_SEPARATOR_CHAR_W)) {} if (startPos == paths.End()) { // No more paths in the string and we just skipped over some white space outPath.Set(W("")); return S_FALSE; } // Support paths being wrapped with quotations if (paths.Skip(startPos, W('\"'))) { wrappedWithQuotes = true; } SString::Iterator iEnd = startPos; // Where current path ends SString::Iterator iNext; // Where next path starts if (wrappedWithQuotes) { if (paths.Find(iEnd, W('\"'))) { iNext = iEnd; // Find where the next path starts - there should be a path separator right after the closing quotation mark if (paths.Find(iNext, PATH_SEPARATOR_CHAR_W)) { iNext++; } else { iNext = paths.End(); } } else { // There was no terminating quotation mark - that's bad GO_WITH_HRESULT(E_INVALIDARG); } } else if (paths.Find(iEnd, PATH_SEPARATOR_CHAR_W)) { iNext = iEnd + 1; } else { iNext = iEnd = paths.End(); } // Skip any trailing spaces while (iEnd[-1] == W(' ')) { iEnd--; } _ASSERTE(startPos < iEnd); outPath.Set(paths, startPos, iEnd); startPos = iNext; Exit: return hr; } HRESULT ApplicationContext::SetupBindingPaths(SString &sTrustedPlatformAssemblies, SString &sPlatformResourceRoots, SString &sAppPaths, SString &sAppNiPaths, BOOL fAcquireLock) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::SetupBindingPaths")); BINDER_LOG_POINTER(W("this"), this); #ifndef CROSSGEN_COMPILE CRITSEC_Holder contextLock(fAcquireLock ? GetCriticalSectionCookie() : NULL); #endif if (m_pTrustedPlatformAssemblyMap != nullptr) { #if defined(BINDER_DEBUG_LOG) BINDER_LOG(W("ApplicationContext::SetupBindingPaths: Binding paths already setup")); #endif // BINDER_LOG_STRING GO_WITH_HRESULT(S_OK); } // // Parse TrustedPlatformAssemblies // m_pTrustedPlatformAssemblyMap = new SimpleNameToFileNameMap(); m_pFileNameHash = new TpaFileNameHash(); sTrustedPlatformAssemblies.Normalize(); for (SString::Iterator i = sTrustedPlatformAssemblies.Begin(); i != sTrustedPlatformAssemblies.End(); ) { SString fileName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sTrustedPlatformAssemblies, i, fileName)); if (pathResult == S_FALSE) { break; } // Find the beginning of the simple name SString::Iterator iSimpleNameStart = fileName.End(); if (!fileName.FindBack(iSimpleNameStart, DIRECTORY_SEPARATOR_CHAR_W)) { // Couldn't find a directory separator. File must have been specified as a relative path. Not allowed. GO_WITH_HRESULT(E_INVALIDARG); } if (iSimpleNameStart == fileName.End()) { GO_WITH_HRESULT(E_INVALIDARG); } // Advance past the directory separator to the first character of the file name iSimpleNameStart++; SString simpleName; bool isNativeImage = false; // GCC complains if we create SStrings inline as part of a function call SString sNiDll(W(".ni.dll")); SString sNiExe(W(".ni.exe")); SString sNiWinmd(W(".ni.winmd")); SString sDll(W(".dll")); SString sExe(W(".exe")); SString sWinmd(W(".winmd")); if (fileName.EndsWithCaseInsensitive(sNiDll) || fileName.EndsWithCaseInsensitive(sNiExe)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 7); isNativeImage = true; } else if (fileName.EndsWithCaseInsensitive(sNiWinmd)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 9); isNativeImage = true; } else if (fileName.EndsWithCaseInsensitive(sDll) || fileName.EndsWithCaseInsensitive(sExe)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 4); } else if (fileName.EndsWithCaseInsensitive(sWinmd)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 6); } else { // Invalid filename GO_WITH_HRESULT(E_INVALIDARG); } const SimpleNameToFileNameMapEntry *pExistingEntry = m_pTrustedPlatformAssemblyMap->LookupPtr(simpleName.GetUnicode()); if (pExistingEntry != nullptr) { // // We want to store only the first entry matching a simple name we encounter. // The exception is if we first store an IL reference and later in the string // we encounter a native image. Since we don't touch IL in the presence of // native images, we replace the IL entry with the NI. // if ((pExistingEntry->m_wszILFileName != nullptr && !isNativeImage) || (pExistingEntry->m_wszNIFileName != nullptr && isNativeImage)) { BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Skipping TPA entry because of already existing IL/NI entry for short name "), fileName.GetUnicode()); continue; } } LPWSTR wszSimpleName = nullptr; if (pExistingEntry == nullptr) { wszSimpleName = new WCHAR[simpleName.GetCount() + 1]; if (wszSimpleName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszSimpleName, simpleName.GetCount() + 1, simpleName.GetUnicode()); } else { wszSimpleName = pExistingEntry->m_wszSimpleName; } LPWSTR wszFileName = new WCHAR[fileName.GetCount() + 1]; if (wszFileName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszFileName, fileName.GetCount() + 1, fileName.GetUnicode()); SimpleNameToFileNameMapEntry mapEntry; mapEntry.m_wszSimpleName = wszSimpleName; if (isNativeImage) { mapEntry.m_wszNIFileName = wszFileName; mapEntry.m_wszILFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszILFileName; } else { mapEntry.m_wszILFileName = wszFileName; mapEntry.m_wszNIFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszNIFileName; } m_pTrustedPlatformAssemblyMap->AddOrReplace(mapEntry); FileNameMapEntry fileNameExistenceEntry; fileNameExistenceEntry.m_wszFileName = wszFileName; m_pFileNameHash->AddOrReplace(fileNameExistenceEntry); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added TPA entry"), wszFileName); } // // Parse PlatformResourceRoots // sPlatformResourceRoots.Normalize(); for (SString::Iterator i = sPlatformResourceRoots.Begin(); i != sPlatformResourceRoots.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sPlatformResourceRoots, i, pathName)); if (pathResult == S_FALSE) { break; } m_platformResourceRoots.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added resource root"), pathName); } // // Parse AppPaths // sAppPaths.Normalize(); for (SString::Iterator i = sAppPaths.Begin(); i != sAppPaths.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sAppPaths, i, pathName)); if (pathResult == S_FALSE) { break; } m_appPaths.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added App Path"), pathName); } // // Parse AppNiPaths // sAppNiPaths.Normalize(); for (SString::Iterator i = sAppNiPaths.Begin(); i != sAppNiPaths.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sAppNiPaths, i, pathName)); if (pathResult == S_FALSE) { break; } m_appNiPaths.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added App NI Path"), pathName); } Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::SetupBindingPaths"), hr); return hr; } HRESULT ApplicationContext::GetAssemblyIdentity(LPCSTR szTextualIdentity, AssemblyIdentityUTF8 **ppAssemblyIdentity) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::GetAssemblyIdentity")); BINDER_LOG_POINTER(W("this"), this); _ASSERTE(szTextualIdentity != NULL); _ASSERTE(ppAssemblyIdentity != NULL); CRITSEC_Holder contextLock(GetCriticalSectionCookie()); AssemblyIdentityUTF8 *pAssemblyIdentity = m_assemblyIdentityCache.Lookup(szTextualIdentity); if (pAssemblyIdentity == NULL) { NewHolder<AssemblyIdentityUTF8> pNewAssemblyIdentity; SString sTextualIdentity; SAFE_NEW(pNewAssemblyIdentity, AssemblyIdentityUTF8); sTextualIdentity.SetUTF8(szTextualIdentity); IF_FAIL_GO(TextualIdentityParser::Parse(sTextualIdentity, pNewAssemblyIdentity)); IF_FAIL_GO(m_assemblyIdentityCache.Add(szTextualIdentity, pNewAssemblyIdentity)); pNewAssemblyIdentity->PopulateUTF8Fields(); pAssemblyIdentity = pNewAssemblyIdentity.Extract(); } *ppAssemblyIdentity = pAssemblyIdentity; Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::GetAssemblyIdentity"), hr); return hr; } bool ApplicationContext::IsTpaListProvided() { return m_pTrustedPlatformAssemblyMap != nullptr; } }; <commit_msg>Fix crossgen /createpdb when input filename is given without path (#5045)<commit_after>// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ============================================================ // // ApplicationContext.cpp // // // Implements the ApplicationContext class // // ============================================================ #ifndef FEATURE_CORESYSTEM #define DISABLE_BINDER_DEBUG_LOGGING #endif #include "applicationcontext.hpp" #include "stringarraylist.h" #include "loadcontext.hpp" #include "propertymap.hpp" #include "failurecache.hpp" #include "assemblyidentitycache.hpp" #ifdef FEATURE_VERSIONING_LOG #include "debuglog.hpp" #endif // FEATURE_VERSIONING_LOG #include "utils.hpp" #include "variables.hpp" #include "ex.h" namespace BINDER_SPACE { STDMETHODIMP ApplicationContext::QueryInterface(REFIID riid, void **ppv) { HRESULT hr = S_OK; if (ppv == NULL) { hr = E_POINTER; } else { if (IsEqualIID(riid, IID_IUnknown)) { AddRef(); *ppv = static_cast<IUnknown *>(this); } else { *ppv = NULL; hr = E_NOINTERFACE; } } return hr; } STDMETHODIMP_(ULONG) ApplicationContext::AddRef() { return InterlockedIncrement(&m_cRef); } STDMETHODIMP_(ULONG) ApplicationContext::Release() { ULONG ulRef = InterlockedDecrement(&m_cRef); if (ulRef == 0) { delete this; } return ulRef; } ApplicationContext::ApplicationContext() { m_cRef = 1; m_dwAppDomainId = 0; m_pExecutionContext = NULL; m_pInspectionContext = NULL; m_pFailureCache = NULL; m_contextCS = NULL; m_pTrustedPlatformAssemblyMap = nullptr; m_pFileNameHash = nullptr; } ApplicationContext::~ApplicationContext() { SAFE_RELEASE(m_pExecutionContext); SAFE_RELEASE(m_pInspectionContext); SAFE_DELETE(m_pFailureCache); if (m_contextCS != NULL) { ClrDeleteCriticalSection(m_contextCS); } if (m_pTrustedPlatformAssemblyMap != nullptr) { delete m_pTrustedPlatformAssemblyMap; } if (m_pFileNameHash != nullptr) { delete m_pFileNameHash; } } HRESULT ApplicationContext::Init() { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::Init")); BINDER_LOG_POINTER(W("this"), this); ReleaseHolder<ExecutionContext> pExecutionContext; ReleaseHolder<InspectionContext> pInspectionContext; PropertyMap *pPropertyMap = NULL; FailureCache *pFailureCache = NULL; // Allocate context objects SAFE_NEW(pExecutionContext, ExecutionContext); SAFE_NEW(pInspectionContext, InspectionContext); SAFE_NEW(pFailureCache, FailureCache); m_contextCS = ClrCreateCriticalSection( CrstFusionAppCtx, CRST_REENTRANCY); if (!m_contextCS) { SAFE_DELETE(pPropertyMap); SAFE_DELETE(pFailureCache); hr = E_OUTOFMEMORY; } else { m_pExecutionContext = pExecutionContext.Extract(); m_pInspectionContext = pInspectionContext.Extract(); m_pFailureCache = pFailureCache; } #if defined(FEATURE_HOST_ASSEMBLY_RESOLVER) m_fCanExplicitlyBindToNativeImages = false; #endif // defined(FEATURE_HOST_ASSEMBLY_RESOLVER) Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::Init"), hr); return hr; } HRESULT GetNextPath(SString& paths, SString::Iterator& startPos, SString& outPath) { HRESULT hr = S_OK; bool wrappedWithQuotes = false; // Skip any leading spaces or path separators while (paths.Skip(startPos, W(' ')) || paths.Skip(startPos, PATH_SEPARATOR_CHAR_W)) {} if (startPos == paths.End()) { // No more paths in the string and we just skipped over some white space outPath.Set(W("")); return S_FALSE; } // Support paths being wrapped with quotations if (paths.Skip(startPos, W('\"'))) { wrappedWithQuotes = true; } SString::Iterator iEnd = startPos; // Where current path ends SString::Iterator iNext; // Where next path starts if (wrappedWithQuotes) { if (paths.Find(iEnd, W('\"'))) { iNext = iEnd; // Find where the next path starts - there should be a path separator right after the closing quotation mark if (paths.Find(iNext, PATH_SEPARATOR_CHAR_W)) { iNext++; } else { iNext = paths.End(); } } else { // There was no terminating quotation mark - that's bad GO_WITH_HRESULT(E_INVALIDARG); } } else if (paths.Find(iEnd, PATH_SEPARATOR_CHAR_W)) { iNext = iEnd + 1; } else { iNext = iEnd = paths.End(); } // Skip any trailing spaces while (iEnd[-1] == W(' ')) { iEnd--; } _ASSERTE(startPos < iEnd); outPath.Set(paths, startPos, iEnd); startPos = iNext; Exit: return hr; } HRESULT ApplicationContext::SetupBindingPaths(SString &sTrustedPlatformAssemblies, SString &sPlatformResourceRoots, SString &sAppPaths, SString &sAppNiPaths, BOOL fAcquireLock) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::SetupBindingPaths")); BINDER_LOG_POINTER(W("this"), this); #ifndef CROSSGEN_COMPILE CRITSEC_Holder contextLock(fAcquireLock ? GetCriticalSectionCookie() : NULL); #endif if (m_pTrustedPlatformAssemblyMap != nullptr) { #if defined(BINDER_DEBUG_LOG) BINDER_LOG(W("ApplicationContext::SetupBindingPaths: Binding paths already setup")); #endif // BINDER_LOG_STRING GO_WITH_HRESULT(S_OK); } // // Parse TrustedPlatformAssemblies // m_pTrustedPlatformAssemblyMap = new SimpleNameToFileNameMap(); m_pFileNameHash = new TpaFileNameHash(); sTrustedPlatformAssemblies.Normalize(); for (SString::Iterator i = sTrustedPlatformAssemblies.Begin(); i != sTrustedPlatformAssemblies.End(); ) { SString fileName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sTrustedPlatformAssemblies, i, fileName)); if (pathResult == S_FALSE) { break; } // Find the beginning of the simple name SString::Iterator iSimpleNameStart = fileName.End(); if (!fileName.FindBack(iSimpleNameStart, DIRECTORY_SEPARATOR_CHAR_W)) { #ifdef CROSSGEN_COMPILE iSimpleNameStart = fileName.Begin(); #else // Couldn't find a directory separator. File must have been specified as a relative path. Not allowed. GO_WITH_HRESULT(E_INVALIDARG); #endif } else { // Advance past the directory separator to the first character of the file name iSimpleNameStart++; } if (iSimpleNameStart == fileName.End()) { GO_WITH_HRESULT(E_INVALIDARG); } SString simpleName; bool isNativeImage = false; // GCC complains if we create SStrings inline as part of a function call SString sNiDll(W(".ni.dll")); SString sNiExe(W(".ni.exe")); SString sNiWinmd(W(".ni.winmd")); SString sDll(W(".dll")); SString sExe(W(".exe")); SString sWinmd(W(".winmd")); if (fileName.EndsWithCaseInsensitive(sNiDll) || fileName.EndsWithCaseInsensitive(sNiExe)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 7); isNativeImage = true; } else if (fileName.EndsWithCaseInsensitive(sNiWinmd)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 9); isNativeImage = true; } else if (fileName.EndsWithCaseInsensitive(sDll) || fileName.EndsWithCaseInsensitive(sExe)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 4); } else if (fileName.EndsWithCaseInsensitive(sWinmd)) { simpleName.Set(fileName, iSimpleNameStart, fileName.End() - 6); } else { // Invalid filename GO_WITH_HRESULT(E_INVALIDARG); } const SimpleNameToFileNameMapEntry *pExistingEntry = m_pTrustedPlatformAssemblyMap->LookupPtr(simpleName.GetUnicode()); if (pExistingEntry != nullptr) { // // We want to store only the first entry matching a simple name we encounter. // The exception is if we first store an IL reference and later in the string // we encounter a native image. Since we don't touch IL in the presence of // native images, we replace the IL entry with the NI. // if ((pExistingEntry->m_wszILFileName != nullptr && !isNativeImage) || (pExistingEntry->m_wszNIFileName != nullptr && isNativeImage)) { BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Skipping TPA entry because of already existing IL/NI entry for short name "), fileName.GetUnicode()); continue; } } LPWSTR wszSimpleName = nullptr; if (pExistingEntry == nullptr) { wszSimpleName = new WCHAR[simpleName.GetCount() + 1]; if (wszSimpleName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszSimpleName, simpleName.GetCount() + 1, simpleName.GetUnicode()); } else { wszSimpleName = pExistingEntry->m_wszSimpleName; } LPWSTR wszFileName = new WCHAR[fileName.GetCount() + 1]; if (wszFileName == nullptr) { GO_WITH_HRESULT(E_OUTOFMEMORY); } wcscpy_s(wszFileName, fileName.GetCount() + 1, fileName.GetUnicode()); SimpleNameToFileNameMapEntry mapEntry; mapEntry.m_wszSimpleName = wszSimpleName; if (isNativeImage) { mapEntry.m_wszNIFileName = wszFileName; mapEntry.m_wszILFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszILFileName; } else { mapEntry.m_wszILFileName = wszFileName; mapEntry.m_wszNIFileName = pExistingEntry == nullptr ? nullptr : pExistingEntry->m_wszNIFileName; } m_pTrustedPlatformAssemblyMap->AddOrReplace(mapEntry); FileNameMapEntry fileNameExistenceEntry; fileNameExistenceEntry.m_wszFileName = wszFileName; m_pFileNameHash->AddOrReplace(fileNameExistenceEntry); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added TPA entry"), wszFileName); } // // Parse PlatformResourceRoots // sPlatformResourceRoots.Normalize(); for (SString::Iterator i = sPlatformResourceRoots.Begin(); i != sPlatformResourceRoots.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sPlatformResourceRoots, i, pathName)); if (pathResult == S_FALSE) { break; } m_platformResourceRoots.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added resource root"), pathName); } // // Parse AppPaths // sAppPaths.Normalize(); for (SString::Iterator i = sAppPaths.Begin(); i != sAppPaths.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sAppPaths, i, pathName)); if (pathResult == S_FALSE) { break; } m_appPaths.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added App Path"), pathName); } // // Parse AppNiPaths // sAppNiPaths.Normalize(); for (SString::Iterator i = sAppNiPaths.Begin(); i != sAppNiPaths.End(); ) { SString pathName; HRESULT pathResult = S_OK; IF_FAIL_GO(pathResult = GetNextPath(sAppNiPaths, i, pathName)); if (pathResult == S_FALSE) { break; } m_appNiPaths.Append(pathName); BINDER_LOG_STRING(W("ApplicationContext::SetupBindingPaths: Added App NI Path"), pathName); } Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::SetupBindingPaths"), hr); return hr; } HRESULT ApplicationContext::GetAssemblyIdentity(LPCSTR szTextualIdentity, AssemblyIdentityUTF8 **ppAssemblyIdentity) { HRESULT hr = S_OK; BINDER_LOG_ENTER(W("ApplicationContext::GetAssemblyIdentity")); BINDER_LOG_POINTER(W("this"), this); _ASSERTE(szTextualIdentity != NULL); _ASSERTE(ppAssemblyIdentity != NULL); CRITSEC_Holder contextLock(GetCriticalSectionCookie()); AssemblyIdentityUTF8 *pAssemblyIdentity = m_assemblyIdentityCache.Lookup(szTextualIdentity); if (pAssemblyIdentity == NULL) { NewHolder<AssemblyIdentityUTF8> pNewAssemblyIdentity; SString sTextualIdentity; SAFE_NEW(pNewAssemblyIdentity, AssemblyIdentityUTF8); sTextualIdentity.SetUTF8(szTextualIdentity); IF_FAIL_GO(TextualIdentityParser::Parse(sTextualIdentity, pNewAssemblyIdentity)); IF_FAIL_GO(m_assemblyIdentityCache.Add(szTextualIdentity, pNewAssemblyIdentity)); pNewAssemblyIdentity->PopulateUTF8Fields(); pAssemblyIdentity = pNewAssemblyIdentity.Extract(); } *ppAssemblyIdentity = pAssemblyIdentity; Exit: BINDER_LOG_LEAVE_HR(W("ApplicationContext::GetAssemblyIdentity"), hr); return hr; } bool ApplicationContext::IsTpaListProvided() { return m_pTrustedPlatformAssemblyMap != nullptr; } }; <|endoftext|>
<commit_before>/*********************************************************************** cmdline.cpp - Utility functions for printing out data in common formats, required by most of the example programs. Copyright (c) 2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "cmdline.h" #include <iostream> #include <stdio.h> #include <string.h> //// globals and constants ///////////////////////////////////////////// bool dtest_mode = false; // true when running under dtest int run_mode = 0; // -m switch's value const char* kpcSampleDatabase = "mysql_cpp_data"; //// att_getopt //////////////////////////////////////////////////////// // An implementation of getopt(), included here so we don't have to // limit ourselves to platforms that provide this natively. It is // adapted from the public domain getopt() implementation presented at // the 1985 UNIFORUM conference in Dallas, Texas. It's been reformatted // and reworked a bit to fit in with MySQL++. static const char* ag_optarg; int ag_optind = 1; static int att_getopt(int argc, char* const argv[], const char* ag_opts) { static int optopt; static int sp = 1; register int c; register const char *cp; if (sp == 1) { /* If all args are processed, finish */ if (ag_optind >= argc) { return EOF; } if (argv[ag_optind][0] != '-' || argv[ag_optind][1] == '\0') { return EOF; } } else if (!strcmp(argv[ag_optind], "--")) { /* No more ag_options to be processed after this one */ ag_optind++; return EOF; } optopt = c = argv[ag_optind][sp]; /* Check for invalid ag_option */ if (c == ':' || (cp = strchr(ag_opts, c)) == NULL) { fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c); if (argv[ag_optind][++sp] == '\0') { ag_optind++; sp = 1; } return '?'; } /* Does this ag_option require an argument? */ if (*++cp == ':') { /* If so, get argument; if none provided output error */ if (argv[ag_optind][sp + 1] != '\0') { ag_optarg = &argv[ag_optind++][sp + 1]; } else if (++ag_optind >= argc) { fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], c); sp = 1; return '?'; } else { ag_optarg = argv[ag_optind++]; } sp = 1; } else { if (argv[ag_optind][++sp] == '\0') { sp = 1; ag_optind++; } ag_optarg = NULL; } return c; } //// print_usage /////////////////////////////////////////////////////// // Show the program's usage message void print_usage(const char* program_name, const char* extra_parms) { std::cout << "usage: " << program_name << " [-s server_addr] [-u user] [-p password] " << extra_parms << std::endl; std::cout << std::endl; std::cout << " If no options are given, connects to database " "server on localhost" << std::endl; std::cout << " using your user name and no password." << std::endl; if (strlen(extra_parms) > 0) { std::cout << std::endl; std::cout << " The extra parameter " << extra_parms << " is required, regardless of which" << std::endl; std::cout << " other arguments you pass." << std::endl; } std::cout << std::endl; } //// parse_command_line //////////////////////////////////////////////// // Wrapper around att_getopt() to return the parameters needed to // connect to a database server and select the database itself. bool parse_command_line(int argc, char *argv[], const char** ppdb, const char** ppserver, const char** ppuser, const char** pppass, const char* extra_parms) { if (argc < 1) { std::cerr << "Bad argument count: " << argc << '!' << std::endl; return false; } if (ppdb && !*ppdb) { *ppdb = "mysql_cpp_data"; // use default DB } int ch; while ((ch = att_getopt(argc, argv, "m:p:s:u:D")) != EOF) { switch (ch) { case 'm': run_mode = atoi(ag_optarg); break; case 'p': *pppass = ag_optarg; break; case 's': *ppserver = ag_optarg; break; case 'u': *ppuser = ag_optarg; break; case 'D': dtest_mode = true; break; default: print_usage(argv[0], extra_parms); return false; } } return true; } <commit_msg>Whitespace fix<commit_after>/*********************************************************************** cmdline.cpp - Utility functions for printing out data in common formats, required by most of the example programs. Copyright (c) 2007 by Educational Technology Resources, Inc. Others may also hold copyrights on code in this file. See the CREDITS file in the top directory of the distribution for details. This file is part of MySQL++. MySQL++ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. MySQL++ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with MySQL++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA ***********************************************************************/ #include "cmdline.h" #include <iostream> #include <stdio.h> #include <string.h> //// globals and constants ///////////////////////////////////////////// bool dtest_mode = false; // true when running under dtest int run_mode = 0; // -m switch's value const char* kpcSampleDatabase = "mysql_cpp_data"; //// att_getopt //////////////////////////////////////////////////////// // An implementation of getopt(), included here so we don't have to // limit ourselves to platforms that provide this natively. It is // adapted from the public domain getopt() implementation presented at // the 1985 UNIFORUM conference in Dallas, Texas. It's been reformatted // and reworked a bit to fit in with MySQL++. static const char* ag_optarg; int ag_optind = 1; static int att_getopt(int argc, char* const argv[], const char* ag_opts) { static int optopt; static int sp = 1; register int c; register const char *cp; if (sp == 1) { /* If all args are processed, finish */ if (ag_optind >= argc) { return EOF; } if (argv[ag_optind][0] != '-' || argv[ag_optind][1] == '\0') { return EOF; } } else if (!strcmp(argv[ag_optind], "--")) { /* No more ag_options to be processed after this one */ ag_optind++; return EOF; } optopt = c = argv[ag_optind][sp]; /* Check for invalid ag_option */ if (c == ':' || (cp = strchr(ag_opts, c)) == NULL) { fprintf(stderr, "%s: illegal option -- %c\n", argv[0], c); if (argv[ag_optind][++sp] == '\0') { ag_optind++; sp = 1; } return '?'; } /* Does this ag_option require an argument? */ if (*++cp == ':') { /* If so, get argument; if none provided output error */ if (argv[ag_optind][sp + 1] != '\0') { ag_optarg = &argv[ag_optind++][sp + 1]; } else if (++ag_optind >= argc) { fprintf(stderr, "%s: option requires an argument -- %c\n", argv[0], c); sp = 1; return '?'; } else { ag_optarg = argv[ag_optind++]; } sp = 1; } else { if (argv[ag_optind][++sp] == '\0') { sp = 1; ag_optind++; } ag_optarg = NULL; } return c; } //// print_usage /////////////////////////////////////////////////////// // Show the program's usage message void print_usage(const char* program_name, const char* extra_parms) { std::cout << "usage: " << program_name << " [-s server_addr] [-u user] [-p password] " << extra_parms << std::endl; std::cout << std::endl; std::cout << " If no options are given, connects to database " "server on localhost" << std::endl; std::cout << " using your user name and no password." << std::endl; if (strlen(extra_parms) > 0) { std::cout << std::endl; std::cout << " The extra parameter " << extra_parms << " is required, regardless of which" << std::endl; std::cout << " other arguments you pass." << std::endl; } std::cout << std::endl; } //// parse_command_line //////////////////////////////////////////////// // Wrapper around att_getopt() to return the parameters needed to // connect to a database server and select the database itself. bool parse_command_line(int argc, char *argv[], const char** ppdb, const char** ppserver, const char** ppuser, const char** pppass, const char* extra_parms) { if (argc < 1) { std::cerr << "Bad argument count: " << argc << '!' << std::endl; return false; } if (ppdb && !*ppdb) { *ppdb = "mysql_cpp_data"; // use default DB } int ch; while ((ch = att_getopt(argc, argv, "m:p:s:u:D")) != EOF) { switch (ch) { case 'm': run_mode = atoi(ag_optarg); break; case 'p': *pppass = ag_optarg; break; case 's': *ppserver = ag_optarg; break; case 'u': *ppuser = ag_optarg; break; case 'D': dtest_mode = true; break; default: print_usage(argv[0], extra_parms); return false; } } return true; } <|endoftext|>
<commit_before>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofEnableSmoothing(); ofSetFrameRate(60); width = ofGetWidth(); height = ofGetHeight(); shader.load("cortex"); fbo.allocate(width,height); //set default values bVert = 0; bHorizon = 0; bDiag = 0; bArms = 0; bRings = 0; bSpiral = 0; vertSpeed = 4.0; horizonSpeed = 4.0; diagSpeed = 4.0; armSpeed = 4.0; ringSpeed = 4.0; spiralSpeed = 4.0; numVert = 48.0; numHorizon = 48.0; numDiag = 48.0; numRings = 12.0; numArms = 4; numSpiral = 3; vertSign = 1; horizonSign = 1; diagSign = 1; armSign = 1; ringSign = 1; spiralSign = 1; } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ fbo.begin(); shader.begin(); setUniforms(); ofRect(0,0,width,height); shader.end(); fbo.end(); fbo.draw(0,0,width,height); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == '1') { bVert = !bVert; } if(key == '2') { bHorizon = !bHorizon; } if(key == '3') { bDiag = !bDiag; } if(key == '4') { bArms = !bArms; } if(key == '5') { bRings = !bRings; } if(key == '6') { bSpiral = !bSpiral; } if(key == 'q') { vertSpeed += 2.0; } if (key == 'Q') { vertSpeed -= 2.0; } if(key == 'w') { horizonSpeed += 2.0; } if (key == 'W') { horizonSpeed -= 2.0; } if(key == 'e') { diagSpeed += 2.0; } if (key == 'E') { diagSpeed -= 2.0; } if(key == 'r') { armSpeed += 2.0; } if (key == 'R') { armSpeed -= 2.0; } if(key == 't') { ringSpeed += 2.0; } if (key == 'T') { ringSpeed -= 2.0; } if(key == 'y') { spiralSpeed += 2.0; } if (key == 'Y') { spiralSpeed -= 2.0; } if(key == 'q') { vertSpeed += 2.0; } if (key == 'Q') { vertSpeed -= 2.0; } if(key == 'w') { horizonSpeed += 2.0; } if (key == 'W') { horizonSpeed -= 2.0; } if(key == 'e') { diagSpeed += 2.0; } if (key == 'E') { diagSpeed -= 2.0; } if(key == 'r') { armSpeed += 2.0; } if (key == 'R') { armSpeed -= 2.0; } if(key == 't') { ringSpeed += 2.0; } if (key == 'T') { ringSpeed -= 2.0; } if(key == 'y') { spiralSpeed += 2.0; } if (key == 'Y') { spiralSpeed -= 2.0; } if(key == 'a') { numVert += 4.0; } if (key == 'A') { numVert -= 4.0; } if(key == 's') { numHorizon += 4.0; } if (key == 'S') { numHorizon -= 4.0; } if(key == 'd') { numDiag += 4.0; } if (key == 'D') { numDiag -= 4.0; } if(key == 'f') { numArms += 1; } if (key == 'F') { numArms -= 1; } if(key == 'G') { numRings += 1.0; } if (key == 'g') { numRings -= 1.0; } if(key == 'h') { numSpiral += 1; } if (key == 'H') { numSpiral -= 1; } if (key == 'z') { vertSign *= -1; } if (key == 'x') { horizonSign *= -1; } if (key == 'c') { diagSign *= -1; } if (key == 'v') { armSign *= -1; } if (key == 'b') { ringSign *= -1; } if (key == 'n') { spiralSign *= -1; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } //-------------------------------------------------------------- void testApp::setUniforms(){ float resolution[] = {width, height}; float time = ofGetElapsedTimef(); shader.setUniform1f("time",time); shader.setUniform2fv("resolution",resolution); //flags for turning patterns on/off shader.setUniform1f("bVert", bVert); shader.setUniform1i("bHorizon", bHorizon); shader.setUniform1i("bDiag", bDiag); shader.setUniform1i("bArms", bArms); shader.setUniform1i("bRings", bRings); shader.setUniform1i("bSpiral", bSpiral); //pattern speeds shader.setUniform1f("vertSpeed", vertSpeed); shader.setUniform1f("horizonSpeed", horizonSpeed); shader.setUniform1f("diagSpeed", diagSpeed); shader.setUniform1f("armSpeed", armSpeed); shader.setUniform1f("ringSpeed", ringSpeed); shader.setUniform1f("spiralSpeed", spiralSpeed); //pattern parameters shader.setUniform1f("numVert", numVert); shader.setUniform1f("numHorizon", numHorizon); shader.setUniform1f("numDiag", numDiag); shader.setUniform1f("numArms", numArms); shader.setUniform1f("numRings", numRings); shader.setUniform1f("numSpiral", numSpiral); //direction parameters shader.setUniform1f("vertSign", vertSign); shader.setUniform1f("horizonSign", horizonSign); shader.setUniform1f("diagSign", diagSign); shader.setUniform1f("armSign", armSign); shader.setUniform1f("ringSign", ringSign); shader.setUniform1f("spiralSign", spiralSign); } <commit_msg>use vertical sync to prevent banding<commit_after>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofEnableSmoothing(); ofSetFrameRate(60); ofSetVerticalSync(true); width = ofGetWidth(); height = ofGetHeight(); shader.load("cortex"); fbo.allocate(width,height); //set default values bVert = 0; bHorizon = 0; bDiag = 0; bArms = 0; bRings = 0; bSpiral = 0; vertSpeed = 4.0; horizonSpeed = 4.0; diagSpeed = 4.0; armSpeed = 4.0; ringSpeed = 4.0; spiralSpeed = 4.0; numVert = 48.0; numHorizon = 48.0; numDiag = 48.0; numRings = 12.0; numArms = 4; numSpiral = 3; vertSign = 1; horizonSign = 1; diagSign = 1; armSign = 1; ringSign = 1; spiralSign = 1; } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ fbo.begin(); shader.begin(); setUniforms(); ofRect(0,0,width,height); shader.end(); fbo.end(); fbo.draw(0,0,width,height); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ if(key == '1') { bVert = !bVert; } if(key == '2') { bHorizon = !bHorizon; } if(key == '3') { bDiag = !bDiag; } if(key == '4') { bArms = !bArms; } if(key == '5') { bRings = !bRings; } if(key == '6') { bSpiral = !bSpiral; } if(key == 'q') { vertSpeed += 2.0; } if (key == 'Q') { vertSpeed -= 2.0; } if(key == 'w') { horizonSpeed += 2.0; } if (key == 'W') { horizonSpeed -= 2.0; } if(key == 'e') { diagSpeed += 2.0; } if (key == 'E') { diagSpeed -= 2.0; } if(key == 'r') { armSpeed += 2.0; } if (key == 'R') { armSpeed -= 2.0; } if(key == 't') { ringSpeed += 2.0; } if (key == 'T') { ringSpeed -= 2.0; } if(key == 'y') { spiralSpeed += 2.0; } if (key == 'Y') { spiralSpeed -= 2.0; } if(key == 'q') { vertSpeed += 2.0; } if (key == 'Q') { vertSpeed -= 2.0; } if(key == 'w') { horizonSpeed += 2.0; } if (key == 'W') { horizonSpeed -= 2.0; } if(key == 'e') { diagSpeed += 2.0; } if (key == 'E') { diagSpeed -= 2.0; } if(key == 'r') { armSpeed += 2.0; } if (key == 'R') { armSpeed -= 2.0; } if(key == 't') { ringSpeed += 2.0; } if (key == 'T') { ringSpeed -= 2.0; } if(key == 'y') { spiralSpeed += 2.0; } if (key == 'Y') { spiralSpeed -= 2.0; } if(key == 'a') { numVert += 4.0; } if (key == 'A') { numVert -= 4.0; } if(key == 's') { numHorizon += 4.0; } if (key == 'S') { numHorizon -= 4.0; } if(key == 'd') { numDiag += 4.0; } if (key == 'D') { numDiag -= 4.0; } if(key == 'f') { numArms += 1; } if (key == 'F') { numArms -= 1; } if(key == 'G') { numRings += 1.0; } if (key == 'g') { numRings -= 1.0; } if(key == 'h') { numSpiral += 1; } if (key == 'H') { numSpiral -= 1; } if (key == 'z') { vertSign *= -1; } if (key == 'x') { horizonSign *= -1; } if (key == 'c') { diagSign *= -1; } if (key == 'v') { armSign *= -1; } if (key == 'b') { ringSign *= -1; } if (key == 'n') { spiralSign *= -1; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ } //-------------------------------------------------------------- void testApp::setUniforms(){ float resolution[] = {width, height}; float time = ofGetElapsedTimef(); shader.setUniform1f("time",time); shader.setUniform2fv("resolution",resolution); //flags for turning patterns on/off shader.setUniform1f("bVert", bVert); shader.setUniform1i("bHorizon", bHorizon); shader.setUniform1i("bDiag", bDiag); shader.setUniform1i("bArms", bArms); shader.setUniform1i("bRings", bRings); shader.setUniform1i("bSpiral", bSpiral); //pattern speeds shader.setUniform1f("vertSpeed", vertSpeed); shader.setUniform1f("horizonSpeed", horizonSpeed); shader.setUniform1f("diagSpeed", diagSpeed); shader.setUniform1f("armSpeed", armSpeed); shader.setUniform1f("ringSpeed", ringSpeed); shader.setUniform1f("spiralSpeed", spiralSpeed); //pattern parameters shader.setUniform1f("numVert", numVert); shader.setUniform1f("numHorizon", numHorizon); shader.setUniform1f("numDiag", numDiag); shader.setUniform1f("numArms", numArms); shader.setUniform1f("numRings", numRings); shader.setUniform1f("numSpiral", numSpiral); //direction parameters shader.setUniform1f("vertSign", vertSign); shader.setUniform1f("horizonSign", horizonSign); shader.setUniform1f("diagSign", diagSign); shader.setUniform1f("armSign", armSign); shader.setUniform1f("ringSign", ringSign); shader.setUniform1f("spiralSign", spiralSign); } <|endoftext|>
<commit_before>/* * Copyright (c) 2012. The Regents of the University of California. All rights reserved. * Licensed pursuant to the terms and conditions available for viewing at: * http://opensource.org/licenses/BSD-3-Clause * * File: GLSLHelpers.cpp * Author: Jonathan Ventura * Last Modified: 11.17.2012 */ #include <GLUtils/GLSLHelpers.h> Eigen::Matrix4d makeProj( const Eigen::Vector4d &params, double width, double height, double nearPlane, double farPlane ) { double left, top, right, bottom; left = -nearPlane * params[2] / params[0]; top = nearPlane * params[3] / params[1]; right = nearPlane * ( width - params[2] ) / params[0]; bottom = - nearPlane * ( height - params[3] ) / params[1]; Eigen::Matrix4d proj = Eigen::Matrix4d::Zero(); proj(0,0) = ( 2 * nearPlane ) / ( right - left ); proj(0,2) = ( right + left ) / ( right - left ); proj(1,1) = ( 2 * nearPlane ) / ( top - bottom ); proj(1,2) = ( top + bottom ) / ( top - bottom ); proj(2,2) = - ( ( farPlane + nearPlane ) / ( farPlane - nearPlane ) ); proj(2,3) = - ( ( 2 * farPlane * nearPlane ) / ( farPlane - nearPlane ) ); proj(3,2) = -1; return proj; } Eigen::Matrix4d makeScale( const Eigen::Vector3d &scale ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat(0,0) = scale[0]; mat(1,1) = scale[1]; mat(2,2) = scale[2]; return mat; } Eigen::Matrix4d makeTranslation( const Eigen::Vector3d &translation ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat(0,3) = translation[0]; mat(1,3) = translation[1]; mat(2,3) = translation[2]; return mat; } Eigen::Matrix4d makeRotation( const Eigen::Matrix3d &rotation ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat.block<3,3>(0,0) = rotation.matrix(); return mat; } Eigen::Matrix4d makeModelView( const Sophus::SE3d &pose ) { Eigen::Matrix4d mat = makeTranslation( pose.translation() ) * makeRotation( pose.so3() ); return mat; } <commit_msg>Fixed bug in GLUtils not using SO3d<commit_after>/* * Copyright (c) 2012. The Regents of the University of California. All rights reserved. * Licensed pursuant to the terms and conditions available for viewing at: * http://opensource.org/licenses/BSD-3-Clause * * File: GLSLHelpers.cpp * Author: Jonathan Ventura * Last Modified: 11.17.2012 */ #include <GLUtils/GLSLHelpers.h> Eigen::Matrix4d makeProj( const Eigen::Vector4d &params, double width, double height, double nearPlane, double farPlane ) { double left, top, right, bottom; left = -nearPlane * params[2] / params[0]; top = nearPlane * params[3] / params[1]; right = nearPlane * ( width - params[2] ) / params[0]; bottom = - nearPlane * ( height - params[3] ) / params[1]; Eigen::Matrix4d proj = Eigen::Matrix4d::Zero(); proj(0,0) = ( 2 * nearPlane ) / ( right - left ); proj(0,2) = ( right + left ) / ( right - left ); proj(1,1) = ( 2 * nearPlane ) / ( top - bottom ); proj(1,2) = ( top + bottom ) / ( top - bottom ); proj(2,2) = - ( ( farPlane + nearPlane ) / ( farPlane - nearPlane ) ); proj(2,3) = - ( ( 2 * farPlane * nearPlane ) / ( farPlane - nearPlane ) ); proj(3,2) = -1; return proj; } Eigen::Matrix4d makeScale( const Eigen::Vector3d &scale ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat(0,0) = scale[0]; mat(1,1) = scale[1]; mat(2,2) = scale[2]; return mat; } Eigen::Matrix4d makeTranslation( const Eigen::Vector3d &translation ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat(0,3) = translation[0]; mat(1,3) = translation[1]; mat(2,3) = translation[2]; return mat; } Eigen::Matrix4d makeRotation( const Sophus::SO3d &rotation ) { Eigen::Matrix4d mat = Eigen::Matrix4d::Identity(); mat.block<3,3>(0,0) = rotation.matrix(); return mat; } Eigen::Matrix4d makeModelView( const Sophus::SE3d &pose ) { Eigen::Matrix4d mat = makeTranslation( pose.translation() ) * makeRotation( pose.so3() ); return mat; } <|endoftext|>
<commit_before>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/FontCache.h" #include "SkFontMgr.h" #include "SkTypeface_win.h" #include "core/platform/NotImplemented.h" #include "core/platform/graphics/Font.h" #include "core/platform/graphics/SimpleFontData.h" #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h" #include "core/platform/graphics/chromium/FontUtilsChromiumWin.h" namespace WebCore { FontCache::FontCache() : m_purgePreventCount(0) { m_fontManager = adoptPtr(SkFontMgr_New_GDI()); } static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character) { SkPaint paint; fontData->setupPaint(&paint); paint.setTextEncoding(SkPaint::kUTF32_TextEncoding); uint16_t glyph; paint.textToGlyphs(&character, sizeof(character), &glyph); return glyph != 0; } // Given the desired base font, this will create a SimpleFontData for a specific // font that can be used to render the given range of characters. PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC) { // FIXME: We should fix getFallbackFamily to take a UChar32 // and remove this split-to-UChar16 code. UChar codeUnits[2]; int codeUnitsLength; if (inputC <= 0xFFFF) { codeUnits[0] = inputC; codeUnitsLength = 1; } else { codeUnits[0] = U16_LEAD(inputC); codeUnits[1] = U16_TRAIL(inputC); codeUnitsLength = 2; } // FIXME: Consider passing fontDescription.dominantScript() // to GetFallbackFamily here. FontDescription fontDescription = font.fontDescription(); UChar32 c; UScriptCode script; const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script); FontPlatformData* data = 0; if (family) data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)), false); // Last resort font list : PanUnicode. CJK fonts have a pretty // large repertoire. Eventually, we need to scan all the fonts // on the system to have a Firefox-like coverage. // Make sure that all of them are lowercased. const static wchar_t* const cjkFonts[] = { L"arial unicode ms", L"ms pgothic", L"simsun", L"gulim", L"pmingliu", L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users. L"ar pl shanheisun uni", L"ar pl zenkai uni", L"han nom a", // Complete CJK Ext. A coverage. L"code2000" // Complete CJK Ext. A coverage. // CJK Ext. B fonts are not listed here because it's of no use // with our current non-BMP character handling because we use // Uniscribe for it and that code path does not go through here. }; const static wchar_t* const commonFonts[] = { L"tahoma", L"arial unicode ms", L"lucida sans unicode", L"microsoft sans serif", L"palatino linotype", // Six fonts below (and code2000 at the end) are not from MS, but // once installed, cover a very wide range of characters. L"dejavu serif", L"dejavu sasns", L"freeserif", L"freesans", L"gentium", L"gentiumalt", L"ms pgothic", L"simsun", L"gulim", L"pmingliu", L"code2000" }; const wchar_t* const* panUniFonts = 0; int numFonts = 0; if (script == USCRIPT_HAN) { panUniFonts = cjkFonts; numFonts = WTF_ARRAY_LENGTH(cjkFonts); } else { panUniFonts = commonFonts; numFonts = WTF_ARRAY_LENGTH(commonFonts); } // Font returned from GetFallbackFamily may not cover |characters| // because it's based on script to font mapping. This problem is // critical enough for non-Latin scripts (especially Han) to // warrant an additional (real coverage) check with fontCotainsCharacter. int i; for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) { family = panUniFonts[i]; data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family))); } // When i-th font (0-base) in |panUniFonts| contains a character and // we get out of the loop, |i| will be |i + 1|. That is, if only the // last font in the array covers the character, |i| will be numFonts. // So, we have to use '<=" rather than '<' to see if we found a font // covering the character. if (i <= numFonts) return getFontResourceData(data, DoNotRetain); return 0; } static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b) { return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str())); } static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family) { SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator(); bool matchesRequestedFamily = false; SkTypeface::LocalizedString actualFamily; while (actualFamilies->next(&actualFamily)) { if (equalIgnoringCase(family, actualFamily.fString)) { matchesRequestedFamily = true; break; } } actualFamilies->unref(); return matchesRequestedFamily; } FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family) { CString name; SkTypeface* tf = createTypeface(fontDescription, family, name); if (!tf) return 0; // Windows will always give us a valid pointer here, even if the face name // is non-existent. We have to double-check and see if the family name was // really used. // FIXME: Do we need to use predefined fonts "guaranteed" to exist // when we're running in layout-test mode? if (!typefacesMatchesFamily(tf, family)) { tf->unref(); return 0; } FontPlatformData* result = new FontPlatformData(tf, name.data(), fontDescription.computedSize(), fontDescription.weight() >= FontWeightBold && !tf->isBold(), fontDescription.italic() && !tf->isItalic(), fontDescription.orientation()); tf->unref(); return result; } } <commit_msg>Change typefacesMatchesFamily to fall back on getFamilyName<commit_after>/* * Copyright (C) 2006, 2007 Apple Computer, Inc. * Copyright (c) 2006, 2007, 2008, 2009, 2012 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "core/platform/graphics/FontCache.h" #include "SkFontMgr.h" #include "SkTypeface_win.h" #include "core/platform/NotImplemented.h" #include "core/platform/graphics/Font.h" #include "core/platform/graphics/SimpleFontData.h" #include "core/platform/graphics/chromium/FontPlatformDataChromiumWin.h" #include "core/platform/graphics/chromium/FontUtilsChromiumWin.h" namespace WebCore { FontCache::FontCache() : m_purgePreventCount(0) { m_fontManager = adoptPtr(SkFontMgr_New_GDI()); } static bool fontContainsCharacter(const FontPlatformData* fontData, const wchar_t* family, UChar32 character) { SkPaint paint; fontData->setupPaint(&paint); paint.setTextEncoding(SkPaint::kUTF32_TextEncoding); uint16_t glyph; paint.textToGlyphs(&character, sizeof(character), &glyph); return glyph != 0; } // Given the desired base font, this will create a SimpleFontData for a specific // font that can be used to render the given range of characters. PassRefPtr<SimpleFontData> FontCache::getFontDataForCharacter(const Font& font, UChar32 inputC) { // FIXME: We should fix getFallbackFamily to take a UChar32 // and remove this split-to-UChar16 code. UChar codeUnits[2]; int codeUnitsLength; if (inputC <= 0xFFFF) { codeUnits[0] = inputC; codeUnitsLength = 1; } else { codeUnits[0] = U16_LEAD(inputC); codeUnits[1] = U16_TRAIL(inputC); codeUnitsLength = 2; } // FIXME: Consider passing fontDescription.dominantScript() // to GetFallbackFamily here. FontDescription fontDescription = font.fontDescription(); UChar32 c; UScriptCode script; const wchar_t* family = getFallbackFamily(codeUnits, codeUnitsLength, fontDescription.genericFamily(), &c, &script); FontPlatformData* data = 0; if (family) data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family)), false); // Last resort font list : PanUnicode. CJK fonts have a pretty // large repertoire. Eventually, we need to scan all the fonts // on the system to have a Firefox-like coverage. // Make sure that all of them are lowercased. const static wchar_t* const cjkFonts[] = { L"arial unicode ms", L"ms pgothic", L"simsun", L"gulim", L"pmingliu", L"wenquanyi zen hei", // Partial CJK Ext. A coverage but more widely known to Chinese users. L"ar pl shanheisun uni", L"ar pl zenkai uni", L"han nom a", // Complete CJK Ext. A coverage. L"code2000" // Complete CJK Ext. A coverage. // CJK Ext. B fonts are not listed here because it's of no use // with our current non-BMP character handling because we use // Uniscribe for it and that code path does not go through here. }; const static wchar_t* const commonFonts[] = { L"tahoma", L"arial unicode ms", L"lucida sans unicode", L"microsoft sans serif", L"palatino linotype", // Six fonts below (and code2000 at the end) are not from MS, but // once installed, cover a very wide range of characters. L"dejavu serif", L"dejavu sasns", L"freeserif", L"freesans", L"gentium", L"gentiumalt", L"ms pgothic", L"simsun", L"gulim", L"pmingliu", L"code2000" }; const wchar_t* const* panUniFonts = 0; int numFonts = 0; if (script == USCRIPT_HAN) { panUniFonts = cjkFonts; numFonts = WTF_ARRAY_LENGTH(cjkFonts); } else { panUniFonts = commonFonts; numFonts = WTF_ARRAY_LENGTH(commonFonts); } // Font returned from GetFallbackFamily may not cover |characters| // because it's based on script to font mapping. This problem is // critical enough for non-Latin scripts (especially Han) to // warrant an additional (real coverage) check with fontCotainsCharacter. int i; for (i = 0; (!data || !fontContainsCharacter(data, family, c)) && i < numFonts; ++i) { family = panUniFonts[i]; data = getFontResourcePlatformData(font.fontDescription(), AtomicString(family, wcslen(family))); } // When i-th font (0-base) in |panUniFonts| contains a character and // we get out of the loop, |i| will be |i + 1|. That is, if only the // last font in the array covers the character, |i| will be numFonts. // So, we have to use '<=" rather than '<' to see if we found a font // covering the character. if (i <= numFonts) return getFontResourceData(data, DoNotRetain); return 0; } static inline bool equalIgnoringCase(const AtomicString& a, const SkString& b) { return equalIgnoringCase(a, AtomicString::fromUTF8(b.c_str())); } static bool typefacesMatchesFamily(const SkTypeface* tf, const AtomicString& family) { SkTypeface::LocalizedStrings* actualFamilies = tf->createFamilyNameIterator(); bool matchesRequestedFamily = false; SkTypeface::LocalizedString actualFamily; while (actualFamilies->next(&actualFamily)) { if (equalIgnoringCase(family, actualFamily.fString)) { matchesRequestedFamily = true; break; } } actualFamilies->unref(); // getFamilyName may return a name not returned by the createFamilyNameIterator. // Specifically in cases where Windows substitutes the font based on the // HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\FontSubstitutes registry entries. if (!matchesRequestedFamily) { SkString familyName; tf->getFamilyName(&familyName); if (equalIgnoringCase(family, familyName)) matchesRequestedFamily = true; } return matchesRequestedFamily; } FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const AtomicString& family) { CString name; SkTypeface* tf = createTypeface(fontDescription, family, name); if (!tf) return 0; // Windows will always give us a valid pointer here, even if the face name // is non-existent. We have to double-check and see if the family name was // really used. // FIXME: Do we need to use predefined fonts "guaranteed" to exist // when we're running in layout-test mode? if (!typefacesMatchesFamily(tf, family)) { tf->unref(); return 0; } FontPlatformData* result = new FontPlatformData(tf, name.data(), fontDescription.computedSize(), fontDescription.weight() >= FontWeightBold && !tf->isBold(), fontDescription.italic() && !tf->isItalic(), fontDescription.orientation()); tf->unref(); return result; } } <|endoftext|>
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "btree/secondary_operations.hpp" #include "btree/operations.hpp" #include "buffer_cache/blob.hpp" #include "buffer_cache/serialize_onto_blob.hpp" #include "containers/archive/vector_stream.hpp" #include "protocol_api.hpp" RDB_IMPL_ME_SERIALIZABLE_4(secondary_index_t, superblock, opaque_definition, post_construction_complete, id); void get_secondary_indexes_internal(transaction_t *txn, buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { const btree_sindex_block_t *data = static_cast<const btree_sindex_block_t *>(sindex_block->get_data_read()); blob_t sindex_blob(txn->get_cache()->get_block_size(), const_cast<char *>(data->sindex_blob), btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); deserialize_from_blob(txn, &sindex_blob, sindexes_out); } void set_secondary_indexes_internal(transaction_t *txn, buf_lock_t *sindex_block, const std::map<std::string, secondary_index_t> &sindexes) { btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(sindex_block->get_data_write()); blob_t sindex_blob(txn->get_cache()->get_block_size(), data->sindex_blob, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); serialize_onto_blob(txn, &sindex_blob, sindexes); } void initialize_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block) { btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(sindex_block->get_data_write()); data->magic = btree_sindex_block_t::expected_magic; memset(data->sindex_blob, 0, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); set_secondary_indexes_internal(txn, sindex_block, std::map<std::string, secondary_index_t>()); } bool get_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); auto it = sindex_map.find(id); if (it != sindex_map.end()) { *sindex_out = it->second; return true; } else { return false; } } bool get_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, uuid_u id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { *sindex_out = it->second; return true; } } return false; } void get_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { get_secondary_indexes_internal(txn, sindex_block, sindexes_out); } void set_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); /* We insert even if it already exists overwriting the old value. */ sindex_map[id] = sindex; set_secondary_indexes_internal(txn, sindex_block, sindex_map); } void set_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, uuid_u id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { guarantee(sindex.id == id, "This shouldn't change the id."); it->second = sindex; } } set_secondary_indexes_internal(txn, sindex_block, sindex_map); } bool delete_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); if (sindex_map.erase(id) == 1) { set_secondary_indexes_internal(txn, sindex_block, sindex_map); return true; } else { return false; } } void delete_all_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block) { set_secondary_indexes_internal(txn, sindex_block, std::map<std::string, secondary_index_t>()); } <commit_msg>Fixed alt cache linking problems related to secondary_operations.cc (integrated alt cache code into the whole file).<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved. #include "btree/secondary_operations.hpp" #include "btree/slice.hpp" // RSI: for SLICE_ALT #include "btree/operations.hpp" #if SLICE_ALT #include "buffer_cache/alt/alt.hpp" #include "buffer_cache/alt/alt_blob.hpp" #include "buffer_cache/alt/alt_serialize_onto_blob.hpp" #endif #include "buffer_cache/blob.hpp" #include "buffer_cache/serialize_onto_blob.hpp" #include "containers/archive/vector_stream.hpp" #include "protocol_api.hpp" using namespace alt; // RSI RDB_IMPL_ME_SERIALIZABLE_4(secondary_index_t, superblock, opaque_definition, post_construction_complete, id); #if SLICE_ALT void get_secondary_indexes_internal(alt_buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { #else void get_secondary_indexes_internal(transaction_t *txn, buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { #endif #if SLICE_ALT alt_buf_read_t read(sindex_block); const btree_sindex_block_t *data = static_cast<const btree_sindex_block_t *>(read.get_data_read()); #else const btree_sindex_block_t *data = static_cast<const btree_sindex_block_t *>(sindex_block->get_data_read()); #endif #if SLICE_ALT alt::blob_t sindex_blob(sindex_block->cache()->get_block_size(), const_cast<char *>(data->sindex_blob), btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); deserialize_from_blob(alt_buf_parent_t(sindex_block), &sindex_blob, sindexes_out); #else blob_t sindex_blob(txn->get_cache()->get_block_size(), const_cast<char *>(data->sindex_blob), btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); deserialize_from_blob(txn, &sindex_blob, sindexes_out); #endif } #if SLICE_ALT void set_secondary_indexes_internal(alt_buf_lock_t *sindex_block, const std::map<std::string, secondary_index_t> &sindexes) { alt_buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); alt::blob_t sindex_blob(sindex_block->cache()->get_block_size(), data->sindex_blob, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); serialize_onto_blob(alt_buf_parent_t(sindex_block), &sindex_blob, sindexes); } #else void set_secondary_indexes_internal(transaction_t *txn, buf_lock_t *sindex_block, const std::map<std::string, secondary_index_t> &sindexes) { btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(sindex_block->get_data_write()); blob_t sindex_blob(txn->get_cache()->get_block_size(), data->sindex_blob, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); serialize_onto_blob(txn, &sindex_blob, sindexes); } #endif #if SLICE_ALT void initialize_secondary_indexes(alt_buf_lock_t *sindex_block) { alt_buf_write_t write(sindex_block); btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(write.get_data_write()); data->magic = btree_sindex_block_t::expected_magic; memset(data->sindex_blob, 0, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); set_secondary_indexes_internal(sindex_block, std::map<std::string, secondary_index_t>()); } #else void initialize_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block) { btree_sindex_block_t *data = static_cast<btree_sindex_block_t *>(sindex_block->get_data_write()); data->magic = btree_sindex_block_t::expected_magic; memset(data->sindex_blob, 0, btree_sindex_block_t::SINDEX_BLOB_MAXREFLEN); set_secondary_indexes_internal(txn, sindex_block, std::map<std::string, secondary_index_t>()); } #endif #if SLICE_ALT bool get_secondary_index(alt_buf_lock_t *sindex_block, const std::string &id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); auto it = sindex_map.find(id); if (it != sindex_map.end()) { *sindex_out = it->second; return true; } else { return false; } } #else bool get_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); auto it = sindex_map.find(id); if (it != sindex_map.end()) { *sindex_out = it->second; return true; } else { return false; } } #endif #if SLICE_ALT bool get_secondary_index(alt_buf_lock_t *sindex_block, uuid_u id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { *sindex_out = it->second; return true; } } return false; } #else bool get_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, uuid_u id, secondary_index_t *sindex_out) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { *sindex_out = it->second; return true; } } return false; } #endif #if SLICE_ALT void get_secondary_indexes(alt_buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { get_secondary_indexes_internal(sindex_block, sindexes_out); } #else void get_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block, std::map<std::string, secondary_index_t> *sindexes_out) { get_secondary_indexes_internal(txn, sindex_block, sindexes_out); } #endif #if SLICE_ALT void set_secondary_index(alt_buf_lock_t *sindex_block, const std::string &id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); /* We insert even if it already exists overwriting the old value. */ sindex_map[id] = sindex; set_secondary_indexes_internal(sindex_block, sindex_map); } #else void set_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); /* We insert even if it already exists overwriting the old value. */ sindex_map[id] = sindex; set_secondary_indexes_internal(txn, sindex_block, sindex_map); } #endif #if SLICE_ALT void set_secondary_index(alt_buf_lock_t *sindex_block, uuid_u id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { guarantee(sindex.id == id, "This shouldn't change the id."); it->second = sindex; } } set_secondary_indexes_internal(sindex_block, sindex_map); } #else void set_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, uuid_u id, const secondary_index_t &sindex) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); for (auto it = sindex_map.begin(); it != sindex_map.end(); ++it) { if (it->second.id == id) { guarantee(sindex.id == id, "This shouldn't change the id."); it->second = sindex; } } set_secondary_indexes_internal(txn, sindex_block, sindex_map); } #endif #if SLICE_ALT bool delete_secondary_index(alt_buf_lock_t *sindex_block, const std::string &id) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(sindex_block, &sindex_map); if (sindex_map.erase(id) == 1) { set_secondary_indexes_internal(sindex_block, sindex_map); return true; } else { return false; } } #else bool delete_secondary_index(transaction_t *txn, buf_lock_t *sindex_block, const std::string &id) { std::map<std::string, secondary_index_t> sindex_map; get_secondary_indexes_internal(txn, sindex_block, &sindex_map); if (sindex_map.erase(id) == 1) { set_secondary_indexes_internal(txn, sindex_block, sindex_map); return true; } else { return false; } } #endif #if SLICE_ALT void delete_all_secondary_indexes(alt_buf_lock_t *sindex_block) { set_secondary_indexes_internal(sindex_block, std::map<std::string, secondary_index_t>()); } #else void delete_all_secondary_indexes(transaction_t *txn, buf_lock_t *sindex_block) { set_secondary_indexes_internal(txn, sindex_block, std::map<std::string, secondary_index_t>()); } #endif <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern void sendPlayerInfo(void); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); setTimeout(10); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); sendPlayerInfo(); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,-1,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += _advertiseGroups; msg += "&title="; msg += publicizedTitle; setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Don't need to send playerInfo twice, wait for addPlayer<commit_after>/* bzflag * Copyright (c) 1993 - 2005 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ // Provide BZFS with a list server connection /* class header */ #include "ListServerConnection.h" /* system implementation headers */ #include <string.h> #include <string> #include <math.h> #include <errno.h> #include <set> /* common implementation headers */ #include "bzfio.h" #include "version.h" #include "TextUtils.h" #include "Protocol.h" #include "GameKeeper.h" #include "bzfsAPI.h" #include "WorldEventManager.h" /* local implementation headers */ #include "CmdLineOptions.h" // FIXME remove externs! extern PingPacket getTeamCounts(); extern uint16_t curMaxPlayers; extern void sendMessage(int playerIndex, PlayerId targetPlayer, const char *message); extern CmdLineOptions *clOptions; const int ListServerLink::NotConnected = -1; ListServerLink::ListServerLink(std::string listServerURL, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string bzfsUserAgent = "bzfs "; bzfsUserAgent += getAppVersion(); setURL(listServerURL); setUserAgent(bzfsUserAgent); setDNSCachingTime(-1); setTimeout(10); if (clOptions->pingInterface != "") setInterface(clOptions->pingInterface); publicizeAddress = publicizedAddress; publicizeDescription = publicizedTitle; advertiseGroups = _advertiseGroups; //if this c'tor is called, it's safe to publicize publicizeServer = true; queuedRequest = false; // schedule initial ADD message queueMessage(ListServerLink::ADD); } ListServerLink::ListServerLink() { // does not create a usable link, so checks should be placed // in all public member functions to ensure that nothing tries // to happen if publicizeServer is false publicizeServer = false; } ListServerLink::~ListServerLink() { // now tell the list server that we're going away. this can // take some time but we don't want to wait too long. we do // our own multiplexing loop and wait for a maximum of 3 seconds // total. // if we aren't supposed to be publicizing, skip the whole thing // and don't waste 3 seconds. if (!publicizeServer) return; queueMessage(ListServerLink::REMOVE); for (int i = 0; i < 12; i++) { cURLManager::perform(); if (!queuedRequest) break; TimeKeeper::sleep(0.25f); } } void ListServerLink::finalization(char *data, unsigned int length, bool good) { queuedRequest = false; if (good && (length < 2048)) { char buf[2048]; memcpy(buf, data, length); int bytes = length; buf[bytes]=0; char* base = buf; static char *tokGoodIdentifier = "TOKGOOD: "; static char *tokBadIdentifier = "TOKBAD: "; // walks entire reply including HTTP headers while (*base) { // find next newline char* scan = base; while (*scan && *scan != '\r' && *scan != '\n') scan++; // if no newline then no more complete replies if (*scan != '\r' && *scan != '\n') break; while (*scan && (*scan == '\r' || *scan == '\n')) *scan++ = '\0'; DEBUG4("Got line: \"%s\"\n", base); // TODO don't do this if we don't want central logins if (strncmp(base, tokGoodIdentifier, strlen(tokGoodIdentifier)) == 0) { char *callsign, *group; callsign = base + strlen(tokGoodIdentifier); DEBUG3("Got: %s\n", base); group = callsign; while (*group && (*group != ':')) group++; while (*group && (*group == ':')) *group++ = 0; int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } if (playerIndex < curMaxPlayers) { // don't accept the global auth if there's a local account // of the same name and the local account is not marked as // being the same as the global account if (!playerData->accessInfo.hasRealPassword() || playerData->accessInfo.getUserInfo(callsign) .hasGroup("LOCAL.GLOBAL")) { playerData->_LSAState = GameKeeper::Player::verified; if (!playerData->accessInfo.isRegistered()) playerData->accessInfo.storeInfo(NULL); playerData->accessInfo.setPermissionRights(); while (*group) { char *nextgroup = group; while (*nextgroup && (*nextgroup != ':')) nextgroup++; while (*nextgroup && (*nextgroup == ':')) *nextgroup++ = 0; playerData->accessInfo.addGroup(group); group = nextgroup; } playerData->authentication.global(true); sendMessage(ServerPlayer, playerIndex, "Global login approved!"); } else { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected. " "This callsign is registered locally on this " "server."); sendMessage(ServerPlayer, playerIndex, "If the local account is yours, " "/identify, /deregister and reconnnect, " "or ask an admin for the LOCAL.GLOBAL group."); sendMessage(ServerPlayer, playerIndex, "If it is not yours, please ask an admin " "to deregister it so that you may use your global " "callsign."); } playerData->player.clearToken(); } } else if (!strncmp(base, tokBadIdentifier, strlen(tokBadIdentifier))) { char *callsign; callsign = base + strlen(tokBadIdentifier); int playerIndex; GameKeeper::Player *playerData = NULL; for (playerIndex = 0; playerIndex < curMaxPlayers; playerIndex++) { playerData = GameKeeper::Player::getPlayerByIndex(playerIndex); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; if (!TextUtils::compare_nocase(playerData->player.getCallSign(), callsign)) break; } DEBUG3("Got: [%d] %s\n", playerIndex, base); if (playerIndex < curMaxPlayers) { playerData->_LSAState = GameKeeper::Player::failed; sendMessage(ServerPlayer, playerIndex, "Global login rejected, bad token."); playerData->player.clearToken(); } } // next reply base = scan; } } for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if (playerData->_LSAState != GameKeeper::Player::checking) continue; playerData->_LSAState = GameKeeper::Player::timed; } if (nextMessageType != ListServerLink::NONE) { // There was a pending request arrived after we write: // we should redo all the stuff sendQueuedMessages(); } } void ListServerLink::queueMessage(MessageType type) { // ignore if the server is not public if (!publicizeServer) return; // record next message to send. nextMessageType = type; if (!queuedRequest) sendQueuedMessages(); else DEBUG3("There is a message already queued to the list server: not sending this one yet.\n"); } void ListServerLink::sendQueuedMessages() { queuedRequest = true; if (nextMessageType == ListServerLink::ADD) { DEBUG3("Queuing ADD message to list server\n"); bz_ListServerUpdateEvent updateEvent; updateEvent.address = publicizeAddress; updateEvent.description = publicizeDescription; updateEvent.groups = advertiseGroups; worldEventManager.callEvents(bz_eListServerUpdateEvent,-1,&updateEvent); addMe(getTeamCounts(), std::string(updateEvent.address.c_str()), std::string(updateEvent.description.c_str()), std::string(updateEvent.groups.c_str())); lastAddTime = TimeKeeper::getCurrent(); } else if (nextMessageType == ListServerLink::REMOVE) { DEBUG3("Queuing REMOVE message to list server\n"); removeMe(publicizeAddress); } nextMessageType = ListServerLink::NONE; } void ListServerLink::addMe(PingPacket pingInfo, std::string publicizedAddress, std::string publicizedTitle, std::string _advertiseGroups) { std::string msg; std::string hdr; // encode ping reply as ascii hex digits plus NULL char gameInfo[PingPacketHexPackedSize + 1]; pingInfo.packHex(gameInfo); // send ADD message (must send blank line) msg = "action=ADD&nameport="; msg += publicizedAddress; msg += "&version="; msg += getServerVersion(); msg += "&gameinfo="; msg += gameInfo; msg += "&build="; msg += getAppVersion(); msg += "&checktokens="; std::set<std::string> callSigns; // callsign1@ip1=token1%0D%0Acallsign2@ip2=token2%0D%0A for (int i = 0; i < curMaxPlayers; i++) { GameKeeper::Player *playerData = GameKeeper::Player::getPlayerByIndex(i); if (!playerData) continue; if ((playerData->_LSAState != GameKeeper::Player::required) && (playerData->_LSAState != GameKeeper::Player::requesting)) continue; if (callSigns.count(playerData->player.getCallSign())) continue; callSigns.insert(playerData->player.getCallSign()); playerData->_LSAState = GameKeeper::Player::checking; NetHandler *handler = playerData->netHandler; msg += TextUtils::url_encode(playerData->player.getCallSign()); Address addr = handler->getIPAddress(); if (!addr.isPrivate()) { msg += "@"; msg += handler->getTargetIP(); } msg += "="; msg += playerData->player.getToken(); msg += "%0D%0A"; } msg += "&groups="; // *groups=GROUP0%0D%0AGROUP1%0D%0A PlayerAccessMap::iterator itr = groupAccess.begin(); for ( ; itr != groupAccess.end(); itr++) { if (itr->first.substr(0, 6) != "LOCAL.") { msg += itr->first.c_str(); msg += "%0D%0A"; } } msg += "&advertgroups="; msg += _advertiseGroups; msg += "&title="; msg += publicizedTitle; setPostMode(msg); addHandle(); } void ListServerLink::removeMe(std::string publicizedAddress) { std::string msg; msg = "action=REMOVE&nameport="; msg += publicizedAddress; setPostMode(msg); addHandle(); } // Local Variables: *** // mode:C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/* * Copyright 2008-2009 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file iterator_traits.inl * \brief Inline file for iterator_traits.h. */ #include <thrust/iterator/iterator_categories.h> #include <thrust/iterator/detail/iterator_category_to_traversal.h> #include <thrust/detail/type_traits.h> #if __GNUC__ // forward declaration of gnu's __normal_iterator namespace __gnu_cxx { template<typename Iterator, typename Container> class __normal_iterator; } // end __gnu_cxx #endif // __GNUC__ #if _MSC_VER // forward declaration of MSVC's "normal iterators" namespace std { template<typename Value, typename Difference, typename Pointer, typename Reference> struct _Ranit; } // end std #endif // _MSC_VER namespace thrust { template<typename Iterator> struct iterator_value { typedef typename thrust::iterator_traits<Iterator>::value_type type; }; // end iterator_value template<typename Iterator> struct iterator_pointer { typedef typename thrust::iterator_traits<Iterator>::pointer type; }; // end iterator_pointer template<typename Iterator> struct iterator_reference { typedef typename iterator_traits<Iterator>::reference type; }; // end iterator_reference template<typename Iterator> struct iterator_difference { typedef typename thrust::iterator_traits<Iterator>::difference_type type; }; // end iterator_difference template<typename Iterator> struct iterator_space : detail::iterator_category_to_space< typename thrust::iterator_traits<Iterator>::iterator_category > { }; // end iterator_space template <typename Iterator> struct iterator_traversal : detail::iterator_category_to_traversal< typename thrust::iterator_traits<Iterator>::iterator_category > { }; // end iterator_traversal namespace detail { template <typename T> struct is_iterator_traversal : thrust::detail::is_convertible<T, incrementable_traversal_tag> { }; // end is_iterator_traversal template<typename T> struct is_iterator_space : detail::is_convertible<T, space_tag> { }; // end is_iterator_space #ifdef __GNUC__ template<typename T> struct is_gnu_normal_iterator : false_type { }; // end is_gnu_normal_iterator // catch gnu __normal_iterators template<typename Iterator, typename Container> struct is_gnu_normal_iterator< __gnu_cxx::__normal_iterator<Iterator, Container> > : true_type { }; // end is_gnu_normal_iterator #endif // __GNUC__ #ifdef _MSC_VER // catch msvc _Ranit template<typename Iterator> struct is_convertible_to_msvc_Ranit : is_convertible< Iterator, std::_Ranit< typename iterator_value<Iterator>::type, typename iterator_difference<Iterator>::type, typename iterator_pointer<Iterator>::type, typename iterator_reference<Iterator>::type > > {}; #endif // _MSC_VER template<typename T> struct is_trivial_iterator : integral_constant< bool, is_pointer<T>::value | is_device_ptr<T>::value #if __GNUC__ | is_gnu_normal_iterator<T>::value #endif // __GNUC__ #ifdef _MSC_VER | is_convertible_to_msvc_Ranit<T>::value #endif // _MSC_VER > {}; // XXX this should be implemented better template<typename Space1, typename Space2> struct are_spaces_interoperable : thrust::detail::false_type {}; template<> struct are_spaces_interoperable< thrust::host_space_tag, thrust::detail::omp_device_space_tag > : thrust::detail::true_type {}; template<> struct are_spaces_interoperable< thrust::detail::omp_device_space_tag, thrust::host_space_tag > : thrust::detail::true_type {}; } // end namespace detail } // end namespace thrust <commit_msg>Revert change to is_iterator_space which should not have been checked in.<commit_after>/* * Copyright 2008-2009 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*! \file iterator_traits.inl * \brief Inline file for iterator_traits.h. */ #include <thrust/iterator/iterator_categories.h> #include <thrust/iterator/detail/iterator_category_to_traversal.h> #include <thrust/detail/type_traits.h> #if __GNUC__ // forward declaration of gnu's __normal_iterator namespace __gnu_cxx { template<typename Iterator, typename Container> class __normal_iterator; } // end __gnu_cxx #endif // __GNUC__ #if _MSC_VER // forward declaration of MSVC's "normal iterators" namespace std { template<typename Value, typename Difference, typename Pointer, typename Reference> struct _Ranit; } // end std #endif // _MSC_VER namespace thrust { template<typename Iterator> struct iterator_value { typedef typename thrust::iterator_traits<Iterator>::value_type type; }; // end iterator_value template<typename Iterator> struct iterator_pointer { typedef typename thrust::iterator_traits<Iterator>::pointer type; }; // end iterator_pointer template<typename Iterator> struct iterator_reference { typedef typename iterator_traits<Iterator>::reference type; }; // end iterator_reference template<typename Iterator> struct iterator_difference { typedef typename thrust::iterator_traits<Iterator>::difference_type type; }; // end iterator_difference template<typename Iterator> struct iterator_space : detail::iterator_category_to_space< typename thrust::iterator_traits<Iterator>::iterator_category > { }; // end iterator_space template <typename Iterator> struct iterator_traversal : detail::iterator_category_to_traversal< typename thrust::iterator_traits<Iterator>::iterator_category > { }; // end iterator_traversal namespace detail { template <typename T> struct is_iterator_traversal : thrust::detail::is_convertible<T, incrementable_traversal_tag> { }; // end is_iterator_traversal template<typename T> struct is_iterator_space : detail::or_< detail::is_convertible<T, any_space_tag>, detail::or_< detail::is_convertible<T, host_space_tag>, detail::is_convertible<T, device_space_tag> > > { }; // end is_iterator_space #ifdef __GNUC__ template<typename T> struct is_gnu_normal_iterator : false_type { }; // end is_gnu_normal_iterator // catch gnu __normal_iterators template<typename Iterator, typename Container> struct is_gnu_normal_iterator< __gnu_cxx::__normal_iterator<Iterator, Container> > : true_type { }; // end is_gnu_normal_iterator #endif // __GNUC__ #ifdef _MSC_VER // catch msvc _Ranit template<typename Iterator> struct is_convertible_to_msvc_Ranit : is_convertible< Iterator, std::_Ranit< typename iterator_value<Iterator>::type, typename iterator_difference<Iterator>::type, typename iterator_pointer<Iterator>::type, typename iterator_reference<Iterator>::type > > {}; #endif // _MSC_VER template<typename T> struct is_trivial_iterator : integral_constant< bool, is_pointer<T>::value | is_device_ptr<T>::value #if __GNUC__ | is_gnu_normal_iterator<T>::value #endif // __GNUC__ #ifdef _MSC_VER | is_convertible_to_msvc_Ranit<T>::value #endif // _MSC_VER > {}; // XXX this should be implemented better template<typename Space1, typename Space2> struct are_spaces_interoperable : thrust::detail::false_type {}; template<> struct are_spaces_interoperable< thrust::host_space_tag, thrust::detail::omp_device_space_tag > : thrust::detail::true_type {}; template<> struct are_spaces_interoperable< thrust::detail::omp_device_space_tag, thrust::host_space_tag > : thrust::detail::true_type {}; } // end namespace detail } // end namespace thrust <|endoftext|>
<commit_before>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "MessageUtilities.h" template <> bool MessageUtilities::parse(const char *str, bool &dest) { if (strcasecmp(str, "true") == 0 || strcasecmp(str, "1") == 0) dest = true; else if (strcasecmp(str, "false") == 0 || strcasecmp(str, "0") == 0) dest = false; else return false; return true; } template <> bool MessageUtilities::parse(const char *str, double &dest) { if (sscanf(str,"%lf",&dest) != 1) return false; /* We don't want NaN no matter what - it's of no use in this * scenario. (And strtof will allow the string "NAN" as NaN) */ if (isnan(dest)) dest = 0.0; return true; } template <> bool MessageUtilities::parse(const char *str, float &dest) { double tmp; // Use double parsing and convert if (!MessageUtilities::parse(str, tmp)) return false; dest = (float)tmp; return true; } template <> bool MessageUtilities::parse(const char *str, uint64_t &dest) { if (sscanf(str,"%lld",(long long int *)&dest) != 1) return false; return true; } template<> bool MessageUtilities::parse(const char *str, uint32_t &dest) { uint64_t tmp; if (!MessageUtilities::parse(str, tmp)) return false; dest = (uint32_t) tmp; return true; } template <> bool MessageUtilities::parse(const char *str, std::string &dest) { dest = str; return true; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <commit_msg>Type long long not allowed in ISO C++ so use intmax_t. Still produces a warning for sscanf but at least no error.<commit_after>/* bzflag * Copyright (c) 1993 - 2008 Tim Riker * * This package is free software; you can redistribute it and/or * modify it under the terms of the license found in the file * named LICENSE that should have accompanied this file. * * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. */ #include "MessageUtilities.h" template <> bool MessageUtilities::parse(const char *str, bool &dest) { if (strcasecmp(str, "true") == 0 || strcasecmp(str, "1") == 0) dest = true; else if (strcasecmp(str, "false") == 0 || strcasecmp(str, "0") == 0) dest = false; else return false; return true; } template <> bool MessageUtilities::parse(const char *str, double &dest) { if (sscanf(str,"%lf",&dest) != 1) return false; /* We don't want NaN no matter what - it's of no use in this * scenario. (And strtof will allow the string "NAN" as NaN) */ if (isnan(dest)) dest = 0.0; return true; } template <> bool MessageUtilities::parse(const char *str, float &dest) { double tmp; // Use double parsing and convert if (!MessageUtilities::parse(str, tmp)) return false; dest = (float)tmp; return true; } template <> bool MessageUtilities::parse(const char *str, uint64_t &dest) { if (sscanf(str,"%lld",(intmax_t *)&dest) != 1) return false; return true; } template<> bool MessageUtilities::parse(const char *str, uint32_t &dest) { uint64_t tmp; if (!MessageUtilities::parse(str, tmp)) return false; dest = (uint32_t) tmp; return true; } template <> bool MessageUtilities::parse(const char *str, std::string &dest) { dest = str; return true; } // Local Variables: *** // mode: C++ *** // tab-width: 8 *** // c-basic-offset: 2 *** // indent-tabs-mode: t *** // End: *** // ex: shiftwidth=2 tabstop=8 <|endoftext|>
<commit_before>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAddImageFilter.h" #include "itkAnisotropicDiffusionFunction.h" #include "itkAnisotropicDiffusionImageFilter.h" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBSplineCenteredL2ResampleImageFilterBase.txx" #include "itkBSplineCenteredResampleImageFilterBase.txx" #include "itkBSplineDecompositionImageFilter.txx" #include "itkBSplineDownsampleImageFilter.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBSplineL2ResampleImageFilterBase.txx" #include "itkBSplineResampleImageFilterBase.txx" #include "itkBSplineResampleImageFunction.h" #include "itkBSplineUpsampleImageFilter.txx" #include "itkBilateralImageFilter.txx" #include "itkBinaryDilateImageFilter.txx" #include "itkBinaryErodeImageFilter.txx" #include "itkBinaryFunctorImageFilter.txx" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMedianImageFilter.txx" #include "itkBinaryThresholdImageFilter.txx" #include "itkBinomialBlurImageFilter.txx" #include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx" #include "itkBloxBoundaryPointToCoreAtomImageFilter.txx" #include "itkCannyEdgeDetectionImageFilter.txx" #include "itkCastImageFilter.h" #include "itkChangeInformationImageFilter.txx" #include "itkComposeRGBImageFilter.h" #include "itkConfidenceConnectedImageFilter.txx" #include "itkConnectedThresholdImageFilter.txx" #include "itkConstantPadImageFilter.txx" #include "itkCosImageFilter.h" #include "itkCropImageFilter.txx" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkDanielssonDistanceMapImageFilter.txx" #include "itkDerivativeImageFilter.txx" #include "itkDifferenceOfGaussiansGradientImageFilter.txx" #include "itkDilateObjectMorphologyImageFilter.txx" #include "itkDirectedHausdorffDistanceImageFilter.txx" #include "itkDiscreteGaussianImageFilter.txx" #include "itkDivideImageFilter.h" #include "itkEdgePotentialImageFilter.h" #include "itkEigenAnalysis2DImageFilter.txx" #include "itkErodeObjectMorphologyImageFilter.txx" #include "itkExpImageFilter.h" #include "itkExpNegativeImageFilter.h" #include "itkExpandImageFilter.txx" #include "itkExtractImageFilter.txx" #include "itkExtractImageFilterRegionCopier.h" #include "itkFlipImageFilter.txx" #include "itkGaussianImageSource.txx" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientImageFilter.txx" #include "itkGradientImageToBloxBoundaryPointImageFilter.txx" #include "itkGradientMagnitudeImageFilter.txx" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx" #include "itkGradientNDAnisotropicDiffusionFunction.txx" #include "itkGradientRecursiveGaussianImageFilter.txx" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleDilateImageFilter.txx" #include "itkGrayscaleErodeImageFilter.txx" #include "itkGrayscaleFunctionDilateImageFilter.txx" #include "itkGrayscaleFunctionErodeImageFilter.txx" #include "itkHardConnectedComponentImageFilter.txx" #include "itkHausdorffDistanceImageFilter.txx" #include "itkImageToMeshFilter.txx" #include "itkImageToParametricSpaceFilter.txx" #include "itkImportImageFilter.txx" #include "itkInteriorExteriorMeshFilter.txx" #include "itkInterpolateImageFilter.txx" #include "itkInterpolateImagePointsFilter.txx" #include "itkIsolatedConnectedImageFilter.txx" #include "itkJoinImageFilter.h" #include "itkLaplacianImageFilter.txx" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMaskImageFilter.h" #include "itkMaximumImageFilter.h" #include "itkMeanImageFilter.txx" #include "itkMedianImageFilter.txx" #include "itkMinimumImageFilter.h" #include "itkMinimumMaximumImageCalculator.txx" #include "itkMinimumMaximumImageFilter.txx" #include "itkMirrorPadImageFilter.txx" #include "itkMorphologyImageFilter.txx" #include "itkMultiplyImageFilter.h" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.txx" #include "itkNeighborhoodConnectedImageFilter.txx" #include "itkNeighborhoodOperatorImageFilter.txx" #include "itkNonThreadedShrinkImageFilter.txx" #include "itkNormalizeImageFilter.txx" #include "itkObjectMorphologyImageFilter.txx" #include "itkPadImageFilter.txx" #include "itkParametricSpaceToImageSpaceMeshFilter.txx" #include "itkPermuteAxesImageFilter.txx" #include "itkPlaheImageFilter.txx" #include "itkRandomImageSource.txx" #include "itkRecursiveGaussianImageFilter.txx" #include "itkRecursiveSeparableImageFilter.txx" #include "itkReflectImageFilter.txx" #include "itkReflectiveImageRegionConstIterator.txx" #include "itkReflectiveImageRegionIterator.txx" #include "itkResampleImageFilter.txx" #include "itkRescaleIntensityImageFilter.txx" #include "itkScalarAnisotropicDiffusionFunction.txx" #include "itkScalarToArrayCastImageFilter.h" #include "itkShiftScaleImageFilter.txx" #include "itkShrinkImageFilter.txx" #include "itkSigmoidImageFilter.h" #include "itkSimilarityIndexImageFilter.txx" #include "itkSinImageFilter.h" #include "itkSobelEdgeDetectionImageFilter.txx" #include "itkSparseFieldLayer.txx" #include "itkSparseFieldLevelSetImageFilter.txx" #include "itkSpatialFunctionImageEvaluatorFilter.txx" #include "itkSpatialObjectToImageFilter.txx" #include "itkSqrtImageFilter.h" #include "itkSquaredDifferenceImageFilter.h" #include "itkStatisticsImageFilter.txx" #include "itkStreamingImageFilter.txx" #include "itkSubtractImageFilter.h" #include "itkTanImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.txx" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.txx" #include "itkTobogganImageFilter.txx" #include "itkTransformMeshFilter.txx" #include "itkTwoOutputExampleImageFilter.txx" #include "itkUnaryFunctorImageFilter.txx" #include "itkVTKImageExport.txx" #include "itkVTKImageExportBase.h" #include "itkVTKImageImport.txx" #include "itkVectorAnisotropicDiffusionFunction.txx" #include "itkVectorCastImageFilter.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkVectorExpandImageFilter.txx" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientMagnitudeImageFilter.txx" #include "itkVectorGradientNDAnisotropicDiffusionFunction.txx" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkVectorNeighborhoodOperatorImageFilter.txx" #include "itkWarpImageFilter.txx" #include "itkWrapPadImageFilter.txx" #include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx" #include "itkZeroCrossingImageFilter.txx" int main ( int , char* ) { return 0; } <commit_msg>ENH: Updated to latest headers<commit_after>/*========================================================================= Program: Insight Segmentation & Registration Toolkit (ITK) Module: Language: C++ Date: Version: Copyright (c) 2000 National Library of Medicine All rights reserved. See COPYRIGHT.txt for copyright details. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include <iostream> // This file has been generated by BuildHeaderTest.tcl // Test to include each header file for Insight #include "itkAcosImageFilter.h" #include "itkAdaptImageFilter.h" #include "itkAddImageFilter.h" #include "itkAnisotropicDiffusionFunction.h" #include "itkAnisotropicDiffusionImageFilter.h" #include "itkAsinImageFilter.h" #include "itkAtan2ImageFilter.h" #include "itkAtanImageFilter.h" #include "itkBSplineCenteredL2ResampleImageFilterBase.txx" #include "itkBSplineCenteredResampleImageFilterBase.txx" #include "itkBSplineDecompositionImageFilter.txx" #include "itkBSplineDownsampleImageFilter.txx" #include "itkBSplineInterpolateImageFunction.txx" #include "itkBSplineL2ResampleImageFilterBase.txx" #include "itkBSplineResampleImageFilterBase.txx" #include "itkBSplineResampleImageFunction.h" #include "itkBSplineUpsampleImageFilter.txx" #include "itkBilateralImageFilter.txx" #include "itkBinaryDilateImageFilter.txx" #include "itkBinaryErodeImageFilter.txx" #include "itkBinaryFunctorImageFilter.txx" #include "itkBinaryMagnitudeImageFilter.h" #include "itkBinaryMedianImageFilter.txx" #include "itkBinaryThresholdImageFilter.txx" #include "itkBinomialBlurImageFilter.txx" #include "itkBloxBoundaryPointImageToBloxBoundaryProfileImageFilter.txx" #include "itkBloxBoundaryPointToCoreAtomImageFilter.txx" #include "itkCannyEdgeDetectionImageFilter.txx" #include "itkCastImageFilter.h" #include "itkChangeInformationImageFilter.txx" #include "itkComposeRGBImageFilter.h" #include "itkConfidenceConnectedImageFilter.txx" #include "itkConnectedThresholdImageFilter.txx" #include "itkConstantPadImageFilter.txx" #include "itkCosImageFilter.h" #include "itkCropImageFilter.txx" #include "itkCurvatureAnisotropicDiffusionImageFilter.h" #include "itkCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkDanielssonDistanceMapImageFilter.txx" #include "itkDerivativeImageFilter.txx" #include "itkDifferenceOfGaussiansGradientImageFilter.txx" #include "itkDilateObjectMorphologyImageFilter.txx" #include "itkDirectedHausdorffDistanceImageFilter.txx" #include "itkDiscreteGaussianImageFilter.txx" #include "itkDivideImageFilter.h" #include "itkEdgePotentialImageFilter.h" #include "itkEigenAnalysis2DImageFilter.txx" #include "itkErodeObjectMorphologyImageFilter.txx" #include "itkExpImageFilter.h" #include "itkExpNegativeImageFilter.h" #include "itkExpandImageFilter.txx" #include "itkExtractImageFilter.txx" #include "itkExtractImageFilterRegionCopier.h" #include "itkFlipImageFilter.txx" #include "itkGaussianImageSource.txx" #include "itkGradientAnisotropicDiffusionImageFilter.h" #include "itkGradientImageFilter.txx" #include "itkGradientImageToBloxBoundaryPointImageFilter.txx" #include "itkGradientMagnitudeImageFilter.txx" #include "itkGradientMagnitudeRecursiveGaussianImageFilter.txx" #include "itkGradientNDAnisotropicDiffusionFunction.txx" #include "itkGradientRecursiveGaussianImageFilter.txx" #include "itkGradientToMagnitudeImageFilter.h" #include "itkGrayscaleDilateImageFilter.txx" #include "itkGrayscaleErodeImageFilter.txx" #include "itkGrayscaleFunctionDilateImageFilter.txx" #include "itkGrayscaleFunctionErodeImageFilter.txx" #include "itkHardConnectedComponentImageFilter.txx" #include "itkHausdorffDistanceImageFilter.txx" #include "itkImageToMeshFilter.txx" #include "itkImageToParametricSpaceFilter.txx" #include "itkImportImageFilter.txx" #include "itkInteriorExteriorMeshFilter.txx" #include "itkInterpolateImageFilter.txx" #include "itkInterpolateImagePointsFilter.txx" #include "itkIsolatedConnectedImageFilter.txx" #include "itkJoinImageFilter.h" #include "itkLaplacianImageFilter.txx" #include "itkLog10ImageFilter.h" #include "itkLogImageFilter.h" #include "itkMaskImageFilter.h" #include "itkMaximumImageFilter.h" #include "itkMeanImageFilter.txx" #include "itkMedianImageFilter.txx" #include "itkMinimumImageFilter.h" #include "itkMinimumMaximumImageCalculator.txx" #include "itkMinimumMaximumImageFilter.txx" #include "itkMirrorPadImageFilter.txx" #include "itkMorphologyImageFilter.txx" #include "itkMultiplyImageFilter.h" #include "itkNaryAddImageFilter.h" #include "itkNaryFunctorImageFilter.txx" #include "itkNeighborhoodConnectedImageFilter.txx" #include "itkNeighborhoodOperatorImageFilter.txx" #include "itkNonThreadedShrinkImageFilter.txx" #include "itkNormalizeImageFilter.txx" #include "itkObjectMorphologyImageFilter.txx" #include "itkPadImageFilter.txx" #include "itkParametricSpaceToImageSpaceMeshFilter.txx" #include "itkPermuteAxesImageFilter.txx" #include "itkPlaheImageFilter.txx" #include "itkRandomImageSource.txx" #include "itkRecursiveGaussianImageFilter.txx" #include "itkRecursiveSeparableImageFilter.txx" #include "itkReflectImageFilter.txx" #include "itkReflectiveImageRegionConstIterator.txx" #include "itkReflectiveImageRegionIterator.txx" #include "itkResampleImageFilter.txx" #include "itkRescaleIntensityImageFilter.txx" #include "itkScalarAnisotropicDiffusionFunction.txx" #include "itkScalarToArrayCastImageFilter.h" #include "itkShiftScaleImageFilter.txx" #include "itkShrinkImageFilter.txx" #include "itkSigmoidImageFilter.h" #include "itkSimilarityIndexImageFilter.txx" #include "itkSinImageFilter.h" #include "itkSobelEdgeDetectionImageFilter.txx" #include "itkSparseFieldLayer.txx" #include "itkSparseFieldLevelSetImageFilter.txx" #include "itkSpatialFunctionImageEvaluatorFilter.txx" #include "itkSpatialObjectToImageFilter.txx" #include "itkSqrtImageFilter.h" #include "itkSquareImageFilter.h" #include "itkSquaredDifferenceImageFilter.h" #include "itkStatisticsImageFilter.txx" #include "itkStreamingImageFilter.txx" #include "itkSubtractImageFilter.h" #include "itkTanImageFilter.h" #include "itkTernaryAddImageFilter.h" #include "itkTernaryFunctorImageFilter.txx" #include "itkTernaryMagnitudeImageFilter.h" #include "itkTernaryMagnitudeSquaredImageFilter.h" #include "itkThresholdImageFilter.txx" #include "itkTobogganImageFilter.txx" #include "itkTransformMeshFilter.txx" #include "itkTwoOutputExampleImageFilter.txx" #include "itkUnaryFunctorImageFilter.txx" #include "itkVTKImageExport.txx" #include "itkVTKImageExportBase.h" #include "itkVTKImageImport.txx" #include "itkVectorAnisotropicDiffusionFunction.txx" #include "itkVectorCastImageFilter.h" #include "itkVectorCurvatureAnisotropicDiffusionImageFilter.h" #include "itkVectorCurvatureNDAnisotropicDiffusionFunction.txx" #include "itkVectorExpandImageFilter.txx" #include "itkVectorGradientAnisotropicDiffusionImageFilter.h" #include "itkVectorGradientMagnitudeImageFilter.txx" #include "itkVectorGradientNDAnisotropicDiffusionFunction.txx" #include "itkVectorIndexSelectionCastImageFilter.h" #include "itkVectorNeighborhoodOperatorImageFilter.txx" #include "itkWarpImageFilter.txx" #include "itkWrapPadImageFilter.txx" #include "itkZeroCrossingBasedEdgeDetectionImageFilter.txx" #include "itkZeroCrossingImageFilter.txx" int main ( int , char* ) { return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: passworddlg.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: mav $ $Date: 2002-10-31 11:08:38 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVT_FILEDLG_HXX #include <svtools/filedlg.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef UUI_IDS_HRC #include <ids.hrc> #endif #ifndef UUI_PASSWORDDLG_HRC #include <passworddlg.hrc> #endif #ifndef UUI_PASSWORDDLG_HXX #include <passworddlg.hxx> #endif // PasswordDialog--------------------------------------------------------- // ----------------------------------------------------------------------- IMPL_LINK( PasswordDialog, OKHdl_Impl, OKButton *, EMPTYARG ) { EndDialog( RET_OK ); return 1; } // ----------------------------------------------------------------------- PasswordDialog::PasswordDialog ( Window* pParent, ::com::sun::star::task::PasswordRequestMode aDialogMode, ResMgr* pResMgr ) : ModalDialog( pParent, ResId( DLG_UUI_PASSWORD, pResMgr ) ), aFTPassword ( this, ResId( FT_PASSWORD ) ), aEDPassword ( this, ResId( ED_PASSWORD ) ), aOKBtn ( this, ResId( BTN_PASSWORD_OK ) ), aCancelBtn ( this, ResId( BTN_PASSWORD_CANCEL ) ), aHelpBtn ( this, ResId( BTN_PASSWORD_HELP ) ), nDialogMode ( aDialogMode ), pResourceMgr ( pResMgr ) { if( nDialogMode == ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER ) { String aErrorMsg( ResId( STR_ERROR_PASSWORD_WRONG, pResourceMgr )); ErrorBox aErrorBox( this, WB_OK, aErrorMsg ); aErrorBox.Execute(); } FreeResource(); aOKBtn.SetClickHdl( LINK( this, PasswordDialog, OKHdl_Impl ) ); }; <commit_msg>INTEGRATION: CWS fwklhf01 (1.3.142); FILE MERGED 2004/06/23 08:18:00 mav 1.3.142.1: #i30599# use parent when dialog itself is not visible<commit_after>/************************************************************************* * * $RCSfile: passworddlg.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2004-07-23 11:14:22 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (the "License"); You may not use this file * except in compliance with the License. You may obtain a copy of the * License at http://www.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVT_FILEDLG_HXX #include <svtools/filedlg.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef UUI_IDS_HRC #include <ids.hrc> #endif #ifndef UUI_PASSWORDDLG_HRC #include <passworddlg.hrc> #endif #ifndef UUI_PASSWORDDLG_HXX #include <passworddlg.hxx> #endif // PasswordDialog--------------------------------------------------------- // ----------------------------------------------------------------------- IMPL_LINK( PasswordDialog, OKHdl_Impl, OKButton *, EMPTYARG ) { EndDialog( RET_OK ); return 1; } // ----------------------------------------------------------------------- PasswordDialog::PasswordDialog ( Window* pParent, ::com::sun::star::task::PasswordRequestMode aDialogMode, ResMgr* pResMgr ) : ModalDialog( pParent, ResId( DLG_UUI_PASSWORD, pResMgr ) ), aFTPassword ( this, ResId( FT_PASSWORD ) ), aEDPassword ( this, ResId( ED_PASSWORD ) ), aOKBtn ( this, ResId( BTN_PASSWORD_OK ) ), aCancelBtn ( this, ResId( BTN_PASSWORD_CANCEL ) ), aHelpBtn ( this, ResId( BTN_PASSWORD_HELP ) ), nDialogMode ( aDialogMode ), pResourceMgr ( pResMgr ) { if( nDialogMode == ::com::sun::star::task::PasswordRequestMode_PASSWORD_REENTER ) { String aErrorMsg( ResId( STR_ERROR_PASSWORD_WRONG, pResourceMgr )); ErrorBox aErrorBox( pParent, WB_OK, aErrorMsg ); aErrorBox.Execute(); } FreeResource(); aOKBtn.SetClickHdl( LINK( this, PasswordDialog, OKHdl_Impl ) ); }; <|endoftext|>
<commit_before>#ifndef ORIGEN_HPP_INCLUDED #define ORIGEN_HPP_INCLUDED #define ORIGEN_VERSION "0.5.0" #ifndef debugger #define debugger __asm__("int $3"); #endif #include "origen/utils.hpp" #include "origen/helpers.hpp" #include "origen/site.hpp" namespace Origen { extern vector<Site> Sites; Utils::Version version(); Site& site(); Site& site(int site); } #endif <commit_msg>Wrote new version in C++ code<commit_after>#ifndef ORIGEN_HPP_INCLUDED #define ORIGEN_HPP_INCLUDED #define ORIGEN_VERSION "0.6.0" #ifndef debugger #define debugger __asm__("int $3"); #endif #include "origen/utils.hpp" #include "origen/helpers.hpp" #include "origen/site.hpp" namespace Origen { extern vector<Site> Sites; Utils::Version version(); Site& site(); Site& site(int site); } #endif <|endoftext|>
<commit_before>#include "PhysicallyBasedMaterial.h" #include "BindIndexInfo.h" using namespace Rendering; using namespace Rendering::Buffer; using namespace Rendering::Shader; using namespace Rendering::Texture; void PhysicallyBasedMaterial::Initialize(Device::DirectX& dx) { auto indexer = GetConstBufferBook().GetIndexer(); uint findIdx = indexer.Find(ParamCB::GetKey()); // Error, param const buffer was already allocated assert(findIdx == ConstBuffers::IndexerType::FailIndex()); BindConstBuffer bind; { ConstBuffer& paramCB = bind.resource; paramCB.Initialize(dx, sizeof(ParamCB)); bind.bindIndex = static_cast<uint>(ConstBufferBindIndex::PhysicallyBasedMaterial); bind.useCS = false; bind.useGS = false; bind.useVS = false; bind.usePS = true; } GetConstBufferBook().Add(ParamCB::GetKey(), bind); } void PhysicallyBasedMaterial::Destroy() { } void PhysicallyBasedMaterial::UpdateConstBuffer(Device::DirectX& dx) { ParamCB param; param.mainColor_alpha = ( (static_cast<uint>(_mainColor.r * 255.0f) & 0xff) << 24 | (static_cast<uint>(_mainColor.g * 255.0f) & 0xff) << 16 | (static_cast<uint>(_mainColor.b * 255.0f) & 0xff) << 8 | (static_cast<uint>(_mainColor.a * 255.0f) & 0xff) ); param.emissiveColor_Metallic = ((static_cast<uint>(_emissiveColor.r * 255.0f) & 0xff) << 24 | (static_cast<uint>(_emissiveColor.g * 255.0f) & 0xff) << 16 | (static_cast<uint>(_emissiveColor.b * 255.0f) & 0xff) << 8 | (static_cast<uint>(_metallic * 255.0f) & 0xff)); uint scaledSpecularity = static_cast<uint>(_specularity * 255.0f) & 0xff; uint scaledRoughness = static_cast<uint>(_roughness * 255.0f) & 0xff; uint existTextureFlag = 0; { const auto& indexer = GetTextureBook().GetIndexer(); existTextureFlag |= static_cast<uint>(indexer.Has(GetDiffuseMapKey())) << 0; existTextureFlag |= static_cast<uint>(indexer.Has(GetNormalMapKey())) << 1; existTextureFlag |= static_cast<uint>(indexer.Has(GetOpacityMapKey())) << 2; existTextureFlag |= static_cast<uint>(indexer.Has(GetHeightMapKey())) << 3; existTextureFlag |= static_cast<uint>(indexer.Has(GetMetallicMapKey())) << 4; existTextureFlag |= static_cast<uint>(indexer.Has(GetOcclusionMapKey())) << 5; existTextureFlag |= static_cast<uint>(indexer.Has(GetRoughnessMapKey())) << 6; existTextureFlag |= static_cast<uint>(indexer.Has(GetEmissionMapKey())) << 7; } uint resultFlag = (scaledRoughness << 24) | (scaledSpecularity << 16) | (existTextureFlag & 0xffff); param.roughness_specularity_existTextureFlag = resultFlag; float ior = min(max(0.0f, _ior), 1.0f) * 255.0f; param.flag_ior = (static_cast<uint>(_flag) << 8) | static_cast<uint>(ior); auto indexer = GetConstBufferBook().GetIndexer(); uint findIndex = indexer.Find(ParamCB::GetKey()); assert(findIndex != decltype(indexer)::FailIndex()); GetConstBufferBook().Get(findIndex).resource.UpdateSubResource(dx, &param); _dirty = false; } void PhysicallyBasedMaterial::UpdateMap(const std::string& key, TextureBindIndex bind, const Texture::Texture2D& tex) { auto& textureBook = GetTextureBook(); if (textureBook.GetIndexer().Has(key) == false) { //BindTextured2D bindTex2D; //{ // //bindTex2D.resource = tex; // //bindTex2D.bindIndex = static_cast<uint>(bind); // //bindTex2D.useVS = bindTex2D.useGS = bindTex2D.useCS = false; // //bindTex2D.usePS = true; //} //textureBook.Add(key, bindTex2D); } else { uint findIdx = textureBook.GetIndexer().Find(key); //textureBook.Get(findIdx).resource = tex; } } <commit_msg>Update PhysicallyBasedMaterial.cpp<commit_after>#include "PhysicallyBasedMaterial.h" #include "BindIndexInfo.h" using namespace Rendering; using namespace Rendering::Buffer; using namespace Rendering::Shader; using namespace Rendering::Texture; void PhysicallyBasedMaterial::Initialize(Device::DirectX& dx) { auto indexer = GetConstBufferBook().GetIndexer(); uint findIdx = indexer.Find(ParamCB::GetKey()); // Error, param const buffer was already allocated assert(findIdx == ConstBuffers::IndexerType::FailIndex()); BindConstBuffer bind; { ConstBuffer& paramCB = bind.resource; paramCB.Initialize(dx, sizeof(ParamCB)); bind.bindIndex = static_cast<uint>(ConstBufferBindIndex::PhysicallyBasedMaterial); bind.useCS = false; bind.useGS = false; bind.useVS = false; bind.usePS = true; } GetConstBufferBook().Add(ParamCB::GetKey(), bind); } void PhysicallyBasedMaterial::Destroy() { } void PhysicallyBasedMaterial::UpdateConstBuffer(Device::DirectX& dx) { ParamCB param; param.mainColor_alpha = ( (static_cast<uint>(_mainColor.r * 255.0f) & 0xff) << 24 | (static_cast<uint>(_mainColor.g * 255.0f) & 0xff) << 16 | (static_cast<uint>(_mainColor.b * 255.0f) & 0xff) << 8 | (static_cast<uint>(_mainColor.a * 255.0f) & 0xff) ); param.emissiveColor_Metallic = ((static_cast<uint>(_emissiveColor.r * 255.0f) & 0xff) << 24 | (static_cast<uint>(_emissiveColor.g * 255.0f) & 0xff) << 16 | (static_cast<uint>(_emissiveColor.b * 255.0f) & 0xff) << 8 | (static_cast<uint>(_metallic * 255.0f) & 0xff)); uint scaledSpecularity = static_cast<uint>(_specularity * 255.0f) & 0xff; uint scaledRoughness = static_cast<uint>(_roughness * 255.0f) & 0xff; uint existTextureFlag = 0; { const auto& indexer = GetTextureBook().GetIndexer(); existTextureFlag |= static_cast<uint>(indexer.Has(GetDiffuseMapKey())) << 0; existTextureFlag |= static_cast<uint>(indexer.Has(GetNormalMapKey())) << 1; existTextureFlag |= static_cast<uint>(indexer.Has(GetOpacityMapKey())) << 2; existTextureFlag |= static_cast<uint>(indexer.Has(GetHeightMapKey())) << 3; existTextureFlag |= static_cast<uint>(indexer.Has(GetMetallicMapKey())) << 4; existTextureFlag |= static_cast<uint>(indexer.Has(GetOcclusionMapKey())) << 5; existTextureFlag |= static_cast<uint>(indexer.Has(GetRoughnessMapKey())) << 6; existTextureFlag |= static_cast<uint>(indexer.Has(GetEmissionMapKey())) << 7; } uint resultFlag = (scaledRoughness << 24) | (scaledSpecularity << 16) | (existTextureFlag & 0xffff); param.roughness_specularity_existTextureFlag = resultFlag; float ior = min(max(0.0f, _ior), 1.0f) * 255.0f; param.flag_ior = (static_cast<uint>(_flag) << 8) | static_cast<uint>(ior); auto indexer = GetConstBufferBook().GetIndexer(); uint findIndex = indexer.Find(ParamCB::GetKey()); assert(findIndex != decltype(indexer)::FailIndex()); GetConstBufferBook().Get(findIndex).resource.UpdateSubResource(dx, &param); _dirty = false; } void PhysicallyBasedMaterial::RegistTexture(const std::string& key, TextureBindIndex bind, const Texture::Texture2D& tex) { auto& textureBook = GetTextureBook(); if (textureBook.GetIndexer().Has(key) == false) { BindTextured2D bindTex2D; { bindTex2D.resource = tex; bindTex2D.bindIndex = static_cast<uint>(bind); bindTex2D.useVS = bindTex2D.useGS = bindTex2D.useCS = false; bindTex2D.usePS = true; } textureBook.Add(key, bindTex2D); } else { uint findIdx = textureBook.GetIndexer().Find(key); textureBook.Get(findIdx).resource = tex; } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkClipDataSet.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkClipDataSet.h" #include "vtkMergePoints.h" #include "vtkObjectFactory.h" #include "vtkFloatArray.h" #include <math.h> vtkCxxRevisionMacro(vtkClipDataSet, "1.15"); vtkStandardNewMacro(vtkClipDataSet); //---------------------------------------------------------------------------- // Construct with user-specified implicit function; InsideOut turned off; value // set to 0.0; and generate clip scalars turned off. vtkClipDataSet::vtkClipDataSet(vtkImplicitFunction *cf) { this->ClipFunction = cf; this->InsideOut = 0; this->Locator = NULL; this->Value = 0.0; this->GenerateClipScalars = 0; this->GenerateClippedOutput = 0; this->vtkSource::SetNthOutput(1,vtkUnstructuredGrid::New()); this->Outputs[1]->Delete(); this->InputScalarsSelection = NULL; } //---------------------------------------------------------------------------- vtkClipDataSet::~vtkClipDataSet() { if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } this->SetClipFunction(NULL); this->SetInputScalarsSelection(NULL); } //---------------------------------------------------------------------------- // Overload standard modified time function. If Clip functions is modified, // then this object is modified as well. unsigned long vtkClipDataSet::GetMTime() { unsigned long mTime=this->vtkDataSetToUnstructuredGridFilter::GetMTime(); unsigned long time; if ( this->ClipFunction != NULL ) { time = this->ClipFunction->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if ( this->Locator != NULL ) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } vtkUnstructuredGrid *vtkClipDataSet::GetClippedOutput() { if (this->NumberOfOutputs < 2) { return NULL; } return (vtkUnstructuredGrid *)(this->Outputs[1]); } //---------------------------------------------------------------------------- // // Clip through data generating surface. // void vtkClipDataSet::Execute() { vtkDataSet *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkUnstructuredGrid *clippedOutput = this->GetClippedOutput(); if (input == NULL) { return; } vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType numCells = input->GetNumberOfCells(); vtkPointData *inPD=input->GetPointData(), *outPD = output->GetPointData(); vtkCellData *inCD=input->GetCellData(); vtkCellData *outCD[2]; vtkPoints *newPoints; vtkFloatArray *cellScalars; vtkDataArray *clipScalars; vtkPoints *cellPts; vtkIdList *cellIds; float s; vtkIdType npts; vtkIdType *pts; int cellType = 0; vtkIdType i; int j; vtkIdType estimatedSize; vtkUnsignedCharArray *types[2]; vtkIntArray *locs[2]; int numOutputs = 1; vtkIdType newCellId; vtkDebugMacro(<< "Clipping dataset"); // Initialize self; create output objects // if ( numPts < 1 ) { //vtkErrorMacro(<<"No data to clip"); return; } if ( !this->ClipFunction && this->GenerateClipScalars ) { vtkErrorMacro(<<"Cannot generate clip scalars if no clip function defined"); return; } // allocate the output and associated helper classes estimatedSize = numCells; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } cellScalars = vtkFloatArray::New(); cellScalars->Allocate(VTK_CELL_SIZE); vtkCellArray *conn[2]; conn[0] = vtkCellArray::New(); conn[0]->Allocate(estimatedSize,estimatedSize/2); conn[0]->InitTraversal(); types[0] = vtkUnsignedCharArray::New(); types[0]->Allocate(estimatedSize,estimatedSize/2); locs[0] = vtkIntArray::New(); locs[0]->Allocate(estimatedSize,estimatedSize/2); if ( this->GenerateClippedOutput ) { numOutputs = 2; conn[1] = vtkCellArray::New(); conn[1]->Allocate(estimatedSize,estimatedSize/2); conn[1]->InitTraversal(); types[1] = vtkUnsignedCharArray::New(); types[1]->Allocate(estimatedSize,estimatedSize/2); locs[1] = vtkIntArray::New(); locs[1]->Allocate(estimatedSize,estimatedSize/2); } newPoints = vtkPoints::New(); newPoints->Allocate(numPts,numPts/2); // locator used to merge potentially duplicate points if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (newPoints, input->GetBounds()); // Determine whether we're clipping with input scalars or a clip function // and do necessary setup. if ( this->ClipFunction ) { vtkFloatArray *tmpScalars = vtkFloatArray::New(); tmpScalars->SetNumberOfTuples(numPts); inPD = vtkPointData::New(); inPD->ShallowCopy(input->GetPointData());//copies original if ( this->GenerateClipScalars ) { inPD->SetScalars(tmpScalars); } for ( i=0; i < numPts; i++ ) { s = this->ClipFunction->FunctionValue(input->GetPoint(i)); tmpScalars->SetTuple(i,&s); } clipScalars = tmpScalars; } else //using input scalars { clipScalars = inPD->GetScalars(this->InputScalarsSelection); if ( !clipScalars ) { vtkErrorMacro(<<"Cannot clip without clip function or input scalars"); return; } } if ( !this->GenerateClipScalars && !input->GetPointData()->GetScalars(this->InputScalarsSelection)) { outPD->CopyScalarsOff(); } else { outPD->CopyScalarsOn(); } outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2); outCD[0] = output->GetCellData(); outCD[0]->CopyAllocate(inCD,estimatedSize,estimatedSize/2); if ( this->GenerateClippedOutput ) { outCD[1] = clippedOutput->GetCellData(); outCD[1]->CopyAllocate(inCD,estimatedSize,estimatedSize/2); } //Process all cells and clip each in turn // int abort=0; vtkIdType updateTime = numCells/20 + 1; // update roughly every 5% vtkGenericCell *cell = vtkGenericCell::New(); int num[2]; num[0]=num[1]=0; int numNew[2]; numNew[0]=numNew[1]=0; for (vtkIdType cellId=0; cellId < numCells && !abort; cellId++) { if ( !(cellId % updateTime) ) { this->UpdateProgress((float)cellId / numCells); abort = this->GetAbortExecute(); } input->GetCell(cellId,cell); cellPts = cell->GetPoints(); cellIds = cell->GetPointIds(); npts = cellPts->GetNumberOfPoints(); // evaluate implicit cutting function for ( i=0; i < npts; i++ ) { s = clipScalars->GetComponent(cellIds->GetId(i), 0); cellScalars->InsertTuple(i, &s); } // perform the clipping cell->Clip(this->Value, cellScalars, this->Locator, conn[0], inPD, outPD, inCD, cellId, outCD[0], this->InsideOut); numNew[0] = conn[0]->GetNumberOfCells() - num[0]; num[0] = conn[0]->GetNumberOfCells(); if ( this->GenerateClippedOutput ) { cell->Clip(this->Value, cellScalars, this->Locator, conn[1], inPD, outPD, inCD, cellId, outCD[1], !this->InsideOut); numNew[1] = conn[1]->GetNumberOfCells() - num[1]; num[1] = conn[1]->GetNumberOfCells(); } for (i=0; i<numOutputs; i++) //for both outputs { for (j=0; j < numNew[i]; j++) { locs[i]->InsertNextValue(conn[i]->GetTraversalLocation()); conn[i]->GetNextCell(npts,pts); //For each new cell added, got to set the type of the cell switch ( cell->GetCellDimension() ) { case 0: //points are generated------------------------------- cellType = (npts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX); break; case 1: //lines are generated---------------------------------- cellType = (npts > 2 ? VTK_POLY_LINE : VTK_LINE); break; case 2: //polygons are generated------------------------------ cellType = (npts == 3 ? VTK_TRIANGLE : (npts == 4 ? VTK_QUAD : VTK_POLYGON)); break; case 3: //tetrahedra are generated------------------------------ cellType = VTK_TETRA; break; } //switch newCellId = types[i]->InsertNextValue(cellType); outCD[i]->CopyData(inCD, cellId, newCellId); } //for each new cell } //for both outputs } //for each cell cell->Delete(); cellScalars->Delete(); if ( this->ClipFunction ) { clipScalars->Delete(); inPD->Delete(); } output->SetPoints(newPoints); output->SetCells(types[0], locs[0], conn[0]); conn[0]->Delete(); types[0]->Delete(); locs[0]->Delete(); if ( this->GenerateClippedOutput ) { clippedOutput->SetPoints(newPoints); clippedOutput->SetCells(types[1], locs[1], conn[1]); conn[1]->Delete(); types[1]->Delete(); locs[1]->Delete(); } newPoints->Delete(); this->Locator->Initialize();//release any extra memory output->Squeeze(); } //---------------------------------------------------------------------------- // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkClipDataSet::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } //---------------------------------------------------------------------------- void vtkClipDataSet::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } //---------------------------------------------------------------------------- void vtkClipDataSet::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->ClipFunction ) { os << indent << "Clip Function: " << this->ClipFunction << "\n"; } else { os << indent << "Clip Function: (none)\n"; } os << indent << "InsideOut: " << (this->InsideOut ? "On\n" : "Off\n"); os << indent << "Value: " << this->Value << "\n"; if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } os << indent << "Generate Clip Scalars: " << (this->GenerateClipScalars ? "On\n" : "Off\n"); os << indent << "Generate Clipped Output: " << (this->GenerateClippedOutput ? "On\n" : "Off\n"); } <commit_msg>Fixed printself defect.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkClipDataSet.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkClipDataSet.h" #include "vtkMergePoints.h" #include "vtkObjectFactory.h" #include "vtkFloatArray.h" #include <math.h> vtkCxxRevisionMacro(vtkClipDataSet, "1.16"); vtkStandardNewMacro(vtkClipDataSet); //---------------------------------------------------------------------------- // Construct with user-specified implicit function; InsideOut turned off; value // set to 0.0; and generate clip scalars turned off. vtkClipDataSet::vtkClipDataSet(vtkImplicitFunction *cf) { this->ClipFunction = cf; this->InsideOut = 0; this->Locator = NULL; this->Value = 0.0; this->GenerateClipScalars = 0; this->GenerateClippedOutput = 0; this->vtkSource::SetNthOutput(1,vtkUnstructuredGrid::New()); this->Outputs[1]->Delete(); this->InputScalarsSelection = NULL; } //---------------------------------------------------------------------------- vtkClipDataSet::~vtkClipDataSet() { if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } this->SetClipFunction(NULL); this->SetInputScalarsSelection(NULL); } //---------------------------------------------------------------------------- // Overload standard modified time function. If Clip functions is modified, // then this object is modified as well. unsigned long vtkClipDataSet::GetMTime() { unsigned long mTime=this->vtkDataSetToUnstructuredGridFilter::GetMTime(); unsigned long time; if ( this->ClipFunction != NULL ) { time = this->ClipFunction->GetMTime(); mTime = ( time > mTime ? time : mTime ); } if ( this->Locator != NULL ) { time = this->Locator->GetMTime(); mTime = ( time > mTime ? time : mTime ); } return mTime; } vtkUnstructuredGrid *vtkClipDataSet::GetClippedOutput() { if (this->NumberOfOutputs < 2) { return NULL; } return (vtkUnstructuredGrid *)(this->Outputs[1]); } //---------------------------------------------------------------------------- // // Clip through data generating surface. // void vtkClipDataSet::Execute() { vtkDataSet *input = this->GetInput(); vtkUnstructuredGrid *output = this->GetOutput(); vtkUnstructuredGrid *clippedOutput = this->GetClippedOutput(); if (input == NULL) { return; } vtkIdType numPts = input->GetNumberOfPoints(); vtkIdType numCells = input->GetNumberOfCells(); vtkPointData *inPD=input->GetPointData(), *outPD = output->GetPointData(); vtkCellData *inCD=input->GetCellData(); vtkCellData *outCD[2]; vtkPoints *newPoints; vtkFloatArray *cellScalars; vtkDataArray *clipScalars; vtkPoints *cellPts; vtkIdList *cellIds; float s; vtkIdType npts; vtkIdType *pts; int cellType = 0; vtkIdType i; int j; vtkIdType estimatedSize; vtkUnsignedCharArray *types[2]; vtkIntArray *locs[2]; int numOutputs = 1; vtkIdType newCellId; vtkDebugMacro(<< "Clipping dataset"); // Initialize self; create output objects // if ( numPts < 1 ) { //vtkErrorMacro(<<"No data to clip"); return; } if ( !this->ClipFunction && this->GenerateClipScalars ) { vtkErrorMacro(<<"Cannot generate clip scalars if no clip function defined"); return; } // allocate the output and associated helper classes estimatedSize = numCells; estimatedSize = estimatedSize / 1024 * 1024; //multiple of 1024 if (estimatedSize < 1024) { estimatedSize = 1024; } cellScalars = vtkFloatArray::New(); cellScalars->Allocate(VTK_CELL_SIZE); vtkCellArray *conn[2]; conn[0] = vtkCellArray::New(); conn[0]->Allocate(estimatedSize,estimatedSize/2); conn[0]->InitTraversal(); types[0] = vtkUnsignedCharArray::New(); types[0]->Allocate(estimatedSize,estimatedSize/2); locs[0] = vtkIntArray::New(); locs[0]->Allocate(estimatedSize,estimatedSize/2); if ( this->GenerateClippedOutput ) { numOutputs = 2; conn[1] = vtkCellArray::New(); conn[1]->Allocate(estimatedSize,estimatedSize/2); conn[1]->InitTraversal(); types[1] = vtkUnsignedCharArray::New(); types[1]->Allocate(estimatedSize,estimatedSize/2); locs[1] = vtkIntArray::New(); locs[1]->Allocate(estimatedSize,estimatedSize/2); } newPoints = vtkPoints::New(); newPoints->Allocate(numPts,numPts/2); // locator used to merge potentially duplicate points if ( this->Locator == NULL ) { this->CreateDefaultLocator(); } this->Locator->InitPointInsertion (newPoints, input->GetBounds()); // Determine whether we're clipping with input scalars or a clip function // and do necessary setup. if ( this->ClipFunction ) { vtkFloatArray *tmpScalars = vtkFloatArray::New(); tmpScalars->SetNumberOfTuples(numPts); inPD = vtkPointData::New(); inPD->ShallowCopy(input->GetPointData());//copies original if ( this->GenerateClipScalars ) { inPD->SetScalars(tmpScalars); } for ( i=0; i < numPts; i++ ) { s = this->ClipFunction->FunctionValue(input->GetPoint(i)); tmpScalars->SetTuple(i,&s); } clipScalars = tmpScalars; } else //using input scalars { clipScalars = inPD->GetScalars(this->InputScalarsSelection); if ( !clipScalars ) { vtkErrorMacro(<<"Cannot clip without clip function or input scalars"); return; } } if ( !this->GenerateClipScalars && !input->GetPointData()->GetScalars(this->InputScalarsSelection)) { outPD->CopyScalarsOff(); } else { outPD->CopyScalarsOn(); } outPD->InterpolateAllocate(inPD,estimatedSize,estimatedSize/2); outCD[0] = output->GetCellData(); outCD[0]->CopyAllocate(inCD,estimatedSize,estimatedSize/2); if ( this->GenerateClippedOutput ) { outCD[1] = clippedOutput->GetCellData(); outCD[1]->CopyAllocate(inCD,estimatedSize,estimatedSize/2); } //Process all cells and clip each in turn // int abort=0; vtkIdType updateTime = numCells/20 + 1; // update roughly every 5% vtkGenericCell *cell = vtkGenericCell::New(); int num[2]; num[0]=num[1]=0; int numNew[2]; numNew[0]=numNew[1]=0; for (vtkIdType cellId=0; cellId < numCells && !abort; cellId++) { if ( !(cellId % updateTime) ) { this->UpdateProgress((float)cellId / numCells); abort = this->GetAbortExecute(); } input->GetCell(cellId,cell); cellPts = cell->GetPoints(); cellIds = cell->GetPointIds(); npts = cellPts->GetNumberOfPoints(); // evaluate implicit cutting function for ( i=0; i < npts; i++ ) { s = clipScalars->GetComponent(cellIds->GetId(i), 0); cellScalars->InsertTuple(i, &s); } // perform the clipping cell->Clip(this->Value, cellScalars, this->Locator, conn[0], inPD, outPD, inCD, cellId, outCD[0], this->InsideOut); numNew[0] = conn[0]->GetNumberOfCells() - num[0]; num[0] = conn[0]->GetNumberOfCells(); if ( this->GenerateClippedOutput ) { cell->Clip(this->Value, cellScalars, this->Locator, conn[1], inPD, outPD, inCD, cellId, outCD[1], !this->InsideOut); numNew[1] = conn[1]->GetNumberOfCells() - num[1]; num[1] = conn[1]->GetNumberOfCells(); } for (i=0; i<numOutputs; i++) //for both outputs { for (j=0; j < numNew[i]; j++) { locs[i]->InsertNextValue(conn[i]->GetTraversalLocation()); conn[i]->GetNextCell(npts,pts); //For each new cell added, got to set the type of the cell switch ( cell->GetCellDimension() ) { case 0: //points are generated------------------------------- cellType = (npts > 1 ? VTK_POLY_VERTEX : VTK_VERTEX); break; case 1: //lines are generated---------------------------------- cellType = (npts > 2 ? VTK_POLY_LINE : VTK_LINE); break; case 2: //polygons are generated------------------------------ cellType = (npts == 3 ? VTK_TRIANGLE : (npts == 4 ? VTK_QUAD : VTK_POLYGON)); break; case 3: //tetrahedra are generated------------------------------ cellType = VTK_TETRA; break; } //switch newCellId = types[i]->InsertNextValue(cellType); outCD[i]->CopyData(inCD, cellId, newCellId); } //for each new cell } //for both outputs } //for each cell cell->Delete(); cellScalars->Delete(); if ( this->ClipFunction ) { clipScalars->Delete(); inPD->Delete(); } output->SetPoints(newPoints); output->SetCells(types[0], locs[0], conn[0]); conn[0]->Delete(); types[0]->Delete(); locs[0]->Delete(); if ( this->GenerateClippedOutput ) { clippedOutput->SetPoints(newPoints); clippedOutput->SetCells(types[1], locs[1], conn[1]); conn[1]->Delete(); types[1]->Delete(); locs[1]->Delete(); } newPoints->Delete(); this->Locator->Initialize();//release any extra memory output->Squeeze(); } //---------------------------------------------------------------------------- // Specify a spatial locator for merging points. By default, // an instance of vtkMergePoints is used. void vtkClipDataSet::SetLocator(vtkPointLocator *locator) { if ( this->Locator == locator) { return; } if ( this->Locator ) { this->Locator->UnRegister(this); this->Locator = NULL; } if ( locator ) { locator->Register(this); } this->Locator = locator; this->Modified(); } //---------------------------------------------------------------------------- void vtkClipDataSet::CreateDefaultLocator() { if ( this->Locator == NULL ) { this->Locator = vtkMergePoints::New(); } } //---------------------------------------------------------------------------- void vtkClipDataSet::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); if ( this->ClipFunction ) { os << indent << "Clip Function: " << this->ClipFunction << "\n"; } else { os << indent << "Clip Function: (none)\n"; } os << indent << "InsideOut: " << (this->InsideOut ? "On\n" : "Off\n"); os << indent << "Value: " << this->Value << "\n"; if ( this->Locator ) { os << indent << "Locator: " << this->Locator << "\n"; } else { os << indent << "Locator: (none)\n"; } os << indent << "Generate Clip Scalars: " << (this->GenerateClipScalars ? "On\n" : "Off\n"); os << indent << "Generate Clipped Output: " << (this->GenerateClippedOutput ? "On\n" : "Off\n"); if (this->InputScalarsSelection) { os << indent << "InputScalarsSelection: " << this->InputScalarsSelection << endl; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "movetool.h" #include "formeditorscene.h" #include "formeditorview.h" #include "formeditorwidget.h" #include "resizehandleitem.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #include <QAction> #include <QDebug> namespace QmlDesigner { MoveTool::MoveTool(FormEditorView *editorView) : AbstractFormEditorTool(editorView), m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView), m_selectionIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeIndicator(editorView->scene()->manipulatorLayerItem()), m_anchorIndicator(editorView->scene()->manipulatorLayerItem()), m_bindingIndicator(editorView->scene()->manipulatorLayerItem()), m_contentNotEditableIndicator(editorView->scene()->manipulatorLayerItem()) { m_selectionIndicator.setCursor(Qt::SizeAllCursor); } MoveTool::~MoveTool() { } void MoveTool::clear() { m_moveManipulator.clear(); m_movingItems.clear(); m_selectionIndicator.clear(); m_resizeIndicator.clear(); m_anchorIndicator.clear(); m_bindingIndicator.clear(); m_contentNotEditableIndicator.clear(); AbstractFormEditorTool::clear(); } void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { if (itemList.isEmpty()) return; m_movingItems = movingItems(items()); if (m_movingItems.isEmpty()) return; m_moveManipulator.setItems(m_movingItems); m_moveManipulator.begin(event->scenePos()); } AbstractFormEditorTool::mousePressEvent(itemList, event); } void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (m_moveManipulator.isActive()) { if (m_movingItems.isEmpty()) return; // m_selectionIndicator.hide(); m_resizeIndicator.hide(); m_anchorIndicator.hide(); m_bindingIndicator.hide(); FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems); if (containerItem && view()->currentState().isBaseState()) { if (containerItem != m_movingItems.first()->parentItem() && event->modifiers().testFlag(Qt::ShiftModifier)) { m_moveManipulator.reparentTo(containerItem); } } m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers())); } } void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) { view()->changeToSelectionTool(); return; } ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle) { view()->changeToResizeTool(); return; } if (!topSelectedItemIsMovable(itemList)) { view()->changeToSelectionTool(); return; } m_contentNotEditableIndicator.setItems(toFormEditorItemList(itemList)); } void MoveTool::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: event->setAccepted(false); return; } double moveStep = 1.0; if (event->modifiers().testFlag(Qt::ShiftModifier)) moveStep = 10.0; if (!event->isAutoRepeat()) { QList<FormEditorItem*> movableItems(movingItems(items())); if (movableItems.isEmpty()) return; m_moveManipulator.setItems(movableItems); // m_selectionIndicator.hide(); m_resizeIndicator.hide(); m_anchorIndicator.hide(); m_bindingIndicator.hide(); m_moveManipulator.beginRewriterTransaction(); } switch (event->key()) { case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break; case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break; case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break; case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break; } if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) { event->accept(); view()->changeToSelectionTool(); } } void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent) { switch (keyEvent->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: keyEvent->setAccepted(false); return; } if (!keyEvent->isAutoRepeat()) { m_moveManipulator.beginRewriterTransaction(); m_moveManipulator.clear(); // m_selectionIndicator.show(); m_resizeIndicator.show(); m_anchorIndicator.show(); m_bindingIndicator.show(); } } void MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/) { } void MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/) { } void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (m_moveManipulator.isActive()) { if (m_movingItems.isEmpty()) return; m_moveManipulator.end(generateUseSnapping(event->modifiers())); m_selectionIndicator.show(); m_resizeIndicator.show(); m_anchorIndicator.show(); m_bindingIndicator.show(); m_movingItems.clear(); } AbstractFormEditorTool::mouseReleaseEvent(itemList, event); } void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event); } void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList) { foreach (FormEditorItem* removedItem, removedItemList) m_movingItems.removeOne(removedItem); } void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList) { m_selectionIndicator.setItems(movingItems(itemList)); m_resizeIndicator.setItems(itemList); m_anchorIndicator.setItems(itemList); m_bindingIndicator.setItems(itemList); updateMoveManipulator(); } void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/) { } void MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList) { m_moveManipulator.synchronizeInstanceParent(itemList); } void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/) { } bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList) { if (itemList.isEmpty()) return false; QGraphicsItem *firstParent = itemList.first()->parentItem(); foreach (FormEditorItem* item, itemList) { if (firstParent != item->parentItem()) return false; } return true; } bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem, const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem* item, itemList) { if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem) return false; } return true; } FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList) { if (itemList.isEmpty()) return 0; foreach (FormEditorItem* item, itemList) { if (isAncestorOfAllItems(item, itemList)) return item; } return 0; } void MoveTool::updateMoveManipulator() { if (m_moveManipulator.isActive()) return; } void MoveTool::beginWithPoint(const QPointF &beginPoint) { m_movingItems = movingItems(items()); if (m_movingItems.isEmpty()) return; m_moveManipulator.setItems(m_movingItems); m_moveManipulator.begin(beginPoint); } static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem *item, itemList) { if (item && item->qmlItemNode().isValid() && item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode())) return false; } return true; } FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList, const QList<FormEditorItem*> &selectedItemList) { Q_ASSERT(!selectedItemList.isEmpty()); foreach (QGraphicsItem* item, itemUnderMouseList) { FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item); if (formEditorItem && !selectedItemList.contains(formEditorItem) && isNotAncestorOfItemInList(formEditorItem, selectedItemList) && formEditorItem->isContainer()) return formEditorItem; } return 0; } QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList) { QList<FormEditorItem*> filteredItemList(itemList); QMutableListIterator<FormEditorItem*> listIterator(filteredItemList); while (listIterator.hasNext()) { FormEditorItem *item = listIterator.next(); if (!item->qmlItemNode().isValid() || !item->qmlItemNode().instanceIsMovable() || !item->qmlItemNode().modelIsMovable() || item->qmlItemNode().instanceIsInLayoutable()) listIterator.remove(); } return filteredItemList; } QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList) { QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList); FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList); if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) { // view()->changeToSelectionTool(); return QList<FormEditorItem*>(); } if (ancestorItem != 0 && ancestorItem->parentItem() != 0) { QList<FormEditorItem*> ancestorItemList; ancestorItemList.append(ancestorItem); return ancestorItemList; } if (!haveSameParent(filteredItemList)) { // view()->changeToSelectionTool(); return QList<FormEditorItem*>(); } return filteredItemList; } void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList) { const QList<FormEditorItem*> selectedItemList = filterSelectedModelNodes(itemList); m_selectionIndicator.updateItems(selectedItemList); m_resizeIndicator.updateItems(selectedItemList); m_anchorIndicator.updateItems(selectedItemList); m_bindingIndicator.updateItems(selectedItemList); m_contentNotEditableIndicator.updateItems(selectedItemList); } } <commit_msg>QmlDesigner: Remove workaround<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "movetool.h" #include "formeditorscene.h" #include "formeditorview.h" #include "formeditorwidget.h" #include "resizehandleitem.h" #include <QApplication> #include <QGraphicsSceneMouseEvent> #include <QAction> #include <QDebug> namespace QmlDesigner { MoveTool::MoveTool(FormEditorView *editorView) : AbstractFormEditorTool(editorView), m_moveManipulator(editorView->scene()->manipulatorLayerItem(), editorView), m_selectionIndicator(editorView->scene()->manipulatorLayerItem()), m_resizeIndicator(editorView->scene()->manipulatorLayerItem()), m_anchorIndicator(editorView->scene()->manipulatorLayerItem()), m_bindingIndicator(editorView->scene()->manipulatorLayerItem()), m_contentNotEditableIndicator(editorView->scene()->manipulatorLayerItem()) { m_selectionIndicator.setCursor(Qt::SizeAllCursor); } MoveTool::~MoveTool() { } void MoveTool::clear() { m_moveManipulator.clear(); m_movingItems.clear(); m_selectionIndicator.clear(); m_resizeIndicator.clear(); m_anchorIndicator.clear(); m_bindingIndicator.clear(); m_contentNotEditableIndicator.clear(); AbstractFormEditorTool::clear(); } void MoveTool::mousePressEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (event->button() == Qt::LeftButton) { if (itemList.isEmpty()) return; m_movingItems = movingItems(items()); if (m_movingItems.isEmpty()) return; m_moveManipulator.setItems(m_movingItems); m_moveManipulator.begin(event->scenePos()); } AbstractFormEditorTool::mousePressEvent(itemList, event); } void MoveTool::mouseMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (m_moveManipulator.isActive()) { if (m_movingItems.isEmpty()) return; // m_selectionIndicator.hide(); m_resizeIndicator.hide(); m_anchorIndicator.hide(); m_bindingIndicator.hide(); FormEditorItem *containerItem = containerFormEditorItem(itemList, m_movingItems); if (containerItem && view()->currentState().isBaseState()) { if (containerItem != m_movingItems.first()->parentItem() && event->modifiers().testFlag(Qt::ShiftModifier)) { m_moveManipulator.reparentTo(containerItem); } } m_moveManipulator.update(event->scenePos(), generateUseSnapping(event->modifiers())); } } void MoveTool::hoverMoveEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent * /*event*/) { if (itemList.isEmpty()) { view()->changeToSelectionTool(); return; } ResizeHandleItem* resizeHandle = ResizeHandleItem::fromGraphicsItem(itemList.first()); if (resizeHandle) { view()->changeToResizeTool(); return; } if (!topSelectedItemIsMovable(itemList)) { view()->changeToSelectionTool(); return; } m_contentNotEditableIndicator.setItems(toFormEditorItemList(itemList)); } void MoveTool::keyPressEvent(QKeyEvent *event) { switch (event->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: event->setAccepted(false); return; } double moveStep = 1.0; if (event->modifiers().testFlag(Qt::ShiftModifier)) moveStep = 10.0; if (!event->isAutoRepeat()) { QList<FormEditorItem*> movableItems(movingItems(items())); if (movableItems.isEmpty()) return; m_moveManipulator.setItems(movableItems); // m_selectionIndicator.hide(); m_resizeIndicator.hide(); m_anchorIndicator.hide(); m_bindingIndicator.hide(); m_moveManipulator.beginRewriterTransaction(); } switch (event->key()) { case Qt::Key_Left: m_moveManipulator.moveBy(-moveStep, 0.0); break; case Qt::Key_Right: m_moveManipulator.moveBy(moveStep, 0.0); break; case Qt::Key_Up: m_moveManipulator.moveBy(0.0, -moveStep); break; case Qt::Key_Down: m_moveManipulator.moveBy(0.0, moveStep); break; } if (event->key() == Qt::Key_Escape && !m_movingItems.isEmpty()) { event->accept(); view()->changeToSelectionTool(); } } void MoveTool::keyReleaseEvent(QKeyEvent *keyEvent) { switch (keyEvent->key()) { case Qt::Key_Shift: case Qt::Key_Alt: case Qt::Key_Control: case Qt::Key_AltGr: keyEvent->setAccepted(false); return; } if (!keyEvent->isAutoRepeat()) { m_moveManipulator.clear(); // m_selectionIndicator.show(); m_resizeIndicator.show(); m_anchorIndicator.show(); m_bindingIndicator.show(); } } void MoveTool::dragLeaveEvent(QGraphicsSceneDragDropEvent * /*event*/) { } void MoveTool::dragMoveEvent(QGraphicsSceneDragDropEvent * /*event*/) { } void MoveTool::mouseReleaseEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { if (m_moveManipulator.isActive()) { if (m_movingItems.isEmpty()) return; m_moveManipulator.end(generateUseSnapping(event->modifiers())); m_selectionIndicator.show(); m_resizeIndicator.show(); m_anchorIndicator.show(); m_bindingIndicator.show(); m_movingItems.clear(); } AbstractFormEditorTool::mouseReleaseEvent(itemList, event); } void MoveTool::mouseDoubleClickEvent(const QList<QGraphicsItem*> &itemList, QGraphicsSceneMouseEvent *event) { AbstractFormEditorTool::mouseDoubleClickEvent(itemList, event); } void MoveTool::itemsAboutToRemoved(const QList<FormEditorItem*> &removedItemList) { foreach (FormEditorItem* removedItem, removedItemList) m_movingItems.removeOne(removedItem); } void MoveTool::selectedItemsChanged(const QList<FormEditorItem*> &itemList) { m_selectionIndicator.setItems(movingItems(itemList)); m_resizeIndicator.setItems(itemList); m_anchorIndicator.setItems(itemList); m_bindingIndicator.setItems(itemList); updateMoveManipulator(); } void MoveTool::instancesCompleted(const QList<FormEditorItem*> & /*itemList*/) { } void MoveTool::instancesParentChanged(const QList<FormEditorItem *> &itemList) { m_moveManipulator.synchronizeInstanceParent(itemList); } void MoveTool::instancePropertyChange(const QList<QPair<ModelNode, PropertyName> > & /*propertyList*/) { } bool MoveTool::haveSameParent(const QList<FormEditorItem*> &itemList) { if (itemList.isEmpty()) return false; QGraphicsItem *firstParent = itemList.first()->parentItem(); foreach (FormEditorItem* item, itemList) { if (firstParent != item->parentItem()) return false; } return true; } bool MoveTool::isAncestorOfAllItems(FormEditorItem* maybeAncestorItem, const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem* item, itemList) { if (!maybeAncestorItem->isAncestorOf(item) && item != maybeAncestorItem) return false; } return true; } FormEditorItem* MoveTool::ancestorIfOtherItemsAreChild(const QList<FormEditorItem*> &itemList) { if (itemList.isEmpty()) return 0; foreach (FormEditorItem* item, itemList) { if (isAncestorOfAllItems(item, itemList)) return item; } return 0; } void MoveTool::updateMoveManipulator() { if (m_moveManipulator.isActive()) return; } void MoveTool::beginWithPoint(const QPointF &beginPoint) { m_movingItems = movingItems(items()); if (m_movingItems.isEmpty()) return; m_moveManipulator.setItems(m_movingItems); m_moveManipulator.begin(beginPoint); } static bool isNotAncestorOfItemInList(FormEditorItem *formEditorItem, const QList<FormEditorItem*> &itemList) { foreach (FormEditorItem *item, itemList) { if (item && item->qmlItemNode().isValid() && item->qmlItemNode().isAncestorOf(formEditorItem->qmlItemNode())) return false; } return true; } FormEditorItem* MoveTool::containerFormEditorItem(const QList<QGraphicsItem*> &itemUnderMouseList, const QList<FormEditorItem*> &selectedItemList) { Q_ASSERT(!selectedItemList.isEmpty()); foreach (QGraphicsItem* item, itemUnderMouseList) { FormEditorItem *formEditorItem = FormEditorItem::fromQGraphicsItem(item); if (formEditorItem && !selectedItemList.contains(formEditorItem) && isNotAncestorOfItemInList(formEditorItem, selectedItemList) && formEditorItem->isContainer()) return formEditorItem; } return 0; } QList<FormEditorItem*> movalbeItems(const QList<FormEditorItem*> &itemList) { QList<FormEditorItem*> filteredItemList(itemList); QMutableListIterator<FormEditorItem*> listIterator(filteredItemList); while (listIterator.hasNext()) { FormEditorItem *item = listIterator.next(); if (!item->qmlItemNode().isValid() || !item->qmlItemNode().instanceIsMovable() || !item->qmlItemNode().modelIsMovable() || item->qmlItemNode().instanceIsInLayoutable()) listIterator.remove(); } return filteredItemList; } QList<FormEditorItem*> MoveTool::movingItems(const QList<FormEditorItem*> &selectedItemList) { QList<FormEditorItem*> filteredItemList = movalbeItems(selectedItemList); FormEditorItem* ancestorItem = ancestorIfOtherItemsAreChild(filteredItemList); if (ancestorItem != 0 && ancestorItem->qmlItemNode().isRootNode()) { // view()->changeToSelectionTool(); return QList<FormEditorItem*>(); } if (ancestorItem != 0 && ancestorItem->parentItem() != 0) { QList<FormEditorItem*> ancestorItemList; ancestorItemList.append(ancestorItem); return ancestorItemList; } if (!haveSameParent(filteredItemList)) { // view()->changeToSelectionTool(); return QList<FormEditorItem*>(); } return filteredItemList; } void MoveTool::formEditorItemsChanged(const QList<FormEditorItem*> &itemList) { const QList<FormEditorItem*> selectedItemList = filterSelectedModelNodes(itemList); m_selectionIndicator.updateItems(selectedItemList); m_resizeIndicator.updateItems(selectedItemList); m_anchorIndicator.updateItems(selectedItemList); m_bindingIndicator.updateItems(selectedItemList); m_contentNotEditableIndicator.updateItems(selectedItemList); } } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <ipPic/ipPicTypeMultiplex.h> #include <ANN/ANN.h> #include "ipSegmentation.h" static ANNkd_tree *annTree; static ANNpoint queryPt; static ANNidxArray nnIdx; static ANNdistArray dists; // find next pixel in ANN: #define QUERY_DIST(qOfs) \ queryPt[0] = (float)(qOfs % line) + 0.5; \ queryPt[1] = (float)(qOfs / line) + 0.5; \ annTree->annkSearch( queryPt, 1, nnIdx, dists ); #define PROCESS_PIXEL \ histVal = *((ipUInt2_t*)history->data+testOfs); \ segVal = *((ipUInt1_t*)seg->data+testOfs); \ if ( segVal > 0 && histVal <= maxHist && testOfs!=oldOfs ) { \ grad = ipMITKSegmentationGetDistGradient( testOfs, seg ); \ QUERY_DIST(testOfs) \ if (grad<minGrad) { \ minGrad = grad; \ gradCand = testOfs; \ } \ if (dists[0] > maxDist) { \ maxDist = dists[0]; \ candOfs = testOfs; \ } \ } float ipMITKSegmentationGetDistGradient( int ofs, ipPicDescriptor *seg ) { ipUInt4_t unsignedOfs = ofs < 0 ? seg->n[0]*seg->n[1] - seg->n[0] : ofs; if (unsignedOfs < seg->n[0] || unsignedOfs >= seg->n[0]*seg->n[1] - seg->n[0]) // exclude image borders { return 1.0; // initialization value of minGrad (high gradient) } float x = (float)(ofs % seg->n[0]) + 0.5; float y = (float)(ofs / seg->n[0]) + 0.5; ipUInt1_t segVal = 0; // initialize to stop valgrind's warning about "Conditional jump or move depends on uninitialised value(s)" queryPt[0] = x+1; queryPt[1] = y; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d1 = sqrt( dists[0] ); // right dist segVal = *((ipUInt1_t*)seg->data+ofs+1); if (!segVal) d1 = -10.0; queryPt[0] = x-1; queryPt[1] = y; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d2 = sqrt( dists[0] ); // left dist segVal = *((ipUInt1_t*)seg->data+ofs-1); if (!segVal) d2 = -10.0; queryPt[0] = x; queryPt[1] = y+1; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d3 = sqrt( dists[0] ); // lower dist segVal = *((ipUInt1_t*)seg->data+ofs+seg->n[0]); if (!segVal) d3 = -10.0; queryPt[0] = x; queryPt[1] = y-1; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d4 = sqrt( dists[0] ); // upper dist segVal = *((ipUInt1_t*)seg->data+ofs-seg->n[0]); if (!segVal) d4 = -10.0; float res = 0.5*(float)sqrt( (d1-d2)*(d1-d2) + (d3-d4)*(d3-d4) ); return res; } tCutResult ipMITKSegmentationGetCutPoints( ipPicDescriptor *seg, ipPicDescriptor *history, int ofs ) { bool debug(false); tCutResult res; int resContourSize = 5000; res.traceline = (float*)malloc( resContourSize*sizeof(float)*2 ); res.onGradient = (bool*)malloc( resContourSize*sizeof(bool) ); res.numPoints = 0; res.absMin = 0; res.cutIt = false; res.deleteCurve = 0; if (!history) return res; // no history! if (*((ipUInt2_t*)history->data + ofs) == 0) return res; // ofs not inside known history // get one point on the contour: ipUInt1_t *ptr = (ipUInt1_t*)seg->data + ofs; int endLine = ((ofs / seg->n[0]) + 1) * seg->n[0] -1; int contourOfs = ofs; while (contourOfs!=endLine && *ptr!=0) { ptr++; contourOfs++; } if (*ptr == 0) contourOfs--; // get back on the contour! // extract the contour: int sizeContour, sizeBuffer; float *contour = ipMITKSegmentationGetContour8N( seg, contourOfs, sizeContour, sizeBuffer ); // init ANN tree with contour points: queryPt = annAllocPt( 2 ); ANNpointArray dataPts = annAllocPts( sizeContour, 2 ); nnIdx = new ANNidx[10]; dists = new ANNdist[10]; for (int i=0; i<sizeContour; i++) { (dataPts[i])[0] = contour[2*i]; (dataPts[i])[1] = contour[2*i+1]; } annTree = new ANNkd_tree( dataPts, sizeContour, 2 ); // trace to center: int line = history->n[0]; int maxOfs = line * history->n[1]; QUERY_DIST(ofs) float maxDist = dists[0]; float minDist = 10000; // current minimum distance from border float oldDist = 0; int candOfs = ofs; int nextOfs = -1; int oldOfs, testOfs, gradCand=-1; float grad, minGrad; bool skelettonReached = false; ipUInt2_t histVal; ipUInt1_t segVal; ipUInt2_t maxHist = 10000; if (maxHist==0 && debug) printf( "maxHist = 0!\n" ); do { oldOfs = nextOfs; nextOfs = candOfs; // store point info: if (res.numPoints < resContourSize) { res.traceline[2*res.numPoints] = (float)(nextOfs % line) + 0.5; res.traceline[2*res.numPoints+1] = (float)(nextOfs / line) + 0.5; if (nextOfs==gradCand) res.onGradient[res.numPoints] = true; else res.onGradient[res.numPoints] = false; res.numPoints++; if (res.numPoints == resContourSize) { resContourSize *= 2; // explodes, but such contours must be very strange res.traceline = (float*)realloc( res.traceline, resContourSize*sizeof(float)*2 ); res.onGradient = (bool*)realloc( res.onGradient, resContourSize*sizeof(bool) ); if ((res.traceline == NULL) || (res.onGradient == NULL)) { res.numPoints = 0; res.cutIt = false; return res; } } } maxHist = *((ipUInt2_t*)history->data + nextOfs); // don't exceed this history! maxDist = 0; // clear maxDist minGrad = 1.0; // clear minGrad int traceSinceMin = res.numPoints - 1 - res.absMin; float weight = 20.0 / (20.0+traceSinceMin); if (weight < 0.5) weight = 0.5; QUERY_DIST(nextOfs) if (!skelettonReached && dists[0] < oldDist) { skelettonReached = true; if (debug) printf( "skeletton reached at %i, oldDist=%.1f, currentDist=%.1f\n", res.numPoints - 1, oldDist, dists[0] ); } oldDist = dists[0]; if (skelettonReached && weight*dists[0] < minDist) { minDist = dists[0]; res.absMin = res.numPoints - 1; // has already been increased } // check right: testOfs = nextOfs+1; if (testOfs%line!=0) { // check top right: PROCESS_PIXEL testOfs = nextOfs-line; if (testOfs > 0) { testOfs++; PROCESS_PIXEL } // check bottom right: testOfs = nextOfs+line; if (testOfs < maxOfs) { testOfs++; PROCESS_PIXEL } } // check top: testOfs = nextOfs-line; if (testOfs > 0) { PROCESS_PIXEL } // check left: testOfs = nextOfs-1; if (nextOfs%line!=0) { PROCESS_PIXEL // check top left: testOfs = nextOfs-line; if (testOfs > 0) { testOfs--; PROCESS_PIXEL } // check bottom left: testOfs = nextOfs+line; if (testOfs < maxOfs) { testOfs--; PROCESS_PIXEL } } // check bottom: testOfs = nextOfs+line; if (testOfs < maxOfs) { PROCESS_PIXEL } // check for run on gradient: if (minGrad < 0.5) { candOfs = gradCand; if (debug) printf( "." ); } else if (debug) printf( "x" ); } while (candOfs != nextOfs); if (res.absMin < (res.numPoints-10)) { res.absMin += (int)(sqrt(minDist)/2.0); // int cutX = (int)(res.traceline[2*res.absMin]-0.5); // int cutY = (int)(res.traceline[2*res.absMin+1]-0.5); // int cutOfs = cutX + line*cutY; // histVal = *((ipUInt2_t*)history->data+cutOfs); // printf( "histVal at Cut=%i\n", histVal ); // if (histVal > 1) { res.cutIt = true; float cutXf = (float)res.traceline[2*res.absMin]; float cutYf = (float)res.traceline[2*res.absMin+1]; queryPt[0] = cutXf; queryPt[1] = cutYf; annTree->annkSearch( queryPt, 1, nnIdx, dists ); int cutIdx1 = nnIdx[0]; res.cutCoords[0] = contour[2*cutIdx1]; res.cutCoords[1] = contour[2*cutIdx1+1]; int cutIdx2 = cutIdx1; float minDist = 100000000; int testCnt = 0; for (int i=0; i<sizeContour; i++) { int idxDif = abs(cutIdx1-i); // take wraparound into account: if (idxDif > (sizeContour/2)) idxDif = sizeContour - idxDif; if ( idxDif > 50 ) { float dist = (cutXf-contour[2*i])*(cutXf-contour[2*i]) + (cutYf-contour[2*i+1])*(cutYf-contour[2*i+1]); if (dist < minDist) { minDist = dist; cutIdx2 = i; } } else testCnt++; } res.cutCoords[2] = contour[2*cutIdx2]; res.cutCoords[3] = contour[2*cutIdx2+1]; if (debug) printf( "idx1=%i, idx2=%i, %i pts not evaluated.\n", cutIdx1, cutIdx2, testCnt ); if ((res.cutCoords[0] == res.cutCoords[2]) && (res.cutCoords[1] == res.cutCoords[3])) { free( contour ); // free ANN stuff: annDeallocPt( queryPt ); annDeallocPts( dataPts ); delete[] nnIdx; delete[] dists; delete annTree; res.cutIt = false; return res; } float *curve1 = (float*)malloc( 2*sizeof(float)*sizeContour ); float *curve2 = (float*)malloc( 2*sizeof(float)*sizeContour ); int sizeCurve1, sizeCurve2; ipMITKSegmentationSplitContour( contour, sizeContour, res.cutCoords, curve1, sizeCurve1, curve2, sizeCurve2 ); float clickX = (float)(ofs % line) + 0.5; float clickY = (float)(ofs / line) + 0.5; if (ipMITKSegmentationIsInsideContour( curve1, sizeCurve1, clickX, clickY )) { res.deleteCurve = curve1; res.deleteSize = sizeCurve1; free( curve2 ); } else { res.deleteCurve = curve2; res.deleteSize = sizeCurve2; free( curve1 ); } } free( contour ); // free ANN stuff: annDeallocPt( queryPt ); annDeallocPts( dataPts ); delete[] nnIdx; delete[] dists; delete annTree; return res; } <commit_msg>FIX (#1185): Tests for SliceBasedSegmentation crash sometimes<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Module: $RCSfile: mitkPropertyManager.cpp,v $ Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include <ipPic/ipPicTypeMultiplex.h> #include <ANN/ANN.h> #include "ipSegmentation.h" static ANNkd_tree *annTree; static ANNpoint queryPt; static ANNidxArray nnIdx; static ANNdistArray dists; // find next pixel in ANN: #define QUERY_DIST(qOfs) \ queryPt[0] = (float)(qOfs % line) + 0.5; \ queryPt[1] = (float)(qOfs / line) + 0.5; \ annTree->annkSearch( queryPt, 1, nnIdx, dists ); #define PROCESS_PIXEL \ histVal = *((ipUInt2_t*)history->data+testOfs); \ segVal = *((ipUInt1_t*)seg->data+testOfs); \ if ( segVal > 0 && histVal <= maxHist && testOfs!=oldOfs ) { \ grad = ipMITKSegmentationGetDistGradient( testOfs, seg ); \ QUERY_DIST(testOfs) \ if (grad<minGrad) { \ minGrad = grad; \ gradCand = testOfs; \ } \ if (dists[0] > maxDist) { \ maxDist = dists[0]; \ candOfs = testOfs; \ } \ } float ipMITKSegmentationGetDistGradient( int ofs, ipPicDescriptor *seg ) { ipUInt4_t unsignedOfs = ofs < 0 ? seg->n[0]*seg->n[1] - seg->n[0] : ofs; if (unsignedOfs < seg->n[0] || unsignedOfs >= seg->n[0]*seg->n[1] - seg->n[0]) // exclude image borders { return 1.0; // initialization value of minGrad (high gradient) } float x = (float)(ofs % seg->n[0]) + 0.5; float y = (float)(ofs / seg->n[0]) + 0.5; ipUInt1_t segVal = 0; // initialize to stop valgrind's warning about "Conditional jump or move depends on uninitialised value(s)" queryPt[0] = x+1; queryPt[1] = y; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d1 = sqrt( dists[0] ); // right dist segVal = *((ipUInt1_t*)seg->data+ofs+1); if (!segVal) d1 = -10.0; queryPt[0] = x-1; queryPt[1] = y; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d2 = sqrt( dists[0] ); // left dist segVal = *((ipUInt1_t*)seg->data+ofs-1); if (!segVal) d2 = -10.0; queryPt[0] = x; queryPt[1] = y+1; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d3 = sqrt( dists[0] ); // lower dist segVal = *((ipUInt1_t*)seg->data+ofs+seg->n[0]); if (!segVal) d3 = -10.0; queryPt[0] = x; queryPt[1] = y-1; annTree->annkSearch( queryPt, 1, nnIdx, dists ); float d4 = sqrt( dists[0] ); // upper dist segVal = *((ipUInt1_t*)seg->data+ofs-seg->n[0]); if (!segVal) d4 = -10.0; float res = 0.5*(float)sqrt( (d1-d2)*(d1-d2) + (d3-d4)*(d3-d4) ); return res; } tCutResult ipMITKSegmentationGetCutPoints( ipPicDescriptor *seg, ipPicDescriptor *history, int ofs ) { bool debug(false); tCutResult res; int resContourSize = 5000; res.traceline = (float*)malloc( resContourSize*sizeof(float)*2 ); res.onGradient = (bool*)malloc( resContourSize*sizeof(bool) ); res.numPoints = 0; res.absMin = 0; res.cutIt = false; res.deleteCurve = 0; if (!history) return res; // no history! if (*((ipUInt2_t*)history->data + ofs) == 0) return res; // ofs not inside known history // get one point on the contour: ipUInt1_t *ptr = (ipUInt1_t*)seg->data + ofs; int endLine = ((ofs / seg->n[0]) + 1) * seg->n[0] -1; int contourOfs = ofs; while (contourOfs!=endLine && *ptr!=0) { ptr++; contourOfs++; } if (*ptr == 0) contourOfs--; // get back on the contour! // extract the contour: int sizeContour, sizeBuffer; float *contour = ipMITKSegmentationGetContour8N( seg, contourOfs, sizeContour, sizeBuffer ); // init ANN tree with contour points: queryPt = annAllocPt( 2 ); ANNpointArray dataPts = annAllocPts( sizeContour, 2 ); nnIdx = new ANNidx[10]; dists = new ANNdist[10]; for (int i=0; i<sizeContour; i++) { (dataPts[i])[0] = contour[2*i]; (dataPts[i])[1] = contour[2*i+1]; } annTree = new ANNkd_tree( dataPts, sizeContour, 2 ); // trace to center: int line = history->n[0]; int maxOfs = line * history->n[1]; QUERY_DIST(ofs) float maxDist = dists[0]; float minDist = 10000; // current minimum distance from border float oldDist = 0; int candOfs = ofs; int nextOfs = -1; int oldOfs, testOfs, gradCand=-1; float grad, minGrad; bool skelettonReached = false; ipUInt2_t histVal; ipUInt1_t segVal; ipUInt2_t maxHist = 10000; if (maxHist==0 && debug) printf( "maxHist = 0!\n" ); do { oldOfs = nextOfs; nextOfs = candOfs; // store point info: if (res.numPoints < resContourSize) { res.traceline[2*res.numPoints] = (float)(nextOfs % line) + 0.5; res.traceline[2*res.numPoints+1] = (float)(nextOfs / line) + 0.5; if (nextOfs==gradCand) res.onGradient[res.numPoints] = true; else res.onGradient[res.numPoints] = false; if (debug) { printf( "(%.f,%.f): H=%i, G=%i\n", res.traceline[2*res.numPoints], res.traceline[2*res.numPoints+1], *((ipUInt2_t*)history->data+nextOfs), res.onGradient[res.numPoints] ); } res.numPoints++; if (res.numPoints == resContourSize) { resContourSize *= 2; // explodes, but such contours must be very strange res.traceline = (float*)realloc( res.traceline, resContourSize*sizeof(float)*2 ); res.onGradient = (bool*)realloc( res.onGradient, resContourSize*sizeof(bool) ); if ((res.traceline == NULL) || (res.onGradient == NULL)) { res.numPoints = 0; res.cutIt = false; return res; } } } maxHist = *((ipUInt2_t*)history->data + nextOfs); // don't exceed this history! maxDist = 0; // clear maxDist minGrad = 1.0; // clear minGrad int traceSinceMin = res.numPoints - 1 - res.absMin; float weight = 20.0 / (20.0+traceSinceMin); if (weight < 0.5) weight = 0.5; QUERY_DIST(nextOfs) if (!skelettonReached && dists[0] < oldDist) { skelettonReached = true; if (debug) printf( "skeletton reached at %i, oldDist=%.1f, currentDist=%.1f\n", res.numPoints - 1, oldDist, dists[0] ); } oldDist = dists[0]; if (skelettonReached && weight*dists[0] < minDist) { minDist = dists[0]; res.absMin = res.numPoints - 1; // has already been increased } // check right: testOfs = nextOfs+1; if (testOfs%line!=0) { // check top right: PROCESS_PIXEL testOfs = nextOfs-line; if (testOfs > 0) { testOfs++; PROCESS_PIXEL } // check bottom right: testOfs = nextOfs+line; if (testOfs < maxOfs) { testOfs++; PROCESS_PIXEL } } // check top: testOfs = nextOfs-line; if (testOfs > 0) { PROCESS_PIXEL } // check left: testOfs = nextOfs-1; if (nextOfs%line!=0) { PROCESS_PIXEL // check top left: testOfs = nextOfs-line; if (testOfs > 0) { testOfs--; PROCESS_PIXEL } // check bottom left: testOfs = nextOfs+line; if (testOfs < maxOfs) { testOfs--; PROCESS_PIXEL } } // check bottom: testOfs = nextOfs+line; if (testOfs < maxOfs) { PROCESS_PIXEL } // check for run on gradient: if (minGrad < 0.5) { candOfs = gradCand; if (debug) printf( "." ); } else if (debug) printf( "x" ); } while (candOfs != nextOfs && maxHist > 0); if (res.absMin < (res.numPoints-10)) { res.absMin += (int)(sqrt(minDist)/2.0); // int cutX = (int)(res.traceline[2*res.absMin]-0.5); // int cutY = (int)(res.traceline[2*res.absMin+1]-0.5); // int cutOfs = cutX + line*cutY; // histVal = *((ipUInt2_t*)history->data+cutOfs); // printf( "histVal at Cut=%i\n", histVal ); // if (histVal > 1) { res.cutIt = true; float cutXf = (float)res.traceline[2*res.absMin]; float cutYf = (float)res.traceline[2*res.absMin+1]; queryPt[0] = cutXf; queryPt[1] = cutYf; annTree->annkSearch( queryPt, 1, nnIdx, dists ); int cutIdx1 = nnIdx[0]; res.cutCoords[0] = contour[2*cutIdx1]; res.cutCoords[1] = contour[2*cutIdx1+1]; int cutIdx2 = cutIdx1; float minDist = 100000000; int testCnt = 0; for (int i=0; i<sizeContour; i++) { int idxDif = abs(cutIdx1-i); // take wraparound into account: if (idxDif > (sizeContour/2)) idxDif = sizeContour - idxDif; if ( idxDif > 50 ) { float dist = (cutXf-contour[2*i])*(cutXf-contour[2*i]) + (cutYf-contour[2*i+1])*(cutYf-contour[2*i+1]); if (dist < minDist) { minDist = dist; cutIdx2 = i; } } else testCnt++; } res.cutCoords[2] = contour[2*cutIdx2]; res.cutCoords[3] = contour[2*cutIdx2+1]; if (debug) printf( "idx1=%i, idx2=%i, %i pts not evaluated.\n", cutIdx1, cutIdx2, testCnt ); if ((res.cutCoords[0] == res.cutCoords[2]) && (res.cutCoords[1] == res.cutCoords[3])) { free( contour ); // free ANN stuff: annDeallocPt( queryPt ); annDeallocPts( dataPts ); delete[] nnIdx; delete[] dists; delete annTree; res.cutIt = false; return res; } float *curve1 = (float*)malloc( 2*sizeof(float)*sizeContour ); float *curve2 = (float*)malloc( 2*sizeof(float)*sizeContour ); int sizeCurve1, sizeCurve2; ipMITKSegmentationSplitContour( contour, sizeContour, res.cutCoords, curve1, sizeCurve1, curve2, sizeCurve2 ); float clickX = (float)(ofs % line) + 0.5; float clickY = (float)(ofs / line) + 0.5; if (ipMITKSegmentationIsInsideContour( curve1, sizeCurve1, clickX, clickY )) { res.deleteCurve = curve1; res.deleteSize = sizeCurve1; free( curve2 ); } else { res.deleteCurve = curve2; res.deleteSize = sizeCurve2; free( curve1 ); } } free( contour ); // free ANN stuff: annDeallocPt( queryPt ); annDeallocPts( dataPts ); delete[] nnIdx; delete[] dists; delete annTree; return res; } <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #include "common.h" const int ser_n = 1<<18; void merge(dataType *data, int n1, int n2, dataType *res) { // printf("Thread %d doing merge.\n", omp_get_thread_num()); int i = 0, j = n1, k = 0; while(i < n1 && j < n2) if((long long)data[i].key < (long long)data[j].key) res[k++] = data[i++]; else res[k++] = data[j++]; while(i < n1) res[k++] = data[i++]; while(j < n2) res[k++] = data[j++]; } void mSort_helper(dataType *data, int n, dataType *res) { // printf("Thread %d\n", omp_get_thread_num()); if(n == 1) { res[0] = data[0]; return; } if(n == 0) { return; } if(n < 0) { #ifdef DEBUG printf("n < 0 in mSort_helper.\n"); #endif exit(1); } #pragma omp task if(n > ser_n) firstprivate(res, n, data) untied mSort_helper(res, n/2, data); #pragma omp task if(n > ser_n) firstprivate(res, n, data) untied mSort_helper(res+n/2, n-n/2, data+n/2); #pragma omp taskwait merge(data, n/2, n, res); } void mSort(dataType *data, int n) { dataType *res = new dataType[n]; #pragma omp parallel firstprivate(res, n, data) { int i; #pragma omp for for (i = 0; i < n; ++i) res[i] = data[i]; #pragma omp master// implicit nowait { Dprintf("%d threads\n", omp_get_num_threads()); mSort_helper(res, n, data); } } delete [] res; } <commit_msg>Reduced ser_n<commit_after>#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #include "sort.h" const int ser_n = 1<<13; void merge(dataType *data, int n1, int n2, dataType *res) { // printf("Thread %d doing merge.\n", omp_get_thread_num()); int i = 0, j = n1, k = 0; while(i < n1 && j < n2) if((long long)data[i].key < (long long)data[j].key) res[k++] = data[i++]; else res[k++] = data[j++]; while(i < n1) res[k++] = data[i++]; while(j < n2) res[k++] = data[j++]; } void mSort_helper(dataType *data, int n, dataType *res) { // printf("Thread %d\n", omp_get_thread_num()); if(n == 1) { res[0] = data[0]; return; } if(n == 0) { return; } if(n < 0) { #ifdef DEBUG printf("n < 0 in mSort_helper.\n"); #endif exit(1); } #pragma omp task if(n > ser_n) firstprivate(res, n, data) untied mSort_helper(res, n/2, data); #pragma omp task if(n > ser_n) firstprivate(res, n, data) untied mSort_helper(res+n/2, n-n/2, data+n/2); #pragma omp taskwait merge(data, n/2, n, res); } void mSort(dataType *data, int n) { dataType *res = new dataType[n]; #pragma omp parallel firstprivate(res, n, data) { int i; #pragma omp for for (i = 0; i < n; ++i) res[i] = data[i]; #pragma omp master// implicit nowait { //printf("%d threads\n", omp_get_num_threads()); mSort_helper(res, n, data); } } delete [] res; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bmpconv.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 11:58:48 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <bitmap.hxx> #include <impbmpconv.hxx> #include <svapp.hxx> #include <vos/mutex.hxx> #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_ #include <com/sun/star/script/XInvocation.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _CPPUHELPER_COMPBASE1_HXX_ #include <cppuhelper/compbase1.hxx> #endif using namespace com::sun::star::uno; using namespace com::sun::star::script; using namespace com::sun::star::beans; using namespace com::sun::star::reflection; using namespace com::sun::star::awt; using namespace rtl; namespace vcl { class BmpTransporter : public cppu::WeakImplHelper1< com::sun::star::awt::XBitmap > { Sequence<sal_Int8> m_aBM; com::sun::star::awt::Size m_aSize; public: BmpTransporter( const Bitmap& rBM ); virtual ~BmpTransporter(); virtual com::sun::star::awt::Size SAL_CALL getSize() throw(); virtual Sequence< sal_Int8 > SAL_CALL getDIB() throw(); virtual Sequence< sal_Int8 > SAL_CALL getMaskDIB() throw(); }; class BmpConverter : public cppu::WeakImplHelper1< com::sun::star::script::XInvocation > { public: BmpConverter(); virtual ~BmpConverter(); virtual Reference< XIntrospectionAccess > SAL_CALL getIntrospection() throw(); virtual void SAL_CALL setValue( const OUString& rProperty, const Any& rValue ) throw( UnknownPropertyException ); virtual Any SAL_CALL getValue( const OUString& rProperty ) throw( UnknownPropertyException ); virtual sal_Bool SAL_CALL hasMethod( const OUString& rName ) throw(); virtual sal_Bool SAL_CALL hasProperty( const OUString& rProp ) throw(); virtual Any SAL_CALL invoke( const OUString& rFunction, const Sequence< Any >& rParams, Sequence< sal_Int16 >& rOutParamIndex, Sequence< Any >& rOutParam ) throw( CannotConvertException, InvocationTargetException ); }; } using namespace vcl; Reference< XInvocation > vcl::createBmpConverter() { return static_cast<XInvocation*>(new BmpConverter()); } BmpConverter::BmpConverter() { } BmpConverter::~BmpConverter() { } Reference< XIntrospectionAccess > SAL_CALL BmpConverter::getIntrospection() throw() { return Reference< XIntrospectionAccess >(); } void SAL_CALL BmpConverter::setValue( const OUString&, const Any& ) throw( UnknownPropertyException ) { throw UnknownPropertyException(); } Any SAL_CALL BmpConverter::getValue( const OUString& ) throw( UnknownPropertyException ) { throw UnknownPropertyException(); } sal_Bool SAL_CALL BmpConverter::hasMethod( const OUString& rName ) throw() { return rName.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ); } sal_Bool SAL_CALL BmpConverter::hasProperty( const OUString& ) throw() { return sal_False; } Any SAL_CALL BmpConverter::invoke( const OUString& rFunction, const Sequence< Any >& rParams, Sequence< sal_Int16 >&, Sequence< Any >& ) throw( CannotConvertException, InvocationTargetException ) { Any aRet; if( rFunction.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ) ) { Reference< XBitmap > xBM; sal_uInt16 nTargetDepth = 0; if( rParams.getLength() != 2 ) throw CannotConvertException(); if( ! (rParams.getConstArray()[0] >>= xBM ) || ! ( rParams.getConstArray()[1] >>= nTargetDepth ) ) throw CannotConvertException(); Sequence< sal_Int8 > aDIB = xBM->getDIB(); // call into vcl not thread safe vos::OGuard aGuard( Application::GetSolarMutex() ); SvMemoryStream aStream( aDIB.getArray(), aDIB.getLength(), STREAM_READ | STREAM_WRITE ); Bitmap aBM; aBM.Read( aStream, TRUE ); if( nTargetDepth < 4 ) nTargetDepth = 1; else if( nTargetDepth < 8 ) nTargetDepth = 4; else if( nTargetDepth >8 && nTargetDepth < 24 ) nTargetDepth = 24; if( aBM.GetBitCount() == 24 && nTargetDepth <= 8 ) aBM.Dither( BMP_DITHER_FLOYD ); if( aBM.GetBitCount() != nTargetDepth ) { switch( nTargetDepth ) { case 1: aBM.Convert( BMP_CONVERSION_1BIT_THRESHOLD );break; case 4: aBM.ReduceColors( BMP_CONVERSION_4BIT_COLORS );break; case 8: aBM.ReduceColors( BMP_CONVERSION_8BIT_COLORS );break; case 24: aBM.Convert( BMP_CONVERSION_24BIT );break; } } xBM = new BmpTransporter( aBM ); aRet <<= xBM; } else throw InvocationTargetException(); return aRet; } BmpTransporter::BmpTransporter( const Bitmap& rBM ) { m_aSize.Width = rBM.GetSizePixel().Width(); m_aSize.Height = rBM.GetSizePixel().Height(); SvMemoryStream aStream; rBM.Write( aStream, FALSE, TRUE ); m_aBM = Sequence<sal_Int8>((const sal_Int8*)aStream.GetData(), aStream.GetSize() ); } BmpTransporter::~BmpTransporter() { } com::sun::star::awt::Size SAL_CALL BmpTransporter::getSize() throw() { return m_aSize; } Sequence< sal_Int8 > SAL_CALL BmpTransporter::getDIB() throw() { return m_aBM; } Sequence< sal_Int8 > SAL_CALL BmpTransporter::getMaskDIB() throw() { return Sequence< sal_Int8 >(); } <commit_msg>INTEGRATION: CWS vgbugs07 (1.5.240); FILE MERGED 2007/06/04 13:29:34 vg 1.5.240.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: bmpconv.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: hr $ $Date: 2007-06-27 20:11:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_vcl.hxx" #include <vcl/bitmap.hxx> #include <impbmpconv.hxx> #include <vcl/svapp.hxx> #include <vos/mutex.hxx> #ifndef _STREAM_HXX #include <tools/stream.hxx> #endif #ifndef _COM_SUN_STAR_SCRIPT_XINVOCATION_HPP_ #include <com/sun/star/script/XInvocation.hpp> #endif #ifndef _COM_SUN_STAR_AWT_XBITMAP_HPP_ #include <com/sun/star/awt/XBitmap.hpp> #endif #ifndef _CPPUHELPER_COMPBASE1_HXX_ #include <cppuhelper/compbase1.hxx> #endif using namespace com::sun::star::uno; using namespace com::sun::star::script; using namespace com::sun::star::beans; using namespace com::sun::star::reflection; using namespace com::sun::star::awt; using namespace rtl; namespace vcl { class BmpTransporter : public cppu::WeakImplHelper1< com::sun::star::awt::XBitmap > { Sequence<sal_Int8> m_aBM; com::sun::star::awt::Size m_aSize; public: BmpTransporter( const Bitmap& rBM ); virtual ~BmpTransporter(); virtual com::sun::star::awt::Size SAL_CALL getSize() throw(); virtual Sequence< sal_Int8 > SAL_CALL getDIB() throw(); virtual Sequence< sal_Int8 > SAL_CALL getMaskDIB() throw(); }; class BmpConverter : public cppu::WeakImplHelper1< com::sun::star::script::XInvocation > { public: BmpConverter(); virtual ~BmpConverter(); virtual Reference< XIntrospectionAccess > SAL_CALL getIntrospection() throw(); virtual void SAL_CALL setValue( const OUString& rProperty, const Any& rValue ) throw( UnknownPropertyException ); virtual Any SAL_CALL getValue( const OUString& rProperty ) throw( UnknownPropertyException ); virtual sal_Bool SAL_CALL hasMethod( const OUString& rName ) throw(); virtual sal_Bool SAL_CALL hasProperty( const OUString& rProp ) throw(); virtual Any SAL_CALL invoke( const OUString& rFunction, const Sequence< Any >& rParams, Sequence< sal_Int16 >& rOutParamIndex, Sequence< Any >& rOutParam ) throw( CannotConvertException, InvocationTargetException ); }; } using namespace vcl; Reference< XInvocation > vcl::createBmpConverter() { return static_cast<XInvocation*>(new BmpConverter()); } BmpConverter::BmpConverter() { } BmpConverter::~BmpConverter() { } Reference< XIntrospectionAccess > SAL_CALL BmpConverter::getIntrospection() throw() { return Reference< XIntrospectionAccess >(); } void SAL_CALL BmpConverter::setValue( const OUString&, const Any& ) throw( UnknownPropertyException ) { throw UnknownPropertyException(); } Any SAL_CALL BmpConverter::getValue( const OUString& ) throw( UnknownPropertyException ) { throw UnknownPropertyException(); } sal_Bool SAL_CALL BmpConverter::hasMethod( const OUString& rName ) throw() { return rName.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ); } sal_Bool SAL_CALL BmpConverter::hasProperty( const OUString& ) throw() { return sal_False; } Any SAL_CALL BmpConverter::invoke( const OUString& rFunction, const Sequence< Any >& rParams, Sequence< sal_Int16 >&, Sequence< Any >& ) throw( CannotConvertException, InvocationTargetException ) { Any aRet; if( rFunction.equalsIgnoreAsciiCase( OUString::createFromAscii( "convert-bitmap-depth" ) ) ) { Reference< XBitmap > xBM; sal_uInt16 nTargetDepth = 0; if( rParams.getLength() != 2 ) throw CannotConvertException(); if( ! (rParams.getConstArray()[0] >>= xBM ) || ! ( rParams.getConstArray()[1] >>= nTargetDepth ) ) throw CannotConvertException(); Sequence< sal_Int8 > aDIB = xBM->getDIB(); // call into vcl not thread safe vos::OGuard aGuard( Application::GetSolarMutex() ); SvMemoryStream aStream( aDIB.getArray(), aDIB.getLength(), STREAM_READ | STREAM_WRITE ); Bitmap aBM; aBM.Read( aStream, TRUE ); if( nTargetDepth < 4 ) nTargetDepth = 1; else if( nTargetDepth < 8 ) nTargetDepth = 4; else if( nTargetDepth >8 && nTargetDepth < 24 ) nTargetDepth = 24; if( aBM.GetBitCount() == 24 && nTargetDepth <= 8 ) aBM.Dither( BMP_DITHER_FLOYD ); if( aBM.GetBitCount() != nTargetDepth ) { switch( nTargetDepth ) { case 1: aBM.Convert( BMP_CONVERSION_1BIT_THRESHOLD );break; case 4: aBM.ReduceColors( BMP_CONVERSION_4BIT_COLORS );break; case 8: aBM.ReduceColors( BMP_CONVERSION_8BIT_COLORS );break; case 24: aBM.Convert( BMP_CONVERSION_24BIT );break; } } xBM = new BmpTransporter( aBM ); aRet <<= xBM; } else throw InvocationTargetException(); return aRet; } BmpTransporter::BmpTransporter( const Bitmap& rBM ) { m_aSize.Width = rBM.GetSizePixel().Width(); m_aSize.Height = rBM.GetSizePixel().Height(); SvMemoryStream aStream; rBM.Write( aStream, FALSE, TRUE ); m_aBM = Sequence<sal_Int8>((const sal_Int8*)aStream.GetData(), aStream.GetSize() ); } BmpTransporter::~BmpTransporter() { } com::sun::star::awt::Size SAL_CALL BmpTransporter::getSize() throw() { return m_aSize; } Sequence< sal_Int8 > SAL_CALL BmpTransporter::getDIB() throw() { return m_aBM; } Sequence< sal_Int8 > SAL_CALL BmpTransporter::getMaskDIB() throw() { return Sequence< sal_Int8 >(); } <|endoftext|>
<commit_before>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkEMClassification.h> #include <irtkGaussian.h> char *output_name; void usage() { cerr << "Usage: ems [image] [n] [atlas 1 ... atlas n] [output] <options>" << endl; exit(1); } int main(int argc, char **argv) { int i, n, ok, padding, iterations; bool nobg=false; if (argc < 4) { usage(); exit(1); } // Input image irtkRealImage image; image.Read(argv[1]); argc--; argv++; // Number of tissues n = atoi(argv[1]); argc--; argv++; // Probabilistic atlas irtkRealImage **atlas = new irtkRealImage*[n]; irtkRealImage *background=NULL; // Read atlas for each tissue for (i = 0; i < n; i++) { atlas[i] = new irtkRealImage; atlas[i]->Read(argv[1]); cerr << "Image " << i <<" = " << argv[1] <<endl; argc--; argv++; } // File name for output output_name = argv[1]; argc--; argv++; // Default parameters iterations = 15; padding = -1;//MIN_GREY; // Parse remaining parameters while (argc > 1) { ok = False; if ((ok == False) && (strcmp(argv[1], "-iterations") == 0)) { argc--; argv++; iterations = atoi(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-padding") == 0)) { argc--; argv++; padding = atoi(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-background") == 0)) { argc--; argv++; background = new irtkRealImage; background->Read(argv[1]); cerr << "background = " << argv[1] <<endl; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-nobg") == 0)) { argc--; argv++; nobg=true; cerr << "Not adding background tissue."<<endl; ok = True; } if (ok == False) { cerr << "Can not parse argument " << argv[1] << endl; usage(); } } irtkEMClassification *classification; if (nobg) classification= new irtkEMClassification(n, atlas); else classification= new irtkEMClassification(n, atlas, background); classification->SetPadding(padding); classification->SetInput(image); classification->Initialise(); double rel_diff; //for (i = 0; rel_diff > 0.0001; i++){ i=0; do { cout << "Iteration = " << i+1 << " / " << iterations << endl; rel_diff = classification->Iterate(i); i++; } while ((rel_diff>0.001)&&(i<50)); irtkRealImage segmentation; classification->ConstructSegmentation(segmentation); segmentation.Write(output_name); if (n==11) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"caudate.nii.gz"); classification->WriteProbMap(3,"putamen.nii.gz"); classification->WriteProbMap(4,"nigra.nii.gz"); classification->WriteProbMap(5,"cerebellum.nii.gz"); classification->WriteProbMap(6,"thalamus.nii.gz"); classification->WriteProbMap(7,"pallidum.nii.gz"); classification->WriteProbMap(8,"brainstem.nii.gz"); classification->WriteProbMap(9,"white.nii.gz"); classification->WriteProbMap(10,"cerebellum-white.nii.gz"); classification->WriteProbMap(11,"other.nii.gz"); } if (n==7) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"caudate.nii.gz"); classification->WriteProbMap(3,"putamen.nii.gz"); classification->WriteProbMap(4,"thalamus.nii.gz"); classification->WriteProbMap(5,"pallidum.nii.gz"); classification->WriteProbMap(6,"white.nii.gz"); classification->WriteProbMap(7,"other.nii.gz"); } if (n==3) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"white.nii.gz"); } classification->WriteGaussianParameters("parameters.txt"); delete classification; } <commit_msg>Print parameters on screen<commit_after>/*========================================================================= Library : Image Registration Toolkit (IRTK) Module : $Id$ Copyright : Imperial College, Department of Computing Visual Information Processing (VIP), 2008 onwards Date : $Date$ Version : $Revision$ Changes : $Author$ =========================================================================*/ #include <irtkImage.h> #include <irtkEMClassification.h> #include <irtkGaussian.h> char *output_name; void usage() { cerr << "Usage: ems [image] [n] [atlas 1 ... atlas n] [output] <options>" << endl; exit(1); } int main(int argc, char **argv) { int i, n, ok, padding, iterations; bool nobg=false; if (argc < 4) { usage(); exit(1); } // Input image irtkRealImage image; image.Read(argv[1]); argc--; argv++; // Number of tissues n = atoi(argv[1]); argc--; argv++; // Probabilistic atlas irtkRealImage **atlas = new irtkRealImage*[n]; irtkRealImage *background=NULL; // Read atlas for each tissue for (i = 0; i < n; i++) { atlas[i] = new irtkRealImage; atlas[i]->Read(argv[1]); cerr << "Image " << i <<" = " << argv[1] <<endl; argc--; argv++; } // File name for output output_name = argv[1]; argc--; argv++; // Default parameters iterations = 15; padding = -1;//MIN_GREY; // Parse remaining parameters while (argc > 1) { ok = False; if ((ok == False) && (strcmp(argv[1], "-iterations") == 0)) { argc--; argv++; iterations = atoi(argv[1]); argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-padding") == 0)) { argc--; argv++; padding = atoi(argv[1]); cerr << "padding = " << padding <<endl; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-background") == 0)) { argc--; argv++; background = new irtkRealImage; background->Read(argv[1]); cerr << "background = " << argv[1] <<endl; argc--; argv++; ok = True; } if ((ok == False) && (strcmp(argv[1], "-nobg") == 0)) { argc--; argv++; nobg=true; cerr << "Not adding background tissue."<<endl; ok = True; } if (ok == False) { cerr << "Can not parse argument " << argv[1] << endl; usage(); } } irtkEMClassification *classification; if (nobg) classification= new irtkEMClassification(n, atlas); else classification= new irtkEMClassification(n, atlas, background); classification->SetPadding(padding); classification->SetInput(image); classification->Initialise(); double rel_diff; //for (i = 0; rel_diff > 0.0001; i++){ i=0; do { cout << "Iteration = " << i+1 << " / " << iterations << endl; rel_diff = classification->Iterate(i); i++; } while ((rel_diff>0.001)&&(i<50)); irtkRealImage segmentation; classification->ConstructSegmentation(segmentation); segmentation.Write(output_name); if (n==11) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"caudate.nii.gz"); classification->WriteProbMap(3,"putamen.nii.gz"); classification->WriteProbMap(4,"nigra.nii.gz"); classification->WriteProbMap(5,"cerebellum.nii.gz"); classification->WriteProbMap(6,"thalamus.nii.gz"); classification->WriteProbMap(7,"pallidum.nii.gz"); classification->WriteProbMap(8,"brainstem.nii.gz"); classification->WriteProbMap(9,"white.nii.gz"); classification->WriteProbMap(10,"cerebellum-white.nii.gz"); classification->WriteProbMap(11,"other.nii.gz"); } if (n==7) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"caudate.nii.gz"); classification->WriteProbMap(3,"putamen.nii.gz"); classification->WriteProbMap(4,"thalamus.nii.gz"); classification->WriteProbMap(5,"pallidum.nii.gz"); classification->WriteProbMap(6,"white.nii.gz"); classification->WriteProbMap(7,"other.nii.gz"); } if (n==3) { classification->WriteProbMap(0,"csf.nii.gz"); classification->WriteProbMap(1,"gray.nii.gz"); classification->WriteProbMap(2,"white.nii.gz"); } classification->WriteGaussianParameters("parameters.txt"); delete classification; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDeque.h" #include "SkLayerRasterizer.h" #include "SkPaint.h" #include "SkRasterizer.h" #include "Test.h" class SkReadBuffer; // Dummy class to place on a paint just to ensure the paint's destructor // is called. // ONLY to be used by LayerRasterizer_destructor, since other tests may // be run in a separate thread, and this class is not threadsafe. class DummyRasterizer : public SkRasterizer { public: DummyRasterizer() : INHERITED() { // Not threadsafe. Only used in one thread. gCount++; } ~DummyRasterizer() { // Not threadsafe. Only used in one thread. gCount--; } static int GetCount() { return gCount; } SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(DummyRasterizer) private: DummyRasterizer(SkReadBuffer&) {} static int gCount; typedef SkRasterizer INHERITED; }; int DummyRasterizer::gCount; // Check to make sure that the SkPaint in the layer has its destructor called. DEF_TEST(LayerRasterizer_destructor, reporter) { { SkPaint paint; paint.setRasterizer(SkNEW(DummyRasterizer))->unref(); REPORTER_ASSERT(reporter, DummyRasterizer::GetCount() == 1); SkLayerRasterizer::Builder builder; builder.addLayer(paint); } REPORTER_ASSERT(reporter, DummyRasterizer::GetCount() == 0); } class LayerRasterizerTester { public: static int CountLayers(const SkLayerRasterizer& layerRasterizer) { return layerRasterizer.fLayers->count(); } static const SkDeque& GetLayers(const SkLayerRasterizer& layerRasterizer) { return *layerRasterizer.fLayers; } }; // MUST stay in sync with definition of SkLayerRasterizer_Rec in SkLayerRasterizer.cpp. struct SkLayerRasterizer_Rec { SkPaint fPaint; SkVector fOffset; }; static bool equals(const SkLayerRasterizer_Rec& rec1, const SkLayerRasterizer_Rec& rec2) { return rec1.fPaint == rec2.fPaint && rec1.fOffset == rec2.fOffset; } DEF_TEST(LayerRasterizer_copy, reporter) { SkLayerRasterizer::Builder builder; SkPaint paint; // Create a bunch of paints with different flags. for (uint32_t flags = 0x01; flags < SkPaint::kAllFlags; flags <<= 1) { paint.setFlags(flags); builder.addLayer(paint, flags, flags); } // Create a layer rasterizer with all the existing layers. SkAutoTUnref<SkLayerRasterizer> firstCopy(builder.snapshotRasterizer()); // Add one more layer. paint.setFlags(SkPaint::kAllFlags); builder.addLayer(paint); SkAutoTUnref<SkLayerRasterizer> oneLarger(builder.snapshotRasterizer()); SkAutoTUnref<SkLayerRasterizer> detached(builder.detachRasterizer()); // Check the counts for consistency. const int largerCount = LayerRasterizerTester::CountLayers(*oneLarger.get()); const int smallerCount = LayerRasterizerTester::CountLayers(*firstCopy.get()); REPORTER_ASSERT(reporter, largerCount == LayerRasterizerTester::CountLayers(*detached.get())); REPORTER_ASSERT(reporter, smallerCount == largerCount - 1); const SkLayerRasterizer_Rec* recFirstCopy = NULL; const SkLayerRasterizer_Rec* recOneLarger = NULL; const SkLayerRasterizer_Rec* recDetached = NULL; const SkDeque& layersFirstCopy = LayerRasterizerTester::GetLayers(*firstCopy.get()); const SkDeque& layersOneLarger = LayerRasterizerTester::GetLayers(*oneLarger.get()); const SkDeque& layersDetached = LayerRasterizerTester::GetLayers(*detached.get()); // Ensure that our version of SkLayerRasterizer_Rec is the same as the one in // SkLayerRasterizer.cpp - or at least the same size. If the order were switched, we // would fail the test elsewhere. REPORTER_ASSERT(reporter, layersFirstCopy.elemSize() == sizeof(SkLayerRasterizer_Rec)); REPORTER_ASSERT(reporter, layersOneLarger.elemSize() == sizeof(SkLayerRasterizer_Rec)); REPORTER_ASSERT(reporter, layersDetached.elemSize() == sizeof(SkLayerRasterizer_Rec)); SkDeque::F2BIter iterFirstCopy(layersFirstCopy); SkDeque::F2BIter iterOneLarger(layersOneLarger); SkDeque::F2BIter iterDetached(layersDetached); for (int i = 0; i < largerCount; ++i) { recFirstCopy = static_cast<const SkLayerRasterizer_Rec*>(iterFirstCopy.next()); recOneLarger = static_cast<const SkLayerRasterizer_Rec*>(iterOneLarger.next()); recDetached = static_cast<const SkLayerRasterizer_Rec*>(iterDetached.next()); REPORTER_ASSERT(reporter, equals(*recOneLarger, *recDetached)); if (smallerCount == i) { REPORTER_ASSERT(reporter, recFirstCopy == NULL); } else { REPORTER_ASSERT(reporter, equals(*recFirstCopy, *recOneLarger)); } } } <commit_msg>Cast int to float.<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkDeque.h" #include "SkLayerRasterizer.h" #include "SkPaint.h" #include "SkRasterizer.h" #include "Test.h" class SkReadBuffer; // Dummy class to place on a paint just to ensure the paint's destructor // is called. // ONLY to be used by LayerRasterizer_destructor, since other tests may // be run in a separate thread, and this class is not threadsafe. class DummyRasterizer : public SkRasterizer { public: DummyRasterizer() : INHERITED() { // Not threadsafe. Only used in one thread. gCount++; } ~DummyRasterizer() { // Not threadsafe. Only used in one thread. gCount--; } static int GetCount() { return gCount; } SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(DummyRasterizer) private: DummyRasterizer(SkReadBuffer&) {} static int gCount; typedef SkRasterizer INHERITED; }; int DummyRasterizer::gCount; // Check to make sure that the SkPaint in the layer has its destructor called. DEF_TEST(LayerRasterizer_destructor, reporter) { { SkPaint paint; paint.setRasterizer(SkNEW(DummyRasterizer))->unref(); REPORTER_ASSERT(reporter, DummyRasterizer::GetCount() == 1); SkLayerRasterizer::Builder builder; builder.addLayer(paint); } REPORTER_ASSERT(reporter, DummyRasterizer::GetCount() == 0); } class LayerRasterizerTester { public: static int CountLayers(const SkLayerRasterizer& layerRasterizer) { return layerRasterizer.fLayers->count(); } static const SkDeque& GetLayers(const SkLayerRasterizer& layerRasterizer) { return *layerRasterizer.fLayers; } }; // MUST stay in sync with definition of SkLayerRasterizer_Rec in SkLayerRasterizer.cpp. struct SkLayerRasterizer_Rec { SkPaint fPaint; SkVector fOffset; }; static bool equals(const SkLayerRasterizer_Rec& rec1, const SkLayerRasterizer_Rec& rec2) { return rec1.fPaint == rec2.fPaint && rec1.fOffset == rec2.fOffset; } DEF_TEST(LayerRasterizer_copy, reporter) { SkLayerRasterizer::Builder builder; SkPaint paint; // Create a bunch of paints with different flags. for (uint32_t flags = 0x01; flags < SkPaint::kAllFlags; flags <<= 1) { paint.setFlags(flags); builder.addLayer(paint, static_cast<SkScalar>(flags), static_cast<SkScalar>(flags)); } // Create a layer rasterizer with all the existing layers. SkAutoTUnref<SkLayerRasterizer> firstCopy(builder.snapshotRasterizer()); // Add one more layer. paint.setFlags(SkPaint::kAllFlags); builder.addLayer(paint); SkAutoTUnref<SkLayerRasterizer> oneLarger(builder.snapshotRasterizer()); SkAutoTUnref<SkLayerRasterizer> detached(builder.detachRasterizer()); // Check the counts for consistency. const int largerCount = LayerRasterizerTester::CountLayers(*oneLarger.get()); const int smallerCount = LayerRasterizerTester::CountLayers(*firstCopy.get()); REPORTER_ASSERT(reporter, largerCount == LayerRasterizerTester::CountLayers(*detached.get())); REPORTER_ASSERT(reporter, smallerCount == largerCount - 1); const SkLayerRasterizer_Rec* recFirstCopy = NULL; const SkLayerRasterizer_Rec* recOneLarger = NULL; const SkLayerRasterizer_Rec* recDetached = NULL; const SkDeque& layersFirstCopy = LayerRasterizerTester::GetLayers(*firstCopy.get()); const SkDeque& layersOneLarger = LayerRasterizerTester::GetLayers(*oneLarger.get()); const SkDeque& layersDetached = LayerRasterizerTester::GetLayers(*detached.get()); // Ensure that our version of SkLayerRasterizer_Rec is the same as the one in // SkLayerRasterizer.cpp - or at least the same size. If the order were switched, we // would fail the test elsewhere. REPORTER_ASSERT(reporter, layersFirstCopy.elemSize() == sizeof(SkLayerRasterizer_Rec)); REPORTER_ASSERT(reporter, layersOneLarger.elemSize() == sizeof(SkLayerRasterizer_Rec)); REPORTER_ASSERT(reporter, layersDetached.elemSize() == sizeof(SkLayerRasterizer_Rec)); SkDeque::F2BIter iterFirstCopy(layersFirstCopy); SkDeque::F2BIter iterOneLarger(layersOneLarger); SkDeque::F2BIter iterDetached(layersDetached); for (int i = 0; i < largerCount; ++i) { recFirstCopy = static_cast<const SkLayerRasterizer_Rec*>(iterFirstCopy.next()); recOneLarger = static_cast<const SkLayerRasterizer_Rec*>(iterOneLarger.next()); recDetached = static_cast<const SkLayerRasterizer_Rec*>(iterDetached.next()); REPORTER_ASSERT(reporter, equals(*recOneLarger, *recDetached)); if (smallerCount == i) { REPORTER_ASSERT(reporter, recFirstCopy == NULL); } else { REPORTER_ASSERT(reporter, equals(*recFirstCopy, *recOneLarger)); } } } <|endoftext|>
<commit_before>/*========================================================================= Program: Visualization Toolkit Module: vtkLabeledDataMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkLabeledDataMapper.h" #include "vtkDataSet.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkLabeledDataMapper* vtkLabeledDataMapper::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkLabeledDataMapper"); if(ret) { return (vtkLabeledDataMapper*)ret; } // If the factory was unable to create the object, then create it here. return new vtkLabeledDataMapper; } // Instantiate object with font size 12 of font Arial (bolding, // italic, shadows on) and %%-#6.3g label format. By default, point ids // are labeled. vtkLabeledDataMapper::vtkLabeledDataMapper() { this->Input = NULL; this->LabelMode = VTK_LABEL_IDS; this->FontSize = 12; this->Bold = 1; this->Italic = 1; this->Shadow = 1; this->FontFamily = VTK_ARIAL; this->LabelFormat = new char[8]; strcpy(this->LabelFormat,"%g"); this->LabeledComponent = (-1); this->FieldDataArray = 0; this->NumberOfLabels = 0; this->NumberOfLabelsAllocated = 50; this->TextMappers = new vtkTextMapper * [this->NumberOfLabelsAllocated]; for (int i=0; i<this->NumberOfLabelsAllocated; i++) { this->TextMappers[i] = vtkTextMapper::New(); } } // Release any graphics resources that are being consumed by this actor. // The parameter window could be used to determine which graphic // resources to release. void vtkLabeledDataMapper::ReleaseGraphicsResources(vtkWindow *win) { if (this->TextMappers != NULL ) { for (int i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->ReleaseGraphicsResources(win); } } } vtkLabeledDataMapper::~vtkLabeledDataMapper() { if (this->LabelFormat) { delete [] this->LabelFormat; } if (this->TextMappers != NULL ) { for (int i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->Delete(); } delete [] this->TextMappers; } this->SetInput(NULL); } void vtkLabeledDataMapper::RenderOverlay(vtkViewport *viewport, vtkActor2D *actor) { int i; float x[3]; vtkDataSet *input=this->GetInput(); if ( ! input ) { vtkErrorMacro(<<"Need input data to render labels"); return; } for (i=0; i<this->NumberOfLabels; i++) { this->Input->GetPoint(i,x); actor->GetPositionCoordinate()->SetCoordinateSystemToWorld(); actor->GetPositionCoordinate()->SetValue(x); this->TextMappers[i]->RenderOverlay(viewport, actor); } } void vtkLabeledDataMapper::RenderOpaqueGeometry(vtkViewport *viewport, vtkActor2D *actor) { int i, j, numComp = 0, pointIdLabels, activeComp = 0; char string[1024], format[1024]; float val, x[3]; vtkDataSet *input=this->GetInput(); if ( ! input ) { vtkErrorMacro(<<"Need input data to render labels"); return; } vtkPointData *pd=input->GetPointData(); vtkDataArray *data; float *tuple; vtkFieldData *fd; input->Update(); // Check to see whether we have to rebuild everything if ( this->GetMTime() > this->BuildTime || input->GetMTime() > this->BuildTime ) { vtkDebugMacro(<<"Rebuilding labels"); // figure out what to label, and if we can label it pointIdLabels = 0; data = NULL; switch (this->LabelMode) { case VTK_LABEL_IDS: pointIdLabels = 1; break; case VTK_LABEL_SCALARS: if ( pd->GetScalars() ) { data = pd->GetScalars()->GetData(); } break; case VTK_LABEL_VECTORS: if ( pd->GetVectors() ) { data = pd->GetVectors()->GetData(); } break; case VTK_LABEL_NORMALS: if ( pd->GetNormals() ) { data = pd->GetNormals()->GetData(); } break; case VTK_LABEL_TCOORDS: if ( pd->GetTCoords() ) { data = pd->GetTCoords()->GetData(); } break; case VTK_LABEL_TENSORS: if ( pd->GetTensors() ) { data = pd->GetTensors()->GetData(); } break; case VTK_LABEL_FIELD_DATA: if ( (fd=pd->GetFieldData()) ) { int arrayNum = (this->FieldDataArray < fd->GetNumberOfArrays() ? this->FieldDataArray : fd->GetNumberOfArrays() - 1); data = pd->GetFieldData()->GetArray(arrayNum); } break; } // determine number of components and check input if ( pointIdLabels ) { ; } else if ( data ) { numComp = data->GetNumberOfComponents(); tuple = new float[numComp]; activeComp = 0; if ( this->LabeledComponent >= 0 ) { numComp = 1; activeComp = (this->LabeledComponent < numComp ? this->LabeledComponent : numComp - 1); } } else { vtkErrorMacro(<<"Need input data to render labels"); return; } this->NumberOfLabels = this->Input->GetNumberOfPoints(); if ( this->NumberOfLabels > this->NumberOfLabelsAllocated ) { // delete old stuff for (i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->Delete(); } delete [] this->TextMappers; this->NumberOfLabelsAllocated = this->NumberOfLabels; this->TextMappers = new vtkTextMapper * [this->NumberOfLabelsAllocated]; for (i=0; i<this->NumberOfLabelsAllocated; i++) { this->TextMappers[i] = vtkTextMapper::New(); } }//if we have to allocate new text mappers for (i=0; i < this->NumberOfLabels; i++) { if ( pointIdLabels ) { val = (float)i; sprintf(string, this->LabelFormat, val); } else { data->GetTuple(i, tuple); if ( numComp == 1) { sprintf(string, this->LabelFormat, tuple[activeComp]); } else { strcpy(format, "("); strcat(format, this->LabelFormat); for (j=0; j<(numComp-1); j++) { sprintf(string, format, tuple[j]); strcpy(format,string); strcat(format,", "); strcat(format, this->LabelFormat); } sprintf(string, format, tuple[numComp-1]); strcat(string, ")"); } } this->TextMappers[i]->SetInput(string); this->TextMappers[i]->SetFontSize(this->FontSize); this->TextMappers[i]->SetBold(this->Bold); this->TextMappers[i]->SetItalic(this->Italic); this->TextMappers[i]->SetShadow(this->Shadow); this->TextMappers[i]->SetFontFamily(this->FontFamily); } if ( data ) { delete [] tuple; } this->BuildTime.Modified(); } for (i=0; i<this->NumberOfLabels; i++) { this->Input->GetPoint(i,x); actor->GetPositionCoordinate()->SetCoordinateSystemToWorld(); actor->GetPositionCoordinate()->SetValue(x); this->TextMappers[i]->RenderOpaqueGeometry(viewport, actor); } } void vtkLabeledDataMapper::PrintSelf(ostream& os, vtkIndent indent) { vtkMapper2D::PrintSelf(os,indent); if ( this->Input ) { os << indent << "Input: (" << this->Input << ")\n"; } else { os << indent << "Input: (none)\n"; } os << indent << "Label Mode: "; if ( this->LabelMode == VTK_LABEL_IDS ) { os << "Label Ids\n"; } else if ( this->LabelMode == VTK_LABEL_SCALARS ) { os << "Label Scalars\n"; } else if ( this->LabelMode == VTK_LABEL_VECTORS ) { os << "Label Vectors\n"; } else if ( this->LabelMode == VTK_LABEL_NORMALS ) { os << "Label Normals\n"; } else if ( this->LabelMode == VTK_LABEL_TCOORDS ) { os << "Label TCoords\n"; } else if ( this->LabelMode == VTK_LABEL_TENSORS ) { os << "Label Tensors\n"; } else { os << "Label Field Data\n"; } os << indent << "Font Family: "; if ( this->FontFamily == VTK_ARIAL ) { os << "Arial\n"; } else if ( this->FontFamily == VTK_COURIER ) { os << "Courier\n"; } else { os << "Times\n"; } os << indent << "Font Size: " << this->FontSize << "\n"; os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n"); os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n"); os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n"); os << indent << "Label Format: " << this->LabelFormat << "\n"; os << indent << "Labeled Component: "; if ( this->LabeledComponent < 0 ) { os << "(All Components)\n"; } else { os << this->LabeledComponent << "\n"; } os << indent << "Field Data Array: " << this->FieldDataArray << "\n"; } <commit_msg>ERR: Last check in had conflict. Missed a NULLset when resolving. Seems previous check in put this in to remove warnings.<commit_after>/*========================================================================= Program: Visualization Toolkit Module: vtkLabeledDataMapper.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. * Modified source versions must be plainly marked as such, and must not be misrepresented as being the original software. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. =========================================================================*/ #include "vtkLabeledDataMapper.h" #include "vtkDataSet.h" #include "vtkObjectFactory.h" //------------------------------------------------------------------------------ vtkLabeledDataMapper* vtkLabeledDataMapper::New() { // First try to create the object from the vtkObjectFactory vtkObject* ret = vtkObjectFactory::CreateInstance("vtkLabeledDataMapper"); if(ret) { return (vtkLabeledDataMapper*)ret; } // If the factory was unable to create the object, then create it here. return new vtkLabeledDataMapper; } // Instantiate object with font size 12 of font Arial (bolding, // italic, shadows on) and %%-#6.3g label format. By default, point ids // are labeled. vtkLabeledDataMapper::vtkLabeledDataMapper() { this->Input = NULL; this->LabelMode = VTK_LABEL_IDS; this->FontSize = 12; this->Bold = 1; this->Italic = 1; this->Shadow = 1; this->FontFamily = VTK_ARIAL; this->LabelFormat = new char[8]; strcpy(this->LabelFormat,"%g"); this->LabeledComponent = (-1); this->FieldDataArray = 0; this->NumberOfLabels = 0; this->NumberOfLabelsAllocated = 50; this->TextMappers = new vtkTextMapper * [this->NumberOfLabelsAllocated]; for (int i=0; i<this->NumberOfLabelsAllocated; i++) { this->TextMappers[i] = vtkTextMapper::New(); } } // Release any graphics resources that are being consumed by this actor. // The parameter window could be used to determine which graphic // resources to release. void vtkLabeledDataMapper::ReleaseGraphicsResources(vtkWindow *win) { if (this->TextMappers != NULL ) { for (int i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->ReleaseGraphicsResources(win); } } } vtkLabeledDataMapper::~vtkLabeledDataMapper() { if (this->LabelFormat) { delete [] this->LabelFormat; } if (this->TextMappers != NULL ) { for (int i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->Delete(); } delete [] this->TextMappers; } this->SetInput(NULL); } void vtkLabeledDataMapper::RenderOverlay(vtkViewport *viewport, vtkActor2D *actor) { int i; float x[3]; vtkDataSet *input=this->GetInput(); if ( ! input ) { vtkErrorMacro(<<"Need input data to render labels"); return; } for (i=0; i<this->NumberOfLabels; i++) { this->Input->GetPoint(i,x); actor->GetPositionCoordinate()->SetCoordinateSystemToWorld(); actor->GetPositionCoordinate()->SetValue(x); this->TextMappers[i]->RenderOverlay(viewport, actor); } } void vtkLabeledDataMapper::RenderOpaqueGeometry(vtkViewport *viewport, vtkActor2D *actor) { int i, j, numComp = 0, pointIdLabels, activeComp = 0; char string[1024], format[1024]; float val, x[3]; vtkDataSet *input=this->GetInput(); if ( ! input ) { vtkErrorMacro(<<"Need input data to render labels"); return; } vtkPointData *pd=input->GetPointData(); vtkDataArray *data; float *tuple=NULL; vtkFieldData *fd; input->Update(); // Check to see whether we have to rebuild everything if ( this->GetMTime() > this->BuildTime || input->GetMTime() > this->BuildTime ) { vtkDebugMacro(<<"Rebuilding labels"); // figure out what to label, and if we can label it pointIdLabels = 0; data = NULL; switch (this->LabelMode) { case VTK_LABEL_IDS: pointIdLabels = 1; break; case VTK_LABEL_SCALARS: if ( pd->GetScalars() ) { data = pd->GetScalars()->GetData(); } break; case VTK_LABEL_VECTORS: if ( pd->GetVectors() ) { data = pd->GetVectors()->GetData(); } break; case VTK_LABEL_NORMALS: if ( pd->GetNormals() ) { data = pd->GetNormals()->GetData(); } break; case VTK_LABEL_TCOORDS: if ( pd->GetTCoords() ) { data = pd->GetTCoords()->GetData(); } break; case VTK_LABEL_TENSORS: if ( pd->GetTensors() ) { data = pd->GetTensors()->GetData(); } break; case VTK_LABEL_FIELD_DATA: if ( (fd=pd->GetFieldData()) ) { int arrayNum = (this->FieldDataArray < fd->GetNumberOfArrays() ? this->FieldDataArray : fd->GetNumberOfArrays() - 1); data = pd->GetFieldData()->GetArray(arrayNum); } break; } // determine number of components and check input if ( pointIdLabels ) { ; } else if ( data ) { numComp = data->GetNumberOfComponents(); tuple = new float[numComp]; activeComp = 0; if ( this->LabeledComponent >= 0 ) { numComp = 1; activeComp = (this->LabeledComponent < numComp ? this->LabeledComponent : numComp - 1); } } else { vtkErrorMacro(<<"Need input data to render labels"); return; } this->NumberOfLabels = this->Input->GetNumberOfPoints(); if ( this->NumberOfLabels > this->NumberOfLabelsAllocated ) { // delete old stuff for (i=0; i < this->NumberOfLabelsAllocated; i++) { this->TextMappers[i]->Delete(); } delete [] this->TextMappers; this->NumberOfLabelsAllocated = this->NumberOfLabels; this->TextMappers = new vtkTextMapper * [this->NumberOfLabelsAllocated]; for (i=0; i<this->NumberOfLabelsAllocated; i++) { this->TextMappers[i] = vtkTextMapper::New(); } }//if we have to allocate new text mappers for (i=0; i < this->NumberOfLabels; i++) { if ( pointIdLabels ) { val = (float)i; sprintf(string, this->LabelFormat, val); } else { data->GetTuple(i, tuple); if ( numComp == 1) { sprintf(string, this->LabelFormat, tuple[activeComp]); } else { strcpy(format, "("); strcat(format, this->LabelFormat); for (j=0; j<(numComp-1); j++) { sprintf(string, format, tuple[j]); strcpy(format,string); strcat(format,", "); strcat(format, this->LabelFormat); } sprintf(string, format, tuple[numComp-1]); strcat(string, ")"); } } this->TextMappers[i]->SetInput(string); this->TextMappers[i]->SetFontSize(this->FontSize); this->TextMappers[i]->SetBold(this->Bold); this->TextMappers[i]->SetItalic(this->Italic); this->TextMappers[i]->SetShadow(this->Shadow); this->TextMappers[i]->SetFontFamily(this->FontFamily); } if ( data ) { delete [] tuple; } this->BuildTime.Modified(); } for (i=0; i<this->NumberOfLabels; i++) { this->Input->GetPoint(i,x); actor->GetPositionCoordinate()->SetCoordinateSystemToWorld(); actor->GetPositionCoordinate()->SetValue(x); this->TextMappers[i]->RenderOpaqueGeometry(viewport, actor); } } void vtkLabeledDataMapper::PrintSelf(ostream& os, vtkIndent indent) { vtkMapper2D::PrintSelf(os,indent); if ( this->Input ) { os << indent << "Input: (" << this->Input << ")\n"; } else { os << indent << "Input: (none)\n"; } os << indent << "Label Mode: "; if ( this->LabelMode == VTK_LABEL_IDS ) { os << "Label Ids\n"; } else if ( this->LabelMode == VTK_LABEL_SCALARS ) { os << "Label Scalars\n"; } else if ( this->LabelMode == VTK_LABEL_VECTORS ) { os << "Label Vectors\n"; } else if ( this->LabelMode == VTK_LABEL_NORMALS ) { os << "Label Normals\n"; } else if ( this->LabelMode == VTK_LABEL_TCOORDS ) { os << "Label TCoords\n"; } else if ( this->LabelMode == VTK_LABEL_TENSORS ) { os << "Label Tensors\n"; } else { os << "Label Field Data\n"; } os << indent << "Font Family: "; if ( this->FontFamily == VTK_ARIAL ) { os << "Arial\n"; } else if ( this->FontFamily == VTK_COURIER ) { os << "Courier\n"; } else { os << "Times\n"; } os << indent << "Font Size: " << this->FontSize << "\n"; os << indent << "Bold: " << (this->Bold ? "On\n" : "Off\n"); os << indent << "Italic: " << (this->Italic ? "On\n" : "Off\n"); os << indent << "Shadow: " << (this->Shadow ? "On\n" : "Off\n"); os << indent << "Label Format: " << this->LabelFormat << "\n"; os << indent << "Labeled Component: "; if ( this->LabeledComponent < 0 ) { os << "(All Components)\n"; } else { os << this->LabeledComponent << "\n"; } os << indent << "Field Data Array: " << this->FieldDataArray << "\n"; } <|endoftext|>
<commit_before>//===- BreakConstantGEPs.cpp - Change constant GEPs into GEP instructions - --// // // pocl note: This pass is taken from The SAFECode project with trivial modifications. // Automatic locals might cause constant GEPs which cause problems during // converting the locals to kernel function arguments for thread safety. // // The SAFECode Compiler // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass changes all GEP constant expressions into GEP instructions. This // permits the rest of SAFECode to put run-time checks on them if necessary. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "break-constgeps" #include "CompilerWarnings.h" IGNORE_COMPILER_WARNING("-Wunused-parameter") #include "config.h" #if (defined LLVM_3_1 || defined LLVM_3_2) #include "llvm/Constants.h" #include "llvm/InstrTypes.h" #include "llvm/Instruction.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #else #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #endif #include "llvm/ADT/Statistic.h" #if (defined LLVM_3_2 || defined LLVM_3_3 || defined LLVM_3_4) #include "llvm/Support/InstIterator.h" #else #include "llvm/IR/InstIterator.h" #endif #include "BreakConstantGEPs.h" #include "Workgroup.h" #include <iostream> #include <map> #include <utility> // Identifier variable for the pass char BreakConstantGEPs::ID = 0; // Statistics STATISTIC (GEPChanges, "Number of Converted GEP Constant Expressions"); STATISTIC (TotalChanges, "Number of Converted Constant Expressions"); POP_COMPILER_DIAGS // Register the pass static RegisterPass<BreakConstantGEPs> P ("break-constgeps", "Remove GEP Constant Expressions"); // // Function: hasConstantGEP() // // Description: // This function determines whether the given value is a constant expression // that has a constant GEP expression embedded within it. // // Inputs: // V - The value to check. // // Return value: // NULL - This value is not a constant expression with a constant expression // GEP within it. // ~NULL - A pointer to the value casted into a ConstantExpr is returned. // static ConstantExpr * hasConstantGEP (Value * V) { if (ConstantExpr * CE = dyn_cast<ConstantExpr>(V)) { if (CE->getOpcode() == Instruction::GetElementPtr || CE->getOpcode() == Instruction::BitCast) { return CE; } else { for (unsigned index = 0; index < CE->getNumOperands(); ++index) { if (hasConstantGEP (CE->getOperand(index))) return CE; } } } return 0; } // // Function: convertGEP() // // Description: // Convert a GEP constant expression into a GEP instruction. // // Inputs: // CE - The GEP constant expression. // InsertPt - The instruction before which to insert the new GEP instruction. // // Return value: // A pointer to the new GEP instruction is returned. // static Instruction * convertGEP (ConstantExpr * CE, Instruction * InsertPt) { // // Create iterators to the indices of the constant expression. // std::vector<Value *> Indices; for (unsigned index = 1; index < CE->getNumOperands(); ++index) { Indices.push_back (CE->getOperand (index)); } // // Update the statistics. // ++GEPChanges; // // Make the new GEP instruction. // #ifdef LLVM_OLDER_THAN_3_7 return (GetElementPtrInst::Create (CE->getOperand(0), Indices, CE->getName(), InsertPt)); #else /* The first NULL is the Type. It is not used at all, just asserted * against. And it asserts, no matter what is passed. Except NULL. * Seems this API is still "fluctuation in progress"*/ return (GetElementPtrInst::Create (NULL, CE->getOperand(0), Indices, CE->getName(), InsertPt)); #endif } // // Function: convertExpression() // // Description: // Convert a constant expression into an instruction. This routine does *not* // perform any recursion, so the resulting instruction may have constant // expression operands. // static Instruction * convertExpression (ConstantExpr * CE, Instruction * InsertPt) { // // Convert this constant expression into a regular instruction. // Instruction * NewInst = 0; switch (CE->getOpcode()) { case Instruction::GetElementPtr: { NewInst = convertGEP (CE, InsertPt); break; } case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: { Instruction::BinaryOps Op = (Instruction::BinaryOps)(CE->getOpcode()); NewInst = BinaryOperator::Create (Op, CE->getOperand(0), CE->getOperand(1), CE->getName(), InsertPt); break; } case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::PtrToInt: case Instruction::IntToPtr: case Instruction::BitCast: { Instruction::CastOps Op = (Instruction::CastOps)(CE->getOpcode()); NewInst = CastInst::Create (Op, CE->getOperand(0), CE->getType(), CE->getName(), InsertPt); break; } case Instruction:: FCmp: case Instruction:: ICmp: { Instruction::OtherOps Op = (Instruction::OtherOps)(CE->getOpcode()); NewInst = CmpInst::Create (Op, CE->getPredicate(), CE->getOperand(0), CE->getOperand(1), CE->getName(), InsertPt); break; } case Instruction:: Select: NewInst = SelectInst::Create (CE->getOperand(0), CE->getOperand(1), CE->getOperand(2), CE->getName(), InsertPt); break; case Instruction:: ExtractElement: case Instruction:: InsertElement: case Instruction:: ShuffleVector: case Instruction:: InsertValue: default: assert (0 && "Unhandled constant expression!\n"); break; } // // Update the statistics. // ++TotalChanges; return NewInst; } // // Method: runOnFunction() // // Description: // Entry point for this LLVM pass. // // Return value: // true - The function was modified. // false - The function was not modified. // bool BreakConstantGEPs::runOnFunction (Function & F) { if (!pocl::Workgroup::isKernelToProcess(F)) return false; bool modified = false; // Worklist of values to check for constant GEP expressions std::vector<Instruction *> Worklist; // // Initialize the worklist by finding all instructions that have one or more // operands containing a constant GEP expression. // for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) { for (BasicBlock::iterator i = BB->begin(); i != BB->end(); ++i) { // // Scan through the operands of this instruction. If it is a constant // expression GEP, insert an instruction GEP before the instruction. // Instruction * I = i; for (unsigned index = 0; index < I->getNumOperands(); ++index) { if (hasConstantGEP (I->getOperand(index))) { Worklist.push_back (I); } } } } // // Determine whether we will modify anything. // if (Worklist.size()) modified = true; // // While the worklist is not empty, take an item from it, convert the // operands into instructions if necessary, and determine if the newly // added instructions need to be processed as well. // while (Worklist.size()) { Instruction * I = Worklist.back(); Worklist.pop_back(); // // Scan through the operands of this instruction and convert each into an // instruction. Note that this works a little differently for phi // instructions because the new instruction must be added to the // appropriate predecessor block. // if (PHINode * PHI = dyn_cast<PHINode>(I)) { for (unsigned index = 0; index < PHI->getNumIncomingValues(); ++index) { // // For PHI Nodes, if an operand is a constant expression with a GEP, we // want to insert the new instructions in the predecessor basic block. // // Note: It seems that it's possible for a phi to have the same // incoming basic block listed multiple times; this seems okay as long // the same value is listed for the incoming block. // Instruction * InsertPt = PHI->getIncomingBlock(index)->getTerminator(); if (ConstantExpr * CE = hasConstantGEP (PHI->getIncomingValue(index))) { Instruction * NewInst = convertExpression (CE, InsertPt); for (unsigned i2 = index; i2 < PHI->getNumIncomingValues(); ++i2) { if ((PHI->getIncomingBlock (i2)) == PHI->getIncomingBlock (index)) PHI->setIncomingValue (i2, NewInst); } Worklist.push_back (NewInst); } } } else { for (unsigned index = 0; index < I->getNumOperands(); ++index) { // // For other instructions, we want to insert instructions replacing // constant expressions immediently before the instruction using the // constant expression. // if (ConstantExpr * CE = hasConstantGEP (I->getOperand(index))) { Instruction * NewInst = convertExpression (CE, I); I->replaceUsesOfWith (CE, NewInst); Worklist.push_back (NewInst); } } } } return modified; } <commit_msg>Unbreak build on LLVM <3.7<commit_after>//===- BreakConstantGEPs.cpp - Change constant GEPs into GEP instructions - --// // // pocl note: This pass is taken from The SAFECode project with trivial modifications. // Automatic locals might cause constant GEPs which cause problems during // converting the locals to kernel function arguments for thread safety. // // The SAFECode Compiler // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This pass changes all GEP constant expressions into GEP instructions. This // permits the rest of SAFECode to put run-time checks on them if necessary. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "break-constgeps" #include "CompilerWarnings.h" IGNORE_COMPILER_WARNING("-Wunused-parameter") #include "config.h" #include "pocl.h" #if (defined LLVM_3_1 || defined LLVM_3_2) #include "llvm/Constants.h" #include "llvm/InstrTypes.h" #include "llvm/Instruction.h" #include "llvm/Instructions.h" #include "llvm/LLVMContext.h" #else #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instruction.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/LLVMContext.h" #endif #include "llvm/ADT/Statistic.h" #if (defined LLVM_3_2 || defined LLVM_3_3 || defined LLVM_3_4) #include "llvm/Support/InstIterator.h" #else #include "llvm/IR/InstIterator.h" #endif #include "BreakConstantGEPs.h" #include "Workgroup.h" #include <iostream> #include <map> #include <utility> // Identifier variable for the pass char BreakConstantGEPs::ID = 0; // Statistics STATISTIC (GEPChanges, "Number of Converted GEP Constant Expressions"); STATISTIC (TotalChanges, "Number of Converted Constant Expressions"); POP_COMPILER_DIAGS // Register the pass static RegisterPass<BreakConstantGEPs> P ("break-constgeps", "Remove GEP Constant Expressions"); // // Function: hasConstantGEP() // // Description: // This function determines whether the given value is a constant expression // that has a constant GEP expression embedded within it. // // Inputs: // V - The value to check. // // Return value: // NULL - This value is not a constant expression with a constant expression // GEP within it. // ~NULL - A pointer to the value casted into a ConstantExpr is returned. // static ConstantExpr * hasConstantGEP (Value * V) { if (ConstantExpr * CE = dyn_cast<ConstantExpr>(V)) { if (CE->getOpcode() == Instruction::GetElementPtr || CE->getOpcode() == Instruction::BitCast) { return CE; } else { for (unsigned index = 0; index < CE->getNumOperands(); ++index) { if (hasConstantGEP (CE->getOperand(index))) return CE; } } } return 0; } // // Function: convertGEP() // // Description: // Convert a GEP constant expression into a GEP instruction. // // Inputs: // CE - The GEP constant expression. // InsertPt - The instruction before which to insert the new GEP instruction. // // Return value: // A pointer to the new GEP instruction is returned. // static Instruction * convertGEP (ConstantExpr * CE, Instruction * InsertPt) { // // Create iterators to the indices of the constant expression. // std::vector<Value *> Indices; for (unsigned index = 1; index < CE->getNumOperands(); ++index) { Indices.push_back (CE->getOperand (index)); } // // Update the statistics. // ++GEPChanges; // // Make the new GEP instruction. // #ifdef LLVM_OLDER_THAN_3_7 return (GetElementPtrInst::Create (CE->getOperand(0), Indices, CE->getName(), InsertPt)); #else /* The first NULL is the Type. It is not used at all, just asserted * against. And it asserts, no matter what is passed. Except NULL. * Seems this API is still "fluctuation in progress"*/ return (GetElementPtrInst::Create (NULL, CE->getOperand(0), Indices, CE->getName(), InsertPt)); #endif } // // Function: convertExpression() // // Description: // Convert a constant expression into an instruction. This routine does *not* // perform any recursion, so the resulting instruction may have constant // expression operands. // static Instruction * convertExpression (ConstantExpr * CE, Instruction * InsertPt) { // // Convert this constant expression into a regular instruction. // Instruction * NewInst = 0; switch (CE->getOpcode()) { case Instruction::GetElementPtr: { NewInst = convertGEP (CE, InsertPt); break; } case Instruction::Add: case Instruction::Sub: case Instruction::Mul: case Instruction::UDiv: case Instruction::SDiv: case Instruction::FDiv: case Instruction::URem: case Instruction::SRem: case Instruction::FRem: case Instruction::Shl: case Instruction::LShr: case Instruction::AShr: case Instruction::And: case Instruction::Or: case Instruction::Xor: { Instruction::BinaryOps Op = (Instruction::BinaryOps)(CE->getOpcode()); NewInst = BinaryOperator::Create (Op, CE->getOperand(0), CE->getOperand(1), CE->getName(), InsertPt); break; } case Instruction::Trunc: case Instruction::ZExt: case Instruction::SExt: case Instruction::FPToUI: case Instruction::FPToSI: case Instruction::UIToFP: case Instruction::SIToFP: case Instruction::FPTrunc: case Instruction::FPExt: case Instruction::PtrToInt: case Instruction::IntToPtr: case Instruction::BitCast: { Instruction::CastOps Op = (Instruction::CastOps)(CE->getOpcode()); NewInst = CastInst::Create (Op, CE->getOperand(0), CE->getType(), CE->getName(), InsertPt); break; } case Instruction:: FCmp: case Instruction:: ICmp: { Instruction::OtherOps Op = (Instruction::OtherOps)(CE->getOpcode()); NewInst = CmpInst::Create (Op, CE->getPredicate(), CE->getOperand(0), CE->getOperand(1), CE->getName(), InsertPt); break; } case Instruction:: Select: NewInst = SelectInst::Create (CE->getOperand(0), CE->getOperand(1), CE->getOperand(2), CE->getName(), InsertPt); break; case Instruction:: ExtractElement: case Instruction:: InsertElement: case Instruction:: ShuffleVector: case Instruction:: InsertValue: default: assert (0 && "Unhandled constant expression!\n"); break; } // // Update the statistics. // ++TotalChanges; return NewInst; } // // Method: runOnFunction() // // Description: // Entry point for this LLVM pass. // // Return value: // true - The function was modified. // false - The function was not modified. // bool BreakConstantGEPs::runOnFunction (Function & F) { if (!pocl::Workgroup::isKernelToProcess(F)) return false; bool modified = false; // Worklist of values to check for constant GEP expressions std::vector<Instruction *> Worklist; // // Initialize the worklist by finding all instructions that have one or more // operands containing a constant GEP expression. // for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) { for (BasicBlock::iterator i = BB->begin(); i != BB->end(); ++i) { // // Scan through the operands of this instruction. If it is a constant // expression GEP, insert an instruction GEP before the instruction. // Instruction * I = i; for (unsigned index = 0; index < I->getNumOperands(); ++index) { if (hasConstantGEP (I->getOperand(index))) { Worklist.push_back (I); } } } } // // Determine whether we will modify anything. // if (Worklist.size()) modified = true; // // While the worklist is not empty, take an item from it, convert the // operands into instructions if necessary, and determine if the newly // added instructions need to be processed as well. // while (Worklist.size()) { Instruction * I = Worklist.back(); Worklist.pop_back(); // // Scan through the operands of this instruction and convert each into an // instruction. Note that this works a little differently for phi // instructions because the new instruction must be added to the // appropriate predecessor block. // if (PHINode * PHI = dyn_cast<PHINode>(I)) { for (unsigned index = 0; index < PHI->getNumIncomingValues(); ++index) { // // For PHI Nodes, if an operand is a constant expression with a GEP, we // want to insert the new instructions in the predecessor basic block. // // Note: It seems that it's possible for a phi to have the same // incoming basic block listed multiple times; this seems okay as long // the same value is listed for the incoming block. // Instruction * InsertPt = PHI->getIncomingBlock(index)->getTerminator(); if (ConstantExpr * CE = hasConstantGEP (PHI->getIncomingValue(index))) { Instruction * NewInst = convertExpression (CE, InsertPt); for (unsigned i2 = index; i2 < PHI->getNumIncomingValues(); ++i2) { if ((PHI->getIncomingBlock (i2)) == PHI->getIncomingBlock (index)) PHI->setIncomingValue (i2, NewInst); } Worklist.push_back (NewInst); } } } else { for (unsigned index = 0; index < I->getNumOperands(); ++index) { // // For other instructions, we want to insert instructions replacing // constant expressions immediently before the instruction using the // constant expression. // if (ConstantExpr * CE = hasConstantGEP (I->getOperand(index))) { Instruction * NewInst = convertExpression (CE, I); I->replaceUsesOfWith (CE, NewInst); Worklist.push_back (NewInst); } } } } return modified; } <|endoftext|>
<commit_before>#ifndef TO_FPTR_HPP_INCLUDED #define TO_FPTR_HPP_INCLUDED #include <utility> #include <functional> namespace tmp_lib { template<typename LAMBDA, typename RET, typename... ARGS> class to_fptr_t { static thread_local std::function<RET(ARGS...)> tl_function; static RET fptr_handler(ARGS... args) { tl_function(std::forward<ARGS>(args)...); } static void set_func(std::function<RET(ARGS...)>&& func) { tl_function = std::move(func); } public: template<typename LAMBDA2, typename RET2, typename... ARGS2> friend RET2(*to_fptr(std::function<RET2(ARGS2...)>, LAMBDA2))(ARGS2...); }; template<typename LAMBDA, typename RET, typename... ARGS> thread_local std::function<RET(ARGS...)> to_fptr_t<LAMBDA, RET, ARGS...>::tl_function = nullptr; template<typename LAMBDA, typename RET, typename... ARGS> RET(*to_fptr(std::function<RET(ARGS...)> func, LAMBDA lambda))(ARGS... args) { using T = to_fptr_t<LAMBDA, RET, ARGS...>; T::set_func(std::move(func)); //T::tl_function = std::move(func); return &T::fptr_handler; } } #endif // TO_FPTR_HPP_INCLUDED <commit_msg>Update to_fptr.hpp<commit_after>#ifndef TO_FPTR_HPP_INCLUDED #define TO_FPTR_HPP_INCLUDED #include <utility> #include <functional> namespace tmp_lib { template<typename LAMBDA, typename RET, typename... ARGS> class to_fptr_t { static thread_local std::function<RET(ARGS...)> tl_function; static RET fptr_handler(ARGS... args) { return tl_function(std::forward<ARGS>(args)...); } static void set_func(std::function<RET(ARGS...)>&& func) { tl_function = std::move(func); } public: template<typename LAMBDA2, typename RET2, typename... ARGS2> friend RET2(*to_fptr(std::function<RET2(ARGS2...)>, LAMBDA2))(ARGS2...); }; template<typename LAMBDA, typename RET, typename... ARGS> thread_local std::function<RET(ARGS...)> to_fptr_t<LAMBDA, RET, ARGS...>::tl_function = nullptr; template<typename LAMBDA, typename RET, typename... ARGS> RET(*to_fptr(std::function<RET(ARGS...)> func, LAMBDA lambda))(ARGS... args) { using T = to_fptr_t<LAMBDA, RET, ARGS...>; T::set_func(std::move(func)); //T::tl_function = std::move(func); return &T::fptr_handler; } } #endif // TO_FPTR_HPP_INCLUDED <|endoftext|>
<commit_before>#include "blas.hpp" #include "linalg.hpp" #include "mkl.h" #include "strassen.hpp" #include "timing.hpp" #include <stdexcept> #include <vector> Geqrf(int m, int n, float *A, int lda, float *tau) { // First perform the workspace query. float *work = new float[1]; int lwork = -1; int info; sgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad sgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new float[lwork]; sgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad sgeqrf_ call"); } } Geqrf(int m, int n, double *A, int lda, double *tau) { // First perform the workspace query. double *work = new double[1]; int lwork = -1; int info; dgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad dgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new double[lwork]; dgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad dgeqrf_ call"); } } template <typename Scalar> void QR (Matrix<Scalar>& A, std::vector<Scalar>& tau, int pos) { int m = A.m(); int n = A.n(); int lda = A.stride(); Scalar *A_data = A.data(); Scalar *curr_tau = &tau[pos]; Geqrf(m, n, A_data, lda, curr_tau); } template<typename Scalar> void FastQR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int blocksize) { if (A.m() < A.n()) { throw std::logic_error("Only supporting m >= n"); } tau.resize(A.n()); for (int i = 0; i < A.m() && A.m() - i > blocksize; i += blocksize) { // Split A as // A = (A1 A2) // and compute QR on A1 Matrix<Scalar> A1 = A.Submatrix(i, i, A.m() - i, blocksize); QR(A1, tau, i); // Compute LU on the panel. Matrix<Scalar> Panel = A.Submatrix(i, i, A.m() - i, blocksize); LU(Panel, pivots, i); Pivot(A, pivots, i, blocksize); // Solve for L11U12 = A12 Matrix<Scalar> L11 = Panel.Submatrix(0, 0, blocksize, blocksize); Matrix<Scalar> A12 = A.Submatrix(i, i + blocksize, blocksize, A.n() - i - blocksize); TriangSolve(L11, A12); // Update with schur complement using fast algorithm. Matrix<Scalar> L21 = Panel.Submatrix(i, 0, A.m() - i - blocksize, blocksize); Matrix<Scalar> A22 = A.Submatrix(i, i, A.m() - i, A.n() - i); int num_steps = 1; strassen::FastMatmul(L21, A12, A22, num_steps, 0, 1.0, 1.0); } // Now deal with the leftovers int start_ind = (A.m() / blocksize) * blocksize; int num_left = A.m() - start_ind; assert(num_left >= A.m()); if (num_left == 0) { return; } Matrix<Scalar> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind); LU(A_end, pivots, start_ind); Pivot(A, pivots, start_ind, num_left); } int main(int argc, char **argv) { int n = 10000; Matrix<double> A = RandomMatrix<double>(n, n); Matrix<double> B = A; std::vector<double> tau(A.n()); Time([&] { QR(A, pivots, 0); }, "Classical QR"); Time([&] { FastQR(B, 2400); }, "Fast QR"); return 0; } <commit_msg>More work on fast QR<commit_after>#include "blas.hpp" #include "linalg.hpp" #include "mkl.h" #include "strassen.hpp" #include "timing.hpp" #include <stdexcept> #include <vector> Geqrf(int m, int n, float *A, int lda, float *tau) { // First perform the workspace query. float *work = new float[1]; int lwork = -1; int info; sgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad sgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new float[lwork]; // QR routine that does the work. sgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad sgeqrf_ call"); } delete [] work; } Geqrf(int m, int n, double *A, int lda, double *tau) { // First perform the workspace query. double *work = new double[1]; int lwork = -1; int info; dgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad dgeqrf_ call"); } // Now allocate the work array. lwork = static_cast<int>(work[0]); delete [] work; work = new double[lwork]; // QR routine that does the work. dgeqrf_(&m, &n, A, &lda, tau, work, lwork, &info); if (info != 0) { throw std::exception("Bad dgeqrf_ call"); } delete [] work; } template <typename Scalar> void QR (Matrix<Scalar>& A, std::vector<Scalar>& tau, int pos) { int m = A.m(); int n = A.n(); int lda = A.stride(); Scalar *A_data = A.data(); Scalar *curr_tau = &tau[pos]; Geqrf(m, n, A_data, lda, curr_tau); } void Larft(char direct, char storev, int m, int n, double *V, int ldv, double *tau, double *T, int ldt) { dlarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } void Larft(char direct, char storev, int m, int n, float *V, int ldv, float *tau, float *T, int ldt) { slarft_(&direct, &storev, &m, &n, V, &ldv, tau, T, &ldt); } template <typename Scalar> Matrix<Scalar> TriangFactor(Matrix<Scalar>& A, std::vector<Scalar>& tau, int pos) { char direct = 'F'; // Forward direction of householder reflectors. char storev = 'C'; // Columns of V are stored columnwise. Scalar *A_data = A.data(); int M = A.m(); int N = A.n(); int lda = A.stride(); Scalar *tau = &tau[pos]; // Triangular matrix for storing data. int ldt = N; Matrix<Scalar> T(ldt, N); Scalar *T_data = T.data(); Larft(direct, storev, M, N, A_data, lda, tau, T_data, ldt); return T; } template<typename Scalar> void FastQR(Matrix<Scalar>& A, std::vector<Scalar>& tau, int blocksize) { if (A.m() < A.n()) { throw std::logic_error("Only supporting m >= n"); } tau.resize(A.n()); for (int i = 0; i < A.m() && A.m() - i > blocksize; i += blocksize) { // Split A as // A = (A1 A2) // and compute QR on A1 Matrix<Scalar> A1 = A.Submatrix(i, i, A.m() - i, blocksize); Matrix<Scalar> A2 = A.Submatrix(i, i + blocksize, A.m() - i, A.n() - i - blocksize); QR(A1, tau, i); // Form the triangular factor of the reflectors Matrix<Scalar> T = TriangFactor(A1, tau, pos); } // Now deal with the leftovers int start_ind = (A.m() / blocksize) * blocksize; int num_left = A.m() - start_ind; assert(num_left >= A.m()); if (num_left == 0) { return; } Matrix<Scalar> A_end = A.Submatrix(start_ind, start_ind, num_left, A.n() - start_ind); LU(A_end, pivots, start_ind); Pivot(A, pivots, start_ind, num_left); } int main(int argc, char **argv) { int n = 10000; Matrix<double> A = RandomMatrix<double>(n, n); Matrix<double> B = A; std::vector<double> tau(A.n()); Time([&] { QR(A, pivots, 0); }, "Classical QR"); Time([&] { FastQR(B, 2400); }, "Fast QR"); return 0; } <|endoftext|>
<commit_before>/* examples / skeletal_animation.cc * ================================ * * In this example we'll animate Imrod, .... amazing model. * * Let's begin by including GDT: */ #include "gdt.h" /* Specifying our app * ------------------ * * We'll use SDL as the platform backend with OpenGL as the graphics backend: */ #include "backends/sdl/sdl.hh" #include "backends/opengl/opengl.hh" using my_app = gdt::application<gdt::platform::sdl::backend_for_opengl, gdt::graphics::opengl::backend, gdt::no_audio, gdt::no_physics, gdt::no_networking, gdt::context>; /* Our rendering pipeline is going to be a forward rendering pipeline with * skeletal animation support: */ using rigged_pipeline = gdt::rigged_pipeline<my_app::graphics>; /* The imrod asset class * ----------------------- * * Our main asset in this example is Imrod, so we'll * create an asset class, subclassing from both gdt::drawable * and gdt::animatable types. This will provide us with * the ability to have a skeleton animatable and drawable model. */ class imrod : public my_app::asset<imrod>, public my_app::drawable<imrod>, public my_app::animatable<imrod> { /* Member variables * ~~~~~~~~~~~~~~~~ * * There are just a few more things we need in our asset class, such * as our material assets and an animation object to hold our single * animation for Imrod. */ private: my_app::texture _diffuse_map, _normal_map, _specular_map; rigged_pipeline::material _material; gdt::animation _anim; public: /* Constructing imrod * ~~~~~~~~~~~~~~~~~~ * * Our constructor has some work to do before we can use the imrod * class: * * Construct drawable_asset with our imrod model file, * * Construct animatable_asset with a skeleton read from the imrod model file, * * Construct our texture maps, * * Construct our material; and * * Construct the animation object with our animation sequence for this example. */ imrod(const my_app::context& ctx) : my_app::drawable<imrod>(ctx, "res/examples/imrod.smd"), my_app::animatable<imrod>(gdt::read_skeleton("res/examples/imrod.smd")), _diffuse_map(ctx, "res/examples/imrod.png"), _normal_map(ctx, "res/examples/imrod_nm.png"), _specular_map(ctx, "res/examples/imrod_s.png"), _material(ctx, &_diffuse_map, &_normal_map, &_specular_map), _anim("res/examples/imrod.ani", get_skeleton()) { play(&_anim,0); } const rigged_pipeline::material& get_material() const { return _material; } }; /* The imrod_scene class * ----------------------- * * Our imrod scene is going to set up everything needed to render our asset * using a camera we can control with the mouse and keyboard. * * Let's take a look at the private members first: */ class imrod_scene : public my_app::scene { private: /* Member variables * ~~~~~~~~~~~~~~~~ * * First, we set up our `_imrod` asset as a driven (gdt::driven) instance * (gdt::instance) of our imrod class. We use gdt::direct_driver * to allow code-based control over the asset location, scale and rotation. */ gdt::driven<gdt::instance<imrod>, gdt::direct_driver> _imrod; /* We also set up our `_camera`, again as a driven instance, but this time * using gdt::hover_driver to allow the camera to move freely in 3D using * standard camera controls (pan, track, dolly, etc..) */ gdt::driven<gdt::instance<gdt::camera>, gdt::hover_driver> _camera; /* Instead of controlling the camera through code, we'll allow the user * to control it using gdt::wsad_controller */ gdt::wsad_controller _wsad; /* For rendering, we'll use a forward rendering pipeline with skeletal * animation support. */ rigged_pipeline _pipeline; float _ambient_light = 0.3; gdt::math::vec3 _light_direction = {-0.7, 0.5, 0.9}; public: /* Note how the constructor initializes both `_imrod` and `_camera` * using their drivers initializator - a function object designed to * generate initializers for the drivers. */ imrod_scene(const my_app::context& ctx, gdt::screen* screen) : _imrod(ctx, gdt::pos::origin), _camera(ctx, gdt::pov_driver::look_at({-60, 90, -60}, {0, 0, 0}), screen), _pipeline(ctx) { /* Our model is rotated 90 degrees on the X axis, so we fix this: */ _imrod.get_driver_ptr()->rotate({gdt::math::PI / 2, 0, 0}); } /* Updating * ~~~~~~~~ * * Update is called on every frame and this is where you * would usually begin running your own scene logic, * as well as call other update methods for assets, controllers or other * GDT objects you manage in the scene. * * In our case, we'll update our gdt::wsad_controller, our imrod asset * object, check if Q was pressed to exit and finally, call render to draw * a frame. */ void update(const my_app::context& ctx) override { _wsad.update(ctx, _camera.get_driver_ptr()); _imrod.get_animatable_ptr()->update(ctx); if (ctx.get_platform()->is_key_pressed(gdt::key::Q)) { ctx.quit(); } render(ctx); } /* Rendering * ~~~~~~~~~ * * To render Imrod, we'll create a render pass targeting the screen * and clear it. We'll then use the forward rendering pipeline, * set the material to use, the camera and some lighting information * we can control with our ImGui UI. * Finally, we'll draw our imrod asset. */ void render(const my_app::context& ctx) override { my_app::render_pass(ctx) .target(my_app::graphics::screen_buffer) .clear(); _pipeline.use(ctx) .set_material(_imrod.get_drawable().get_material()) .set_camera(_camera) .set_ambient_additive(_ambient_light) .set_light_direction(_light_direction) .draw(_imrod); } /* ImGui * ~~~~~ * * Overriding the imgui method allows you to use ImGui as a development * and debugging tool. */ void imgui(const my_app::context& ctx) override { _camera.entity_ptr()->imgui(); ImGui::InputFloat4("x",&_camera.get_transformable_ptr()->get_transform_ptr(0)->xx); ImGui::InputFloat4("y",&_camera.get_transformable_ptr()->get_transform_ptr(0)->yx); ImGui::InputFloat4("z",&_camera.get_transformable_ptr()->get_transform_ptr(0)->zx); ImGui::InputFloat4("w",&_camera.get_transformable_ptr()->get_transform_ptr(0)->wx); if (ImGui::CollapsingHeader("shader")) { ImGui::SliderFloat("Ambient", &_ambient_light, 0.0f, 1.0f); ImGui::SliderFloat3("Light Direction", &_light_direction.x, -1.0f, 1.0f); } ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } }; /* Running the app * --------------- * * Nothing too special here. Just create the app object * and use the template method `run` to start our one and only * scene. */ int main() { try { my_app().run<imrod_scene>(); } catch (const std::exception & e) { LOG_ERROR << e.what(); } } <commit_msg>Removing unneeded ImGui controls.<commit_after>/* examples / skeletal_animation.cc * ================================ * * In this example we'll animate Imrod, .... amazing model. * * Let's begin by including GDT: */ #include "gdt.h" /* Specifying our app * ------------------ * * We'll use SDL as the platform backend with OpenGL as the graphics backend: */ #include "backends/sdl/sdl.hh" #include "backends/opengl/opengl.hh" using my_app = gdt::application<gdt::platform::sdl::backend_for_opengl, gdt::graphics::opengl::backend, gdt::no_audio, gdt::no_physics, gdt::no_networking, gdt::context>; /* Our rendering pipeline is going to be a forward rendering pipeline with * skeletal animation support: */ using rigged_pipeline = gdt::rigged_pipeline<my_app::graphics>; /* The imrod asset class * ----------------------- * * Our main asset in this example is Imrod, so we'll * create an asset class, subclassing from both gdt::drawable * and gdt::animatable types. This will provide us with * the ability to have a skeleton animatable and drawable model. */ class imrod : public my_app::asset<imrod>, public my_app::drawable<imrod>, public my_app::animatable<imrod> { /* Member variables * ~~~~~~~~~~~~~~~~ * * There are just a few more things we need in our asset class, such * as our material assets and an animation object to hold our single * animation for Imrod. */ private: my_app::texture _diffuse_map, _normal_map, _specular_map; rigged_pipeline::material _material; gdt::animation _anim; public: /* Constructing imrod * ~~~~~~~~~~~~~~~~~~ * * Our constructor has some work to do before we can use the imrod * class: * * Construct drawable_asset with our imrod model file, * * Construct animatable_asset with a skeleton read from the imrod model file, * * Construct our texture maps, * * Construct our material; and * * Construct the animation object with our animation sequence for this example. */ imrod(const my_app::context& ctx) : my_app::drawable<imrod>(ctx, "res/examples/imrod.smd"), my_app::animatable<imrod>(gdt::read_skeleton("res/examples/imrod.smd")), _diffuse_map(ctx, "res/examples/imrod.png"), _normal_map(ctx, "res/examples/imrod_nm.png"), _specular_map(ctx, "res/examples/imrod_s.png"), _material(ctx, &_diffuse_map, &_normal_map, &_specular_map), _anim("res/examples/imrod.ani", get_skeleton()) { play(&_anim,0); } const rigged_pipeline::material& get_material() const { return _material; } }; /* The imrod_scene class * ----------------------- * * Our imrod scene is going to set up everything needed to render our asset * using a camera we can control with the mouse and keyboard. * * Let's take a look at the private members first: */ class imrod_scene : public my_app::scene { private: /* Member variables * ~~~~~~~~~~~~~~~~ * * First, we set up our `_imrod` asset as a driven (gdt::driven) instance * (gdt::instance) of our imrod class. We use gdt::direct_driver * to allow code-based control over the asset location, scale and rotation. */ gdt::driven<gdt::instance<imrod>, gdt::direct_driver> _imrod; /* We also set up our `_camera`, again as a driven instance, but this time * using gdt::hover_driver to allow the camera to move freely in 3D using * standard camera controls (pan, track, dolly, etc..) */ gdt::driven<gdt::instance<gdt::camera>, gdt::hover_driver> _camera; /* Instead of controlling the camera through code, we'll allow the user * to control it using gdt::wsad_controller */ gdt::wsad_controller _wsad; /* For rendering, we'll use a forward rendering pipeline with skeletal * animation support. */ rigged_pipeline _pipeline; float _ambient_light = 0.3; gdt::math::vec3 _light_direction = {-0.7, 0.5, 0.9}; public: /* Note how the constructor initializes both `_imrod` and `_camera` * using their drivers initializator - a function object designed to * generate initializers for the drivers. */ imrod_scene(const my_app::context& ctx, gdt::screen* screen) : _imrod(ctx, gdt::pos::origin), _camera(ctx, gdt::pov_driver::look_at({-60, 90, -60}, {0, 0, 0}), screen), _pipeline(ctx) { /* Our model is rotated 90 degrees on the X axis, so we fix this: */ _imrod.get_driver_ptr()->rotate({gdt::math::PI / 2, 0, 0}); } /* Updating * ~~~~~~~~ * * Update is called on every frame and this is where you * would usually begin running your own scene logic, * as well as call other update methods for assets, controllers or other * GDT objects you manage in the scene. * * In our case, we'll update our gdt::wsad_controller, our imrod asset * object, check if Q was pressed to exit and finally, call render to draw * a frame. */ void update(const my_app::context& ctx) override { _wsad.update(ctx, _camera.get_driver_ptr()); _imrod.get_animatable_ptr()->update(ctx); if (ctx.get_platform()->is_key_pressed(gdt::key::Q)) { ctx.quit(); } render(ctx); } /* Rendering * ~~~~~~~~~ * * To render Imrod, we'll create a render pass targeting the screen * and clear it. We'll then use the forward rendering pipeline, * set the material to use, the camera and some lighting information * we can control with our ImGui UI. * Finally, we'll draw our imrod asset. */ void render(const my_app::context& ctx) override { my_app::render_pass(ctx) .target(my_app::graphics::screen_buffer) .clear(); _pipeline.use(ctx) .set_material(_imrod.get_drawable().get_material()) .set_camera(_camera) .set_ambient_additive(_ambient_light) .set_light_direction(_light_direction) .draw(_imrod); } /* ImGui * ~~~~~ * * Overriding the imgui method allows you to use ImGui as a development * and debugging tool. */ void imgui(const my_app::context& ctx) override { _camera.entity_ptr()->imgui(); if (ImGui::CollapsingHeader("shader")) { ImGui::SliderFloat("Ambient", &_ambient_light, 0.0f, 1.0f); ImGui::SliderFloat3("Light Direction", &_light_direction.x, -1.0f, 1.0f); } ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate); } }; /* Running the app * --------------- * * Nothing too special here. Just create the app object * and use the template method `run` to start our one and only * scene. */ int main() { try { my_app().run<imrod_scene>(); } catch (const std::exception & e) { LOG_ERROR << e.what(); } } <|endoftext|>
<commit_before>#ifndef VIRTUALFUNCTIONS_H_ #define VIRTUALFUNCTIONS_H_ #include <iostream> #include <ostream> #include <memory> using namespace std; class Shape { public: Shape() {} virtual ~Shape ( ) {} virtual void draw(int x, int y) { cout << "Shape::draw(): " << x << ", " << y << endl; } private: Shape (const Shape&); Shape& operator=(const Shape&); }; class Polygon : public Shape { public: virtual void draw ( int x, int y ) override { cout << "Polygon::draw(): " << x << ", " << y << endl; } }; class Evilgon : public Shape { public: // Here we define new function draw (shadowing draw() from Shape), because // of different types of function arguments virtual void draw ( double x, double y ) { cout << "Evilgon::draw(): " << x << ", " << y << endl; } }; // If we put "final" here, we would declare that class Triangle is final // derived class and we can't create another class (like BermudaTriangle), // which will inherit Triangle. class Triangle /*final*/ : public Polygon { public: // If we put "final" here (with or without override), we declare that // this overriding of function is final and we can't override it again in // child class of Triangle (BermudaTriangle in this example) virtual void draw ( int x, int y ) /*final*/ override { cout << "Triangle::draw(): " << x << ", " << y << endl; } }; class BermudaTriangle : public Triangle { public: virtual void draw ( int x, int y ) override { cout << "BermudaTriangle::draw(): " << x << ", " << y << endl; } }; class Base { public: Base ( ) { } virtual ~Base ( ) { } // Interface function void draw ( int x, int y ) { cout << "Start of interface method Base::draw()" << endl; // Function (or functions) that do real work do_draw ( x, y ); cout << "Exit Base::draw()" << endl; } private: // abstract virtual function for real functionality of method draw virtual void do_draw ( int x, int y ) = 0; Base ( const Base& ); Base& operator=( const Base& ); }; class Derived : public Base { public: virtual void do_draw (int, int) { cout << "In Derived::do_draw() doing real work" << endl; } }; void StartVF() { shared_ptr<Shape> shape = make_shared<Polygon>(); shape->draw(11, 12); shape = make_shared<Evilgon>(); // Error - calling method Shape::draw(), but not Evilgon::draw(); // To block this error write virtual methods in derived classes like this: // virtual void func(...) override {...} // Special word override signals to compiler to carefully check this // function shape->draw (33, 44); shared_ptr<Base> base = make_shared<Derived> ( ); base->draw ( 12, 13 ); } #endif /* VIRTUALFUNCTIONS_H_ */ <commit_msg>Add code example for pure virtual destructor<commit_after>#ifndef VIRTUALFUNCTIONS_H_ #define VIRTUALFUNCTIONS_H_ #include <iostream> #include <ostream> #include <memory> using namespace std; class Shape { public: Shape() {} virtual ~Shape ( ) {} virtual void draw(int x, int y) { cout << "Shape::draw(): " << x << ", " << y << endl; } private: Shape (const Shape&); Shape& operator=(const Shape&); }; class Polygon : public Shape { public: virtual void draw ( int x, int y ) override { cout << "Polygon::draw(): " << x << ", " << y << endl; } }; class Evilgon : public Shape { public: // Here we define new function draw (shadowing draw() from Shape), because // of different types of function arguments virtual void draw ( double x, double y ) { cout << "Evilgon::draw(): " << x << ", " << y << endl; } }; // If we put "final" here, we would declare that class Triangle is final // derived class and we can't create another class (like BermudaTriangle), // which will inherit Triangle. class Triangle /*final*/ : public Polygon { public: // If we put "final" here (with or without override), we declare that // this overriding of function is final and we can't override it again in // child class of Triangle (BermudaTriangle in this example) virtual void draw ( int x, int y ) /*final*/ override { cout << "Triangle::draw(): " << x << ", " << y << endl; } }; class BermudaTriangle : public Triangle { public: virtual void draw ( int x, int y ) override { cout << "BermudaTriangle::draw(): " << x << ", " << y << endl; } }; class Base { public: virtual ~Base ( ) { } // Interface function void draw(int x, int y) { cout << "Start of interface method Base::draw()" << endl; // Function (or functions) that do real work do_draw ( x, y ); cout << "Exit Base::draw()" << endl; } private: // virtual function for real functionality of method draw virtual void do_draw (int x, int y) = 0; }; class Derived : public Base { public: virtual ~Derived() override {} private: virtual void do_draw (int, int) override { cout << "In Derived::do_draw() doing real work" << endl; } }; // How to make pure virtual destructor int base class class Object { public: virtual ~Object() = 0; }; // Anyway we must provide implementation for ~Object. We could make it only // outside of class body. Object::~Object() { cout << "Inside pure virtual destructor of Object" << endl; } class RealObject : public Object { public: virtual ~RealObject() override { cout << "Inside virtual destructor of RealObject" << endl; } }; void StartVF() { shared_ptr<Shape> shape = make_shared<Polygon>(); shape->draw(11, 12); shape = make_shared<Evilgon>(); // Error - calling method Shape::draw(), but not Evilgon::draw(); // To block this error write virtual methods in derived classes like this: // virtual void func(...) override {...} // Special word override signals to compiler to carefully check this // function shape->draw (33, 44); Derived d; d.draw(4, 3); shared_ptr<Object> object = make_shared<RealObject> ( ); } #endif /* VIRTUALFUNCTIONS_H_ */ <|endoftext|>
<commit_before>/* Nazara Engine Copyright (C) 2015 Jérôme "Lynix" Leclercq ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NAZARA_PREREQUESITES_HPP #define NAZARA_PREREQUESITES_HPP // Identification du compilateur ///TODO: Rajouter des tests d'identification de compilateurs #if defined(__BORLANDC__) #define NAZARA_COMPILER_BORDLAND #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __FUNC__ #elif defined(__clang__) #define NAZARA_COMPILER_CLANG #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) #define NAZARA_FUNCTION __PRETTY_FUNCTION__ #elif defined(__GNUC__) || defined(__MINGW32__) #define NAZARA_COMPILER_GCC #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) #define NAZARA_FUNCTION __PRETTY_FUNCTION__ #ifdef __MINGW32__ #define NAZARA_COMPILER_MINGW #ifdef __MINGW64_VERSION_MAJOR #define NAZARA_COMPILER_MINGW_W64 #endif #endif #elif defined(__INTEL_COMPILER) || defined(__ICL) #define NAZARA_COMPILER_INTEL #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __FUNCTION__ #elif defined(_MSC_VER) #define NAZARA_COMPILER_MSVC #define NAZARA_COMPILER_SUPPORTS_CPP11 (_MSC_VER >= 1900) #define NAZARA_DEPRECATED(txt) __declspec(deprecated(txt)) #define NAZARA_FUNCTION __FUNCSIG__ #pragma warning(disable: 4251) #else #define NAZARA_COMPILER_UNKNOWN #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __func__ // __func__ est standard depuis le C++11 /// Cette ligne n'est là que pour prévenir, n'hésitez pas à la commenter si elle vous empêche de compiler #pragma message This compiler is not fully supported #endif #if !NAZARA_COMPILER_SUPPORTS_CPP11 #error Nazara requires a C++11 compliant compiler #endif // Nazara version macro #define NAZARA_VERSION_MAJOR 0 #define NAZARA_VERSION_MINOR 2 #define NAZARA_VERSION_PATCH 0 #include <Nazara/Core/Config.hpp> // Identification de la plateforme #if defined(_WIN32) #define NAZARA_PLATFORM_WINDOWS #define NAZARA_EXPORT __declspec(dllexport) #define NAZARA_IMPORT __declspec(dllimport) // Des defines pour le header Windows #if defined(NAZARA_BUILD) // Pour ne pas entrer en conflit avec les defines de l'application ou d'une autre bibliothèque #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #if NAZARA_CORE_WINDOWS_NT6 // Version de Windows minimale : Vista #define NAZARA_WINNT 0x0600 #else #define NAZARA_WINNT 0x0501 #endif // Pour ne pas casser le define déjà en place s'il est applicable #if defined(_WIN32_WINNT) #if _WIN32_WINNT < NAZARA_WINNT #undef _WIN32_WINNT #define _WIN32_WINNT NAZARA_WINNT #endif #else #define _WIN32_WINNT NAZARA_WINNT #endif #endif #elif defined(__linux__) || defined(__unix__) #define NAZARA_PLATFORM_LINUX #define NAZARA_PLATFORM_GLX #define NAZARA_PLATFORM_POSIX #define NAZARA_PLATFORM_X11 #define NAZARA_EXPORT __attribute__((visibility ("default"))) #define NAZARA_IMPORT __attribute__((visibility ("default"))) /*#elif defined(__APPLE__) && defined(__MACH__) #define NAZARA_CORE_API #define NAZARA_PLATFORM_MACOSX #define NAZARA_PLATFORM_POSIX*/ #else // À commenter pour tenter quand même une compilation #error This operating system is not fully supported by the Nazara Engine #define NAZARA_PLATFORM_UNKNOWN #define NAZARA_CORE_API #endif // Détection 64 bits #if !defined(NAZARA_PLATFORM_x64) && (defined(_WIN64) || defined(__amd64__) || defined(__x86_64__) || defined(__ia64__) || defined(__ia64) || \ defined(_M_IA64) || defined(__itanium__) || defined(__MINGW64__) || defined(_M_AMD64) || defined (_M_X64)) #define NAZARA_PLATFORM_x64 #endif // Définit NDEBUG si NAZARA_DEBUG n'est pas présent #if !defined(NAZARA_DEBUG) && !defined(NDEBUG) #define NDEBUG #endif // Macros supplémentaires #define NazaraPrefix(a, prefix) prefix ## a #define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) #define NazaraSuffix(a, suffix) a ## suffix #define NazaraSuffixMacro(a, suffix) NazaraSuffix(a, suffix) #define NazaraStringify(s) #s #define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define NazaraUnused(a) (void) a #include <climits> #include <cstdint> static_assert(CHAR_BIT == 8, "CHAR_BIT is expected to be 8"); static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" ); static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size"); static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size"); static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size"); static_assert(sizeof(uint8_t) == 1, "uint8_t is not of the correct size" ); static_assert(sizeof(uint16_t) == 2, "uint16_t is not of the correct size"); static_assert(sizeof(uint32_t) == 4, "uint32_t is not of the correct size"); static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size"); namespace Nz { typedef int8_t Int8; typedef uint8_t UInt8; typedef int16_t Int16; typedef uint16_t UInt16; typedef int32_t Int32; typedef uint32_t UInt32; typedef int64_t Int64; typedef uint64_t UInt64; } #endif // NAZARA_PREREQUESITES_HPP <commit_msg>Core/Prerequesites: Remove NDEBUG automatic definition (not used)<commit_after>/* Nazara Engine Copyright (C) 2015 Jérôme "Lynix" Leclercq ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NAZARA_PREREQUESITES_HPP #define NAZARA_PREREQUESITES_HPP // Try to identify the compiler #if defined(__BORLANDC__) #define NAZARA_COMPILER_BORDLAND #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __FUNC__ #elif defined(__clang__) #define NAZARA_COMPILER_CLANG #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) #define NAZARA_FUNCTION __PRETTY_FUNCTION__ #elif defined(__GNUC__) || defined(__MINGW32__) #define NAZARA_COMPILER_GCC #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) __attribute__((__deprecated__(txt))) #define NAZARA_FUNCTION __PRETTY_FUNCTION__ #ifdef __MINGW32__ #define NAZARA_COMPILER_MINGW #ifdef __MINGW64_VERSION_MAJOR #define NAZARA_COMPILER_MINGW_W64 #endif #endif #elif defined(__INTEL_COMPILER) || defined(__ICL) #define NAZARA_COMPILER_INTEL #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __FUNCTION__ #elif defined(_MSC_VER) #define NAZARA_COMPILER_MSVC #define NAZARA_COMPILER_SUPPORTS_CPP11 (_MSC_VER >= 1900) #define NAZARA_DEPRECATED(txt) __declspec(deprecated(txt)) #define NAZARA_FUNCTION __FUNCSIG__ #pragma warning(disable: 4251) #else #define NAZARA_COMPILER_UNKNOWN #define NAZARA_COMPILER_SUPPORTS_CPP11 (defined(__cplusplus) && __cplusplus >= 201103L) #define NAZARA_DEPRECATED(txt) #define NAZARA_FUNCTION __func__ // __func__ has been standardized in C++ 2011 #pragma message This compiler is not fully supported #endif #if !NAZARA_COMPILER_SUPPORTS_CPP11 #error Nazara requires a C++11 compliant compiler #endif // Nazara version macro #define NAZARA_VERSION_MAJOR 0 #define NAZARA_VERSION_MINOR 2 #define NAZARA_VERSION_PATCH 0 #include <Nazara/Core/Config.hpp> // Try to identify target platform via defines #if defined(_WIN32) #define NAZARA_PLATFORM_WINDOWS #define NAZARA_EXPORT __declspec(dllexport) #define NAZARA_IMPORT __declspec(dllimport) // Somes defines for windows.h include.. #if defined(NAZARA_BUILD) #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #ifndef NOMINMAX #define NOMINMAX #endif #if NAZARA_CORE_WINDOWS_NT6 #define NAZARA_WINNT 0x0600 #else #define NAZARA_WINNT 0x0501 #endif // Keep the actual define if existing and greater than our requirement #if defined(_WIN32_WINNT) #if _WIN32_WINNT < NAZARA_WINNT #undef _WIN32_WINNT #define _WIN32_WINNT NAZARA_WINNT #endif #else #define _WIN32_WINNT NAZARA_WINNT #endif #endif #elif defined(__linux__) || defined(__unix__) #define NAZARA_PLATFORM_LINUX #define NAZARA_PLATFORM_GLX #define NAZARA_PLATFORM_POSIX #define NAZARA_PLATFORM_X11 #define NAZARA_EXPORT __attribute__((visibility ("default"))) #define NAZARA_IMPORT __attribute__((visibility ("default"))) /*#elif defined(__APPLE__) && defined(__MACH__) #define NAZARA_CORE_API #define NAZARA_PLATFORM_MACOSX #define NAZARA_PLATFORM_POSIX*/ #else #error This operating system is not fully supported by the Nazara Engine #define NAZARA_PLATFORM_UNKNOWN #define NAZARA_CORE_API #endif // Détection 64 bits #if !defined(NAZARA_PLATFORM_x64) && (defined(_WIN64) || defined(__amd64__) || defined(__x86_64__) || defined(__ia64__) || defined(__ia64) || \ defined(_M_IA64) || defined(__itanium__) || defined(__MINGW64__) || defined(_M_AMD64) || defined (_M_X64)) #define NAZARA_PLATFORM_x64 #endif // A bunch of useful macros #define NazaraPrefix(a, prefix) prefix ## a #define NazaraPrefixMacro(a, prefix) NazaraPrefix(a, prefix) #define NazaraSuffix(a, suffix) a ## suffix #define NazaraSuffixMacro(a, suffix) NazaraSuffix(a, suffix) #define NazaraStringify(s) #s #define NazaraStringifyMacro(s) NazaraStringify(s) // http://gcc.gnu.org/onlinedocs/cpp/Stringification.html#Stringification #define NazaraUnused(a) (void) a #include <climits> #include <cstdint> static_assert(CHAR_BIT == 8, "CHAR_BIT is expected to be 8"); static_assert(sizeof(int8_t) == 1, "int8_t is not of the correct size" ); static_assert(sizeof(int16_t) == 2, "int16_t is not of the correct size"); static_assert(sizeof(int32_t) == 4, "int32_t is not of the correct size"); static_assert(sizeof(int64_t) == 8, "int64_t is not of the correct size"); static_assert(sizeof(uint8_t) == 1, "uint8_t is not of the correct size" ); static_assert(sizeof(uint16_t) == 2, "uint16_t is not of the correct size"); static_assert(sizeof(uint32_t) == 4, "uint32_t is not of the correct size"); static_assert(sizeof(uint64_t) == 8, "uint64_t is not of the correct size"); namespace Nz { typedef int8_t Int8; typedef uint8_t UInt8; typedef int16_t Int16; typedef uint16_t UInt16; typedef int32_t Int32; typedef uint32_t UInt32; typedef int64_t Int64; typedef uint64_t UInt64; } #endif // NAZARA_PREREQUESITES_HPP <|endoftext|>
<commit_before>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2014--2015 */ /* Alternate POST / setup and loop / main for non-OpenTRV code running on OpenTRV h/w platform. Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc! */ // Arduino libraries. //#include <Wire.h> #include "V0p2_Main.h" #include "V0p2_Generic_Config.h" #include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers. #include "Control.h" #include "EEPROM_Utils.h" #include "FHT8V_Wireless_Rad_Valve.h" #include "RTC_Support.h" #include "Power_Management.h" #include "PRNG.h" #include "RFM22_Radio.h" #include "Security.h" #include "Serial_IO.h" #include "UI_Minimal.h" // Link in support for alternate Power On Self-Test and main loop if required. #if defined(ALT_MAIN_LOOP) // Called from startup() after some initial setup has been done. // Can abort with panic() if need be. void POSTalt() { #if defined(USE_MODULE_RFM22RADIOSIMPLE) // // Initialise the radio, if configured, ASAP, because it can suck a lot of power until properly initialised. // RFM22PowerOnInit(); // // Check that the radio is correctly connected; panic if not... // if(!RFM22CheckConnected()) { panic(); } // // Configure the radio. // RFM22RegisterBlockSetup(FHT8V_RFM22_Reg_Values); // // Put the radio in low-power standby mode. // RFM22ModeStandbyAndClearState(); // Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised. static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true); RFM23B.preinit(NULL); // Check that the radio is correctly connected; panic if not... if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); } #endif // Force initialisation into low-power state. const int heat = TemperatureC16.read(); #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("temp: "); DEBUG_SERIAL_PRINT(heat); DEBUG_SERIAL_PRINTLN(); #endif // const int light = AmbLight.read(); //#if 0 && defined(DEBUG) // DEBUG_SERIAL_PRINT_FLASHSTRING("light: "); // DEBUG_SERIAL_PRINT(light); // DEBUG_SERIAL_PRINTLN(); //#endif // Trailing setup for the run // -------------------------- RFM23B.listen(true); } // Position to move the valve to [0,100]. static uint8_t valvePosition = 42; // <<<<<<<< YOUR STUFF SETS THIS! // Called from loop(). void loopAlt() { // Sleep in low-power mode (waiting for interrupts) until seconds roll. // NOTE: sleep at the top of the loop to minimise timing jitter/delay from Arduino background activity after loop() returns. // DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms. #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("*E"); // End-of-cycle sleep. #endif #if !defined(MIN_ENERGY_BOOT) powerDownSerial(); // Ensure that serial I/O is off. // Power down most stuff (except radio for hub RX). minimisePowerWithoutSleep(); // RFM22ModeStandbyAndClearState(); #endif static uint_fast8_t TIME_LSD; // Controller's notion of seconds within major cycle. uint_fast8_t newTLSD; while(TIME_LSD == (newTLSD = getSecondsLT())) { nap(WDTO_15MS, true); // sleepUntilInt(); // Normal long minimal-power sleep until wake-up interrupt. // DEBUG_SERIAL_PRINTLN_FLASHSTRING("w"); // Wakeup. RFM23B.poll(); while(0 != RFM23B.getRXMsgsQueued()) { uint8_t buf[65]; const uint8_t msglen = RFM23B.getRXMsg(buf, sizeof(buf)); const bool neededWaking = powerUpSerialIfDisabled(); OTRadioLink::dumpRXMsg(buf, msglen); flushSerialSCTSensitive(); if(neededWaking) { powerDownSerial(); } } } TIME_LSD = newTLSD; #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("*S"); // Start-of-cycle wake. #endif // START LOOP BODY // =============== // DEBUG_SERIAL_PRINTLN_FLASHSTRING("*"); // Power up serail for the loop body. // May just want to turn it on in POSTalt() and leave it on... const bool neededWaking = powerUpSerialIfDisabled(); #if defined(USE_MODULE_FHT8VSIMPLE) // Try for double TX for more robust conversation with valve? const bool doubleTXForFTH8V = false; // FHT8V is highest priority and runs first. // ---------- HALF SECOND #0 ----------- bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); // Time for extra TX before UI. // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@0"); } #endif // EXPERIMENTAL TEST OF NEW RADIO CODE #if 1 && defined(DEBUG) // DEBUG_SERIAL_PRINT_FLASHSTRING("listening to channel: "); // DEBUG_SERIAL_PRINT(RFM23B.getListenChannel()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.listen(false); // DEBUG_SERIAL_PRINT_FLASHSTRING("MODE "); // DEBUG_SERIAL_PRINT(RFM23B.getMode()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.listen(true); // DEBUG_SERIAL_PRINT_FLASHSTRING("MODE "); // DEBUG_SERIAL_PRINT(RFM23B.getMode()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.poll(); for(uint8_t lastErr; 0 != (lastErr = RFM23B.getRXErr()); ) { DEBUG_SERIAL_PRINT_FLASHSTRING("err "); DEBUG_SERIAL_PRINT(lastErr); DEBUG_SERIAL_PRINTLN(); } DEBUG_SERIAL_PRINT_FLASHSTRING("RSSI "); DEBUG_SERIAL_PRINT(RFM23B.getRSSI()); DEBUG_SERIAL_PRINTLN(); static uint8_t oldDroppedRecent; const uint8_t droppedRecent = RFM23B.getRXMsgsDroppedRecent(); if(droppedRecent != oldDroppedRecent) { DEBUG_SERIAL_PRINT_FLASHSTRING("?DROPPED recent: "); DEBUG_SERIAL_PRINT(droppedRecent); DEBUG_SERIAL_PRINTLN(); oldDroppedRecent = droppedRecent; } #endif #if defined(USE_MODULE_FHT8VSIMPLE) if(0 == TIME_LSD) { // Once per minute regenerate valve-setting command ready to transmit. FHT8VCreateValveSetCmdFrame(valvePosition); } #endif #if defined(USE_MODULE_FHT8VSIMPLE) if(useExtraFHT8VTXSlots) { // Time for extra TX before other actions, but don't bother if minimising power in frost mode. // ---------- HALF SECOND #1 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@1"); } } #endif #if defined(USE_MODULE_FHT8VSIMPLE) && defined(TWO_S_TICK_RTC_SUPPORT) if(useExtraFHT8VTXSlots) { // ---------- HALF SECOND #2 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@2"); } } #endif #if defined(USE_MODULE_FHT8VSIMPLE) && defined(TWO_S_TICK_RTC_SUPPORT) if(useExtraFHT8VTXSlots) { // ---------- HALF SECOND #3 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@3"); } } #endif // Force any pending output before return / possible UART power-down. flushSerialSCTSensitive(); if(neededWaking) { powerDownSerial(); } } #endif <commit_msg>COH-25: WIP<commit_after>/* The OpenTRV project licenses this file to you under the Apache Licence, Version 2.0 (the "Licence"); you may not use this file except in compliance with the Licence. You may obtain a copy of the Licence at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the Licence for the specific language governing permissions and limitations under the Licence. Author(s) / Copyright (s): Damon Hart-Davis 2014--2015 */ /* Alternate POST / setup and loop / main for non-OpenTRV code running on OpenTRV h/w platform. Also for rapid prototyping without dead-weight of OpenTRV intricate timing, etc! */ // Arduino libraries. //#include <Wire.h> #include "V0p2_Main.h" #include "V0p2_Generic_Config.h" #include "V0p2_Board_IO_Config.h" // I/O pin allocation: include ahead of I/O module headers. #include "Control.h" #include "EEPROM_Utils.h" #include "FHT8V_Wireless_Rad_Valve.h" #include "RTC_Support.h" #include "Power_Management.h" #include "PRNG.h" #include "RFM22_Radio.h" #include "Security.h" #include "Serial_IO.h" #include "UI_Minimal.h" // Link in support for alternate Power On Self-Test and main loop if required. #if defined(ALT_MAIN_LOOP) // Called from startup() after some initial setup has been done. // Can abort with panic() if need be. void POSTalt() { #if defined(USE_MODULE_RFM22RADIOSIMPLE) // Initialise the radio, if configured, ASAP because it can suck a lot of power until properly initialised. static const OTRadioLink::OTRadioChannelConfig RFMConfig(FHT8V_RFM22_Reg_Values, true, true, true); RFM23B.preinit(NULL); // Check that the radio is correctly connected; panic if not... if(!RFM23B.configure(1, &RFMConfig) || !RFM23B.begin()) { panic(); } #endif // Force initialisation into low-power state. const int heat = TemperatureC16.read(); #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINT_FLASHSTRING("temp: "); DEBUG_SERIAL_PRINT(heat); DEBUG_SERIAL_PRINTLN(); #endif // const int light = AmbLight.read(); //#if 0 && defined(DEBUG) // DEBUG_SERIAL_PRINT_FLASHSTRING("light: "); // DEBUG_SERIAL_PRINT(light); // DEBUG_SERIAL_PRINTLN(); //#endif // Trailing setup for the run // -------------------------- RFM23B.listen(true); } // Position to move the valve to [0,100]. static uint8_t valvePosition = 42; // <<<<<<<< YOUR STUFF SETS THIS! // Called from loop(). void loopAlt() { // Sleep in low-power mode (waiting for interrupts) until seconds roll. // NOTE: sleep at the top of the loop to minimise timing jitter/delay from Arduino background activity after loop() returns. // DHD20130425: waking up from sleep and getting to start processing below this block may take >10ms. #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("*E"); // End-of-cycle sleep. #endif #if !defined(MIN_ENERGY_BOOT) powerDownSerial(); // Ensure that serial I/O is off. // Power down most stuff (except radio for hub RX). minimisePowerWithoutSleep(); // RFM22ModeStandbyAndClearState(); #endif static uint_fast8_t TIME_LSD; // Controller's notion of seconds within major cycle. uint_fast8_t newTLSD; while(TIME_LSD == (newTLSD = getSecondsLT())) { nap(WDTO_15MS, true); // sleepUntilInt(); // Normal long minimal-power sleep until wake-up interrupt. // DEBUG_SERIAL_PRINTLN_FLASHSTRING("w"); // Wakeup. RFM23B.poll(); while(0 != RFM23B.getRXMsgsQueued()) { uint8_t buf[65]; const uint8_t msglen = RFM23B.getRXMsg(buf, sizeof(buf)); const bool neededWaking = powerUpSerialIfDisabled(); OTRadioLink::dumpRXMsg(buf, msglen); Serial.flush(); if(neededWaking) { powerDownSerial(); } } } TIME_LSD = newTLSD; #if 0 && defined(DEBUG) DEBUG_SERIAL_PRINTLN_FLASHSTRING("*S"); // Start-of-cycle wake. #endif // START LOOP BODY // =============== // DEBUG_SERIAL_PRINTLN_FLASHSTRING("*"); // Power up serail for the loop body. // May just want to turn it on in POSTalt() and leave it on... const bool neededWaking = powerUpSerialIfDisabled(); #if defined(USE_MODULE_FHT8VSIMPLE) // Try for double TX for more robust conversation with valve? const bool doubleTXForFTH8V = false; // FHT8V is highest priority and runs first. // ---------- HALF SECOND #0 ----------- bool useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_First(doubleTXForFTH8V); // Time for extra TX before UI. // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@0"); } #endif // EXPERIMENTAL TEST OF NEW RADIO CODE #if 1 && defined(DEBUG) // DEBUG_SERIAL_PRINT_FLASHSTRING("listening to channel: "); // DEBUG_SERIAL_PRINT(RFM23B.getListenChannel()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.listen(false); // DEBUG_SERIAL_PRINT_FLASHSTRING("MODE "); // DEBUG_SERIAL_PRINT(RFM23B.getMode()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.listen(true); // DEBUG_SERIAL_PRINT_FLASHSTRING("MODE "); // DEBUG_SERIAL_PRINT(RFM23B.getMode()); // DEBUG_SERIAL_PRINTLN(); // RFM23B.poll(); for(uint8_t lastErr; 0 != (lastErr = RFM23B.getRXErr()); ) { DEBUG_SERIAL_PRINT_FLASHSTRING("err "); DEBUG_SERIAL_PRINT(lastErr); DEBUG_SERIAL_PRINTLN(); } DEBUG_SERIAL_PRINT_FLASHSTRING("RSSI "); DEBUG_SERIAL_PRINT(RFM23B.getRSSI()); DEBUG_SERIAL_PRINTLN(); static uint8_t oldDroppedRecent; const uint8_t droppedRecent = RFM23B.getRXMsgsDroppedRecent(); if(droppedRecent != oldDroppedRecent) { DEBUG_SERIAL_PRINT_FLASHSTRING("?DROPPED recent: "); DEBUG_SERIAL_PRINT(droppedRecent); DEBUG_SERIAL_PRINTLN(); oldDroppedRecent = droppedRecent; } #endif #if defined(USE_MODULE_FHT8VSIMPLE) if(0 == TIME_LSD) { // Once per minute regenerate valve-setting command ready to transmit. FHT8VCreateValveSetCmdFrame(valvePosition); } #endif #if defined(USE_MODULE_FHT8VSIMPLE) if(useExtraFHT8VTXSlots) { // Time for extra TX before other actions, but don't bother if minimising power in frost mode. // ---------- HALF SECOND #1 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@1"); } } #endif #if defined(USE_MODULE_FHT8VSIMPLE) && defined(TWO_S_TICK_RTC_SUPPORT) if(useExtraFHT8VTXSlots) { // ---------- HALF SECOND #2 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@2"); } } #endif #if defined(USE_MODULE_FHT8VSIMPLE) && defined(TWO_S_TICK_RTC_SUPPORT) if(useExtraFHT8VTXSlots) { // ---------- HALF SECOND #3 ----------- useExtraFHT8VTXSlots = localFHT8VTRVEnabled() && FHT8VPollSyncAndTX_Next(doubleTXForFTH8V); // if(useExtraFHT8VTXSlots) { DEBUG_SERIAL_PRINTLN_FLASHSTRING("ES@3"); } } #endif // Force any pending output before return / possible UART power-down. flushSerialSCTSensitive(); if(neededWaking) { powerDownSerial(); } } #endif <|endoftext|>
<commit_before>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "DeviceLister.h" #include "logging/Logger.h" #include "utils/Filename.h" #include <dirent.h> #include <mntent.h> #include <sys/types.h> #include <vector> #include <memory> #include <cerrno> #include <sstream> #include <cstdio> #include <algorithm> #include <cstring> #include <limits.h> #include <unistd.h> namespace medialibrary { namespace fs { DeviceLister::DeviceMap DeviceLister::listDevices() const { static const std::vector<std::string> bannedDevice = { "loop" }; const std::string devPath = "/dev/disk/by-uuid/"; // Don't use fs::Directory to iterate, as it resolves the symbolic links automatically. // We need the link name & what it points to. std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( devPath.c_str() ), &closedir ); if ( dir == nullptr ) { std::stringstream err; err << "Failed to open /dev/disk/by-uuid: " << strerror(errno); throw std::runtime_error( err.str() ); } DeviceMap res; dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } std::string path = devPath + result->d_name; char linkPath[PATH_MAX] = {}; if ( readlink( path.c_str(), linkPath, PATH_MAX ) < 0 ) { std::stringstream err; err << "Failed to resolve uuid -> device link: " << result->d_name << " (" << strerror(errno) << ')'; throw std::runtime_error( err.str() ); } auto deviceName = utils::file::fileName( linkPath ); if ( std::find_if( begin( bannedDevice ), end( bannedDevice ), [&deviceName]( const std::string& pattern ) { return deviceName.length() >= pattern.length() && deviceName.find( pattern ) == 0; }) != end( bannedDevice ) ) continue; auto uuid = result->d_name; LOG_INFO( "Discovered device ", deviceName, " -> {", uuid, '}' ); res[deviceName] = uuid; } return res; } DeviceLister::MountpointMap DeviceLister::listMountpoints() const { static const std::vector<std::string> allowedFsType = { "vfat", "exfat", "sdcardfs", "fuse", "ntfs", "fat32", "ext3", "ext4", "esdfs" }; MountpointMap res; errno = 0; mntent* s; char buff[512]; mntent smnt; FILE* f = setmntent("/etc/mtab", "r"); if ( f == nullptr ) throw std::runtime_error( "Failed to read /etc/mtab" ); std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &endmntent ); while ( getmntent_r( f, &smnt, buff, sizeof(buff) ) != nullptr ) { s = &smnt; if ( std::find( begin( allowedFsType ), end( allowedFsType ), s->mnt_type ) == end( allowedFsType ) ) continue; auto deviceName = s->mnt_fsname; if ( res.count( deviceName ) == 0 ) { LOG_INFO( "Discovered mountpoint ", deviceName, " mounted on ", s->mnt_dir, " (", s->mnt_type, ')' ); res[deviceName] = s->mnt_dir; } else LOG_INFO( "Ignoring duplicated mountpoint (", s->mnt_dir, ") for device ", deviceName ); errno = 0; } if ( errno != 0 ) { LOG_ERROR( "Failed to read mountpoints: ", strerror( errno ) ); } return res; } std::pair<std::string,std::string> DeviceLister::deviceFromDeviceMapper( const std::string& devicePath ) const { if ( devicePath.find( "/dev/mapper" ) != 0 ) return {}; char linkPath[PATH_MAX + 1]; auto linkSize = readlink( devicePath.c_str(), linkPath, PATH_MAX ); if ( linkSize < 0 ) { std::stringstream err; err << "Failed to resolve device -> mapper link: " << devicePath << " (" << strerror(errno) << ')'; throw std::runtime_error( err.str() ); } linkPath[linkSize] = 0; LOG_INFO( "Resolved ", devicePath, " to ", linkPath, " device mapper" ); const auto dmName = utils::file::fileName( linkPath ); std::string dmSlavePath = "/sys/block/" + dmName + "/slaves"; std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( dmSlavePath.c_str() ), &closedir ); std::string res; if ( dir == nullptr ) { std::stringstream err; err << "Failed to open device-mapper slaves directory (" << linkPath << ')'; throw std::runtime_error( err.str() ); } dirent* result; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } if ( res.empty() == true ) res = result->d_name; else LOG_WARN( "More than one slave for device mapper ", linkPath ); } LOG_INFO( "Device mapper ", dmName, " maps to ", res ); return { dmName, res }; } bool DeviceLister::isRemovable( const std::string& deviceName ) const { std::stringstream removableFilePath; removableFilePath << "/sys/block/" << deviceName << "/removable"; std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), "r" ), &fclose ); // Assume the file isn't removable by default if ( removableFile != nullptr ) { char buff; if ( fread(&buff, sizeof(buff), 1, removableFile.get() ) != 1 ) return buff == '1'; return false; } return false; } std::vector<std::tuple<std::string, std::string, bool>> DeviceLister::devices() const { std::vector<std::tuple<std::string, std::string, bool>> res; try { DeviceMap mountpoints = listMountpoints(); if ( mountpoints.empty() == true ) { LOG_WARN( "Failed to detect any mountpoint" ); return res; } auto devices = listDevices(); if ( devices.empty() == true ) { LOG_WARN( "Failed to detect any device" ); return res; } for ( const auto& p : mountpoints ) { const auto& devicePath = p.first; auto deviceName = utils::file::fileName( devicePath ); const auto& mountpoint = p.second; auto it = devices.find( deviceName ); std::string uuid; if ( it != end( devices ) ) uuid = it->second; else { std::pair<std::string, std::string> dmPair; LOG_INFO( "Failed to find device for mountpoint ", mountpoint, ". Attempting to resolve using device mapper" ); try { // Fetch a pair containing the device-mapper device name and // the block device it points to dmPair = deviceFromDeviceMapper( devicePath ); } catch( std::runtime_error& ex ) { LOG_WARN( "Failed to resolve using device mapper: ", ex.what() ); continue; } // First try with the block device it = devices.find( dmPair.second ); if ( it != end( devices ) ) uuid = it->second; else { // Otherwise try with the device mapper name. it = devices.find( dmPair.first ); if( it != end( devices ) ) uuid = it->second; else { LOG_ERROR( "Failed to resolve mountpoint ", mountpoint, " to any known device" ); continue; } } } auto removable = isRemovable( deviceName ); res.emplace_back( std::make_tuple( uuid, utils::file::toMrl( mountpoint ), removable ) ); } } catch(std::runtime_error& ex) { LOG_WARN( "Failed to list devices: ", ex.what(), ". Falling back to a dummy device containing '/'" ); res.emplace_back( std::make_tuple( "{dummy-device}", utils::file::toMrl( "/" ), false ) ); } return res; } } } <commit_msg>DeviceLister: unix: Add xfs to the allowed FS types<commit_after>/***************************************************************************** * Media Library ***************************************************************************** * Copyright (C) 2015-2019 Hugo Beauzée-Luyssen, Videolabs, VideoLAN * * Authors: Hugo Beauzée-Luyssen <[email protected]> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "DeviceLister.h" #include "logging/Logger.h" #include "utils/Filename.h" #include <dirent.h> #include <mntent.h> #include <sys/types.h> #include <vector> #include <memory> #include <cerrno> #include <sstream> #include <cstdio> #include <algorithm> #include <cstring> #include <limits.h> #include <unistd.h> namespace medialibrary { namespace fs { DeviceLister::DeviceMap DeviceLister::listDevices() const { static const std::vector<std::string> bannedDevice = { "loop" }; const std::string devPath = "/dev/disk/by-uuid/"; // Don't use fs::Directory to iterate, as it resolves the symbolic links automatically. // We need the link name & what it points to. std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( devPath.c_str() ), &closedir ); if ( dir == nullptr ) { std::stringstream err; err << "Failed to open /dev/disk/by-uuid: " << strerror(errno); throw std::runtime_error( err.str() ); } DeviceMap res; dirent* result = nullptr; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } std::string path = devPath + result->d_name; char linkPath[PATH_MAX] = {}; if ( readlink( path.c_str(), linkPath, PATH_MAX ) < 0 ) { std::stringstream err; err << "Failed to resolve uuid -> device link: " << result->d_name << " (" << strerror(errno) << ')'; throw std::runtime_error( err.str() ); } auto deviceName = utils::file::fileName( linkPath ); if ( std::find_if( begin( bannedDevice ), end( bannedDevice ), [&deviceName]( const std::string& pattern ) { return deviceName.length() >= pattern.length() && deviceName.find( pattern ) == 0; }) != end( bannedDevice ) ) continue; auto uuid = result->d_name; LOG_INFO( "Discovered device ", deviceName, " -> {", uuid, '}' ); res[deviceName] = uuid; } return res; } DeviceLister::MountpointMap DeviceLister::listMountpoints() const { static const std::vector<std::string> allowedFsType = { "vfat", "exfat", "sdcardfs", "fuse", "ntfs", "fat32", "ext3", "ext4", "esdfs", "xfs" }; MountpointMap res; errno = 0; mntent* s; char buff[512]; mntent smnt; FILE* f = setmntent("/etc/mtab", "r"); if ( f == nullptr ) throw std::runtime_error( "Failed to read /etc/mtab" ); std::unique_ptr<FILE, int(*)(FILE*)> fPtr( f, &endmntent ); while ( getmntent_r( f, &smnt, buff, sizeof(buff) ) != nullptr ) { s = &smnt; if ( std::find( begin( allowedFsType ), end( allowedFsType ), s->mnt_type ) == end( allowedFsType ) ) continue; auto deviceName = s->mnt_fsname; if ( res.count( deviceName ) == 0 ) { LOG_INFO( "Discovered mountpoint ", deviceName, " mounted on ", s->mnt_dir, " (", s->mnt_type, ')' ); res[deviceName] = s->mnt_dir; } else LOG_INFO( "Ignoring duplicated mountpoint (", s->mnt_dir, ") for device ", deviceName ); errno = 0; } if ( errno != 0 ) { LOG_ERROR( "Failed to read mountpoints: ", strerror( errno ) ); } return res; } std::pair<std::string,std::string> DeviceLister::deviceFromDeviceMapper( const std::string& devicePath ) const { if ( devicePath.find( "/dev/mapper" ) != 0 ) return {}; char linkPath[PATH_MAX + 1]; auto linkSize = readlink( devicePath.c_str(), linkPath, PATH_MAX ); if ( linkSize < 0 ) { std::stringstream err; err << "Failed to resolve device -> mapper link: " << devicePath << " (" << strerror(errno) << ')'; throw std::runtime_error( err.str() ); } linkPath[linkSize] = 0; LOG_INFO( "Resolved ", devicePath, " to ", linkPath, " device mapper" ); const auto dmName = utils::file::fileName( linkPath ); std::string dmSlavePath = "/sys/block/" + dmName + "/slaves"; std::unique_ptr<DIR, int(*)(DIR*)> dir( opendir( dmSlavePath.c_str() ), &closedir ); std::string res; if ( dir == nullptr ) { std::stringstream err; err << "Failed to open device-mapper slaves directory (" << linkPath << ')'; throw std::runtime_error( err.str() ); } dirent* result; while ( ( result = readdir( dir.get() ) ) != nullptr ) { if ( strcmp( result->d_name, "." ) == 0 || strcmp( result->d_name, ".." ) == 0 ) { continue; } if ( res.empty() == true ) res = result->d_name; else LOG_WARN( "More than one slave for device mapper ", linkPath ); } LOG_INFO( "Device mapper ", dmName, " maps to ", res ); return { dmName, res }; } bool DeviceLister::isRemovable( const std::string& deviceName ) const { std::stringstream removableFilePath; removableFilePath << "/sys/block/" << deviceName << "/removable"; std::unique_ptr<FILE, int(*)(FILE*)> removableFile( fopen( removableFilePath.str().c_str(), "r" ), &fclose ); // Assume the file isn't removable by default if ( removableFile != nullptr ) { char buff; if ( fread(&buff, sizeof(buff), 1, removableFile.get() ) != 1 ) return buff == '1'; return false; } return false; } std::vector<std::tuple<std::string, std::string, bool>> DeviceLister::devices() const { std::vector<std::tuple<std::string, std::string, bool>> res; try { DeviceMap mountpoints = listMountpoints(); if ( mountpoints.empty() == true ) { LOG_WARN( "Failed to detect any mountpoint" ); return res; } auto devices = listDevices(); if ( devices.empty() == true ) { LOG_WARN( "Failed to detect any device" ); return res; } for ( const auto& p : mountpoints ) { const auto& devicePath = p.first; auto deviceName = utils::file::fileName( devicePath ); const auto& mountpoint = p.second; auto it = devices.find( deviceName ); std::string uuid; if ( it != end( devices ) ) uuid = it->second; else { std::pair<std::string, std::string> dmPair; LOG_INFO( "Failed to find device for mountpoint ", mountpoint, ". Attempting to resolve using device mapper" ); try { // Fetch a pair containing the device-mapper device name and // the block device it points to dmPair = deviceFromDeviceMapper( devicePath ); } catch( std::runtime_error& ex ) { LOG_WARN( "Failed to resolve using device mapper: ", ex.what() ); continue; } // First try with the block device it = devices.find( dmPair.second ); if ( it != end( devices ) ) uuid = it->second; else { // Otherwise try with the device mapper name. it = devices.find( dmPair.first ); if( it != end( devices ) ) uuid = it->second; else { LOG_ERROR( "Failed to resolve mountpoint ", mountpoint, " to any known device" ); continue; } } } auto removable = isRemovable( deviceName ); res.emplace_back( std::make_tuple( uuid, utils::file::toMrl( mountpoint ), removable ) ); } } catch(std::runtime_error& ex) { LOG_WARN( "Failed to list devices: ", ex.what(), ". Falling back to a dummy device containing '/'" ); res.emplace_back( std::make_tuple( "{dummy-device}", utils::file::toMrl( "/" ), false ) ); } return res; } } } <|endoftext|>
<commit_before>/**************************************************************************** * Copyright 2013 Evan Drumwright * This library is distributed under the terms of the GNU Lesser General Public * License (found in COPYING). ****************************************************************************/ // This file includes common routines for all matrices, dynamic and fixed size, and mutable and constant (through inclusion of ConstMatrixCommon.inl) // include the constant versions #include "ConstMatrixCommon.inl" /// Gets a column iterator to a block COLUMN_ITERATOR block_column_iterator_begin(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif COLUMN_ITERATOR i; i._count = 0; i._sz = (row_end - row_start)*(col_end - col_start); i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = i._current_data = data() + i._ld*col_start + row_start; return i; } /// Gets a column iterator to a block COLUMN_ITERATOR block_column_iterator_end(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif COLUMN_ITERATOR i; i._sz = (row_end - row_start)*(col_end - col_start); i._count = i._sz; i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = data() + i._ld*col_start + row_start; i._current_data = i._data_start + i._sz; return i; } /// Gets a row iterator to a block ROW_ITERATOR block_row_iterator_begin(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif ROW_ITERATOR i; i._count = 0; i._sz = (row_end - row_start)*(col_end - col_start); i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = i._current_data = data() + i._ld*col_start + row_start; return i; } /// Gets a row iterator to a block ROW_ITERATOR block_row_iterator_end(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif ROW_ITERATOR i; i._sz = (row_end - row_start)*(col_end - col_start); i._count = i._sz; i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = data() + i._ld*col_start + row_start; i._current_data = i._data_start + i._sz; return i; } template <class V> MATRIXX& set_row(unsigned row, const V& v) { #ifndef NEXCEPT if (row > rows()) throw InvalidIndexException(); if (sizeof(data()) != sizeof(v.data())) throw DataMismatchException(); #endif // setup the iterators ROW_ITERATOR target = block_row_iterator_begin(row, row+1, 0, columns()); ROW_ITERATOR target_end = target.end(); CONST_ROW_ITERATOR source = v.row_iterator_begin(); // iterate while (target != target_end) *target++ = *source++; return *this; } template <class V> MATRIXX& set_column(unsigned column, const V& v) { #ifndef NEXCEPT if (column > columns()) throw InvalidIndexException(); if (sizeof(data()) != sizeof(v.data())) throw DataMismatchException(); #endif // setup the iterators COLUMN_ITERATOR target = block_column_iterator_begin(0, rows(), column, column+1); COLUMN_ITERATOR target_end = target.end(); CONST_COLUMN_ITERATOR source = v.column_iterator_begin(); // iterate while (target != target_end) *target++ = *source++; return *this; } /// Sets the specified sub matrix /** * \param row_start the row to start (inclusive) * \param col_start the column to start (inclusive) * \param m the source matrix * \param transpose determines whether the m is to be transposed * \note fails assertion if m is too large to insert into this */ template <class M> MATRIXX& set_sub_mat(unsigned row_start, unsigned col_start, const M& m, Transposition trans = eNoTranspose) { #ifndef NEXCEPT if (sizeof(data()) != sizeof(m.data())) throw DataMismatchException(); if (trans == eNoTranspose) { if (row_start + m.rows() > rows() || col_start + m.columns() > columns()) throw MissizeException(); } else if (row_start + m.columns() > rows() || col_start + m.rows() > columns()) throw MissizeException(); #endif // make sure there is data to copy if (m.rows() == 0 || m.columns() == 0) return *this; // copy each column of m using BLAS if (trans == eNoTranspose) { CONST_COLUMN_ITERATOR mIter = m.column_iterator_begin(); COLUMN_ITERATOR tIter = column_iterator_begin(); while (mIter != mIter.end()) { *tIter = *mIter; tIter++; mIter++; } } else { CONST_ROW_ITERATOR mIter = m.row_iterator_begin(); COLUMN_ITERATOR tIter = column_iterator_begin(); while (mIter != mIter.end()) { *tIter = *mIter; tIter++; mIter++; } } return *this; } /// Get an iterator to the beginning (iterates column by column) ROW_ITERATOR row_iterator_begin() { ROW_ITERATOR i; i._count = 0; i._sz = rows()*columns(); i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = i._current_data = data(); return i; } /// Get an iterator to the end ROW_ITERATOR row_iterator_end() { ROW_ITERATOR i; i._sz = rows()*columns(); i._count = i._sz; i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = data(); i._current_data = data() + i._ld*i._columns; return i; } /// Get an iterator to the beginning (iterates column by column) COLUMN_ITERATOR column_iterator_begin() { COLUMN_ITERATOR i; i._count = 0; i._sz = rows()*columns(); i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = i._current_data = data(); return i; } /// Get an iterator to the end COLUMN_ITERATOR column_iterator_end() { COLUMN_ITERATOR i; i._sz = rows()*columns(); i._count = i._sz; i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = data(); i._current_data = data() + i._ld*i._columns; return i; } <commit_msg>Fixed bug in set_sub_mat()<commit_after>/**************************************************************************** * Copyright 2013 Evan Drumwright * This library is distributed under the terms of the GNU Lesser General Public * License (found in COPYING). ****************************************************************************/ // This file includes common routines for all matrices, dynamic and fixed size, and mutable and constant (through inclusion of ConstMatrixCommon.inl) // include the constant versions #include "ConstMatrixCommon.inl" /// Gets a column iterator to a block COLUMN_ITERATOR block_column_iterator_begin(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif COLUMN_ITERATOR i; i._count = 0; i._sz = (row_end - row_start)*(col_end - col_start); i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = i._current_data = data() + i._ld*col_start + row_start; return i; } /// Gets a column iterator to a block COLUMN_ITERATOR block_column_iterator_end(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif COLUMN_ITERATOR i; i._sz = (row_end - row_start)*(col_end - col_start); i._count = i._sz; i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = data() + i._ld*col_start + row_start; i._current_data = i._data_start + i._sz; return i; } /// Gets a row iterator to a block ROW_ITERATOR block_row_iterator_begin(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif ROW_ITERATOR i; i._count = 0; i._sz = (row_end - row_start)*(col_end - col_start); i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = i._current_data = data() + i._ld*col_start + row_start; return i; } /// Gets a row iterator to a block ROW_ITERATOR block_row_iterator_end(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) { #ifndef NEXCEPT if (row_end < row_start || row_end > rows() || col_end < col_start || col_end > columns()) throw InvalidIndexException(); #endif ROW_ITERATOR i; i._sz = (row_end - row_start)*(col_end - col_start); i._count = i._sz; i._ld = leading_dim(); i._rows = row_end - row_start; i._columns = col_end - col_start; i._data_start = data() + i._ld*col_start + row_start; i._current_data = i._data_start + i._sz; return i; } template <class V> MATRIXX& set_row(unsigned row, const V& v) { #ifndef NEXCEPT if (row > rows()) throw InvalidIndexException(); if (sizeof(data()) != sizeof(v.data())) throw DataMismatchException(); #endif // setup the iterators ROW_ITERATOR target = block_row_iterator_begin(row, row+1, 0, columns()); ROW_ITERATOR target_end = target.end(); CONST_ROW_ITERATOR source = v.row_iterator_begin(); // iterate while (target != target_end) *target++ = *source++; return *this; } template <class V> MATRIXX& set_column(unsigned column, const V& v) { #ifndef NEXCEPT if (column > columns()) throw InvalidIndexException(); if (sizeof(data()) != sizeof(v.data())) throw DataMismatchException(); #endif // setup the iterators COLUMN_ITERATOR target = block_column_iterator_begin(0, rows(), column, column+1); COLUMN_ITERATOR target_end = target.end(); CONST_COLUMN_ITERATOR source = v.column_iterator_begin(); // iterate while (target != target_end) *target++ = *source++; return *this; } /// Sets the specified sub matrix /** * \param row_start the row to start (inclusive) * \param col_start the column to start (inclusive) * \param m the source matrix * \param transpose determines whether the m is to be transposed * \note fails assertion if m is too large to insert into this */ template <class M> MATRIXX& set_sub_mat(unsigned row_start, unsigned col_start, const M& m, Transposition trans = eNoTranspose) { #ifndef NEXCEPT if (sizeof(data()) != sizeof(m.data())) throw DataMismatchException(); if (trans == eNoTranspose) { if (row_start + m.rows() > rows() || col_start + m.columns() > columns()) throw MissizeException(); } else if (row_start + m.columns() > rows() || col_start + m.rows() > columns()) throw MissizeException(); #endif // make sure there is data to copy if (m.rows() == 0 || m.columns() == 0) return *this; // copy each column of m using BLAS if (trans == eNoTranspose) { CONST_COLUMN_ITERATOR mIter = m.column_iterator_begin(); COLUMN_ITERATOR tIter = block_column_iterator_begin(row_start, row_start+m.rows(), col_start, col_start+m.columns()); while (mIter != mIter.end()) { *tIter = *mIter; tIter++; mIter++; } } else { CONST_ROW_ITERATOR mIter = m.row_iterator_begin(); COLUMN_ITERATOR tIter = block_column_iterator_begin(row_start, row_start+m.rows(), col_start, col_start+m.columns()); while (mIter != mIter.end()) { *tIter = *mIter; tIter++; mIter++; } } return *this; } /// Get an iterator to the beginning (iterates column by column) ROW_ITERATOR row_iterator_begin() { ROW_ITERATOR i; i._count = 0; i._sz = rows()*columns(); i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = i._current_data = data(); return i; } /// Get an iterator to the end ROW_ITERATOR row_iterator_end() { ROW_ITERATOR i; i._sz = rows()*columns(); i._count = i._sz; i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = data(); i._current_data = data() + i._ld*i._columns; return i; } /// Get an iterator to the beginning (iterates column by column) COLUMN_ITERATOR column_iterator_begin() { COLUMN_ITERATOR i; i._count = 0; i._sz = rows()*columns(); i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = i._current_data = data(); return i; } /// Get an iterator to the end COLUMN_ITERATOR column_iterator_end() { COLUMN_ITERATOR i; i._sz = rows()*columns(); i._count = i._sz; i._ld = leading_dim(); i._rows = rows(); i._columns = columns(); i._data_start = data(); i._current_data = data() + i._ld*i._columns; return i; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // STP - SFML TMX Parser // Copyright (c) 2013-2014 Manuel Sabogal // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef STP_OBJECTGROUP_HPP #define STP_OBJECTGROUP_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <string> #include <vector> #include <unordered_map> #include "SFML/Graphics/VertexArray.hpp" #include "SFML/Graphics/PrimitiveType.hpp" #include "SFML/Graphics/Drawable.hpp" #include "STP/Config.hpp" #include "STP/Core/MapObject.hpp" #include "STP/Core/TileSet.hpp" namespace tmx { enum ObjectType { Rectangle, Ellipse, Polygon, Polyline, Tile }; //////////////////////////////////////////////////////////// /// \brief Class for manage the TMX ObjectGroups /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup : public MapObject { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// /// Constructs an empty object group with no values. /// //////////////////////////////////////////////////////////// ObjectGroup(); //////////////////////////////////////////////////////////// /// \brief Constructs a object group given a name, width, height /// opacity, visible and hexcolor atributes /// /// \param name The name of the object group /// \param width The width of the object group in tiles /// \param height The height of the object group in tiles /// \param opacity Float value between 0.0 to 1.0 /// \param visible The visibility of the object group /// \param hexcolor Hexadecimal color used to display the objects in this group. (example value: 0x0000FF for blue) /// //////////////////////////////////////////////////////////// ObjectGroup(const std::string& name, unsigned int width, unsigned int height, float opacity, bool visible, int32_t hexcolor = -1); //////////////////////////////////////////////////////////// /// Nested classes /// //////////////////////////////////////////////////////////// class Object; //////////////////////////////////////////////////////////// /// \brief Add a new Object to the object group /// /// \param newobject Object to be added /// //////////////////////////////////////////////////////////// void AddObject(tmx::ObjectGroup::Object newobject); //////////////////////////////////////////////////////////// /// \brief Change the color of the object group, does not affect the opacity /// /// \param color sf::Color RGB value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); //////////////////////////////////////////////////////////// /// \brief Change the opacity of the object group /// /// \param opacity Float value between 0.0 to 1.0 /// //////////////////////////////////////////////////////////// void SetOpacity(float opacity); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::vector<tmx::ObjectGroup::Object> objects_; }; //////////////////////////////////////////////////////////// /// \brief Class for manage each Object inside of the ObjectGroup /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup::Object : public sf::Drawable, public tmx::Properties { public: //////////////////////////////////////////////////////////// /// \brief Construct a Object given a name, width, height /// rotation, visible and image atributes /// /// \param name The name of the object (An arbitrary string) /// \param type The type of the object (An arbitrary string) /// \param x The x coordinate of the object in pixels /// \param y The y coordinate of the object in pixels /// \param width The width of the object in pixels (defaults to 0) /// \param height The width of the object in pixels (defaults to 0) /// \param rotation The rotation of the object in degrees clockwise (defaults to 0) /// \param visible The visibility of the object /// \param shape_type The shape type of the object, see tmx::ObjectType /// \param vertices_points String containing a list of coordinates (example: "0,0 17,17 -14,18") /// //////////////////////////////////////////////////////////// Object(const std::string& name, const std::string& type, int x, int y, unsigned int width, unsigned int height, float rotation, bool visible, tmx::ObjectType shape_type, const std::string& vertices_points = std::string(), tmx::TileSet::Tile* tile = nullptr); public: //////////////////////////////////////////////////////////// /// \brief Change the color of the tile, affect the opacity. /// /// \param color sf::Color RGBA value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::string name_; std::string type_; unsigned int x_, y_; unsigned int width_, height_; float rotation_; tmx::TileSet::Tile* tile_; std::vector<sf::Vertex> vertices_; public: /// \brief Visibility of the Object bool visible; }; } // namespace tmx #endif // STP_OBJECTGROUP_HPP <commit_msg>Added documentation for the last commit changes.<commit_after>//////////////////////////////////////////////////////////// // // The MIT License (MIT) // // STP - SFML TMX Parser // Copyright (c) 2013-2014 Manuel Sabogal // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // //////////////////////////////////////////////////////////// #ifndef STP_OBJECTGROUP_HPP #define STP_OBJECTGROUP_HPP //////////////////////////////////////////////////////////// // Headers //////////////////////////////////////////////////////////// #include <string> #include <vector> #include <unordered_map> #include "SFML/Graphics/VertexArray.hpp" #include "SFML/Graphics/PrimitiveType.hpp" #include "SFML/Graphics/Drawable.hpp" #include "STP/Config.hpp" #include "STP/Core/MapObject.hpp" #include "STP/Core/TileSet.hpp" namespace tmx { enum ObjectType { Rectangle, Ellipse, Polygon, Polyline, Tile }; //////////////////////////////////////////////////////////// /// \brief Class for manage the TMX ObjectGroups /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup : public MapObject { public: //////////////////////////////////////////////////////////// /// \brief Default constructor /// /// Constructs an empty object group with no values. /// //////////////////////////////////////////////////////////// ObjectGroup(); //////////////////////////////////////////////////////////// /// \brief Constructs a object group given a name, width, height /// opacity, visible and hexcolor atributes /// /// \param name The name of the object group /// \param width The width of the object group in tiles /// \param height The height of the object group in tiles /// \param opacity Float value between 0.0 to 1.0 /// \param visible The visibility of the object group /// \param hexcolor Hexadecimal color used to display the objects in this group. (example value: 0x0000FF for blue) /// //////////////////////////////////////////////////////////// ObjectGroup(const std::string& name, unsigned int width, unsigned int height, float opacity, bool visible, int32_t hexcolor = -1); //////////////////////////////////////////////////////////// /// Nested classes /// //////////////////////////////////////////////////////////// class Object; //////////////////////////////////////////////////////////// /// \brief Add a new Object to the object group /// /// \param newobject Object to be added /// //////////////////////////////////////////////////////////// void AddObject(tmx::ObjectGroup::Object newobject); //////////////////////////////////////////////////////////// /// \brief Change the color of the object group, does not affect the opacity /// /// \param color sf::Color RGB value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); //////////////////////////////////////////////////////////// /// \brief Change the opacity of the object group /// /// \param opacity Float value between 0.0 to 1.0 /// //////////////////////////////////////////////////////////// void SetOpacity(float opacity); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::vector<tmx::ObjectGroup::Object> objects_; }; //////////////////////////////////////////////////////////// /// \brief Class for manage each Object inside of the ObjectGroup /// //////////////////////////////////////////////////////////// class STP_API ObjectGroup::Object : public sf::Drawable, public tmx::Properties { public: //////////////////////////////////////////////////////////// /// \brief Construct a Object given a name, width, height /// rotation, visible and image atributes /// /// \param name The name of the object (An arbitrary string) /// \param type The type of the object (An arbitrary string) /// \param x The x coordinate of the object in pixels /// \param y The y coordinate of the object in pixels /// \param width The width of the object in pixels (defaults to 0) /// \param height The width of the object in pixels (defaults to 0) /// \param rotation The rotation of the object in degrees clockwise (defaults to 0) /// \param visible The visibility of the object /// \param shape_type The shape type of the object, see tmx::ObjectType /// \param vertices_points String containing a list of coordinates (example: "0,0 17,17 -14,18") /// \param tile Pointer to a Ttmx::TileSet::Tile, only used when is a Tile-Object, otherwise is nullptr. /// //////////////////////////////////////////////////////////// Object(const std::string& name, const std::string& type, int x, int y, unsigned int width, unsigned int height, float rotation, bool visible, tmx::ObjectType shape_type, const std::string& vertices_points = std::string(), tmx::TileSet::Tile* tile = nullptr); public: //////////////////////////////////////////////////////////// /// \brief Change the color of the tile, affect the opacity. /// /// \param color sf::Color RGBA value /// //////////////////////////////////////////////////////////// void SetColor(const sf::Color& color); private: void draw(sf::RenderTarget& target, sf::RenderStates states) const; private: std::string name_; std::string type_; unsigned int x_, y_; unsigned int width_, height_; float rotation_; tmx::TileSet::Tile* tile_; std::vector<sf::Vertex> vertices_; public: /// \brief Visibility of the Object bool visible; }; } // namespace tmx #endif // STP_OBJECTGROUP_HPP <|endoftext|>
<commit_before>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbLineSegmentDetector.h" #include "otbDrawLineSpatialObjectListFilter.h" #include "otbLineSpatialObjectList.h" #include "itkLineIterator.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int otbLineSegmentDetector( int argc, char * argv[] ) { const char * infname = argv[1]; const char * outfname = argv[2]; typedef double InputPixelType; const unsigned int Dimension = 2; /** Typedefs */ typedef otb::Image< InputPixelType, Dimension > InputImageType; typedef InputImageType::IndexType IndexType; typedef otb::ImageFileReader<InputImageType> ReaderType; typedef otb::ImageFileWriter<InputImageType> WriterType; typedef otb::DrawLineSpatialObjectListFilter< InputImageType ,InputImageType > DrawLineListType; typedef otb::LineSegmentDetector<InputImageType , InputPixelType> lsdFilterType; typedef itk::LineIterator<InputImageType> LineIteratorFilter; /** Instanciation of smart pointer*/ lsdFilterType::Pointer lsdFilter = lsdFilterType::New(); DrawLineListType::Pointer drawLineFilter = DrawLineListType::New(); ReaderType::Pointer reader = ReaderType::New(); /** */ typedef otb::LineSpatialObjectList LinesListType; typedef LinesListType::LineType LineType; LinesListType::Pointer list = LinesListType::New(); LineType::PointListType pointList; LineType::LinePointType pointBegin , pointEnd; IndexType IndexBegin , IndexEnd; /***/ reader->SetFileName(infname); lsdFilter->SetInput(reader->GetOutput()); lsdFilter->Update(); LinesListType::const_iterator it = lsdFilter->GetOutput()->begin(); LinesListType::const_iterator itEnd = lsdFilter->GetOutput()->end(); while(it != itEnd) { LineType::PointListType & pointsList = (*it)->GetPoints(); LineType::PointListType::const_iterator itPoints = pointsList.begin(); float x = (*itPoints).GetPosition()[0]; float y = (*itPoints).GetPosition()[1]; IndexBegin[0] = x ; IndexBegin[1] = y; itPoints++; float x1 = (*itPoints).GetPosition()[0]; float y1 = (*itPoints).GetPosition()[1]; IndexEnd[0]= x1 ; IndexEnd[1] = y1; LineIteratorFilter itLine(reader->GetOutput(),IndexBegin, IndexEnd); itLine.GoToBegin(); while(!itLine.IsAtEnd()) { if(reader->GetOutput()->GetRequestedRegion().IsInside(itLine.GetIndex())) itLine.Set(255.); ++itLine; } ++it; } std::cout << " lsdFilter Ouput Size" << lsdFilter->GetOutput()->size() <<std::endl; /** Write The Output Image*/ WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(reader->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <commit_msg>ENH: correct Warnings<commit_after>/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbImage.h" #include "otbLineSegmentDetector.h" #include "otbDrawLineSpatialObjectListFilter.h" #include "otbLineSpatialObjectList.h" #include "itkLineIterator.h" #include "otbImageFileReader.h" #include "otbImageFileWriter.h" int otbLineSegmentDetector( int argc, char * argv[] ) { const char * infname = argv[1]; const char * outfname = argv[2]; typedef double InputPixelType; const unsigned int Dimension = 2; /** Typedefs */ typedef otb::Image< InputPixelType, Dimension > InputImageType; typedef InputImageType::IndexType IndexType; typedef otb::ImageFileReader<InputImageType> ReaderType; typedef otb::ImageFileWriter<InputImageType> WriterType; typedef otb::DrawLineSpatialObjectListFilter< InputImageType ,InputImageType > DrawLineListType; typedef otb::LineSegmentDetector<InputImageType , InputPixelType> lsdFilterType; typedef itk::LineIterator<InputImageType> LineIteratorFilter; /** Instanciation of smart pointer*/ lsdFilterType::Pointer lsdFilter = lsdFilterType::New(); DrawLineListType::Pointer drawLineFilter = DrawLineListType::New(); ReaderType::Pointer reader = ReaderType::New(); /** */ typedef otb::LineSpatialObjectList LinesListType; typedef LinesListType::LineType LineType; LinesListType::Pointer list = LinesListType::New(); LineType::PointListType pointList; LineType::LinePointType pointBegin , pointEnd; IndexType IndexBegin , IndexEnd; /***/ reader->SetFileName(infname); lsdFilter->SetInput(reader->GetOutput()); lsdFilter->Update(); LinesListType::const_iterator it = lsdFilter->GetOutput()->begin(); LinesListType::const_iterator itEnd = lsdFilter->GetOutput()->end(); while(it != itEnd) { LineType::PointListType & pointsList = (*it)->GetPoints(); LineType::PointListType::const_iterator itPoints = pointsList.begin(); float x = (*itPoints).GetPosition()[0]; float y = (*itPoints).GetPosition()[1]; IndexBegin[0] = static_cast<int>(x) ; IndexBegin[1] = static_cast<int>(y); itPoints++; float x1 = (*itPoints).GetPosition()[0]; float y1 = (*itPoints).GetPosition()[1]; IndexEnd[0]= static_cast<int>(x1) ; IndexEnd[1] = static_cast<int>(y1); LineIteratorFilter itLine(reader->GetOutput(),IndexBegin, IndexEnd); itLine.GoToBegin(); while(!itLine.IsAtEnd()) { if(reader->GetOutput()->GetRequestedRegion().IsInside(itLine.GetIndex())) itLine.Set(255.); ++itLine; } ++it; } std::cout << " lsdFilter Ouput Size" << lsdFilter->GetOutput()->size() <<std::endl; /** Write The Output Image*/ WriterType::Pointer writer = WriterType::New(); writer->SetFileName(outfname); writer->SetInput(reader->GetOutput()); writer->Update(); return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/* * VapourSynth D2V Plugin * * Copyright (c) 2012 Derek Buitenhuis * * This file is part of d2vsource. * * d2vsource is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * d2vsource is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with d2vsource; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <stdint.h> #include <stdlib.h> } #include <VapourSynth.h> #include <VSHelper.h> #include "d2v.hpp" #include "d2vsource.hpp" #include "decode.hpp" #include "directrender.hpp" void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) *instanceData; vsapi->setVideoInfo(&d->vi, 1, node); } const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) *instanceData; VSFrameRef *s, *f; VSMap *props; string msg; int ret; /* Unreference the previously decoded frame. */ av_frame_unref(d->frame); ret = decodeframe(n, d->d2v, d->dec, d->frame, msg); if (ret < 0) { vsapi->setFilterError(msg.c_str(), frameCtx); return NULL; } /* Grab our direct-rendered frame. */ s = (VSFrameRef *) d->frame->opaque; if (!s) { vsapi->setFilterError("Seek pattern broke d2vsource! Please send a sample.", frameCtx); return NULL; } /* If our width and height are the same, just return it. */ if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) { f = (VSFrameRef *) vsapi->cloneFrameRef(s); return f; } f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core); /* Copy into VS's buffers. */ vs_bitblt(vsapi->getWritePtr(f, 0), vsapi->getStride(f, 0), vsapi->getWritePtr(s, 0), vsapi->getStride(s, 0), d->vi.width, d->vi.height); vs_bitblt(vsapi->getWritePtr(f, 1), vsapi->getStride(f, 1), vsapi->getWritePtr(s, 1), vsapi->getStride(s, 1), d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH); vs_bitblt(vsapi->getWritePtr(f, 2), vsapi->getStride(f, 2), vsapi->getWritePtr(s, 2), vsapi->getStride(s, 2), d->vi.width >> d->vi.format->subSamplingW, d->vi.height >> d->vi.format->subSamplingH); props = vsapi->getFramePropsRW(f); /* * The DGIndex manual simply says: * "The matrix field displays the currently applicable matrix_coefficients value (colorimetry)." * * I can only assume this lines up with the tables VS uses correctly. */ vsapi->propSetInt(props, "_Matrix", d->d2v->gops[d->d2v->frames[n].gop].matrix, paReplace); vsapi->propSetInt(props, "_DurationNum", d->d2v->fps_den, paReplace); vsapi->propSetInt(props, "_DurationDen", d->d2v->fps_num, paReplace); vsapi->propSetFloat(props, "_AbsoluteTime", (static_cast<double>(d->d2v->fps_den) * n) / static_cast<double>(d->d2v->fps_num), paReplace); if (d->d2v->yuvrgb_scale == PC) vsapi->propSetInt(props, "_ColorRange", 0, paReplace); else if (d->d2v->yuvrgb_scale == TV) vsapi->propSetInt(props, "_ColorRange", 1, paReplace); switch (d->frame->pict_type) { case AV_PICTURE_TYPE_I: vsapi->propSetData(props, "_PictType", "I", 1, paReplace); break; case AV_PICTURE_TYPE_P: vsapi->propSetData(props, "_PictType", "P", 1, paReplace); break; case AV_PICTURE_TYPE_B: vsapi->propSetData(props, "_PictType", "B", 1, paReplace); break; default: break; } int fieldbased; if (d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_PROGRESSIVE) fieldbased = 0; else fieldbased = 1 + !!(d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_TFF); vsapi->propSetInt(props, "_FieldBased", fieldbased, paReplace); vsapi->propSetInt(props, "_ChromaLocation", d->d2v->mpeg_type == 1 ? 1 : 0, paReplace); return f; } void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) instanceData; d2vfreep(&d->d2v); decodefreep(&d->dec); av_frame_unref(d->frame); av_freep(&d->frame); free(d); } void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) { d2vData *data; string msg; bool no_crop; bool rff; int threads; int err; /* Need to get thread info before anything to pass to decodeinit(). */ threads = vsapi->propGetInt(in, "threads", 0, &err); if (err) threads = 0; if (threads < 0) { vsapi->setError(out, "Invalid number of threads."); return; } /* Allocate our private data. */ data = (d2vData *) malloc(sizeof(*data)); if (!data) { vsapi->setError(out, "Cannot allocate private data."); return; } data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg); if (!data->d2v) { vsapi->setError(out, msg.c_str()); free(data); return; } data->dec = decodeinit(data->d2v, threads, msg); if (!data->dec) { vsapi->setError(out, msg.c_str()); d2vfreep(&data->d2v); free(data); return; } /* * Make our private data available to libavcodec, and * set our custom get/release_buffer funcs. */ data->dec->avctx->opaque = (void *) data; data->dec->avctx->get_buffer2 = VSGetBuffer; /* Last frame is crashy right now. */ data->vi.numFrames = data->d2v->frames.size(); data->vi.width = data->d2v->width; data->vi.height = data->d2v->height; data->vi.fpsNum = data->d2v->fps_num; data->vi.fpsDen = data->d2v->fps_den; /* Stash the pointer to our core. */ data->core = core; data->api = (VSAPI *) vsapi; /* * Stash our aligned width and height for use with our * custom get_buffer, since it could require this. */ data->aligned_width = FFALIGN(data->vi.width, 16); data->aligned_height = FFALIGN(data->vi.height, 32); data->frame = av_frame_alloc(); if (!data->frame) { vsapi->setError(out, "Cannot allocate AVFrame."); d2vfreep(&data->d2v); decodefreep(&data->dec); free(data); return; } /* * Decode 1 frame to find out how the chroma is subampled. * The first time our custom get_buffer is called, it will * fill in data->vi.format. */ data->format_set = false; err = decodeframe(0, data->d2v, data->dec, data->frame, msg); if (err < 0) { msg.insert(0, "Failed to decode test frame: "); vsapi->setError(out, msg.c_str()); d2vfreep(&data->d2v); decodefreep(&data->dec); av_frame_unref(data->frame); av_freep(&data->frame); free(data); return; } /* See if nocrop is enabled, and set the width/height accordingly. */ no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err); if (err) no_crop = false; if (no_crop) { data->vi.width = data->aligned_width; data->vi.height = data->aligned_height; } vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmUnordered, nfMakeLinear, data, core); rff = !!vsapi->propGetInt(in, "rff", 0, &err); if (err) rff = true; if (rff) { VSPlugin *d2vPlugin = vsapi->getPluginById("com.sources.d2vsource", core); VSPlugin *corePlugin = vsapi->getPluginById("com.vapoursynth.std", core); VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL); VSNodeRef *middle; VSNodeRef *after; VSMap *args = vsapi->createMap(); VSMap *ret; const char *error; vsapi->propSetNode(args, "clip", before, paReplace); vsapi->freeNode(before); ret = vsapi->invoke(corePlugin, "Cache", args); middle = vsapi->propGetNode(ret, "clip", 0, NULL); vsapi->freeMap(ret); vsapi->propSetNode(args, "clip", middle, paReplace); vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL), vsapi->propGetDataSize(in, "input", 0, NULL), paReplace); vsapi->freeNode(middle); ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args); vsapi->freeMap(args); error = vsapi->getError(ret); if (error) { vsapi->setError(out, error); vsapi->freeMap(ret); d2vfreep(&data->d2v); decodefreep(&data->dec); av_frame_unref(data->frame); av_freep(&data->frame); free(data); return; } after = vsapi->propGetNode(ret, "clip", 0, NULL); vsapi->propSetNode(out, "clip", after, paReplace); vsapi->freeNode(after); vsapi->freeMap(ret); } } <commit_msg>d2vsource: Always set the frame properties<commit_after>/* * VapourSynth D2V Plugin * * Copyright (c) 2012 Derek Buitenhuis * * This file is part of d2vsource. * * d2vsource is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * d2vsource is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with d2vsource; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ extern "C" { #include <stdint.h> #include <stdlib.h> } #include <VapourSynth.h> #include <VSHelper.h> #include "d2v.hpp" #include "d2vsource.hpp" #include "decode.hpp" #include "directrender.hpp" void VS_CC d2vInit(VSMap *in, VSMap *out, void **instanceData, VSNode *node, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) *instanceData; vsapi->setVideoInfo(&d->vi, 1, node); } const VSFrameRef *VS_CC d2vGetFrame(int n, int activationReason, void **instanceData, void **frameData, VSFrameContext *frameCtx, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) *instanceData; const VSFrameRef *s; VSFrameRef *f; VSMap *props; string msg; int ret; int plane; /* Unreference the previously decoded frame. */ av_frame_unref(d->frame); ret = decodeframe(n, d->d2v, d->dec, d->frame, msg); if (ret < 0) { vsapi->setFilterError(msg.c_str(), frameCtx); return NULL; } /* Grab our direct-rendered frame. */ s = (const VSFrameRef *) d->frame->opaque; if (!s) { vsapi->setFilterError("Seek pattern broke d2vsource! Please send a sample.", frameCtx); return NULL; } /* If our width and height are the same, just return it. */ if (d->vi.width == d->aligned_width && d->vi.height == d->aligned_height) { f = vsapi->copyFrame(s, core); } else { f = vsapi->newVideoFrame(d->vi.format, d->vi.width, d->vi.height, NULL, core); /* Copy into VS's buffers. */ for (plane = 0; plane < d->vi.format->numPlanes; plane++) { uint8_t *dstp = vsapi->getWritePtr(f, plane); const uint8_t *srcp = vsapi->getReadPtr(s, plane); int dst_stride = vsapi->getStride(f, plane); int src_stride = vsapi->getStride(s, plane); int width = vsapi->getFrameWidth(f, plane); int height = vsapi->getFrameHeight(f, plane); vs_bitblt(dstp, dst_stride, srcp, src_stride, width * d->vi.format->bytesPerSample, height); } } props = vsapi->getFramePropsRW(f); /* * The DGIndex manual simply says: * "The matrix field displays the currently applicable matrix_coefficients value (colorimetry)." * * I can only assume this lines up with the tables VS uses correctly. */ vsapi->propSetInt(props, "_Matrix", d->d2v->gops[d->d2v->frames[n].gop].matrix, paReplace); vsapi->propSetInt(props, "_DurationNum", d->d2v->fps_den, paReplace); vsapi->propSetInt(props, "_DurationDen", d->d2v->fps_num, paReplace); vsapi->propSetFloat(props, "_AbsoluteTime", (static_cast<double>(d->d2v->fps_den) * n) / static_cast<double>(d->d2v->fps_num), paReplace); if (d->d2v->yuvrgb_scale == PC) vsapi->propSetInt(props, "_ColorRange", 0, paReplace); else if (d->d2v->yuvrgb_scale == TV) vsapi->propSetInt(props, "_ColorRange", 1, paReplace); switch (d->frame->pict_type) { case AV_PICTURE_TYPE_I: vsapi->propSetData(props, "_PictType", "I", 1, paReplace); break; case AV_PICTURE_TYPE_P: vsapi->propSetData(props, "_PictType", "P", 1, paReplace); break; case AV_PICTURE_TYPE_B: vsapi->propSetData(props, "_PictType", "B", 1, paReplace); break; default: break; } int fieldbased; if (d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_PROGRESSIVE) fieldbased = 0; else fieldbased = 1 + !!(d->d2v->gops[d->d2v->frames[n].gop].flags[d->d2v->frames[n].offset] & FRAME_FLAG_TFF); vsapi->propSetInt(props, "_FieldBased", fieldbased, paReplace); vsapi->propSetInt(props, "_ChromaLocation", d->d2v->mpeg_type == 1 ? 1 : 0, paReplace); return f; } void VS_CC d2vFree(void *instanceData, VSCore *core, const VSAPI *vsapi) { d2vData *d = (d2vData *) instanceData; d2vfreep(&d->d2v); decodefreep(&d->dec); av_frame_unref(d->frame); av_freep(&d->frame); free(d); } void VS_CC d2vCreate(const VSMap *in, VSMap *out, void *userData, VSCore *core, const VSAPI *vsapi) { d2vData *data; string msg; bool no_crop; bool rff; int threads; int err; /* Need to get thread info before anything to pass to decodeinit(). */ threads = vsapi->propGetInt(in, "threads", 0, &err); if (err) threads = 0; if (threads < 0) { vsapi->setError(out, "Invalid number of threads."); return; } /* Allocate our private data. */ data = (d2vData *) malloc(sizeof(*data)); if (!data) { vsapi->setError(out, "Cannot allocate private data."); return; } data->d2v = d2vparse((char *) vsapi->propGetData(in, "input", 0, 0), msg); if (!data->d2v) { vsapi->setError(out, msg.c_str()); free(data); return; } data->dec = decodeinit(data->d2v, threads, msg); if (!data->dec) { vsapi->setError(out, msg.c_str()); d2vfreep(&data->d2v); free(data); return; } /* * Make our private data available to libavcodec, and * set our custom get/release_buffer funcs. */ data->dec->avctx->opaque = (void *) data; data->dec->avctx->get_buffer2 = VSGetBuffer; /* Last frame is crashy right now. */ data->vi.numFrames = data->d2v->frames.size(); data->vi.width = data->d2v->width; data->vi.height = data->d2v->height; data->vi.fpsNum = data->d2v->fps_num; data->vi.fpsDen = data->d2v->fps_den; /* Stash the pointer to our core. */ data->core = core; data->api = (VSAPI *) vsapi; /* * Stash our aligned width and height for use with our * custom get_buffer, since it could require this. */ data->aligned_width = FFALIGN(data->vi.width, 16); data->aligned_height = FFALIGN(data->vi.height, 32); data->frame = av_frame_alloc(); if (!data->frame) { vsapi->setError(out, "Cannot allocate AVFrame."); d2vfreep(&data->d2v); decodefreep(&data->dec); free(data); return; } /* * Decode 1 frame to find out how the chroma is subampled. * The first time our custom get_buffer is called, it will * fill in data->vi.format. */ data->format_set = false; err = decodeframe(0, data->d2v, data->dec, data->frame, msg); if (err < 0) { msg.insert(0, "Failed to decode test frame: "); vsapi->setError(out, msg.c_str()); d2vfreep(&data->d2v); decodefreep(&data->dec); av_frame_unref(data->frame); av_freep(&data->frame); free(data); return; } /* See if nocrop is enabled, and set the width/height accordingly. */ no_crop = !!vsapi->propGetInt(in, "nocrop", 0, &err); if (err) no_crop = false; if (no_crop) { data->vi.width = data->aligned_width; data->vi.height = data->aligned_height; } vsapi->createFilter(in, out, "d2vsource", d2vInit, d2vGetFrame, d2vFree, fmUnordered, nfMakeLinear, data, core); rff = !!vsapi->propGetInt(in, "rff", 0, &err); if (err) rff = true; if (rff) { VSPlugin *d2vPlugin = vsapi->getPluginById("com.sources.d2vsource", core); VSPlugin *corePlugin = vsapi->getPluginById("com.vapoursynth.std", core); VSNodeRef *before = vsapi->propGetNode(out, "clip", 0, NULL); VSNodeRef *middle; VSNodeRef *after; VSMap *args = vsapi->createMap(); VSMap *ret; const char *error; vsapi->propSetNode(args, "clip", before, paReplace); vsapi->freeNode(before); ret = vsapi->invoke(corePlugin, "Cache", args); middle = vsapi->propGetNode(ret, "clip", 0, NULL); vsapi->freeMap(ret); vsapi->propSetNode(args, "clip", middle, paReplace); vsapi->propSetData(args, "d2v", vsapi->propGetData(in, "input", 0, NULL), vsapi->propGetDataSize(in, "input", 0, NULL), paReplace); vsapi->freeNode(middle); ret = vsapi->invoke(d2vPlugin, "ApplyRFF", args); vsapi->freeMap(args); error = vsapi->getError(ret); if (error) { vsapi->setError(out, error); vsapi->freeMap(ret); d2vfreep(&data->d2v); decodefreep(&data->dec); av_frame_unref(data->frame); av_freep(&data->frame); free(data); return; } after = vsapi->propGetNode(ret, "clip", 0, NULL); vsapi->propSetNode(out, "clip", after, paReplace); vsapi->freeNode(after); vsapi->freeMap(ret); } } <|endoftext|>
<commit_before>#pragma once #include<memory> #ifndef NDEBUG #include<vector> #include<limits> #endif namespace AnyODE { #if __cplusplus >= 201402L using std::make_unique; #else template <class T, class ...Args> typename std::enable_if < !std::is_array<T>::value, std::unique_ptr<T> >::type make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } template <class T> typename std::enable_if < std::is_array<T>::value, std::unique_ptr<T> >::type make_unique(std::size_t n) { typedef typename std::remove_extent<T>::type RT; return std::unique_ptr<T>(new RT[n]); } #endif #ifdef NDEBUG template<typename T> using buffer_t = std::unique_ptr<T[]>; template<typename T> using buffer_ptr_t = T*; template<typename T> constexpr T* buffer_get_raw_ptr(buffer_t<T>& buf) { return buf.get(); } template<typename T> inline constexpr buffer_t<T> buffer_factory(std::size_t n) { return make_unique<T[]>(n); } #else template<typename T> using buffer_t = std::vector<T>; template<typename T> using buffer_ptr_t = T*; template<typename T> inline constexpr buffer_t<T> buffer_factory(std::size_t n) { return buffer_t<T>(n, std::numeric_limits<T>::signaling_NaN()); } template<typename T> constexpr T* buffer_get_raw_ptr(buffer_t<T>& buf) { return &buf[0]; } #endif } <commit_msg>Added AnyODE::buffer_is_initialized<commit_after>#pragma once #include<memory> #ifndef NDEBUG #include<vector> #include<limits> #endif namespace AnyODE { #if __cplusplus >= 201402L using std::make_unique; #else template <class T, class ...Args> typename std::enable_if < !std::is_array<T>::value, std::unique_ptr<T> >::type make_unique(Args&& ...args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } template <class T> typename std::enable_if < std::is_array<T>::value, std::unique_ptr<T> >::type make_unique(std::size_t n) { typedef typename std::remove_extent<T>::type RT; return std::unique_ptr<T>(new RT[n]); } #endif #ifdef NDEBUG template<typename T> using buffer_t = std::unique_ptr<T[]>; template<typename T> using buffer_ptr_t = T*; template<typename T> constexpr T* buffer_get_raw_ptr(buffer_t<T>& buf) { return buf.get(); } template<typename T> inline constexpr buffer_t<T> buffer_factory(std::size_t n) { return make_unique<T[]>(n); } template<typename T> constexpr bool buffer_is_initialized(const buffer_t<T>& buf) { return (bool)buf; } #else template<typename T> using buffer_t = std::vector<T>; template<typename T> using buffer_ptr_t = T*; template<typename T> inline constexpr buffer_t<T> buffer_factory(std::size_t n) { return buffer_t<T>(n, std::numeric_limits<T>::signaling_NaN()); } template<typename T> constexpr T* buffer_get_raw_ptr(buffer_t<T>& buf) { return &buf[0]; } template<typename T> constexpr bool buffer_is_initialized(const buffer_t<T>& buf) { return buf.size() > 0; } #endif } <|endoftext|>
<commit_before>/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Author(s): Jonathan Poelen */ #define BOOST_AUTO_TEST_MAIN #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TestAuthentifierNew #include <boost/test/auto_unit_test.hpp> #include "container/trie.hpp" #include <algorithm> #include <vector> #include <iomanip> using char_trie = container::trie<char>; using flat_char_trie = container::flat_trie<char_trie::value_type>; void str_tree(char_trie const & trie, std::string & s, unsigned depth = 0u) { for (auto & node : trie) { s.append(depth, ' '); s += node.get(); if (node.is_terminal()) { s += " @"; } s += '\n'; str_tree(node.nodes(), s, depth+1); } } template<class Trie, class FwIt> bool disambigus(Trie const & trie, FwIt first, FwIt last, std::string & result) { for (auto & c : *first) { auto pos = trie.find(c); if (pos != trie.end()) { if (last - first == 1) { if (pos->is_terminal()) { result += c; return true; } } else if (!pos->empty() && disambigus(pos->nodes(), first+1, last, result)) { result += c; return true; } } } return false; } #include <sys/time.h> #include <sys/resource.h> BOOST_AUTO_TEST_CASE(TestTrie) { { rlimit rlim{10000000, 10000000}; setrlimit(RLIMIT_AS, &rlim); } std::vector<std::string> strings{"abcd", "abce", "abcehn", "abcehne", "abcehnu", "abcej", "azerty", "abc", "bob", "coco", "paco", "parano"}; std::sort(begin(strings), end(strings)); char_trie trie(begin(strings), end(strings)); std::string s; str_tree(trie, s); BOOST_CHECK_EQUAL( s, "a\n" " b\n" " c @\n" " d @\n" " e @\n" " h\n" " n @\n" " e @\n" " u @\n" " j\n" " z\n" " e\n" " r\n" " t\n" " y @\n" "b\n" " o\n" " b @\n" "c\n" " o\n" " c\n" " o @\n" "p\n" " a\n" " c\n" " o @\n" " r\n" " a\n" " n\n" " o @\n" ); flat_char_trie flat_trie(trie); { std::stringstream oss; auto write = [](std::stringstream & oss, flat_char_trie const & flat_trie) { for (auto & node : flat_trie.all()) { oss << node.get(); if (node.empty()) { oss << " 0 "; } else { oss << std::setw(3) << node.relative_pos() << " "; } oss << node.size() << (node.is_terminal() ? " @\n" : "\n"); } }; write(oss, flat_trie); auto const str1 = oss.str(); BOOST_CHECK_EQUAL( str1, "a 4 2\n" "b 5 1\n" "c 5 1\n" "p 5 1\n" "b 5 1\n" "z 5 1\n" "o 5 1\n" "o 5 1\n" "a 5 2\n" "c 6 2 @\n" "e 7 1\n" "b 0 0 @\n" "c 6 1\n" "c 6 1\n" "r 6 1\n" "d 0 0 @\n" "e 5 2 @\n" "r 6 1\n" "o 0 0 @\n" "o 0 0 @\n" "a 4 1\n" "h 4 1\n" "j 0 0\n" "t 3 1\n" "n 3 1\n" "n 3 2 @\n" "y 0 0 @\n" "o 0 0 @\n" "e 0 0 @\n" "u 0 0 @\n" ); using node_type = flat_char_trie::node_type; std::vector<node_type> nodes; std::string l; while (std::getline(oss, l)) { std::istringstream iss(l); node_type::value_type c; unsigned sz; unsigned pos; char is_terminal = 0; iss >> c >> pos >> sz >> is_terminal; nodes.emplace_back(c, pos, sz, !!is_terminal); } flat_char_trie flat_trie2(std::move(nodes)); write(oss, flat_trie2); BOOST_CHECK_EQUAL(str1, oss.str()); } using letters_t = std::vector<char>; std::vector<letters_t> word{ {'a'}, {'b', 'z'}, {'e'}, {'r'}, {'u', 't'}, // {'y'}, {'y'}, }; s.clear(); if (disambigus(trie, word.begin(), word.end(), s)) { std::cout << s << std::endl; } else { std::cout << "noop\n"; } s.clear(); if (disambigus(flat_trie.nodes(), word.begin(), word.end(), s)) { std::cout << s << std::endl; } else { std::cout << "noop\n"; } } <commit_msg>fixes compilation<commit_after>/* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. Author(s): Jonathan Poelen */ #define BOOST_AUTO_TEST_MAIN #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE TestAuthentifierNew #include <boost/test/auto_unit_test.hpp> #include "container/trie.hpp" #include <algorithm> #include <vector> #include <iomanip> using char_trie = container::trie<char>; using flat_char_trie = container::flat_trie<char_trie::value_type>; void str_tree(char_trie const & trie, std::string & s, unsigned depth = 0u) { for (auto & node : trie) { s.append(depth, ' '); s += node.get(); if (node.is_terminal()) { s += " @"; } s += '\n'; str_tree(node.nodes(), s, depth+1); } } template<class Trie, class FwIt> bool disambigus(Trie const & trie, FwIt first, FwIt last, std::string & result) { for (auto & c : *first) { auto pos = trie.find(c); if (pos != trie.end()) { if (last - first == 1) { if (pos->is_terminal()) { result += c; return true; } } else if (!pos->empty() && disambigus(pos->nodes(), first+1, last, result)) { result += c; return true; } } } return false; } #include <sys/time.h> #include <sys/resource.h> BOOST_AUTO_TEST_CASE(TestTrie) { { rlimit rlim{10000000, 10000000}; setrlimit(RLIMIT_AS, &rlim); } std::vector<std::string> strings{"abcd", "abce", "abcehn", "abcehne", "abcehnu", "abcej", "azerty", "abc", "bob", "coco", "paco", "parano"}; std::sort(begin(strings), end(strings)); char_trie trie(begin(strings), end(strings)); std::string s; str_tree(trie, s); BOOST_CHECK_EQUAL( s, "a\n" " b\n" " c @\n" " d @\n" " e @\n" " h\n" " n @\n" " e @\n" " u @\n" " j\n" " z\n" " e\n" " r\n" " t\n" " y @\n" "b\n" " o\n" " b @\n" "c\n" " o\n" " c\n" " o @\n" "p\n" " a\n" " c\n" " o @\n" " r\n" " a\n" " n\n" " o @\n" ); flat_char_trie flat_trie(trie); { std::stringstream oss; auto write = [](std::stringstream & oss, flat_char_trie const & flat_trie) { for (auto & node : flat_trie.all()) { oss << node.get(); if (node.empty()) { oss << " 0 "; } else { oss << std::setw(3) << node.relative_pos() << " "; } oss << node.size() << (node.is_terminal() ? " @\n" : "\n"); } }; write(oss, flat_trie); auto const str1 = oss.str(); BOOST_CHECK_EQUAL( str1, "a 4 2\n" "b 5 1\n" "c 5 1\n" "p 5 1\n" "b 5 1\n" "z 5 1\n" "o 5 1\n" "o 5 1\n" "a 5 2\n" "c 6 2 @\n" "e 7 1\n" "b 0 0 @\n" "c 6 1\n" "c 6 1\n" "r 6 1\n" "d 0 0 @\n" "e 5 2 @\n" "r 6 1\n" "o 0 0 @\n" "o 0 0 @\n" "a 4 1\n" "h 4 1\n" "j 0 0\n" "t 3 1\n" "n 3 1\n" "n 3 2 @\n" "y 0 0 @\n" "o 0 0 @\n" "e 0 0 @\n" "u 0 0 @\n" ); using node_type = flat_char_trie::node_type; std::vector<node_type> nodes; std::string l; while (std::getline(oss, l)) { std::istringstream iss(l); node_type::value_type c; unsigned sz; unsigned pos; char is_terminal = 0; iss >> c >> pos >> sz >> is_terminal; nodes.emplace_back(c, pos, sz, !!is_terminal); } flat_char_trie flat_trie2(std::move(nodes)); write(oss, flat_trie2); BOOST_CHECK_EQUAL(str1, oss.str()); } } <|endoftext|>
<commit_before>// MFEM Example 6 - Parallel Version // // Compile with: make ex6p // // Sample runs: mpirun -np 4 ex6p -m ../data/square-disc.mesh -o 1 // mpirun -np 4 ex6p -m ../data/square-disc.mesh -o 2 // mpirun -np 4 ex6p -m ../data/square-disc-nurbs.mesh -o 2 // mpirun -np 4 ex6p -m ../data/star.mesh -o 3 // mpirun -np 4 ex6p -m ../data/escher.mesh -o 2 // mpirun -np 4 ex6p -m ../data/fichera.mesh -o 2 // mpirun -np 4 ex6p -m ../data/disc-nurbs.mesh -o 2 // mpirun -np 4 ex6p -m ../data/ball-nurbs.mesh // mpirun -np 4 ex6p -m ../data/pipe-nurbs.mesh // mpirun -np 4 ex6p -m ../data/star-surf.mesh -o 2 // mpirun -np 4 ex6p -m ../data/square-disc-surf.mesh -o 2 // mpirun -np 4 ex6p -m ../data/amr-quad.mesh // // Device sample runs: // mpirun -np 4 ex6p -pa -d cuda // mpirun -np 4 ex6p -pa -d occa-cuda // mpirun -np 4 ex6p -pa -d raja-omp // mpirun -np 4 ex6p -pa -d ceed-cpu // mpirun -np 4 ex6p -pa -d ceed-cuda // // Description: This is a version of Example 1 with a simple adaptive mesh // refinement loop. The problem being solved is again the Laplace // equation -Delta u = 1 with homogeneous Dirichlet boundary // conditions. The problem is solved on a sequence of meshes which // are locally refined in a conforming (triangles, tetrahedrons) // or non-conforming (quadrilaterals, hexahedra) manner according // to a simple ZZ error estimator. // // The example demonstrates MFEM's capability to work with both // conforming and nonconforming refinements, in 2D and 3D, on // linear, curved and surface meshes. Interpolation of functions // from coarse to fine meshes, as well as persistent GLVis // visualization are also illustrated. // // We recommend viewing Example 1 before viewing this example. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 1. Initialize MPI. int num_procs, myid; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // 2. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; bool pa = false; int max_dofs = 50000; const char *device_config = "cpu"; bool visualization = true; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)."); args.AddOption(&max_dofs, "-md", "--max-dofs", "Maximum number of degrees of freedom for the AMR loop."); args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa", "--no-partial-assembly", "Enable Partial Assembly."); args.AddOption(&device_config, "-d", "--device", "Device configuration string, see Device::Configure()."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { if (myid == 0) { args.PrintUsage(cout); } MPI_Finalize(); return 1; } if (myid == 0) { args.PrintOptions(cout); } // 3. Enable hardware devices such as GPUs, and programming models such as // CUDA, OCCA, RAJA and OpenMP based on command line options. Device device(device_config); if (myid == 0) { device.Print(); } // 4. Read the (serial) mesh from the given mesh file on all processors. We // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface // and volume meshes with the same code. Mesh *mesh = new Mesh(mesh_file, 1, 1); int dim = mesh->Dimension(); int sdim = mesh->SpaceDimension(); // 5. Refine the serial mesh on all processors to increase the resolution. // Also project a NURBS mesh to a piecewise-quadratic curved mesh. Make // sure that the mesh is non-conforming. if (mesh->NURBSext) { mesh->UniformRefinement(); mesh->SetCurvature(2); } mesh->EnsureNCMesh(); // 6. Define a parallel mesh by partitioning the serial mesh. // Once the parallel mesh is defined, the serial mesh can be deleted. ParMesh pmesh(MPI_COMM_WORLD, *mesh); delete mesh; MFEM_VERIFY(pmesh.bdr_attributes.Size() > 0, "Boundary attributes required in the mesh."); Array<int> ess_bdr(pmesh.bdr_attributes.Max()); ess_bdr = 1; // 7. Define a finite element space on the mesh. The polynomial order is // one (linear) by default, but this can be changed on the command line. H1_FECollection fec(order, dim); ParFiniteElementSpace fespace(&pmesh, &fec); // 8. As in Example 1p, we set up bilinear and linear forms corresponding to // the Laplace problem -\Delta u = 1. We don't assemble the discrete // problem yet, this will be done in the main loop. ParBilinearForm a(&fespace); if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); } ParLinearForm b(&fespace); ConstantCoefficient one(1.0); BilinearFormIntegrator *integ = new DiffusionIntegrator(one); a.AddDomainIntegrator(integ); b.AddDomainIntegrator(new DomainLFIntegrator(one)); // 9. The solution vector x and the associated finite element grid function // will be maintained over the AMR iterations. We initialize it to zero. ParGridFunction x(&fespace); x = 0; // 10. Connect to GLVis. char vishost[] = "localhost"; int visport = 19916; socketstream sout; if (visualization) { sout.open(vishost, visport); if (!sout) { if (myid == 0) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; cout << "GLVis visualization disabled.\n"; } visualization = false; } sout.precision(8); } // 11. Set up an error estimator. Here we use the Zienkiewicz-Zhu estimator // with L2 projection in the smoothing step to better handle hanging // nodes and parallel partitioning. We need to supply a space for the // discontinuous flux (L2) and a space for the smoothed flux (H(div) is // used here). L2_FECollection flux_fec(order, dim); ParFiniteElementSpace flux_fes(&pmesh, &flux_fec, sdim); RT_FECollection smooth_flux_fec(order-1, dim); ParFiniteElementSpace smooth_flux_fes(&pmesh, &smooth_flux_fec); // Another possible option for the smoothed flux space: // H1_FECollection smooth_flux_fec(order, dim); // ParFiniteElementSpace smooth_flux_fes(&pmesh, &smooth_flux_fec, dim); L2ZienkiewiczZhuEstimator estimator(*integ, x, flux_fes, smooth_flux_fes); // 12. A refiner selects and refines elements based on a refinement strategy. // The strategy here is to refine elements with errors larger than a // fraction of the maximum element error. Other strategies are possible. // The refiner will call the given error estimator. ThresholdRefiner refiner(estimator); refiner.SetTotalErrorFraction(0.7); // 13. The main AMR loop. In each iteration we solve the problem on the // current mesh, visualize the solution, and refine the mesh. for (int it = 0; ; it++) { HYPRE_Int global_dofs = fespace.GlobalTrueVSize(); if (myid == 0) { cout << "\nAMR iteration " << it << endl; cout << "Number of unknowns: " << global_dofs << endl; } // 14. Assemble the right-hand side and determine the list of true // (i.e. parallel conforming) essential boundary dofs. Array<int> ess_tdof_list; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); b.Assemble(); // 15. Assemble the stiffness matrix. Note that MFEM doesn't care at this // point that the mesh is nonconforming and parallel. The FE space is // considered 'cut' along hanging edges/faces, and also across // processor boundaries. a.Assemble(); // 16. Create the parallel linear system: eliminate boundary conditions. // The system will be solved for true (unconstrained/unique) DOFs only. OperatorPtr A; Vector B, X; const int copy_interior = 1; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B, copy_interior); // 17. Solve the linear system A X = B. // * With full assembly, use the BoomerAMG preconditioner from hypre. // * With partial assembly, use no preconditioner, for now. HypreBoomerAMG *amg = NULL; if (!pa) { amg = new HypreBoomerAMG; amg->SetPrintLevel(0); } CGSolver cg(MPI_COMM_WORLD); cg.SetRelTol(1e-6); cg.SetMaxIter(2000); cg.SetPrintLevel(3); // print the first and the last iterations only if (amg) { cg.SetPreconditioner(*amg); } cg.SetOperator(*A); cg.Mult(B, X); delete amg; // 18. Switch back to the host and extract the parallel grid function // corresponding to the finite element approximation X. This is the // local solution on each processor. a.RecoverFEMSolution(X, b, x); // 19. Send the solution by socket to a GLVis server. if (visualization) { sout << "parallel " << num_procs << " " << myid << "\n"; sout << "solution\n" << pmesh << x << flush; } if (global_dofs > max_dofs) { if (myid == 0) { cout << "Reached the maximum number of dofs. Stop." << endl; } break; } // 20. Call the refiner to modify the mesh. The refiner calls the error // estimator to obtain element errors, then it selects elements to be // refined and finally it modifies the mesh. The Stop() method can be // used to determine if a stopping criterion was met. refiner.Apply(pmesh); if (refiner.Stop()) { if (myid == 0) { cout << "Stopping criterion satisfied. Stop." << endl; } break; } // 21. Update the finite element space (recalculate the number of DOFs, // etc.) and create a grid function update matrix. Apply the matrix // to any GridFunctions over the space. In this case, the update // matrix is an interpolation matrix so the updated GridFunction will // still represent the same function as before refinement. fespace.Update(); x.Update(); // 22. Load balance the mesh, and update the space and solution. Currently // available only for nonconforming meshes. if (pmesh.Nonconforming()) { pmesh.Rebalance(); // Update the space and the GridFunction. This time the update matrix // redistributes the GridFunction among the processors. fespace.Update(); x.Update(); } // 23. Inform also the bilinear and linear forms that the space has // changed. a.Update(); b.Update(); } MPI_Finalize(); return 0; } <commit_msg>Sync ex6p max_dofs with master<commit_after>// MFEM Example 6 - Parallel Version // // Compile with: make ex6p // // Sample runs: mpirun -np 4 ex6p -m ../data/square-disc.mesh -o 1 // mpirun -np 4 ex6p -m ../data/square-disc.mesh -o 2 // mpirun -np 4 ex6p -m ../data/square-disc-nurbs.mesh -o 2 // mpirun -np 4 ex6p -m ../data/star.mesh -o 3 // mpirun -np 4 ex6p -m ../data/escher.mesh -o 2 // mpirun -np 4 ex6p -m ../data/fichera.mesh -o 2 // mpirun -np 4 ex6p -m ../data/disc-nurbs.mesh -o 2 // mpirun -np 4 ex6p -m ../data/ball-nurbs.mesh // mpirun -np 4 ex6p -m ../data/pipe-nurbs.mesh // mpirun -np 4 ex6p -m ../data/star-surf.mesh -o 2 // mpirun -np 4 ex6p -m ../data/square-disc-surf.mesh -o 2 // mpirun -np 4 ex6p -m ../data/amr-quad.mesh // // Device sample runs: // mpirun -np 4 ex6p -pa -d cuda // mpirun -np 4 ex6p -pa -d occa-cuda // mpirun -np 4 ex6p -pa -d raja-omp // mpirun -np 4 ex6p -pa -d ceed-cpu // mpirun -np 4 ex6p -pa -d ceed-cuda // // Description: This is a version of Example 1 with a simple adaptive mesh // refinement loop. The problem being solved is again the Laplace // equation -Delta u = 1 with homogeneous Dirichlet boundary // conditions. The problem is solved on a sequence of meshes which // are locally refined in a conforming (triangles, tetrahedrons) // or non-conforming (quadrilaterals, hexahedra) manner according // to a simple ZZ error estimator. // // The example demonstrates MFEM's capability to work with both // conforming and nonconforming refinements, in 2D and 3D, on // linear, curved and surface meshes. Interpolation of functions // from coarse to fine meshes, as well as persistent GLVis // visualization are also illustrated. // // We recommend viewing Example 1 before viewing this example. #include "mfem.hpp" #include <fstream> #include <iostream> using namespace std; using namespace mfem; int main(int argc, char *argv[]) { // 1. Initialize MPI. int num_procs, myid; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); MPI_Comm_rank(MPI_COMM_WORLD, &myid); // 2. Parse command-line options. const char *mesh_file = "../data/star.mesh"; int order = 1; bool pa = false; int max_dofs = 100000; const char *device_config = "cpu"; bool visualization = true; OptionsParser args(argc, argv); args.AddOption(&mesh_file, "-m", "--mesh", "Mesh file to use."); args.AddOption(&order, "-o", "--order", "Finite element order (polynomial degree)."); args.AddOption(&max_dofs, "-md", "--max-dofs", "Maximum number of degrees of freedom for the AMR loop."); args.AddOption(&pa, "-pa", "--partial-assembly", "-no-pa", "--no-partial-assembly", "Enable Partial Assembly."); args.AddOption(&device_config, "-d", "--device", "Device configuration string, see Device::Configure()."); args.AddOption(&visualization, "-vis", "--visualization", "-no-vis", "--no-visualization", "Enable or disable GLVis visualization."); args.Parse(); if (!args.Good()) { if (myid == 0) { args.PrintUsage(cout); } MPI_Finalize(); return 1; } if (myid == 0) { args.PrintOptions(cout); } // 3. Enable hardware devices such as GPUs, and programming models such as // CUDA, OCCA, RAJA and OpenMP based on command line options. Device device(device_config); if (myid == 0) { device.Print(); } // 4. Read the (serial) mesh from the given mesh file on all processors. We // can handle triangular, quadrilateral, tetrahedral, hexahedral, surface // and volume meshes with the same code. Mesh *mesh = new Mesh(mesh_file, 1, 1); int dim = mesh->Dimension(); int sdim = mesh->SpaceDimension(); // 5. Refine the serial mesh on all processors to increase the resolution. // Also project a NURBS mesh to a piecewise-quadratic curved mesh. Make // sure that the mesh is non-conforming. if (mesh->NURBSext) { mesh->UniformRefinement(); mesh->SetCurvature(2); } mesh->EnsureNCMesh(); // 6. Define a parallel mesh by partitioning the serial mesh. // Once the parallel mesh is defined, the serial mesh can be deleted. ParMesh pmesh(MPI_COMM_WORLD, *mesh); delete mesh; MFEM_VERIFY(pmesh.bdr_attributes.Size() > 0, "Boundary attributes required in the mesh."); Array<int> ess_bdr(pmesh.bdr_attributes.Max()); ess_bdr = 1; // 7. Define a finite element space on the mesh. The polynomial order is // one (linear) by default, but this can be changed on the command line. H1_FECollection fec(order, dim); ParFiniteElementSpace fespace(&pmesh, &fec); // 8. As in Example 1p, we set up bilinear and linear forms corresponding to // the Laplace problem -\Delta u = 1. We don't assemble the discrete // problem yet, this will be done in the main loop. ParBilinearForm a(&fespace); if (pa) { a.SetAssemblyLevel(AssemblyLevel::PARTIAL); } ParLinearForm b(&fespace); ConstantCoefficient one(1.0); BilinearFormIntegrator *integ = new DiffusionIntegrator(one); a.AddDomainIntegrator(integ); b.AddDomainIntegrator(new DomainLFIntegrator(one)); // 9. The solution vector x and the associated finite element grid function // will be maintained over the AMR iterations. We initialize it to zero. ParGridFunction x(&fespace); x = 0; // 10. Connect to GLVis. char vishost[] = "localhost"; int visport = 19916; socketstream sout; if (visualization) { sout.open(vishost, visport); if (!sout) { if (myid == 0) { cout << "Unable to connect to GLVis server at " << vishost << ':' << visport << endl; cout << "GLVis visualization disabled.\n"; } visualization = false; } sout.precision(8); } // 11. Set up an error estimator. Here we use the Zienkiewicz-Zhu estimator // with L2 projection in the smoothing step to better handle hanging // nodes and parallel partitioning. We need to supply a space for the // discontinuous flux (L2) and a space for the smoothed flux (H(div) is // used here). L2_FECollection flux_fec(order, dim); ParFiniteElementSpace flux_fes(&pmesh, &flux_fec, sdim); RT_FECollection smooth_flux_fec(order-1, dim); ParFiniteElementSpace smooth_flux_fes(&pmesh, &smooth_flux_fec); // Another possible option for the smoothed flux space: // H1_FECollection smooth_flux_fec(order, dim); // ParFiniteElementSpace smooth_flux_fes(&pmesh, &smooth_flux_fec, dim); L2ZienkiewiczZhuEstimator estimator(*integ, x, flux_fes, smooth_flux_fes); // 12. A refiner selects and refines elements based on a refinement strategy. // The strategy here is to refine elements with errors larger than a // fraction of the maximum element error. Other strategies are possible. // The refiner will call the given error estimator. ThresholdRefiner refiner(estimator); refiner.SetTotalErrorFraction(0.7); // 13. The main AMR loop. In each iteration we solve the problem on the // current mesh, visualize the solution, and refine the mesh. for (int it = 0; ; it++) { HYPRE_Int global_dofs = fespace.GlobalTrueVSize(); if (myid == 0) { cout << "\nAMR iteration " << it << endl; cout << "Number of unknowns: " << global_dofs << endl; } // 14. Assemble the right-hand side and determine the list of true // (i.e. parallel conforming) essential boundary dofs. Array<int> ess_tdof_list; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); b.Assemble(); // 15. Assemble the stiffness matrix. Note that MFEM doesn't care at this // point that the mesh is nonconforming and parallel. The FE space is // considered 'cut' along hanging edges/faces, and also across // processor boundaries. a.Assemble(); // 16. Create the parallel linear system: eliminate boundary conditions. // The system will be solved for true (unconstrained/unique) DOFs only. OperatorPtr A; Vector B, X; const int copy_interior = 1; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B, copy_interior); // 17. Solve the linear system A X = B. // * With full assembly, use the BoomerAMG preconditioner from hypre. // * With partial assembly, use no preconditioner, for now. HypreBoomerAMG *amg = NULL; if (!pa) { amg = new HypreBoomerAMG; amg->SetPrintLevel(0); } CGSolver cg(MPI_COMM_WORLD); cg.SetRelTol(1e-6); cg.SetMaxIter(2000); cg.SetPrintLevel(3); // print the first and the last iterations only if (amg) { cg.SetPreconditioner(*amg); } cg.SetOperator(*A); cg.Mult(B, X); delete amg; // 18. Switch back to the host and extract the parallel grid function // corresponding to the finite element approximation X. This is the // local solution on each processor. a.RecoverFEMSolution(X, b, x); // 19. Send the solution by socket to a GLVis server. if (visualization) { sout << "parallel " << num_procs << " " << myid << "\n"; sout << "solution\n" << pmesh << x << flush; } if (global_dofs > max_dofs) { if (myid == 0) { cout << "Reached the maximum number of dofs. Stop." << endl; } break; } // 20. Call the refiner to modify the mesh. The refiner calls the error // estimator to obtain element errors, then it selects elements to be // refined and finally it modifies the mesh. The Stop() method can be // used to determine if a stopping criterion was met. refiner.Apply(pmesh); if (refiner.Stop()) { if (myid == 0) { cout << "Stopping criterion satisfied. Stop." << endl; } break; } // 21. Update the finite element space (recalculate the number of DOFs, // etc.) and create a grid function update matrix. Apply the matrix // to any GridFunctions over the space. In this case, the update // matrix is an interpolation matrix so the updated GridFunction will // still represent the same function as before refinement. fespace.Update(); x.Update(); // 22. Load balance the mesh, and update the space and solution. Currently // available only for nonconforming meshes. if (pmesh.Nonconforming()) { pmesh.Rebalance(); // Update the space and the GridFunction. This time the update matrix // redistributes the GridFunction among the processors. fespace.Update(); x.Update(); } // 23. Inform also the bilinear and linear forms that the space has // changed. a.Update(); b.Update(); } MPI_Finalize(); return 0; } <|endoftext|>
<commit_before>/** * \file Exception.hpp * \brief Defines custom exceptions used in framework. */ #ifndef ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #define ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #pragma once #include "Core.hpp" #include "Log.hpp" #include <stdexcept> namespace atlas { namespace core { /** * \class Exception * \brief Defines a custom exception. * * This class extends the exception class provided by the STD library * and links it to the existing logging system so error messages * can always be displayed. */ class Exception : public std::exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(const char* msg) : message(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(std::string const& msg) : message(msg) { } /** * Constructs the error message for the exception with the * following format: \verbatim Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } protected: /** * \var message * Contains the message that is displayed whenever the exception * is thrown. */ std::string message; }; /** * \class RuntimeException * \brief Defines an exception for runtime errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class RuntimeException : public Exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Runtime Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Runtime Exception : " + message; CRITICAL_LOG(text); return text.c_str(); } }; /** * \class LogicException * \brief Defines an exception for logic errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class LogicException : public Exception { /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Logic Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Logic Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } }; } } #endif<commit_msg>[brief] Adds missing public declaration to LogicException.<commit_after>/** * \file Exception.hpp * \brief Defines custom exceptions used in framework. */ #ifndef ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #define ATLAS_INCLUDE_ATLAS_CORE_EXCEPTION_HPP #pragma once #include "Core.hpp" #include "Log.hpp" #include <stdexcept> namespace atlas { namespace core { /** * \class Exception * \brief Defines a custom exception. * * This class extends the exception class provided by the STD library * and links it to the existing logging system so error messages * can always be displayed. */ class Exception : public std::exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(const char* msg) : message(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ Exception(std::string const& msg) : message(msg) { } /** * Constructs the error message for the exception with the * following format: \verbatim Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } protected: /** * \var message * Contains the message that is displayed whenever the exception * is thrown. */ std::string message; }; /** * \class RuntimeException * \brief Defines an exception for runtime errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class RuntimeException : public Exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ RuntimeException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Runtime Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Runtime Exception : " + message; CRITICAL_LOG(text); return text.c_str(); } }; /** * \class LogicException * \brief Defines an exception for logic errors. * * Extends the base Exception class and modifies the final error * message that is produced. This is mostly for code readability so * different kinds of errors can be differentiated. */ class LogicException : public Exception { public: /** * Standard constructor with char array. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(const char* msg) : Exception(msg) { } /** * Standard constructor with string. * * \param[in] msg The message to be displayed when the exception * is triggered. */ LogicException(std::string const& msg) : Exception(msg) { } /** * Constructs the error message for the exception with the * following format: * \verbatim Logic Exception: <message> \endverbatim. * The function then outputs the message to the log using the * critical flag and then returns the message. * * \return The message with the specified format. */ virtual const char* what() const throw() { std::string text = "Logic Exception: " + message; CRITICAL_LOG(text); return text.c_str(); } }; } } #endif<|endoftext|>
<commit_before>//----------------------------------------------------------------------------- // // Copyright (C) 2015 David Hill // // See COPYING for license information. // //----------------------------------------------------------------------------- // // Store class. // //----------------------------------------------------------------------------- #ifndef ACSVM__Store_H__ #define ACSVM__Store_H__ #include "Types.hpp" #include <new> #include <utility> //----------------------------------------------------------------------------| // Types | // namespace ACSVM { // // Store // // Manages storage area for locals. // template<typename T> class Store { public: Store() : store{nullptr}, storeEnd{nullptr}, active{nullptr}, activeEnd{nullptr} {} ~Store() {clear(); ::operator delete(store);} // operator [] T &operator [] (std::size_t idx) {return active[idx];} // // alloc // void alloc(std::size_t count) { // Possibly reallocate underlying storage. if(static_cast<std::size_t>(storeEnd - activeEnd) < count) { // Save pointers as indexes. std::size_t activeIdx = active - store; std::size_t activeEndIdx = activeEnd - store; std::size_t storeEndIdx = storeEnd - store; // Calculate new array size. if(SIZE_MAX / sizeof(T) - storeEndIdx < count * 2) throw std::bad_alloc(); storeEndIdx += count * 2; // Allocate and initialize new array. T *storeNew = static_cast<T *>(::operator new(storeEndIdx * sizeof(T))); for(T *itrNew = storeNew, *itr = activeEnd, *end = store; itr != end;) { new(itrNew++) T(std::move(*--itr)); itr->~T(); } // Free old array. ::operator delete(store); // Restore pointers. store = storeNew; active = store + activeIdx; activeEnd = store + activeEndIdx; storeEnd = store + storeEndIdx; } active = activeEnd; while(count--) new(activeEnd++) T{}; } // // allocLoad // // Allocates storage for loading from saved state. countFull elements are // value-initialized and count elements are made available. That is, they // should correspond to a prior call to sizeFull and size, respectively. // void allocLoad(std::size_t countFull, std::size_t count) { clear(); alloc(countFull); active = activeEnd - count; } // beginFull T *beginFull() {return store;} T const *beginFull() const {return store;} // // clear // void clear() { while(activeEnd != store) (--activeEnd)->~T(); active = store; } // dataFull T const *dataFull() const {return store;} // end T *end() {return activeEnd;} T const *end() const {return activeEnd;} // // free // // count must be the size (in elements)of the previous allocation. // void free(std::size_t count) { while(activeEnd != active) (--activeEnd)->~T(); active -= count; } // size std::size_t size() const {return activeEnd - active;} // sizeFull std::size_t sizeFull() const {return activeEnd - store;} private: T *store, *storeEnd; T *active, *activeEnd; }; } #endif//ACSVM__Store_H__ <commit_msg>Fixed Store::alloc's reallocation iterating old values in wrong order.<commit_after>//----------------------------------------------------------------------------- // // Copyright (C) 2015 David Hill // // See COPYING for license information. // //----------------------------------------------------------------------------- // // Store class. // //----------------------------------------------------------------------------- #ifndef ACSVM__Store_H__ #define ACSVM__Store_H__ #include "Types.hpp" #include <new> #include <utility> //----------------------------------------------------------------------------| // Types | // namespace ACSVM { // // Store // // Manages storage area for locals. // template<typename T> class Store { public: Store() : store{nullptr}, storeEnd{nullptr}, active{nullptr}, activeEnd{nullptr} {} ~Store() {clear(); ::operator delete(store);} // operator [] T &operator [] (std::size_t idx) {return active[idx];} // // alloc // void alloc(std::size_t count) { // Possibly reallocate underlying storage. if(static_cast<std::size_t>(storeEnd - activeEnd) < count) { // Save pointers as indexes. std::size_t activeIdx = active - store; std::size_t activeEndIdx = activeEnd - store; std::size_t storeEndIdx = storeEnd - store; // Calculate new array size. if(SIZE_MAX / sizeof(T) - storeEndIdx < count * 2) throw std::bad_alloc(); storeEndIdx += count * 2; // Allocate and initialize new array. T *storeNew = static_cast<T *>(::operator new(storeEndIdx * sizeof(T))); for(T *out = storeNew, *in = store, *end = activeEnd; in != end; ++out, ++in) { new(out) T(std::move(*in)); in->~T(); } // Free old array. ::operator delete(store); // Restore pointers. store = storeNew; active = store + activeIdx; activeEnd = store + activeEndIdx; storeEnd = store + storeEndIdx; } active = activeEnd; while(count--) new(activeEnd++) T{}; } // // allocLoad // // Allocates storage for loading from saved state. countFull elements are // value-initialized and count elements are made available. That is, they // should correspond to a prior call to sizeFull and size, respectively. // void allocLoad(std::size_t countFull, std::size_t count) { clear(); alloc(countFull); active = activeEnd - count; } // begin T *begin() {return active;} T const *begin() const {return active;} // beginFull T *beginFull() {return store;} T const *beginFull() const {return store;} // // clear // void clear() { while(activeEnd != store) (--activeEnd)->~T(); active = store; } // dataFull T const *dataFull() const {return store;} // end T *end() {return activeEnd;} T const *end() const {return activeEnd;} // // free // // count must be the size (in elements) of the previous allocation. // void free(std::size_t count) { while(activeEnd != active) (--activeEnd)->~T(); active -= count; } // size std::size_t size() const {return activeEnd - active;} // sizeFull std::size_t sizeFull() const {return activeEnd - store;} private: T *store, *storeEnd; T *active, *activeEnd; }; } #endif//ACSVM__Store_H__ <|endoftext|>
<commit_before><commit_msg>add test example code for arduino tsp<commit_after><|endoftext|>
<commit_before>/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "xmlattribute.h" #include <array> #include <libxml/tree.h> #include <string> #include "namespaces.h" namespace libcellml { /** * @brief The XmlAttribute::XmlAttributeImpl struct. * * This struct is the private implementation struct for the XmlAttribute class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct XmlAttribute::XmlAttributeImpl { xmlAttrPtr mXmlAttributePtr; }; XmlAttribute::XmlAttribute() : mPimpl(new XmlAttributeImpl()) { } XmlAttribute::~XmlAttribute() { delete mPimpl; } void XmlAttribute::setXmlAttribute(const xmlAttrPtr &attribute) { mPimpl->mXmlAttributePtr = attribute; } std::string XmlAttribute::namespaceUri() const { if (mPimpl->mXmlAttributePtr->ns == nullptr) { return {}; } return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->href); } std::string XmlAttribute::namespacePrefix() const { if (mPimpl->mXmlAttributePtr->ns == nullptr || mPimpl->mXmlAttributePtr->ns->prefix == nullptr) { return {}; } return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->prefix); } bool XmlAttribute::inNamespaceUri(const char *ns) const { return xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0; } bool XmlAttribute::isType(const char *name, const char *ns) const { return (xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0) && (xmlStrcmp(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(name)) == 0); } bool XmlAttribute::isCellmlType(const char *name) const { return isType(name, CELLML_2_0_NS); } std::string XmlAttribute::name() const { return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->name); } std::string XmlAttribute::value() const { std::string valueString; if ((mPimpl->mXmlAttributePtr->name != nullptr) && (mPimpl->mXmlAttributePtr->parent != nullptr)) { xmlChar *value = xmlGetProp(mPimpl->mXmlAttributePtr->parent, mPimpl->mXmlAttributePtr->name); valueString = std::string(reinterpret_cast<const char *>(value)); xmlFree(value); } return valueString; } XmlAttributePtr XmlAttribute::next() const { xmlAttrPtr next = mPimpl->mXmlAttributePtr->next; XmlAttributePtr nextHandle = nullptr; if (next != nullptr) { nextHandle = std::make_shared<XmlAttribute>(); nextHandle->setXmlAttribute(next); } return nextHandle; } void XmlAttribute::removeAttribute() { xmlRemoveProp(mPimpl->mXmlAttributePtr); } void XmlAttribute::setNamespacePrefix(const std::string &prefix) { std::array<xmlChar, 50> buffer = {}; xmlNodePtr parent = mPimpl->mXmlAttributePtr->parent; xmlChar *fullelemname = xmlBuildQName(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(prefix.c_str()), buffer.data(), buffer.size()); auto oldAttribute = mPimpl->mXmlAttributePtr; mPimpl->mXmlAttributePtr = xmlSetProp(parent, fullelemname, reinterpret_cast<const xmlChar *>(value().c_str())); xmlRemoveProp(oldAttribute); } } // namespace libcellml <commit_msg>Add static cast when passing size_t length of array to LibXml2.<commit_after>/* Copyright libCellML Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "xmlattribute.h" #include <array> #include <libxml/tree.h> #include <string> #include "namespaces.h" namespace libcellml { /** * @brief The XmlAttribute::XmlAttributeImpl struct. * * This struct is the private implementation struct for the XmlAttribute class. Separating * the implementation from the definition allows for greater flexibility when * distributing the code. */ struct XmlAttribute::XmlAttributeImpl { xmlAttrPtr mXmlAttributePtr; }; XmlAttribute::XmlAttribute() : mPimpl(new XmlAttributeImpl()) { } XmlAttribute::~XmlAttribute() { delete mPimpl; } void XmlAttribute::setXmlAttribute(const xmlAttrPtr &attribute) { mPimpl->mXmlAttributePtr = attribute; } std::string XmlAttribute::namespaceUri() const { if (mPimpl->mXmlAttributePtr->ns == nullptr) { return {}; } return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->href); } std::string XmlAttribute::namespacePrefix() const { if (mPimpl->mXmlAttributePtr->ns == nullptr || mPimpl->mXmlAttributePtr->ns->prefix == nullptr) { return {}; } return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->ns->prefix); } bool XmlAttribute::inNamespaceUri(const char *ns) const { return xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0; } bool XmlAttribute::isType(const char *name, const char *ns) const { return (xmlStrcmp(reinterpret_cast<const xmlChar *>(namespaceUri().c_str()), reinterpret_cast<const xmlChar *>(ns)) == 0) && (xmlStrcmp(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(name)) == 0); } bool XmlAttribute::isCellmlType(const char *name) const { return isType(name, CELLML_2_0_NS); } std::string XmlAttribute::name() const { return reinterpret_cast<const char *>(mPimpl->mXmlAttributePtr->name); } std::string XmlAttribute::value() const { std::string valueString; if ((mPimpl->mXmlAttributePtr->name != nullptr) && (mPimpl->mXmlAttributePtr->parent != nullptr)) { xmlChar *value = xmlGetProp(mPimpl->mXmlAttributePtr->parent, mPimpl->mXmlAttributePtr->name); valueString = std::string(reinterpret_cast<const char *>(value)); xmlFree(value); } return valueString; } XmlAttributePtr XmlAttribute::next() const { xmlAttrPtr next = mPimpl->mXmlAttributePtr->next; XmlAttributePtr nextHandle = nullptr; if (next != nullptr) { nextHandle = std::make_shared<XmlAttribute>(); nextHandle->setXmlAttribute(next); } return nextHandle; } void XmlAttribute::removeAttribute() { xmlRemoveProp(mPimpl->mXmlAttributePtr); } void XmlAttribute::setNamespacePrefix(const std::string &prefix) { std::array<xmlChar, 50> buffer = {}; xmlNodePtr parent = mPimpl->mXmlAttributePtr->parent; xmlChar *fullelemname = xmlBuildQName(mPimpl->mXmlAttributePtr->name, reinterpret_cast<const xmlChar *>(prefix.c_str()), buffer.data(), static_cast<int>(buffer.size())); auto oldAttribute = mPimpl->mXmlAttributePtr; mPimpl->mXmlAttributePtr = xmlSetProp(parent, fullelemname, reinterpret_cast<const xmlChar *>(value().c_str())); xmlRemoveProp(oldAttribute); } } // namespace libcellml <|endoftext|>
<commit_before>#ifndef CLUE_FORMATTING_BASE__ #define CLUE_FORMATTING_BASE__ #include <clue/config.hpp> #include <clue/type_traits.hpp> #include <clue/string_view.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstdint> #include <cstdarg> #include <string> #include <stdexcept> #include <algorithm> namespace clue { namespace fmt { //=============================================== // // Formatting flags // //=============================================== enum { uppercase = 0x01, padzeros = 0x02, showpos = 0x04 }; typedef unsigned int flag_t; //=============================================== // // C-format // //=============================================== inline ::std::string c_sprintf(const char *fmt, ...) { std::va_list args0, args; va_start(args0, fmt); va_copy(args, args0); size_t n = (size_t)::std::vsnprintf(nullptr, 0, fmt, args0); va_end(args0); ::std::string str(n, '\0'); if (n > 0) { ::std::vsnprintf(const_cast<char*>(str.data()), n+1, fmt, args); } va_end(args); return ::std::move(str); } //=============================================== // // Formatter implementation helper // //=============================================== template<typename Fmt, typename T, typename charT> size_t formatted_write_unknown_length( const Fmt& fmt, // the formatter const T& x, // the value to be formatted size_t width, // field width bool leftjust, // whether to left-adjust charT *buf, // buffer base size_t buf_len) // buffer size { CLUE_ASSERT(buf_len > width); size_t n = fmt.formatted_write(x, buf, buf_len); CLUE_ASSERT(buf_len > n); if (width > n) { // re-justify size_t np = width - n; if (leftjust) { ::std::fill_n(buf + n, np, static_cast<charT>(' ')); buf[width] = (charT)('\0'); } else { ::std::memmove(buf + np, buf, n * sizeof(charT)); ::std::fill_n(buf, np, static_cast<charT>(' ')); } buf[width] = static_cast<charT>('\0'); return width; } else { return n; } } template<typename Fmt, typename T, typename charT> size_t formatted_write_known_length( const Fmt& fmt, // the formatter const T& x, // the value to be formatted size_t n, // the length of formatted x size_t width, // field width bool leftjust, // whether to left-adjust charT *buf, // buffer base size_t buf_len) // buffer size { CLUE_ASSERT(buf_len > n && buf_len > width); if (width > n) { size_t np = width - n; if (leftjust) { fmt.formatted_write(x, buf, n + 1); ::std::fill_n(buf + n, np, (charT)(' ')); buf[width] = static_cast<charT>('\0'); } else { ::std::fill_n(buf, np, static_cast<charT>(' ')); fmt.formatted_write(x, buf + np, n + 1); } return width; } else { fmt.formatted_write(x, buf, n+1); return n; } } //=============================================== // // Bool formatting // //=============================================== class default_bool_formatter { public: constexpr size_t max_formatted_length(bool x) const noexcept { return x ? 4 : 5; } template<typename charT> size_t formatted_write(bool x, charT *buf, size_t buf_len) const { if (x) { CLUE_ASSERT(buf_len > 4); std::copy_n("true", 5, buf); return 4; } else { CLUE_ASSERT(buf_len > 5); std::copy_n("false", 6, buf); return 5; } } template<typename charT> size_t formatted_write(bool x, size_t width, bool ljust, charT *buf, size_t buf_len) const { return formatted_write_known_length( *this, x, max_formatted_length(x), width, ljust, buf, buf_len); } }; //=============================================== // // Char formatting // //=============================================== class default_char_formatter { public: template<typename charT> constexpr size_t max_formatted_length(charT c) const noexcept { return 1; } template<typename charT> size_t formatted_write(charT c, charT *buf, size_t buf_len) const { buf[0] = c; buf[1] = static_cast<charT>('\0'); return 1; } template<typename charT> size_t formatted_write(charT c, size_t width, bool ljust, charT *buf, size_t buf_len) const { return formatted_write_known_length( *this, c, 1, width, ljust, buf, buf_len); } }; //=============================================== // // String formatting // //=============================================== class default_string_formatter { public: // max_formatted_length template<typename charT> constexpr size_t max_formatted_length(const charT *sz) const noexcept { return ::std::char_traits<charT>::length(sz); } template<typename charT, typename Traits, typename Allocator> constexpr size_t max_formatted_length( const ::std::basic_string<charT, Traits, Allocator>& s) const noexcept { return s.size(); } template<typename charT, typename Traits> constexpr size_t max_formatted_length( const basic_string_view<charT, Traits>& sv) const noexcept { return sv.size(); } // formatted_write template<typename charT> size_t formatted_write( const charT* s, charT *buf, size_t buf_len) const noexcept { const charT *p = s; const charT *pend = s + buf_len; while (*p && p != pend) *buf++ = *p++; *buf = '\0'; return static_cast<size_t>(p - s); } template<typename charT, typename Traits, typename Allocator> size_t formatted_write( const ::std::basic_string<charT, Traits, Allocator>& s, charT *buf, size_t buf_len) const noexcept { return formatted_write_(s.data(), s.size(), buf, buf_len); } template<typename charT, typename Traits> size_t formatted_write( const basic_string_view<charT, Traits>& sv, charT *buf, size_t buf_len) const noexcept { return formatted_write_(sv.data(), sv.size(), buf, buf_len); } // formatted_write (with width & left-just) template<typename charT> size_t formatted_write( const charT* s, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { size_t len = ::std::char_traits<charT>::length(s); return formatted_write_(s, len, width, ljust, buf, buf_len); } template<typename charT, typename Traits, typename Allocator> size_t formatted_write( const ::std::basic_string<charT, Traits, Allocator>& s, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { return formatted_write_(s.data(), s.size(), width, ljust, buf, buf_len); } template<typename charT, typename Traits> size_t formatted_write( const basic_string_view<charT, Traits>& sv, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { return formatted_write_(sv.data(), sv.size(), width, ljust, buf, buf_len); } private: template<typename charT> size_t formatted_write_(const charT *src, size_t n, charT *buf, size_t buf_len) const noexcept { CLUE_ASSERT(n < buf_len); ::std::memcpy(buf, src, n * sizeof(charT)); buf[n] = static_cast<charT>('\0'); return n; } template<typename charT> size_t formatted_write_(const charT *src, size_t n, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { CLUE_ASSERT(n < buf_len && width < buf_len); if (width > n) { size_t np = width - n; if (ljust) { ::std::memcpy(buf, src, n * sizeof(charT)); ::std::fill_n(buf + n, np, ' '); } else { ::std::fill_n(buf, np, ' '); ::std::memcpy(buf + np, src, n * sizeof(charT)); } buf[width] = static_cast<charT>('\0'); return width; } else { ::std::memcpy(buf, src, n * sizeof(charT)); buf[n] = static_cast<charT>('\0'); return n; } } }; //=============================================== // // Generic formatting // //=============================================== template<typename T> struct default_formatter; template<typename T> inline typename default_formatter<decay_t<T>>::type get_default_formatter(const T& x) noexcept { return default_formatter<decay_t<T>>::get(); } template<typename T> using default_formatter_t = typename default_formatter<T>::type; // for bool template<> struct default_formatter<bool> { using type = default_bool_formatter; static constexpr type get() noexcept { return type{}; } }; // for characters and char* #define CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(CHARTYPE) \ template<> struct default_formatter<CHARTYPE> { \ using type = default_char_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; \ template<> struct default_formatter<CHARTYPE*> { \ using type = default_string_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; \ template<> struct default_formatter<const CHARTYPE*> { \ using type = default_string_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(wchar_t) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char16_t) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char32_t) // for string types template<typename charT, typename Traits> struct default_formatter<basic_string_view<charT, Traits>> { using type = default_string_formatter; static constexpr type get() noexcept { return type{}; } }; template<typename charT, typename Traits, typename Allocator> struct default_formatter<::std::basic_string<charT, Traits, Allocator>> { using type = default_string_formatter; static constexpr type get() noexcept { return type{}; } }; // with functions template<typename T, typename Fmt> struct with_fmt_t { const T& value; const Fmt& formatter; }; template<typename T, typename Fmt> struct with_fmt_ex_t { const T& value; const Fmt& formatter; size_t width; bool leftjust; }; template<typename T, typename Fmt> inline enable_if_t<::std::is_class<Fmt>::value, with_fmt_t<T, Fmt>> with(const T& v, const Fmt& fmt) { return with_fmt_t<T, Fmt>{v, fmt}; } template<typename T, typename Fmt> inline enable_if_t<::std::is_class<Fmt>::value, with_fmt_ex_t<T, Fmt>> with(const T& v, const Fmt& fmt, size_t width, bool ljust=false) { return with_fmt_ex_t<T, Fmt>{v, fmt, width, ljust}; } template<typename T> inline with_fmt_ex_t<T, default_formatter_t<decay_t<T>>> with(const T& v, size_t width, bool ljust=false) { return with(v, default_formatter<decay_t<T>>::get(), width, ljust); } } // end namespace fmt } // end namespace clue #endif <commit_msg>some assertions for formatted_write_known_length<commit_after>#ifndef CLUE_FORMATTING_BASE__ #define CLUE_FORMATTING_BASE__ #include <clue/config.hpp> #include <clue/type_traits.hpp> #include <clue/string_view.hpp> #include <cstdio> #include <cstdlib> #include <cstring> #include <cstdint> #include <cstdarg> #include <string> #include <stdexcept> #include <algorithm> namespace clue { namespace fmt { //=============================================== // // Formatting flags // //=============================================== enum { uppercase = 0x01, padzeros = 0x02, showpos = 0x04 }; typedef unsigned int flag_t; //=============================================== // // C-format // //=============================================== inline ::std::string c_sprintf(const char *fmt, ...) { std::va_list args0, args; va_start(args0, fmt); va_copy(args, args0); size_t n = (size_t)::std::vsnprintf(nullptr, 0, fmt, args0); va_end(args0); ::std::string str(n, '\0'); if (n > 0) { ::std::vsnprintf(const_cast<char*>(str.data()), n+1, fmt, args); } va_end(args); return ::std::move(str); } //=============================================== // // Formatter implementation helper // //=============================================== template<typename Fmt, typename T, typename charT> size_t formatted_write_unknown_length( const Fmt& fmt, // the formatter const T& x, // the value to be formatted size_t width, // field width bool leftjust, // whether to left-adjust charT *buf, // buffer base size_t buf_len) // buffer size { CLUE_ASSERT(buf_len > width); size_t n = fmt.formatted_write(x, buf, buf_len); CLUE_ASSERT(buf_len > n); if (width > n) { // re-justify size_t np = width - n; if (leftjust) { ::std::fill_n(buf + n, np, static_cast<charT>(' ')); buf[width] = (charT)('\0'); } else { ::std::memmove(buf + np, buf, n * sizeof(charT)); ::std::fill_n(buf, np, static_cast<charT>(' ')); } buf[width] = static_cast<charT>('\0'); return width; } else { return n; } } template<typename Fmt, typename T, typename charT> size_t formatted_write_known_length( const Fmt& fmt, // the formatter const T& x, // the value to be formatted size_t n, // the length of formatted x size_t width, // field width bool leftjust, // whether to left-adjust charT *buf, // buffer base size_t buf_len) // buffer size { CLUE_ASSERT(buf_len > n && buf_len > width); if (width > n) { size_t np = width - n; if (leftjust) { size_t wlen = fmt.formatted_write(x, buf, n + 1); CLUE_ASSERT(wlen == n); ::std::fill_n(buf + n, np, (charT)(' ')); buf[width] = static_cast<charT>('\0'); } else { ::std::fill_n(buf, np, static_cast<charT>(' ')); size_t wlen = fmt.formatted_write(x, buf + np, n + 1); CLUE_ASSERT(wlen == n); } return width; } else { size_t wlen = fmt.formatted_write(x, buf, n+1); CLUE_ASSERT(wlen == n); return n; } } //=============================================== // // Bool formatting // //=============================================== class default_bool_formatter { public: constexpr size_t max_formatted_length(bool x) const noexcept { return x ? 4 : 5; } template<typename charT> size_t formatted_write(bool x, charT *buf, size_t buf_len) const { if (x) { CLUE_ASSERT(buf_len > 4); std::copy_n("true", 5, buf); return 4; } else { CLUE_ASSERT(buf_len > 5); std::copy_n("false", 6, buf); return 5; } } template<typename charT> size_t formatted_write(bool x, size_t width, bool ljust, charT *buf, size_t buf_len) const { return formatted_write_known_length( *this, x, max_formatted_length(x), width, ljust, buf, buf_len); } }; //=============================================== // // Char formatting // //=============================================== class default_char_formatter { public: template<typename charT> constexpr size_t max_formatted_length(charT c) const noexcept { return 1; } template<typename charT> size_t formatted_write(charT c, charT *buf, size_t buf_len) const { buf[0] = c; buf[1] = static_cast<charT>('\0'); return 1; } template<typename charT> size_t formatted_write(charT c, size_t width, bool ljust, charT *buf, size_t buf_len) const { return formatted_write_known_length( *this, c, 1, width, ljust, buf, buf_len); } }; //=============================================== // // String formatting // //=============================================== class default_string_formatter { public: // max_formatted_length template<typename charT> constexpr size_t max_formatted_length(const charT *sz) const noexcept { return ::std::char_traits<charT>::length(sz); } template<typename charT, typename Traits, typename Allocator> constexpr size_t max_formatted_length( const ::std::basic_string<charT, Traits, Allocator>& s) const noexcept { return s.size(); } template<typename charT, typename Traits> constexpr size_t max_formatted_length( const basic_string_view<charT, Traits>& sv) const noexcept { return sv.size(); } // formatted_write template<typename charT> size_t formatted_write( const charT* s, charT *buf, size_t buf_len) const noexcept { const charT *p = s; const charT *pend = s + buf_len; while (*p && p != pend) *buf++ = *p++; *buf = '\0'; return static_cast<size_t>(p - s); } template<typename charT, typename Traits, typename Allocator> size_t formatted_write( const ::std::basic_string<charT, Traits, Allocator>& s, charT *buf, size_t buf_len) const noexcept { return formatted_write_(s.data(), s.size(), buf, buf_len); } template<typename charT, typename Traits> size_t formatted_write( const basic_string_view<charT, Traits>& sv, charT *buf, size_t buf_len) const noexcept { return formatted_write_(sv.data(), sv.size(), buf, buf_len); } // formatted_write (with width & left-just) template<typename charT> size_t formatted_write( const charT* s, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { size_t len = ::std::char_traits<charT>::length(s); return formatted_write_(s, len, width, ljust, buf, buf_len); } template<typename charT, typename Traits, typename Allocator> size_t formatted_write( const ::std::basic_string<charT, Traits, Allocator>& s, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { return formatted_write_(s.data(), s.size(), width, ljust, buf, buf_len); } template<typename charT, typename Traits> size_t formatted_write( const basic_string_view<charT, Traits>& sv, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { return formatted_write_(sv.data(), sv.size(), width, ljust, buf, buf_len); } private: template<typename charT> size_t formatted_write_(const charT *src, size_t n, charT *buf, size_t buf_len) const noexcept { CLUE_ASSERT(n < buf_len); ::std::memcpy(buf, src, n * sizeof(charT)); buf[n] = static_cast<charT>('\0'); return n; } template<typename charT> size_t formatted_write_(const charT *src, size_t n, size_t width, bool ljust, charT *buf, size_t buf_len) const noexcept { CLUE_ASSERT(n < buf_len && width < buf_len); if (width > n) { size_t np = width - n; if (ljust) { ::std::memcpy(buf, src, n * sizeof(charT)); ::std::fill_n(buf + n, np, ' '); } else { ::std::fill_n(buf, np, ' '); ::std::memcpy(buf + np, src, n * sizeof(charT)); } buf[width] = static_cast<charT>('\0'); return width; } else { ::std::memcpy(buf, src, n * sizeof(charT)); buf[n] = static_cast<charT>('\0'); return n; } } }; //=============================================== // // Generic formatting // //=============================================== template<typename T> struct default_formatter; template<typename T> inline typename default_formatter<decay_t<T>>::type get_default_formatter(const T& x) noexcept { return default_formatter<decay_t<T>>::get(); } template<typename T> using default_formatter_t = typename default_formatter<T>::type; // for bool template<> struct default_formatter<bool> { using type = default_bool_formatter; static constexpr type get() noexcept { return type{}; } }; // for characters and char* #define CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(CHARTYPE) \ template<> struct default_formatter<CHARTYPE> { \ using type = default_char_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; \ template<> struct default_formatter<CHARTYPE*> { \ using type = default_string_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; \ template<> struct default_formatter<const CHARTYPE*> { \ using type = default_string_formatter; \ static constexpr type get() noexcept { return type{}; } \ }; CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(wchar_t) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char16_t) CLUE_DEFINE_DEFAULT_CHAR_AND_STR_FORMATTER(char32_t) // for string types template<typename charT, typename Traits> struct default_formatter<basic_string_view<charT, Traits>> { using type = default_string_formatter; static constexpr type get() noexcept { return type{}; } }; template<typename charT, typename Traits, typename Allocator> struct default_formatter<::std::basic_string<charT, Traits, Allocator>> { using type = default_string_formatter; static constexpr type get() noexcept { return type{}; } }; // with functions template<typename T, typename Fmt> struct with_fmt_t { const T& value; const Fmt& formatter; }; template<typename T, typename Fmt> struct with_fmt_ex_t { const T& value; const Fmt& formatter; size_t width; bool leftjust; }; template<typename T, typename Fmt> inline enable_if_t<::std::is_class<Fmt>::value, with_fmt_t<T, Fmt>> with(const T& v, const Fmt& fmt) { return with_fmt_t<T, Fmt>{v, fmt}; } template<typename T, typename Fmt> inline enable_if_t<::std::is_class<Fmt>::value, with_fmt_ex_t<T, Fmt>> with(const T& v, const Fmt& fmt, size_t width, bool ljust=false) { return with_fmt_ex_t<T, Fmt>{v, fmt, width, ljust}; } template<typename T> inline with_fmt_ex_t<T, default_formatter_t<decay_t<T>>> with(const T& v, size_t width, bool ljust=false) { return with(v, default_formatter<decay_t<T>>::get(), width, ljust); } } // end namespace fmt } // end namespace clue #endif <|endoftext|>
<commit_before>#include "Render.h" #include "interface/Interface.h" #include "base/basedef.h" #include "math/hash.h" #include <GL/glew.h> using fei::Render; static const GLchar *basicVertexShader = { "void main()" "{" " gl_TexCoord[0] = gl_MultiTexCoord0;" " gl_FrontColor = gl_Color;" " gl_Position = ftransform();" "}" }; static const GLchar *basicFragmentShader = { "uniform sampler2D feiTex;" "uniform float feiUseTex;" "void main() {" " vec4 color = gl_Color;" " if (feiUseTex == 1.0) {" " vec4 texColor = texture2D(feiTex, gl_TexCoord[0].st);" " if (texColor.a == 0.0 || color.a == 0.0) discard;" " color *= texColor;" " }" " gl_FragColor = color;" "}" }; Render* Render::instance = nullptr; Render* Render::getInstance() { if (!instance) { instance = new Render(); } return instance; } Render::Render() { } bool Render::init() { if (!fei::Interface::getInstance()->feiInit()) { return false; } GLenum err = glewInit(); if (GLEW_OK != err) { std::fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return false; } else { std::printf("GLEW Version: %s\n", glewGetString(GLEW_VERSION)); std::printf("OpenGL Version: %s\n", glGetString(GL_VERSION)); if (GLEW_VERSION_2_0) { std::printf("GLSL Version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); basicShader.loadString(basicVertexShader, basicFragmentShader); basicShader.push(); } else { std::printf("Shader unsupported!\n"); } glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); } return true; } void Render::destroy() { while (!shaderStack.empty()) { shaderStack.pop(); } deleteUnusedTexture(); } void Render::executeBeforeFrame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); auto shader = getShaderProgram(); if (shader) { shader->use(); } } void Render::executeAfterFrame() { deleteUnusedTexture(); } void Render::setViewport(const fei::Rect& viewport) { glViewport((GLint)viewport.getPosition().x, (GLint)viewport.getPosition().y, (GLsizei)viewport.getSize().x, (GLsizei)viewport.getSize().y); } const fei::Rect Render::getViewport() { int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); return fei::Rect((float)viewport[0], (float)viewport[1], (float)viewport[2], (float)viewport[3]); } void Render::pushShader(fei::ShaderProgram* shader) { if (shaderStack.empty() || shaderStack.top() != shader) { shaderStack.push(shader); shader->use(); } } void Render::popShader(fei::ShaderProgram* shader) { if (!shaderStack.empty() && shaderStack.top() == shader) { shaderStack.pop(); if (shaderStack.empty()) { glUseProgram(0); } else { shaderStack.top()->use(); } } } fei::ShaderProgram* Render::getShaderProgram() { if (!shaderStack.empty()) { return shaderStack.top(); } else { return nullptr; } } void Render::registTexture(const char* filename, GLuint id) { int hash = fei::bkdrHash(filename); fileTextureMap[hash] = id; } void Render::deleteTexture(GLuint id) { glDeleteTextures(1, &id); textureSizeMap.erase(textureSizeMap.find(id)); for (auto it = fileTextureMap.begin(); it != fileTextureMap.end(); ++it) { if (it->second == id) { fileTextureMap.erase(it); break; } } } int Render::queryTexture(const char* filename) { int hash = fei::bkdrHash(filename); GLuint ans = 0; auto it = fileTextureMap.find(hash); if (it != fileTextureMap.end()) { ans = it->second; } return ans; } void Render::registTexSize(GLuint id, const fei::Vec2& size) { textureSizeMap[id] = size; } const fei::Vec2 Render::queryTexSize(GLuint id) { return textureSizeMap[id]; } void Render::addRefTexture(GLuint id) { if (!id) return; textureRCMap[id]++; } void Render::releaseTexture(GLuint id) { if (!id) return; textureRCMap[id]--; } void Render::deleteUnusedTexture() { for (auto it = textureRCMap.begin(); it != textureRCMap.end();) { if (it->second == 0) { deleteTexture(it->first); it = textureRCMap.erase(it); } else { ++it; } } } void Render::bindTexture(GLuint tex) { glBindTexture(GL_TEXTURE_2D, tex); auto shader = getShaderProgram(); if (shader) { shader->setUniform("feiUseTex", 1.0f); shader->setUniform("feiTex", (float)tex); } } void Render::disableTexture() { auto shader = getShaderProgram(); if (shader) { shader->setUniform("feiUseTex", 0.0f); } } void Render::drawTexQuad(const fei::Vec2& size, GLfloat* texCoord) { GLfloat w2 = size.x / 2.0f; GLfloat h2 = size.y / 2.0f; GLfloat vertex[] = {-w2, h2, -w2, -h2, w2, h2, w2, -h2}; GLfloat defaultTexCoord[] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f}; glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, 0, vertex); if (texCoord) { glTexCoordPointer(2, GL_FLOAT, 0, texCoord); } else { glTexCoordPointer(2, GL_FLOAT, 0, defaultTexCoord); } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } void Render::drawShape(const fei::Shape* shape) { GLenum type = GL_TRIANGLE_FAN; if (!shape->isSolid()) { type = GL_LINE_LOOP; } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, shape->getDataPtr()); glDrawArrays(type, 0, shape->getDataSize()); glDisableClientState(GL_VERTEX_ARRAY); } void Render::useColor(const fei::Vec4* color) { glColor4fv(&color->x); }<commit_msg>update Render::pushShader and Render::popShader<commit_after>#include "Render.h" #include "interface/Interface.h" #include "base/basedef.h" #include "math/hash.h" #include <GL/glew.h> using fei::Render; static const GLchar *basicVertexShader = { "void main()" "{" " gl_TexCoord[0] = gl_MultiTexCoord0;" " gl_FrontColor = gl_Color;" " gl_Position = ftransform();" "}" }; static const GLchar *basicFragmentShader = { "uniform sampler2D feiTex;" "uniform float feiUseTex;" "void main() {" " vec4 color = gl_Color;" " if (feiUseTex == 1.0) {" " vec4 texColor = texture2D(feiTex, gl_TexCoord[0].st);" " if (texColor.a == 0.0 || color.a == 0.0) discard;" " color *= texColor;" " }" " gl_FragColor = color;" "}" }; Render* Render::instance = nullptr; Render* Render::getInstance() { if (!instance) { instance = new Render(); } return instance; } Render::Render() { } bool Render::init() { if (!fei::Interface::getInstance()->feiInit()) { return false; } GLenum err = glewInit(); if (GLEW_OK != err) { std::fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err)); return false; } else { std::printf("GLEW Version: %s\n", glewGetString(GLEW_VERSION)); std::printf("OpenGL Version: %s\n", glGetString(GL_VERSION)); if (GLEW_VERSION_2_0) { std::printf("GLSL Version: %s\n", glGetString(GL_SHADING_LANGUAGE_VERSION)); basicShader.loadString(basicVertexShader, basicFragmentShader); basicShader.push(); } else { std::printf("Shader unsupported!\n"); } glEnable(GL_CULL_FACE); glCullFace(GL_FRONT); } return true; } void Render::destroy() { while (!shaderStack.empty()) { shaderStack.pop(); } deleteUnusedTexture(); } void Render::executeBeforeFrame() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); auto shader = getShaderProgram(); if (shader) { shader->use(); } } void Render::executeAfterFrame() { deleteUnusedTexture(); } void Render::setViewport(const fei::Rect& viewport) { glViewport((GLint)viewport.getPosition().x, (GLint)viewport.getPosition().y, (GLsizei)viewport.getSize().x, (GLsizei)viewport.getSize().y); } const fei::Rect Render::getViewport() { int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); return fei::Rect((float)viewport[0], (float)viewport[1], (float)viewport[2], (float)viewport[3]); } void Render::pushShader(fei::ShaderProgram* shader) { if (shaderStack.empty() || shaderStack.top() != shader) { shader->use(); } shaderStack.push(shader); } void Render::popShader(fei::ShaderProgram* shader) { if (!shaderStack.empty() && shaderStack.top() == shader) { shaderStack.pop(); if (shaderStack.empty()) { glUseProgram(0); } else if (shaderStack.top() != shader) { shaderStack.top()->use(); } } } fei::ShaderProgram* Render::getShaderProgram() { if (!shaderStack.empty()) { return shaderStack.top(); } else { return nullptr; } } void Render::registTexture(const char* filename, GLuint id) { int hash = fei::bkdrHash(filename); fileTextureMap[hash] = id; } void Render::deleteTexture(GLuint id) { glDeleteTextures(1, &id); textureSizeMap.erase(textureSizeMap.find(id)); for (auto it = fileTextureMap.begin(); it != fileTextureMap.end(); ++it) { if (it->second == id) { fileTextureMap.erase(it); break; } } } int Render::queryTexture(const char* filename) { int hash = fei::bkdrHash(filename); GLuint ans = 0; auto it = fileTextureMap.find(hash); if (it != fileTextureMap.end()) { ans = it->second; } return ans; } void Render::registTexSize(GLuint id, const fei::Vec2& size) { textureSizeMap[id] = size; } const fei::Vec2 Render::queryTexSize(GLuint id) { return textureSizeMap[id]; } void Render::addRefTexture(GLuint id) { if (!id) return; textureRCMap[id]++; } void Render::releaseTexture(GLuint id) { if (!id) return; textureRCMap[id]--; } void Render::deleteUnusedTexture() { for (auto it = textureRCMap.begin(); it != textureRCMap.end();) { if (it->second == 0) { deleteTexture(it->first); it = textureRCMap.erase(it); } else { ++it; } } } void Render::bindTexture(GLuint tex) { glBindTexture(GL_TEXTURE_2D, tex); auto shader = getShaderProgram(); if (shader) { shader->setUniform("feiUseTex", 1.0f); shader->setUniform("feiTex", (float)tex); } } void Render::disableTexture() { auto shader = getShaderProgram(); if (shader) { shader->setUniform("feiUseTex", 0.0f); } } void Render::drawTexQuad(const fei::Vec2& size, GLfloat* texCoord) { GLfloat w2 = size.x / 2.0f; GLfloat h2 = size.y / 2.0f; GLfloat vertex[] = {-w2, h2, -w2, -h2, w2, h2, w2, -h2}; GLfloat defaultTexCoord[] = {0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 0.0f}; glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); glVertexPointer(2, GL_FLOAT, 0, vertex); if (texCoord) { glTexCoordPointer(2, GL_FLOAT, 0, texCoord); } else { glTexCoordPointer(2, GL_FLOAT, 0, defaultTexCoord); } glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); glDisableClientState(GL_VERTEX_ARRAY); glDisableClientState(GL_TEXTURE_COORD_ARRAY); } void Render::drawShape(const fei::Shape* shape) { GLenum type = GL_TRIANGLE_FAN; if (!shape->isSolid()) { type = GL_LINE_LOOP; } glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, shape->getDataPtr()); glDrawArrays(type, 0, shape->getDataSize()); glDisableClientState(GL_VERTEX_ARRAY); } void Render::useColor(const fei::Vec4* color) { glColor4fv(&color->x); } <|endoftext|>
<commit_before><commit_msg>abstract_runner: debug logs<commit_after><|endoftext|>
<commit_before>#ifndef YADI_FACTORY_HPP__ #define YADI_FACTORY_HPP__ #include <yaml-cpp/yaml.h> #include <functional> #include <map> #include <memory> #include <string> namespace yadi { template <typename base_t> struct factory_traits { using ptr_type = std::shared_ptr<base_t>; }; template <typename base_t> using ptr_type_t = typename factory_traits<base_t>::ptr_type; template <typename base_t> class factory { public: using base_type = base_t; using initializer_type = std::function<ptr_type_t<base_type>(YAML::Node)>; using ptr_type = ptr_type_t<base_type>; private: struct type_info { initializer_type initializer; std::string help; }; public: using type_store = std::map<std::string, type_info>; public: static void register_type(std::string type, initializer_type initializer) { mut_types()[type].initializer = initializer; } static ptr_type create(std::string const& type, YAML::Node const& config = {}) { typename type_store::const_iterator type_iter = mut_types().find(type); if (type_iter == mut_types().end()) { throw std::runtime_error(type + " not found"); } return type_iter->second.initializer(config); } static ptr_type create(YAML::Node const& factory_config) { if (!factory_config.IsDefined()) { throw std::runtime_error("Factory config not defined"); } if (factory_config.IsScalar()) { std::string type = factory_config.as<std::string>(""); if (type.empty()) { throw std::runtime_error("Factory config scalar not valid"); } return create(type); } if (factory_config.IsMap()) { YAML::Node typeNode = factory_config["type"]; if (!typeNode.IsDefined()) { throw std::runtime_error("Factory config type not defined"); } std::string type = typeNode.as<std::string>(""); if (type.empty()) { throw std::runtime_error("Factory config type not valid"); } YAML::Node configNode = factory_config["config"]; return create(type, configNode); } throw std::runtime_error("Factory config not valid, YAML must be scalar string or map"); } static type_store types() { return mut_types(); } private: static type_store& mut_types() { static type_store TYPES; return TYPES; } }; template <typename base_t> using initializer_type_t = typename factory<base_t>::initializer_type; template <typename base_t, typename impl_t> ptr_type_t<base_t> yaml_init(YAML::Node const& config) { ptr_type_t<base_t> ret(new impl_t(config)); return ret; }; // TODO complete function inline YAML::Node merge_yaml(YAML::Node const& left, YAML::Node const& /* right */) { return left; } template <typename base_t> void register_type(std::string type, initializer_type_t<base_t> initializer) { factory<base_t>::register_type(type, initializer); }; template <typename base_t, typename impl_t> void register_type(std::string type) { register_type<base_t>(type, &yaml_init<base_t, impl_t>); }; template <typename base_t, typename impl_t> void register_type_no_arg(std::string type) { register_type<base_t>(type, [](YAML::Node) { ptr_type_t<base_t> p(new impl_t); return p; }); } template <typename base_t> void register_alias(std::string alias, std::string type, YAML::Node config) { register_type<base_t>(alias, [type, config](YAML::Node const& passedConfig) { YAML::Node mergedConfig = merge_yaml(config, passedConfig); return factory<base_t>::create(type, mergedConfig); }); } template <typename base_t> void register_aliases(YAML::Node aliases) { // TODO error handling std::map<std::string, YAML::Node> aliasesMap = aliases.as<std::map<std::string, YAML::Node>>(); for (auto const& entry : aliasesMap) { std::string type = entry.second["type"].as<std::string>(); YAML::Node config = entry.second["config"]; register_alias<base_t>(entry.first, type, config); } } } // namespace yadi #define YADI_INIT_BEGIN_N(NAME) \ namespace { \ struct static_initialization_##NAME { \ static_initialization_##NAME() { #define YADI_INIT_END_N(NAME) \ } \ } \ ; \ static_initialization_##NAME static_initialization_##NAME##__; \ } #define YADI_INIT_BEGIN YADI_INIT_BEGIN_N(ANON) #define YADI_INIT_END YADI_INIT_END_N(ANON) #endif // YADI_FACTORY_HPP__ <commit_msg>Comments<commit_after>#ifndef YADI_FACTORY_HPP__ #define YADI_FACTORY_HPP__ #include <yaml-cpp/yaml.h> #include <functional> #include <map> #include <memory> #include <string> namespace yadi { /** * @brief Factory traits that can be changed for base_t. * @tparam base_t */ template <typename base_t> struct factory_traits { using ptr_type = std::shared_ptr<base_t>; /// The type of pointer to return from create. }; /** * @brief The type of pointer the base_t factory creates. */ template <typename base_t> using ptr_type_t = typename factory_traits<base_t>::ptr_type; /** * A YAML based factory. * @tparam base_t */ template <typename base_t> class factory { public: using base_type = base_t; using initializer_type = std::function<ptr_type_t<base_type>(YAML::Node)>; using ptr_type = ptr_type_t<base_type>; struct type_info { initializer_type initializer; std::string help; }; using type_store = std::map<std::string, type_info>; public: /** * @brief Registers initializer to type. When create is called with type this initializer will be called. * Overwrites initializer if already registered (will change). * @param type * @param initializer */ static void register_type(std::string type, initializer_type initializer) { mut_types()[type].initializer = initializer; } /** * @brief Calls the initializer associated with type passing the given YAML config. * @param type * @param config * @return The result of the registered initializer * @throws std::runtime_error if no initializer is registered for type */ static ptr_type create(std::string const& type, YAML::Node const& config = {}) { typename type_store::const_iterator type_iter = mut_types().find(type); if (type_iter == mut_types().end()) { throw std::runtime_error(type + " not found"); } return type_iter->second.initializer(config); } /** * @brief Pulls type and config from YAML. This function is especially usefil when loading nested types * from YAML configuration. If factory_config is a scalar string it will be used as type. If factory_config * is a map then "type" and "config" keys will be pulled from it and used as such. * @param factory_config * @return */ static ptr_type create(YAML::Node const& factory_config) { if (!factory_config.IsDefined()) { throw std::runtime_error("Factory config not defined"); } if (factory_config.IsScalar()) { std::string type = factory_config.as<std::string>(""); if (type.empty()) { throw std::runtime_error("Factory config scalar not valid"); } return create(type); } if (factory_config.IsMap()) { YAML::Node typeNode = factory_config["type"]; if (!typeNode.IsDefined()) { throw std::runtime_error("Factory config type not defined"); } std::string type = typeNode.as<std::string>(""); if (type.empty()) { throw std::runtime_error("Factory config type not valid"); } YAML::Node configNode = factory_config["config"]; return create(type, configNode); } throw std::runtime_error("Factory config not valid, YAML must be scalar string or map"); } /** * @brief A copy of the stored types and their registered initializers and help. * @return */ static type_store types() { return mut_types(); } private: static type_store& mut_types() { static type_store TYPES; return TYPES; } }; template <typename base_t> using initializer_type_t = typename factory<base_t>::initializer_type; /** * @brief Constructs impl_t via a constructor that accepts YAML and returns as pointer to base_t, * ptr_type_t<base_t>. * @tparam base_t Use to determine pointer type. * @tparam impl_t Type to construct * @param config Argument to constructor. * @return The constructed type as ptr_type_t<base_t> */ template <typename base_t, typename impl_t> ptr_type_t<base_t> yaml_init(YAML::Node const& config) { ptr_type_t<base_t> ret(new impl_t(config)); return ret; }; // TODO complete function // TODO change argument names /** * If both types are maps then they are merged. If right is not defined then left is used. Otherwise, error. * @param left * @return */ inline YAML::Node merge_yaml(YAML::Node const& left, YAML::Node const& /* right */) { return left; } /** * @brief Equivalent to factory<baes_t>::register_type(type, initializer) * @tparam base_t * @param type * @param initializer */ template <typename base_t> void register_type(std::string type, initializer_type_t<base_t> initializer) { factory<base_t>::register_type(type, initializer); }; /** * @brief Registers type using yaml_init function as initializer. * @tparam base_t * @tparam impl_t * @param type */ template <typename base_t, typename impl_t> void register_type(std::string type) { register_type<base_t>(type, &yaml_init<base_t, impl_t>); }; /** * @brief Registers type to initializer that will construct impl_t using default constructor. * @tparam base_t * @tparam impl_t * @param type */ template <typename base_t, typename impl_t> void register_type_no_arg(std::string type) { register_type<base_t>(type, [](YAML::Node) { ptr_type_t<base_t> p(new impl_t); return p; }); } /** * @brief Registers alias to type and config pair. When create is called for alias the passed in and registered * configs are merged and the initializer registered to type is called with the result. * @tparam base_t * @param alias * @param type * @param config */ template <typename base_t> void register_alias(std::string alias, std::string type, YAML::Node config) { register_type<base_t>(alias, [type, config](YAML::Node const& passedConfig) { YAML::Node mergedConfig = merge_yaml(config, passedConfig); return factory<base_t>::create(type, mergedConfig); }); } /** * @brief Loads aliases from a YAML file. The file should be a map of the format... * alias: * type: actualType * config: ... * * For each entry register_alias() is called. * @tparam base_t * @param aliases */ template <typename base_t> void register_aliases(YAML::Node aliases) { // TODO error handling std::map<std::string, YAML::Node> aliasesMap = aliases.as<std::map<std::string, YAML::Node>>(); for (auto const& entry : aliasesMap) { std::string type = entry.second["type"].as<std::string>(); YAML::Node config = entry.second["config"]; register_alias<base_t>(entry.first, type, config); } } } // namespace yadi #define YADI_INIT_BEGIN_N(NAME) \ namespace { \ struct static_initialization_##NAME { \ static_initialization_##NAME() { #define YADI_INIT_END_N(NAME) \ } \ } \ ; \ static_initialization_##NAME static_initialization_##NAME##__; \ } #define YADI_INIT_BEGIN YADI_INIT_BEGIN_N(ANON) #define YADI_INIT_END YADI_INIT_END_N(ANON) #endif // YADI_FACTORY_HPP__ <|endoftext|>
<commit_before>#include <boost/test/unit_test.hpp> #include "graph.h" #include "common.h" BOOST_AUTO_TEST_CASE(graph_instantiation) { Graph g; ///// // empty graph BOOST_REQUIRE(g.empty()); BOOST_REQUIRE(g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 0u); BOOST_REQUIRE(g.nodes().begin() == g.nodes().end()); ///// // add one node BOOST_REQUIRE_NO_THROW(g.nodes().add(additionNode(), "add_1")); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 1u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); BOOST_REQUIRE(g.nodes().begin()+1 == g.nodes().end()); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes().begin()->metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes().begin()->name(), "add_1"); ///// // add two more nodes BOOST_REQUIRE_NO_THROW(g.nodes().add(multiplicationNode(), "mult_1")); BOOST_REQUIRE_NO_THROW(g.nodes().add(additionNode(), "add_2")); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 3u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); for(size_t a=0; a<3; ++a) BOOST_REQUIRE_EQUAL(&(g.nodes()[a]), &(*(g.nodes().begin() + a))); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[1].metadata()), &(multiplicationNode())); BOOST_REQUIRE_EQUAL(g.nodes()[1].name(), "mult_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[2].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[2].name(), "add_2"); ///// // remove one node (mult_1) BOOST_REQUIRE_NO_THROW(g.nodes().erase(g.nodes().begin() + 1)); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 2u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); BOOST_REQUIRE(g.nodes().begin()+2 == g.nodes().end()); for(size_t a=0; a<2; ++a) BOOST_REQUIRE_EQUAL(&(g.nodes()[a]), &(*(g.nodes().begin() + a))); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[1].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[1].name(), "add_2"); ///// // clear the graph BOOST_REQUIRE_NO_THROW(g.clear()); BOOST_REQUIRE(g.empty()); BOOST_REQUIRE(g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 0u); BOOST_REQUIRE(g.nodes().begin() == g.nodes().end()); } <commit_msg>Added simple node instantiation callback tests<commit_after>#include <boost/test/unit_test.hpp> #include "graph.h" #include "common.h" namespace { unsigned s_nodeCount = 0; } BOOST_AUTO_TEST_CASE(graph_instantiation) { Graph g; ////// // connect callbacks g.onAddNode([&](Node&) { ++s_nodeCount; }); g.onRemoveNode([&](Node&) { --s_nodeCount; }); ///// // empty graph BOOST_REQUIRE(g.empty()); BOOST_REQUIRE(g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 0u); BOOST_REQUIRE(g.nodes().begin() == g.nodes().end()); ///// // add one node BOOST_REQUIRE_NO_THROW(g.nodes().add(additionNode(), "add_1")); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 1u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); BOOST_REQUIRE(g.nodes().begin() + 1 == g.nodes().end()); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes().begin()->metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes().begin()->name(), "add_1"); BOOST_CHECK_EQUAL(s_nodeCount, 1u); ///// // add two more nodes BOOST_REQUIRE_NO_THROW(g.nodes().add(multiplicationNode(), "mult_1")); BOOST_REQUIRE_NO_THROW(g.nodes().add(additionNode(), "add_2")); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 3u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); for(size_t a = 0; a < 3; ++a) BOOST_REQUIRE_EQUAL(&(g.nodes()[a]), &(*(g.nodes().begin() + a))); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[1].metadata()), &(multiplicationNode())); BOOST_REQUIRE_EQUAL(g.nodes()[1].name(), "mult_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[2].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[2].name(), "add_2"); BOOST_CHECK_EQUAL(s_nodeCount, 3u); ///// // remove one node (mult_1) BOOST_REQUIRE_NO_THROW(g.nodes().erase(g.nodes().begin() + 1)); BOOST_REQUIRE(not g.empty()); BOOST_REQUIRE(not g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 2u); BOOST_REQUIRE(g.nodes().begin() != g.nodes().end()); BOOST_REQUIRE(g.nodes().begin() + 2 == g.nodes().end()); for(size_t a = 0; a < 2; ++a) BOOST_REQUIRE_EQUAL(&(g.nodes()[a]), &(*(g.nodes().begin() + a))); BOOST_REQUIRE_EQUAL(&(g.nodes()[0].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[0].name(), "add_1"); BOOST_REQUIRE_EQUAL(&(g.nodes()[1].metadata()), &(additionNode())); BOOST_REQUIRE_EQUAL(g.nodes()[1].name(), "add_2"); BOOST_CHECK_EQUAL(s_nodeCount, 2u); ///// // clear the graph BOOST_REQUIRE_NO_THROW(g.clear()); BOOST_REQUIRE(g.empty()); BOOST_REQUIRE(g.nodes().empty()); BOOST_REQUIRE_EQUAL(g.nodes().size(), 0u); BOOST_REQUIRE(g.nodes().begin() == g.nodes().end()); BOOST_CHECK_EQUAL(s_nodeCount, 0u); } <|endoftext|>
<commit_before>/* * Copyright 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GUARD_sqlite_dbconn_hpp_8577399267152603 #define GUARD_sqlite_dbconn_hpp_8577399267152603 // Hide from Doxygen /// @cond /** @file * * @brief Header file pertaining to SQLiteDBConn class. */ #include "../sqloxx_exceptions.hpp" #include "sql_statement_impl.hpp" #include <jewel/checked_arithmetic.hpp> #include "sqlite3.h" // Compiling directly into build #include <boost/filesystem/path.hpp> #include <limits> #include <string> #include <vector> namespace sqloxx { namespace detail { /** * @class SQLiteDBConn * * This class is designed to be used only by other classes within * the Sqloxx module, and should not be accessed by external client * code. * * This class is intended to encapsulate calls to the C API * provided by SQLite, in relation to managing a database connection * represented by a sqlite3* struct. * * SQLiteDBConn is in designed to be contained * within an instance of DatabaseConnection; and it is DatabaseConnection * that provides the higher-level interface with clients outside of * Sqloxx, as well as a range of convenience functions that are not * provided by this lower-level class. * * @todo MEDIUM PRIORITY Supply public member functions to close * any database connections and to shut down SQLite3. Current this is done * in the destructor, but destructors should not throw, so the destructor * calls std::terminate() if close or shut-down fails. */ class SQLiteDBConn { friend class SQLStatementImpl; public: /** * Initializes SQLite3 and creates a database connection * initially set to null. * * @throws SQLiteInitializationError if initialization fails * for any reason. */ SQLiteDBConn(); SQLiteDBConn(SQLiteDBConn const&) = delete; SQLiteDBConn(SQLiteDBConn&&) = delete; SQLiteDBConn& operator=(SQLiteDBConn const&) = delete; SQLiteDBConn& operator=(SQLiteDBConn&&) = delete; /** * Closes any open SQLite3 database connection, and also * shuts down SQLite3. * * Does not throw. If SQLite3 connection closure or shutdown fails, * the application is aborted with a diagnostic message written to * std::clog. */ ~SQLiteDBConn(); /** * Returns \c true iff the SQLiteDBConn is currently connected to a * database file. Does not throw. */ bool is_valid() const; /** * Implements DatabaseConnection::open. */ void open(boost::filesystem::path const& filepath); /** * Implements DatabaseConnection::execute_sql */ void execute_sql(std::string const& str); /** * At this point this function does not fully support SQLite extended * error codes; only the basic error codes. If errcode is an extended * error code that is not also a basic error code, and is not * SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then the function will * throw SQLiteUnknownErrorCode. If errcode is a basic error code that * is not SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then it will throw an * exception derived from * SQLiteException, with the exception thrown corresponding to the * error code (see sqloxx_exceptions.hpp) and the error message returned * by called what() on the exception corresponding to the error message * produced by SQLite. * * If the database connection is invalid (in particular, if the connection * is not open), then InvalidConnection will always be thrown, regardless * of the value of errcode. * * errcode should be the return value of an operation just executed on * the SQLite API on this database connection. The function assumes that * no other operation has been executed on the API since the operation * that produced errcode. * * @throws InvalidConnection if the database connection is invalid. This * takes precedence over other exceptions that might be thrown. * * @throws an exception derived from SQLiteException if and only if * errcode is something other than SQLITE_OK, BUT * * @throws std::logic_error if errcode is not the latest error code * produced by a call to the SQLite API on this database connection. * * @param a SQLite error code. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ void throw_on_failure(int errcode); private: /** * A connection to a SQLite3 database file. * * (Note this is a raw pointer not a smart pointer * to facilitate more straightforward interaction with the SQLite * C API.) */ sqlite3* m_connection; }; } // namespace detail } // namespace sqloxx /// @endcond // End hiding from Doxygen #endif // GUARD_sqlite_dbconn_hpp_8577399267152603 <commit_msg>Added a TODO re. SQLiteDBConn, re. managing SQLite initialization and shutdown functions better.<commit_after>/* * Copyright 2013 Matthew Harvey * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef GUARD_sqlite_dbconn_hpp_8577399267152603 #define GUARD_sqlite_dbconn_hpp_8577399267152603 // Hide from Doxygen /// @cond /** @file * * @brief Header file pertaining to SQLiteDBConn class. */ #include "../sqloxx_exceptions.hpp" #include "sql_statement_impl.hpp" #include <jewel/checked_arithmetic.hpp> #include "sqlite3.h" // Compiling directly into build #include <boost/filesystem/path.hpp> #include <limits> #include <string> #include <vector> namespace sqloxx { namespace detail { /** * @class SQLiteDBConn * * This class is designed to be used only by other classes within * the Sqloxx module, and should not be accessed by external client * code. * * This class is intended to encapsulate calls to the C API * provided by SQLite, in relation to managing a database connection * represented by a sqlite3* struct. * * SQLiteDBConn is in designed to be contained * within an instance of DatabaseConnection; and it is DatabaseConnection * that provides the higher-level interface with clients outside of * Sqloxx, as well as a range of convenience functions that are not * provided by this lower-level class. * * @todo MEDIUM PRIORITY Supply public member functions to close * any database connections and to shut down SQLite3. Current this is done * in the destructor, but destructors should not throw, so the destructor * calls std::terminate() if close or shut-down fails. * * @todo HIGH PRIORITY sqlite3_initialize() and sqlite3_shutdown() * functions should probably be managed such that they are called automatically * only by the first SQLiteDBConn to be created globally, and the last * SQLiteDBConn to be destructed globally, respectively. */ class SQLiteDBConn { friend class SQLStatementImpl; public: /** * Initializes SQLite3 and creates a database connection * initially set to null. * * @throws SQLiteInitializationError if initialization fails * for any reason. */ SQLiteDBConn(); SQLiteDBConn(SQLiteDBConn const&) = delete; SQLiteDBConn(SQLiteDBConn&&) = delete; SQLiteDBConn& operator=(SQLiteDBConn const&) = delete; SQLiteDBConn& operator=(SQLiteDBConn&&) = delete; /** * Closes any open SQLite3 database connection, and also * shuts down SQLite3. * * Does not throw. If SQLite3 connection closure or shutdown fails, * the application is aborted with a diagnostic message written to * std::clog. */ ~SQLiteDBConn(); /** * Returns \c true iff the SQLiteDBConn is currently connected to a * database file. Does not throw. */ bool is_valid() const; /** * Implements DatabaseConnection::open. */ void open(boost::filesystem::path const& filepath); /** * Implements DatabaseConnection::execute_sql */ void execute_sql(std::string const& str); /** * At this point this function does not fully support SQLite extended * error codes; only the basic error codes. If errcode is an extended * error code that is not also a basic error code, and is not * SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then the function will * throw SQLiteUnknownErrorCode. If errcode is a basic error code that * is not SQLITE_OK, SQLITE_DONE or SQLITE_ROW, then it will throw an * exception derived from * SQLiteException, with the exception thrown corresponding to the * error code (see sqloxx_exceptions.hpp) and the error message returned * by called what() on the exception corresponding to the error message * produced by SQLite. * * If the database connection is invalid (in particular, if the connection * is not open), then InvalidConnection will always be thrown, regardless * of the value of errcode. * * errcode should be the return value of an operation just executed on * the SQLite API on this database connection. The function assumes that * no other operation has been executed on the API since the operation * that produced errcode. * * @throws InvalidConnection if the database connection is invalid. This * takes precedence over other exceptions that might be thrown. * * @throws an exception derived from SQLiteException if and only if * errcode is something other than SQLITE_OK, BUT * * @throws std::logic_error if errcode is not the latest error code * produced by a call to the SQLite API on this database connection. * * @param a SQLite error code. * * <b>Exception safety</b>: <em>strong guarantee</em>. */ void throw_on_failure(int errcode); private: /** * A connection to a SQLite3 database file. * * (Note this is a raw pointer not a smart pointer * to facilitate more straightforward interaction with the SQLite * C API.) */ sqlite3* m_connection; }; } // namespace detail } // namespace sqloxx /// @endcond // End hiding from Doxygen #endif // GUARD_sqlite_dbconn_hpp_8577399267152603 <|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "client.h" #include <util/timer.h> #include <util/clientstatus.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include <cassert> #include <cstring> #include <iostream> static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = 0; j < i; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } Client::Client(vespalib::CryptoEngine::SP engine, ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(std::move(engine), _args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _contentbufsize; int _leftOversLen; char *_contentbuf; const char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _contentbufsize(0), _leftOversLen(0), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _args._maxLineSize; _contentbuf = new char[_contentbufsize]; } } bool reset(); int findUrl(char *buf, int buflen); int nextUrl(char *buf, int buflen); int nextContent(); const char *content() const { return _contentbuf; } ~UrlReader() { delete [] _contentbuf; } }; bool UrlReader::reset() { if (_restarts == _args._restartLimit) { return false; } else if (_args._restartLimit > 0) { _restarts++; } _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } return true; } int UrlReader::findUrl(char *buf, int buflen) { while (true) { if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { // reached logical EOF return -1; } int ll = _reader.ReadLine(buf, buflen); if (ll < 0) { // reached physical EOF return ll; } if (ll > 0) { if (buf[0] == '/' || !_args._usePostMode) { // found URL return ll; } } } } int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { int sz = std::min(_leftOversLen, buflen-1); strncpy(buf, _leftOvers, sz); buf[sz] = '\0'; _leftOvers = NULL; return _leftOversLen; } int ll = findUrl(buf, buflen); if (ll > 0) { return ll; } if (reset()) { // try again ll = findUrl(buf, buflen); } return ll; } int UrlReader::nextContent() { char *buf = _contentbuf; int totLen = 0; // make sure we don't chop leftover URL while (totLen + _args._maxLineSize < _contentbufsize) { // allow space for newline: int room = _contentbufsize - totLen - 1; int len = _reader.ReadLine(buf, room); if (len < 0) { // reached EOF break; } len = std::min(len, room); if (len > 0 && buf[0] == '/') { // reached next URL _leftOvers = buf; _leftOversLen = len; break; } buf += len; totLen += len; *buf++ = '\n'; totLen++; } // ignore last newline return (totLen > 0) ? totLen-1 : 0; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.nextContent() : 0; auto content = urlSource.content(); if (_args->_usePostMode && _args->_base64Decode) { auto base64_content = std::string(urlSource.content(), cLen); auto decoded = base64_decode(base64_content); content = decoded.c_str(); cLen = content.size(); } _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, content, cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <commit_msg>compilation fix<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include "client.h" #include <util/timer.h> #include <util/clientstatus.h> #include <httpclient/httpclient.h> #include <util/filereader.h> #include <cassert> #include <cstring> #include <iostream> static const std::string base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz" "0123456789+/"; static inline bool is_base64(unsigned char c) { return (isalnum(c) || (c == '+') || (c == '/')); } std::string base64_decode(std::string const& encoded_string) { int in_len = encoded_string.size(); int i = 0; int j = 0; int in_ = 0; unsigned char char_array_4[4], char_array_3[3]; std::string ret; while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) { char_array_4[i++] = encoded_string[in_]; in_++; if (i ==4) { for (i = 0; i <4; i++) char_array_4[i] = base64_chars.find(char_array_4[i]); char_array_3[0] = ( char_array_4[0] << 2 ) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3]; for (i = 0; (i < 3); i++) ret += char_array_3[i]; i = 0; } } if (i) { for (j = 0; j < i; j++) char_array_4[j] = base64_chars.find(char_array_4[j]); char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4); char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2); for (j = 0; (j < i - 1); j++) ret += char_array_3[j]; } return ret; } Client::Client(vespalib::CryptoEngine::SP engine, ClientArguments *args) : _args(args), _status(new ClientStatus()), _reqTimer(new Timer()), _cycleTimer(new Timer()), _masterTimer(new Timer()), _http(new HTTPClient(std::move(engine), _args->_hostname, _args->_port, _args->_keepAlive, _args->_headerBenchmarkdataCoverage, _args->_extraHeaders, _args->_authority)), _reader(new FileReader()), _output(), _linebufsize(args->_maxLineSize), _linebuf(new char[_linebufsize]), _stop(false), _done(false), _thread() { assert(args != NULL); _cycleTimer->SetMax(_args->_cycle); } Client::~Client() { delete [] _linebuf; } void Client::runMe(Client * me) { me->run(); } class UrlReader { FileReader &_reader; const ClientArguments &_args; int _restarts; int _contentbufsize; int _leftOversLen; char *_contentbuf; const char *_leftOvers; public: UrlReader(FileReader& reader, const ClientArguments &args) : _reader(reader), _args(args), _restarts(0), _contentbufsize(0), _leftOversLen(0), _contentbuf(0), _leftOvers(0) { if (_args._usePostMode) { _contentbufsize = 16 * _args._maxLineSize; _contentbuf = new char[_contentbufsize]; } } bool reset(); int findUrl(char *buf, int buflen); int nextUrl(char *buf, int buflen); int nextContent(); const char *content() const { return _contentbuf; } ~UrlReader() { delete [] _contentbuf; } }; bool UrlReader::reset() { if (_restarts == _args._restartLimit) { return false; } else if (_args._restartLimit > 0) { _restarts++; } _reader.Reset(); // Start reading from offset if (_args._singleQueryFile) { _reader.SetFilePos(_args._queryfileOffset); } return true; } int UrlReader::findUrl(char *buf, int buflen) { while (true) { if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) { // reached logical EOF return -1; } int ll = _reader.ReadLine(buf, buflen); if (ll < 0) { // reached physical EOF return ll; } if (ll > 0) { if (buf[0] == '/' || !_args._usePostMode) { // found URL return ll; } } } } int UrlReader::nextUrl(char *buf, int buflen) { if (_leftOvers) { int sz = std::min(_leftOversLen, buflen-1); strncpy(buf, _leftOvers, sz); buf[sz] = '\0'; _leftOvers = NULL; return _leftOversLen; } int ll = findUrl(buf, buflen); if (ll > 0) { return ll; } if (reset()) { // try again ll = findUrl(buf, buflen); } return ll; } int UrlReader::nextContent() { char *buf = _contentbuf; int totLen = 0; // make sure we don't chop leftover URL while (totLen + _args._maxLineSize < _contentbufsize) { // allow space for newline: int room = _contentbufsize - totLen - 1; int len = _reader.ReadLine(buf, room); if (len < 0) { // reached EOF break; } len = std::min(len, room); if (len > 0 && buf[0] == '/') { // reached next URL _leftOvers = buf; _leftOversLen = len; break; } buf += len; totLen += len; *buf++ = '\n'; totLen++; } // ignore last newline return (totLen > 0) ? totLen-1 : 0; } void Client::run() { char inputFilename[1024]; char outputFilename[1024]; char timestr[64]; int linelen; /// int reslen; std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay)); // open query file snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum); if (!_reader->Open(inputFilename)) { printf("Client %d: ERROR: could not open file '%s' [read mode]\n", _args->_myNum, inputFilename); _status->SetError("Could not open query file."); return; } if (_args->_outputPattern != NULL) { snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum); _output = std::make_unique<std::ofstream>(outputFilename, std::ofstream::out | std::ofstream::binary); if (_output->fail()) { printf("Client %d: ERROR: could not open file '%s' [write mode]\n", _args->_myNum, outputFilename); _status->SetError("Could not open output file."); return; } } if (_output) _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); if (_args->_ignoreCount == 0) _masterTimer->Start(); // Start reading from offset if ( _args->_singleQueryFile ) _reader->SetFilePos(_args->_queryfileOffset); UrlReader urlSource(*_reader, *_args); size_t urlNumber = 0; // run queries while (!_stop) { _cycleTimer->Start(); linelen = urlSource.nextUrl(_linebuf, _linebufsize); if (linelen > 0) { ++urlNumber; } else { if (urlNumber == 0) { fprintf(stderr, "Client %d: ERROR: could not read any lines from '%s'\n", _args->_myNum, inputFilename); _status->SetError("Could not read any lines from query file."); } break; } if (linelen < _linebufsize) { if (_output) { _output->write("URL: ", strlen("URL: ")); _output->write(_linebuf, linelen); _output->write("\n\n", 2); } if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) { strcat(_linebuf, _args->_queryStringToAppend.c_str()); } int cLen = _args->_usePostMode ? urlSource.nextContent() : 0; auto content = urlSource.content(); if (_args->_usePostMode && _args->_base64Decode) { auto base64_content = std::string(urlSource.content(), cLen); auto decoded = base64_decode(base64_content); content = decoded.c_str(); cLen = decoded.size(); } _reqTimer->Start(); auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, content, cLen); _reqTimer->Stop(); _status->AddRequestStatus(fetch_status.RequestStatus()); if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0) ++_status->_zeroHitQueries; if (_output) { if (!fetch_status.Ok()) { _output->write("\nFBENCH: URL FETCH FAILED!\n", strlen("\nFBENCH: URL FETCH FAILED!\n")); _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); } else { sprintf(timestr, "\nTIME USED: %0.4f s\n", _reqTimer->GetTimespan() / 1000.0); _output->write(timestr, strlen(timestr)); _output->write(&FBENCH_DELIMITER[1], strlen(FBENCH_DELIMITER) - 1); } } if (fetch_status.ResultSize() >= _args->_byteLimit) { if (_args->_ignoreCount == 0) _status->ResponseTime(_reqTimer->GetTimespan()); } else { if (_args->_ignoreCount == 0) _status->RequestFailed(); } } else { if (_args->_ignoreCount == 0) _status->SkippedRequest(); } _cycleTimer->Stop(); if (_args->_cycle < 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan()))); } else { if (_cycleTimer->GetRemaining() > 0) { std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining()))); } else { if (_args->_ignoreCount == 0) _status->OverTime(); } } if (_args->_ignoreCount > 0) { _args->_ignoreCount--; if (_args->_ignoreCount == 0) _masterTimer->Start(); } // Update current time span to calculate Q/s _status->SetRealTime(_masterTimer->GetCurrent()); } _masterTimer->Stop(); _status->SetRealTime(_masterTimer->GetTimespan()); _status->SetReuseCount(_http->GetReuseCount()); printf("."); fflush(stdout); _done = true; } void Client::stop() { _stop = true; } bool Client::done() { return _done; } void Client::start() { _thread = std::thread(Client::runMe, this); } void Client::join() { _thread.join(); } <|endoftext|>
<commit_before>#include "ngraph.h" #include <stdint.h> #include <iostream> #include <cstring> #include <engpar_support.h> #include "Iterators/PinIterator.h" #include "Iterators/GraphIterator.h" #include "agi_typeconvert.h" namespace agi { GraphEdge* PNgraph::getEdge(lid_t lid,etype t) { return reinterpret_cast<GraphEdge*>( toPtr(num_types*lid+t+1) ); } void Ngraph::getResidence(GraphEdge* e, Peers& residence) const { //residence.clear(); agi::PinIterator* pitr = pins(e); agi::GraphVertex* vtx; lid_t deg = degree(e); for (lid_t i=0;i<deg;i++) { vtx = iterate(pitr); residence.insert(owner(vtx)); } destroy(pitr); } bool Ngraph::isResidentOn(GraphEdge* e,part_t peer) const { agi::PinIterator* pitr = pins(e); agi::GraphVertex* vtx; lid_t deg = degree(e); for (lid_t i=0;i<deg;i++) { vtx = iterate(pitr); if (owner(vtx)==peer) { destroy(pitr); return true; } } destroy(pitr); return false; } wgt_t Ngraph::weight(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; if (isHyperGraph) return edge_weights[type][edge_list[type][id]]; return edge_weights[type][id]; } lid_t Ngraph::localID(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; return id/num_types; } gid_t Ngraph::globalID(GraphEdge* edge) const { if (!isHyperGraph) return localID(edge); uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; return edge_unmap[type][id/num_types]; } lid_t Ngraph::u(lid_t e, etype t) const { bool found = false; lid_t index = 0; lid_t bound_low=0; lid_t bound_high = numLocalVtxs(); while (!found) { index = (bound_high+bound_low)/2; if (degree_list[t][index]<= e&& degree_list[t][index+1]>e) found=true; else if (degree_list[t][index]<=e) bound_low=index; else bound_high=index; } return index; } GraphVertex* Ngraph::u(GraphEdge* edge) const { lid_t lid = (uintptr_t)(edge)-1; etype type = lid%num_types; lid/=num_types; lid_t vid = u(lid,type); return reinterpret_cast<GraphVertex*>(vid+1); } GraphVertex* Ngraph::v(GraphEdge* edge) const { if (isHyperGraph) { EnGPar_Error_Message("v(edge) not supported in hypergraph mode\n"); return NULL; } if (edge==NULL) return NULL; uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1); } lid_t Ngraph::degree(GraphEdge* edge) const { if (!isHyperGraph) return 2; //This check is used for GraphIterator if (edge==NULL) return 0; uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; return pin_degree_list[type][id+1]-pin_degree_list[type][id]; } PinIterator* Ngraph::pins(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; if (!isHyperGraph) { return new PinIterator(reinterpret_cast<lid_t*>(u(edge)), reinterpret_cast<lid_t*>( toPtr(edge_list[type][id]+1)) ); } return new PinIterator((pin_list[type]+pin_degree_list[type][id]), pin_list[type]+pin_degree_list[type][id+1]); } void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) { assert(!edge_weights[t]); if (wgts.size()==0) { edge_weights[t] = new wgt_t[num_local_edges[t]]; for (gid_t i=0;i<num_local_edges[t];i++) edge_weights[t][i]=1; return; } assert((lid_t)wgts.size()==num_local_edges[t]); edge_weights[t] = new wgt_t[num_local_edges[t]]; memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t)); } //Protected functions void Ngraph::makeEdgeArray(etype t, int count) { edge_unmap[t] = new gid_t[count]; edge_weights[t] = new wgt_t[count]; } void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) { edge_unmap[t][lid] = gid; edge_weights[t][lid] = w; edge_mapping[t][gid]=lid; } EVEIterator* Ngraph::eve_begin(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; lid_t start = eve_offsets[type][id]*num_types+type; return reinterpret_cast<EVEIterator*>(toPtr(start+1)); } EVEIterator* Ngraph::eve_end(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; lid_t start = eve_offsets[type][id+1]*num_types+num_types+type; return reinterpret_cast<EVEIterator*>(toPtr(start+1)); } } <commit_msg>fix edge weights<commit_after>#include "ngraph.h" #include <stdint.h> #include <iostream> #include <cstring> #include <engpar_support.h> #include "Iterators/PinIterator.h" #include "Iterators/GraphIterator.h" #include "agi_typeconvert.h" namespace agi { GraphEdge* PNgraph::getEdge(lid_t lid,etype t) { return reinterpret_cast<GraphEdge*>( toPtr(num_types*lid+t+1) ); } void Ngraph::getResidence(GraphEdge* e, Peers& residence) const { //residence.clear(); agi::PinIterator* pitr = pins(e); agi::GraphVertex* vtx; lid_t deg = degree(e); for (lid_t i=0;i<deg;i++) { vtx = iterate(pitr); residence.insert(owner(vtx)); } destroy(pitr); } bool Ngraph::isResidentOn(GraphEdge* e,part_t peer) const { agi::PinIterator* pitr = pins(e); agi::GraphVertex* vtx; lid_t deg = degree(e); for (lid_t i=0;i<deg;i++) { vtx = iterate(pitr); if (owner(vtx)==peer) { destroy(pitr); return true; } } destroy(pitr); return false; } wgt_t Ngraph::weight(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; if (!isHyperGraph) return edge_weights[type][edge_list[type][id]]; return edge_weights[type][id]; } lid_t Ngraph::localID(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; return id/num_types; } gid_t Ngraph::globalID(GraphEdge* edge) const { if (!isHyperGraph) return localID(edge); uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; return edge_unmap[type][id/num_types]; } lid_t Ngraph::u(lid_t e, etype t) const { bool found = false; lid_t index = 0; lid_t bound_low=0; lid_t bound_high = numLocalVtxs(); while (!found) { index = (bound_high+bound_low)/2; if (degree_list[t][index]<= e&& degree_list[t][index+1]>e) found=true; else if (degree_list[t][index]<=e) bound_low=index; else bound_high=index; } return index; } GraphVertex* Ngraph::u(GraphEdge* edge) const { lid_t lid = (uintptr_t)(edge)-1; etype type = lid%num_types; lid/=num_types; lid_t vid = u(lid,type); return reinterpret_cast<GraphVertex*>(vid+1); } GraphVertex* Ngraph::v(GraphEdge* edge) const { if (isHyperGraph) { EnGPar_Error_Message("v(edge) not supported in hypergraph mode\n"); return NULL; } if (edge==NULL) return NULL; uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; return reinterpret_cast<GraphVertex*>(edge_list[type][id]+1); } lid_t Ngraph::degree(GraphEdge* edge) const { if (!isHyperGraph) return 2; //This check is used for GraphIterator if (edge==NULL) return 0; uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; return pin_degree_list[type][id+1]-pin_degree_list[type][id]; } PinIterator* Ngraph::pins(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; if (!isHyperGraph) { return new PinIterator(reinterpret_cast<lid_t*>(u(edge)), reinterpret_cast<lid_t*>( toPtr(edge_list[type][id]+1)) ); } return new PinIterator((pin_list[type]+pin_degree_list[type][id]), pin_list[type]+pin_degree_list[type][id+1]); } void Ngraph::setEdgeWeights(std::vector<wgt_t>& wgts, etype t) { assert(!edge_weights[t]); if (wgts.size()==0) { edge_weights[t] = new wgt_t[num_local_edges[t]]; for (gid_t i=0;i<num_local_edges[t];i++) edge_weights[t][i]=1; return; } assert((lid_t)wgts.size()==num_local_edges[t]); edge_weights[t] = new wgt_t[num_local_edges[t]]; memcpy(edge_weights[t],&(wgts[0]),num_local_edges[t]*sizeof(wgt_t)); } //Protected functions void Ngraph::makeEdgeArray(etype t, int count) { edge_unmap[t] = new gid_t[count]; edge_weights[t] = new wgt_t[count]; } void Ngraph::setEdge(lid_t lid,gid_t gid, wgt_t w,etype t) { edge_unmap[t][lid] = gid; edge_weights[t][lid] = w; edge_mapping[t][gid]=lid; } EVEIterator* Ngraph::eve_begin(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; lid_t start = eve_offsets[type][id]*num_types+type; return reinterpret_cast<EVEIterator*>(toPtr(start+1)); } EVEIterator* Ngraph::eve_end(GraphEdge* edge) const { uintptr_t id = (uintptr_t)(edge)-1; etype type = id%num_types; id/=num_types; lid_t start = eve_offsets[type][id+1]*num_types+num_types+type; return reinterpret_cast<EVEIterator*>(toPtr(start+1)); } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // This is an implementation of a random-access compressed file compatible // with Cassandra's org.apache.cassandra.io.compress compressed files. // // To allow reasonably-efficient seeking in the compressed file, the file // is not compressed as a whole, but rather divided into chunks of a known // size (by default, 64 KB), where each chunk is compressed individually. // The compressed size of each chunk is different, so for allowing seeking // to a particular position in the uncompressed data, we need to also know // the position of each chunk. This offset vector is supplied externally as // a "compression_metadata" object, which also contains additional information // needed from decompression - such as the chunk size and compressor type. // // Cassandra supports four different compression algorithms for the chunks, // LZ4, Snappy, Deflate, and Zstd - the default (and therefore most important) is // LZ4. Each compressor is an implementation of the "compressor" class. // // Each compressed chunk is followed by a 4-byte checksum of the compressed // data, using the Adler32 or CRC32 algorithm. In Cassandra, there is a parameter // "crc_check_chance" (defaulting to 1.0) which determines the probability // of us verifying the checksum of each chunk we read. // // This implementation does not cache the compressed disk blocks (which // are read using O_DIRECT), nor uncompressed data. We intend to cache high- // level Cassandra rows, not disk blocks. #include <vector> #include <cstdint> #include <iterator> #include <seastar/core/file.hh> #include <seastar/core/seastar.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include "types.hh" #include "sstables/types.hh" #include "checksum_utils.hh" #include "../compress.hh" class compression_parameters; class compressor; using compressor_ptr = shared_ptr<compressor>; namespace sstables { struct compression; struct compression { // To reduce the memory footpring of compression-info, n offsets are grouped // together into segments, where each segment stores a base absolute offset // into the file, the other offsets in the segments being relative offsets // (and thus of reduced size). Also offsets are allocated only just enough // bits to store their maximum value. The offsets are thus packed in a // buffer like so: // arrrarrrarrr... // where n is 4, a is an absolute offset and r are offsets relative to a. // Segments are stored in buckets, where each bucket has its own base offset. // Segments in a buckets are optimized to address as large of a chunk of the // data as possible for a given chunk size and bucket size. // // This is not a general purpose container. There are limitations: // * Can't be used before init() is called. // * at() is best called incrementally, altough random lookups are // perfectly valid as well. // * The iterator and at() can't provide references to the elements. // * No point insert is available. class segmented_offsets { public: class state { std::size_t _current_index{0}; std::size_t _current_bucket_index{0}; uint64_t _current_bucket_segment_index{0}; uint64_t _current_segment_relative_index{0}; uint64_t _current_segment_offset_bits{0}; void update_position_trackers(std::size_t index, uint16_t segment_size_bits, uint32_t segments_per_bucket, uint8_t grouped_offsets); friend class segmented_offsets; }; class accessor { const segmented_offsets& _offsets; mutable state _state; public: accessor(const segmented_offsets& offsets) : _offsets(offsets) { } uint64_t at(std::size_t i) const { return _offsets.at(i, _state); } }; class writer { segmented_offsets& _offsets; state _state; public: writer(segmented_offsets& offsets) : _offsets(offsets) { } void push_back(uint64_t offset) { return _offsets.push_back(offset, _state); } }; accessor get_accessor() const { return accessor(*this); } writer get_writer() { return writer(*this); } private: struct bucket { uint64_t base_offset; std::unique_ptr<char[]> storage; }; uint32_t _chunk_size{0}; uint8_t _segment_base_offset_size_bits{0}; uint8_t _segmented_offset_size_bits{0}; uint16_t _segment_size_bits{0}; uint32_t _segments_per_bucket{0}; uint8_t _grouped_offsets{0}; uint64_t _last_written_offset{0}; std::size_t _size{0}; std::deque<bucket> _storage; uint64_t read(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits) const; void write(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits, uint64_t value); uint64_t at(std::size_t i, state& s) const; void push_back(uint64_t offset, state& s); public: class const_iterator : public std::iterator<std::random_access_iterator_tag, const uint64_t> { friend class segmented_offsets; struct end_tag {}; segmented_offsets::accessor _offsets; std::size_t _index; const_iterator(const segmented_offsets& offsets) : _offsets(offsets.get_accessor()) , _index(0) { } const_iterator(const segmented_offsets& offsets, end_tag) : _offsets(offsets.get_accessor()) , _index(offsets.size()) { } public: const_iterator(const const_iterator& other) = default; const_iterator& operator=(const const_iterator& other) { assert(&_offsets == &other._offsets); _index = other._index; return *this; } const_iterator operator++(int) { const_iterator it{*this}; return ++it; } const_iterator& operator++() { *this += 1; return *this; } const_iterator operator+(ssize_t i) const { const_iterator it{*this}; it += i; return it; } const_iterator& operator+=(ssize_t i) { _index += i; return *this; } const_iterator operator--(int) { const_iterator it{*this}; return --it; } const_iterator& operator--() { *this -= 1; return *this; } const_iterator operator-(ssize_t i) const { const_iterator it{*this}; it -= i; return it; } const_iterator& operator-=(ssize_t i) { _index -= i; return *this; } value_type operator*() const { return _offsets.at(_index); } value_type operator[](ssize_t i) const { return _offsets.at(_index + i); } bool operator==(const const_iterator& other) const { return _index == other._index; } bool operator!=(const const_iterator& other) const { return !(*this == other); } bool operator<(const const_iterator& other) const { return _index < other._index; } bool operator<=(const const_iterator& other) const { return _index <= other._index; } bool operator>(const const_iterator& other) const { return _index > other._index; } bool operator>=(const const_iterator& other) const { return _index >= other._index; } }; segmented_offsets() = default; segmented_offsets(const segmented_offsets&) = delete; segmented_offsets& operator=(const segmented_offsets&) = delete; segmented_offsets(segmented_offsets&&) = default; segmented_offsets& operator=(segmented_offsets&&) = default; // Has to be called before using the class. Doing otherwise // results in undefined behaviour! Don't call more than once! // TODO: fold into constructor, once the parse() et. al. code // allows it. void init(uint32_t chunk_size); uint32_t chunk_size() const noexcept { return _chunk_size; } std::size_t size() const noexcept { return _size; } const_iterator begin() const { return const_iterator(*this); } const_iterator end() const { return const_iterator(*this, const_iterator::end_tag{}); } const_iterator cbegin() const { return const_iterator(*this); } const_iterator cend() const { return const_iterator(*this, const_iterator::end_tag{}); } }; disk_string<uint16_t> name; disk_array<uint32_t, option> options; uint32_t chunk_len = 0; uint64_t data_len = 0; segmented_offsets offsets; private: // Variables *not* found in the "Compression Info" file (added by update()): uint64_t _compressed_file_length = 0; uint32_t _full_checksum = 0; public: // Set the compressor algorithm, please check the definition of enum compressor. void set_compressor(compressor_ptr c); // After changing _compression, update() must be called to update // additional variables depending on it. void update(uint64_t compressed_file_length); operator bool() const { return !name.value.empty(); } // locate() locates in the compressed file the given byte position of // the uncompressed data: // 1. The byte range containing the appropriate compressed chunk, and // 2. the offset into the uncompressed chunk. // Note that the last 4 bytes of the returned chunk are not the actual // compressed data, but rather the checksum of the compressed data. // locate() throws an out-of-range exception if the position is beyond // the last chunk. struct chunk_and_offset { uint64_t chunk_start; uint64_t chunk_len; // variable size of compressed chunk unsigned offset; // offset into chunk after uncompressing it }; chunk_and_offset locate(uint64_t position, const compression::segmented_offsets::accessor& accessor); unsigned uncompressed_chunk_length() const noexcept { return chunk_len; } void set_uncompressed_chunk_length(uint32_t cl) { chunk_len = cl; offsets.init(chunk_len); } uint64_t uncompressed_file_length() const noexcept { return data_len; } void set_uncompressed_file_length(uint64_t fl) { data_len = fl; } uint64_t compressed_file_length() const { return _compressed_file_length; } void set_compressed_file_length(uint64_t compressed_file_length) { _compressed_file_length = compressed_file_length; } uint32_t get_full_checksum() const { return _full_checksum; } void set_full_checksum(uint32_t checksum) { _full_checksum = checksum; } friend class sstable; }; // for API query only. Free function just to distinguish it from an accessor in compression compressor_ptr get_sstable_compressor(const compression&); // Note: compression_metadata is passed by reference; The caller is // responsible for keeping the compression_metadata alive as long as there // are open streams on it. This should happen naturally on a higher level - // as long as we have *sstables* work in progress, we need to keep the whole // sstable alive, and the compression metadata is only a part of it. input_stream<char> make_compressed_file_k_l_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_k_l_format_output_stream(output_stream<char> out, sstables::compression* cm, const compression_parameters& cp); input_stream<char> make_compressed_file_m_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_m_format_output_stream(output_stream<char> out, sstables::compression* cm, const compression_parameters& cp); } <commit_msg>sstables: remove std::iterator from const_iterator<commit_after>/* * Copyright (C) 2015 ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once // This is an implementation of a random-access compressed file compatible // with Cassandra's org.apache.cassandra.io.compress compressed files. // // To allow reasonably-efficient seeking in the compressed file, the file // is not compressed as a whole, but rather divided into chunks of a known // size (by default, 64 KB), where each chunk is compressed individually. // The compressed size of each chunk is different, so for allowing seeking // to a particular position in the uncompressed data, we need to also know // the position of each chunk. This offset vector is supplied externally as // a "compression_metadata" object, which also contains additional information // needed from decompression - such as the chunk size and compressor type. // // Cassandra supports four different compression algorithms for the chunks, // LZ4, Snappy, Deflate, and Zstd - the default (and therefore most important) is // LZ4. Each compressor is an implementation of the "compressor" class. // // Each compressed chunk is followed by a 4-byte checksum of the compressed // data, using the Adler32 or CRC32 algorithm. In Cassandra, there is a parameter // "crc_check_chance" (defaulting to 1.0) which determines the probability // of us verifying the checksum of each chunk we read. // // This implementation does not cache the compressed disk blocks (which // are read using O_DIRECT), nor uncompressed data. We intend to cache high- // level Cassandra rows, not disk blocks. #include <vector> #include <cstdint> #include <iterator> #include <seastar/core/file.hh> #include <seastar/core/seastar.hh> #include <seastar/core/shared_ptr.hh> #include <seastar/core/fstream.hh> #include "types.hh" #include "sstables/types.hh" #include "checksum_utils.hh" #include "../compress.hh" class compression_parameters; class compressor; using compressor_ptr = shared_ptr<compressor>; namespace sstables { struct compression; struct compression { // To reduce the memory footpring of compression-info, n offsets are grouped // together into segments, where each segment stores a base absolute offset // into the file, the other offsets in the segments being relative offsets // (and thus of reduced size). Also offsets are allocated only just enough // bits to store their maximum value. The offsets are thus packed in a // buffer like so: // arrrarrrarrr... // where n is 4, a is an absolute offset and r are offsets relative to a. // Segments are stored in buckets, where each bucket has its own base offset. // Segments in a buckets are optimized to address as large of a chunk of the // data as possible for a given chunk size and bucket size. // // This is not a general purpose container. There are limitations: // * Can't be used before init() is called. // * at() is best called incrementally, altough random lookups are // perfectly valid as well. // * The iterator and at() can't provide references to the elements. // * No point insert is available. class segmented_offsets { public: class state { std::size_t _current_index{0}; std::size_t _current_bucket_index{0}; uint64_t _current_bucket_segment_index{0}; uint64_t _current_segment_relative_index{0}; uint64_t _current_segment_offset_bits{0}; void update_position_trackers(std::size_t index, uint16_t segment_size_bits, uint32_t segments_per_bucket, uint8_t grouped_offsets); friend class segmented_offsets; }; class accessor { const segmented_offsets& _offsets; mutable state _state; public: accessor(const segmented_offsets& offsets) : _offsets(offsets) { } uint64_t at(std::size_t i) const { return _offsets.at(i, _state); } }; class writer { segmented_offsets& _offsets; state _state; public: writer(segmented_offsets& offsets) : _offsets(offsets) { } void push_back(uint64_t offset) { return _offsets.push_back(offset, _state); } }; accessor get_accessor() const { return accessor(*this); } writer get_writer() { return writer(*this); } private: struct bucket { uint64_t base_offset; std::unique_ptr<char[]> storage; }; uint32_t _chunk_size{0}; uint8_t _segment_base_offset_size_bits{0}; uint8_t _segmented_offset_size_bits{0}; uint16_t _segment_size_bits{0}; uint32_t _segments_per_bucket{0}; uint8_t _grouped_offsets{0}; uint64_t _last_written_offset{0}; std::size_t _size{0}; std::deque<bucket> _storage; uint64_t read(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits) const; void write(uint64_t bucket_index, uint64_t offset_bits, uint64_t size_bits, uint64_t value); uint64_t at(std::size_t i, state& s) const; void push_back(uint64_t offset, state& s); public: class const_iterator { public: using iterator_category = std::random_access_iterator_tag; using value_type = const uint64_t; using difference_type = std::ptrdiff_t; using pointer = const uint64_t*; using reference = const uint64_t&; private: friend class segmented_offsets; struct end_tag {}; segmented_offsets::accessor _offsets; std::size_t _index; const_iterator(const segmented_offsets& offsets) : _offsets(offsets.get_accessor()) , _index(0) { } const_iterator(const segmented_offsets& offsets, end_tag) : _offsets(offsets.get_accessor()) , _index(offsets.size()) { } public: const_iterator(const const_iterator& other) = default; const_iterator& operator=(const const_iterator& other) { assert(&_offsets == &other._offsets); _index = other._index; return *this; } const_iterator operator++(int) { const_iterator it{*this}; return ++it; } const_iterator& operator++() { *this += 1; return *this; } const_iterator operator+(ssize_t i) const { const_iterator it{*this}; it += i; return it; } const_iterator& operator+=(ssize_t i) { _index += i; return *this; } const_iterator operator--(int) { const_iterator it{*this}; return --it; } const_iterator& operator--() { *this -= 1; return *this; } const_iterator operator-(ssize_t i) const { const_iterator it{*this}; it -= i; return it; } const_iterator& operator-=(ssize_t i) { _index -= i; return *this; } value_type operator*() const { return _offsets.at(_index); } value_type operator[](ssize_t i) const { return _offsets.at(_index + i); } bool operator==(const const_iterator& other) const { return _index == other._index; } bool operator!=(const const_iterator& other) const { return !(*this == other); } bool operator<(const const_iterator& other) const { return _index < other._index; } bool operator<=(const const_iterator& other) const { return _index <= other._index; } bool operator>(const const_iterator& other) const { return _index > other._index; } bool operator>=(const const_iterator& other) const { return _index >= other._index; } }; segmented_offsets() = default; segmented_offsets(const segmented_offsets&) = delete; segmented_offsets& operator=(const segmented_offsets&) = delete; segmented_offsets(segmented_offsets&&) = default; segmented_offsets& operator=(segmented_offsets&&) = default; // Has to be called before using the class. Doing otherwise // results in undefined behaviour! Don't call more than once! // TODO: fold into constructor, once the parse() et. al. code // allows it. void init(uint32_t chunk_size); uint32_t chunk_size() const noexcept { return _chunk_size; } std::size_t size() const noexcept { return _size; } const_iterator begin() const { return const_iterator(*this); } const_iterator end() const { return const_iterator(*this, const_iterator::end_tag{}); } const_iterator cbegin() const { return const_iterator(*this); } const_iterator cend() const { return const_iterator(*this, const_iterator::end_tag{}); } }; disk_string<uint16_t> name; disk_array<uint32_t, option> options; uint32_t chunk_len = 0; uint64_t data_len = 0; segmented_offsets offsets; private: // Variables *not* found in the "Compression Info" file (added by update()): uint64_t _compressed_file_length = 0; uint32_t _full_checksum = 0; public: // Set the compressor algorithm, please check the definition of enum compressor. void set_compressor(compressor_ptr c); // After changing _compression, update() must be called to update // additional variables depending on it. void update(uint64_t compressed_file_length); operator bool() const { return !name.value.empty(); } // locate() locates in the compressed file the given byte position of // the uncompressed data: // 1. The byte range containing the appropriate compressed chunk, and // 2. the offset into the uncompressed chunk. // Note that the last 4 bytes of the returned chunk are not the actual // compressed data, but rather the checksum of the compressed data. // locate() throws an out-of-range exception if the position is beyond // the last chunk. struct chunk_and_offset { uint64_t chunk_start; uint64_t chunk_len; // variable size of compressed chunk unsigned offset; // offset into chunk after uncompressing it }; chunk_and_offset locate(uint64_t position, const compression::segmented_offsets::accessor& accessor); unsigned uncompressed_chunk_length() const noexcept { return chunk_len; } void set_uncompressed_chunk_length(uint32_t cl) { chunk_len = cl; offsets.init(chunk_len); } uint64_t uncompressed_file_length() const noexcept { return data_len; } void set_uncompressed_file_length(uint64_t fl) { data_len = fl; } uint64_t compressed_file_length() const { return _compressed_file_length; } void set_compressed_file_length(uint64_t compressed_file_length) { _compressed_file_length = compressed_file_length; } uint32_t get_full_checksum() const { return _full_checksum; } void set_full_checksum(uint32_t checksum) { _full_checksum = checksum; } friend class sstable; }; // for API query only. Free function just to distinguish it from an accessor in compression compressor_ptr get_sstable_compressor(const compression&); // Note: compression_metadata is passed by reference; The caller is // responsible for keeping the compression_metadata alive as long as there // are open streams on it. This should happen naturally on a higher level - // as long as we have *sstables* work in progress, we need to keep the whole // sstable alive, and the compression metadata is only a part of it. input_stream<char> make_compressed_file_k_l_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_k_l_format_output_stream(output_stream<char> out, sstables::compression* cm, const compression_parameters& cp); input_stream<char> make_compressed_file_m_format_input_stream(file f, sstables::compression* cm, uint64_t offset, size_t len, class file_input_stream_options options); output_stream<char> make_compressed_file_m_format_output_stream(output_stream<char> out, sstables::compression* cm, const compression_parameters& cp); } <|endoftext|>
<commit_before>// Copyright (c) 2021 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test.hpp" #include "iceoryx_posh/roudi/memory/iceoryx_roudi_memory_manager.hpp" using namespace ::testing; using iox::roudi::IceOryxRouDiMemoryManager; namespace iox { namespace test { /// @brief This test file verifies that the BaseClass IceoryxRouDiMemoryManager is tested class IceoryxRoudiMemoryManager_test : public Test { public: std::unique_ptr<IceOryxRouDiMemoryManager> m_roudiMemoryManagerTest; void SetUp() override { auto config = iox::RouDiConfig_t().setDefaults(); m_roudiMemoryManagerTest = std::unique_ptr<IceOryxRouDiMemoryManager>(new IceOryxRouDiMemoryManager(config)); } void TearDown() override { } }; /// @brief test to check constructor TEST_F(IceoryxRoudiMemoryManager_test, ConstructorSuccess) { EXPECT_THAT(m_roudiMemoryManagerTest, Not(Eq(nullptr))); } /// @brief test to check function introspectionMemoryManager TEST_F(IceoryxRoudiMemoryManager_test, IntrospectionMemoryManagerNulloptWhenNotPresent) { auto result = m_roudiMemoryManagerTest->introspectionMemoryManager(); EXPECT_THAT(result, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function segmentManager TEST_F(IceoryxRoudiMemoryManager_test, segmentManagerNulloptWhenNotPresent) { auto resultTest = m_roudiMemoryManagerTest->segmentManager(); EXPECT_THAT(resultTest, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function portPool TEST_F(IceoryxRoudiMemoryManager_test, portPoolNulloptWhenNotPresent) { auto testResult = m_roudiMemoryManagerTest->portPool(); EXPECT_THAT(testResult, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function createAndAnnouceMemory TEST_F(IceoryxRoudiMemoryManager_test, createAndAnnouceMemorySuccess) { auto testResult = m_roudiMemoryManagerTest->createAndAnnounceMemory(); EXPECT_THAT(testResult.has_error(), Eq(false)); } } // namespace test } // iox <commit_msg>iox-#454 add new tests after review findings<commit_after>// Copyright (c) 2021 by Robert Bosch GmbH. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "test.hpp" #include "iceoryx_posh/roudi/memory/iceoryx_roudi_memory_manager.hpp" using namespace ::testing; using iox::roudi::IceOryxRouDiMemoryManager; namespace iox { namespace test { /// @brief This test file verifies that the BaseClass IceoryxRouDiMemoryManager is tested class IceoryxRoudiMemoryManager_test : public Test { public: std::unique_ptr<IceOryxRouDiMemoryManager> m_roudiMemoryManagerTest; void SetUp() override { auto config = iox::RouDiConfig_t().setDefaults(); m_roudiMemoryManagerTest = std::unique_ptr<IceOryxRouDiMemoryManager>(new IceOryxRouDiMemoryManager(config)); } void TearDown() override { } }; /// @brief test to check constructor TEST_F(IceoryxRoudiMemoryManager_test, ConstructorSuccess) { EXPECT_THAT(m_roudiMemoryManagerTest, Not(Eq(nullptr))); } /// @brief test to check function introspectionMemoryManager TEST_F(IceoryxRoudiMemoryManager_test, IntrospectionMemoryManagerNulloptWhenNotPresent) { auto result = m_roudiMemoryManagerTest->introspectionMemoryManager(); EXPECT_THAT(result, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function segmentManager TEST_F(IceoryxRoudiMemoryManager_test, segmentManagerNulloptWhenNotPresent) { auto resultTest = m_roudiMemoryManagerTest->segmentManager(); EXPECT_THAT(resultTest, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function portPool TEST_F(IceoryxRoudiMemoryManager_test, portPoolNulloptWhenNotPresent) { auto testResult = m_roudiMemoryManagerTest->portPool(); EXPECT_THAT(testResult, Eq(iox::cxx::nullopt_t())); } /// @brief test to check function createAndAnnouceMemory TEST_F(IceoryxRoudiMemoryManager_test, createAndAnnouceMemorySuccess) { auto testResult = m_roudiMemoryManagerTest->createAndAnnounceMemory(); EXPECT_THAT(testResult.has_error(), Eq(false)); } /// @brief test to check function MgmtMemoryProviderSuccess TEST_F(IceoryxRoudiMemoryManager_test, MgmtMemoryProviderSuccess) { auto testResult = m_roudiMemoryManagerTest->mgmtMemoryProvider(); EXPECT_THAT(testResult, Not(Eq(nullptr))); } /// @brief test to check function NullOptCheck TEST_F(IceoryxRoudiMemoryManager_test, NullOptCheck) { auto tr = m_roudiMemoryManagerTest->createAndAnnounceMemory(); EXPECT_THAT(tr.has_error(), Eq(false)); auto result = m_roudiMemoryManagerTest->introspectionMemoryManager(); EXPECT_THAT(result, Not(Eq(iox::cxx::nullopt_t()))); auto resultTest = m_roudiMemoryManagerTest->segmentManager(); EXPECT_THAT(resultTest, Not(Eq(iox::cxx::nullopt_t()))); auto testResult = m_roudiMemoryManagerTest->portPool(); EXPECT_THAT(testResult, Not(Eq(iox::cxx::nullopt_t()))); } /// @brief test to check Destroy segmentation fault TEST_F(IceoryxRoudiMemoryManager_test, DestroySegFault) { auto testResult = m_roudiMemoryManagerTest->createAndAnnounceMemory(); EXPECT_THAT(testResult.has_error(), Eq(false)); auto result = m_roudiMemoryManagerTest->destroyMemory(); EXPECT_THAT(result.has_error(), Eq(false)); auto res = m_roudiMemoryManagerTest->introspectionMemoryManager(); EXPECT_THAT(res, Eq(iox::cxx::nullopt_t())); auto resultTest = m_roudiMemoryManagerTest->segmentManager(); EXPECT_THAT(resultTest, Eq(iox::cxx::nullopt_t())); } } // namespace test } // iox <|endoftext|>
<commit_before>#include <fstream> #include <boost/filesystem.hpp> #include <util/helpers.hpp> #include <imageprocessing/ConnectedComponent.h> #include <sopnet/exceptions.h> #include <sopnet/segments/EndSegment.h> #include <sopnet/segments/ContinuationSegment.h> #include <sopnet/segments/BranchSegment.h> #include "GeometryFeatureExtractor.h" logger::LogChannel geometryfeatureextractorlog("geometryfeatureextractorlog", "[GeometryFeatureExtractor] "); util::ProgramOption optionDisableSliceDistanceFeature( util::_module = "sopnet.features", util::_long_name = "disableSliceDistanceFeature", util::_description_text = "Disable the use of slice distance features.", util::_default_value = 50); GeometryFeatureExtractor::GeometryFeatureExtractor() : _features(boost::make_shared<Features>()), _overlap(false, false), _alignedOverlap(false, true), _noSliceDistance(optionDisableSliceDistanceFeature) { registerInput(_segments, "segments"); registerOutput(_features, "features"); } void GeometryFeatureExtractor::updateOutputs() { LOG_DEBUG(geometryfeatureextractorlog) << "extracting features" << std::endl; _features->clear(); if (_noSliceDistance) _features->resize(_segments->size(), 10); else _features->resize(_segments->size(), 14); _features->addName("center distance"); _features->addName("set difference"); _features->addName("set difference ratio"); _features->addName("aligned set difference"); _features->addName("aligned set difference ratio"); _features->addName("size"); _features->addName("overlap"); _features->addName("overlap ratio"); _features->addName("aligned overlap"); _features->addName("aligned overlap ratio"); if (!_noSliceDistance) { _features->addName("average slice distance"); _features->addName("max slice distance"); _features->addName("aligned average slice distance"); _features->addName("aligned max slice distance"); } foreach (boost::shared_ptr<EndSegment> segment, _segments->getEnds()) getFeatures(*segment); foreach (boost::shared_ptr<ContinuationSegment> segment, _segments->getContinuations()) getFeatures(*segment); foreach (boost::shared_ptr<BranchSegment> segment, _segments->getBranches()) getFeatures(*segment); LOG_ALL(geometryfeatureextractorlog) << "found features: " << *_features << std::endl; LOG_DEBUG(geometryfeatureextractorlog) << "done" << std::endl; // free memory _distance.clearCache(); } template <typename SegmentType> void GeometryFeatureExtractor::getFeatures(const SegmentType& segment) { computeFeatures(segment, _features->get(segment.getId())); } void GeometryFeatureExtractor::computeFeatures(const EndSegment& end, std::vector<double>& features) { features[0] = Features::NoFeatureValue; features[1] = Features::NoFeatureValue; features[2] = Features::NoFeatureValue; features[3] = Features::NoFeatureValue; features[4] = Features::NoFeatureValue; features[5] = end.getSlice()->getComponent()->getSize(); features[6] = Features::NoFeatureValue; features[7] = Features::NoFeatureValue; features[8] = Features::NoFeatureValue; features[9] = Features::NoFeatureValue; if (!_noSliceDistance) { features[10] = Features::NoFeatureValue; features[11] = Features::NoFeatureValue; features[12] = Features::NoFeatureValue; features[13] = Features::NoFeatureValue; } } void GeometryFeatureExtractor::computeFeatures(const ContinuationSegment& continuation, std::vector<double>& features) { const util::point<double>& sourceCenter = continuation.getSourceSlice()->getComponent()->getCenter(); const util::point<double>& targetCenter = continuation.getTargetSlice()->getComponent()->getCenter(); unsigned int sourceSize = continuation.getSourceSlice()->getComponent()->getSize(); unsigned int targetSize = continuation.getTargetSlice()->getComponent()->getSize(); util::point<double> difference = sourceCenter - targetCenter; double distance = difference.x*difference.x + difference.y*difference.y; double overlap = _overlap(*continuation.getSourceSlice(), *continuation.getTargetSlice()); double overlapRatio = overlap/(sourceSize + targetSize - overlap); double alignedOverlap = _alignedOverlap(*continuation.getSourceSlice(), *continuation.getTargetSlice()); double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize - overlap); double setDifference = (sourceSize - overlap) + (targetSize - overlap); double setDifferenceRatio = setDifference/(sourceSize + targetSize); double alignedSetDifference = (sourceSize - alignedOverlap) + (targetSize - alignedOverlap); double alignedSetDifferenceRatio = alignedSetDifference/(sourceSize + targetSize); features[0] = distance; features[1] = setDifference; features[2] = setDifferenceRatio; features[3] = alignedSetDifference; features[4] = alignedSetDifferenceRatio; features[5] = (continuation.getSourceSlice()->getComponent()->getSize() + continuation.getTargetSlice()->getComponent()->getSize())*0.5; features[6] = overlap; features[7] = overlapRatio; features[8] = alignedOverlap; features[9] = alignedOverlapRatio; if (!_noSliceDistance) { double averageSliceDistance, maxSliceDistance; _distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, false, averageSliceDistance, maxSliceDistance); double alignedAverageSliceDistance, alignedMaxSliceDistance; _distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance); features[10] = averageSliceDistance; features[11] = maxSliceDistance; features[12] = alignedAverageSliceDistance; features[13] = alignedMaxSliceDistance; } } void GeometryFeatureExtractor::computeFeatures(const BranchSegment& branch, std::vector<double>& features) { const util::point<double>& sourceCenter = branch.getSourceSlice()->getComponent()->getCenter(); const util::point<double>& targetCenter1 = branch.getTargetSlice1()->getComponent()->getCenter(); const util::point<double>& targetCenter2 = branch.getTargetSlice2()->getComponent()->getCenter(); unsigned int sourceSize = branch.getSourceSlice()->getComponent()->getSize(); unsigned int targetSize1 = branch.getTargetSlice1()->getComponent()->getSize(); unsigned int targetSize2 = branch.getTargetSlice2()->getComponent()->getSize(); unsigned int targetSize = targetSize1 + targetSize2; util::point<double> difference = sourceCenter - (targetCenter1*targetSize1 + targetCenter2*targetSize2)/((double)(targetSize)); double distance = difference.x*difference.x + difference.y*difference.y; double overlap = _overlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice()); double overlapRatio = overlap/(sourceSize + targetSize - overlap); double alignedOverlap = _alignedOverlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice()); double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize - alignedOverlap); double setDifference = (sourceSize - overlap) + (targetSize - overlap); double setDifferenceRatio = setDifference/(sourceSize + targetSize); double alignedSetDifference = (sourceSize - alignedOverlap) + (targetSize - alignedOverlap); double alignedSetDifferenceRatio = alignedSetDifference/(sourceSize + targetSize); features[0] = distance; features[1] = setDifference; features[2] = setDifferenceRatio; features[3] = alignedSetDifference; features[4] = alignedSetDifferenceRatio; features[5] = (branch.getSourceSlice()->getComponent()->getSize() + branch.getTargetSlice1()->getComponent()->getSize() + branch.getTargetSlice2()->getComponent()->getSize())/3.0; features[6] = overlap; features[7] = overlapRatio; features[8] = alignedOverlap; features[9] = alignedOverlapRatio; if (!_noSliceDistance) { double averageSliceDistance, maxSliceDistance; _distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, false, averageSliceDistance, maxSliceDistance); double alignedAverageSliceDistance, alignedMaxSliceDistance; _distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance); features[10] = averageSliceDistance; features[11] = maxSliceDistance; features[12] = alignedAverageSliceDistance; features[13] = alignedMaxSliceDistance; } } <commit_msg>bugfix: initial value of program option in GeometryFeatureExtractor was of wrong type<commit_after>#include <fstream> #include <boost/filesystem.hpp> #include <util/helpers.hpp> #include <imageprocessing/ConnectedComponent.h> #include <sopnet/exceptions.h> #include <sopnet/segments/EndSegment.h> #include <sopnet/segments/ContinuationSegment.h> #include <sopnet/segments/BranchSegment.h> #include "GeometryFeatureExtractor.h" logger::LogChannel geometryfeatureextractorlog("geometryfeatureextractorlog", "[GeometryFeatureExtractor] "); util::ProgramOption optionDisableSliceDistanceFeature( util::_module = "sopnet.features", util::_long_name = "disableSliceDistanceFeature", util::_description_text = "Disable the use of slice distance features."); GeometryFeatureExtractor::GeometryFeatureExtractor() : _features(boost::make_shared<Features>()), _overlap(false, false), _alignedOverlap(false, true), _noSliceDistance(optionDisableSliceDistanceFeature) { registerInput(_segments, "segments"); registerOutput(_features, "features"); } void GeometryFeatureExtractor::updateOutputs() { LOG_DEBUG(geometryfeatureextractorlog) << "extracting features" << std::endl; _features->clear(); if (_noSliceDistance) _features->resize(_segments->size(), 10); else _features->resize(_segments->size(), 14); _features->addName("center distance"); _features->addName("set difference"); _features->addName("set difference ratio"); _features->addName("aligned set difference"); _features->addName("aligned set difference ratio"); _features->addName("size"); _features->addName("overlap"); _features->addName("overlap ratio"); _features->addName("aligned overlap"); _features->addName("aligned overlap ratio"); if (!_noSliceDistance) { _features->addName("average slice distance"); _features->addName("max slice distance"); _features->addName("aligned average slice distance"); _features->addName("aligned max slice distance"); } foreach (boost::shared_ptr<EndSegment> segment, _segments->getEnds()) getFeatures(*segment); foreach (boost::shared_ptr<ContinuationSegment> segment, _segments->getContinuations()) getFeatures(*segment); foreach (boost::shared_ptr<BranchSegment> segment, _segments->getBranches()) getFeatures(*segment); LOG_ALL(geometryfeatureextractorlog) << "found features: " << *_features << std::endl; LOG_DEBUG(geometryfeatureextractorlog) << "done" << std::endl; // free memory _distance.clearCache(); } template <typename SegmentType> void GeometryFeatureExtractor::getFeatures(const SegmentType& segment) { computeFeatures(segment, _features->get(segment.getId())); } void GeometryFeatureExtractor::computeFeatures(const EndSegment& end, std::vector<double>& features) { features[0] = Features::NoFeatureValue; features[1] = Features::NoFeatureValue; features[2] = Features::NoFeatureValue; features[3] = Features::NoFeatureValue; features[4] = Features::NoFeatureValue; features[5] = end.getSlice()->getComponent()->getSize(); features[6] = Features::NoFeatureValue; features[7] = Features::NoFeatureValue; features[8] = Features::NoFeatureValue; features[9] = Features::NoFeatureValue; if (!_noSliceDistance) { features[10] = Features::NoFeatureValue; features[11] = Features::NoFeatureValue; features[12] = Features::NoFeatureValue; features[13] = Features::NoFeatureValue; } } void GeometryFeatureExtractor::computeFeatures(const ContinuationSegment& continuation, std::vector<double>& features) { const util::point<double>& sourceCenter = continuation.getSourceSlice()->getComponent()->getCenter(); const util::point<double>& targetCenter = continuation.getTargetSlice()->getComponent()->getCenter(); unsigned int sourceSize = continuation.getSourceSlice()->getComponent()->getSize(); unsigned int targetSize = continuation.getTargetSlice()->getComponent()->getSize(); util::point<double> difference = sourceCenter - targetCenter; double distance = difference.x*difference.x + difference.y*difference.y; double overlap = _overlap(*continuation.getSourceSlice(), *continuation.getTargetSlice()); double overlapRatio = overlap/(sourceSize + targetSize - overlap); double alignedOverlap = _alignedOverlap(*continuation.getSourceSlice(), *continuation.getTargetSlice()); double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize - overlap); double setDifference = (sourceSize - overlap) + (targetSize - overlap); double setDifferenceRatio = setDifference/(sourceSize + targetSize); double alignedSetDifference = (sourceSize - alignedOverlap) + (targetSize - alignedOverlap); double alignedSetDifferenceRatio = alignedSetDifference/(sourceSize + targetSize); features[0] = distance; features[1] = setDifference; features[2] = setDifferenceRatio; features[3] = alignedSetDifference; features[4] = alignedSetDifferenceRatio; features[5] = (continuation.getSourceSlice()->getComponent()->getSize() + continuation.getTargetSlice()->getComponent()->getSize())*0.5; features[6] = overlap; features[7] = overlapRatio; features[8] = alignedOverlap; features[9] = alignedOverlapRatio; if (!_noSliceDistance) { double averageSliceDistance, maxSliceDistance; _distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, false, averageSliceDistance, maxSliceDistance); double alignedAverageSliceDistance, alignedMaxSliceDistance; _distance(*continuation.getSourceSlice(), *continuation.getTargetSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance); features[10] = averageSliceDistance; features[11] = maxSliceDistance; features[12] = alignedAverageSliceDistance; features[13] = alignedMaxSliceDistance; } } void GeometryFeatureExtractor::computeFeatures(const BranchSegment& branch, std::vector<double>& features) { const util::point<double>& sourceCenter = branch.getSourceSlice()->getComponent()->getCenter(); const util::point<double>& targetCenter1 = branch.getTargetSlice1()->getComponent()->getCenter(); const util::point<double>& targetCenter2 = branch.getTargetSlice2()->getComponent()->getCenter(); unsigned int sourceSize = branch.getSourceSlice()->getComponent()->getSize(); unsigned int targetSize1 = branch.getTargetSlice1()->getComponent()->getSize(); unsigned int targetSize2 = branch.getTargetSlice2()->getComponent()->getSize(); unsigned int targetSize = targetSize1 + targetSize2; util::point<double> difference = sourceCenter - (targetCenter1*targetSize1 + targetCenter2*targetSize2)/((double)(targetSize)); double distance = difference.x*difference.x + difference.y*difference.y; double overlap = _overlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice()); double overlapRatio = overlap/(sourceSize + targetSize - overlap); double alignedOverlap = _alignedOverlap(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice()); double alignedOverlapRatio = alignedOverlap/(sourceSize + targetSize - alignedOverlap); double setDifference = (sourceSize - overlap) + (targetSize - overlap); double setDifferenceRatio = setDifference/(sourceSize + targetSize); double alignedSetDifference = (sourceSize - alignedOverlap) + (targetSize - alignedOverlap); double alignedSetDifferenceRatio = alignedSetDifference/(sourceSize + targetSize); features[0] = distance; features[1] = setDifference; features[2] = setDifferenceRatio; features[3] = alignedSetDifference; features[4] = alignedSetDifferenceRatio; features[5] = (branch.getSourceSlice()->getComponent()->getSize() + branch.getTargetSlice1()->getComponent()->getSize() + branch.getTargetSlice2()->getComponent()->getSize())/3.0; features[6] = overlap; features[7] = overlapRatio; features[8] = alignedOverlap; features[9] = alignedOverlapRatio; if (!_noSliceDistance) { double averageSliceDistance, maxSliceDistance; _distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, false, averageSliceDistance, maxSliceDistance); double alignedAverageSliceDistance, alignedMaxSliceDistance; _distance(*branch.getTargetSlice1(), *branch.getTargetSlice2(), *branch.getSourceSlice(), true, true, alignedAverageSliceDistance, alignedMaxSliceDistance); features[10] = averageSliceDistance; features[11] = maxSliceDistance; features[12] = alignedAverageSliceDistance; features[13] = alignedMaxSliceDistance; } } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. *: Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. *: Neither the name of the University of Wisconsin - Madison nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \file MCLS_TpetraCrsMatrixAdapter.hpp * \author Stuart R. Slattery * \brief Tpetra::CrsMatrix Adapter. */ //---------------------------------------------------------------------------// #ifndef MCLS_TPETRACRSMATRIXADAPTER_HPP #define MCLS_TPETRACRSMATRIXADAPTER_HPP #include <algorithm> #include <MCLS_DBC.hpp> #include <MCLS_MatrixTraits.hpp> #include <MCLS_TpetraHelpers.hpp> #include <Teuchos_as.hpp> #include <Teuchos_ArrayView.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_Comm.hpp> #include <Tpetra_Vector.hpp> #include <Tpetra_CrsMatrix.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_Import.hpp> #include <Tpetra_RowMatrixTransposer.hpp> #include <Tpetra_Distributor.hpp> namespace MCLS { //---------------------------------------------------------------------------// /*! * \class MatrixTraits * \brief Traits specialization for Tpetra::CrsMatrix. */ template<class Scalar, class LO, class GO> class MatrixTraits<Tpetra::Vector<Scalar,LO,GO>, Tpetra::CrsMatrix<Scalar,LO,GO> > { public: //@{ //! Typedefs. typedef typename Tpetra::CrsMatrix<Scalar,LO,GO> matrix_type; typedef typename Tpetra::Vector<Scalar,LO,GO> vector_type; typedef typename vector_type::scalar_type scalar_type; typedef typename vector_type::local_ordinal_type local_ordinal_type; typedef typename vector_type::global_ordinal_type global_ordinal_type; typedef TpetraMatrixHelpers<Scalar,LO,GO,matrix_type> TMH; //@} /*! * \brief Create a reference-counted pointer to a new empty vector from a * matrix to give the vector the same parallel distribution as the * matrix parallel row distribution. */ static Teuchos::RCP<vector_type> cloneVectorFromMatrixRows( const matrix_type& matrix ) { return Tpetra::createVector<Scalar,LO,GO>( matrix.getRowMap() ); } /*! * \brief Create a reference-counted pointer to a new empty vector from a * matrix to give the vector the same parallel distribution as the * matrix parallel column distribution. */ static Teuchos::RCP<vector_type> cloneVectorFromMatrixCols( const matrix_type& matrix ) { Require( matrix.isFillComplete() ); return Tpetra::createVector<Scalar,LO,GO>( matrix.getColMap() ); } /*! * \brief Get the communicator. */ static Teuchos::RCP<const Teuchos::Comm<int> > getComm( const matrix_type& matrix ) { return matrix.getComm(); } /*! * \brief Get the global number of rows. */ static GO getGlobalNumRows( const matrix_type& matrix ) { return Teuchos::as<GO>( matrix.getGlobalNumRows() ); } /*! * \brief Get the local number of rows. */ static LO getLocalNumRows( const matrix_type& matrix ) { return Teuchos::as<LO>( matrix.getRowMap()->getNodeNumElements() ); } /*! * \brief Get the maximum number of entries in a row globally. */ static GO getGlobalMaxNumRowEntries( const matrix_type& matrix ) { return Teuchos::as<GO>( matrix.getGlobalMaxNumRowEntries() ); } /*! * \brief Given a local row on-process, provide the global ordinal. */ static GO getGlobalRow( const matrix_type& matrix, const LO& local_row ) { Require( matrix.getRowMap()->isNodeLocalElement( local_row ) ); return matrix.getRowMap()->getGlobalElement( local_row ); } /*! * \brief Given a global row on-process, provide the local ordinal. */ static LO getLocalRow( const matrix_type& matrix, const GO& global_row ) { Require( matrix.getRowMap()->isNodeGlobalElement( global_row ) ); return matrix.getRowMap()->getLocalElement( global_row ); } /*! * \brief Given a local col on-process, provide the global ordinal. */ static GO getGlobalCol( const matrix_type& matrix, const LO& local_col ) { Require( matrix.isFillComplete() ); Require( matrix.getColMap()->isNodeLocalElement( local_col ) ); return matrix.getColMap()->getGlobalElement( local_col ); } /*! * \brief Given a global col on-process, provide the local ordinal. */ static LO getLocalCol( const matrix_type& matrix, const GO& global_col ) { Require( matrix.isFillComplete() ); Require( matrix.getColMap()->isNodeGlobalElement( global_col ) ); return matrix.getColMap()->getLocalElement( global_col ); } /*! * \brief Get the owning process rank for the given global rows. */ static void getGlobalRowRanks( const matrix_type& matrix, const Teuchos::ArrayView<global_ordinal_type>& global_rows, const Teuchos::ArrayView<int>& ranks ) { matrix.getRowMap()->getRemoteIndexList( global_rows, ranks ); } /*! * \brief Determine whether or not a given global row is on-process. */ static bool isGlobalRow( const matrix_type& matrix, const GO& global_row ) { return matrix.getRowMap()->isNodeGlobalElement( global_row ); } /*! * \brief Determine whether or not a given local row is on-process. */ static bool isLocalRow( const matrix_type& matrix, const LO& local_row ) { return matrix.getRowMap()->isNodeLocalElement( local_row ); } /*! * \brief Determine whether or not a given global col is on-process. */ static bool isGlobalCol( const matrix_type& matrix, const GO& global_col ) { Require( matrix.isFillComplete() ); return matrix.getColMap()->isNodeGlobalElement( global_col ); } /*! * \brief Determine whether or not a given local col is on-process. */ static bool isLocalCol( const matrix_type& matrix, const LO& local_col ) { Require( matrix.isFillComplete() ); return matrix.getColMap()->isNodeLocalElement( local_col ); } /*! * \brief Get a copy of a global row. */ static void getGlobalRowCopy( const matrix_type& matrix, const GO& global_row, const Teuchos::ArrayView<GO>& indices, const Teuchos::ArrayView<Scalar>& values, std::size_t& num_entries ) { Require( matrix.isFillComplete() ); Require( matrix.getRowMap()->isNodeGlobalElement( global_row ) ); matrix.getGlobalRowCopy( global_row, indices, values, num_entries ); } /*! * \brief Get a copy of a local row. */ static void getLocalRowCopy( const matrix_type& matrix, const LO& local_row, const Teuchos::ArrayView<LO>& indices, const Teuchos::ArrayView<Scalar>& values, std::size_t& num_entries ) { Require( matrix.isFillComplete() ); Require( matrix.getRowMap()->isNodeLocalElement( local_row ) ); matrix.getLocalRowCopy( local_row, indices, values, num_entries ); } /*! * \brief Get a copy of the local diagonal of the matrix. */ static void getLocalDiagCopy( const matrix_type& matrix, vector_type& vector ) { matrix.getLocalDiagCopy( vector ); } /*! * \brief Apply the row matrix to a vector. A*x = y. */ static void apply( const matrix_type& A, const vector_type& x, vector_type& y ) { A.apply( x, y ); } /*! * \brief Get a copy of the transpose of a matrix. */ static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix ) { Tpetra::RowMatrixTransposer<Scalar,LO,GO> transposer( matrix ); return transposer.createTranspose(); } /* * \brief Create a reference-counted pointer to a new matrix with a * specified number of off-process nearest-neighbor global rows. */ static Teuchos::RCP<matrix_type> copyNearestNeighbors( const matrix_type& matrix, const GO& num_neighbors ) { Require( num_neighbors >= 0 ); // Setup for neighbor construction. Teuchos::RCP<const Tpetra::Map<LO,GO> > empty_map = Tpetra::createUniformContigMap<LO,GO>( 0, matrix.getComm() ); Teuchos::RCP<matrix_type> neighbor_matrix = Tpetra::createCrsMatrix<Scalar,LO,GO>( empty_map ); neighbor_matrix->fillComplete(); Teuchos::ArrayView<const GO> global_rows; typename Teuchos::ArrayView<const GO>::const_iterator global_rows_it; typename Teuchos::Array<GO>::iterator ghost_global_bound; // Get the initial off proc columns. Teuchos::Array<GO> ghost_global_rows = TMH::getOffProcColsAsRows( matrix ); // Build the neighbors by traversing the graph. for ( GO i = 0; i < num_neighbors; ++i ) { // Get rid of the global rows that belong to the original // matrix. We don't need to store these, just the neighbors. global_rows = matrix.getRowMap()->getNodeElementList(); for ( global_rows_it = global_rows.begin(); global_rows_it != global_rows.end(); ++global_rows_it ) { ghost_global_bound = std::remove( ghost_global_rows.begin(), ghost_global_rows.end(), *global_rows_it ); ghost_global_rows.resize( std::distance(ghost_global_rows.begin(), ghost_global_bound) ); } // Get the current set of global rows in the neighbor matrix. global_rows = neighbor_matrix->getRowMap()->getNodeElementList(); // Append the on proc neighbor columns to the off proc columns. for ( global_rows_it = global_rows.begin(); global_rows_it != global_rows.end(); ++global_rows_it ) { ghost_global_rows.push_back( *global_rows_it ); } // Make a new map of the combined global rows and off proc columns. Teuchos::RCP<const Tpetra::Map<LO,GO> > ghost_map = Tpetra::createNonContigMap<LO,GO>( ghost_global_rows(), neighbor_matrix->getComm() ); // Import the neighbor matrix with the new neighbor. Tpetra::Import<LO,GO> ghost_importer( matrix.getRowMap(), ghost_map ); neighbor_matrix = TMH::importAndFillCompleteMatrix( matrix, ghost_importer ); // Get the next rows in the graph. ghost_global_rows = TMH::getOffProcColsAsRows( *neighbor_matrix ); } Ensure( !neighbor_matrix.is_null() ); Ensure( neighbor_matrix->isFillComplete() ); return neighbor_matrix; } }; //---------------------------------------------------------------------------// #endif // end MCLS_TPETRACRSMATRIXADAPTER_HPP } // end namespace MCLS //---------------------------------------------------------------------------// // end MCLS_TpetraCrsMatrixAdapter.hpp //---------------------------------------------------------------------------// <commit_msg>updated Tpetra::CrsMatrix transpose method for new constructor<commit_after>//---------------------------------------------------------------------------// /* Copyright (c) 2012, Stuart R. Slattery All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: *: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. *: Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. *: Neither the name of the University of Wisconsin - Madison nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ //---------------------------------------------------------------------------// /*! * \file MCLS_TpetraCrsMatrixAdapter.hpp * \author Stuart R. Slattery * \brief Tpetra::CrsMatrix Adapter. */ //---------------------------------------------------------------------------// #ifndef MCLS_TPETRACRSMATRIXADAPTER_HPP #define MCLS_TPETRACRSMATRIXADAPTER_HPP #include <algorithm> #include <MCLS_DBC.hpp> #include <MCLS_MatrixTraits.hpp> #include <MCLS_TpetraHelpers.hpp> #include <Teuchos_as.hpp> #include <Teuchos_ArrayView.hpp> #include <Teuchos_Array.hpp> #include <Teuchos_Comm.hpp> #include <Tpetra_Vector.hpp> #include <Tpetra_CrsMatrix.hpp> #include <Tpetra_Map.hpp> #include <Tpetra_Import.hpp> #include <Tpetra_RowMatrixTransposer.hpp> #include <Tpetra_Distributor.hpp> namespace MCLS { //---------------------------------------------------------------------------// /*! * \class MatrixTraits * \brief Traits specialization for Tpetra::CrsMatrix. */ template<class Scalar, class LO, class GO> class MatrixTraits<Tpetra::Vector<Scalar,LO,GO>, Tpetra::CrsMatrix<Scalar,LO,GO> > { public: //@{ //! Typedefs. typedef typename Tpetra::CrsMatrix<Scalar,LO,GO> matrix_type; typedef typename Tpetra::Vector<Scalar,LO,GO> vector_type; typedef typename vector_type::scalar_type scalar_type; typedef typename vector_type::local_ordinal_type local_ordinal_type; typedef typename vector_type::global_ordinal_type global_ordinal_type; typedef TpetraMatrixHelpers<Scalar,LO,GO,matrix_type> TMH; //@} /*! * \brief Create a reference-counted pointer to a new empty vector from a * matrix to give the vector the same parallel distribution as the * matrix parallel row distribution. */ static Teuchos::RCP<vector_type> cloneVectorFromMatrixRows( const matrix_type& matrix ) { return Tpetra::createVector<Scalar,LO,GO>( matrix.getRowMap() ); } /*! * \brief Create a reference-counted pointer to a new empty vector from a * matrix to give the vector the same parallel distribution as the * matrix parallel column distribution. */ static Teuchos::RCP<vector_type> cloneVectorFromMatrixCols( const matrix_type& matrix ) { Require( matrix.isFillComplete() ); return Tpetra::createVector<Scalar,LO,GO>( matrix.getColMap() ); } /*! * \brief Get the communicator. */ static Teuchos::RCP<const Teuchos::Comm<int> > getComm( const matrix_type& matrix ) { return matrix.getComm(); } /*! * \brief Get the global number of rows. */ static GO getGlobalNumRows( const matrix_type& matrix ) { return Teuchos::as<GO>( matrix.getGlobalNumRows() ); } /*! * \brief Get the local number of rows. */ static LO getLocalNumRows( const matrix_type& matrix ) { return Teuchos::as<LO>( matrix.getRowMap()->getNodeNumElements() ); } /*! * \brief Get the maximum number of entries in a row globally. */ static GO getGlobalMaxNumRowEntries( const matrix_type& matrix ) { return Teuchos::as<GO>( matrix.getGlobalMaxNumRowEntries() ); } /*! * \brief Given a local row on-process, provide the global ordinal. */ static GO getGlobalRow( const matrix_type& matrix, const LO& local_row ) { Require( matrix.getRowMap()->isNodeLocalElement( local_row ) ); return matrix.getRowMap()->getGlobalElement( local_row ); } /*! * \brief Given a global row on-process, provide the local ordinal. */ static LO getLocalRow( const matrix_type& matrix, const GO& global_row ) { Require( matrix.getRowMap()->isNodeGlobalElement( global_row ) ); return matrix.getRowMap()->getLocalElement( global_row ); } /*! * \brief Given a local col on-process, provide the global ordinal. */ static GO getGlobalCol( const matrix_type& matrix, const LO& local_col ) { Require( matrix.isFillComplete() ); Require( matrix.getColMap()->isNodeLocalElement( local_col ) ); return matrix.getColMap()->getGlobalElement( local_col ); } /*! * \brief Given a global col on-process, provide the local ordinal. */ static LO getLocalCol( const matrix_type& matrix, const GO& global_col ) { Require( matrix.isFillComplete() ); Require( matrix.getColMap()->isNodeGlobalElement( global_col ) ); return matrix.getColMap()->getLocalElement( global_col ); } /*! * \brief Get the owning process rank for the given global rows. */ static void getGlobalRowRanks( const matrix_type& matrix, const Teuchos::ArrayView<global_ordinal_type>& global_rows, const Teuchos::ArrayView<int>& ranks ) { matrix.getRowMap()->getRemoteIndexList( global_rows, ranks ); } /*! * \brief Determine whether or not a given global row is on-process. */ static bool isGlobalRow( const matrix_type& matrix, const GO& global_row ) { return matrix.getRowMap()->isNodeGlobalElement( global_row ); } /*! * \brief Determine whether or not a given local row is on-process. */ static bool isLocalRow( const matrix_type& matrix, const LO& local_row ) { return matrix.getRowMap()->isNodeLocalElement( local_row ); } /*! * \brief Determine whether or not a given global col is on-process. */ static bool isGlobalCol( const matrix_type& matrix, const GO& global_col ) { Require( matrix.isFillComplete() ); return matrix.getColMap()->isNodeGlobalElement( global_col ); } /*! * \brief Determine whether or not a given local col is on-process. */ static bool isLocalCol( const matrix_type& matrix, const LO& local_col ) { Require( matrix.isFillComplete() ); return matrix.getColMap()->isNodeLocalElement( local_col ); } /*! * \brief Get a copy of a global row. */ static void getGlobalRowCopy( const matrix_type& matrix, const GO& global_row, const Teuchos::ArrayView<GO>& indices, const Teuchos::ArrayView<Scalar>& values, std::size_t& num_entries ) { Require( matrix.isFillComplete() ); Require( matrix.getRowMap()->isNodeGlobalElement( global_row ) ); matrix.getGlobalRowCopy( global_row, indices, values, num_entries ); } /*! * \brief Get a copy of a local row. */ static void getLocalRowCopy( const matrix_type& matrix, const LO& local_row, const Teuchos::ArrayView<LO>& indices, const Teuchos::ArrayView<Scalar>& values, std::size_t& num_entries ) { Require( matrix.isFillComplete() ); Require( matrix.getRowMap()->isNodeLocalElement( local_row ) ); matrix.getLocalRowCopy( local_row, indices, values, num_entries ); } /*! * \brief Get a copy of the local diagonal of the matrix. */ static void getLocalDiagCopy( const matrix_type& matrix, vector_type& vector ) { matrix.getLocalDiagCopy( vector ); } /*! * \brief Apply the row matrix to a vector. A*x = y. */ static void apply( const matrix_type& A, const vector_type& x, vector_type& y ) { A.apply( x, y ); } /*! * \brief Get a copy of the transpose of a matrix. */ static Teuchos::RCP<matrix_type> copyTranspose( const matrix_type& matrix ) { Teuchos::RCP<const matrix_type> matrix_rcp = Teuchos::rcpFromRef( matrix ); Tpetra::RowMatrixTransposer<Scalar,LO,GO> transposer( matrix_rcp ); return transposer.createTranspose(); } /* * \brief Create a reference-counted pointer to a new matrix with a * specified number of off-process nearest-neighbor global rows. */ static Teuchos::RCP<matrix_type> copyNearestNeighbors( const matrix_type& matrix, const GO& num_neighbors ) { Require( num_neighbors >= 0 ); // Setup for neighbor construction. Teuchos::RCP<const Tpetra::Map<LO,GO> > empty_map = Tpetra::createUniformContigMap<LO,GO>( 0, matrix.getComm() ); Teuchos::RCP<matrix_type> neighbor_matrix = Tpetra::createCrsMatrix<Scalar,LO,GO>( empty_map ); neighbor_matrix->fillComplete(); Teuchos::ArrayView<const GO> global_rows; typename Teuchos::ArrayView<const GO>::const_iterator global_rows_it; typename Teuchos::Array<GO>::iterator ghost_global_bound; // Get the initial off proc columns. Teuchos::Array<GO> ghost_global_rows = TMH::getOffProcColsAsRows( matrix ); // Build the neighbors by traversing the graph. for ( GO i = 0; i < num_neighbors; ++i ) { // Get rid of the global rows that belong to the original // matrix. We don't need to store these, just the neighbors. global_rows = matrix.getRowMap()->getNodeElementList(); for ( global_rows_it = global_rows.begin(); global_rows_it != global_rows.end(); ++global_rows_it ) { ghost_global_bound = std::remove( ghost_global_rows.begin(), ghost_global_rows.end(), *global_rows_it ); ghost_global_rows.resize( std::distance(ghost_global_rows.begin(), ghost_global_bound) ); } // Get the current set of global rows in the neighbor matrix. global_rows = neighbor_matrix->getRowMap()->getNodeElementList(); // Append the on proc neighbor columns to the off proc columns. for ( global_rows_it = global_rows.begin(); global_rows_it != global_rows.end(); ++global_rows_it ) { ghost_global_rows.push_back( *global_rows_it ); } // Make a new map of the combined global rows and off proc columns. Teuchos::RCP<const Tpetra::Map<LO,GO> > ghost_map = Tpetra::createNonContigMap<LO,GO>( ghost_global_rows(), neighbor_matrix->getComm() ); // Import the neighbor matrix with the new neighbor. Tpetra::Import<LO,GO> ghost_importer( matrix.getRowMap(), ghost_map ); neighbor_matrix = TMH::importAndFillCompleteMatrix( matrix, ghost_importer ); // Get the next rows in the graph. ghost_global_rows = TMH::getOffProcColsAsRows( *neighbor_matrix ); } Ensure( !neighbor_matrix.is_null() ); Ensure( neighbor_matrix->isFillComplete() ); return neighbor_matrix; } }; //---------------------------------------------------------------------------// #endif // end MCLS_TPETRACRSMATRIXADAPTER_HPP } // end namespace MCLS //---------------------------------------------------------------------------// // end MCLS_TpetraCrsMatrixAdapter.hpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "FluxBC.h" template<> InputParameters validParams<FluxBC>() { InputParameters params = validParams<IntegratedBC>(); return params; } FluxBC::FluxBC(const std::string & name, InputParameters params) : IntegratedBC(name, params) { } FluxBC::~FluxBC() { } Real FluxBC::computeQpResidual() { return computeQpFluxResidual() * _normals[_qp] * _test[_i][_qp]; } Real FluxBC::computeQpJacobian() { return computeQpFluxJacobian() * _normals[_qp] * _test[_i][_qp]; } <commit_msg>Fixing sign in FluxBC (refs #617)<commit_after>/****************************************************************/ /* DO NOT MODIFY THIS HEADER */ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* (c) 2010 Battelle Energy Alliance, LLC */ /* ALL RIGHTS RESERVED */ /* */ /* Prepared by Battelle Energy Alliance, LLC */ /* Under Contract No. DE-AC07-05ID14517 */ /* With the U. S. Department of Energy */ /* */ /* See COPYRIGHT for full restrictions */ /****************************************************************/ #include "FluxBC.h" template<> InputParameters validParams<FluxBC>() { InputParameters params = validParams<IntegratedBC>(); return params; } FluxBC::FluxBC(const std::string & name, InputParameters params) : IntegratedBC(name, params) { } FluxBC::~FluxBC() { } Real FluxBC::computeQpResidual() { return - computeQpFluxResidual() * _normals[_qp] * _test[_i][_qp]; } Real FluxBC::computeQpJacobian() { return - computeQpFluxJacobian() * _normals[_qp] * _test[_i][_qp]; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** Copyright (C) 2014 Nomovok Ltd. All rights reserved. ** Contact: [email protected] ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //![0] #include <QGuiApplication> #include <QQmlComponent> #include <QQuickView> #include <QDebug> #include "qrcloader.h" int main(int argc, char *argv[]) { int ret; QGuiApplication app(argc, argv); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); //QQmlContext *ctxt = view.rootContext(); QQmlEngine *engine = view.engine(); #if 1 QrcLoader qrcloader(engine); ret = qrcloader.load(":/app.qmc", "app.qrc"); if(ret != 0){ qWarning() << "Couldn't load from qrc file error=%d" << ret; return 0; } QQmlComponent *component = qrcloader.getRootComponent(); #else QQmlComponent *component = new QQmlComponent(engine, QUrl("qml/multipleitems.qml")); #endif if (!component) { qDebug() << "Could not load component"; return -1; } if (!component->isReady()) { qDebug() << "Component is not ready"; if (component->isError()) { foreach (const QQmlError &error, component->errors()) { qDebug() << error.toString(); } } return -1; } QObject *rootObject = component->create(); if (!rootObject) { qDebug() << "Could not create root object"; return -1; } view.setContent(component->url(), component, rootObject); view.show(); ret = app.exec(); delete rootObject; delete component; return ret; } //![0] <commit_msg>Change plugin test to load directly, not via qrc<commit_after>/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** Copyright (C) 2014 Nomovok Ltd. All rights reserved. ** Contact: [email protected] ** ** This file is part of the documentation of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Digia Plc and its Subsidiary(-ies) nor the names ** of its contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** ** $QT_END_LICENSE$ ** ****************************************************************************/ //![0] #include <QGuiApplication> #include <QQmlComponent> #include <QQuickView> #include <QDebug> #include "qrcloader.h" int main(int argc, char *argv[]) { int ret; QGuiApplication app(argc, argv); QQuickView view; view.setResizeMode(QQuickView::SizeRootObjectToView); //QQmlContext *ctxt = view.rootContext(); QQmlEngine *engine = view.engine(); #if 1 QmcLoader loader(engine); QQmlComponent *component = loader.loadComponent("app.qmc"); #else QQmlComponent *component = new QQmlComponent(engine, QUrl("qml/multipleitems.qml")); #endif if (!component) { qDebug() << "Could not load component"; return -1; } if (!component->isReady()) { qDebug() << "Component is not ready"; if (component->isError()) { foreach (const QQmlError &error, component->errors()) { qDebug() << error.toString(); } } return -1; } QObject *rootObject = component->create(); if (!rootObject) { qDebug() << "Could not create root object"; return -1; } view.setContent(component->url(), component, rootObject); view.show(); ret = app.exec(); delete rootObject; delete component; return ret; } //![0] <|endoftext|>
<commit_before>#include "inner_readers.h" #include "../flags.h" #include <cassert> using namespace dariadb; using namespace dariadb::compression; using namespace dariadb::storage; InnerReader::InnerReader(dariadb::Flag flag, dariadb::Time from, dariadb::Time to) : _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end = false; } void InnerReader::add(Chunk_Ptr c) { std::lock_guard<std::mutex> lg(_mutex); this->_chunks[c->first.id].push_back(c); } void InnerReader::add_tp(Chunk_Ptr c) { std::lock_guard<std::mutex> lg(_mutex); this->_tp_chunks[c->first.id].push_back(c); } bool InnerReader::isEnd() const { return this->end && this->_tp_readed; } dariadb::IdArray InnerReader::getIds()const { dariadb::IdArray result; result.resize(_chunks.size()); size_t pos = 0; for (auto &kv : _chunks) { result[pos] = kv.first; pos++; } return result; } void InnerReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (Chunk_Ptr cur_ch:ch.second) { if (cur_ch->is_dropped) { throw MAKE_EXCEPTION("InnerReader::cur_ch->is_dropped"); } cur_ch->lock(); auto bw = std::make_shared<BinaryBuffer>(cur_ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, cur_ch->first); if (check_meas(cur_ch->first)) { auto sub = cur_ch->first; clb->call(sub); } for (size_t j = 0; j < cur_ch->count; j++) { auto sub = crr.read(); sub.id = cur_ch->first.id; if (check_meas(sub)) { clb->call(sub); } else { if (sub.time > _to) { break; } } } cur_ch->unlock(); } } _chunks.clear(); end = true; } void InnerReader::readTimePoint(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex_tp); std::list<Chunk_Ptr> to_read_chunks{}; for (auto cand_ch : _tp_chunks) { auto candidate = cand_ch.second.front(); for (auto cur_chunk: cand_ch.second) { if (candidate->first.time < cur_chunk->first.time) { candidate = cur_chunk; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { auto bw = std::make_shared<BinaryBuffer>(ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, ch->first); Meas candidate; candidate = ch->first; ch->lock(); for (size_t i = 0; i < ch->count; i++) { auto sub = crr.read(); sub.id = ch->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; }if (sub.time > _from) { break; } } ch->unlock(); if (candidate.time <= _from) { //TODO make as options candidate.time = _from; clb->call(candidate); _tp_readed_times.insert(std::make_tuple(candidate.id, candidate.time)); } } auto m = dariadb::Meas::empty(); m.time = _from; m.flag = dariadb::Flags::NO_DATA; for (auto id : _not_exist) { m.id = id; clb->call(m); } _tp_readed = true; } bool InnerReader::check_meas(const Meas&m)const { auto tmp = std::make_tuple(m.id, m.time); if (this->_tp_readed_times.find(tmp) != _tp_readed_times.end()) { return false; } using utils::inInterval; if ((in_filter(_flag, m.flag)) && (inInterval(_from, _to, m.time))) { return true; } return false; } Reader_ptr InnerReader::clone()const { auto res = std::make_shared<InnerReader>(_flag, _from, _to); res->_chunks = _chunks; res->_tp_chunks = _tp_chunks; res->_flag = _flag; res->_from = _from; res->_to = _to; res->_tp_readed = _tp_readed; res->end = end; res->_not_exist = _not_exist; res->_tp_readed_times = _tp_readed_times; return res; } void InnerReader::reset() { end = false; _tp_readed = false; _tp_readed_times.clear(); } InnerCurrentValuesReader::InnerCurrentValuesReader() { this->end = false; } InnerCurrentValuesReader::~InnerCurrentValuesReader() {} bool InnerCurrentValuesReader::isEnd() const { return this->end; } void InnerCurrentValuesReader::readCurVals(storage::ReaderClb*clb) { for (auto v : _cur_values) { clb->call(v); } } void InnerCurrentValuesReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); readCurVals(clb); this->end = true; } IdArray InnerCurrentValuesReader::getIds()const { dariadb::IdArray result; result.resize(_cur_values.size()); size_t pos = 0; for (auto v : _cur_values) { result[pos] = v.id; pos++; } return result; } Reader_ptr InnerCurrentValuesReader::clone()const { auto raw_reader = new InnerCurrentValuesReader(); Reader_ptr result{ raw_reader }; raw_reader->_cur_values = _cur_values; return result; } void InnerCurrentValuesReader::reset() { end = false; } <commit_msg>verbose<commit_after>#include "inner_readers.h" #include "../flags.h" #include <cassert> using namespace dariadb; using namespace dariadb::compression; using namespace dariadb::storage; InnerReader::InnerReader(dariadb::Flag flag, dariadb::Time from, dariadb::Time to) : _chunks{}, _flag(flag), _from(from), _to(to), _tp_readed(false) { is_time_point_reader = false; end = false; } void InnerReader::add(Chunk_Ptr c) { std::lock_guard<std::mutex> lg(_mutex); this->_chunks[c->first.id].push_back(c); } void InnerReader::add_tp(Chunk_Ptr c) { std::lock_guard<std::mutex> lg(_mutex); this->_tp_chunks[c->first.id].push_back(c); } bool InnerReader::isEnd() const { return this->end && this->_tp_readed; } dariadb::IdArray InnerReader::getIds()const { dariadb::IdArray result; result.resize(_chunks.size()); size_t pos = 0; for (auto &kv : _chunks) { result[pos] = kv.first; pos++; } return result; } void InnerReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); if (!_tp_readed) { this->readTimePoint(clb); } for (auto ch : _chunks) { for (Chunk_Ptr cur_ch:ch.second) { if (cur_ch->is_dropped) { throw MAKE_EXCEPTION("InnerReader::cur_ch->is_dropped"); } cur_ch->lock(); auto bw = std::make_shared<BinaryBuffer>(cur_ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, cur_ch->first); if (check_meas(cur_ch->first)) { auto sub = cur_ch->first; clb->call(sub); } for (size_t j = 0; j < cur_ch->count; j++) { auto sub = crr.read(); sub.id = cur_ch->first.id; if (check_meas(sub)) { clb->call(sub); } else { if (sub.time > _to) { break; } } } cur_ch->unlock(); } } _chunks.clear(); end = true; } void InnerReader::readTimePoint(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex_tp); std::list<Chunk_Ptr> to_read_chunks{}; for (auto cand_ch : _tp_chunks) { auto candidate = cand_ch.second.front(); for (auto cur_chunk: cand_ch.second) { if (candidate->first.time < cur_chunk->first.time) { candidate = cur_chunk; } } to_read_chunks.push_back(candidate); } for (auto ch : to_read_chunks) { auto bw = std::make_shared<BinaryBuffer>(ch->bw->get_range()); bw->reset_pos(); CopmressedReader crr(bw, ch->first); Meas candidate; candidate = ch->first; ch->lock(); for (size_t i = 0; i < ch->count; i++) { auto sub = crr.read(); std::cout << "sub: t" << sub.time << " v: " << sub.value << " f: " << sub.flag << " s: " << sub.src << std::endl; sub.id = ch->first.id; if ((sub.time <= _from) && (sub.time >= candidate.time)) { candidate = sub; }if (sub.time > _from) { break; } } ch->unlock(); if (candidate.time <= _from) { //TODO make as options candidate.time = _from; clb->call(candidate); _tp_readed_times.insert(std::make_tuple(candidate.id, candidate.time)); } } auto m = dariadb::Meas::empty(); m.time = _from; m.flag = dariadb::Flags::NO_DATA; for (auto id : _not_exist) { m.id = id; clb->call(m); } _tp_readed = true; } bool InnerReader::check_meas(const Meas&m)const { auto tmp = std::make_tuple(m.id, m.time); if (this->_tp_readed_times.find(tmp) != _tp_readed_times.end()) { return false; } using utils::inInterval; if ((in_filter(_flag, m.flag)) && (inInterval(_from, _to, m.time))) { return true; } return false; } Reader_ptr InnerReader::clone()const { auto res = std::make_shared<InnerReader>(_flag, _from, _to); res->_chunks = _chunks; res->_tp_chunks = _tp_chunks; res->_flag = _flag; res->_from = _from; res->_to = _to; res->_tp_readed = _tp_readed; res->end = end; res->_not_exist = _not_exist; res->_tp_readed_times = _tp_readed_times; return res; } void InnerReader::reset() { end = false; _tp_readed = false; _tp_readed_times.clear(); } InnerCurrentValuesReader::InnerCurrentValuesReader() { this->end = false; } InnerCurrentValuesReader::~InnerCurrentValuesReader() {} bool InnerCurrentValuesReader::isEnd() const { return this->end; } void InnerCurrentValuesReader::readCurVals(storage::ReaderClb*clb) { for (auto v : _cur_values) { clb->call(v); } } void InnerCurrentValuesReader::readNext(storage::ReaderClb*clb) { std::lock_guard<std::mutex> lg(_mutex); readCurVals(clb); this->end = true; } IdArray InnerCurrentValuesReader::getIds()const { dariadb::IdArray result; result.resize(_cur_values.size()); size_t pos = 0; for (auto v : _cur_values) { result[pos] = v.id; pos++; } return result; } Reader_ptr InnerCurrentValuesReader::clone()const { auto raw_reader = new InnerCurrentValuesReader(); Reader_ptr result{ raw_reader }; raw_reader->_cur_values = _cur_values; return result; } void InnerCurrentValuesReader::reset() { end = false; } <|endoftext|>
<commit_before>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #pragma once #include <vector> #include <type_traits> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/mpl/at.hpp> #include <boost/preprocessor.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/function_types/parameter_types.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include <windows.h> namespace hadesmem { class Process; class RemoteFunctionRet { public: RemoteFunctionRet(DWORD_PTR ReturnValue, DWORD64 ReturnValue64, DWORD LastError); DWORD_PTR GetReturnValue() const; DWORD64 GetReturnValue64() const; DWORD GetLastError() const; private: DWORD_PTR m_ReturnValue; DWORD64 m_ReturnValue64; DWORD m_LastError; }; enum class CallConv { kDefault, kCdecl, kStdCall, kThisCall, kFastCall, kX64 }; RemoteFunctionRet Call(Process const& process, LPCVOID address, CallConv call_conv, std::vector<PVOID> const& args); std::vector<RemoteFunctionRet> CallMulti(Process const& process, std::vector<LPCVOID> addresses, std::vector<CallConv> call_convs, std::vector<std::vector<PVOID>> const& args_full); // TODO: Improve and clean up this mess, move to different file, etc. #ifndef HADESMEM_CALL_MAX_ARGS #define HADESMEM_CALL_MAX_ARGS 10 #endif // #ifndef HADESMEM_CALL_MAX_ARGS #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_REPEAT #error "[HadesMem] HADESMEM_CALL_MAX_ARGS exceeds Boost.Preprocessor repeat limit." #endif // #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_REPEAT #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_ITERATION #error "[HadesMem] HADESMEM_CALL_MAX_ARGS exceeds Boost.Preprocessor iteration limit." #endif // #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_ITERATION #define HADESMEM_CALL_DEFINE_ARG(z, n, unused) , typename boost::mpl::at_c<boost::function_types::parameter_types<FuncT>, n>::type a##n #define HADESMEM_CALL_ADD_ARG(z, n, unused) \ typedef typename boost::mpl::at_c<boost::function_types::parameter_types<FuncT>, n>::type A##n;\ static_assert(std::is_integral<A##n>::value || std::is_pointer<A##n>::value, "Currently only integral or pointer types are supported.");\ static_assert(sizeof(A##n) <= sizeof(PVOID), "Currently only memsize (or smaller) types are supported.");\ args.push_back((PVOID)(a##n));\ #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT>\ RemoteFunctionRet Call(Process const& process, LPCVOID address, CallConv call_conv \ BOOST_PP_REPEAT(n, HADESMEM_CALL_DEFINE_ARG, ~))\ {\ static_assert(boost::function_types::function_arity<FuncT>::value == n, "Invalid number of arguments.");\ std::vector<PVOID> args;\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ return Call(process, address, call_conv, args);\ }\ #define BOOST_PP_LOCAL_LIMITS (1, HADESMEM_CALL_MAX_ARGS) // TODO: Document why this is necessary. #if defined(HADESMEM_GCC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wint-to-pointer-cast" #endif // #if defined(HADESMEM_GCC) #include BOOST_PP_LOCAL_ITERATE() #if defined(HADESMEM_GCC) #pragma GCC diagnostic pop #endif // #if defined(HADESMEM_GCC) #undef HADESMEM_CALL_DEFINE_ARG #undef HADESMEM_CALL_ADD_ARG } <commit_msg>* Work around a GCC warning.<commit_after>// Copyright Joshua Boyce 2010-2012. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // This file is part of HadesMem. // <http://www.raptorfactor.com/> <[email protected]> #pragma once #include <vector> #include <type_traits> #include "hadesmem/detail/warning_disable_prefix.hpp" #include <boost/mpl/at.hpp> #include <boost/preprocessor.hpp> #include <boost/function_types/result_type.hpp> #include <boost/function_types/function_arity.hpp> #include <boost/function_types/parameter_types.hpp> #include "hadesmem/detail/warning_disable_suffix.hpp" #include <windows.h> namespace hadesmem { class Process; class RemoteFunctionRet { public: RemoteFunctionRet(DWORD_PTR ReturnValue, DWORD64 ReturnValue64, DWORD LastError); DWORD_PTR GetReturnValue() const; DWORD64 GetReturnValue64() const; DWORD GetLastError() const; private: DWORD_PTR m_ReturnValue; DWORD64 m_ReturnValue64; DWORD m_LastError; }; enum class CallConv { kDefault, kCdecl, kStdCall, kThisCall, kFastCall, kX64 }; RemoteFunctionRet Call(Process const& process, LPCVOID address, CallConv call_conv, std::vector<PVOID> const& args); std::vector<RemoteFunctionRet> CallMulti(Process const& process, std::vector<LPCVOID> addresses, std::vector<CallConv> call_convs, std::vector<std::vector<PVOID>> const& args_full); // TODO: Improve and clean up this mess, move to different file, etc. #ifndef HADESMEM_CALL_MAX_ARGS #define HADESMEM_CALL_MAX_ARGS 10 #endif // #ifndef HADESMEM_CALL_MAX_ARGS #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_REPEAT #error "[HadesMem] HADESMEM_CALL_MAX_ARGS exceeds Boost.Preprocessor repeat limit." #endif // #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_REPEAT #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_ITERATION #error "[HadesMem] HADESMEM_CALL_MAX_ARGS exceeds Boost.Preprocessor iteration limit." #endif // #if HADESMEM_CALL_MAX_ARGS > BOOST_PP_LIMIT_ITERATION #define HADESMEM_CALL_DEFINE_ARG(z, n, unused) , typename boost::mpl::at_c<boost::function_types::parameter_types<FuncT>, n>::type a##n #define HADESMEM_CALL_ADD_ARG(z, n, unused) \ typedef typename boost::mpl::at_c<boost::function_types::parameter_types<FuncT>, n>::type A##n;\ static_assert(std::is_integral<A##n>::value || std::is_pointer<A##n>::value, "Currently only integral or pointer types are supported.");\ static_assert(sizeof(A##n) <= sizeof(PVOID), "Currently only memsize (or smaller) types are supported.");\ union U##n { A##n a; PVOID p; } u##n;\ u##n.a = a##n;\ args.push_back(u##n.p);\ #define BOOST_PP_LOCAL_MACRO(n)\ template <typename FuncT>\ RemoteFunctionRet Call(Process const& process, LPCVOID address, CallConv call_conv \ BOOST_PP_REPEAT(n, HADESMEM_CALL_DEFINE_ARG, ~))\ {\ static_assert(boost::function_types::function_arity<FuncT>::value == n, "Invalid number of arguments.");\ std::vector<PVOID> args;\ BOOST_PP_REPEAT(n, HADESMEM_CALL_ADD_ARG, ~)\ return Call(process, address, call_conv, args);\ }\ #define BOOST_PP_LOCAL_LIMITS (1, HADESMEM_CALL_MAX_ARGS) #include BOOST_PP_LOCAL_ITERATE() #undef HADESMEM_CALL_DEFINE_ARG #undef HADESMEM_CALL_ADD_ARG } <|endoftext|>
<commit_before>/* * Copyright 2011, 2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thread> #include <GL/freeglut.h> #include "DOMImplementationImp.h" #include "ECMAScript.h" #include "WindowImp.h" #include "font/FontDatabase.h" #include "http/HTTPConnection.h" #include "Test.util.h" #ifdef USE_V8 #include "v8/ScriptV8.h" #endif // USE_V8 using namespace org::w3c::dom::bootstrap; using namespace org::w3c::dom; html::Window window(0); int main(int argc, char* argv[]) { #ifdef USE_V8 v8::HandleScope handleScope; #endif // USE_V8 if (argc < 3) { std::cout << "usage : " << argv[0] << " navigator_directory [user.css]\n"; return EXIT_FAILURE; } init(&argc, argv); initLogLevel(&argc, argv); initFonts(&argc, argv); // Load the default CSS file std::string defaultSheet = argv[1]; defaultSheet += "/default.css"; getDOMImplementation()->setDefaultCSSStyleSheet(loadStyleSheet(defaultSheet.c_str())); // Load the user CSS file if (3 <= argc) getDOMImplementation()->setUserCSSStyleSheet(loadStyleSheet(argv[2])); std::thread httpService(std::ref(HttpConnectionManager::getInstance())); // Set privileges to the navigator window. char navigatorUrl[PATH_MAX + 7]; strcpy(navigatorUrl, "file://"); realpath(argv[1], navigatorUrl + 7); HttpRequest::setAboutPath(navigatorUrl + 7); strcat(navigatorUrl, "/navigator.html"); WindowImp* imp = new WindowImp(); window = imp; imp->enableZoom(false); imp->open(utfconv(navigatorUrl), u"_self", u"", true); glutMainLoop(); window = 0; ECMAScriptContext::shutDown(); HttpConnectionManager::getInstance().stop(); httpService.join(); } <commit_msg>(main) : Fix a bug.<commit_after>/* * Copyright 2011, 2012 Esrille Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <thread> #include <GL/freeglut.h> #include "DOMImplementationImp.h" #include "ECMAScript.h" #include "WindowImp.h" #include "font/FontDatabase.h" #include "http/HTTPConnection.h" #include "Test.util.h" #ifdef USE_V8 #include "v8/ScriptV8.h" #endif // USE_V8 using namespace org::w3c::dom::bootstrap; using namespace org::w3c::dom; html::Window window(0); int main(int argc, char* argv[]) { #ifdef USE_V8 v8::HandleScope handleScope; #endif // USE_V8 if (argc < 2) { std::cout << "usage : " << argv[0] << " navigator_directory [user.css]\n"; return EXIT_FAILURE; } init(&argc, argv); initLogLevel(&argc, argv); initFonts(&argc, argv); // Load the default CSS file std::string defaultSheet = argv[1]; defaultSheet += "/default.css"; getDOMImplementation()->setDefaultCSSStyleSheet(loadStyleSheet(defaultSheet.c_str())); // Load the user CSS file if (3 <= argc) getDOMImplementation()->setUserCSSStyleSheet(loadStyleSheet(argv[2])); std::thread httpService(std::ref(HttpConnectionManager::getInstance())); // Set privileges to the navigator window. char navigatorUrl[PATH_MAX + 7]; strcpy(navigatorUrl, "file://"); realpath(argv[1], navigatorUrl + 7); HttpRequest::setAboutPath(navigatorUrl + 7); strcat(navigatorUrl, "/navigator.html"); WindowImp* imp = new WindowImp(); window = imp; imp->enableZoom(false); imp->open(utfconv(navigatorUrl), u"_self", u"", true); glutMainLoop(); window = 0; ECMAScriptContext::shutDown(); HttpConnectionManager::getInstance().stop(); httpService.join(); } <|endoftext|>
<commit_before>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) UNSPECIFIED - FILL IN, 2005 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: loggingLogSvcHandler.cpp,v 1.29 2008/04/24 09:07:38 cparedes Exp $" * * who when what * -------- -------- ---------------------------------------------- * dfugate 2005-04-04 created */ #include "loggingLogSvcHandler.h" #include <loggingLoggingProxy.h> #include <loggingLogLevelDefinition.h> #ifdef MAKE_VXWORKS #include <acsutil.h> #endif #include <ace/Log_Record.h> static char *rcsId="@(#) $Id: loggingLogSvcHandler.cpp,v 1.29 2008/04/24 09:07:38 cparedes Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); namespace Logging { // ---------------------------------------------------------- //helper function used to convert from ACS logging priorities //to ACE log priorities ACE_Log_Priority acs2acePriority(Logging::BaseLog::Priority acsPriority) { ACE_Log_Priority retVal = LM_SHUTDOWN; switch(acsPriority) { case Logging::BaseLog::LM_TRACE: retVal = LM_TRACE; break; case Logging::BaseLog::LM_DEBUG: retVal = LM_DEBUG; break; case Logging::BaseLog::LM_INFO: retVal = LM_INFO; break; case Logging::BaseLog::LM_NOTICE: retVal = LM_NOTICE; break; case Logging::BaseLog::LM_WARNING: retVal = LM_WARNING; break; case Logging::BaseLog::LM_ERROR: retVal = LM_ERROR; break; case Logging::BaseLog::LM_CRITICAL: retVal = LM_CRITICAL; break; case Logging::BaseLog::LM_ALERT: retVal = LM_ALERT; break; case Logging::BaseLog::LM_EMERGENCY: retVal = LM_EMERGENCY; break; case Logging::BaseLog::LM_SHUTDOWN: retVal = LM_SHUTDOWN; break; default: //should NEVER be the case but //if this does occur we default //to a level that will always be //logged retVal = LM_SHUTDOWN; } return retVal; } // ---------------------------------------------------------- //helper function used to convert from ACE logging priorities //to ACS log priorities Logging::BaseLog::Priority ace2acsPriority(ACE_Log_Priority acePriority) { Logging::BaseLog::Priority retVal = Logging::BaseLog::LM_SHUTDOWN; switch(acePriority) { case LM_TRACE: retVal = Logging::BaseLog::LM_TRACE; break; case LM_DEBUG: retVal = Logging::BaseLog::LM_DEBUG; break; case LM_INFO: retVal = Logging::BaseLog::LM_INFO; break; case LM_NOTICE: retVal = Logging::BaseLog::LM_NOTICE; break; case LM_WARNING: retVal = Logging::BaseLog::LM_WARNING; break; case LM_ERROR: retVal = Logging::BaseLog::LM_ERROR; break; case LM_CRITICAL: retVal = Logging::BaseLog::LM_CRITICAL; break; case LM_ALERT: retVal = Logging::BaseLog::LM_ALERT; break; case LM_EMERGENCY: retVal = Logging::BaseLog::LM_EMERGENCY; break; case LM_SHUTDOWN: retVal = Logging::BaseLog::LM_SHUTDOWN; break; default: //should NEVER be the case but //if this does occur we default //to a level that will always be //logged retVal = Logging::BaseLog::LM_SHUTDOWN; } return retVal; } // ---------------------------------------------------------- LogSvcHandler::LogSvcHandler(const std::string& soName) : sourceObjectName_m(soName) { setRemoteLevelType(NOT_DEFINED_LOG_LEVEL); setLocalLevelType(NOT_DEFINED_LOG_LEVEL); char *acsSTDIO = getenv("ACS_LOG_STDOUT"); int envStdioPriority = -1; if (acsSTDIO && *acsSTDIO) { envStdioPriority = atoi(acsSTDIO); } char *acsCentralizeLogger = getenv("ACS_LOG_CENTRAL"); int envCentralizePriority = -1; if (acsCentralizeLogger && *acsCentralizeLogger) { envCentralizePriority = atoi(acsCentralizeLogger); } setLevels(LM_TRACE, LM_TRACE,DEFAULT_LOG_LEVEL); if(envStdioPriority >= 0) setLevels((Priority)-1, static_cast<Logging::BaseLog::Priority>(LogLevelDefinition::getACELogPriority(envStdioPriority)), ENV_LOG_LEVEL); if(envCentralizePriority >= 0) setLevels(static_cast<Logging::BaseLog::Priority>(LogLevelDefinition::getACELogPriority(envCentralizePriority)), (Priority)-1, ENV_LOG_LEVEL); } // ---------------------------------------------------------- void LogSvcHandler::log(const LogRecord& lr) { //may need to make some changes to the message if the CORBA //logging service is down std::string message = lr.message; //if it's a trace we set the message to be "". if((lr.priority==LM_TRACE) && (message==FIELD_UNAVAILABLE)) { message = ""; } //add a newline if the logging service is unavailable if(LoggingProxy::isInit()==false) { message = message + '\n'; } LoggingProxy::File(lr.file.c_str()); LoggingProxy::Line(lr.line); //only set the logging flags if the priority is debug or trace if((lr.priority==LM_DEBUG)||(lr.priority==LM_TRACE)) { LoggingProxy::Flags(LM_SOURCE_INFO | LM_RUNTIME_CONTEXT); } //if the field is available if(lr.method!=FIELD_UNAVAILABLE) { //set the routine name. LoggingProxy::Routine(lr.method.c_str()); } else { LoggingProxy::Routine(""); } if(lr.priority == LM_SHUTDOWN) message = " -- ERROR in the priority of this message, please check the source --" + message; //set the component/container/etc name LoggingProxy::SourceObject(sourceObjectName_m.c_str()); //figure out the time long sec_ = ACE_static_cast(CORBA::ULongLong, lr.timeStamp) / ACE_static_cast(ACE_UINT32, 10000000u) - ACE_UINT64_LITERAL(0x2D8539C80); long usec_ = (lr.timeStamp % 10000000u) / 10; ACE_Time_Value time(sec_, usec_); //create the ACE log message /** * @todo Here there was an assignment to * a local variable never used. * Why was that? * I have now commented it out * int __ace_error = ACE_Log_Msg::last_error_adapter(); */ ACE_Log_Msg::last_error_adapter(); ACE_Log_Msg *ace___ = ACE_Log_Msg::instance(); //create the ACE log record using the message ACE_Log_Record log_record_(acs2acePriority(lr.priority), time, 0); log_record_.msg_data(message.c_str()); // set private flags const int prohibitLocal = getLocalLevel() == LM_SHUTDOWN || lr.priority < getLocalLevel() ? 1 : 0; const int prohibitRemote = getRemoteLevel() == LM_SHUTDOWN ||lr.priority < getRemoteLevel() ? 2 : 0; LoggingProxy::PrivateFlags(prohibitLocal | prohibitRemote); LoggingProxy::LogLevelLocalType(getLocalLevelType()); LoggingProxy::LogLevelRemoteType(getRemoteLevelType()); ace___->log(log_record_, 0); } // ---------------------------------------------------------- std::string LogSvcHandler::getName() const { return std::string("acsLogSvc"); } // ---------------------------------------------------------- void LogSvcHandler::setLevels(Priority remotePriority, Priority localPriority, int type) { if(remotePriority >0 && (type == CDB_REFRESH_LOG_LEVEL || getRemoteLevelType() >= type) ){ setRemoteLevelType(type); setRemoteLevel(remotePriority); } if(localPriority > 0 && ( type == CDB_REFRESH_LOG_LEVEL || getLocalLevelType() >= type )){ setLocalLevelType(type); setLocalLevel(localPriority); } // set global level (min of both) setLevel(getLocalLevel() < getRemoteLevel() ? getLocalLevel() : getRemoteLevel()); } // ---------------------------------------------------------- //--The following section exists solely to remain //--backwards compatible with the ACS 4.0 and earlier //--logging systems. This is provided so that formatted //--(i.e., printf, scanf, etc) messages are supported. //--At some point in time this should //--be removed! //----------------------------------------------------------- LogSvcHandler::DeprecatedLogInfo LogSvcHandler::unformatted2formatted(ACE_Log_Priority messagePriority, const char *fmt, ...) { //tells the compiler to check the format //every time it is called for format string and arguments matching in number //DWF-for some reason this does not compile //__attribute__ ((format (printf, 2, 3))); LogSvcHandler::DeprecatedLogInfo retVal; retVal.priority = ace2acsPriority(messagePriority); //take the format string along with the parameters //and convert them into the formatted string. va_list argp; va_start(argp, fmt); //temporary storage to hold the entire formatted //message. char tempMessage[MAX_MESSAGE_SIZE]; vsnprintf(tempMessage, sizeof(tempMessage), fmt, argp); va_end(argp); //copy the data retVal.message = tempMessage; return retVal; } }; /*___oOo___*/ <commit_msg>got rid of warning/error message due to conversion from enum to int<commit_after>/******************************************************************************* * ALMA - Atacama Large Millimiter Array * (c) UNSPECIFIED - FILL IN, 2005 * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * "@(#) $Id: loggingLogSvcHandler.cpp,v 1.30 2008/10/27 13:32:12 bjeram Exp $" * * who when what * -------- -------- ---------------------------------------------- * dfugate 2005-04-04 created */ #include "loggingLogSvcHandler.h" #include <loggingLoggingProxy.h> #include <loggingLogLevelDefinition.h> #ifdef MAKE_VXWORKS #include <acsutil.h> #endif #include <ace/Log_Record.h> static char *rcsId="@(#) $Id: loggingLogSvcHandler.cpp,v 1.30 2008/10/27 13:32:12 bjeram Exp $"; static void *use_rcsId = ((void)&use_rcsId,(void *) &rcsId); namespace Logging { // ---------------------------------------------------------- //helper function used to convert from ACS logging priorities //to ACE log priorities ACE_Log_Priority acs2acePriority(Logging::BaseLog::Priority acsPriority) { ACE_Log_Priority retVal = LM_SHUTDOWN; switch(acsPriority) { case Logging::BaseLog::LM_TRACE: retVal = LM_TRACE; break; case Logging::BaseLog::LM_DEBUG: retVal = LM_DEBUG; break; case Logging::BaseLog::LM_INFO: retVal = LM_INFO; break; case Logging::BaseLog::LM_NOTICE: retVal = LM_NOTICE; break; case Logging::BaseLog::LM_WARNING: retVal = LM_WARNING; break; case Logging::BaseLog::LM_ERROR: retVal = LM_ERROR; break; case Logging::BaseLog::LM_CRITICAL: retVal = LM_CRITICAL; break; case Logging::BaseLog::LM_ALERT: retVal = LM_ALERT; break; case Logging::BaseLog::LM_EMERGENCY: retVal = LM_EMERGENCY; break; case Logging::BaseLog::LM_SHUTDOWN: retVal = LM_SHUTDOWN; break; default: //should NEVER be the case but //if this does occur we default //to a level that will always be //logged retVal = LM_SHUTDOWN; } return retVal; } // ---------------------------------------------------------- //helper function used to convert from ACE logging priorities //to ACS log priorities Logging::BaseLog::Priority ace2acsPriority(ACE_Log_Priority acePriority) { Logging::BaseLog::Priority retVal = Logging::BaseLog::LM_SHUTDOWN; switch(acePriority) { case LM_TRACE: retVal = Logging::BaseLog::LM_TRACE; break; case LM_DEBUG: retVal = Logging::BaseLog::LM_DEBUG; break; case LM_INFO: retVal = Logging::BaseLog::LM_INFO; break; case LM_NOTICE: retVal = Logging::BaseLog::LM_NOTICE; break; case LM_WARNING: retVal = Logging::BaseLog::LM_WARNING; break; case LM_ERROR: retVal = Logging::BaseLog::LM_ERROR; break; case LM_CRITICAL: retVal = Logging::BaseLog::LM_CRITICAL; break; case LM_ALERT: retVal = Logging::BaseLog::LM_ALERT; break; case LM_EMERGENCY: retVal = Logging::BaseLog::LM_EMERGENCY; break; case LM_SHUTDOWN: retVal = Logging::BaseLog::LM_SHUTDOWN; break; default: //should NEVER be the case but //if this does occur we default //to a level that will always be //logged retVal = Logging::BaseLog::LM_SHUTDOWN; } return retVal; } // ---------------------------------------------------------- LogSvcHandler::LogSvcHandler(const std::string& soName) : sourceObjectName_m(soName) { setRemoteLevelType(NOT_DEFINED_LOG_LEVEL); setLocalLevelType(NOT_DEFINED_LOG_LEVEL); char *acsSTDIO = getenv("ACS_LOG_STDOUT"); int envStdioPriority = -1; if (acsSTDIO && *acsSTDIO) { envStdioPriority = atoi(acsSTDIO); } char *acsCentralizeLogger = getenv("ACS_LOG_CENTRAL"); int envCentralizePriority = -1; if (acsCentralizeLogger && *acsCentralizeLogger) { envCentralizePriority = atoi(acsCentralizeLogger); } setLevels(LM_TRACE, LM_TRACE,DEFAULT_LOG_LEVEL); if(envStdioPriority >= 0) setLevels((Priority)-1, static_cast<Logging::BaseLog::Priority>(LogLevelDefinition::getACELogPriority(envStdioPriority)), ENV_LOG_LEVEL); if(envCentralizePriority >= 0) setLevels(static_cast<Logging::BaseLog::Priority>(LogLevelDefinition::getACELogPriority(envCentralizePriority)), (Priority)-1, ENV_LOG_LEVEL); } // ---------------------------------------------------------- void LogSvcHandler::log(const LogRecord& lr) { //may need to make some changes to the message if the CORBA //logging service is down std::string message = lr.message; //if it's a trace we set the message to be "". if((lr.priority==LM_TRACE) && (message==FIELD_UNAVAILABLE)) { message = ""; } //add a newline if the logging service is unavailable if(LoggingProxy::isInit()==false) { message = message + '\n'; } LoggingProxy::File(lr.file.c_str()); LoggingProxy::Line(lr.line); //only set the logging flags if the priority is debug or trace if((lr.priority==LM_DEBUG)||(lr.priority==LM_TRACE)) { LoggingProxy::Flags(LM_SOURCE_INFO | LM_RUNTIME_CONTEXT); } //if the field is available if(lr.method!=FIELD_UNAVAILABLE) { //set the routine name. LoggingProxy::Routine(lr.method.c_str()); } else { LoggingProxy::Routine(""); } if(lr.priority == LM_SHUTDOWN) message = " -- ERROR in the priority of this message, please check the source --" + message; //set the component/container/etc name LoggingProxy::SourceObject(sourceObjectName_m.c_str()); //figure out the time long sec_ = ACE_static_cast(CORBA::ULongLong, lr.timeStamp) / ACE_static_cast(ACE_UINT32, 10000000u) - ACE_UINT64_LITERAL(0x2D8539C80); long usec_ = (lr.timeStamp % 10000000u) / 10; ACE_Time_Value time(sec_, usec_); //create the ACE log message /** * @todo Here there was an assignment to * a local variable never used. * Why was that? * I have now commented it out * int __ace_error = ACE_Log_Msg::last_error_adapter(); */ ACE_Log_Msg::last_error_adapter(); ACE_Log_Msg *ace___ = ACE_Log_Msg::instance(); //create the ACE log record using the message ACE_Log_Record log_record_(acs2acePriority(lr.priority), time, 0); log_record_.msg_data(message.c_str()); // set private flags const int prohibitLocal = getLocalLevel() == LM_SHUTDOWN || lr.priority < getLocalLevel() ? 1 : 0; const int prohibitRemote = getRemoteLevel() == LM_SHUTDOWN ||lr.priority < getRemoteLevel() ? 2 : 0; LoggingProxy::PrivateFlags(prohibitLocal | prohibitRemote); LoggingProxy::LogLevelLocalType(getLocalLevelType()); LoggingProxy::LogLevelRemoteType(getRemoteLevelType()); ace___->log(log_record_, 0); } // ---------------------------------------------------------- std::string LogSvcHandler::getName() const { return std::string("acsLogSvc"); } // ---------------------------------------------------------- void LogSvcHandler::setLevels(Priority remotePriority, Priority localPriority, int type) { if(remotePriority >0 && (type == CDB_REFRESH_LOG_LEVEL || getRemoteLevelType() >= type) ){ setRemoteLevelType(type); setRemoteLevel(remotePriority); } if(localPriority > 0 && ( type == CDB_REFRESH_LOG_LEVEL || getLocalLevelType() >= type )){ setLocalLevelType(type); setLocalLevel(localPriority); } // set global level (min of both) setLevel(static_cast<Logging::BaseLog::Priority>(getLocalLevel() < getRemoteLevel() ? getLocalLevel() : getRemoteLevel())); } // ---------------------------------------------------------- //--The following section exists solely to remain //--backwards compatible with the ACS 4.0 and earlier //--logging systems. This is provided so that formatted //--(i.e., printf, scanf, etc) messages are supported. //--At some point in time this should //--be removed! //----------------------------------------------------------- LogSvcHandler::DeprecatedLogInfo LogSvcHandler::unformatted2formatted(ACE_Log_Priority messagePriority, const char *fmt, ...) { //tells the compiler to check the format //every time it is called for format string and arguments matching in number //DWF-for some reason this does not compile //__attribute__ ((format (printf, 2, 3))); LogSvcHandler::DeprecatedLogInfo retVal; retVal.priority = ace2acsPriority(messagePriority); //take the format string along with the parameters //and convert them into the formatted string. va_list argp; va_start(argp, fmt); //temporary storage to hold the entire formatted //message. char tempMessage[MAX_MESSAGE_SIZE]; vsnprintf(tempMessage, sizeof(tempMessage), fmt, argp); va_end(argp); //copy the data retVal.message = tempMessage; return retVal; } }; /*___oOo___*/ <|endoftext|>
<commit_before>/*========================================================================= Program: Bender Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Bender includes #include "CreateTetrahedralMeshCLP.h" #include "benderIOUtils.h" // ITK includes #include "itkBinaryThresholdImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageFileWriter.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkRelabelComponentImageFilter.h" #include "itkConstantPadImageFilter.h" // Slicer includes #include "itkPluginUtilities.h" // VTK includes #include <vtkCleanPolyData.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkTetra.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkSmartPointer.h> // Cleaver includes #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/PaddedVolume.h> #include <Cleaver/ScalarField.h> #include <Cleaver/Volume.h> #include <LabelMapField.h> // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { template <class T> int DoIt( int argc, char * argv[] ); std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps( int argc, char * argv[]); } // end of anonymous namespace int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { itk::GetImageType(InputVolume, pixelType, componentType); switch( componentType ) { case itk::ImageIOBase::UCHAR: return DoIt<unsigned char>( argc, argv ); break; case itk::ImageIOBase::CHAR: return DoIt<char>( argc, argv ); break; case itk::ImageIOBase::USHORT: return DoIt<unsigned short>( argc, argv ); break; case itk::ImageIOBase::SHORT: return DoIt<short>( argc, argv ); break; case itk::ImageIOBase::UINT: return DoIt<unsigned int>( argc, argv ); break; case itk::ImageIOBase::INT: return DoIt<int>( argc, argv ); break; case itk::ImageIOBase::ULONG: return DoIt<unsigned long>( argc, argv ); break; case itk::ImageIOBase::LONG: return DoIt<long>( argc, argv ); break; case itk::ImageIOBase::FLOAT: return DoIt<float>( argc, argv ); break; case itk::ImageIOBase::DOUBLE: return DoIt<double>( argc, argv ); break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cerr << "Unknown component type: " << componentType << std::endl; break; } } catch( itk::ExceptionObject & excep ) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { std::vector<Cleaver::LabelMapField::ImageType::Pointer > SplitLabelMaps(Cleaver::LabelMapField::ImageType *image, bool verbose) { typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; typedef itk::ImageFileWriter<LabelImageType> ImageWriterType; // Assign continuous labels to the connected components, background is // considered to be 0 and will be ignored in the relabeling process. RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New(); relabelFilter->SetInput( image ); relabelFilter->Update(); if (verbose) { std::cout << "Total Number of Labels: " << relabelFilter->GetNumberOfObjects() << std::endl; } // Extract the labels typedef RelabelFilterType::LabelType LabelType; ThresholdFilterType::Pointer skinThresholdFilter = ThresholdFilterType::New(); // Create a list of images corresponding to labels std::vector<LabelImageType::Pointer> labels; // The skin label will become background for internal (smaller) organs skinThresholdFilter->SetInput(relabelFilter->GetOutput()); skinThresholdFilter->SetLowerThreshold(1); skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1); skinThresholdFilter->SetInsideValue(-1); skinThresholdFilter->SetOutsideValue(0); skinThresholdFilter->Update(); labels.push_back(skinThresholdFilter->GetOutput()); for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end; ++i) { ThresholdFilterType::Pointer organThresholdFilter = ThresholdFilterType::New(); organThresholdFilter->SetInput(relabelFilter->GetOutput()); organThresholdFilter->SetLowerThreshold(i); organThresholdFilter->SetUpperThreshold(i); organThresholdFilter->SetInsideValue(i); organThresholdFilter->SetOutsideValue(-1); organThresholdFilter->Update(); labels.push_back(organThresholdFilter->GetOutput()); } return labels; } template <class T> int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef T InputPixelType; typedef itk::Image<InputPixelType,3> InputImageType; typedef itk::CastImageFilter<InputImageType, LabelImageType> CastFilterType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ConstantPadImageFilter<InputImageType, InputImageType> ConstantPadType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( InputVolume ); reader->Update(); typename CastFilterType::Pointer castingFilter = CastFilterType::New(); castingFilter->SetInput(reader->GetOutput()); std::vector<Cleaver::ScalarField*> labelMaps; std::vector<LabelImageType::Pointer> labels = SplitLabelMaps(castingFilter->GetOutput(), Verbose); // Get a map from the original labels to the new labels std::map<InputPixelType, InputPixelType> originalLabels; for(size_t i = 0; i < labels.size(); ++i) { itk::ImageRegionConstIterator<InputImageType> imageIterator( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<LabelImageType> labelsIterator( labels[i], labels[i]->GetLargestPossibleRegion()); bool foundCorrespondence = false; while(!imageIterator.IsAtEnd() && !labelsIterator.IsAtEnd() && !foundCorrespondence) { if (labelsIterator.Value() > 0) { originalLabels[labelsIterator.Value()] = imageIterator.Value(); } ++imageIterator; ++labelsIterator; } } if (Verbose) { std::cout << "Total labels found: " << labels.size() << std::endl; } for(size_t i = 0; i < labels.size(); ++i) { labelMaps.push_back(new Cleaver::LabelMapField(labels[i])); static_cast<Cleaver::LabelMapField*>(labelMaps.back())-> SetGenerateDataFromLabels(true); } if(labelMaps.empty()) { std::cerr << "Failed to load image data. Terminating." << std::endl; return 0; } if(labelMaps.size() < 2) { labelMaps.push_back(new Cleaver::InverseField(labelMaps[0])); } Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps); if (Padding) { volume = new Cleaver::PaddedVolume(volume); } if (Verbose) { std::cout << "Creating Mesh with Volume Size " << volume->size().toString() << std::endl; } //-------------------------------- // Create Mesher & TetMesh //-------------------------------- Cleaver::TetMesh *cleaverMesh = Cleaver::createMeshFromVolume(volume, Verbose); if (!cleaverMesh) { // Clean up delete volume; delete cleaverMesh; std::cerr << "Mesh computation failed !" << std::endl; return EXIT_FAILURE; } //------------------ // Compute Angles //------------------ if(Verbose) { cleaverMesh->computeAngles(); std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << cleaverMesh->min_angle << std::endl; std::cout << "max: " << cleaverMesh->max_angle << std::endl; } const int airLabel = 0; int paddedVolumeLabel = labels.size(); vtkNew<vtkCellArray> meshTetras; vtkNew<vtkIntArray> cellData; cellData->SetName("Labels"); for(size_t i = 0, end = cleaverMesh->tets.size(); i < end; ++i) { int label = cleaverMesh->tets[i]->mat_label; if(label == airLabel || label == paddedVolumeLabel) { continue; } vtkNew<vtkTetra> meshTetra; meshTetra->GetPointIds()->SetId(0, cleaverMesh->tets[i]->verts[0]->tm_v_index); meshTetra->GetPointIds()->SetId(1, cleaverMesh->tets[i]->verts[1]->tm_v_index); meshTetra->GetPointIds()->SetId(2, cleaverMesh->tets[i]->verts[2]->tm_v_index); meshTetra->GetPointIds()->SetId(3, cleaverMesh->tets[i]->verts[3]->tm_v_index); meshTetras->InsertNextCell(meshTetra.GetPointer()); cellData->InsertNextValue(originalLabels[label]); } vtkNew<vtkPoints> points; points->SetNumberOfPoints(cleaverMesh->verts.size()); for (size_t i = 0, end = cleaverMesh->verts.size(); i < end; ++i) { Cleaver::vec3 &pos = cleaverMesh->verts[i]->pos(); points->SetPoint(i, pos.x, pos.y, pos.z); } vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New(); vtkMesh->SetPoints(points.GetPointer()); vtkMesh->SetPolys(meshTetras.GetPointer()); vtkMesh->GetCellData()->SetScalars(cellData.GetPointer()); vtkNew<vtkCleanPolyData> cleanFilter; cleanFilter->PointMergingOff(); // Prevent from creating triangles or lines cleanFilter->SetInput(vtkMesh); // Since cleaver does not take into account the image properties such as // sapcing or origin, we need to transform the output points so the mesh can // match the original image. vtkNew<vtkTransform> transform; LabelImageType::SpacingType spacing = reader->GetOutput()->GetSpacing(); LabelImageType::PointType origin = reader->GetOutput()->GetOrigin(); LabelImageType::DirectionType imageDirection = reader->GetOutput()->GetDirection(); // Transform points to RAS (what is concatenated first is done last !) vtkNew<vtkMatrix4x4> rasMatrix; rasMatrix->Identity(); rasMatrix->SetElement(0, 0, -1.0); rasMatrix->SetElement(1, 1, -1.0); transform->Concatenate(rasMatrix.GetPointer()); // Translation double voxelSize[3]; voxelSize[0] = spacing[0]; voxelSize[1] = spacing[1]; voxelSize[2] = spacing[2]; double voxelDiagonale = vtkMath::Norm(voxelSize) / 2; vtkNew<vtkMatrix4x4> directionMatrix; directionMatrix->Identity(); for (int i = 0; i < imageDirection.RowDimensions; ++i) { for (int j = 0; j < imageDirection.ColumnDimensions; ++j) { directionMatrix->SetElement(i, j, imageDirection[i][j]); } } vtkNew<vtkTransform> offsetTransform; offsetTransform->Concatenate(directionMatrix.GetPointer()); double offset = Padding ? (Cleaver::PaddedVolume::DefaultThickness + 1) * voxelDiagonale : 0.; double* offsets = offsetTransform->TransformDoubleVector(offset, offset, offset); transform->Translate( origin[0] - offsets[0], origin[1] - offsets[1], origin[2] - offsets[2]); // Scaling and rotation vtkNew<vtkMatrix4x4> scaleMatrix; scaleMatrix->DeepCopy(directionMatrix.GetPointer()); for (int i = 0; i < spacing.GetNumberOfComponents(); ++i) { scaleMatrix->SetElement(i, i, scaleMatrix->GetElement(i, i) * spacing[i]); } transform->Concatenate(scaleMatrix.GetPointer()); // Actual transformation vtkNew<vtkTransformPolyDataFilter> transformFilter; transformFilter->SetInput(cleanFilter->GetOutput()); transformFilter->SetTransform(transform.GetPointer()); bender::IOUtils::WritePolyData(transformFilter->GetOutput(), OutputMesh); // Clean up delete volume; delete cleaverMesh; return EXIT_SUCCESS; } } // end of anonymous namespace <commit_msg>Re-organize cleaver to vtk conversion<commit_after>/*========================================================================= Program: Bender Copyright (c) Kitware Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.txt Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =========================================================================*/ // Bender includes #include "CreateTetrahedralMeshCLP.h" #include "benderIOUtils.h" // ITK includes #include "itkBinaryThresholdImageFilter.h" #include "itkCastImageFilter.h" #include "itkImageFileWriter.h" #include "itkImageRegionConstIterator.h" #include "itkImageRegionIterator.h" #include "itkRelabelComponentImageFilter.h" #include "itkConstantPadImageFilter.h" // Slicer includes #include "itkPluginUtilities.h" // VTK includes #include <vtkCleanPolyData.h> #include <vtkCellArray.h> #include <vtkCellData.h> #include <vtkTetra.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> #include <vtkPolyData.h> #include <vtkPolyDataWriter.h> #include <vtkMath.h> #include <vtkNew.h> #include <vtkSmartPointer.h> // Cleaver includes #include <Cleaver/Cleaver.h> #include <Cleaver/InverseField.h> #include <Cleaver/PaddedVolume.h> #include <Cleaver/ScalarField.h> #include <Cleaver/Volume.h> #include <LabelMapField.h> // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { template <class T> int DoIt( int argc, char * argv[] ); std::vector<Cleaver::LabelMapField::ImageType::Pointer> SplitLabelMaps( int argc, char * argv[]); } // end of anonymous namespace int main( int argc, char * argv[] ) { PARSE_ARGS; itk::ImageIOBase::IOPixelType pixelType; itk::ImageIOBase::IOComponentType componentType; try { itk::GetImageType(InputVolume, pixelType, componentType); switch( componentType ) { case itk::ImageIOBase::UCHAR: return DoIt<unsigned char>( argc, argv ); break; case itk::ImageIOBase::CHAR: return DoIt<char>( argc, argv ); break; case itk::ImageIOBase::USHORT: return DoIt<unsigned short>( argc, argv ); break; case itk::ImageIOBase::SHORT: return DoIt<short>( argc, argv ); break; case itk::ImageIOBase::UINT: return DoIt<unsigned int>( argc, argv ); break; case itk::ImageIOBase::INT: return DoIt<int>( argc, argv ); break; case itk::ImageIOBase::ULONG: return DoIt<unsigned long>( argc, argv ); break; case itk::ImageIOBase::LONG: return DoIt<long>( argc, argv ); break; case itk::ImageIOBase::FLOAT: return DoIt<float>( argc, argv ); break; case itk::ImageIOBase::DOUBLE: return DoIt<double>( argc, argv ); break; case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE: default: std::cerr << "Unknown component type: " << componentType << std::endl; break; } } catch( itk::ExceptionObject & excep ) { std::cerr << argv[0] << ": exception caught !" << std::endl; std::cerr << excep << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } // Use an anonymous namespace to keep class types and function names // from colliding when module is used as shared object module. Every // thing should be in an anonymous namespace except for the module // entry point, e.g. main() // namespace { std::vector<Cleaver::LabelMapField::ImageType::Pointer > SplitLabelMaps(Cleaver::LabelMapField::ImageType *image, bool verbose) { typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef itk::RelabelComponentImageFilter<LabelImageType, LabelImageType> RelabelFilterType; typedef itk::BinaryThresholdImageFilter<LabelImageType, LabelImageType> ThresholdFilterType; typedef itk::ImageFileWriter<LabelImageType> ImageWriterType; // Assign continuous labels to the connected components, background is // considered to be 0 and will be ignored in the relabeling process. RelabelFilterType::Pointer relabelFilter = RelabelFilterType::New(); relabelFilter->SetInput( image ); relabelFilter->Update(); if (verbose) { std::cout << "Total Number of Labels: " << relabelFilter->GetNumberOfObjects() << std::endl; } // Extract the labels typedef RelabelFilterType::LabelType LabelType; ThresholdFilterType::Pointer skinThresholdFilter = ThresholdFilterType::New(); // Create a list of images corresponding to labels std::vector<LabelImageType::Pointer> labels; // The skin label will become background for internal (smaller) organs skinThresholdFilter->SetInput(relabelFilter->GetOutput()); skinThresholdFilter->SetLowerThreshold(1); skinThresholdFilter->SetUpperThreshold(relabelFilter->GetNumberOfObjects()+1); skinThresholdFilter->SetInsideValue(-1); skinThresholdFilter->SetOutsideValue(0); skinThresholdFilter->Update(); labels.push_back(skinThresholdFilter->GetOutput()); for (LabelType i = 1, end = relabelFilter->GetNumberOfObjects()+1; i < end; ++i) { ThresholdFilterType::Pointer organThresholdFilter = ThresholdFilterType::New(); organThresholdFilter->SetInput(relabelFilter->GetOutput()); organThresholdFilter->SetLowerThreshold(i); organThresholdFilter->SetUpperThreshold(i); organThresholdFilter->SetInsideValue(i); organThresholdFilter->SetOutsideValue(-1); organThresholdFilter->Update(); labels.push_back(organThresholdFilter->GetOutput()); } return labels; } template <class T> int DoIt( int argc, char * argv[] ) { PARSE_ARGS; typedef Cleaver::LabelMapField::ImageType LabelImageType; typedef T InputPixelType; typedef itk::Image<InputPixelType,3> InputImageType; typedef itk::CastImageFilter<InputImageType, LabelImageType> CastFilterType; typedef itk::ImageFileReader<InputImageType> ReaderType; typedef itk::ConstantPadImageFilter<InputImageType, InputImageType> ConstantPadType; typename ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( InputVolume ); reader->Update(); typename CastFilterType::Pointer castingFilter = CastFilterType::New(); castingFilter->SetInput(reader->GetOutput()); std::vector<Cleaver::ScalarField*> labelMaps; std::vector<LabelImageType::Pointer> labels = SplitLabelMaps(castingFilter->GetOutput(), Verbose); // Get a map from the original labels to the new labels std::map<InputPixelType, InputPixelType> originalLabels; for(size_t i = 0; i < labels.size(); ++i) { itk::ImageRegionConstIterator<InputImageType> imageIterator( reader->GetOutput(), reader->GetOutput()->GetLargestPossibleRegion()); itk::ImageRegionConstIterator<LabelImageType> labelsIterator( labels[i], labels[i]->GetLargestPossibleRegion()); bool foundCorrespondence = false; while(!imageIterator.IsAtEnd() && !labelsIterator.IsAtEnd() && !foundCorrespondence) { if (labelsIterator.Value() > 0) { originalLabels[labelsIterator.Value()] = imageIterator.Value(); } ++imageIterator; ++labelsIterator; } } if (Verbose) { std::cout << "Total labels found: " << labels.size() << std::endl; } for(size_t i = 0; i < labels.size(); ++i) { labelMaps.push_back(new Cleaver::LabelMapField(labels[i])); static_cast<Cleaver::LabelMapField*>(labelMaps.back())-> SetGenerateDataFromLabels(true); } if(labelMaps.empty()) { std::cerr << "Failed to load image data. Terminating." << std::endl; return 0; } if(labelMaps.size() < 2) { labelMaps.push_back(new Cleaver::InverseField(labelMaps[0])); } Cleaver::AbstractVolume *volume = new Cleaver::Volume(labelMaps); if (Padding) { volume = new Cleaver::PaddedVolume(volume); } if (Verbose) { std::cout << "Creating Mesh with Volume Size " << volume->size().toString() << std::endl; } //-------------------------------- // Create Mesher & TetMesh //-------------------------------- Cleaver::TetMesh *cleaverMesh = Cleaver::createMeshFromVolume(volume, Verbose); if (!cleaverMesh) { // Clean up delete volume; delete cleaverMesh; std::cerr << "Mesh computation failed !" << std::endl; return EXIT_FAILURE; } //------------------ // Compute Angles //------------------ if(Verbose) { cleaverMesh->computeAngles(); std::cout.precision(12); std::cout << "Worst Angles:" << std::endl; std::cout << "min: " << cleaverMesh->min_angle << std::endl; std::cout << "max: " << cleaverMesh->max_angle << std::endl; } //------------------ // Fill polydata //------------------ // Constants for undesired material const int airLabel = 0; int paddedVolumeLabel = labels.size(); // Points and cell arrays vtkNew<vtkCellArray> meshTetras; vtkNew<vtkPoints> points; points->SetNumberOfPoints(cleaverMesh->tets.size() * 4); vtkNew<vtkIntArray> cellData; cellData->SetName("Labels"); for(size_t i = 0; i < cleaverMesh->tets.size(); ++i) { int label = cleaverMesh->tets[i]->mat_label; if(label == airLabel || label == paddedVolumeLabel) { continue; } vtkNew<vtkTetra> meshTetra; for (int j = 0; j < 4; ++j) { Cleaver::vec3 &pos = cleaverMesh->tets[i]->verts[j]->pos(); int vertexIndex = cleaverMesh->tets[i]->verts[j]->tm_v_index; points->SetPoint(vertexIndex, pos.x, pos.y, pos.z); meshTetra->GetPointIds()->SetId(j, vertexIndex); } meshTetras->InsertNextCell(meshTetra.GetPointer()); cellData->InsertNextValue(originalLabels[label]); } vtkSmartPointer<vtkPolyData> vtkMesh = vtkSmartPointer<vtkPolyData>::New(); vtkMesh->SetPoints(points.GetPointer()); vtkMesh->SetPolys(meshTetras.GetPointer()); vtkMesh->GetCellData()->SetScalars(cellData.GetPointer()); vtkNew<vtkCleanPolyData> cleanFilter; cleanFilter->PointMergingOff(); // Prevent from creating triangles or lines cleanFilter->SetInput(vtkMesh); // Since cleaver does not take into account the image properties such as // sapcing or origin, we need to transform the output points so the mesh can // match the original image. vtkNew<vtkTransform> transform; LabelImageType::SpacingType spacing = reader->GetOutput()->GetSpacing(); LabelImageType::PointType origin = reader->GetOutput()->GetOrigin(); LabelImageType::DirectionType imageDirection = reader->GetOutput()->GetDirection(); // Transform points to RAS (what is concatenated first is done last !) vtkNew<vtkMatrix4x4> rasMatrix; rasMatrix->Identity(); rasMatrix->SetElement(0, 0, -1.0); rasMatrix->SetElement(1, 1, -1.0); transform->Concatenate(rasMatrix.GetPointer()); // Translation double voxelSize[3]; voxelSize[0] = spacing[0]; voxelSize[1] = spacing[1]; voxelSize[2] = spacing[2]; double voxelDiagonale = vtkMath::Norm(voxelSize) / 2; vtkNew<vtkMatrix4x4> directionMatrix; directionMatrix->Identity(); for (int i = 0; i < imageDirection.RowDimensions; ++i) { for (int j = 0; j < imageDirection.ColumnDimensions; ++j) { directionMatrix->SetElement(i, j, imageDirection[i][j]); } } vtkNew<vtkTransform> offsetTransform; offsetTransform->Concatenate(directionMatrix.GetPointer()); double offset = Padding ? (Cleaver::PaddedVolume::DefaultThickness + 1) * voxelDiagonale : 0.; double* offsets = offsetTransform->TransformDoubleVector(offset, offset, offset); transform->Translate( origin[0] - offsets[0], origin[1] - offsets[1], origin[2] - offsets[2]); // Scaling and rotation vtkNew<vtkMatrix4x4> scaleMatrix; scaleMatrix->DeepCopy(directionMatrix.GetPointer()); for (int i = 0; i < spacing.GetNumberOfComponents(); ++i) { scaleMatrix->SetElement(i, i, scaleMatrix->GetElement(i, i) * spacing[i]); } transform->Concatenate(scaleMatrix.GetPointer()); // Actual transformation vtkNew<vtkTransformPolyDataFilter> transformFilter; transformFilter->SetInput(cleanFilter->GetOutput()); transformFilter->SetTransform(transform.GetPointer()); bender::IOUtils::WritePolyData(transformFilter->GetOutput(), OutputMesh); // Clean up delete volume; delete cleaverMesh; return EXIT_SUCCESS; } } // end of anonymous namespace <|endoftext|>
<commit_before>// sky.cxx -- ssg based sky model // // Written by Curtis Olson, started December 1997. // SSG-ified by Curtis Olson, February 2000. // // Copyright (C) 1997-2000 Curtis L. Olson - http://www.flightgear.org/~curt // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // $Id$ #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "sky.hxx" #include "cloudfield.hxx" #include "newcloud.hxx" #include <simgear/math/sg_random.h> #include <simgear/scene/util/RenderConstants.hxx> #include <osg/StateSet> #include <osg/Depth> // Constructor SGSky::SGSky( void ) { effective_visibility = visibility = 10000.0; // near cloud visibility state variables in_puff = false; puff_length = 0; puff_progression = 0; ramp_up = 0.15; ramp_down = 0.15; in_cloud = -1; clouds_3d_enabled = false; clouds_3d_density = 0.8; pre_root = new osg::Group; pre_root->setNodeMask(simgear::BACKGROUND_BIT); osg::StateSet* preStateSet = new osg::StateSet; preStateSet->setAttribute(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false)); pre_root->setStateSet(preStateSet); cloud_root = new osg::Group; cloud_root->setNodeMask(simgear::MODEL_BIT); pre_selector = new osg::Switch; pre_transform = new osg::Group; _ephTransform = new osg::MatrixTransform; } // Destructor SGSky::~SGSky( void ) { } // initialize the sky and connect the components to the scene graph at // the provided branch void SGSky::build( double h_radius_m, double v_radius_m, double sun_size, double moon_size, const SGEphemeris& eph, SGPropertyNode *property_tree_node ) { dome = new SGSkyDome; pre_transform->addChild( dome->build( h_radius_m, v_radius_m ) ); pre_transform->addChild(_ephTransform.get()); planets = new SGStars; _ephTransform->addChild( planets->build(eph.getNumPlanets(), eph.getPlanets(), h_radius_m) ); stars = new SGStars; _ephTransform->addChild( stars->build(eph.getNumStars(), eph.getStars(), h_radius_m) ); moon = new SGMoon; _ephTransform->addChild( moon->build(tex_path, moon_size) ); oursun = new SGSun; _ephTransform->addChild( oursun->build(tex_path, sun_size, property_tree_node ) ); pre_selector->addChild( pre_transform.get() ); pre_root->addChild( pre_selector.get() ); } // repaint the sky components based on current value of sun_angle, // sky, and fog colors. // // sun angle in degrees relative to verticle // 0 degrees = high noon // 90 degrees = sun rise/set // 180 degrees = darkest midnight bool SGSky::repaint( const SGSkyColor &sc, const SGEphemeris& eph ) { if ( effective_visibility > 1000.0 ) { enable(); dome->repaint( sc.adj_sky_color, sc.sky_color, sc.fog_color, sc.sun_angle, effective_visibility ); stars->repaint( sc.sun_angle, eph.getNumStars(), eph.getStars() ); planets->repaint( sc.sun_angle, eph.getNumPlanets(), eph.getPlanets() ); oursun->repaint( sc.sun_angle, effective_visibility ); moon->repaint( sc.moon_angle ); for ( unsigned i = 0; i < cloud_layers.size(); ++i ) { if (cloud_layers[i]->getCoverage() != SGCloudLayer::SG_CLOUD_CLEAR){ cloud_layers[i]->repaint( sc.cloud_color ); } } } else { // turn off sky disable(); } SGCloudField::updateFog((double)effective_visibility, osg::Vec4f(toOsg(sc.fog_color), 1.0f)); return true; } // reposition the sky at the specified origin and orientation // // lon specifies a rotation about the Z axis // lat specifies a rotation about the new Y axis // spin specifies a rotation about the new Z axis (this allows // additional orientation for the sunrise/set effects and is used by // the skydome and perhaps clouds. bool SGSky::reposition( const SGSkyState &st, const SGEphemeris& eph, double dt ) { double angle = st.gst * 15; // degrees double angleRad = SGMiscd::deg2rad(angle); SGVec3f zero_elev, view_up; double lon, lat, alt; SGGeod geodZeroViewPos = SGGeod::fromGeodM(st.pos_geod, 0); zero_elev = toVec3f( SGVec3d::fromGeod(geodZeroViewPos) ); view_up = toVec3f( st.ori.backTransform(SGVec3d::e2()) ); lon = st.pos_geod.getLongitudeRad(); lat = st.pos_geod.getLatitudeRad(); alt = st.pos_geod.getElevationM(); dome->reposition( zero_elev, alt, lon, lat, st.spin ); osg::Matrix m = osg::Matrix::rotate(angleRad, osg::Vec3(0, 0, -1)); m.postMultTranslate(toOsg(st.pos)); _ephTransform->setMatrix(m); double sun_ra = eph.getSunRightAscension(); double sun_dec = eph.getSunDeclination(); oursun->reposition( sun_ra, sun_dec, st.sun_dist, lat, alt, st.sun_angle ); double moon_ra = eph.getMoonRightAscension(); double moon_dec = eph.getMoonDeclination(); moon->reposition( moon_ra, moon_dec, st.moon_dist ); for ( unsigned i = 0; i < cloud_layers.size(); ++i ) { if ( cloud_layers[i]->getCoverage() != SGCloudLayer::SG_CLOUD_CLEAR ) { cloud_layers[i]->reposition( zero_elev, view_up, lon, lat, alt, dt); } else cloud_layers[i]->getNode()->setAllChildrenOff(); } return true; } void SGSky::add_cloud_layer( SGCloudLayer * layer ) { cloud_layers.push_back(layer); cloud_root->addChild(layer->getNode()); layer->set_enable3dClouds(clouds_3d_enabled); } const SGCloudLayer * SGSky::get_cloud_layer (int i) const { return cloud_layers[i]; } SGCloudLayer * SGSky::get_cloud_layer (int i) { return cloud_layers[i]; } int SGSky::get_cloud_layer_count () const { return cloud_layers.size(); } double SGSky::get_3dCloudDensity() const { return SGNewCloud::getDensity(); } void SGSky::set_3dCloudDensity(double density) { SGNewCloud::setDensity(density); } float SGSky::get_3dCloudVisRange() const { return SGCloudField::getVisRange(); } void SGSky::set_3dCloudVisRange(float vis) { SGCloudField::setVisRange(vis); for ( int i = 0; i < (int)cloud_layers.size(); ++i ) { cloud_layers[i]->get_layer3D()->applyVisRange(); } } void SGSky::texture_path( const string& path ) { tex_path = SGPath( path ); } // modify the current visibility based on cloud layers, thickness, // transition range, and simulated "puffs". void SGSky::modify_vis( float alt, float time_factor ) { float effvis = visibility; for ( int i = 0; i < (int)cloud_layers.size(); ++i ) { float asl = cloud_layers[i]->getElevation_m(); float thickness = cloud_layers[i]->getThickness_m(); float transition = cloud_layers[i]->getTransition_m(); double ratio = 1.0; if ( cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_CLEAR ) { // less than 50% coverage -- assume we're in the clear for now ratio = 1.0; } else if ( alt < asl - transition ) { // below cloud layer ratio = 1.0; } else if ( alt < asl ) { // in lower transition ratio = (asl - alt) / transition; } else if ( alt < asl + thickness ) { // in cloud layer ratio = 0.0; } else if ( alt < asl + thickness + transition ) { // in upper transition ratio = (alt - (asl + thickness)) / transition; } else { // above cloud layer ratio = 1.0; } if ( cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_CLEAR || cloud_layers[i]->get_layer3D()->defined3D) { // do nothing, clear layers aren't drawn, don't affect // visibility andn dont' need to be faded in or out. } else if ( (cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_FEW) || (cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_SCATTERED) ) { // set the alpha fade value for the cloud layer. For less // dense cloud layers we fade the layer to nothing as we // approach it because we stay clear visibility-wise as we // pass through it. float temp = ratio * 2.0; if ( temp > 1.0 ) { temp = 1.0; } cloud_layers[i]->setAlpha( temp ); // don't touch visibility } else { // maintain full alpha for denser cloud layer types. // Let's set the value explicitly in case someone changed // the layer type. cloud_layers[i]->setAlpha( 1.0 ); // lower visibility as we approach the cloud layer. // accumulate effects from multiple cloud layers effvis *= ratio; } #if 0 if ( ratio < 1.0 ) { if ( ! in_puff ) { // calc chance of entering cloud puff double rnd = sg_random(); double chance = rnd * rnd * rnd; if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) { in_puff = true; puff_length = sg_random() * 2.0; // up to 2 seconds puff_progression = 0.0; } } if ( in_puff ) { // modify actual_visibility based on puff envelope if ( puff_progression <= ramp_up ) { double x = SGD_PI_2 * puff_progression / ramp_up; double factor = 1.0 - sin( x ); // cout << "ramp up = " << puff_progression // << " factor = " << factor << endl; effvis = effvis * factor; } else if ( puff_progression >= ramp_up + puff_length ) { double x = SGD_PI_2 * (puff_progression - (ramp_up + puff_length)) / ramp_down; double factor = sin( x ); // cout << "ramp down = " // << puff_progression - (ramp_up + puff_length) // << " factor = " << factor << endl; effvis = effvis * factor; } else { effvis = 0.0; } /* cout << "len = " << puff_length << " x = " << x << " factor = " << factor << " actual_visibility = " << actual_visibility << endl; */ // time_factor = ( global_multi_loop * // current_options.get_speed_up() ) / // (double)current_options.get_model_hz(); puff_progression += time_factor; // cout << "time factor = " << time_factor << endl; /* cout << "gml = " << global_multi_loop << " speed up = " << current_options.get_speed_up() << " hz = " << current_options.get_model_hz() << endl; */ if ( puff_progression > puff_length + ramp_up + ramp_down) { in_puff = false; } } } #endif // never let visibility drop below 25 meters if ( effvis <= 25.0 ) { effvis = 25.0; } } // for effective_visibility = effvis; } <commit_msg>Oops, it was the scenery up vector, not the viewer up vector<commit_after>// sky.cxx -- ssg based sky model // // Written by Curtis Olson, started December 1997. // SSG-ified by Curtis Olson, February 2000. // // Copyright (C) 1997-2000 Curtis L. Olson - http://www.flightgear.org/~curt // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. // // $Id$ #ifdef HAVE_CONFIG_H # include <simgear_config.h> #endif #include "sky.hxx" #include "cloudfield.hxx" #include "newcloud.hxx" #include <simgear/math/sg_random.h> #include <simgear/scene/util/RenderConstants.hxx> #include <osg/StateSet> #include <osg/Depth> // Constructor SGSky::SGSky( void ) { effective_visibility = visibility = 10000.0; // near cloud visibility state variables in_puff = false; puff_length = 0; puff_progression = 0; ramp_up = 0.15; ramp_down = 0.15; in_cloud = -1; clouds_3d_enabled = false; clouds_3d_density = 0.8; pre_root = new osg::Group; pre_root->setNodeMask(simgear::BACKGROUND_BIT); osg::StateSet* preStateSet = new osg::StateSet; preStateSet->setAttribute(new osg::Depth(osg::Depth::LESS, 0.0, 1.0, false)); pre_root->setStateSet(preStateSet); cloud_root = new osg::Group; cloud_root->setNodeMask(simgear::MODEL_BIT); pre_selector = new osg::Switch; pre_transform = new osg::Group; _ephTransform = new osg::MatrixTransform; } // Destructor SGSky::~SGSky( void ) { } // initialize the sky and connect the components to the scene graph at // the provided branch void SGSky::build( double h_radius_m, double v_radius_m, double sun_size, double moon_size, const SGEphemeris& eph, SGPropertyNode *property_tree_node ) { dome = new SGSkyDome; pre_transform->addChild( dome->build( h_radius_m, v_radius_m ) ); pre_transform->addChild(_ephTransform.get()); planets = new SGStars; _ephTransform->addChild( planets->build(eph.getNumPlanets(), eph.getPlanets(), h_radius_m) ); stars = new SGStars; _ephTransform->addChild( stars->build(eph.getNumStars(), eph.getStars(), h_radius_m) ); moon = new SGMoon; _ephTransform->addChild( moon->build(tex_path, moon_size) ); oursun = new SGSun; _ephTransform->addChild( oursun->build(tex_path, sun_size, property_tree_node ) ); pre_selector->addChild( pre_transform.get() ); pre_root->addChild( pre_selector.get() ); } // repaint the sky components based on current value of sun_angle, // sky, and fog colors. // // sun angle in degrees relative to verticle // 0 degrees = high noon // 90 degrees = sun rise/set // 180 degrees = darkest midnight bool SGSky::repaint( const SGSkyColor &sc, const SGEphemeris& eph ) { if ( effective_visibility > 1000.0 ) { enable(); dome->repaint( sc.adj_sky_color, sc.sky_color, sc.fog_color, sc.sun_angle, effective_visibility ); stars->repaint( sc.sun_angle, eph.getNumStars(), eph.getStars() ); planets->repaint( sc.sun_angle, eph.getNumPlanets(), eph.getPlanets() ); oursun->repaint( sc.sun_angle, effective_visibility ); moon->repaint( sc.moon_angle ); for ( unsigned i = 0; i < cloud_layers.size(); ++i ) { if (cloud_layers[i]->getCoverage() != SGCloudLayer::SG_CLOUD_CLEAR){ cloud_layers[i]->repaint( sc.cloud_color ); } } } else { // turn off sky disable(); } SGCloudField::updateFog((double)effective_visibility, osg::Vec4f(toOsg(sc.fog_color), 1.0f)); return true; } // reposition the sky at the specified origin and orientation // // lon specifies a rotation about the Z axis // lat specifies a rotation about the new Y axis // spin specifies a rotation about the new Z axis (this allows // additional orientation for the sunrise/set effects and is used by // the skydome and perhaps clouds. bool SGSky::reposition( const SGSkyState &st, const SGEphemeris& eph, double dt ) { double angle = st.gst * 15; // degrees double angleRad = SGMiscd::deg2rad(angle); SGVec3f zero_elev, view_up; double lon, lat, alt; SGGeod geodZeroViewPos = SGGeod::fromGeodM(st.pos_geod, 0); zero_elev = toVec3f( SGVec3d::fromGeod(geodZeroViewPos) ); // calculate the scenery up vector SGQuatd hlOr = SGQuatd::fromLonLat(st.pos_geod); view_up = toVec3f(hlOr.backTransform(-SGVec3d::e3())); // viewer location lon = st.pos_geod.getLongitudeRad(); lat = st.pos_geod.getLatitudeRad(); alt = st.pos_geod.getElevationM(); dome->reposition( zero_elev, alt, lon, lat, st.spin ); osg::Matrix m = osg::Matrix::rotate(angleRad, osg::Vec3(0, 0, -1)); m.postMultTranslate(toOsg(st.pos)); _ephTransform->setMatrix(m); double sun_ra = eph.getSunRightAscension(); double sun_dec = eph.getSunDeclination(); oursun->reposition( sun_ra, sun_dec, st.sun_dist, lat, alt, st.sun_angle ); double moon_ra = eph.getMoonRightAscension(); double moon_dec = eph.getMoonDeclination(); moon->reposition( moon_ra, moon_dec, st.moon_dist ); for ( unsigned i = 0; i < cloud_layers.size(); ++i ) { if ( cloud_layers[i]->getCoverage() != SGCloudLayer::SG_CLOUD_CLEAR ) { cloud_layers[i]->reposition( zero_elev, view_up, lon, lat, alt, dt); } else cloud_layers[i]->getNode()->setAllChildrenOff(); } return true; } void SGSky::add_cloud_layer( SGCloudLayer * layer ) { cloud_layers.push_back(layer); cloud_root->addChild(layer->getNode()); layer->set_enable3dClouds(clouds_3d_enabled); } const SGCloudLayer * SGSky::get_cloud_layer (int i) const { return cloud_layers[i]; } SGCloudLayer * SGSky::get_cloud_layer (int i) { return cloud_layers[i]; } int SGSky::get_cloud_layer_count () const { return cloud_layers.size(); } double SGSky::get_3dCloudDensity() const { return SGNewCloud::getDensity(); } void SGSky::set_3dCloudDensity(double density) { SGNewCloud::setDensity(density); } float SGSky::get_3dCloudVisRange() const { return SGCloudField::getVisRange(); } void SGSky::set_3dCloudVisRange(float vis) { SGCloudField::setVisRange(vis); for ( int i = 0; i < (int)cloud_layers.size(); ++i ) { cloud_layers[i]->get_layer3D()->applyVisRange(); } } void SGSky::texture_path( const string& path ) { tex_path = SGPath( path ); } // modify the current visibility based on cloud layers, thickness, // transition range, and simulated "puffs". void SGSky::modify_vis( float alt, float time_factor ) { float effvis = visibility; for ( int i = 0; i < (int)cloud_layers.size(); ++i ) { float asl = cloud_layers[i]->getElevation_m(); float thickness = cloud_layers[i]->getThickness_m(); float transition = cloud_layers[i]->getTransition_m(); double ratio = 1.0; if ( cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_CLEAR ) { // less than 50% coverage -- assume we're in the clear for now ratio = 1.0; } else if ( alt < asl - transition ) { // below cloud layer ratio = 1.0; } else if ( alt < asl ) { // in lower transition ratio = (asl - alt) / transition; } else if ( alt < asl + thickness ) { // in cloud layer ratio = 0.0; } else if ( alt < asl + thickness + transition ) { // in upper transition ratio = (alt - (asl + thickness)) / transition; } else { // above cloud layer ratio = 1.0; } if ( cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_CLEAR || cloud_layers[i]->get_layer3D()->defined3D) { // do nothing, clear layers aren't drawn, don't affect // visibility andn dont' need to be faded in or out. } else if ( (cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_FEW) || (cloud_layers[i]->getCoverage() == SGCloudLayer::SG_CLOUD_SCATTERED) ) { // set the alpha fade value for the cloud layer. For less // dense cloud layers we fade the layer to nothing as we // approach it because we stay clear visibility-wise as we // pass through it. float temp = ratio * 2.0; if ( temp > 1.0 ) { temp = 1.0; } cloud_layers[i]->setAlpha( temp ); // don't touch visibility } else { // maintain full alpha for denser cloud layer types. // Let's set the value explicitly in case someone changed // the layer type. cloud_layers[i]->setAlpha( 1.0 ); // lower visibility as we approach the cloud layer. // accumulate effects from multiple cloud layers effvis *= ratio; } #if 0 if ( ratio < 1.0 ) { if ( ! in_puff ) { // calc chance of entering cloud puff double rnd = sg_random(); double chance = rnd * rnd * rnd; if ( chance > 0.95 /* * (diff - 25) / 50.0 */ ) { in_puff = true; puff_length = sg_random() * 2.0; // up to 2 seconds puff_progression = 0.0; } } if ( in_puff ) { // modify actual_visibility based on puff envelope if ( puff_progression <= ramp_up ) { double x = SGD_PI_2 * puff_progression / ramp_up; double factor = 1.0 - sin( x ); // cout << "ramp up = " << puff_progression // << " factor = " << factor << endl; effvis = effvis * factor; } else if ( puff_progression >= ramp_up + puff_length ) { double x = SGD_PI_2 * (puff_progression - (ramp_up + puff_length)) / ramp_down; double factor = sin( x ); // cout << "ramp down = " // << puff_progression - (ramp_up + puff_length) // << " factor = " << factor << endl; effvis = effvis * factor; } else { effvis = 0.0; } /* cout << "len = " << puff_length << " x = " << x << " factor = " << factor << " actual_visibility = " << actual_visibility << endl; */ // time_factor = ( global_multi_loop * // current_options.get_speed_up() ) / // (double)current_options.get_model_hz(); puff_progression += time_factor; // cout << "time factor = " << time_factor << endl; /* cout << "gml = " << global_multi_loop << " speed up = " << current_options.get_speed_up() << " hz = " << current_options.get_model_hz() << endl; */ if ( puff_progression > puff_length + ramp_up + ramp_down) { in_puff = false; } } } #endif // never let visibility drop below 25 meters if ( effvis <= 25.0 ) { effvis = 25.0; } } // for effective_visibility = effvis; } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkVideoToVideoFilter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" // typedefs for test const unsigned int Dimension = 2; typedef unsigned char InputPixelType; typedef itk::Image< InputPixelType, Dimension > InputFrameType; typedef itk::VideoStream< InputFrameType > InputVideoType; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputFrameType; typedef itk::VideoStream< OutputFrameType > OutputVideoType; namespace itk { namespace VideoToVideoFilterTest { /** * Create a new frame and fill it with the indicated value */ InputFrameType::Pointer CreateInputFrame(InputPixelType val) { InputFrameType::Pointer out = InputFrameType::New(); InputFrameType::RegionType largestRegion; InputFrameType::SizeType sizeLR; InputFrameType::IndexType startLR; startLR.Fill(0); sizeLR[0] = 50; sizeLR[1] = 40; largestRegion.SetSize(sizeLR); largestRegion.SetIndex(startLR); out->SetRegions(largestRegion); out->Allocate(); // Fill with the desired value itk::ImageRegionIterator<InputFrameType> iter(out, largestRegion); while(!iter.IsAtEnd()) { iter.Set(val); ++iter; } return out; } /** \class DummyVideoToVideoFilter * \brief A simple implementation of VideoTOVideoFilter for the test */ template<class TInputVideoStream, class TOutputVideoStream> class DummyVideoToVideoFilter : public VideoToVideoFilter<TInputVideoStream, TOutputVideoStream> { public: /** Standard class typedefs */ typedef TInputVideoStream InputVideoStreamType; typedef TOutputVideoStream OutputVideoStreamType; typedef DummyVideoToVideoFilter< InputVideoStreamType, OutputVideoStreamType > Self; typedef VideoSource< OutputVideoStreamType > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef WeakPointer< const Self > ConstWeakPointer; typedef typename TInputVideoStream::FrameType InputFrameType; typedef typename InputFrameType::RegionType InputFrameSpatialRegionType; typedef typename TOutputVideoStream::FrameType OutputFrameType; typedef typename OutputFrameType::RegionType OutputFrameSpatialRegionType; itkNewMacro(Self); itkTypeMacro(DummyVideoToVideoFilter, VideoToVideoFilter); protected: /** Constructor */ DummyVideoToVideoFilter() { this->TemporalProcessObject::m_UnitInputNumberOfFrames = 2; this->TemporalProcessObject::m_UnitOutputNumberOfFrames = 1; this->TemporalProcessObject::m_FrameSkipPerOutput = 1; this->TemporalProcessObject::m_InputStencilCurrentFrameIndex = 1; } /** Override ThreadedGenerateData to set all pixels in the requested region * to 1 */ virtual void ThreadedGenerateData( const OutputFrameSpatialRegionType& outputRegionForThread, int threadId) { const InputVideoStreamType* input = this->GetInput(); OutputVideoStreamType* output = this->GetOutput(); typename OutputVideoStreamType::TemporalRegionType outReqTempRegion = output->GetRequestedTemporalRegion(); unsigned long outputStart = outReqTempRegion.GetFrameStart(); unsigned long outputDuration = outReqTempRegion.GetFrameDuration(); typename InputVideoStreamType::TemporalRegionType inReqTempRegion = input->GetRequestedTemporalRegion(); unsigned long inputStart = inReqTempRegion.GetFrameStart(); unsigned long inputDuration = inReqTempRegion.GetFrameDuration(); // Print out your threadId std::cout << "Working on thread " << threadId << std::endl; std::cout << " input: " << inputStart << " -> " << inputDuration << std::endl; std::cout << " output: " << outputStart << " -> " << outputDuration << std::endl; // Just as a check, throw an exception if the durations aren't equal to the // unit output sizes if (outputDuration != this->TemporalProcessObject::m_UnitOutputNumberOfFrames) { itkExceptionMacro(<< "Trying to generate output of non-unit size. Got: " << outputDuration << " Expected: " << this->TemporalProcessObject::m_UnitOutputNumberOfFrames); } if (inputDuration < this->TemporalProcessObject::m_UnitInputNumberOfFrames) { itkExceptionMacro(<< "Input buffered region smaller than unit size. Got: " << inputDuration << " Expected: " << this->TemporalProcessObject::m_UnitInputNumberOfFrames); } // Get the two input frames and average them in the requested spatial region of the // output frame const InputFrameType* inFrame0 = input->GetFrame(inputStart); const InputFrameType* inFrame1 = input->GetFrame(inputStart+1); OutputFrameType* outFrame = output->GetFrame(outputStart); itk::ImageRegionConstIterator<InputFrameType> inIter0(inFrame0, outputRegionForThread); itk::ImageRegionConstIterator<InputFrameType> inIter1(inFrame1, outputRegionForThread); itk::ImageRegionIterator<OutputFrameType> outIter(outFrame, outputRegionForThread); while(!outIter.IsAtEnd()) { // Average input pixel values OutputPixelType val = ((OutputPixelType)inIter0.Get() + (OutputPixelType)inIter1.Get()) / 2; outIter.Set(val); ++outIter; ++inIter0; ++inIter1; } } }; } // end namespace VideoToVideoFilterTest } // end namespace itk /** * Test the basic functionality of temporal data objects */ int itkVideoToVideoFilterTest( int argc, char* argv[] ) { ////// // Set up new filter ////// // Instantiate a filter typedef itk::VideoToVideoFilterTest:: DummyVideoToVideoFilter< InputVideoType, OutputVideoType > VideoFilterType; VideoFilterType::Pointer filter = VideoFilterType::New(); // Set up an input video stream InputVideoType::Pointer inputVideo = InputVideoType::New(); itk::TemporalRegion inputLargestTemporalRegion; unsigned long inputStart = 0; unsigned long inputDuration = 10; inputLargestTemporalRegion.SetFrameStart(inputStart); inputLargestTemporalRegion.SetFrameDuration(inputDuration); inputVideo->SetLargestPossibleTemporalRegion(inputLargestTemporalRegion); // Fill the input with frames inputVideo->SetNumberOfBuffers(inputDuration); for (unsigned long i = inputStart; i < inputStart + inputDuration; ++i) { inputVideo->SetFrame(i, itk::VideoToVideoFilterTest::CreateInputFrame(i)); } inputVideo->SetBufferedTemporalRegion(inputLargestTemporalRegion); ////// // Connect input to filter and update ////// // Connect input filter->SetInput(inputVideo); filter->UpdateOutputInformation(); filter->GetOutput()->SetRequestedTemporalRegion( filter->GetOutput()->GetLargestPossibleTemporalRegion()); // Set up the requested spatial region on the output frames OutputFrameType::RegionType outputRequestedSpatialRegion; OutputFrameType::SizeType size; OutputFrameType::IndexType start; size[0] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[0]/2; size[1] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[1]/2; start[0] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[0]/4; start[1] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[1]/4; outputRequestedSpatialRegion.SetSize(size); outputRequestedSpatialRegion.SetIndex(start); filter->GetOutput()->SetAllRequestedSpatialRegions(outputRequestedSpatialRegion); // Set the number of frame buffers on the output so that we get all output // frames buffered at the end filter->GetOutput()->SetNumberOfBuffers( filter->GetOutput()->GetLargestPossibleTemporalRegion().GetFrameDuration()); // Update the filter filter->SetNumberOfThreads(1); filter->Update(); // Report on output buffers std::cout << "Number of output buffers: " << filter->GetOutput()->GetNumberOfBuffers() << std::endl; // Make sure results are correct in the requested spatia region unsigned long outputStart = filter->GetOutput()->GetRequestedTemporalRegion().GetFrameStart(); unsigned long outputDuration = filter->GetOutput()->GetRequestedTemporalRegion().GetFrameDuration(); for (unsigned long i = outputStart; i < outputStart + outputDuration; ++i) { std::cout << "Checking frame: " << i << std::endl; const OutputFrameType* frame = filter->GetOutput()->GetFrame(i); itk::ImageRegionConstIterator<OutputFrameType> iter(frame, frame->GetRequestedRegion()); while (!iter.IsAtEnd()) { OutputPixelType expectedVal = ((OutputPixelType)(i)-1.0 + (OutputPixelType)(i))/2.0; OutputPixelType epsilon = .00001; if (iter.Get() < expectedVal - epsilon || iter.Get() > expectedVal + epsilon) { std::cerr << "Filter didn't set values correctly. Got: " << iter.Get() << " Expected: " << expectedVal << std::endl; return EXIT_FAILURE; } ++iter; } } ////// // Return Successfully ////// return EXIT_SUCCESS; } <commit_msg>ENH: test area outside of requested spatial region after filter<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkVideoToVideoFilter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" // typedefs for test const unsigned int Dimension = 2; typedef unsigned char InputPixelType; typedef itk::Image< InputPixelType, Dimension > InputFrameType; typedef itk::VideoStream< InputFrameType > InputVideoType; typedef float OutputPixelType; typedef itk::Image< OutputPixelType, Dimension > OutputFrameType; typedef itk::VideoStream< OutputFrameType > OutputVideoType; namespace itk { namespace VideoToVideoFilterTest { /** * Create a new frame and fill it with the indicated value */ InputFrameType::Pointer CreateInputFrame(InputPixelType val) { InputFrameType::Pointer out = InputFrameType::New(); InputFrameType::RegionType largestRegion; InputFrameType::SizeType sizeLR; InputFrameType::IndexType startLR; startLR.Fill(0); sizeLR[0] = 50; sizeLR[1] = 40; largestRegion.SetSize(sizeLR); largestRegion.SetIndex(startLR); out->SetRegions(largestRegion); out->Allocate(); // Fill with the desired value itk::ImageRegionIterator<InputFrameType> iter(out, largestRegion); while(!iter.IsAtEnd()) { iter.Set(val); ++iter; } return out; } /** \class DummyVideoToVideoFilter * \brief A simple implementation of VideoTOVideoFilter for the test */ template<class TInputVideoStream, class TOutputVideoStream> class DummyVideoToVideoFilter : public VideoToVideoFilter<TInputVideoStream, TOutputVideoStream> { public: /** Standard class typedefs */ typedef TInputVideoStream InputVideoStreamType; typedef TOutputVideoStream OutputVideoStreamType; typedef DummyVideoToVideoFilter< InputVideoStreamType, OutputVideoStreamType > Self; typedef VideoSource< OutputVideoStreamType > Superclass; typedef SmartPointer< Self > Pointer; typedef SmartPointer< const Self > ConstPointer; typedef WeakPointer< const Self > ConstWeakPointer; typedef typename TInputVideoStream::FrameType InputFrameType; typedef typename InputFrameType::RegionType InputFrameSpatialRegionType; typedef typename TOutputVideoStream::FrameType OutputFrameType; typedef typename OutputFrameType::RegionType OutputFrameSpatialRegionType; itkNewMacro(Self); itkTypeMacro(DummyVideoToVideoFilter, VideoToVideoFilter); protected: /** Constructor */ DummyVideoToVideoFilter() { this->TemporalProcessObject::m_UnitInputNumberOfFrames = 2; this->TemporalProcessObject::m_UnitOutputNumberOfFrames = 1; this->TemporalProcessObject::m_FrameSkipPerOutput = 1; this->TemporalProcessObject::m_InputStencilCurrentFrameIndex = 1; } /** Override ThreadedGenerateData to set all pixels in the requested region * to 1 */ virtual void ThreadedGenerateData( const OutputFrameSpatialRegionType& outputRegionForThread, int threadId) { const InputVideoStreamType* input = this->GetInput(); OutputVideoStreamType* output = this->GetOutput(); typename OutputVideoStreamType::TemporalRegionType outReqTempRegion = output->GetRequestedTemporalRegion(); unsigned long outputStart = outReqTempRegion.GetFrameStart(); unsigned long outputDuration = outReqTempRegion.GetFrameDuration(); typename InputVideoStreamType::TemporalRegionType inReqTempRegion = input->GetRequestedTemporalRegion(); unsigned long inputStart = inReqTempRegion.GetFrameStart(); unsigned long inputDuration = inReqTempRegion.GetFrameDuration(); // Print out your threadId std::cout << "Working on thread " << threadId << std::endl; std::cout << " input: " << inputStart << " -> " << inputDuration << std::endl; std::cout << " output: " << outputStart << " -> " << outputDuration << std::endl; // Just as a check, throw an exception if the durations aren't equal to the // unit output sizes if (outputDuration != this->TemporalProcessObject::m_UnitOutputNumberOfFrames) { itkExceptionMacro(<< "Trying to generate output of non-unit size. Got: " << outputDuration << " Expected: " << this->TemporalProcessObject::m_UnitOutputNumberOfFrames); } if (inputDuration < this->TemporalProcessObject::m_UnitInputNumberOfFrames) { itkExceptionMacro(<< "Input buffered region smaller than unit size. Got: " << inputDuration << " Expected: " << this->TemporalProcessObject::m_UnitInputNumberOfFrames); } // Get the two input frames and average them in the requested spatial region of the // output frame const InputFrameType* inFrame0 = input->GetFrame(inputStart); const InputFrameType* inFrame1 = input->GetFrame(inputStart+1); OutputFrameType* outFrame = output->GetFrame(outputStart); itk::ImageRegionConstIterator<InputFrameType> inIter0(inFrame0, outputRegionForThread); itk::ImageRegionConstIterator<InputFrameType> inIter1(inFrame1, outputRegionForThread); itk::ImageRegionIterator<OutputFrameType> outIter(outFrame, outputRegionForThread); while(!outIter.IsAtEnd()) { // Average input pixel values OutputPixelType val = ((OutputPixelType)inIter0.Get() + (OutputPixelType)inIter1.Get()) / 2; outIter.Set(val); ++outIter; ++inIter0; ++inIter1; } } }; } // end namespace VideoToVideoFilterTest } // end namespace itk /** * Test the basic functionality of temporal data objects */ int itkVideoToVideoFilterTest( int argc, char* argv[] ) { ////// // Set up new filter ////// // Instantiate a filter typedef itk::VideoToVideoFilterTest:: DummyVideoToVideoFilter< InputVideoType, OutputVideoType > VideoFilterType; VideoFilterType::Pointer filter = VideoFilterType::New(); // Set up an input video stream InputVideoType::Pointer inputVideo = InputVideoType::New(); itk::TemporalRegion inputLargestTemporalRegion; unsigned long inputStart = 0; unsigned long inputDuration = 10; inputLargestTemporalRegion.SetFrameStart(inputStart); inputLargestTemporalRegion.SetFrameDuration(inputDuration); inputVideo->SetLargestPossibleTemporalRegion(inputLargestTemporalRegion); // Fill the input with frames inputVideo->SetNumberOfBuffers(inputDuration); for (unsigned long i = inputStart; i < inputStart + inputDuration; ++i) { inputVideo->SetFrame(i, itk::VideoToVideoFilterTest::CreateInputFrame(i)); } inputVideo->SetBufferedTemporalRegion(inputLargestTemporalRegion); ////// // Connect input to filter and update ////// // Connect input filter->SetInput(inputVideo); filter->UpdateOutputInformation(); filter->GetOutput()->SetRequestedTemporalRegion( filter->GetOutput()->GetLargestPossibleTemporalRegion()); // Set up the requested spatial region on the output frames OutputFrameType::RegionType outputRequestedSpatialRegion; OutputFrameType::SizeType size; OutputFrameType::IndexType start; size[0] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[0]/2; size[1] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[1]/2; start[0] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[0]/4; start[1] = inputVideo->GetFrame(0)->GetLargestPossibleRegion().GetSize()[1]/4; outputRequestedSpatialRegion.SetSize(size); outputRequestedSpatialRegion.SetIndex(start); filter->GetOutput()->SetAllRequestedSpatialRegions(outputRequestedSpatialRegion); // Set the number of frame buffers on the output so that we get all output // frames buffered at the end filter->GetOutput()->SetNumberOfBuffers( filter->GetOutput()->GetLargestPossibleTemporalRegion().GetFrameDuration()); // Update the filter filter->SetNumberOfThreads(1); filter->Update(); // Report on output buffers std::cout << "Number of output buffers: " << filter->GetOutput()->GetNumberOfBuffers() << std::endl; // Make sure results are correct in the requested spatial region unsigned long outputStart = filter->GetOutput()->GetRequestedTemporalRegion().GetFrameStart(); unsigned long outputDuration = filter->GetOutput()->GetRequestedTemporalRegion().GetFrameDuration(); for (unsigned long i = outputStart; i < outputStart + outputDuration; ++i) { std::cout << "Checking frame: " << i << std::endl; const OutputFrameType* frame = filter->GetOutput()->GetFrame(i); itk::ImageRegionConstIterator<OutputFrameType> iter(frame, frame->GetRequestedRegion()); OutputPixelType expectedVal = ((OutputPixelType)(i)-1.0 + (OutputPixelType)(i))/2.0; OutputPixelType epsilon = .00001; while (!iter.IsAtEnd()) { if (iter.Get() < expectedVal - epsilon || iter.Get() > expectedVal + epsilon) { std::cerr << "Filter didn't set values correctly. Got: " << iter.Get() << " Expected: " << expectedVal << std::endl; return EXIT_FAILURE; } ++iter; } // Make sure nothing set outside of requested spatial region OutputFrameType::IndexType idx; idx.Fill(0); if (frame->GetPixel(idx) > expectedVal - epsilon && frame->GetPixel(idx) < expectedVal + epsilon) { std::cerr << "Filter set pixel outside of requested region" << std::endl; return EXIT_FAILURE; } } ////// // Return Successfully ////// return EXIT_SUCCESS; } <|endoftext|>
<commit_before>#include <exception> #include <assert.h> #include "Stack.h" using namespace std; template <typename T> Stack<T>::Node::Node(T _data, Node* _pNext) { this->data = _data; this->pNext = _pNext; } template <typename T> Stack<T>::Stack() { init(); } template <typename T> Stack<T>::~Stack() { destroy(); } template <typename T> Stack<T>::Stack(Stack<T> const & other) { init(); copyFrom(other); } template <typename T> Stack<T>& Stack<T>::operator=(Stack<T> const & other) { if (this != &other) { destroy(); copyFrom(other); } return *this; } template <typename T> void Stack<T>::init() { this->pTop = NULL; this->used = 0; } template <typename T> void Stack<T>::destroy() { Node* p; while (pTop) { p = pTop; pTop = pTop->pNext; delete p; } init(); } template <typename T> void Stack<T>::copyFrom(Stack<T> const & other) { if (other.isEmpty()) { return; } Node *ours, *theirs; try { pTop = new Node(other.pTop->data); ours = pTop; theirs = other.pTop->pNext; while (theirs) { ours->pNext = new Node(theirs->data); ours = ours->pNext; theirs = theirs->pNext; } used = other.used; } catch (std::bad_alloc&) { destroy(); throw; } } template <typename T> bool Stack<T>::push(T element) { Node* pNewNode; try { pNewNode = new Node(element, pTop); } catch (...) { return false; } pTop = pNewNode; used++; return true; } template <typename T> bool Stack<T>::pop() { if (used == 0) { return false; } Node* p; p = pTop; pTop = pTop->pNext; delete p; used--; return true; } //template <typename T> //bool Stack<T>::pop(T& element) { // if (used == 0) { // return false; // } // // element = pTop->data; // // Node* pOld = pTop; // pTop = pTop->pNext; // // delete pOld; // // used--; // // return true; //} template <typename T> T Stack<T>::peek() const { assert(used != 0); return pTop->data; } template <typename T> void Stack<T>::removeAll() { destroy(); } template <typename T> size_t Stack<T>::getAllocatedSize() const { return used * sizeof(Node); } template <typename T> size_t Stack<T>::getSize() const { return used; } template <typename T> bool Stack<T>::isEmpty() const { return used == 0; } template class Stack <int>; template class Stack <const char*>;<commit_msg>add some comments of the functions<commit_after>#include <exception> #include <assert.h> #include "Stack.h" using namespace std; template <typename T> Stack<T>::Node::Node(T _data, Node* _pNext) { this->data = _data; this->pNext = _pNext; } template <typename T> Stack<T>::Stack() { init(); } template <typename T> Stack<T>::~Stack() { destroy(); } template <typename T> Stack<T>::Stack(Stack<T> const & other) { init(); copyFrom(other); } template <typename T> Stack<T>& Stack<T>::operator=(Stack<T> const & other) { if (this != &other) { destroy(); copyFrom(other); } return *this; } /// /// set initial values of the properties /// template <typename T> void Stack<T>::init() { this->pTop = NULL; this->used = 0; } /// /// delete all values in the stack /// realese the allocated memory /// template <typename T> void Stack<T>::destroy() { Node* p; while (pTop) { p = pTop; pTop = pTop->pNext; delete p; } init(); } /// /// copy the content of another stack /// /// the function suggests that the stack /// in which we copy is empty /// template <typename T> void Stack<T>::copyFrom(Stack<T> const & other) { if (other.isEmpty()) { return; } Node *ours, *theirs; try { pTop = new Node(other.pTop->data); ours = pTop; theirs = other.pTop->pNext; while (theirs) { ours->pNext = new Node(theirs->data); ours = ours->pNext; theirs = theirs->pNext; } used = other.used; } catch (std::bad_alloc&) { destroy(); throw; } } /// /// add new element at the top of the stack /// template <typename T> bool Stack<T>::push(T element) { Node* pNewNode; try { pNewNode = new Node(element, pTop); } catch (...) { return false; } pTop = pNewNode; used++; return true; } /// /// remove the element at the top of the stack /// template <typename T> bool Stack<T>::pop() { if (used == 0) { return false; } Node* p; p = pTop; pTop = pTop->pNext; delete p; used--; return true; } /// /// remove and return the element at the top of the stack /// //template <typename T> //bool Stack<T>::pop(T& element) { // if (used == 0) { // return false; // } // // element = pTop->data; // // Node* pOld = pTop; // pTop = pTop->pNext; // // delete pOld; // // used--; // // return true; //} /// /// return the element at the top of the stack /// template <typename T> T Stack<T>::peek() const { assert(used != 0); return pTop->data; } template <typename T> void Stack<T>::removeAll() { destroy(); } template <typename T> size_t Stack<T>::getAllocatedSize() const { return used * sizeof(Node); } template <typename T> size_t Stack<T>::getSize() const { return used; } template <typename T> bool Stack<T>::isEmpty() const { return used == 0; } template class Stack <int>; template class Stack <const char*>; <|endoftext|>
<commit_before>/*============================================================================= Library: CTK Copyright (c) 2010 German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkDicomHostService.h" #include "ctkDicomServicePrivate.h" #include "ctkDicomWG23TypesHelper.h" ctkDicomHostService::ctkDicomHostService(int port) : d_ptr(new ctkDicomServicePrivate(port)) { } ctkDicomHostService::~ctkDicomHostService() { } QString ctkDicomHostService::generateUID() { Q_D(ctkDicomService); const QtSoapType& result = d->askHost("generateUID", NULL); QString resultUID = ctkDicomSoapUID::getUID(result); return resultUID; } QString ctkDicomHostService::getOutputLocation(const QStringList& preferredProtocols) { Q_D(ctkDicomService); QtSoapStruct* input = dynamic_cast<QtSoapStruct*>( new ctkDicomSoapArrayOfString("preferredProtocols", preferredProtocols)); const QtSoapType& result = d->askHost("getOutputLocation", input); QString resultString = result.value().toString(); return resultString; } QRect ctkDicomHostService::getAvailableScreen(const QRect& preferredScreen) { Q_D(ctkDicomService); QtSoapStruct* input = new ctkDicomSoapRectangle("preferredScreen", preferredScreen); const QtSoapType& result = d->askHost("getAvailableScreen", input); QRect resultRect = ctkDicomSoapRectangle::getQRect(result); qDebug() << "x:" << resultRect.x() << " y:" << resultRect.y(); return resultRect; } void ctkDicomHostService::notifyStateChanged(ctkDicomWG23::State state) { Q_D(ctkDicomService); QtSoapType* input = new ctkDicomSoapState("stateChanged", state); d->askHost("notifyStateChanged", input); } void ctkDicomHostService::notifyStatus(const ctkDicomWG23::Status& status) { Q_D(ctkDicomService); QtSoapStruct* input = new ctkDicomSoapStatus("status", status); d->askHost("notifyStatus", input); } <commit_msg>FIX: wrong parameter name in SOAP message of notifyStateChanged<commit_after>/*============================================================================= Library: CTK Copyright (c) 2010 German Cancer Research Center, Division of Medical and Biological Informatics Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. =============================================================================*/ #include "ctkDicomHostService.h" #include "ctkDicomServicePrivate.h" #include "ctkDicomWG23TypesHelper.h" ctkDicomHostService::ctkDicomHostService(int port) : d_ptr(new ctkDicomServicePrivate(port)) { } ctkDicomHostService::~ctkDicomHostService() { } QString ctkDicomHostService::generateUID() { Q_D(ctkDicomService); const QtSoapType& result = d->askHost("generateUID", NULL); QString resultUID = ctkDicomSoapUID::getUID(result); return resultUID; } QString ctkDicomHostService::getOutputLocation(const QStringList& preferredProtocols) { Q_D(ctkDicomService); QtSoapStruct* input = dynamic_cast<QtSoapStruct*>( new ctkDicomSoapArrayOfString("preferredProtocols", preferredProtocols)); const QtSoapType& result = d->askHost("getOutputLocation", input); QString resultString = result.value().toString(); return resultString; } QRect ctkDicomHostService::getAvailableScreen(const QRect& preferredScreen) { Q_D(ctkDicomService); QtSoapStruct* input = new ctkDicomSoapRectangle("preferredScreen", preferredScreen); const QtSoapType& result = d->askHost("getAvailableScreen", input); QRect resultRect = ctkDicomSoapRectangle::getQRect(result); qDebug() << "x:" << resultRect.x() << " y:" << resultRect.y(); return resultRect; } void ctkDicomHostService::notifyStateChanged(ctkDicomWG23::State state) { Q_D(ctkDicomService); QtSoapType* input = new ctkDicomSoapState("state", state); d->askHost("notifyStateChanged", input); } void ctkDicomHostService::notifyStatus(const ctkDicomWG23::Status& status) { Q_D(ctkDicomService); QtSoapStruct* input = new ctkDicomSoapStatus("status", status); d->askHost("notifyStatus", input); } <|endoftext|>
<commit_before>#ifndef AVECADO_FACTORY_HPP #define AVECADO_FACTORY_HPP #include <boost/property_tree/ptree.hpp> namespace pt = boost::property_tree; namespace avecado { namespace post_process { /** * Generic factory class for creating objects based on type name and configuration. */ template <typename T> class factory { public: typedef std::shared_ptr<T> ptr_t; typedef ptr_t (*factory_func_t)(pt::ptree const& config); typedef std::map<std::string, factory_func_t> func_map_t; factory() : m_factory_functions() {}; factory & register_type(std::string const& type, factory_func_t func) { m_factory_functions.insert(std::make_pair(type, func)); return (*this); } ptr_t create(std::string const& type, pt::ptree const& config) const { typename func_map_t::const_iterator f_itr = m_factory_functions.find(type); if (f_itr == m_factory_functions.end()) { // Not found. // TODO: Throw exception here? return ptr_t(); } factory_func_t func = f_itr->second; ptr_t ptr = func(config); return ptr; } private: func_map_t m_factory_functions; }; } // namespace post_process } // namespace avecado #endif // AVECADO_FACTORY_HPP <commit_msg>Fix segfault when config specifies invalid izer types.<commit_after>#ifndef AVECADO_FACTORY_HPP #define AVECADO_FACTORY_HPP #include <boost/property_tree/ptree.hpp> namespace pt = boost::property_tree; namespace avecado { namespace post_process { /** * Generic factory class for creating objects based on type name and configuration. */ template <typename T> class factory { public: typedef std::shared_ptr<T> ptr_t; typedef ptr_t (*factory_func_t)(pt::ptree const& config); typedef std::map<std::string, factory_func_t> func_map_t; factory() : m_factory_functions() {}; factory & register_type(std::string const& type, factory_func_t func) { m_factory_functions.insert(std::make_pair(type, func)); return (*this); } ptr_t create(std::string const& type, pt::ptree const& config) const { typename func_map_t::const_iterator f_itr = m_factory_functions.find(type); if (f_itr == m_factory_functions.end()) { throw std::runtime_error("Unrecognized type: " + type); } factory_func_t func = f_itr->second; ptr_t ptr = func(config); return ptr; } private: func_map_t m_factory_functions; }; } // namespace post_process } // namespace avecado #endif // AVECADO_FACTORY_HPP <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <[email protected]> Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------*/ #include "OgreRoot.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreWindowEventUtilities.h" #include "OgreGLESPrerequisites.h" #include "OgreGLESRenderSystem.h" #include "OgreSymbianEGLSupport.h" #include "OgreSymbianEGLWindow.h" #include "OgreSymbianEGLContext.h" #include <iostream> #include <algorithm> #include <climits> #include <w32std.h> #include <coemain.h> namespace Ogre { SymbianEGLWindow::SymbianEGLWindow(EGLSupport *glsupport) : EGLWindow(glsupport) { } SymbianEGLWindow::~SymbianEGLWindow() { // Destroy the RWindow. if( mWindow != NULL ) { ((RWindow *)mWindow)->SetOrdinalPosition( KOrdinalPositionSwitchToOwningWindow ); ((RWindow *)mWindow)->Close(); delete mWindow; mWindow = NULL; } } EGLContext * SymbianEGLWindow::createEGLContext() const { return new SymbianEGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface); } void SymbianEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height ) { } void SymbianEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) { } void SymbianEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) { // destroy current window, if any if (mWindow) destroy(); mWindow = 0; mClosed = false; mIsDepthBuffered = true; mColourDepth = 32; if (!mIsExternal) { /** Handle to the Windows Server session */ RWsSession iWsSession; /** Handle to the Window group */ RWindowGroup iWindowGroup; /** The Screen device */ CWsScreenDevice* iWsScreenDevice; CCoeEnv* env = CCoeEnv::Static(); iWsSession = env->WsSession(); iWsScreenDevice = env->ScreenDevice(); iWindowGroup = env->RootWin(); { CCoeEnv* env = CCoeEnv::Static(); /** Handle to the Windows Server session */ RWsSession iWsSession; /** Handle to the Window group */ RWindowGroup iWindowGroup; /** The Screen device */ CWsScreenDevice* iWsScreenDevice; iWsSession = env->WsSession(); iWsScreenDevice = env->ScreenDevice(); iWindowGroup = env->RootWin(); if( !iWsScreenDevice ) { return; } RWindow* iWindow; iWindow = new (ELeave) RWindow( iWsSession ); // Construct the window. TInt err2 = iWindow->Construct( iWindowGroup, 435353 ); User::LeaveIfError( err2 ); // Enable the EEventScreenDeviceChanged event. iWindowGroup.EnableScreenChangeEvents(); TPixelsTwipsAndRotation pixnrot; iWsScreenDevice->GetScreenModeSizeAndRotation( iWsScreenDevice->CurrentScreenMode(), pixnrot ); // Set size of the window (cover the entire screen) iWindow->SetExtent( TPoint( 0, 0 ), pixnrot.iPixelSize ); iWindow->SetRequiredDisplayMode( iWsScreenDevice->DisplayMode() ); // Activate window and bring it to the foreground iWindow->Activate(); iWindow->SetVisible( ETrue ); iWindow->SetNonFading( ETrue ); iWindow->SetShadowDisabled( ETrue ); iWindow->EnableRedrawStore( EFalse ); iWindow->EnableVisibilityChangeEvents(); iWindow->SetNonTransparent(); iWindow->SetBackgroundColor(); iWindow->SetOrdinalPosition( 0 ); mWindow = iWindow; } } mNativeDisplay = EGL_DEFAULT_DISPLAY; mEglDisplay = eglGetDisplay(mNativeDisplay); mGLSupport->setGLDisplay(mEglDisplay); // Choose the buffer size based on the Window's display mode. TDisplayMode displayMode = ((RWindow *)mWindow)->DisplayMode(); TInt bufferSize = 0; switch( displayMode ) { case(EColor4K): bufferSize = 12; break; case(EColor64K): bufferSize = 16; break; case(EColor16M): bufferSize = 24; break; case(EColor16MU): case(EColor16MA): bufferSize = 32; break; default: break; } // Set the desired properties for the EGLSurface const EGLint attributeList[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BUFFER_SIZE, bufferSize, EGL_NONE }; EGLint numConfigs = 0; // Choose the best EGLConfig that matches the desired properties. if( eglChooseConfig( mEglDisplay, attributeList, &mEglConfig, 1, &numConfigs ) == EGL_FALSE ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglChooseConfig failed(== EGL_FALSE)!\n" , __FUNCTION__); } if( numConfigs == 0 ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglChooseConfig failed (numConfigs == 0)!\n" , __FUNCTION__); } mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); } void SymbianEGLWindow::reposition( int left, int top ) { } void SymbianEGLWindow::resize( unsigned int width, unsigned int height ) { } void SymbianEGLWindow::windowMovedOrResized() { } void SymbianEGLWindow::switchFullScreen( bool fullscreen ) { } void SymbianEGLWindow::create( const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams ) { String title = name; uint samples = 0; int gamma; short frequency = 0; bool vsync = false; ::EGLContext eglContext = 0; int left = 0; int top = 0; mIsFullScreen = fullScreen; if (miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); if ((opt = miscParams->find("currentGLContext")) != end && StringConverter::parseBool(opt->second)) { eglContext = eglGetCurrentContext(); if (eglContext) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "EGLWindow::create"); } eglContext = eglGetCurrentContext(); mEglSurface = eglGetCurrentSurface(EGL_DRAW); } // Note: Some platforms support AA inside ordinary windows if ((opt = miscParams->find("FSAA")) != end) { samples = StringConverter::parseUnsignedInt(opt->second); } if ((opt = miscParams->find("displayFrequency")) != end) { frequency = (short)StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("vsync")) != end) { vsync = StringConverter::parseBool(opt->second); } if ((opt = miscParams->find("gamma")) != end) { gamma = StringConverter::parseBool(opt->second); } if ((opt = miscParams->find("left")) != end) { left = StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("top")) != end) { top = StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("title")) != end) { title = opt->second; } if ((opt = miscParams->find("externalGLControl")) != end) { mIsExternalGLControl = StringConverter::parseBool(opt->second); } } initNativeCreatedWindow(miscParams); if (mEglSurface) { mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height); } if (!mEglConfig && eglContext) { mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); if (!mEglConfig) { // This should never happen. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a EGLFBConfig", "EGLWindow::create"); } } mIsExternal = (mEglSurface != 0); if (!mEglConfig) { EGLint minAttribs[] = { EGL_LEVEL, 0, EGL_DEPTH_SIZE, 16, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_NONE }; EGLint maxAttribs[] = { EGL_SAMPLES, samples, EGL_STENCIL_SIZE, INT_MAX, EGL_NONE }; mEglConfig = mGLSupport->selectGLConfig(minAttribs, maxAttribs); mHwGamma = false; } if (!mIsTopLevel) { mIsFullScreen = false; left = top = 0; } if (mIsFullScreen) { mGLSupport->switchMode (width, height, frequency); } if (!mIsExternal) { createNativeWindow(left, top, width, height, title); } mContext = createEGLContext(); ::EGLSurface oldDrawableDraw = eglGetCurrentSurface(EGL_DRAW); ::EGLSurface oldDrawableRead = eglGetCurrentSurface(EGL_READ); ::EGLContext oldContext = eglGetCurrentContext(); EGLint glConfigID; mGLSupport->getGLConfigAttrib(mEglConfig, EGL_CONFIG_ID, &glConfigID); LogManager::getSingleton().logMessage("EGLWindow::create used FBConfigID = " + StringConverter::toString(glConfigID)); mName = name; mWidth = width; mHeight = height; mLeft = left; mTop = top; mActive = true; mVisible = true; mClosed = false; } } <commit_msg>Symbian port: Removed some unneeded initialization from the Symbian EGL window.<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2008 Renato Araujo Oliveira Filho <[email protected]> Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --------------------------------------------------------------------------*/ #include "OgreRoot.h" #include "OgreException.h" #include "OgreLogManager.h" #include "OgreStringConverter.h" #include "OgreWindowEventUtilities.h" #include "OgreGLESPrerequisites.h" #include "OgreGLESRenderSystem.h" #include "OgreSymbianEGLSupport.h" #include "OgreSymbianEGLWindow.h" #include "OgreSymbianEGLContext.h" #include <iostream> #include <algorithm> #include <climits> #include <w32std.h> #include <coemain.h> namespace Ogre { SymbianEGLWindow::SymbianEGLWindow(EGLSupport *glsupport) : EGLWindow(glsupport) { } SymbianEGLWindow::~SymbianEGLWindow() { // Destroy the RWindow. if( mWindow != NULL ) { ((RWindow *)mWindow)->SetOrdinalPosition( KOrdinalPositionSwitchToOwningWindow ); ((RWindow *)mWindow)->Close(); delete mWindow; mWindow = NULL; } } EGLContext * SymbianEGLWindow::createEGLContext() const { return new SymbianEGLContext(mEglDisplay, mGLSupport, mEglConfig, mEglSurface); } void SymbianEGLWindow::getLeftAndTopFromNativeWindow( int & left, int & top, uint width, uint height ) { } void SymbianEGLWindow::initNativeCreatedWindow(const NameValuePairList *miscParams) { } void SymbianEGLWindow::createNativeWindow( int &left, int &top, uint &width, uint &height, String &title ) { // destroy current window, if any if (mWindow) destroy(); mWindow = 0; mClosed = false; mIsDepthBuffered = true; mColourDepth = 32; if (!mIsExternal) { /** Handle to the Windows Server session */ RWsSession iWsSession; /** Handle to the Window group */ RWindowGroup iWindowGroup; /** The Screen device */ CWsScreenDevice* iWsScreenDevice; CCoeEnv* env = CCoeEnv::Static(); iWsSession = env->WsSession(); iWsScreenDevice = env->ScreenDevice(); iWindowGroup = env->RootWin(); { CCoeEnv* env = CCoeEnv::Static(); /** Handle to the Windows Server session */ RWsSession iWsSession; /** Handle to the Window group */ RWindowGroup iWindowGroup; /** The Screen device */ CWsScreenDevice* iWsScreenDevice; iWsSession = env->WsSession(); iWsScreenDevice = env->ScreenDevice(); iWindowGroup = env->RootWin(); if( !iWsScreenDevice ) { return; } RWindow* iWindow; iWindow = new (ELeave) RWindow( iWsSession ); // Construct the window. TInt err2 = iWindow->Construct( iWindowGroup, 435353 ); User::LeaveIfError( err2 ); // Enable the EEventScreenDeviceChanged event. iWindowGroup.EnableScreenChangeEvents(); TPixelsTwipsAndRotation pixnrot; iWsScreenDevice->GetScreenModeSizeAndRotation( iWsScreenDevice->CurrentScreenMode(), pixnrot ); // Set size of the window (cover the entire screen) iWindow->SetExtent( TPoint( 0, 0 ), pixnrot.iPixelSize ); iWindow->SetRequiredDisplayMode( iWsScreenDevice->DisplayMode() ); // Activate window and bring it to the foreground iWindow->Activate(); iWindow->SetVisible( ETrue ); iWindow->SetNonFading( ETrue ); iWindow->SetShadowDisabled( ETrue ); iWindow->EnableRedrawStore( EFalse ); iWindow->EnableVisibilityChangeEvents(); iWindow->SetNonTransparent(); iWindow->SetBackgroundColor(); iWindow->SetOrdinalPosition( 0 ); mWindow = iWindow; } } mNativeDisplay = EGL_DEFAULT_DISPLAY; mEglDisplay = eglGetDisplay(mNativeDisplay); mGLSupport->setGLDisplay(mEglDisplay); // Choose the buffer size based on the Window's display mode. TDisplayMode displayMode = ((RWindow *)mWindow)->DisplayMode(); TInt bufferSize = 0; switch( displayMode ) { case(EColor4K): bufferSize = 12; break; case(EColor64K): bufferSize = 16; break; case(EColor16M): bufferSize = 24; break; case(EColor16MU): case(EColor16MA): bufferSize = 32; break; default: break; } // Set the desired properties for the EGLSurface const EGLint attributeList[] = { EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_BUFFER_SIZE, bufferSize, EGL_NONE }; EGLint numConfigs = 0; // Choose the best EGLConfig that matches the desired properties. if( eglChooseConfig( mEglDisplay, attributeList, &mEglConfig, 1, &numConfigs ) == EGL_FALSE ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglChooseConfig failed(== EGL_FALSE)!\n" , __FUNCTION__); } if( numConfigs == 0 ) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "eglChooseConfig failed (numConfigs == 0)!\n" , __FUNCTION__); } mEglSurface = createSurfaceFromWindow(mEglDisplay, mWindow); } void SymbianEGLWindow::reposition( int left, int top ) { } void SymbianEGLWindow::resize( unsigned int width, unsigned int height ) { } void SymbianEGLWindow::windowMovedOrResized() { } void SymbianEGLWindow::switchFullScreen( bool fullscreen ) { } void SymbianEGLWindow::create( const String& name, unsigned int width, unsigned int height, bool fullScreen, const NameValuePairList *miscParams ) { String title = name; uint samples = 0; int gamma; short frequency = 0; bool vsync = false; ::EGLContext eglContext = 0; int left = 0; int top = 0; mIsFullScreen = fullScreen; if (miscParams) { NameValuePairList::const_iterator opt; NameValuePairList::const_iterator end = miscParams->end(); if ((opt = miscParams->find("currentGLContext")) != end && StringConverter::parseBool(opt->second)) { eglContext = eglGetCurrentContext(); if (eglContext) { OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "currentGLContext was specified with no current GL context", "EGLWindow::create"); } eglContext = eglGetCurrentContext(); mEglSurface = eglGetCurrentSurface(EGL_DRAW); } // Note: Some platforms support AA inside ordinary windows if ((opt = miscParams->find("FSAA")) != end) { samples = StringConverter::parseUnsignedInt(opt->second); } if ((opt = miscParams->find("displayFrequency")) != end) { frequency = (short)StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("vsync")) != end) { vsync = StringConverter::parseBool(opt->second); } if ((opt = miscParams->find("gamma")) != end) { gamma = StringConverter::parseBool(opt->second); } if ((opt = miscParams->find("left")) != end) { left = StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("top")) != end) { top = StringConverter::parseInt(opt->second); } if ((opt = miscParams->find("title")) != end) { title = opt->second; } if ((opt = miscParams->find("externalGLControl")) != end) { mIsExternalGLControl = StringConverter::parseBool(opt->second); } } initNativeCreatedWindow(miscParams); if (mEglSurface) { mEglConfig = mGLSupport->getGLConfigFromDrawable (mEglSurface, &width, &height); } if (!mEglConfig && eglContext) { mEglConfig = mGLSupport->getGLConfigFromContext(eglContext); if (!mEglConfig) { // This should never happen. OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Unexpected failure to determine a EGLFBConfig", "EGLWindow::create"); } } mIsExternal = (mEglSurface != 0); if (!mIsTopLevel) { mIsFullScreen = false; left = top = 0; } if (mIsFullScreen) { mGLSupport->switchMode (width, height, frequency); } if (!mIsExternal) { createNativeWindow(left, top, width, height, title); } mContext = createEGLContext(); ::EGLSurface oldDrawableDraw = eglGetCurrentSurface(EGL_DRAW); ::EGLSurface oldDrawableRead = eglGetCurrentSurface(EGL_READ); ::EGLContext oldContext = eglGetCurrentContext(); EGLint glConfigID; mGLSupport->getGLConfigAttrib(mEglConfig, EGL_CONFIG_ID, &glConfigID); LogManager::getSingleton().logMessage("EGLWindow::create used FBConfigID = " + StringConverter::toString(glConfigID)); mName = name; mWidth = width; mHeight = height; mLeft = left; mTop = top; mActive = true; mVisible = true; mClosed = false; } } <|endoftext|>
<commit_before>// uses boost:asio to get some http data #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/write.hpp> #include <iostream> #include <memory> namespace a = boost::asio; using namespace boost::asio::ip; // to get 'tcp::' class session : public std::enable_shared_from_this<session> { public: explicit session(tcp::socket socket) : socket_(std::move(socket)), timer_(socket_.get_io_service()), strand_(socket_.get_io_service()) {} void go() { auto self(shared_from_this()); spawn(strand_, [this, self](a::yield_context yield) { try { char data[128]; for (;;) { timer_.expires_from_now(std::chrono::seconds(10)); std::size_t n = socket_.async_read_some(a::buffer(data), yield); a::async_write(socket_, a::buffer(data, n), yield); } } catch (std::exception &e) { socket_.close(); timer_.cancel(); } }); a::spawn(strand_, [this, self](a::yield_context yield) { while (socket_.is_open()) { boost::system::error_code ignored_ec; timer_.async_wait(yield[ignored_ec]); if (timer_.expires_from_now() <= std::chrono::seconds(0)) socket_.close(); } }); } private: tcp::socket socket_; a::steady_timer timer_; a::io_service::strand strand_; }; int main(int argc, char *argv[]) { try { a::io_service io_service; tcp::resolver resolver(io_service); a::spawn(io_service, [&](a::yield_context yield) { // http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/generic__stream_protocol/socket.html auto endpoint = resolver.async_resolve({"httpbin.org", "http"}, yield); tcp::socket socket(io_service); a::async_connect(socket, endpoint, yield); }); io_service.run(); } catch (std::exception &e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <commit_msg>Can now read a bit of a response<commit_after>// uses boost:asio to get some http data #include <boost/asio/io_service.hpp> #include <boost/asio/ip/tcp.hpp> #include <boost/asio/spawn.hpp> #include <boost/asio/steady_timer.hpp> #include <boost/asio/connect.hpp> #include <boost/asio/write.hpp> #include <boost/asio/read.hpp> #include <boost/asio/buffered_read_stream.hpp> #include <iostream> #include <memory> #include <iterator> #include <iostream> namespace a = boost::asio; using namespace boost::asio::ip; // to get 'tcp::' int main(int argc, char *argv[]) { try { a::io_service io_service; tcp::resolver resolver(io_service); a::spawn(io_service, [&](a::yield_context yield) { // http://www.boost.org/doc/libs/1_60_0/doc/html/boost_asio/reference/generic__stream_protocol/socket.html auto endpoint = resolver.async_resolve({"httpbin.org", "http"}, yield); tcp::socket socket(io_service); a::async_connect(socket, endpoint, yield); std::string request("GET / HTTP/1.1\r\n" "Accept: */*\r\n" "Accept-Encoding: gzip, deflate\r\n\r\n"); a:async_write(socket, a::buffer(request), yield); // Now get the response std::array<char, 128> buf; int bytes = a::async_read(socket, a::buffer(buf), yield); using namespace std; cout << "Got this: "; std::copy(buf.begin(), buf.end(), std::ostream_iterator<char>(cout)); cout << endl; }); io_service.run(); } catch (std::exception &e) { std::cerr << "Exception: " << e.what() << "\n"; } return 0; } <|endoftext|>
<commit_before>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "commands/Command.h" #include "commands/CommandExecutionEngine.h" #include "commands/CommandResult.h" #include "commands/CommandSuggestion.h" #include "handlers/GenericHandler.h" #include "InteractionBasePlugin.h" #include "VisualizationBase/src/items/Item.h" #include "VisualizationBase/src/items/SceneHandlerItem.h" #include "VisualizationBase/src/Scene.h" namespace Interaction { const char* QUOTE_SYMBOLS = "\"'`"; const char* ESCAPE_SYMBOLS = "\\"; CommandExecutionEngine::~CommandExecutionEngine() {} CommandExecutionEngine* CommandExecutionEngine::instance() { static CommandExecutionEngine engine; return &engine; } void CommandExecutionEngine::execute(Visualization::Item *originator, const QString& command, const std::unique_ptr<Visualization::Cursor>& cursor) { lastCommandResult_.clear(); QString trimmed = command.trimmed(); if ( !doQuotesMatch(command, QUOTE_SYMBOLS, ESCAPE_SYMBOLS) ) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("A quoted string expands past the end of the command."))); lastCommandResult_->errors().first()->addResolutionTip("Try inserting a matching quote."); return; } QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; QStringList tokens = tokenize(trimmed, QUOTE_SYMBOLS, ESCAPE_SYMBOLS); bool processed = false; while (target != nullptr && !processed) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); if (handler) { for (int i = 0; i< handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, target, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, target, tokens, cursor)); if (lastCommandResult_->code() != CommandResult::CanNotInterpret) { processed = true; break; } else lastCommandResult_.clear(); } } } if (!processed) target = target->parent(); } // If no item can process this command dispatch it to the SceneItem if (!processed && originator != originator->scene()->sceneHandlerItem()) { auto sceneHandlerItem = source->scene()->sceneHandlerItem(); auto handler = dynamic_cast<GenericHandler*> (sceneHandlerItem->handler()); if ( handler ) { for (int i = 0; i < handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, sceneHandlerItem, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, sceneHandlerItem, tokens, cursor)); if ( lastCommandResult_->code() != CommandResult::CanNotInterpret ) { processed = true; break; } else lastCommandResult_.clear(); } } } } // If the command is still not processed this is an error if (!processed) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("Unknown command '" + command + "' "))); log.warning("Unknown command: " + command); } } QList<CommandSuggestion*> CommandExecutionEngine::autoComplete(Visualization::Item *originator, const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; QString trimmed = textSoFar.trimmed(); QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; // This set keeps a list of commands that have already contributed some suggestions. If a command contributes // suggestions at a more specific context, then we ignore it in less specific contexts, even if it could // contribute more suggestions. The stored value is the hash code of a type_info structure QSet<std::size_t> alreadySuggested; // Get suggestion from item and parents while (target != nullptr) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor)); target = target->parent(); } // Get suggestions from the scene handler item if (originator != originator->scene()->sceneHandlerItem()) { GenericHandler* handler = dynamic_cast<GenericHandler*> (source->scene()->sceneHandlerItem()->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor) ); } return result; } QList<CommandSuggestion*> CommandExecutionEngine::suggestionsForHandler(GenericHandler* handler, QSet<std::size_t>& alreadySuggested, QString trimmedCommandText, Visualization::Item* source, Visualization::Item* target, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; if (handler) for (auto command : handler->commands()) { if (alreadySuggested.contains(typeid(*command).hash_code())) continue; QList<CommandSuggestion*> suggestions; if (!trimmedCommandText.isEmpty() || command->appearsInMenus()) suggestions = command->suggest(source, target, trimmedCommandText, cursor); result.append( suggestions ); if (!suggestions.isEmpty()) alreadySuggested.insert(typeid(*command).hash_code()); } return result; } QString CommandExecutionEngine::extractNavigationString(QString& command) { // Extract navigation information if any QString trimmed = command.trimmed(); QString simplified = trimmed.simplified(); // Note that this will destroy any spacing within quotations. QString navigation; if ( simplified.startsWith("~ ") || simplified.startsWith(".. ") || simplified.startsWith(". ") || simplified.startsWith("../") || simplified.startsWith("./") || simplified.startsWith("/") ) { navigation = trimmed.left(simplified.indexOf(' ')); command = trimmed.mid(navigation.size()).trimmed(); } return navigation; } Visualization::Item* CommandExecutionEngine::navigate(Visualization::Item *originator, const QString&) { //TODO figure out what navigation we want and implement it. return originator; } QStringList CommandExecutionEngine::tokenize(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QStringList result; QString str; QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) { if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); quote = string[i]; str = quote; } else str.append(string[i]); } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) { result.append(str + quote); quote = QChar(); str = QString(); } } } if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); return result; } QStringList CommandExecutionEngine::tokenizeNonQuoted(const QString& string) { //TODO The concept of tokens here is unclear. Define this better. QStringList result; QString str; QChar last; bool fractionInitiated = false; for (int i = 0; i < string.size(); ++i) { if ( string[i] == ' ' ) { if ( !str.isNull() ) result.append(str); str = QString(); fractionInitiated = false; } else if ( string[i].isDigit() && fractionInitiated && last == '.' ) { str = result.last() + '.' + string[i]; result.removeLast(); fractionInitiated = false; } else if ( string[i].isDigit() && str.isNull() ) { fractionInitiated = true; str += string[i]; } else if ( string[i] == '.' && fractionInitiated ) { result.append(str); str = "."; } else if ( string[i].isDigit() && fractionInitiated ) { str += string[i]; } else if ( (string[i].isLetter() || string[i].isDigit() || string[i] == '_') != (last.isLetter() || last.isDigit() || last == '_') ) { if ( !str.isNull() ) result.append(str); str = string[i]; fractionInitiated = false; } else { str += string[i]; } last = string[i]; } if ( !str.isNull() ) result.append(str); return result; } bool CommandExecutionEngine::doQuotesMatch(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) quote = string[i]; } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) quote = QChar(); } } return quote.isNull(); } bool CommandExecutionEngine::isEscaped(const QString& string, int indexToCheck, const QString& escapeSymbols) { int num = 0; int index = indexToCheck - 1; while ( index >= 0 && escapeSymbols.contains(string.at(index)) ) { --index; ++num; } return num % 2 == 1; } } <commit_msg>Show commands in menu only when interprettable.<commit_after>/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following ** disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ***********************************************************************************************************************/ #include "commands/Command.h" #include "commands/CommandExecutionEngine.h" #include "commands/CommandResult.h" #include "commands/CommandSuggestion.h" #include "handlers/GenericHandler.h" #include "InteractionBasePlugin.h" #include "VisualizationBase/src/items/Item.h" #include "VisualizationBase/src/items/SceneHandlerItem.h" #include "VisualizationBase/src/Scene.h" namespace Interaction { const char* QUOTE_SYMBOLS = "\"'`"; const char* ESCAPE_SYMBOLS = "\\"; CommandExecutionEngine::~CommandExecutionEngine() {} CommandExecutionEngine* CommandExecutionEngine::instance() { static CommandExecutionEngine engine; return &engine; } void CommandExecutionEngine::execute(Visualization::Item *originator, const QString& command, const std::unique_ptr<Visualization::Cursor>& cursor) { lastCommandResult_.clear(); QString trimmed = command.trimmed(); if ( !doQuotesMatch(command, QUOTE_SYMBOLS, ESCAPE_SYMBOLS) ) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("A quoted string expands past the end of the command."))); lastCommandResult_->errors().first()->addResolutionTip("Try inserting a matching quote."); return; } QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; QStringList tokens = tokenize(trimmed, QUOTE_SYMBOLS, ESCAPE_SYMBOLS); bool processed = false; while (target != nullptr && !processed) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); if (handler) { for (int i = 0; i< handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, target, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, target, tokens, cursor)); if (lastCommandResult_->code() != CommandResult::CanNotInterpret) { processed = true; break; } else lastCommandResult_.clear(); } } } if (!processed) target = target->parent(); } // If no item can process this command dispatch it to the SceneItem if (!processed && originator != originator->scene()->sceneHandlerItem()) { auto sceneHandlerItem = source->scene()->sceneHandlerItem(); auto handler = dynamic_cast<GenericHandler*> (sceneHandlerItem->handler()); if ( handler ) { for (int i = 0; i < handler->commands().size(); ++i) { if ( handler->commands().at(i)->canInterpret(source, sceneHandlerItem, tokens, cursor) ) { lastCommandResult_ = QSharedPointer<CommandResult>( handler->commands().at(i)->execute(source, sceneHandlerItem, tokens, cursor)); if ( lastCommandResult_->code() != CommandResult::CanNotInterpret ) { processed = true; break; } else lastCommandResult_.clear(); } } } } // If the command is still not processed this is an error if (!processed) { lastCommandResult_ = QSharedPointer<CommandResult>( new CommandResult(new CommandError("Unknown command '" + command + "' "))); log.warning("Unknown command: " + command); } } QList<CommandSuggestion*> CommandExecutionEngine::autoComplete(Visualization::Item *originator, const QString& textSoFar, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; QString trimmed = textSoFar.trimmed(); QString navigation = extractNavigationString(trimmed); // This is the node where we begin trying to process the command Visualization::Item* source = originator; // Alter the source node according to the requested navigation location. if (!navigation.isEmpty()) source = navigate(originator, navigation); // This is the node (source or one of its ancestors) where we manage to process the command. Visualization::Item* target = source; // This set keeps a list of commands that have already contributed some suggestions. If a command contributes // suggestions at a more specific context, then we ignore it in less specific contexts, even if it could // contribute more suggestions. The stored value is the hash code of a type_info structure QSet<std::size_t> alreadySuggested; // Get suggestion from item and parents while (target != nullptr) { GenericHandler* handler = dynamic_cast<GenericHandler*> (target->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor)); target = target->parent(); } // Get suggestions from the scene handler item if (originator != originator->scene()->sceneHandlerItem()) { GenericHandler* handler = dynamic_cast<GenericHandler*> (source->scene()->sceneHandlerItem()->handler()); result.append( suggestionsForHandler(handler, alreadySuggested, trimmed, source, target, cursor) ); } return result; } QList<CommandSuggestion*> CommandExecutionEngine::suggestionsForHandler(GenericHandler* handler, QSet<std::size_t>& alreadySuggested, QString trimmedCommandText, Visualization::Item* source, Visualization::Item* target, const std::unique_ptr<Visualization::Cursor>& cursor) { QList<CommandSuggestion*> result; if (handler) for (auto command : handler->commands()) { if (alreadySuggested.contains(typeid(*command).hash_code())) continue; QList<CommandSuggestion*> suggestions; //If it is a menu command, we must make sure it can be interpreted on the current item in its current state if (!trimmedCommandText.isEmpty() || (command->appearsInMenus() && command->canInterpret(source, target, QStringList(command->name()), cursor))) suggestions = command->suggest(source, target, trimmedCommandText, cursor); result.append( suggestions ); if (!suggestions.isEmpty()) alreadySuggested.insert(typeid(*command).hash_code()); } return result; } QString CommandExecutionEngine::extractNavigationString(QString& command) { // Extract navigation information if any QString trimmed = command.trimmed(); QString simplified = trimmed.simplified(); // Note that this will destroy any spacing within quotations. QString navigation; if ( simplified.startsWith("~ ") || simplified.startsWith(".. ") || simplified.startsWith(". ") || simplified.startsWith("../") || simplified.startsWith("./") || simplified.startsWith("/") ) { navigation = trimmed.left(simplified.indexOf(' ')); command = trimmed.mid(navigation.size()).trimmed(); } return navigation; } Visualization::Item* CommandExecutionEngine::navigate(Visualization::Item *originator, const QString&) { //TODO figure out what navigation we want and implement it. return originator; } QStringList CommandExecutionEngine::tokenize(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QStringList result; QString str; QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) { if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); quote = string[i]; str = quote; } else str.append(string[i]); } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) { result.append(str + quote); quote = QChar(); str = QString(); } } } if ( !str.isNull() ) result.append(tokenizeNonQuoted(str.simplified())); return result; } QStringList CommandExecutionEngine::tokenizeNonQuoted(const QString& string) { //TODO The concept of tokens here is unclear. Define this better. QStringList result; QString str; QChar last; bool fractionInitiated = false; for (int i = 0; i < string.size(); ++i) { if ( string[i] == ' ' ) { if ( !str.isNull() ) result.append(str); str = QString(); fractionInitiated = false; } else if ( string[i].isDigit() && fractionInitiated && last == '.' ) { str = result.last() + '.' + string[i]; result.removeLast(); fractionInitiated = false; } else if ( string[i].isDigit() && str.isNull() ) { fractionInitiated = true; str += string[i]; } else if ( string[i] == '.' && fractionInitiated ) { result.append(str); str = "."; } else if ( string[i].isDigit() && fractionInitiated ) { str += string[i]; } else if ( (string[i].isLetter() || string[i].isDigit() || string[i] == '_') != (last.isLetter() || last.isDigit() || last == '_') ) { if ( !str.isNull() ) result.append(str); str = string[i]; fractionInitiated = false; } else { str += string[i]; } last = string[i]; } if ( !str.isNull() ) result.append(str); return result; } bool CommandExecutionEngine::doQuotesMatch(const QString& string, const QString& quoteSymbols, const QString& escapeSymbols) { QChar quote; for (int i = 0; i < string.size(); ++i) { if ( quote.isNull() ) { if ( quoteSymbols.contains(string[i]) ) quote = string[i]; } else { if ( string[i] == quote && !isEscaped(string, i, escapeSymbols) ) quote = QChar(); } } return quote.isNull(); } bool CommandExecutionEngine::isEscaped(const QString& string, int indexToCheck, const QString& escapeSymbols) { int num = 0; int index = indexToCheck - 1; while ( index >= 0 && escapeSymbols.contains(string.at(index)) ) { --index; ++num; } return num % 2 == 1; } } <|endoftext|>
<commit_before>//============================================================================ // include/vsmc/utility/vector.hpp //---------------------------------------------------------------------------- // // vSMC: Scalable Monte Carlo // // This file is distribured under the 2-clauses BSD License. // See LICENSE for details. //============================================================================ #ifndef VSMC_UTILITY_AVECTOR_HPP #define VSMC_UTILITY_AVECTOR_HPP #include <vsmc/internal/common.hpp> #include <cstdlib> #include <cstring> #include <iterator> #include <utility> #define VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T) \ VSMC_STATIC_ASSERT((::vsmc::cxx11::is_arithmetic<T>::value), \ USE_AVector_WITH_A_TYPE_THAT_IS_NOT_ARITHMETIC) #define VSMC_RUNTIME_ASSERT_UTILITY_AVECTOR_RANGE(i, N) \ VSMC_RUNTIME_ASSERT((i < N), \ ("**AVector** USED WITH AN INDEX OUT OF RANGE")) #if defined(__APPLE__) || defined(__MACOSX) #if VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5) #ifndef VSMC_HAS_POSIX_MEMALIGN #define VSMC_HAS_POSIX_MEMALIGN 1 #endif #endif // VSMC_MAC_VERSION_MIN_REQUIRED(VSMC_MAC_10_5) #elif defined(__linux__) #include <features.h> #if defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L #ifndef VSMC_HAS_POSIX_MEMALIGN #define VSMC_HAS_POSIX_MEMALIGN 1 #endif #endif // defined(_POSIX_C_SOURCE) && _POSIX_C_SOURCE >= 200112L #if defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600 #ifndef VSMC_HAS_POSIX_MEMALIGN #define VSMC_HAS_POSIX_MEMALIGN 1 #endif #endif // defined(_XOPEN_SOURCE) && _XOPEN_SOURCE >= 600 #endif #ifndef VSMC_HAS_POSIX_MEMALIGN #define VSMC_HAS_POSIX_MEMALIGN 0 #endif namespace vsmc { namespace internal { #if VSMC_HAS_MKL #include <mkl_service.h> inline void *aligned_malloc (std::size_t n, std::size_t alignment) {return mkl_malloc(n, static_cast<int>(alignment));} inline void aligned_free (void *ptr) {mkl_free(ptr);} #elif VSMC_HAS_POSIX_MEMALIGN #include <stdlib.h> inline void *aligned_malloc (std::size_t n, std::size_t alignment) { void *ptr; if (posix_memalign(&ptr, alignment, n) != 0) throw std::bad_alloc(); return ptr; } inline void aligned_free (void *ptr) {free(ptr);} #elif defined(_WIN32) #include <malloc.h> inline void *aligned_malloc (std::size_t n, std::size_t alignment) {return _aligned_malloc(n, alignment);} inline void aligned_free (void *ptr) {_aligned_free(ptr);} #else #include <cstdlib> inline void *aligned_malloc (std::size_t n, std::size_t) {return std::malloc(n);} inline void aligned_free (void *ptr) {std::free(ptr);} #endif // VSMC_HAS_MKL } // namespace vsmc::internal /// \brief Dynamic vector /// \ingroup AVector /// /// \details /// This is similiar to `std::vector`, but only accepts arithmetic types. It /// does not have all the functionalities of the STL container. In particular, /// except `resize`, all methods that can change the size of the vector is not /// provided, such as `push_back`. template <typename T> class AVector { public : typedef T value_type; typedef std::size_t size_type; typedef std::ptrdiff_t difference_type; typedef value_type & reference; typedef const value_type & const_reference; typedef value_type * pointer; typedef const value_type * const_pointer; typedef pointer iterator; typedef const_pointer const_iterator; typedef std::reverse_iterator<iterator> reverse_iterator; typedef std::reverse_iterator<const_iterator> const_reverse_iterator; AVector () : size_(0), data_(VSMC_NULLPTR) {VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T);} explicit AVector (size_type count) : size_(0), data_(VSMC_NULLPTR) { VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T); resize(count); std::memset(data_, 0, sizeof(T) * size_); } AVector (size_type count, const value_type &value) : size_(0), data_(VSMC_NULLPTR) { VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T); resize(count); for (size_type i = 0; i != count; ++i) data_[i] = value; } template <typename InputIter> AVector (InputIter first, InputIter last, typename cxx11::enable_if<!( (cxx11::is_same<InputIter, size_type>::value || cxx11::is_convertible<InputIter, size_type>::value) && (cxx11::is_same<InputIter, value_type>::value || cxx11::is_convertible<InputIter, value_type>::value))>:: type * = VSMC_NULLPTR) : size_(0), data_(VSMC_NULLPTR) { VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T); using std::distance; size_type count = distance(first, last); resize(count); for (size_type i = 0; i != size_; ++i, ++first) data_[i] = *first; } AVector (const AVector<T> &other) : size_(0), data_(VSMC_NULLPTR) { VSMC_STATIC_ASSERT_UTILITY_AVECTOR_TYPE(T); resize(other.size_); copy(other.data_); } AVector<T> &operator= (const AVector<T> &other) { if (this != &other) { resize(other.size_); copy(other.data_); } return *this; } #if VSMC_HAS_CXX11_RVALUE_REFERENCES AVector (AVector<T> &&other) : size_(other.size_), data_(other.data_) { other.size_ = 0; other.data_ = VSMC_NULLPTR; } AVector<T> &operator= (AVector<T> &other) {swap(other); return *this;} #endif ~AVector () {if (data_ != VSMC_NULLPTR) deallocate();} reference at (size_type i) { VSMC_RUNTIME_ASSERT_UTILITY_AVECTOR_RANGE(i, size_); return data_[i]; } const_reference at (size_type i) const { VSMC_RUNTIME_ASSERT_UTILITY_AVECTOR_RANGE(i, size_); return data_[i]; } reference operator[] (size_type i) {return data_[i];} const_reference operator[] (size_type i) const {return data_[i];} reference front () {return data_[0];} const_reference front () const {return data_[0];} reference back () {return data_[size_ - 1];} const_reference back () const {return data_[size_ - 1];} pointer data () {return data_;} const_pointer data () const {return data_;} iterator begin () {return data_;} iterator end () {return data_ + size_;} const_iterator begin () const {return data_;} const_iterator end () const {return data_ + size_;} const_iterator cbegin () const {return data_;} const_iterator cend () const {return data_ + size_;} reverse_iterator rbegin () {return reverse_iterator(end());} reverse_iterator rend () {return reverse_iterator(begin());} const_reverse_iterator rbegin () const {return const_reverse_iterator(end());} const_reverse_iterator rend () const {return const_reverse_iterator(begin());} const_reverse_iterator crbegin () const {return const_reverse_iterator(cend());} const_reverse_iterator crend () const {return const_reverse_iterator(cbegin());} bool empty () const {return size_ == 0;} size_type size () const {return size_;} static VSMC_CONSTEXPR size_type max_size () {return static_cast<size_type>(~static_cast<size_type>(0)) / sizeof(T);} size_type capacity () const {return size_;} void resize (size_type new_size) { if (new_size == size_) return; pointer new_data = allocate(new_size); if (data_ != VSMC_NULLPTR) deallocate(); size_ = new_size; data_ = new_data; } void swap (AVector<T> &other) { using std::swap; if (this != &other) { swap(size_, other.size_); swap(data_, other.data_); } } friend inline bool operator== ( const AVector<T> &vec1, const AVector<T> &vec2) { if (vec1.size() != vec2.size()) return false; for (size_type i = 0; i != vec1.size(); ++i) if (vec1[i] != vec2[i]) return false; return true; } friend inline bool operator!= ( const AVector<T> &vec1, const AVector<T> &vec2) {return !(vec1 == vec2);} friend inline bool operator< ( const AVector<T> &vec1, const AVector<T> &vec2) { for (size_type i = 0; i != vec1.size() && i != vec2.size(); ++i) { if (vec1[i] < vec2[i]) return true; if (vec2[i] < vec1[i]) return false; } if (vec1.size() < vec2.size()) return true; return false; } friend inline bool operator> ( const AVector<T> &vec1, const AVector<T> &vec2) { for (size_type i = 0; i != vec1.size() && i != vec2.size(); ++i) { if (vec1[i] > vec2[i]) return true; if (vec2[i] > vec1[i]) return false; } if (vec1.size() > vec2.size()) return true; return false; } friend inline bool operator<= ( const AVector<T> &vec1, const AVector<T> &vec2) {return !(vec1 > vec2);} friend inline bool operator>= ( const AVector<T> &vec1, const AVector<T> &vec2) {return !(vec1 < vec2);} private : size_type size_; pointer data_; pointer allocate (size_type new_size) { return static_cast<pointer>(internal::aligned_malloc( sizeof(T) * new_size, 32)); } void deallocate () {internal::aligned_free(data_);} void copy (const_pointer new_data) { if (data_ + size_ < new_data || new_data + size_ < data_) std::memcpy(data_, new_data, sizeof(T) * size_); else std::memmove(data_, new_data, sizeof(T) * size_); } }; // class AVector template <typename T> inline void swap (AVector<T> &vec1, AVector<T> &vec2) {vec1.swap(vec2);} } // namespace vsmc #endif // VSMC_UTILITY_AVECTOR_HPP <commit_msg>revert last commit; it is too highly experimental<commit_after><|endoftext|>
<commit_before>/** * @file _refcounted.cpp * @brief Atomic, thread-safe ref counting and destruction mixin class * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "_refcounted.h" namespace LLCoreInt { RefCounted::~RefCounted() {} } // end namespace LLCoreInt <commit_msg>Really need to figure out the 'static const' problem on Windows. For now, workaround...<commit_after>/** * @file _refcounted.cpp * @brief Atomic, thread-safe ref counting and destruction mixin class * * $LicenseInfo:firstyear=2012&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2012, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "_refcounted.h" namespace LLCoreInt { #if ! defined(WIN32) const S32 RefCounted::NOT_REF_COUNTED; #endif // ! defined(WIN32) RefCounted::~RefCounted() {} } // end namespace LLCoreInt <|endoftext|>
<commit_before>inline opt_feat::opt_feat(const std::string in_path, const std::string in_actionNames, const int in_col, const int in_row, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ) :path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim) { actions.load( actionNames ); //dim = 14; //dim = 12; //Action Recognition from Video Using feature Covariance Matrices } inline void opt_feat::features_all_videos( field<string> all_people ) { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); field <std::string> load_save_names (n_peo*n_actions,3); int sc = total_scene; //Solo estoy usando 1 int k =0; for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream ss_video_name; ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi"; std::stringstream save_folder; std::stringstream save_feat_video_i; std::stringstream save_labels_video_i; save_folder << "./kth-features_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; save_feat_video_i << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_save_names(k,0) = ss_video_name.str(); load_save_names(k,1) = save_feat_video_i.str(); load_save_names(k,2) = save_labels_video_i.str(); k++; } } //int nProcessors=omp_get_max_threads(); //std::cout<<nProcessors<<std::endl; omp_set_num_threads(10); //Use only 10 processors //std::cout<< omp_get_num_threads()<<std::endl; #pragma omp parallel for for (int i = 0; i<load_save_names.n_rows; ++i) { std::string one_video = load_save_names(i,0); int tid=omp_get_thread_num(); #pragma omp critical cout<< "Processor " << tid <<" doing "<< one_video << endl; Struct_feat_lab my_Struct_feat_lab; feature_video( one_video, my_Struct_feat_lab ); mat mat_features_video_i; vec lab_video_i; if (my_Struct_feat_lab.features_video_i.size()>0) { mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() ); lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() ); for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i) { mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2); lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i); } } else { mat_features_video_i.zeros(dim,0); } std::string save_feat_video_i = load_save_names(i,1); std::string save_labels_video_i = load_save_names(i,2); mat_features_video_i.save( save_feat_video_i, hdf5_binary ); lab_video_i.save( save_labels_video_i, hdf5_binary ); } } // //****************** Feature Extraction************************************** // //*************************************************************************** inline void opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab ) { my_Struct_feat_lab.features_video_i.clear(); my_Struct_feat_lab.labels_video_i.clear(); int new_row = row; int new_col = col; cv::VideoCapture capVideo(one_video); int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT); if( !capVideo.isOpened() ) { cout << "Video couldn't be opened" << endl; return; } cv::Mat prevgray, gray, flow, cflow, frame, prevflow; cv::Mat ixMat, iyMat, ixxMat, iyyMat; cv::Mat flow_xy[2], mag, ang; string text; for(int fr=0; fr<n_frames; fr++){ //cout << fr << " " ; bool bSuccess = capVideo.read(frame); // read a new frame from video if (!bSuccess) //if not success, break loop { cout << "Cannot read the frame from video file" << endl; break; } if (scale_factor!=1) { new_row = row*scale_factor; new_col = col*scale_factor; cv::resize( frame, frame, cv::Size(new_row, new_col) ); } cv::cvtColor(frame, gray, CV_BGR2GRAY); if( prevgray.data ) { //cout << t << " " ; cv::calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, //pyr_scale 3, //levels 9, //winsize 1, //iterations 5, //poly_n 1.1, //poly_sigma 0); //flags //optical flow cv::split(flow, flow_xy); cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true); cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1); cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1); cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1); cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1); float ux = 0, uy = 0, vx = 0, vy = 0; float u, v; if( prevflow.data ) { //cout << new_col << " " << new_row << endl; for (int x = 0 ; x < new_col ; ++x ){ for (int y = 0 ; y < new_row ; ++y ) { vec features_one_pixel(dim); u = flow.at<cv::Vec2f>(y, x)[0]; v = flow.at<cv::Vec2f>(y, x)[1]; //cout << "x= " << x << " - y= " << y << endl; // x grad //cout << " x y grad" << endl; float ix = ixMat.at<float>(y, x); //cout << " y grad" << endl; float iy = iyMat.at<float>(y, x); // grad direction & grad magnitude. (Edges) //cout << "grad direction & grad magnitude" << endl; float gd = std::atan2(std::abs(iy), std::abs(ix)); float gm = std::sqrt(ix * ix + iy * iy); // x second grad //cout << "x y second grad " << endl; float ixx = ixxMat.at<float>(y, x); // y second grad float iyy = iyyMat.at<float>(y, x); //du/dt float ut = u - prevflow.at<cv::Vec2f>(y, x)[0]; // dv/dt float vt = v - prevflow.at<cv::Vec2f>(y, x)[1]; if (x>0 && y>0 ) { ux = u - flow.at<cv::Vec2f>(y, x - 1)[0]; uy = u - flow.at<cv::Vec2f>(y - 1, x)[0]; vx = v - flow.at<cv::Vec2f>(y, x - 1)[1]; vy = v - flow.at<cv::Vec2f>(y - 1, x)[1]; } float Div = (ux + vy); float Vor = (vx - uy); //Adding more features mat G (2,2); mat S; float gd_opflow = ang.at<float>(y,x); float mg_opflow = mag.at<float>(y,x); //Gradient Tensor G << ux << uy << endr << vx << vy << endr; //Rate of Stein Tensor S = 0.5*(G + G.t()); float tr_G = trace(G); float tr_G2 = trace( square(G) ); float tr_S = trace(S); float tr_S2 = trace(square(S)); //Tensor Invariants of the optical flow float Gten = 0.5*( tr_G*tr_G - tr_G2 ); float Sten = 0.5*( tr_S*tr_S - tr_S2 ); if (dim ==12) { features_one_pixel << x << y << fr << gm << u << v << abs(ut) << abs(vt) << Div << Vor << Gten << Sten; } if (dim ==14) { features_one_pixel << x << y << abs(ix) << abs(iy) << abs(ixx) << abs(iyy) << gm << gd << u << v << abs(ut) << abs(vt) << (ux + vy) << (vx - uy); } if (!is_finite( features_one_pixel ) ) { cout << "It's not FINITE... continue???" << endl; getchar(); } // Plotting Moving pixels //cout << " " << gm; double is_zero = accu(abs(features_one_pixel)); if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40 { frame.at<cv::Vec3b>(y,x)[0] = 0; frame.at<cv::Vec3b>(y,x)[1] = 0; frame.at<cv::Vec3b>(y,x)[2] = 255; my_Struct_feat_lab.features_video_i.push_back(features_one_pixel); my_Struct_feat_lab.labels_video_i.push_back( fr ); } } } } if(cv::waitKey(30)>=0) break; } std::swap(prevgray, gray); std::swap(prevflow, flow); //cv::imshow("color", frame); //cv::waitKey(1); } }<commit_msg>Re-calculate for dim=14 features with OpenMP<commit_after>inline opt_feat::opt_feat(const std::string in_path, const std::string in_actionNames, const int in_col, const int in_row, const int in_scale_factor, const int in_shift, const int in_scene, //only for kth const int in_dim ) :path(in_path), actionNames(in_actionNames), col(in_col), row(in_row), scale_factor(in_scale_factor), shift(in_shift), total_scene(in_scene), dim(in_dim) { actions.load( actionNames ); //dim = 14; //dim = 12; //Action Recognition from Video Using feature Covariance Matrices } inline void opt_feat::features_all_videos( field<string> all_people ) { int n_actions = actions.n_rows; int n_peo = all_people.n_rows; //all_people.print("people"); field <std::string> load_save_names (n_peo*n_actions,3); int sc = total_scene; //Solo estoy usando 1 int k =0; for (int pe = 0; pe< n_peo; ++pe) { for (int act=0; act<n_actions; ++act) { std::stringstream ss_video_name; ss_video_name << path << actions (act) << "/" << all_people (pe) << "_" << actions (act) << "_d" << sc << "_uncomp.avi"; std::stringstream save_folder; std::stringstream save_feat_video_i; std::stringstream save_labels_video_i; save_folder << "./kth-features_dim" << dim << "/sc" << sc << "/scale" << scale_factor << "-shift"<< shift ; save_feat_video_i << save_folder.str() << "/" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; save_labels_video_i << save_folder.str() << "/lab_" << all_people (pe) << "_" << actions(act) << "_dim" << dim << ".h5"; load_save_names(k,0) = ss_video_name.str(); load_save_names(k,1) = save_feat_video_i.str(); load_save_names(k,2) = save_labels_video_i.str(); k++; } } //int nProcessors=omp_get_max_threads(); //std::cout<<nProcessors<<std::endl; //omp_set_num_threads(10); //Use only 10 processors //std::cout<< omp_get_num_threads()<<std::endl; wall_clock timer; timer.tic(); //#pragma omp parallel for for (int i = 0; i<load_save_names.n_rows; ++i) { std::string one_video = load_save_names(i,0); int tid=omp_get_thread_num(); // #pragma omp critical cout<< "Processor " << tid <<" doing "<< one_video << endl; Struct_feat_lab my_Struct_feat_lab; feature_video( one_video, my_Struct_feat_lab ); mat mat_features_video_i; vec lab_video_i; if (my_Struct_feat_lab.features_video_i.size()>0) { mat_features_video_i.zeros( dim,my_Struct_feat_lab.features_video_i.size() ); lab_video_i.zeros( my_Struct_feat_lab.features_video_i.size() ); for (uword i = 0; i < my_Struct_feat_lab.features_video_i.size(); ++i) { mat_features_video_i.col(i) = my_Struct_feat_lab.features_video_i.at(i)/norm(my_Struct_feat_lab.features_video_i.at(i),2); lab_video_i(i) = my_Struct_feat_lab.labels_video_i.at(i); } } else { mat_features_video_i.zeros(dim,0); } std::string save_feat_video_i = load_save_names(i,1); std::string save_labels_video_i = load_save_names(i,2); mat_features_video_i.save( save_feat_video_i, hdf5_binary ); lab_video_i.save( save_labels_video_i, hdf5_binary ); } cout << "number of seconds NO parallel : " << n << endl; } // //****************** Feature Extraction************************************** // //*************************************************************************** inline void opt_feat::feature_video( std::string one_video, Struct_feat_lab &my_Struct_feat_lab ) { my_Struct_feat_lab.features_video_i.clear(); my_Struct_feat_lab.labels_video_i.clear(); int new_row = row; int new_col = col; cv::VideoCapture capVideo(one_video); int n_frames = capVideo.get(CV_CAP_PROP_FRAME_COUNT); if( !capVideo.isOpened() ) { cout << "Video couldn't be opened" << endl; return; } cv::Mat prevgray, gray, flow, cflow, frame, prevflow; cv::Mat ixMat, iyMat, ixxMat, iyyMat; cv::Mat flow_xy[2], mag, ang; string text; for(int fr=0; fr<n_frames; fr++){ //cout << fr << " " ; bool bSuccess = capVideo.read(frame); // read a new frame from video if (!bSuccess) //if not success, break loop { cout << "Cannot read the frame from video file" << endl; break; } if (scale_factor!=1) { new_row = row*scale_factor; new_col = col*scale_factor; cv::resize( frame, frame, cv::Size(new_row, new_col) ); } cv::cvtColor(frame, gray, CV_BGR2GRAY); if( prevgray.data ) { //cout << t << " " ; cv::calcOpticalFlowFarneback(prevgray, gray, flow, 0.5, //pyr_scale 3, //levels 9, //winsize 1, //iterations 5, //poly_n 1.1, //poly_sigma 0); //flags //optical flow cv::split(flow, flow_xy); cv::cartToPolar(flow_xy[0], flow_xy[1], mag, ang, true); cv::Sobel(gray, ixMat, CV_32F, 1, 0, 1); cv::Sobel(gray, iyMat, CV_32F, 0, 1, 1); cv::Sobel(gray, ixxMat, CV_32F, 2, 0, 1); cv::Sobel(gray, iyyMat, CV_32F, 0, 2, 1); float ux = 0, uy = 0, vx = 0, vy = 0; float u, v; if( prevflow.data ) { //cout << new_col << " " << new_row << endl; for (int x = 0 ; x < new_col ; ++x ){ for (int y = 0 ; y < new_row ; ++y ) { vec features_one_pixel(dim); u = flow.at<cv::Vec2f>(y, x)[0]; v = flow.at<cv::Vec2f>(y, x)[1]; //cout << "x= " << x << " - y= " << y << endl; // x grad //cout << " x y grad" << endl; float ix = ixMat.at<float>(y, x); //cout << " y grad" << endl; float iy = iyMat.at<float>(y, x); // grad direction & grad magnitude. (Edges) //cout << "grad direction & grad magnitude" << endl; float gd = std::atan2(std::abs(iy), std::abs(ix)); float gm = std::sqrt(ix * ix + iy * iy); // x second grad //cout << "x y second grad " << endl; float ixx = ixxMat.at<float>(y, x); // y second grad float iyy = iyyMat.at<float>(y, x); //du/dt float ut = u - prevflow.at<cv::Vec2f>(y, x)[0]; // dv/dt float vt = v - prevflow.at<cv::Vec2f>(y, x)[1]; if (x>0 && y>0 ) { ux = u - flow.at<cv::Vec2f>(y, x - 1)[0]; uy = u - flow.at<cv::Vec2f>(y - 1, x)[0]; vx = v - flow.at<cv::Vec2f>(y, x - 1)[1]; vy = v - flow.at<cv::Vec2f>(y - 1, x)[1]; } float Div = (ux + vy); float Vor = (vx - uy); //Adding more features mat G (2,2); mat S; float gd_opflow = ang.at<float>(y,x); float mg_opflow = mag.at<float>(y,x); //Gradient Tensor G << ux << uy << endr << vx << vy << endr; //Rate of Stein Tensor S = 0.5*(G + G.t()); float tr_G = trace(G); float tr_G2 = trace( square(G) ); float tr_S = trace(S); float tr_S2 = trace(square(S)); //Tensor Invariants of the optical flow float Gten = 0.5*( tr_G*tr_G - tr_G2 ); float Sten = 0.5*( tr_S*tr_S - tr_S2 ); if (dim ==12) { features_one_pixel << x << y << fr << gm << u << v << abs(ut) << abs(vt) << Div << Vor << Gten << Sten; } if (dim ==14) { features_one_pixel << x << y << abs(ix) << abs(iy) << abs(ixx) << abs(iyy) << gm << gd << u << v << abs(ut) << abs(vt) << (ux + vy) << (vx - uy); } if (!is_finite( features_one_pixel ) ) { cout << "It's not FINITE... continue???" << endl; getchar(); } // Plotting Moving pixels //cout << " " << gm; double is_zero = accu(abs(features_one_pixel)); if (gm>40 && is_finite( features_one_pixel ) && is_zero!=0 ) // Empirically set to 40 { frame.at<cv::Vec3b>(y,x)[0] = 0; frame.at<cv::Vec3b>(y,x)[1] = 0; frame.at<cv::Vec3b>(y,x)[2] = 255; my_Struct_feat_lab.features_video_i.push_back(features_one_pixel); my_Struct_feat_lab.labels_video_i.push_back( fr ); } } } } if(cv::waitKey(30)>=0) break; } std::swap(prevgray, gray); std::swap(prevflow, flow); //cv::imshow("color", frame); //cv::waitKey(1); } }<|endoftext|>
<commit_before>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. // @author Vegard Sjonfjell #include <vespa/storage/persistence/fieldvisitor.h> #include <vespa/storage/persistence/testandsethelper.h> #include <vespa/document/select/parser.h> #include <vespa/document/repo/documenttyperepo.h> #include <vespa/vespalib/util/stringfmt.h> using namespace std::string_literals; namespace storage { void TestAndSetHelper::getDocumentType() { if (!_docId.hasDocType()) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Document id has no doctype")); } _docTypePtr = _component.getTypeRepo()->getDocumentType(_docId.getDocType()); if (_docTypePtr == nullptr) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Document type does not exist")); } } void TestAndSetHelper::parseDocumentSelection() { document::select::Parser parser(*_component.getTypeRepo(), _component.getBucketIdFactory()); try { _docSelectionUp = parser.parse(_cmd.getCondition().getSelection()); } catch (const document::select::ParsingFailedException & e) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Failed to parse test and set condition: "s + e.getMessage())); } } spi::GetResult TestAndSetHelper::retrieveDocument(const document::FieldSet & fieldSet, spi::Context & context) { return _thread._spi.get( _thread.getBucket(_docId, _cmd.getBucket()), fieldSet, _cmd.getDocumentId(), context); } TestAndSetHelper::TestAndSetHelper(PersistenceThread & thread, const api::TestAndSetCommand & cmd, bool missingDocumentImpliesMatch) : _thread(thread), _component(thread._env._component), _cmd(cmd), _docId(cmd.getDocumentId()), _docTypePtr(nullptr), _missingDocumentImpliesMatch(missingDocumentImpliesMatch) { getDocumentType(); parseDocumentSelection(); } TestAndSetHelper::~TestAndSetHelper() = default; api::ReturnCode TestAndSetHelper::retrieveAndMatch(spi::Context & context) { // Walk document selection tree to build a minimal field set FieldVisitor fieldVisitor(*_docTypePtr); _docSelectionUp->visit(fieldVisitor); // Retrieve document auto result = retrieveDocument(fieldVisitor.getFieldSet(), context); // If document exists, match it with selection if (result.hasDocument()) { auto docPtr = result.getDocumentPtr(); if (_docSelectionUp->contains(*docPtr) != document::select::Result::True) { return api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED, vespalib::make_string("Condition did not match document partition=%d, nodeIndex=%d bucket=%lx %s", _thread._env._partition, _thread._env._nodeIndex, _cmd.getBucketId().getRawId(), _cmd.hasBeenRemapped() ? "remapped" : "")); } // Document matches return api::ReturnCode(); } else if (_missingDocumentImpliesMatch) { return api::ReturnCode(); } return api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED, vespalib::make_string("Document does not exist partition=%d, nodeIndex=%d bucket=%lx %s", _thread._env._partition, _thread._env._nodeIndex, _cmd.getBucketId().getRawId(), _cmd.hasBeenRemapped() ? "remapped" : "")); } } // storage <commit_msg>Use PRIx64 macro to specify that type of variable to be printed is uint64_t.<commit_after>// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. // @author Vegard Sjonfjell #include <vespa/storage/persistence/fieldvisitor.h> #include <vespa/storage/persistence/testandsethelper.h> #include <vespa/document/select/parser.h> #include <vespa/document/repo/documenttyperepo.h> #include <vespa/vespalib/util/stringfmt.h> using namespace std::string_literals; namespace storage { void TestAndSetHelper::getDocumentType() { if (!_docId.hasDocType()) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Document id has no doctype")); } _docTypePtr = _component.getTypeRepo()->getDocumentType(_docId.getDocType()); if (_docTypePtr == nullptr) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Document type does not exist")); } } void TestAndSetHelper::parseDocumentSelection() { document::select::Parser parser(*_component.getTypeRepo(), _component.getBucketIdFactory()); try { _docSelectionUp = parser.parse(_cmd.getCondition().getSelection()); } catch (const document::select::ParsingFailedException & e) { throw TestAndSetException(api::ReturnCode(api::ReturnCode::ILLEGAL_PARAMETERS, "Failed to parse test and set condition: "s + e.getMessage())); } } spi::GetResult TestAndSetHelper::retrieveDocument(const document::FieldSet & fieldSet, spi::Context & context) { return _thread._spi.get( _thread.getBucket(_docId, _cmd.getBucket()), fieldSet, _cmd.getDocumentId(), context); } TestAndSetHelper::TestAndSetHelper(PersistenceThread & thread, const api::TestAndSetCommand & cmd, bool missingDocumentImpliesMatch) : _thread(thread), _component(thread._env._component), _cmd(cmd), _docId(cmd.getDocumentId()), _docTypePtr(nullptr), _missingDocumentImpliesMatch(missingDocumentImpliesMatch) { getDocumentType(); parseDocumentSelection(); } TestAndSetHelper::~TestAndSetHelper() = default; api::ReturnCode TestAndSetHelper::retrieveAndMatch(spi::Context & context) { // Walk document selection tree to build a minimal field set FieldVisitor fieldVisitor(*_docTypePtr); _docSelectionUp->visit(fieldVisitor); // Retrieve document auto result = retrieveDocument(fieldVisitor.getFieldSet(), context); // If document exists, match it with selection if (result.hasDocument()) { auto docPtr = result.getDocumentPtr(); if (_docSelectionUp->contains(*docPtr) != document::select::Result::True) { return api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED, vespalib::make_string("Condition did not match document partition=%d, nodeIndex=%d bucket=%" PRIx64 " %s", _thread._env._partition, _thread._env._nodeIndex, _cmd.getBucketId().getRawId(), _cmd.hasBeenRemapped() ? "remapped" : "")); } // Document matches return api::ReturnCode(); } else if (_missingDocumentImpliesMatch) { return api::ReturnCode(); } return api::ReturnCode(api::ReturnCode::TEST_AND_SET_CONDITION_FAILED, vespalib::make_string("Document does not exist partition=%d, nodeIndex=%d bucket=%" PRIx64 " %s", _thread._env._partition, _thread._env._nodeIndex, _cmd.getBucketId().getRawId(), _cmd.hasBeenRemapped() ? "remapped" : "")); } } // storage <|endoftext|>
<commit_before>/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/portability/Time.h> #include <folly/Likely.h> #include <assert.h> #include <chrono> template <typename _Rep, typename _Period> static void duration_to_ts( std::chrono::duration<_Rep, _Period> d, struct timespec* ts) { ts->tv_sec = time_t(std::chrono::duration_cast<std::chrono::seconds>(d).count()); ts->tv_nsec = long(std::chrono::duration_cast<std::chrono::nanoseconds>( d % std::chrono::seconds(1)) .count()); } #if !FOLLY_HAVE_CLOCK_GETTIME || FOLLY_FORCE_CLOCK_GETTIME_DEFINITION #if __MACH__ #include <errno.h> #include <mach/mach_init.h> // @manual #include <mach/mach_port.h> // @manual #include <mach/mach_time.h> // @manual #include <mach/mach_types.h> // @manual #include <mach/task.h> // @manual #include <mach/thread_act.h> // @manual #include <mach/vm_map.h> // @manual static std::chrono::nanoseconds time_value_to_ns(time_value_t t) { return std::chrono::seconds(t.seconds) + std::chrono::microseconds(t.microseconds); } static int clock_process_cputime(struct timespec* ts) { // Get CPU usage for live threads. task_thread_times_info thread_times_info; mach_msg_type_number_t thread_times_info_count = TASK_THREAD_TIMES_INFO_COUNT; kern_return_t kern_result = task_info( mach_task_self(), TASK_THREAD_TIMES_INFO, (thread_info_t)&thread_times_info, &thread_times_info_count); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } // Get CPU usage for terminated threads. mach_task_basic_info task_basic_info; mach_msg_type_number_t task_basic_info_count = MACH_TASK_BASIC_INFO_COUNT; kern_result = task_info( mach_task_self(), MACH_TASK_BASIC_INFO, (thread_info_t)&task_basic_info, &task_basic_info_count); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } auto cputime = time_value_to_ns(thread_times_info.user_time) + time_value_to_ns(thread_times_info.system_time) + time_value_to_ns(task_basic_info.user_time) + time_value_to_ns(task_basic_info.system_time); duration_to_ts(cputime, ts); return 0; } static int clock_thread_cputime(struct timespec* ts) { mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; thread_basic_info_data_t thread_info_data; thread_act_t thread = mach_thread_self(); kern_return_t kern_result = thread_info( thread, THREAD_BASIC_INFO, (thread_info_t)&thread_info_data, &count); mach_port_deallocate(mach_task_self(), thread); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } auto cputime = time_value_to_ns(thread_info_data.system_time) + time_value_to_ns(thread_info_data.user_time); duration_to_ts(cputime, ts); return 0; } __attribute__((weak)) int clock_gettime(clockid_t clk_id, struct timespec* ts) { switch (clk_id) { case CLOCK_REALTIME: { auto now = std::chrono::system_clock::now().time_since_epoch(); duration_to_ts(now, ts); return 0; } case CLOCK_MONOTONIC: { auto now = std::chrono::steady_clock::now().time_since_epoch(); duration_to_ts(now, ts); return 0; } case CLOCK_PROCESS_CPUTIME_ID: return clock_process_cputime(ts); case CLOCK_THREAD_CPUTIME_ID: return clock_thread_cputime(ts); default: errno = EINVAL; return -1; } } int clock_getres(clockid_t clk_id, struct timespec* ts) { if (clk_id != CLOCK_MONOTONIC) { return -1; } static auto info = [] { static mach_timebase_info_data_t info; auto result = (mach_timebase_info(&info) == KERN_SUCCESS) ? &info : nullptr; assert(result); return result; }(); ts->tv_sec = 0; ts->tv_nsec = info->numer / info->denom; return 0; } #elif defined(_WIN32) #include <errno.h> #include <locale.h> #include <stdint.h> #include <stdlib.h> #include <folly/portability/Windows.h> using unsigned_nanos = std::chrono::duration<uint64_t, std::nano>; static unsigned_nanos filetimeToUnsignedNanos(FILETIME ft) { ULARGE_INTEGER i; i.HighPart = ft.dwHighDateTime; i.LowPart = ft.dwLowDateTime; // FILETIMEs are in units of 100ns. return unsigned_nanos(i.QuadPart * 100); }; static LARGE_INTEGER performanceFrequency() { static auto result = [] { LARGE_INTEGER freq; // On Windows XP or later, this will never fail. BOOL res = QueryPerformanceFrequency(&freq); assert(res); return freq; }(); return result; } extern "C" int clock_getres(clockid_t clock_id, struct timespec* res) { if (!res) { errno = EFAULT; return -1; } static constexpr size_t kNsPerSec = 1000000000; switch (clock_id) { case CLOCK_REALTIME: { constexpr auto perSec = double(std::chrono::system_clock::period::num) / std::chrono::system_clock::period::den; res->tv_sec = time_t(perSec); res->tv_nsec = time_t(perSec * kNsPerSec); return 0; } case CLOCK_MONOTONIC: { constexpr auto perSec = double(std::chrono::steady_clock::period::num) / std::chrono::steady_clock::period::den; res->tv_sec = time_t(perSec); res->tv_nsec = time_t(perSec * kNsPerSec); return 0; } case CLOCK_PROCESS_CPUTIME_ID: case CLOCK_THREAD_CPUTIME_ID: { DWORD adj, timeIncrement; BOOL adjDisabled; if (!GetSystemTimeAdjustment(&adj, &timeIncrement, &adjDisabled)) { errno = EINVAL; return -1; } res->tv_sec = 0; res->tv_nsec = long(timeIncrement * 100); return 0; } default: errno = EINVAL; return -1; } } extern "C" int clock_gettime(clockid_t clock_id, struct timespec* tp) { if (!tp) { errno = EFAULT; return -1; } const auto unanosToTimespec = [](timespec* tp, unsigned_nanos t) -> int { static constexpr unsigned_nanos one_sec{std::chrono::seconds(1)}; tp->tv_sec = time_t(std::chrono::duration_cast<std::chrono::seconds>(t).count()); tp->tv_nsec = long((t % one_sec).count()); return 0; }; FILETIME createTime, exitTime, kernalTime, userTime; switch (clock_id) { case CLOCK_REALTIME: { auto now = std::chrono::system_clock::now().time_since_epoch(); duration_to_ts(now, tp); return 0; } case CLOCK_MONOTONIC: { auto now = std::chrono::steady_clock::now().time_since_epoch(); duration_to_ts(now, tp); return 0; } case CLOCK_PROCESS_CPUTIME_ID: { if (!GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernalTime, &userTime)) { errno = EINVAL; return -1; } return unanosToTimespec( tp, filetimeToUnsignedNanos(kernalTime) + filetimeToUnsignedNanos(userTime)); } case CLOCK_THREAD_CPUTIME_ID: { if (!GetThreadTimes( GetCurrentThread(), &createTime, &exitTime, &kernalTime, &userTime)) { errno = EINVAL; return -1; } return unanosToTimespec( tp, filetimeToUnsignedNanos(kernalTime) + filetimeToUnsignedNanos(userTime)); } default: errno = EINVAL; return -1; } } #else #error No clock_gettime(3) compatibility wrapper available for this platform. #endif #endif #ifdef _WIN32 #include <iomanip> #include <sstream> #include <folly/portability/Windows.h> extern "C" { char* asctime_r(const tm* tm, char* buf) { char tmpBuf[64]; if (asctime_s(tmpBuf, tm)) { return nullptr; } // Nothing we can do if the buff is to small :( return strcpy(buf, tmpBuf); } char* ctime_r(const time_t* t, char* buf) { char tmpBuf[64]; if (ctime_s(tmpBuf, 64, t)) { return nullptr; } // Nothing we can do if the buff is to small :( return strcpy(buf, tmpBuf); } tm* gmtime_r(const time_t* t, tm* res) { if (!gmtime_s(res, t)) { return res; } return nullptr; } tm* localtime_r(const time_t* t, tm* o) { if (!localtime_s(o, t)) { return o; } return nullptr; } int nanosleep(const struct timespec* request, struct timespec* remain) { Sleep((DWORD)((request->tv_sec * 1000) + (request->tv_nsec / 1000000))); if (remain != nullptr) { remain->tv_nsec = 0; remain->tv_sec = 0; } return 0; } char* strptime( const char* __restrict s, const char* __restrict f, struct tm* __restrict tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return const_cast<char*>(s + input.tellg()); } } #endif <commit_msg>Prefer FOLLY_ATTR_WEAK over __attribute__((__weak__))<commit_after>/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/portability/Time.h> #include <folly/CPortability.h> #include <folly/Likely.h> #include <assert.h> #include <chrono> template <typename _Rep, typename _Period> static void duration_to_ts( std::chrono::duration<_Rep, _Period> d, struct timespec* ts) { ts->tv_sec = time_t(std::chrono::duration_cast<std::chrono::seconds>(d).count()); ts->tv_nsec = long(std::chrono::duration_cast<std::chrono::nanoseconds>( d % std::chrono::seconds(1)) .count()); } #if !FOLLY_HAVE_CLOCK_GETTIME || FOLLY_FORCE_CLOCK_GETTIME_DEFINITION #if __MACH__ #include <errno.h> #include <mach/mach_init.h> // @manual #include <mach/mach_port.h> // @manual #include <mach/mach_time.h> // @manual #include <mach/mach_types.h> // @manual #include <mach/task.h> // @manual #include <mach/thread_act.h> // @manual #include <mach/vm_map.h> // @manual static std::chrono::nanoseconds time_value_to_ns(time_value_t t) { return std::chrono::seconds(t.seconds) + std::chrono::microseconds(t.microseconds); } static int clock_process_cputime(struct timespec* ts) { // Get CPU usage for live threads. task_thread_times_info thread_times_info; mach_msg_type_number_t thread_times_info_count = TASK_THREAD_TIMES_INFO_COUNT; kern_return_t kern_result = task_info( mach_task_self(), TASK_THREAD_TIMES_INFO, (thread_info_t)&thread_times_info, &thread_times_info_count); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } // Get CPU usage for terminated threads. mach_task_basic_info task_basic_info; mach_msg_type_number_t task_basic_info_count = MACH_TASK_BASIC_INFO_COUNT; kern_result = task_info( mach_task_self(), MACH_TASK_BASIC_INFO, (thread_info_t)&task_basic_info, &task_basic_info_count); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } auto cputime = time_value_to_ns(thread_times_info.user_time) + time_value_to_ns(thread_times_info.system_time) + time_value_to_ns(task_basic_info.user_time) + time_value_to_ns(task_basic_info.system_time); duration_to_ts(cputime, ts); return 0; } static int clock_thread_cputime(struct timespec* ts) { mach_msg_type_number_t count = THREAD_BASIC_INFO_COUNT; thread_basic_info_data_t thread_info_data; thread_act_t thread = mach_thread_self(); kern_return_t kern_result = thread_info( thread, THREAD_BASIC_INFO, (thread_info_t)&thread_info_data, &count); mach_port_deallocate(mach_task_self(), thread); if (UNLIKELY(kern_result != KERN_SUCCESS)) { return -1; } auto cputime = time_value_to_ns(thread_info_data.system_time) + time_value_to_ns(thread_info_data.user_time); duration_to_ts(cputime, ts); return 0; } FOLLY_ATTR_WEAK int clock_gettime(clockid_t clk_id, struct timespec* ts) { switch (clk_id) { case CLOCK_REALTIME: { auto now = std::chrono::system_clock::now().time_since_epoch(); duration_to_ts(now, ts); return 0; } case CLOCK_MONOTONIC: { auto now = std::chrono::steady_clock::now().time_since_epoch(); duration_to_ts(now, ts); return 0; } case CLOCK_PROCESS_CPUTIME_ID: return clock_process_cputime(ts); case CLOCK_THREAD_CPUTIME_ID: return clock_thread_cputime(ts); default: errno = EINVAL; return -1; } } int clock_getres(clockid_t clk_id, struct timespec* ts) { if (clk_id != CLOCK_MONOTONIC) { return -1; } static auto info = [] { static mach_timebase_info_data_t info; auto result = (mach_timebase_info(&info) == KERN_SUCCESS) ? &info : nullptr; assert(result); return result; }(); ts->tv_sec = 0; ts->tv_nsec = info->numer / info->denom; return 0; } #elif defined(_WIN32) #include <errno.h> #include <locale.h> #include <stdint.h> #include <stdlib.h> #include <folly/portability/Windows.h> using unsigned_nanos = std::chrono::duration<uint64_t, std::nano>; static unsigned_nanos filetimeToUnsignedNanos(FILETIME ft) { ULARGE_INTEGER i; i.HighPart = ft.dwHighDateTime; i.LowPart = ft.dwLowDateTime; // FILETIMEs are in units of 100ns. return unsigned_nanos(i.QuadPart * 100); }; static LARGE_INTEGER performanceFrequency() { static auto result = [] { LARGE_INTEGER freq; // On Windows XP or later, this will never fail. BOOL res = QueryPerformanceFrequency(&freq); assert(res); return freq; }(); return result; } extern "C" int clock_getres(clockid_t clock_id, struct timespec* res) { if (!res) { errno = EFAULT; return -1; } static constexpr size_t kNsPerSec = 1000000000; switch (clock_id) { case CLOCK_REALTIME: { constexpr auto perSec = double(std::chrono::system_clock::period::num) / std::chrono::system_clock::period::den; res->tv_sec = time_t(perSec); res->tv_nsec = time_t(perSec * kNsPerSec); return 0; } case CLOCK_MONOTONIC: { constexpr auto perSec = double(std::chrono::steady_clock::period::num) / std::chrono::steady_clock::period::den; res->tv_sec = time_t(perSec); res->tv_nsec = time_t(perSec * kNsPerSec); return 0; } case CLOCK_PROCESS_CPUTIME_ID: case CLOCK_THREAD_CPUTIME_ID: { DWORD adj, timeIncrement; BOOL adjDisabled; if (!GetSystemTimeAdjustment(&adj, &timeIncrement, &adjDisabled)) { errno = EINVAL; return -1; } res->tv_sec = 0; res->tv_nsec = long(timeIncrement * 100); return 0; } default: errno = EINVAL; return -1; } } extern "C" int clock_gettime(clockid_t clock_id, struct timespec* tp) { if (!tp) { errno = EFAULT; return -1; } const auto unanosToTimespec = [](timespec* tp, unsigned_nanos t) -> int { static constexpr unsigned_nanos one_sec{std::chrono::seconds(1)}; tp->tv_sec = time_t(std::chrono::duration_cast<std::chrono::seconds>(t).count()); tp->tv_nsec = long((t % one_sec).count()); return 0; }; FILETIME createTime, exitTime, kernalTime, userTime; switch (clock_id) { case CLOCK_REALTIME: { auto now = std::chrono::system_clock::now().time_since_epoch(); duration_to_ts(now, tp); return 0; } case CLOCK_MONOTONIC: { auto now = std::chrono::steady_clock::now().time_since_epoch(); duration_to_ts(now, tp); return 0; } case CLOCK_PROCESS_CPUTIME_ID: { if (!GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernalTime, &userTime)) { errno = EINVAL; return -1; } return unanosToTimespec( tp, filetimeToUnsignedNanos(kernalTime) + filetimeToUnsignedNanos(userTime)); } case CLOCK_THREAD_CPUTIME_ID: { if (!GetThreadTimes( GetCurrentThread(), &createTime, &exitTime, &kernalTime, &userTime)) { errno = EINVAL; return -1; } return unanosToTimespec( tp, filetimeToUnsignedNanos(kernalTime) + filetimeToUnsignedNanos(userTime)); } default: errno = EINVAL; return -1; } } #else #error No clock_gettime(3) compatibility wrapper available for this platform. #endif #endif #ifdef _WIN32 #include <iomanip> #include <sstream> #include <folly/portability/Windows.h> extern "C" { char* asctime_r(const tm* tm, char* buf) { char tmpBuf[64]; if (asctime_s(tmpBuf, tm)) { return nullptr; } // Nothing we can do if the buff is to small :( return strcpy(buf, tmpBuf); } char* ctime_r(const time_t* t, char* buf) { char tmpBuf[64]; if (ctime_s(tmpBuf, 64, t)) { return nullptr; } // Nothing we can do if the buff is to small :( return strcpy(buf, tmpBuf); } tm* gmtime_r(const time_t* t, tm* res) { if (!gmtime_s(res, t)) { return res; } return nullptr; } tm* localtime_r(const time_t* t, tm* o) { if (!localtime_s(o, t)) { return o; } return nullptr; } int nanosleep(const struct timespec* request, struct timespec* remain) { Sleep((DWORD)((request->tv_sec * 1000) + (request->tv_nsec / 1000000))); if (remain != nullptr) { remain->tv_nsec = 0; remain->tv_sec = 0; } return 0; } char* strptime( const char* __restrict s, const char* __restrict f, struct tm* __restrict tm) { // Isn't the C++ standard lib nice? std::get_time is defined such that its // format parameters are the exact same as strptime. Of course, we have to // create a string stream first, and imbue it with the current C locale, and // we also have to make sure we return the right things if it fails, or // if it succeeds, but this is still far simpler an implementation than any // of the versions in any of the C standard libraries. std::istringstream input(s); input.imbue(std::locale(setlocale(LC_ALL, nullptr))); input >> std::get_time(tm, f); if (input.fail()) { return nullptr; } return const_cast<char*>(s + input.tellg()); } } #endif <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include <cassert> #include <cstdlib> #include "BackTrace.h" #include "Debugger.h" #include "Trace.h" #include "Assertions.h" #if qPlatform_POSIX #include <cstdio> #endif using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Debug; CompileTimeFlagChecker_SOURCE(Stroika::Foundation::Debug, qDebug, qDebug); #if qDebug namespace { void DefaultAssertionHandler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { try { DbgTrace ("%s (%s) failed in '%s'; %s:%d", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #if qPlatform_POSIX fprintf (stderr, "%s (%s) failed in '%s'; %s:%d\n", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #endif #if qDefaultTracingOn { wstring tmp { Debug::BackTrace () }; if (not tmp.empty ()) { DbgTrace (L"BackTrace: %s", tmp.c_str ()); } } #endif DropIntoDebuggerIfPresent (); DbgTrace ("ABORTING..."); #if qPlatform_POSIX fprintf (stderr, "ABORTING...\n"); #endif } catch (...) { } abort (); // if we ever get that far... } void DefaultWeakAssertionHandler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { DbgTrace ("%s (%s) failed in '%s'; %s:%d", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #if qPlatform_POSIX fprintf (stderr, "%s (%s) failed in '%s'; %s:%d\n", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #endif #if qDefaultTracingOn { wstring tmp { Debug::BackTrace () }; if (not tmp.empty ()) { DbgTrace (L"BackTrace: %s", tmp.c_str ()); } } #endif } } namespace { atomic<AssertionHandlerType> sAssertFailureHandler_ = DefaultAssertionHandler_; atomic<WeakAssertionHandlerType> sWeakAssertFailureHandler_ = DefaultWeakAssertionHandler_; } /* ******************************************************************************** **************************** Debug::GetAssertionHandler ************************ ******************************************************************************** */ AssertionHandlerType Stroika::Foundation::Debug::GetAssertionHandler () { return sAssertFailureHandler_; } /* ******************************************************************************** ************************** Debug::GetDefaultAssertionHandler ******************* ******************************************************************************** */ AssertionHandlerType Stroika::Foundation::Debug::GetDefaultAssertionHandler () { return DefaultAssertionHandler_; } /* ******************************************************************************** ********************************* Debug::SetAssertionHandler ******************* ******************************************************************************** */ void Stroika::Foundation::Debug::SetAssertionHandler (AssertionHandlerType assertionHandler) { sAssertFailureHandler_ = (assertionHandler == nullptr) ? DefaultAssertionHandler_ : assertionHandler; } /* ******************************************************************************** ************************** Debug::GetWeakAssertionHandler ********************** ******************************************************************************** */ WeakAssertionHandlerType Stroika::Foundation::Debug::GetWeakAssertionHandler () { return sWeakAssertFailureHandler_; } /* ******************************************************************************** ********************** Debug::GetDefaultWeakAssertionHandler ******************* ******************************************************************************** */ WeakAssertionHandlerType Stroika::Foundation::Debug::GetDefaultWeakAssertionHandler () { return DefaultWeakAssertionHandler_; } /* ******************************************************************************** ************************** Debug::SetWeakAssertionHandler ********************** ******************************************************************************** */ void Stroika::Foundation::Debug::SetWeakAssertionHandler (WeakAssertionHandlerType assertionHandler) { sWeakAssertFailureHandler_ = (assertionHandler == nullptr) ? DefaultWeakAssertionHandler_ : assertionHandler; } void Stroika::Foundation::Debug::Private_::Weak_Assertion_Failed_Handler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { (sWeakAssertFailureHandler_.load ()) (assertCategory, assertionText, fileName, lineNum, functionName); } DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-noreturn\""); // Cannot figure out how to disable this warning? -- LGP 2014-01-04 //DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Wenabled-by-default\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 [[noreturn]] void Stroika::Foundation::Debug::Private_::Assertion_Failed_Handler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { static bool s_InTrap = false; if (s_InTrap) { // prevent infinite looping if we get an assertion triggered while processing an assertion. // And ignore threading issues, because we are pragmatically aborting at this stage anyhow... abort (); } s_InTrap = true; (sAssertFailureHandler_.load ()) (assertCategory, assertionText, fileName, lineNum, functionName); s_InTrap = false; // in case using some sort of assertion handler that allows for continuation // (like under debugger manipulation of PC to go a little further in the code) } //DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Wenabled-by-default\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-noreturn\""); #endif <commit_msg>fix atomic<> usage<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved */ #include "../StroikaPreComp.h" #include <cassert> #include <cstdlib> #include "BackTrace.h" #include "Debugger.h" #include "Trace.h" #include "Assertions.h" #if qPlatform_POSIX #include <cstdio> #endif using namespace Stroika; using namespace Stroika::Foundation; using namespace Stroika::Foundation::Debug; CompileTimeFlagChecker_SOURCE(Stroika::Foundation::Debug, qDebug, qDebug); #if qDebug namespace { void DefaultAssertionHandler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { try { DbgTrace ("%s (%s) failed in '%s'; %s:%d", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #if qPlatform_POSIX fprintf (stderr, "%s (%s) failed in '%s'; %s:%d\n", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #endif #if qDefaultTracingOn { wstring tmp { Debug::BackTrace () }; if (not tmp.empty ()) { DbgTrace (L"BackTrace: %s", tmp.c_str ()); } } #endif DropIntoDebuggerIfPresent (); DbgTrace ("ABORTING..."); #if qPlatform_POSIX fprintf (stderr, "ABORTING...\n"); #endif } catch (...) { } abort (); // if we ever get that far... } void DefaultWeakAssertionHandler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { DbgTrace ("%s (%s) failed in '%s'; %s:%d", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #if qPlatform_POSIX fprintf (stderr, "%s (%s) failed in '%s'; %s:%d\n", assertCategory == nullptr ? "Unknown assertion" : assertCategory, assertionText == nullptr ? "" : assertionText, functionName == nullptr ? "" : functionName, fileName == nullptr ? "" : fileName, lineNum ); #endif #if qDefaultTracingOn { wstring tmp { Debug::BackTrace () }; if (not tmp.empty ()) { DbgTrace (L"BackTrace: %s", tmp.c_str ()); } } #endif } } namespace { atomic<AssertionHandlerType> sAssertFailureHandler_ { DefaultAssertionHandler_ }; atomic<WeakAssertionHandlerType> sWeakAssertFailureHandler_ { DefaultWeakAssertionHandler_ }; } /* ******************************************************************************** **************************** Debug::GetAssertionHandler ************************ ******************************************************************************** */ AssertionHandlerType Stroika::Foundation::Debug::GetAssertionHandler () { return sAssertFailureHandler_; } /* ******************************************************************************** ************************** Debug::GetDefaultAssertionHandler ******************* ******************************************************************************** */ AssertionHandlerType Stroika::Foundation::Debug::GetDefaultAssertionHandler () { return DefaultAssertionHandler_; } /* ******************************************************************************** ********************************* Debug::SetAssertionHandler ******************* ******************************************************************************** */ void Stroika::Foundation::Debug::SetAssertionHandler (AssertionHandlerType assertionHandler) { sAssertFailureHandler_ = (assertionHandler == nullptr) ? DefaultAssertionHandler_ : assertionHandler; } /* ******************************************************************************** ************************** Debug::GetWeakAssertionHandler ********************** ******************************************************************************** */ WeakAssertionHandlerType Stroika::Foundation::Debug::GetWeakAssertionHandler () { return sWeakAssertFailureHandler_; } /* ******************************************************************************** ********************** Debug::GetDefaultWeakAssertionHandler ******************* ******************************************************************************** */ WeakAssertionHandlerType Stroika::Foundation::Debug::GetDefaultWeakAssertionHandler () { return DefaultWeakAssertionHandler_; } /* ******************************************************************************** ************************** Debug::SetWeakAssertionHandler ********************** ******************************************************************************** */ void Stroika::Foundation::Debug::SetWeakAssertionHandler (WeakAssertionHandlerType assertionHandler) { sWeakAssertFailureHandler_ = (assertionHandler == nullptr) ? DefaultWeakAssertionHandler_ : assertionHandler; } void Stroika::Foundation::Debug::Private_::Weak_Assertion_Failed_Handler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { (sWeakAssertFailureHandler_.load ()) (assertCategory, assertionText, fileName, lineNum, functionName); } DISABLE_COMPILER_CLANG_WARNING_START("clang diagnostic ignored \"-Winvalid-noreturn\""); // Cannot figure out how to disable this warning? -- LGP 2014-01-04 //DISABLE_COMPILER_GCC_WARNING_START("GCC diagnostic ignored \"-Wenabled-by-default\""); // Really probably an issue, but not to debug here -- LGP 2014-01-04 [[noreturn]] void Stroika::Foundation::Debug::Private_::Assertion_Failed_Handler_ (const char* assertCategory, const char* assertionText, const char* fileName, int lineNum, const char* functionName) noexcept { static bool s_InTrap = false; if (s_InTrap) { // prevent infinite looping if we get an assertion triggered while processing an assertion. // And ignore threading issues, because we are pragmatically aborting at this stage anyhow... abort (); } s_InTrap = true; (sAssertFailureHandler_.load ()) (assertCategory, assertionText, fileName, lineNum, functionName); s_InTrap = false; // in case using some sort of assertion handler that allows for continuation // (like under debugger manipulation of PC to go a little further in the code) } //DISABLE_COMPILER_GCC_WARNING_END("GCC diagnostic ignored \"-Wenabled-by-default\""); DISABLE_COMPILER_CLANG_WARNING_END("clang diagnostic ignored \"-Winvalid-noreturn\""); #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/PortRemediator.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/Platform.h" #include "fboss/agent/state/PortMap.h" #include "fboss/agent/state/SwitchState.h" namespace { constexpr int kPortRemedyIntervalSec = 25; using facebook::fboss::SwSwitch; using facebook::fboss::SwitchState; using facebook::fboss::PortID; using facebook::fboss::cfg::PortState; void updatePortState( SwSwitch* sw, PortID portId, PortState newPortState, bool preventCoalescing) { auto updateFn = [portId, newPortState]( const std::shared_ptr<SwitchState>& state) { std::shared_ptr<SwitchState> newState{state}; auto port = state->getPorts()->getPortIf(portId); if (!port) { LOG(WARNING) << "Could not flap port " << portId << " not found in port map"; return newState; } const auto newPort = port->modify(&newState); newPort->setState(newPortState); return newState; }; auto name = folly::sformat( "PortRemediator: flap down but enabled port {} ({})", static_cast<uint16_t>(portId), newPortState == PortState::UP ? "up" : "down"); if (preventCoalescing) { sw->updateStateNoCoalescing(name, updateFn); } else { sw->updateState(name, updateFn); } } } namespace facebook { namespace fboss { boost::container::flat_set<PortID> PortRemediator::getUnexpectedDownPorts() const { // TODO - Post t17304538, if Port::state == POWER_DOWN reflects // Admin down always, then just use SwitchState to to determine // which ports to ignore. boost::container::flat_set<PortID> unexpectedDownPorts; boost::container::flat_set<int> configEnabledPorts; for (const auto& cfgPort : sw_->getConfig().ports) { if (cfgPort.state != cfg::PortState::POWER_DOWN && cfgPort.state != cfg::PortState::DOWN) { configEnabledPorts.insert(cfgPort.logicalID); } } const auto portMap = sw_->getState()->getPorts(); for (const auto& port : *portMap) { if (port && configEnabledPorts.find(port->getID()) != configEnabledPorts.end() && !(port->getOperState())) { unexpectedDownPorts.insert(port->getID()); } } return unexpectedDownPorts; } void PortRemediator::timeoutExpired() noexcept { auto unexpectedDownPorts = getUnexpectedDownPorts(); auto platform = sw_->getPlatform(); for (const auto& portId : unexpectedDownPorts) { auto platformPort = platform->getPlatformPort(portId); if (!platformPort->supportsTransceiver()) { continue; } auto infoFuture = platformPort->getTransceiverInfo(); infoFuture.via(sw_->getBackgroundEVB()) .then([ sw = sw_, portId ](TransceiverInfo info) { if (info.present) { updatePortState(sw, portId, cfg::PortState::DOWN, true); updatePortState(sw, portId, cfg::PortState::UP, true); } }); } scheduleTimeout(interval_); } PortRemediator::PortRemediator(SwSwitch* swSwitch) : AsyncTimeout(swSwitch->getBackgroundEVB()), sw_(swSwitch), interval_(kPortRemedyIntervalSec) { }; void PortRemediator::init() { // Schedule the port remedy handler to run bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( PortRemediator::start, (void*)this); if (!ret) { // Throw error from the constructor because this object is unusable if we // cannot start it in event base. throw FbossError("Failed to start PortRemediator"); } } PortRemediator::~PortRemediator() { int stopPortRemediator = sw_->getBackgroundEVB()->runImmediatelyOrRunInEventBaseThreadAndWait( PortRemediator::stop, (void*)this); // At this point, PortRemediator must not be running. if (!stopPortRemediator) { throw FbossError("Failed to stop port remediation handler"); } } }} // facebook::fboss <commit_msg>dont remediate any ports which are admin disabled<commit_after>/* * Copyright (c) 2004-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "fboss/agent/PortRemediator.h" #include "fboss/agent/FbossError.h" #include "fboss/agent/Platform.h" #include "fboss/agent/state/PortMap.h" #include "fboss/agent/state/SwitchState.h" namespace { constexpr int kPortRemedyIntervalSec = 25; using facebook::fboss::SwSwitch; using facebook::fboss::SwitchState; using facebook::fboss::PortID; using facebook::fboss::cfg::PortState; void updatePortState( SwSwitch* sw, PortID portId, PortState newPortState) { auto updateFn = [portId, newPortState]( const std::shared_ptr<SwitchState>& state) { std::shared_ptr<SwitchState> newState{state}; auto port = state->getPorts()->getPortIf(portId); if (!port) { LOG(WARNING) << "Could not flap port " << portId << " not found in port map"; return newState; } const auto newPort = port->modify(&newState); newPort->setState(newPortState); return newState; }; auto name = folly::sformat( "PortRemediator: flap down but enabled port {} ({})", static_cast<uint16_t>(portId), newPortState == PortState::UP ? "up" : "down"); sw->updateStateNoCoalescing(name, updateFn); } } namespace facebook { namespace fboss { boost::container::flat_set<PortID> PortRemediator::getUnexpectedDownPorts() const { boost::container::flat_set<PortID> unexpectedDownPorts; const auto portMap = sw_->getState()->getPorts(); for (const auto& port : *portMap) { if (port && !port->isAdminDisabled() && !port->getOperState()) { unexpectedDownPorts.insert(port->getID()); } } return unexpectedDownPorts; } void PortRemediator::timeoutExpired() noexcept { auto unexpectedDownPorts = getUnexpectedDownPorts(); auto platform = sw_->getPlatform(); for (const auto& portId : unexpectedDownPorts) { auto platformPort = platform->getPlatformPort(portId); if (!platformPort->supportsTransceiver()) { continue; } auto infoFuture = platformPort->getTransceiverInfo(); infoFuture.via(sw_->getBackgroundEVB()) .then([ sw = sw_, portId ](TransceiverInfo info) { if (info.present) { updatePortState(sw, portId, cfg::PortState::DOWN); updatePortState(sw, portId, cfg::PortState::UP); } }); } scheduleTimeout(interval_); } PortRemediator::PortRemediator(SwSwitch* swSwitch) : AsyncTimeout(swSwitch->getBackgroundEVB()), sw_(swSwitch), interval_(kPortRemedyIntervalSec) { }; void PortRemediator::init() { // Schedule the port remedy handler to run bool ret = sw_->getBackgroundEVB()->runInEventBaseThread( PortRemediator::start, (void*)this); if (!ret) { // Throw error from the constructor because this object is unusable if we // cannot start it in event base. throw FbossError("Failed to start PortRemediator"); } } PortRemediator::~PortRemediator() { int stopPortRemediator = sw_->getBackgroundEVB()->runImmediatelyOrRunInEventBaseThreadAndWait( PortRemediator::stop, (void*)this); // At this point, PortRemediator must not be running. if (!stopPortRemediator) { throw FbossError("Failed to stop port remediation handler"); } } }} // facebook::fboss <|endoftext|>