commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
c4f73058fb142859cd59af14d5a4a8ebf7f9b165
Modules/Filtering/DistanceMap/test/itkFastChamferDistanceImageFilterTest.cxx
Modules/Filtering/DistanceMap/test/itkFastChamferDistanceImageFilterTest.cxx
/*========================================================================= * * 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 "itkFastChamferDistanceImageFilter.h" // simple signed distance function namespace { template <typename TPoint> double SimpleSignedDistance( const TPoint & p ) { TPoint center; center.Fill( 16 ); double radius = 10; double accum = 0.0; for( unsigned int j = 0; j < TPoint::PointDimension; j++ ) { accum += static_cast< double >( vnl_math_sqr( p[j] - center[j] ) ); } accum = vcl_sqrt( accum ); if (vnl_math_abs(accum - radius) > 1) { if((accum - radius) > 0) { return radius; } else { return -radius; } } else { return ( accum - radius ); } } } template< unsigned int VDimension > int FastChamferDistanceImageFilterTest( unsigned int iPositive, unsigned int iNegative, unsigned int iOther ) { std::cout<< "Test ITK Chamfer Distance Image Filter" << std::endl; std::cout << "Compute the distance map of a 32^d image" << std::endl; typedef float PixelType; typedef itk::Image<PixelType,VDimension> ImageType; typedef itk::Point<double,VDimension> PointType; typename ImageType::SizeType size; size.Fill( 32 ); typename ImageType::IndexType index; index.Fill( 0 ); typename ImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); typename ImageType::Pointer inputImage = ImageType::New(); inputImage->SetLargestPossibleRegion( region ); inputImage->SetBufferedRegion( region ); inputImage->SetRequestedRegion( region ); inputImage->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it(inputImage,region); // Set the image to 0 while( !it.IsAtEnd() ) { PointType point; inputImage->TransformIndexToPhysicalPoint( it.GetIndex(), point ); it.Set( SimpleSignedDistance( point ) ); ++it; } /* Create Fast Chamfer Distance filter */ typedef itk::FastChamferDistanceImageFilter< ImageType,ImageType> ChamferFilterType; typename ChamferFilterType::Pointer filter = ChamferFilterType::New(); filter->SetInput(inputImage); typename ImageType::Pointer outputImage = filter->GetOutput(); try { filter->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } filter->Print(std::cout); //Create NarrowBand typedef typename ChamferFilterType::BandNodeType BandNodeType; typedef typename ChamferFilterType::NarrowBandType NarrowBandType; typename NarrowBandType::Pointer band = NarrowBandType::New(); band->SetTotalRadius(4); band->SetInnerRadius(2); filter->SetMaximumDistance(5); std::cout<<"Band initial size: "<<band->Size()<<std::endl; filter->SetNarrowBand(band.GetPointer()); filter->Update(); std::cout<<"Band size: "<<band->Size()<<std::endl; //Loop through the band typedef typename NarrowBandType::ConstIterator itNBType; itNBType itNB = band->Begin(); itNBType itNBend = band->End(); // BandNodeType *tmp; unsigned int innerpositive=0; unsigned int innernegative=0; unsigned int otherpoints=0; while( itNB != itNBend ) { if(itNB->m_NodeState == 3) { innerpositive++; } else if(itNB->m_NodeState == 2) { innernegative++; } else { otherpoints++; } ++itNB; } if( innerpositive != iPositive ) { std::cout << "Inner positive points: " << innerpositive << " != " << iPositive << std::endl; return EXIT_FAILURE; } if( innernegative != iNegative ) { std::cout << "Inner negative points: " << innernegative << " != " << iNegative << std::endl; return EXIT_FAILURE; } if( otherpoints != iOther ) { std::cout << "Rest of points: " << otherpoints << " != " << iOther << std::endl; return EXIT_FAILURE; } //Exercising filter methods float inweights[VDimension]; for( unsigned int dim = 0; dim < VDimension; dim++ ) { inweights[dim] = 0.; } if( VDimension > 0 ) { inweights[0]=0.926; } if( VDimension > 1 ) { inweights[1]=1.34; } filter->SetWeights(inweights); const float *outweights = filter->GetWeights().GetDataPointer(); std::cout << "outweights = " << outweights << std::endl; if( filter->GetMaximumDistance() != 5 ) { std::cout << "filter->GetMaximumDistance() != 5" <<std::endl; return EXIT_FAILURE; } /* For debugging write the result typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName("chamferoutput.mhd"); writer->SetInput(filter->GetOutput()); writer->Update(); */ std::cout << "Test passed" << std::endl; return EXIT_SUCCESS; } int itkFastChamferDistanceImageFilterTest( int argc, char* argv[] ) { if( argc != 2 ) { std::cout << "This test requires at least one argument (the image dimension)" <<std::endl; return EXIT_FAILURE; } int Dimension = atoi( argv[1] ); std::cout <<"Dimension = " << Dimension << std::endl; if( Dimension == 1 ) { return FastChamferDistanceImageFilterTest< 1 >( 4, 6, 8 ); } if( Dimension == 2 ) { return FastChamferDistanceImageFilterTest< 2 >( 144, 124, 256 ); } if( Dimension == 3 ) { return FastChamferDistanceImageFilterTest< 3 >( 3068, 2066, 5520 ); } if( Dimension == 4 ) { return FastChamferDistanceImageFilterTest< 4 >( 49472, 28928, 93136 ); } return EXIT_FAILURE; }
/*========================================================================= * * 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 "itkFastChamferDistanceImageFilter.h" // simple signed distance function namespace { template <typename TPoint> double SimpleSignedDistance( const TPoint & p ) { TPoint center; center.Fill( 16 ); double radius = 10; double accum = 0.0; for( unsigned int j = 0; j < TPoint::PointDimension; j++ ) { accum += static_cast< double >( vnl_math_sqr( p[j] - center[j] ) ); } accum = vcl_sqrt( accum ); if (vnl_math_abs(accum - radius) > 1) { if((accum - radius) > 0) { return radius; } else { return -radius; } } else { return ( accum - radius ); } } } template< unsigned int VDimension > int FastChamferDistanceImageFilterTest( unsigned int iPositive, unsigned int iNegative, unsigned int iOther ) { std::cout<< "Test ITK Chamfer Distance Image Filter" << std::endl; std::cout << "Compute the distance map of a 32^d image" << std::endl; typedef float PixelType; typedef itk::Image<PixelType,VDimension> ImageType; typedef itk::Point<double,VDimension> PointType; typename ImageType::SizeType size; size.Fill( 32 ); typename ImageType::IndexType index; index.Fill( 0 ); typename ImageType::RegionType region; region.SetSize( size ); region.SetIndex( index ); typename ImageType::Pointer inputImage = ImageType::New(); inputImage->SetLargestPossibleRegion( region ); inputImage->SetBufferedRegion( region ); inputImage->SetRequestedRegion( region ); inputImage->Allocate(); typedef itk::ImageRegionIteratorWithIndex<ImageType> IteratorType; IteratorType it(inputImage,region); // Set the image to 0 while( !it.IsAtEnd() ) { PointType point; inputImage->TransformIndexToPhysicalPoint( it.GetIndex(), point ); it.Set( SimpleSignedDistance( point ) ); ++it; } /* Create Fast Chamfer Distance filter */ typedef itk::FastChamferDistanceImageFilter< ImageType,ImageType> ChamferFilterType; typename ChamferFilterType::Pointer filter = ChamferFilterType::New(); filter->SetInput(inputImage); typename ImageType::Pointer outputImage = filter->GetOutput(); try { filter->Update(); } catch( itk::ExceptionObject & err ) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } filter->Print(std::cout); //Create NarrowBand typedef typename ChamferFilterType::BandNodeType BandNodeType; typedef typename ChamferFilterType::NarrowBandType NarrowBandType; typename NarrowBandType::Pointer band = NarrowBandType::New(); band->SetTotalRadius(4); band->SetInnerRadius(2); filter->SetMaximumDistance(5); std::cout<<"Band initial size: "<<band->Size()<<std::endl; filter->SetNarrowBand(band.GetPointer()); filter->Update(); std::cout<<"Band size: "<<band->Size()<<std::endl; //Loop through the band typedef typename NarrowBandType::ConstIterator itNBType; itNBType itNB = band->Begin(); itNBType itNBend = band->End(); // BandNodeType *tmp; unsigned int innerpositive=0; unsigned int innernegative=0; unsigned int otherpoints=0; while( itNB != itNBend ) { if(itNB->m_NodeState == 3) { innerpositive++; } else if(itNB->m_NodeState == 2) { innernegative++; } else { otherpoints++; } ++itNB; } if( innerpositive != iPositive ) { std::cout << "Inner positive points: " << innerpositive << " != " << iPositive << std::endl; return EXIT_FAILURE; } if( innernegative != iNegative ) { std::cout << "Inner negative points: " << innernegative << " != " << iNegative << std::endl; return EXIT_FAILURE; } if( otherpoints != iOther ) { std::cout << "Rest of points: " << otherpoints << " != " << iOther << std::endl; return EXIT_FAILURE; } //Exercising filter methods float inweights[VDimension]; for( unsigned int dim = 0; dim < VDimension; dim++ ) { if( dim == 0 ) { inweights[dim] = 0.926f; } else if( dim == 1 ) { inweights[dim] = 1.34f; } else { inweights[dim] = 0.f; } } filter->SetWeights(inweights); const float *outweights = filter->GetWeights().GetDataPointer(); std::cout << "outweights = " << outweights << std::endl; if( filter->GetMaximumDistance() != 5 ) { std::cout << "filter->GetMaximumDistance() != 5" <<std::endl; return EXIT_FAILURE; } /* For debugging write the result typedef itk::ImageFileWriter< ImageType > WriterType; WriterType::Pointer writer = WriterType::New(); writer->SetFileName("chamferoutput.mhd"); writer->SetInput(filter->GetOutput()); writer->Update(); */ std::cout << "Test passed" << std::endl; return EXIT_SUCCESS; } int itkFastChamferDistanceImageFilterTest( int argc, char* argv[] ) { if( argc != 2 ) { std::cout << "This test requires at least one argument (the image dimension)" <<std::endl; return EXIT_FAILURE; } int Dimension = atoi( argv[1] ); std::cout <<"Dimension = " << Dimension << std::endl; if( Dimension == 1 ) { return FastChamferDistanceImageFilterTest< 1 >( 4, 6, 8 ); } if( Dimension == 2 ) { return FastChamferDistanceImageFilterTest< 2 >( 144, 124, 256 ); } if( Dimension == 3 ) { return FastChamferDistanceImageFilterTest< 3 >( 3068, 2066, 5520 ); } if( Dimension == 4 ) { return FastChamferDistanceImageFilterTest< 4 >( 49472, 28928, 93136 ); } return EXIT_FAILURE; }
Fix warning C4789 from VisualStudio 11
COMP: Fix warning C4789 from VisualStudio 11 The warning is: itkfastchamferdistanceimagefiltertest.cxx(189): warning C4789: buffer 'inweights' of size 4 bytes will be overrun; 4 bytes will be written starting at offset 4 Change-Id: I60d072d8e204c896b291699723f0830fd03d8c57
C++
apache-2.0
stnava/ITK,LucHermitte/ITK,hjmjohnson/ITK,blowekamp/ITK,jmerkow/ITK,malaterre/ITK,spinicist/ITK,jmerkow/ITK,fedral/ITK,PlutoniumHeart/ITK,fedral/ITK,biotrump/ITK,atsnyder/ITK,atsnyder/ITK,msmolens/ITK,BlueBrain/ITK,vfonov/ITK,blowekamp/ITK,ajjl/ITK,hendradarwin/ITK,BRAINSia/ITK,zachary-williamson/ITK,jmerkow/ITK,heimdali/ITK,LucHermitte/ITK,fbudin69500/ITK,PlutoniumHeart/ITK,richardbeare/ITK,hjmjohnson/ITK,jmerkow/ITK,blowekamp/ITK,LucasGandel/ITK,atsnyder/ITK,blowekamp/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,InsightSoftwareConsortium/ITK,richardbeare/ITK,fbudin69500/ITK,malaterre/ITK,malaterre/ITK,biotrump/ITK,atsnyder/ITK,thewtex/ITK,LucHermitte/ITK,Kitware/ITK,BlueBrain/ITK,hendradarwin/ITK,fbudin69500/ITK,LucasGandel/ITK,biotrump/ITK,richardbeare/ITK,BRAINSia/ITK,spinicist/ITK,BlueBrain/ITK,spinicist/ITK,eile/ITK,stnava/ITK,PlutoniumHeart/ITK,BRAINSia/ITK,jcfr/ITK,Kitware/ITK,thewtex/ITK,spinicist/ITK,BlueBrain/ITK,PlutoniumHeart/ITK,malaterre/ITK,malaterre/ITK,hendradarwin/ITK,Kitware/ITK,zachary-williamson/ITK,fedral/ITK,LucHermitte/ITK,vfonov/ITK,hendradarwin/ITK,hjmjohnson/ITK,PlutoniumHeart/ITK,thewtex/ITK,fbudin69500/ITK,LucasGandel/ITK,blowekamp/ITK,BRAINSia/ITK,richardbeare/ITK,malaterre/ITK,fedral/ITK,ajjl/ITK,zachary-williamson/ITK,hendradarwin/ITK,BRAINSia/ITK,eile/ITK,malaterre/ITK,eile/ITK,biotrump/ITK,zachary-williamson/ITK,BlueBrain/ITK,vfonov/ITK,msmolens/ITK,heimdali/ITK,ajjl/ITK,BlueBrain/ITK,eile/ITK,fedral/ITK,heimdali/ITK,thewtex/ITK,stnava/ITK,jcfr/ITK,msmolens/ITK,ajjl/ITK,blowekamp/ITK,msmolens/ITK,heimdali/ITK,jcfr/ITK,heimdali/ITK,jmerkow/ITK,blowekamp/ITK,fbudin69500/ITK,InsightSoftwareConsortium/ITK,stnava/ITK,LucasGandel/ITK,biotrump/ITK,LucasGandel/ITK,thewtex/ITK,richardbeare/ITK,fedral/ITK,hendradarwin/ITK,msmolens/ITK,LucHermitte/ITK,jmerkow/ITK,fbudin69500/ITK,ajjl/ITK,eile/ITK,richardbeare/ITK,eile/ITK,InsightSoftwareConsortium/ITK,spinicist/ITK,InsightSoftwareConsortium/ITK,InsightSoftwareConsortium/ITK,PlutoniumHeart/ITK,atsnyder/ITK,heimdali/ITK,zachary-williamson/ITK,vfonov/ITK,heimdali/ITK,msmolens/ITK,richardbeare/ITK,atsnyder/ITK,spinicist/ITK,ajjl/ITK,LucasGandel/ITK,BRAINSia/ITK,fbudin69500/ITK,Kitware/ITK,spinicist/ITK,Kitware/ITK,vfonov/ITK,jmerkow/ITK,zachary-williamson/ITK,msmolens/ITK,thewtex/ITK,LucHermitte/ITK,thewtex/ITK,jcfr/ITK,atsnyder/ITK,heimdali/ITK,malaterre/ITK,hjmjohnson/ITK,BRAINSia/ITK,hendradarwin/ITK,msmolens/ITK,zachary-williamson/ITK,atsnyder/ITK,blowekamp/ITK,eile/ITK,stnava/ITK,stnava/ITK,stnava/ITK,biotrump/ITK,eile/ITK,zachary-williamson/ITK,jcfr/ITK,Kitware/ITK,atsnyder/ITK,biotrump/ITK,malaterre/ITK,PlutoniumHeart/ITK,InsightSoftwareConsortium/ITK,hjmjohnson/ITK,Kitware/ITK,LucHermitte/ITK,eile/ITK,spinicist/ITK,vfonov/ITK,hjmjohnson/ITK,stnava/ITK,vfonov/ITK,spinicist/ITK,BlueBrain/ITK,jmerkow/ITK,PlutoniumHeart/ITK,jcfr/ITK,ajjl/ITK,LucasGandel/ITK,BlueBrain/ITK,LucasGandel/ITK,fedral/ITK,biotrump/ITK,jcfr/ITK,hendradarwin/ITK,LucHermitte/ITK,vfonov/ITK,zachary-williamson/ITK,fbudin69500/ITK,vfonov/ITK,jcfr/ITK,stnava/ITK,ajjl/ITK,fedral/ITK
a3902f735fe8d8ead14a6971d4c47fe1f83e2478
cpp/tests/unit-tests/mqtt/MqttMessagingSkeletonTest.cpp
cpp/tests/unit-tests/mqtt/MqttMessagingSkeletonTest.cpp
/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/serializer/Serializer.h" #include "joynr/Request.h" #include "cluster-controller/mqtt/MqttMessagingSkeleton.h" #include "tests/utils/MockObjects.h" using ::testing::A; using ::testing::_; using ::testing::Eq; using ::testing::AllOf; using ::testing::Property; using ::testing::Pointee; using namespace ::testing; using namespace joynr; class MqttMessagingSkeletonTest : public ::testing::Test { public: MqttMessagingSkeletonTest() : mockMessageRouter() {} void SetUp(){ // create a fake message std::string postFix; std::string senderID; std::string receiverID; std::string requestID; postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; MessagingQos qosSettings = MessagingQos(456000); Request request; request.setMethodName("methodName"); std::vector<Variant> params; params.push_back(Variant::make<int>(42)); params.push_back(Variant::make<std::string>("value")); request.setParamsVariant(params); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer"); paramDatatypes.push_back("String"); request.setParamDatatypes(paramDatatypes); JoynrMessageFactory messageFactory; message = messageFactory.createRequest( senderID, receiverID, qosSettings, request ); } void TearDown(){ } protected: MockMessageRouter mockMessageRouter; JoynrMessage message; }; MATCHER_P(pointerToMqttAddressWithChannelId, channelId, "") { if (arg == nullptr) { return false; } std::shared_ptr<const joynr::system::RoutingTypes::MqttAddress> mqttAddress = std::dynamic_pointer_cast<const joynr::system::RoutingTypes::MqttAddress>(arg); if (mqttAddress == nullptr) { return false; } return mqttAddress->getTopic() == channelId; } TEST_F(MqttMessagingSkeletonTest, transmitTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter); std::string replyAddress = message.getHeaderReplyAddress(); EXPECT_CALL(mockMessageRouter, addNextHop( _, AnyOf( Pointee(A<joynr::system::RoutingTypes::Address>()), pointerToMqttAddressWithChannelId(replyAddress) ), _) ).Times(1); EXPECT_CALL(mockMessageRouter, route(message,_)).Times(1); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(message,onFailure); } TEST_F(MqttMessagingSkeletonTest, onTextMessageReceivedTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter); std::string serializedMessage = serializer::serializeToJson(message); EXPECT_CALL(mockMessageRouter, route(AllOf(Property(&JoynrMessage::getType, Eq(message.getType())), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)).Times(1); mqttMessagingSkeleton.onTextMessageReceived(serializedMessage); }
/* * #%L * %% * Copyright (C) 2011 - 2016 BMW Car IT GmbH * %% * 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. * #L% */ #include <gtest/gtest.h> #include <gmock/gmock.h> #include "joynr/serializer/Serializer.h" #include "joynr/Request.h" #include "cluster-controller/mqtt/MqttMessagingSkeleton.h" #include "tests/utils/MockObjects.h" using ::testing::A; using ::testing::_; using ::testing::Eq; using ::testing::AllOf; using ::testing::Property; using ::testing::Pointee; using namespace ::testing; using namespace joynr; class MqttMessagingSkeletonTest : public ::testing::Test { public: MqttMessagingSkeletonTest() : mockMessageRouter() {} void SetUp(){ // create a fake message std::string postFix; std::string senderID; std::string receiverID; std::string requestID; postFix = "_" + util::createUuid(); senderID = "senderId" + postFix; receiverID = "receiverID" + postFix; requestID = "requestId" + postFix; MessagingQos qosSettings = MessagingQos(456000); Request request; request.setMethodName("methodName"); request.setParams(42, std::string("value")); std::vector<std::string> paramDatatypes; paramDatatypes.push_back("Integer"); paramDatatypes.push_back("String"); request.setParamDatatypes(paramDatatypes); JoynrMessageFactory messageFactory; message = messageFactory.createRequest( senderID, receiverID, qosSettings, request ); } void TearDown(){ } protected: MockMessageRouter mockMessageRouter; JoynrMessage message; }; MATCHER_P(pointerToMqttAddressWithChannelId, channelId, "") { if (arg == nullptr) { return false; } std::shared_ptr<const joynr::system::RoutingTypes::MqttAddress> mqttAddress = std::dynamic_pointer_cast<const joynr::system::RoutingTypes::MqttAddress>(arg); if (mqttAddress == nullptr) { return false; } return mqttAddress->getTopic() == channelId; } TEST_F(MqttMessagingSkeletonTest, transmitTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter); std::string replyAddress = message.getHeaderReplyAddress(); EXPECT_CALL(mockMessageRouter, addNextHop( _, AnyOf( Pointee(A<joynr::system::RoutingTypes::Address>()), pointerToMqttAddressWithChannelId(replyAddress) ), _) ).Times(1); EXPECT_CALL(mockMessageRouter, route(message,_)).Times(1); auto onFailure = [](const exceptions::JoynrRuntimeException& e) { FAIL() << "onFailure called"; }; mqttMessagingSkeleton.transmit(message,onFailure); } TEST_F(MqttMessagingSkeletonTest, onTextMessageReceivedTest) { MqttMessagingSkeleton mqttMessagingSkeleton(mockMessageRouter); std::string serializedMessage = serializer::serializeToJson(message); EXPECT_CALL(mockMessageRouter, route(AllOf(Property(&JoynrMessage::getType, Eq(message.getType())), Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_)).Times(1); mqttMessagingSkeleton.onTextMessageReceived(serializedMessage); }
remove Variant usage in MqttMessagingSkeletonTest
[c++] remove Variant usage in MqttMessagingSkeletonTest Change-Id: If592fe982d5d7389df712162d60adf9a86276b44
C++
apache-2.0
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,clive-jevons/joynr,clive-jevons/joynr,bmwcarit/joynr,bmwcarit/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr,clive-jevons/joynr,bmwcarit/joynr,clive-jevons/joynr
60a12c2eac93d968e504ffc323c2678ca1d70564
cpp/src/grids/protocol.cpp
cpp/src/grids/protocol.cpp
#include <iostream> #include <SDL/SDL.h> #include <SDL/SDL_thread.h> #include <SDL_net.h> #include <json/writer.h> #include <json/reader.h> #include <json/value.h> #include <grids/define.h> #include <grids/protocol.h> namespace Grids { void Protocol::setEventCallback(gevent_callback_t cb, void *userData) { eventCallback = cb; eventCallbackUserData = userData; } void Protocol::setConnectedCallback(gevent_callback_t cb, void *userData) { connectedCallback = cb; connectedCallbackUserData = userData; } int runEventLoopThreadEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->runEventLoop(); return 0; } /* void *dispatchEventEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->dispatchEvent(); } */ Protocol::Protocol() { sock = 0; finishedMutex = SDL_CreateMutex(); running = 0; connectedCallback = NULL; } Protocol::~Protocol() { SDL_DestroyMutex(finishedMutex); } bool Protocol::connectToNode(const char *address) { IPaddress ip; if (SDLNet_ResolveHost(&ip, (char *)address, GRIDS_PORT) == -1) { printf("Could not resolve hostname %s: %s\n", address, SDLNet_GetError()); return 0; } sock = SDLNet_TCP_Open(&ip); if (! sock) { printf("Failed to connect to host %s: %s\n", address, SDLNet_GetError()); return 0; } // hooray we are connnected! initialize protocol sendProtocolInitiationString(); return 1; } void Protocol::sendProtocolInitiationString() { protocolWrite("==Grids/1.0/JSON"); } int Protocol::protocolWrite(const char *str) { uint32_t len = strlen(str); unsigned int outstr_len = len + 4; char *outstr = (char *)malloc(outstr_len); SDLNet_Write32(len, outstr); memcpy((outstr + 4), str, len); int ret = SDLNet_TCP_Send(sock, outstr, outstr_len); // free(outstr); if (ret != outstr_len) { printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); // It may be good to disconnect sock because it is likely invalid now. } return ret; } void Protocol::closeConnection() { SDLNet_TCP_Close(sock); } std::string Protocol::stringifyMap(gridsmap_t *m) { Json::FastWriter *writer = new Json::FastWriter(); Json::Value root = mapToJsonValue(m); return writer->write(root); } void Protocol::sendRequest(std::string evt) { sendRequest(evt, NULL); } void Protocol::sendRequest(std::string evt, gridsmap_t *args) { if (evt.empty()) return; if (args == NULL) { args = new gridsmap_t(); } const static std::string methodkey = "_method"; (*args)[methodkey] = evt; std::string msg = stringifyMap(args); protocolWrite(msg.c_str()); } Json::Value Protocol::mapToJsonValue(gridsmap_t *m) { giterator mapIterator; Json::Value jsonVal; for(mapIterator = m->begin(); mapIterator != m->end(); mapIterator++) { gridskey_t key = mapIterator->first; gridsval_t val = mapIterator->second; jsonVal[key] = val; } return jsonVal; } void Protocol::runEventLoop() { int bytesRead; uint32_t incomingLength; char *buf; char *bufIncoming; setFinished(0); while (! isFinished() && sock) { // read in 4 byte length of message bytesRead = SDLNet_TCP_Recv(sock, &incomingLength, 4); incomingLength = SDLNet_Read32(&incomingLength); if (bytesRead < 0) { std::cerr << "Socket read error: " << SDLNet_GetError() << "\n"; continue; } if (bytesRead != 4) { // socket broken most likely std::cerr << "failed to read from socket\n"; // break; continue; } if (incomingLength > 1024 * 1024 * 1024) { // not going to read in more than a gig, f that std::cerr << "Got incoming message size: " << incomingLength << ". Skipping\n"; continue; } // TODO: run in seperate thread // allocate space for incoming message + null byte buf = (char *)malloc(incomingLength + 1); std::cout << "incoming: " << incomingLength << "\n"; uint32_t bytesRemaining = incomingLength; bufIncoming = buf; do { bytesRead = SDLNet_TCP_Recv(sock, bufIncoming, bytesRemaining); if (bytesRead > 0) { bytesRemaining -= bytesRead; bufIncoming += bytesRead; } } while ((bytesRead > 0) && bytesRemaining && ! isFinished()); buf[incomingLength] = '\0'; if (bytesRead == -1) { // o snap read error std::cerr << "Socket read error: " << bytesRead << "\n"; free(buf); break; } if (bytesRead == 0) { // not chill std::cerr << "Didn't read any data when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } if (bytesRead != incomingLength) { std::cerr << "Only read " << bytesRead << " bytes when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } // TODO: run in seperate thread std::string msg = buf; handleMessage(msg); free(buf); } } void Protocol::handleMessage(std::string &msg) { if (msg.size() < 2) return; // obv. bogus if (msg.find("==", 0, 2) == 0) { // protocol initiation message if (connectedCallback) connectedCallback(this, NULL, connectedCallbackUserData); } else if (msg.find("--", 0, 2) == 0) { // encrypted protocol message } else { // assume this is json for now Json::Value root = parseJson(msg); // FIXME: this is slow and lame //gridsmap_t rootMap = jsonToMap(root); Event *evt = new Event(root["_method"].asString(), root); eventCallback(this, evt, eventCallbackUserData); delete evt; } } gridsmap_t Protocol::jsonToMap(Json::Value &root) { // ghetto, should fix in the future Json::Value::Members memberList = root.getMemberNames(); std::vector<std::string>::iterator iter; gridsmap_t outMap; for (iter = memberList.begin(); iter != memberList.end(); iter++) { Json::Value val = root[*iter]; outMap[*iter] = val; } return outMap; } Json::Value Protocol::parseJson(std::string &msg) { Json::Value root; Json::Reader reader; if (reader.parse(msg, root)) return root; std::cerr << "Could not parse JSON: " << msg << "\n"; return Json::Value(0); } int Protocol::runEventLoopThreaded() { SDL_mutexP(finishedMutex); eventLoopThread = SDL_CreateThread(runEventLoopThreadEntryPoint, this); threadsFinished[getThreadId()] = 0; SDL_mutexV(finishedMutex); return 0; } void Protocol::stopEventLoopThread() { SDL_mutexP(finishedMutex); setFinished(1); SDL_mutexV(finishedMutex); if (running) { SDL_WaitThread(eventLoopThread, NULL); running = 0; } } uint32_t Protocol::getThreadId() { return SDL_GetThreadID(eventLoopThread); } bool Protocol::isFinished() { bool isFinished; SDL_mutexP(finishedMutex); isFinished = threadsFinished[getThreadId()]; SDL_mutexV(finishedMutex); return isFinished; } void Protocol::setFinished(bool fin) { uint32_t threadId = getThreadId(); if (! threadId) return; SDL_mutexP(finishedMutex); threadsFinished[threadId] = fin; SDL_mutexV(finishedMutex); } }
#include <iostream> #include <SDL/SDL.h> #include <SDL/SDL_thread.h> #include <SDL_net.h> #include <json/writer.h> #include <json/reader.h> #include <json/value.h> #include <grids/define.h> #include <grids/protocol.h> namespace Grids { void Protocol::setEventCallback(gevent_callback_t cb, void *userData) { eventCallback = cb; eventCallbackUserData = userData; } void Protocol::setConnectedCallback(gevent_callback_t cb, void *userData) { connectedCallback = cb; connectedCallbackUserData = userData; } int runEventLoopThreadEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->runEventLoop(); return 0; } /* void *dispatchEventEntryPoint(void *arg) { Protocol *gp = (Protocol *)arg; gp->dispatchEvent(); } */ Protocol::Protocol() { sock = 0; finishedMutex = SDL_CreateMutex(); running = 0; connectedCallback = NULL; } Protocol::~Protocol() { SDL_DestroyMutex(finishedMutex); } bool Protocol::connectToNode(const char *address) { IPaddress ip; if (SDLNet_ResolveHost(&ip, (char *)address, GRIDS_PORT) == -1) { printf("Could not resolve hostname %s: %s\n", address, SDLNet_GetError()); return 0; } sock = SDLNet_TCP_Open(&ip); if (! sock) { printf("Failed to connect to host %s: %s\n", address, SDLNet_GetError()); return 0; } // hooray we are connnected! initialize protocol sendProtocolInitiationString(); return 1; } void Protocol::sendProtocolInitiationString() { protocolWrite("==Grids/1.0/JSON"); } int Protocol::protocolWrite(const char *str) { if (! sock) { std::cerr << "No socket exists but Protocol::protocolWrite was called\n"; return -1; } uint32_t len = strlen(str); unsigned int outstr_len = len + 4; char *outstr = (char *)malloc(outstr_len); SDLNet_Write32(len, outstr); memcpy((outstr + 4), str, len); int ret = SDLNet_TCP_Send(sock, outstr, outstr_len); free(outstr); if (ret != outstr_len) { printf("SDLNet_TCP_Send: %s\n", SDLNet_GetError()); // It may be good to disconnect sock because it is likely invalid now. } return ret; } void Protocol::closeConnection() { SDLNet_TCP_Close(sock); } std::string Protocol::stringifyMap(gridsmap_t *m) { Json::FastWriter *writer = new Json::FastWriter(); Json::Value root = mapToJsonValue(m); return writer->write(root); } void Protocol::sendRequest(std::string evt) { sendRequest(evt, NULL); } void Protocol::sendRequest(std::string evt, gridsmap_t *args) { if (evt.empty()) return; if (args == NULL) { args = new gridsmap_t(); } const static std::string methodkey = "_method"; (*args)[methodkey] = evt; std::string msg = stringifyMap(args); protocolWrite(msg.c_str()); } Json::Value Protocol::mapToJsonValue(gridsmap_t *m) { giterator mapIterator; Json::Value jsonVal; for(mapIterator = m->begin(); mapIterator != m->end(); mapIterator++) { gridskey_t key = mapIterator->first; gridsval_t val = mapIterator->second; jsonVal[key] = val; } return jsonVal; } void Protocol::runEventLoop() { int bytesRead, socketReady; uint32_t incomingLength; char *buf; char *bufIncoming; setFinished(0); // create a socket set consisting of our socket, so that we can poll for data SDLNet_SocketSet sockSet = SDLNet_AllocSocketSet(1); int numused = SDLNet_TCP_AddSocket(sockSet, sock); if(numused == -1) { printf("SDLNet_AddSocket: %s\n", SDLNet_GetError()); SDLNet_FreeSocketSet(sockSet); return; } while (! isFinished() && sock) { socketReady = SDLNet_CheckSockets(sockSet, 1000); if (socketReady == -1) { printf("Error in SDLNet_CheckSockets: %s\n", SDLNet_GetError()); //most of the time this is a system error, where perror might help. perror("SDLNet_CheckSockets"); break; } if (socketReady != 1) { // nothing to read continue; } // read in 4 byte length of message bytesRead = SDLNet_TCP_Recv(sock, &incomingLength, 4); if (bytesRead <= 0) { std::cerr << "Socket read error " << bytesRead << ": " << SDLNet_GetError() << "\n"; continue; } incomingLength = SDLNet_Read32(&incomingLength); if (bytesRead != 4) { // socket broken most likely std::cerr << "failed to read from socket\n"; // break; continue; } if (incomingLength > 1024 * 1024 * 1024) { // not going to read in more than a gig, f that std::cerr << "Got incoming message size: " << incomingLength << ". Skipping\n"; continue; } // TODO: run in seperate thread // allocate space for incoming message + null byte buf = (char *)malloc(incomingLength + 1); std::cout << "incoming: " << incomingLength << "\n"; uint32_t bytesRemaining = incomingLength; bufIncoming = buf; do { bytesRead = SDLNet_TCP_Recv(sock, bufIncoming, bytesRemaining); if (bytesRead > 0) { bytesRemaining -= bytesRead; bufIncoming += bytesRead; } } while ((bytesRead > 0) && bytesRemaining && ! isFinished()); buf[incomingLength] = '\0'; if (bytesRead == -1) { // o snap read error std::cerr << "Socket read error: " << bytesRead << "\n"; free(buf); break; } if (bytesRead == 0) { // not chill std::cerr << "Didn't read any data when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } if (bytesRead != incomingLength) { std::cerr << "Only read " << bytesRead << " bytes when expecting message of " << incomingLength << " bytes\n"; free(buf); continue; } // TODO: run in seperate thread std::string msg = buf; handleMessage(msg); free(buf); } SDLNet_FreeSocketSet(sockSet); } void Protocol::handleMessage(std::string &msg) { if (msg.size() < 2) return; // obv. bogus if (msg.find("==", 0, 2) == 0) { // protocol initiation message if (connectedCallback) connectedCallback(this, NULL, connectedCallbackUserData); } else if (msg.find("--", 0, 2) == 0) { // encrypted protocol message } else { // assume this is json for now Json::Value root = parseJson(msg); // FIXME: this is slow and lame //gridsmap_t rootMap = jsonToMap(root); Event *evt = new Event(root["_method"].asString(), root); eventCallback(this, evt, eventCallbackUserData); delete evt; } } gridsmap_t Protocol::jsonToMap(Json::Value &root) { // ghetto, should fix in the future Json::Value::Members memberList = root.getMemberNames(); std::vector<std::string>::iterator iter; gridsmap_t outMap; for (iter = memberList.begin(); iter != memberList.end(); iter++) { Json::Value val = root[*iter]; outMap[*iter] = val; } return outMap; } Json::Value Protocol::parseJson(std::string &msg) { Json::Value root; Json::Reader reader; if (reader.parse(msg, root)) return root; std::cerr << "Could not parse JSON: " << msg << "\n"; return Json::Value(0); } int Protocol::runEventLoopThreaded() { SDL_mutexP(finishedMutex); eventLoopThread = SDL_CreateThread(runEventLoopThreadEntryPoint, this); uint32_t threadId = SDL_GetThreadID(eventLoopThread); threadsFinished[threadId] = 0; SDL_mutexV(finishedMutex); return 0; } void Protocol::stopEventLoopThread() { setFinished(1); if (running) { SDL_WaitThread(eventLoopThread, NULL); running = 0; } } uint32_t Protocol::getThreadId() { return SDL_ThreadID(); } bool Protocol::isFinished() { bool isFinished; SDL_mutexP(finishedMutex); isFinished = threadsFinished[getThreadId()]; SDL_mutexV(finishedMutex); return isFinished; } void Protocol::setFinished(bool fin) { uint32_t threadId = getThreadId(); if (! threadId) return; SDL_mutexP(finishedMutex); threadsFinished[threadId] = fin; SDL_mutexV(finishedMutex); } }
fix some protocol.cpp stuff, including getting the current threadid in a safer fashion and polling for socket data more correctly
fix some protocol.cpp stuff, including getting the current threadid in a safer fashion and polling for socket data more correctly
C++
bsd-3-clause
revmischa/grids,revmischa/grids
0daedb772be0be8e86ea2639ab33893b3f6db679
thrust/system/cuda/detail/memory.inl
thrust/system/cuda/detail/memory.inl
/* * Copyright 2008-2011 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. */ #include <thrust/detail/config.h> #include <thrust/system/cuda/memory.h> #include <limits> #include <cuda_runtime_api.h> #include <thrust/system/cuda_error.h> #include <thrust/system/detail/bad_alloc.h> namespace thrust { namespace detail { namespace backend { namespace cuda { // XXX malloc should be moved into thrust::system::cuda::detail thrust::system::cuda::pointer<void> malloc(tag, std::size_t n) { void *result = 0; cudaError_t error = cudaMalloc(reinterpret_cast<void**>(&result), n); if(error) { throw thrust::system::detail::bad_alloc(thrust::system::cuda_category().message(error).c_str()); } // end if return thrust::system::cuda::pointer<void>(result); } // end malloc() // XXX free should be moved into thrust::system::cuda::detail void free(tag, thrust::system::cuda::pointer<void> ptr) { cudaError_t error = cudaFree(ptr.get()); if(error) { throw thrust::system_error(error, thrust::cuda_category()); } // end error } // end free() } // end cuda } // end backend } // end detail namespace system { namespace cuda { template<typename T> template<typename OtherT> reference<T> & reference<T> ::operator=(const reference<OtherT> &other) { return super_t::operator=(other); } // end reference::operator=() template<typename T> reference<T> & reference<T> ::operator=(const value_type &x) { return super_t::operator=(x); } // end reference::operator=() template<typename T> __host__ __device__ void swap(reference<T> &a, reference<T> &b) { a.swap(b); } // end swap() } // end cuda } // end system namespace detail { // XXX iterator_facade tries to instantiate the Reference // type when computing the answer to is_convertible<Reference,Value> // we can't do that at that point because reference // is not complete // WAR the problem by specializing is_convertible template<typename T> struct is_convertible<thrust::cuda::reference<T>, T> : thrust::detail::true_type {}; namespace backend { // specialize dereference_result and overload dereference template<typename> struct dereference_result; template<typename T> struct dereference_result<thrust::cuda::pointer<T> > { typedef T& type; }; // end dereference_result template<typename T> struct dereference_result<thrust::cuda::pointer<const T> > { typedef const T& type; }; // end dereference_result template<typename T> typename dereference_result< thrust::cuda::pointer<T> >::type dereference(thrust::cuda::pointer<T> ptr) { return *ptr.get(); } // end dereference() template<typename T, typename IndexType> typename dereference_result< thrust::cuda::pointer<T> >::type dereference(thrust::cuda::pointer<T> ptr, IndexType n) { return ptr.get()[n]; } // end dereference() } // end backend } // end detail } // end thrust
/* * Copyright 2008-2011 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. */ #include <thrust/detail/config.h> #include <thrust/system/cuda/memory.h> #include <limits> #include <cuda_runtime_api.h> #include <thrust/system/cuda_error.h> #include <thrust/system/detail/bad_alloc.h> namespace thrust { namespace detail { namespace backend { namespace cuda { // XXX malloc should be moved into thrust::system::cuda::detail thrust::system::cuda::pointer<void> malloc(tag, std::size_t n) { void *result = 0; cudaError_t error = cudaMalloc(reinterpret_cast<void**>(&result), n); if(error) { throw thrust::system::detail::bad_alloc(thrust::system::cuda_category().message(error).c_str()); } // end if return thrust::system::cuda::pointer<void>(result); } // end malloc() // XXX free should be moved into thrust::system::cuda::detail void free(tag, thrust::system::cuda::pointer<void> ptr) { cudaError_t error = cudaFree(ptr.get()); if(error) { throw thrust::system_error(error, thrust::cuda_category()); } // end error } // end free() } // end cuda } // end backend } // end detail namespace system { namespace cuda { template<typename T> template<typename OtherT> reference<T> & reference<T> ::operator=(const reference<OtherT> &other) { return super_t::operator=(other); } // end reference::operator=() template<typename T> reference<T> & reference<T> ::operator=(const value_type &x) { return super_t::operator=(x); } // end reference::operator=() template<typename T> __host__ __device__ void swap(reference<T> &a, reference<T> &b) { a.swap(b); } // end swap() pointer<void> malloc(std::size_t n) { return thrust::detail::backend::cuda::malloc(tag(), n); } // end malloc() void free(pointer<void> ptr) { return thrust::detail::backend::cuda::free(tag(), ptr); } // end free() } // end cuda } // end system namespace detail { // XXX iterator_facade tries to instantiate the Reference // type when computing the answer to is_convertible<Reference,Value> // we can't do that at that point because reference // is not complete // WAR the problem by specializing is_convertible template<typename T> struct is_convertible<thrust::cuda::reference<T>, T> : thrust::detail::true_type {}; namespace backend { // specialize dereference_result and overload dereference template<typename> struct dereference_result; template<typename T> struct dereference_result<thrust::cuda::pointer<T> > { typedef T& type; }; // end dereference_result template<typename T> struct dereference_result<thrust::cuda::pointer<const T> > { typedef const T& type; }; // end dereference_result template<typename T> typename dereference_result< thrust::cuda::pointer<T> >::type dereference(thrust::cuda::pointer<T> ptr) { return *ptr.get(); } // end dereference() template<typename T, typename IndexType> typename dereference_result< thrust::cuda::pointer<T> >::type dereference(thrust::cuda::pointer<T> ptr, IndexType n) { return ptr.get()[n]; } // end dereference() } // end backend } // end detail } // end thrust
Add missing implementations of cuda::malloc & cuda::free.
Add missing implementations of cuda::malloc & cuda::free.
C++
apache-2.0
rdmenezes/thrust,bfurtaw/thrust,levendlee/thrust,rdmenezes/thrust,h1arshad/thrust,julianromera/thrust,Vishwa07/thrust,malenie/thrust,hemmingway/thrust,allendaicool/thrust,h1arshad/thrust,lishi0927/thrust,bfurtaw/thrust,julianromera/thrust,levendlee/thrust,google-code-export/thrust,bfurtaw/thrust,allendaicool/thrust,rdmenezes/thrust,malenie/thrust,google-code-export/thrust,malenie/thrust,lishi0927/thrust,malenie/thrust,UIKit0/thrust,google-code-export/thrust,julianromera/thrust,levendlee/thrust,Vishwa07/thrust,julianromera/thrust,google-code-export/thrust,h1arshad/thrust,allendaicool/thrust,UIKit0/thrust,rdmenezes/thrust,hemmingway/thrust,Vishwa07/thrust,levendlee/thrust,h1arshad/thrust,hemmingway/thrust,bfurtaw/thrust,Vishwa07/thrust,lishi0927/thrust,UIKit0/thrust,allendaicool/thrust,hemmingway/thrust,lishi0927/thrust,UIKit0/thrust
9a4bdd734b215dab03e0385f4c6fb5409651e41e
case_studies/remote_push.hpp
case_studies/remote_push.hpp
// Copyright (c) 2014-2016 Michael J. Sullivan // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file. #ifndef REMOTE_PUSH #define REMOTE_PUSH #include <atomic> #include <cstdio> #include <unistd.h> #define REMOTE_PUSH_MPROTECT 0 #ifdef REMOTE_PUSH_MPROTECT #include <sys/mman.h> namespace rmclib { namespace remote_push { const int kMadeupPageSize = 4096; static struct DummyPage { alignas(kMadeupPageSize) char page[kMadeupPageSize]; DummyPage() { /* Lock the memory so it can't get paged out. If it gets paged * out, changing its protection won't accomplish anything. */ if (mlock(page, 1) < 0) std::terminate(); } /* Force a push using a TLB shootdown */ void forcePush() { /* Make the dummy page writable, then take it away. * We do this because there is really no need to TLB shootdown * when /adding/ permissions. */ if (mprotect(&this->page, 1, PROT_READ|PROT_WRITE) < 0 || mprotect(&this->page, 1, PROT_READ) < 0) { std::terminate(); } } } dummyPage; inline void placeholder() { std::atomic_signal_fence(std::memory_order_seq_cst); } inline void trigger() { dummyPage.forcePush(); } } } #else namespace rmclib { namespace remote_push { inline void placeholder() { std::atomic_thread_fence(std::memory_order_seq_cst); } inline void trigger() { std::atomic_thread_fence(std::memory_order_seq_cst); } } } #endif // Wrapper with more C++11y names namespace rmclib { namespace remote_thread_fence { // This nominally takes a memory order, but we always just // force a full fence. inline void placeholder(std::memory_order order) { rmclib::remote_push::placeholder(); } inline void trigger() { rmclib::remote_push::trigger(); } } } #endif
// Copyright (c) 2014-2016 Michael J. Sullivan // Use of this source code is governed by an MIT-style license that can be // found in the LICENSE file. #ifndef REMOTE_PUSH #define REMOTE_PUSH #include <atomic> #include <cstdio> #include <unistd.h> #define REMOTE_PUSH_MPROTECT 0 #if REMOTE_PUSH_MPROTECT #include <sys/mman.h> namespace rmclib { namespace remote_push { const int kMadeupPageSize = 4096; static struct DummyPage { alignas(kMadeupPageSize) char page[kMadeupPageSize]; DummyPage() { /* Lock the memory so it can't get paged out. If it gets paged * out, changing its protection won't accomplish anything. */ if (mlock(page, 1) < 0) std::terminate(); } /* Force a push using a TLB shootdown */ void forcePush() { /* Make the dummy page writable, then take it away. * We do this because there is really no need to TLB shootdown * when /adding/ permissions. */ if (mprotect(&this->page, 1, PROT_READ|PROT_WRITE) < 0 || mprotect(&this->page, 1, PROT_READ) < 0) { std::terminate(); } } } dummyPage; inline void placeholder() { // clang on arm generates a dmb for an atomic_signal_fence, which // kind of defeats the whole fucking purpose, huh? //std::atomic_signal_fence(std::memory_order_seq_cst); __asm__ __volatile__("":::"memory"); } inline void trigger() { dummyPage.forcePush(); } } } #else namespace rmclib { namespace remote_push { inline void placeholder() { std::atomic_thread_fence(std::memory_order_seq_cst); } inline void trigger() { std::atomic_thread_fence(std::memory_order_seq_cst); } } } #endif // Wrapper with more C++11y names namespace rmclib { namespace remote_thread_fence { // This nominally takes a memory order, but we always just // force a full fence. inline void placeholder(std::memory_order order) { rmclib::remote_push::placeholder(); } inline void trigger() { rmclib::remote_push::trigger(); } } } #endif
Fix total bustage in remote_push.
Fix total bustage in remote_push. Two really stupid problems in remote_push: 1) I'm an idiot and you definitely can't use #ifdef to test a macro that you disable by setting to zero. 2) clang is an idiot and emits a dmb for atomic_signal_fence even though not emitting a dmb is literally the entire point of atomic_signal_fence's existence. This meant that even though remote pushes were supposed to be turned off, we were still generating them but also still doing the read-side dmbs. Asdf.
C++
mit
msullivan/rmc-compiler,msullivan/rmc-compiler,msullivan/rmc-compiler,msullivan/rmc-compiler,msullivan/rmc-compiler,msullivan/rmc-compiler
ba33cdfc11d88afb4c2cad5862931e488ca4d365
compiler/ipe/ipeDriver.cpp
compiler/ipe/ipeDriver.cpp
/* * Copyright 2004-2015 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "ipe.h" #include "ipeReplaceVariables.h" #include "ipeResolve.h" #include "ipeAssignLocations.h" #include "ipeInlinePrimitives.h" #include "ipeEvaluate.h" #include "AstDumpToNode.h" #include "log.h" #include "passes.h" #include "stmt.h" struct PassInfo { const char* name; void (*function)(); }; static PassInfo sPassList[] = { { "parse", parse }, { "replaceVariables", ipeReplaceVariables }, { "resolve", ipeResolve }, { "assignLocations", ipeAssignLocations }, { "inlinePrimitives", ipeInlinePrimitives }, { "evaluate", ipeEvaluate } }; void ipeRun() { size_t passListSize = sizeof(sPassList) / sizeof(sPassList[0]); setupLogfiles(); for (size_t i = 0; i < passListSize; i++) { sPassList[i].function(); AstDumpToNode::view(sPassList[i].name, i + 1); } cleanAst(); destroyAst(); teardownLogfiles(); }
/* * Copyright 2004-2015 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "ipe.h" #include "ipeReplaceVariables.h" #include "ipeResolve.h" #include "ipeCheckReturn.h" #include "ipeInlinePrimitives.h" #include "ipeAssignLocations.h" #include "ipeEvaluate.h" #include "AstDumpToNode.h" #include "log.h" #include "passes.h" #include "stmt.h" struct PassInfo { const char* name; void (*function)(); }; static PassInfo sPassList[] = { { "parse", parse }, { "replaceVariables", ipeReplaceVariables }, { "resolve", ipeResolve }, { "inlinePrimitives", ipeInlinePrimitives }, { "checkReturn", ipeCheckReturn }, { "assignLocations", ipeAssignLocations }, { "evaluate", ipeEvaluate } }; void ipeRun() { size_t passListSize = sizeof(sPassList) / sizeof(sPassList[0]); setupLogfiles(); for (size_t i = 0; i < passListSize; i++) { sPassList[i].function(); AstDumpToNode::view(sPassList[i].name, i + 1); } cleanAst(); destroyAst(); teardownLogfiles(); }
Update driver for new pass
Update driver for new pass
C++
apache-2.0
hildeth/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,hildeth/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,hildeth/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,hildeth/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel
7e706eb266b834e6ff64e3029dd1ae6ff9f8a73c
hardware/msp430/cores/msp430/WMath.cpp
hardware/msp430/cores/msp430/WMath.cpp
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ 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$ */ extern "C" { #include "stdlib.h" } /* * Internal srandom() and random() implmentation, * a simple pseudo-random number generator is the Multiply-with-carry method invented by George Marsaglia. * It is computationally fast and has good (albeit not cryptographically strong) * From: http://en.wikipedia.org/wiki/Random_number_generation#Computational_methods */ static long m_w =123; /* must not be zero */ static long m_z =98765432; /* must not be zero */ static void srandom(long n) { m_w = 123 ^ n; m_z = 98765432 ^ n-1; if ( m_w == 0 ) m_w = 123; if ( m_z == 0 ) m_z = 98765432; } static unsigned long random() { m_z = 36969 * (m_z & 65535) + (m_z >> 16); m_w = 18000 * (m_w & 65535) + (m_w >> 16); return (m_z << 16) + m_w; /* 32-bit result */ } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
/* -*- mode: jde; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* Part of the Wiring project - http://wiring.org.co Copyright (c) 2004-06 Hernando Barragan Modified 13 August 2006, David A. Mellis for Arduino - http://www.arduino.cc/ 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$ */ extern "C" { #include "stdlib.h" /* Using interal random and srandom in file random.c * until msp430-libc adds supports for random and srandom */ extern long random(void); extern void srandom(unsigned long __seed); } void randomSeed(unsigned int seed) { if (seed != 0) { srandom(seed); } } long random(long howbig) { if (howbig == 0) { return 0; } return random() % howbig; } long random(long howsmall, long howbig) { if (howsmall >= howbig) { return howsmall; } long diff = howbig - howsmall; return random(diff) + howsmall; } long map(long x, long in_min, long in_max, long out_min, long out_max) { return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; } unsigned int makeWord(unsigned int w) { return w; } unsigned int makeWord(unsigned char h, unsigned char l) { return (h << 8) | l; }
Add random() and randomSeed() Use local random.c until msp430-libc supports random() and srandom()
Add random() and randomSeed() Use local random.c until msp430-libc supports random() and srandom()
C++
lgpl-2.1
i--storm/Energia,dvdvideo1234/Energia,DavidUser/Energia,meanbot/Energia,cevatbostancioglu/Energia,i--storm/Energia,croberts15/Energia,jadonk/Energia,danielohh/Energia,croberts15/Energia,croberts15/Energia,pasky/Energia,brianonn/Energia,qtonthat/Energia,dvdvideo1234/Energia,qtonthat/Energia,pasky/Energia,NoPinky/Energia,martianmartin/Energia,dvdvideo1234/Energia,martianmartin/Energia,croberts15/Energia,DavidUser/Energia,bobintornado/Energia,DavidUser/Energia,cevatbostancioglu/Energia,NoPinky/Energia,DavidUser/Energia,radiolok/Energia,danielohh/Energia,zacinaction/Energia,croberts15/Energia,DavidUser/Energia,NoPinky/Energia,pasky/Energia,bobintornado/Energia,bobintornado/Energia,pasky/Energia,sanyaade-iot/Energia,dvdvideo1234/Energia,meanbot/Energia,bobintornado/Energia,i--storm/Energia,NoPinky/Energia,meanbot/Energia,danielohh/Energia,battosai30/Energia,vigneshmanix/Energia,battosai30/Energia,brianonn/Energia,i--storm/Energia,zacinaction/Energia,qtonthat/Energia,martianmartin/Energia,jadonk/Energia,battosai30/Energia,danielohh/Energia,vigneshmanix/Energia,qtonthat/Energia,vigneshmanix/Energia,meanbot/Energia,bobintornado/Energia,jadonk/Energia,brianonn/Energia,battosai30/Energia,NoPinky/Energia,sanyaade-iot/Energia,i--storm/Energia,zacinaction/Energia,radiolok/Energia,bobintornado/Energia,DavidUser/Energia,qtonthat/Energia,danielohh/Energia,qtonthat/Energia,zacinaction/Energia,radiolok/Energia,vigneshmanix/Energia,radiolok/Energia,sanyaade-iot/Energia,danielohh/Energia,vigneshmanix/Energia,croberts15/Energia,vigneshmanix/Energia,cevatbostancioglu/Energia,sanyaade-iot/Energia,dvdvideo1234/Energia,sanyaade-iot/Energia,i--storm/Energia,martianmartin/Energia,brianonn/Energia,dvdvideo1234/Energia,NoPinky/Energia,jadonk/Energia,qtonthat/Energia,brianonn/Energia,sanyaade-iot/Energia,jadonk/Energia,meanbot/Energia,cevatbostancioglu/Energia,battosai30/Energia,bobintornado/Energia,danielohh/Energia,sanyaade-iot/Energia,cevatbostancioglu/Energia,zacinaction/Energia,NoPinky/Energia,DavidUser/Energia,zacinaction/Energia,cevatbostancioglu/Energia,radiolok/Energia,cevatbostancioglu/Energia,vigneshmanix/Energia,radiolok/Energia,i--storm/Energia,martianmartin/Energia,battosai30/Energia,dvdvideo1234/Energia,jadonk/Energia,radiolok/Energia,battosai30/Energia,martianmartin/Energia,pasky/Energia,brianonn/Energia,martianmartin/Energia,meanbot/Energia,croberts15/Energia,brianonn/Energia,pasky/Energia
7e290fb96530bd14c4fb6f9f40eb692af5e2e21c
test/benchmark_test.cc
test/benchmark_test.cc
#include "benchmark/benchmark.h" #include <assert.h> #include <math.h> #include <stdint.h> #include <iostream> #include <limits> #include <list> #include <map> #include <mutex> #include <set> #include <sstream> #include <string> #include <vector> namespace { int ATTRIBUTE_NOINLINE Factorial(uint32_t n) { return (n == 1) ? 1 : n * Factorial(n - 1); } double CalculatePi(int depth) { double pi = 0.0; for (int i = 0; i < depth; ++i) { double numerator = static_cast<double>(((i % 2) * 2) - 1); double denominator = static_cast<double>((2 * i) - 1); pi += numerator / denominator; } return (pi - 1.0) * 4; } std::set<int> ConstructRandomSet(int size) { std::set<int> s; for (int i = 0; i < size; ++i) s.insert(i); return s; } std::mutex test_vector_mu; std::vector<int>* test_vector = nullptr; } // end namespace #ifdef DEBUG static void BM_Factorial(benchmark::State& state) { int fac_42 = 0; while (state.KeepRunning()) fac_42 = Factorial(8); // Prevent compiler optimizations CHECK(fac_42 != std::numeric_limits<int>::max()); } BENCHMARK(BM_Factorial); #endif static void BM_CalculatePiRange(benchmark::State& state) { double pi = 0.0; while (state.KeepRunning()) pi = CalculatePi(state.range_x()); std::stringstream ss; ss << pi; state.SetLabel(ss.str()); } BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); static void BM_CalculatePi(benchmark::State& state) { static const int depth = 1024; double pi ATTRIBUTE_UNUSED = 0.0; while (state.KeepRunning()) { pi = CalculatePi(depth); } } BENCHMARK(BM_CalculatePi)->Threads(8); BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); static void BM_SetInsert(benchmark::State& state) { while (state.KeepRunning()) { state.PauseTiming(); std::set<int> data = ConstructRandomSet(state.range_x()); state.ResumeTiming(); for (int j = 0; j < state.range_y(); ++j) data.insert(rand()); } state.SetItemsProcessed(state.iterations() * state.range_y()); state.SetBytesProcessed(state.iterations() * state.range_y() * sizeof(int)); } BENCHMARK(BM_SetInsert)->RangePair(1<<10,8<<10, 1,10); template<typename Q> static void BM_Sequential(benchmark::State& state) { typename Q::value_type v = 42; while (state.KeepRunning()) { Q q; for (int i = state.range_x(); --i; ) q.push_back(v); } const int64_t items_processed = static_cast<int64_t>(state.iterations()) * state.range_x(); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * sizeof(v)); } BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>)->Range(1 << 0, 1 << 10); BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10); static void BM_StringCompare(benchmark::State& state) { std::string s1(state.range_x(), '-'); std::string s2(state.range_x(), '-'); int r = 0; while (state.KeepRunning()) r |= s1.compare(s2); // Prevent compiler optimizations assert(r != std::numeric_limits<int>::max()); } BENCHMARK(BM_StringCompare)->Range(1, 1<<20); static void BM_SetupTeardown(benchmark::State& state) { if (state.thread_index == 0) { // No need to lock test_vector_mu here as this is running single-threaded. test_vector = new std::vector<int>(); } int i = 0; while (state.KeepRunning()) { std::lock_guard<std::mutex> l(test_vector_mu); if (i%2 == 0) test_vector->push_back(i); else test_vector->pop_back(); ++i; } if (state.thread_index == 0) { delete test_vector; } } BENCHMARK(BM_SetupTeardown)->ThreadPerCpu(); static void BM_LongTest(benchmark::State& state) { double tracker = 0.0; while (state.KeepRunning()) for (int i = 0; i < state.range_x(); ++i) tracker += i; assert(tracker != 0.0); } BENCHMARK(BM_LongTest)->Range(1<<16,1<<28); class TestReporter : public benchmark::internal::ConsoleReporter { public: virtual bool ReportContext(const Context& context) const { return ConsoleReporter::ReportContext(context); }; virtual void ReportRuns(const std::vector<Run>& report) const { ++count_; ConsoleReporter::ReportRuns(report); }; TestReporter() : count_(0) {} virtual ~TestReporter() {} int GetCount() const { return count_; } private: mutable size_t count_; }; int main(int argc, const char* argv[]) { benchmark::Initialize(&argc, argv); assert(Factorial(8) == 40320); assert(CalculatePi(1) == 0.0); TestReporter test_reporter; benchmark::RunSpecifiedBenchmarks(&test_reporter); // Make sure we ran all of the tests const size_t count = test_reporter.GetCount(); const size_t expected = (argc == 2) ? std::stoul(argv[1]) : count; if (count != expected) { std::cerr << "ERROR: Expected " << expected << " tests to be ran but only " << count << " completed" << std::endl; return -1; } }
#include "benchmark/benchmark.h" #include <assert.h> #include <math.h> #include <stdint.h> #include <iostream> #include <limits> #include <list> #include <map> #include <mutex> #include <set> #include <sstream> #include <string> #include <vector> namespace { #ifdef DEBUG int ATTRIBUTE_NOINLINE Factorial(uint32_t n) { return (n == 1) ? 1 : n * Factorial(n - 1); } #endif double CalculatePi(int depth) { double pi = 0.0; for (int i = 0; i < depth; ++i) { double numerator = static_cast<double>(((i % 2) * 2) - 1); double denominator = static_cast<double>((2 * i) - 1); pi += numerator / denominator; } return (pi - 1.0) * 4; } std::set<int> ConstructRandomSet(int size) { std::set<int> s; for (int i = 0; i < size; ++i) s.insert(i); return s; } std::mutex test_vector_mu; std::vector<int>* test_vector = nullptr; } // end namespace #ifdef DEBUG static void BM_Factorial(benchmark::State& state) { int fac_42 = 0; while (state.KeepRunning()) fac_42 = Factorial(8); // Prevent compiler optimizations CHECK(fac_42 != std::numeric_limits<int>::max()); } BENCHMARK(BM_Factorial); #endif static void BM_CalculatePiRange(benchmark::State& state) { double pi = 0.0; while (state.KeepRunning()) pi = CalculatePi(state.range_x()); std::stringstream ss; ss << pi; state.SetLabel(ss.str()); } BENCHMARK_RANGE(BM_CalculatePiRange, 1, 1024 * 1024); static void BM_CalculatePi(benchmark::State& state) { static const int depth = 1024; double pi ATTRIBUTE_UNUSED = 0.0; while (state.KeepRunning()) { pi = CalculatePi(depth); } } BENCHMARK(BM_CalculatePi)->Threads(8); BENCHMARK(BM_CalculatePi)->ThreadRange(1, 32); BENCHMARK(BM_CalculatePi)->ThreadPerCpu(); static void BM_SetInsert(benchmark::State& state) { while (state.KeepRunning()) { state.PauseTiming(); std::set<int> data = ConstructRandomSet(state.range_x()); state.ResumeTiming(); for (int j = 0; j < state.range_y(); ++j) data.insert(rand()); } state.SetItemsProcessed(state.iterations() * state.range_y()); state.SetBytesProcessed(state.iterations() * state.range_y() * sizeof(int)); } BENCHMARK(BM_SetInsert)->RangePair(1<<10,8<<10, 1,10); template<typename Q> static void BM_Sequential(benchmark::State& state) { typename Q::value_type v = 42; while (state.KeepRunning()) { Q q; for (int i = state.range_x(); --i; ) q.push_back(v); } const int64_t items_processed = static_cast<int64_t>(state.iterations()) * state.range_x(); state.SetItemsProcessed(items_processed); state.SetBytesProcessed(items_processed * sizeof(v)); } BENCHMARK_TEMPLATE(BM_Sequential, std::vector<int>)->Range(1 << 0, 1 << 10); BENCHMARK_TEMPLATE(BM_Sequential, std::list<int>)->Range(1 << 0, 1 << 10); static void BM_StringCompare(benchmark::State& state) { std::string s1(state.range_x(), '-'); std::string s2(state.range_x(), '-'); int r = 0; while (state.KeepRunning()) r |= s1.compare(s2); // Prevent compiler optimizations assert(r != std::numeric_limits<int>::max()); } BENCHMARK(BM_StringCompare)->Range(1, 1<<20); static void BM_SetupTeardown(benchmark::State& state) { if (state.thread_index == 0) { // No need to lock test_vector_mu here as this is running single-threaded. test_vector = new std::vector<int>(); } int i = 0; while (state.KeepRunning()) { std::lock_guard<std::mutex> l(test_vector_mu); if (i%2 == 0) test_vector->push_back(i); else test_vector->pop_back(); ++i; } if (state.thread_index == 0) { delete test_vector; } } BENCHMARK(BM_SetupTeardown)->ThreadPerCpu(); static void BM_LongTest(benchmark::State& state) { double tracker = 0.0; while (state.KeepRunning()) for (int i = 0; i < state.range_x(); ++i) tracker += i; assert(tracker != 0.0); } BENCHMARK(BM_LongTest)->Range(1<<16,1<<28); class TestReporter : public benchmark::internal::ConsoleReporter { public: virtual bool ReportContext(const Context& context) const { return ConsoleReporter::ReportContext(context); }; virtual void ReportRuns(const std::vector<Run>& report) const { ++count_; ConsoleReporter::ReportRuns(report); }; TestReporter() : count_(0) {} virtual ~TestReporter() {} int GetCount() const { return count_; } private: mutable size_t count_; }; int main(int argc, const char* argv[]) { benchmark::Initialize(&argc, argv); assert(Factorial(8) == 40320); assert(CalculatePi(1) == 0.0); TestReporter test_reporter; benchmark::RunSpecifiedBenchmarks(&test_reporter); // Make sure we ran all of the tests const size_t count = test_reporter.GetCount(); const size_t expected = (argc == 2) ? std::stoul(argv[1]) : count; if (count != expected) { std::cerr << "ERROR: Expected " << expected << " tests to be ran but only " << count << " completed" << std::endl; return -1; } }
Fix release builds
Fix release builds
C++
apache-2.0
everbase/benchmark,LepelTsmok/benchmark,everbase/benchmark,everbase/benchmark,google/benchmark,efcs/benchmark,nickhutchinson/benchmark-cxx03,chemhack/benchmark,chandlerc/benchmark,nickhutchinson/benchmark,chemhack/benchmark,disconnect3d/benchmark,bowlofstew/benchmark,gezidan/benchmark,nickhutchinson/benchmark,ntx-/benchmark,chandlerc/benchmark,subailong/benchmark,quantumsteve/benchmark,codygray/benchmark,xlqian/benchmark,chemhack/benchmark,nickhutchinson/benchmark,gezidan/benchmark,mockingbirdnest/benchmark,quantumsteve/benchmark,chemhack/benchmark,nickhutchinson/benchmark-cxx03,fuchsia-mirror/third_party-benchmark,codygray/benchmark,fuchsia-mirror/third_party-benchmark,subailong/benchmark,Photonomie/benchmark,bowlofstew/benchmark,gezidan/benchmark,eliben/benchmark,nickhutchinson/benchmark-cxx03,xlqian/benchmark,disconnect3d/benchmark,eliben/benchmark,quantumsteve/benchmark,chandlerc/benchmark,mockingbirdnest/benchmark,mockingbirdnest/benchmark,subailong/benchmark,Photonomie/benchmark,google/benchmark,nickhutchinson/benchmark,xlqian/benchmark,ntx-/benchmark,nickhutchinson/benchmark-cxx03,bowlofstew/benchmark,codygray/benchmark,gezidan/benchmark,chandlerc/benchmark,Photonomie/benchmark,LepelTsmok/benchmark,xlqian/benchmark,google/benchmark,ntx-/benchmark,LepelTsmok/benchmark,efcs/benchmark,LepelTsmok/benchmark,Photonomie/benchmark,disconnect3d/benchmark,everbase/benchmark,ntx-/benchmark,eliben/benchmark,eliben/benchmark,bowlofstew/benchmark,disconnect3d/benchmark,fuchsia-mirror/third_party-benchmark,mockingbirdnest/benchmark,efcs/benchmark,codygray/benchmark,subailong/benchmark,fuchsia-mirror/third_party-benchmark,quantumsteve/benchmark,efcs/benchmark
0909ffc26ee1b616ae2ee9ed44aed64243433f33
test/liblll/Parser.cpp
test/liblll/Parser.cpp
/* This file is part of solidity. solidity 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 3 of the License, or (at your option) any later version. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Unit tests for the LLL parser. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <liblll/Compiler.h> using namespace std; namespace dev { namespace lll { namespace test { namespace { bool successParse(std::string const& _source) { std::string ret = eth::parseLLL(_source); return ret.size() != 0; } std::string parse(std::string const& _source) { return eth::parseLLL(_source); } } BOOST_AUTO_TEST_SUITE(LLLParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "1"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_CASE(string) { char const* text = "\"string\""; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"("string")"); } BOOST_AUTO_TEST_CASE(symbol) { char const* text = "symbol"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); BOOST_CHECK(successParse("'symbol")); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); } BOOST_AUTO_TEST_CASE(decimals) { char const* text = "1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(1234)"); } BOOST_AUTO_TEST_CASE(hexadecimals) { char const* text = "0x1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(4660)"); BOOST_CHECK(!successParse("0x")); } BOOST_AUTO_TEST_CASE(sequence) { char const* text = "{ 1234 }"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ 1234 })"); } BOOST_AUTO_TEST_CASE(empty_sequence) { char const* text = "{}"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ })"); } BOOST_AUTO_TEST_CASE(mload) { char const* text = "@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@ 0)"); BOOST_CHECK(successParse("@0x0")); BOOST_CHECK(successParse("@symbol")); BOOST_CHECK(!successParse("@")); } BOOST_AUTO_TEST_CASE(sload) { char const* text = "@@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@@ 0)"); BOOST_CHECK(successParse("@@0x0")); BOOST_CHECK(successParse("@@symbol")); BOOST_CHECK(!successParse("@@")); } BOOST_AUTO_TEST_CASE(mstore) { char const* text = "[0]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([ 0 ] 0)"); BOOST_CHECK(successParse("[0] 0")); BOOST_CHECK(successParse("[0x0]:0x0")); BOOST_CHECK(successParse("[symbol]:symbol")); BOOST_CHECK(!successParse("[]")); BOOST_CHECK(!successParse("[0]")); } BOOST_AUTO_TEST_CASE(sstore) { char const* text = "[[0]]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([[ 0 ]] 0)"); BOOST_CHECK(successParse("[[0]] 0")); BOOST_CHECK(successParse("[[0x0]]:0x0")); BOOST_CHECK(successParse("[[symbol]]:symbol")); BOOST_CHECK(!successParse("[[]]")); BOOST_CHECK(!successParse("[[0x0]]")); } BOOST_AUTO_TEST_CASE(calldataload) { char const* text = "$0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"($ 0)"); BOOST_CHECK(successParse("$0x0")); BOOST_CHECK(successParse("$symbol")); BOOST_CHECK(!successParse("$")); } BOOST_AUTO_TEST_CASE(list) { char const* text = "( 1234 )"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(( 1234 ))"); BOOST_CHECK(successParse("( 1234 5467 )")); BOOST_CHECK(!successParse("()")); } BOOST_AUTO_TEST_CASE(macro_with_zero_args) { char const* text = "(def 'zeroargs () (asm INVALID))"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces
/* This file is part of solidity. solidity 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 3 of the License, or (at your option) any later version. solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>. */ /** * @author Alex Beregszaszi * @date 2016 * Unit tests for the LLL parser. */ #include <string> #include <memory> #include <boost/test/unit_test.hpp> #include <liblll/Compiler.h> using namespace std; namespace dev { namespace lll { namespace test { namespace { bool successParse(std::string const& _source) { std::string ret = eth::parseLLL(_source); return ret.size() != 0; } std::string parse(std::string const& _source) { return eth::parseLLL(_source); } } BOOST_AUTO_TEST_SUITE(LLLParser) BOOST_AUTO_TEST_CASE(smoke_test) { char const* text = "1"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_CASE(string) { char const* text = "\"string\""; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"("string")"); } BOOST_AUTO_TEST_CASE(symbol) { char const* text = "symbol"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); BOOST_CHECK(successParse("'symbol")); BOOST_CHECK_EQUAL(parse(text), R"(symbol)"); } BOOST_AUTO_TEST_CASE(decimals) { char const* text = "1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(1234)"); } BOOST_AUTO_TEST_CASE(hexadecimals) { char const* text = "0x1234"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(4660)"); BOOST_CHECK(!successParse("0x")); } BOOST_AUTO_TEST_CASE(sequence) { char const* text = "{ 1234 }"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ 1234 })"); } BOOST_AUTO_TEST_CASE(empty_sequence) { char const* text = "{}"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"({ })"); } BOOST_AUTO_TEST_CASE(mload) { char const* text = "@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@ 0)"); BOOST_CHECK(successParse("@0x0")); BOOST_CHECK(successParse("@symbol")); BOOST_CHECK(!successParse("@")); } BOOST_AUTO_TEST_CASE(sload) { char const* text = "@@0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(@@ 0)"); BOOST_CHECK(successParse("@@0x0")); BOOST_CHECK(successParse("@@symbol")); BOOST_CHECK(!successParse("@@")); } BOOST_AUTO_TEST_CASE(mstore) { char const* text = "[0]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([ 0 ] 0)"); BOOST_CHECK(successParse("[0] 0")); BOOST_CHECK(successParse("[0x0]:0x0")); BOOST_CHECK(successParse("[symbol]:symbol")); BOOST_CHECK(!successParse("[]")); BOOST_CHECK(!successParse("[0]")); } BOOST_AUTO_TEST_CASE(sstore) { char const* text = "[[0]]:0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"([[ 0 ]] 0)"); BOOST_CHECK(successParse("[[0]] 0")); BOOST_CHECK(successParse("[[0x0]]:0x0")); BOOST_CHECK(successParse("[[symbol]]:symbol")); BOOST_CHECK(!successParse("[[]]")); BOOST_CHECK(!successParse("[[0x0]]")); } BOOST_AUTO_TEST_CASE(calldataload) { char const* text = "$0"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"($ 0)"); BOOST_CHECK(successParse("$0x0")); BOOST_CHECK(successParse("$symbol")); BOOST_CHECK(!successParse("$")); } BOOST_AUTO_TEST_CASE(list) { char const* text = "( 1234 )"; BOOST_CHECK(successParse(text)); BOOST_CHECK_EQUAL(parse(text), R"(( 1234 ))"); BOOST_CHECK(successParse("( 1234 5467 )")); BOOST_CHECK(successParse("()")); } BOOST_AUTO_TEST_CASE(macro_with_zero_args) { char const* text = "(def 'zeroargs () (asm INVALID))"; BOOST_CHECK(successParse(text)); } BOOST_AUTO_TEST_SUITE_END() } } } // end namespaces
Fix the expectation about the parse
Fix the expectation about the parse
C++
mit
ruchevits/solidity,ruchevits/solidity,ruchevits/solidity,ruchevits/solidity
63d16531603f9baa35a177a81cbfb111580ffebb
include/mapnik/grid_vertex_adapter.hpp
include/mapnik/grid_vertex_adapter.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GRID_ADAPTERS_HPP #define MAPNIK_GRID_ADAPTERS_HPP #include <mapnik/vertex.hpp> #include <mapnik/image.hpp> #include <mapnik/image_util.hpp> #include <mapnik/geom_util.hpp> #include <mapnik/view_transform.hpp> #include "agg_rendering_buffer.h" #include "agg_pixfmt_gray.h" #include "agg_renderer_base.h" #include "agg_renderer_scanline.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_bin.h" namespace mapnik { namespace geometry { class spiral_iterator { public: spiral_iterator(int x, int y) : size_x(x), size_y(y), end_(std::max(x, y) * std::max(x, y)), i_(0), x_(0), y_(0) { } bool vertex(int * x, int * y) { while (i_ < end_) { int xp = x_ + size_x / 2; int yp = y_ + size_y / 2; if (std::abs(x_) <= std::abs(y_) && (x_ != y_ || x_ >= 0)) { x_ += ((y_ >= 0) ? 1 : -1); } else { y_ += ((x_ >= 0) ? -1 : 1); } ++i_; if (xp >= 0 && xp < size_x && yp >= 0 && yp < size_y) { *x = xp; *y = yp; return true; } } return false; } void rewind() { i_ = 0; x_ = 0; y_ = 0; } const int size_x, size_y; private: const int end_; int i_; int x_, y_; }; struct row_grid_iterator { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> row_grid_iterator( PathType & path, box2d<coord_type> const & envelope, coord_type dx, coord_type dy, view_transform const & vt) : center_(envelope.width() / 2.0, envelope.height() / 2.0), size_x_(std::ceil(vt.width() / dx)), size_y_(std::ceil(vt.height() / dy)), x_(0), y_(0) { } inline bool vertex(int * x, int * y) { for (; y_ < size_y_; ++y_, x_ = 0) { for (; x_ < size_x_; ) { *x = x_; *y = y_; ++x_; return true; } } return false; } inline void rewind() { x_ = 0; y_ = 0; } const coord2d_type center_; const int size_x_, size_y_; int x_, y_; }; struct spiral_grid_iterator { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> spiral_grid_iterator( PathType & path, box2d<coord_type> const & envelope, coord_type dx, coord_type dy, view_transform const & vt) : vt_(vt), center_(interior(path, envelope)), size_x_(std::ceil((vt.width() + std::abs((vt.width() / 2.0) - center_.x) * 2.0) / dx)), size_y_(std::ceil((vt.height() + std::abs((vt.height() / 2.0) - center_.y) * 2.0) / dy)), si_(size_x_, size_y_) { } template <typename PathType> coord2d_type interior(PathType & path, box2d<coord_type> const & envelope) const { coord2d_type interior; if (!label::interior_position(path, interior.x, interior.y)) { interior = envelope.center(); } vt_.forward(&interior.x, &interior.y); return interior; } inline bool vertex(int * x, int * y) { return si_.vertex(x, y); } inline void rewind() { si_.rewind(); } view_transform const & vt_; const coord2d_type center_; const int size_x_, size_y_; spiral_iterator si_; }; template <typename PathType, typename TransformType> class transform_path { public: using coord_type = double; transform_path(PathType & path, TransformType const & transform) : path_(path), transform_(transform) { } void rewind(unsigned) { path_.rewind(0); } unsigned vertex(coord_type * x, coord_type * y) { unsigned command = path_.vertex(x, y); if (command != mapnik::SEG_END) { transform_.forward(x, y); } return command; } private: PathType & path_; TransformType const & transform_; }; template <typename GridIterator> struct grid_vertex_adapter { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> grid_vertex_adapter(PathType & path, coord_type dx, coord_type dy) : grid_vertex_adapter(path, dx, dy, mapnik::envelope(path)) { } void rewind(unsigned) { gi_.rewind(); } unsigned vertex(coord_type * x, coord_type * y) { int pix_x, pix_y; while (gi_.vertex(&pix_x, &pix_y)) { pix_x = gi_.center_.x + static_cast<double>(pix_x - gi_.size_x_ / 2) * dx_; pix_y = gi_.center_.y + static_cast<double>(pix_y - gi_.size_y_ / 2) * dy_; if (pix_x >= 0 && pix_x < img_.width() && pix_y >= 0 && pix_y < img_.height() && get_pixel<image_gray8::pixel_type>(img_, pix_x, pix_y)) { *x = pix_x; *y = pix_y; vt_.backward(x, y); return mapnik::SEG_MOVETO; } } return mapnik::SEG_END; } geometry_types type() const { return geometry_types::MultiPoint; } protected: template <typename PathType> grid_vertex_adapter( PathType & path, coord_type dx, coord_type dy, box2d<coord_type> envelope) : scale_(get_scale(envelope)), dx_(dx * scale_), dy_(dy * scale_), img_(create_bitmap(envelope)), vt_(img_.width(), img_.height(), envelope), gi_(path, envelope, dx_, dy_, vt_) { transform_path<PathType, view_transform> tp(path, vt_); tp.rewind(0); agg::rasterizer_scanline_aa<> ras; ras.add_path(tp); agg::rendering_buffer buf(img_.data(), img_.width(), img_.height(), img_.row_size()); agg::pixfmt_gray8 pixfmt(buf); using renderer_base = agg::renderer_base<agg::pixfmt_gray8>; using renderer_bin = agg::renderer_scanline_bin_solid<renderer_base>; renderer_base rb(pixfmt); renderer_bin ren_bin(rb); ren_bin.color(agg::gray8(1)); agg::scanline_bin sl_bin; agg::render_scanlines(ras, sl_bin, ren_bin); } double get_scale(box2d<coord_type> const & envelope) const { coord_type size = std::max(envelope.width(), envelope.height()); const int max_size = 32768; if (size > max_size) { return max_size / size; } return 1; } image_gray8 create_bitmap(box2d<coord_type> const & box) const { if (!box.valid()) { return image_gray8(0, 0); } return image_gray8(box.width() * scale_, box.height() * scale_); } const double scale_; const coord_type dx_, dy_; image_gray8 img_; const view_transform vt_; GridIterator gi_; }; template <typename GridIterator> struct alternating_grid_vertex_adapter : grid_vertex_adapter<GridIterator> { using coord_type = double; template <typename PathType> alternating_grid_vertex_adapter(PathType & path, coord_type dx, coord_type dy) : grid_vertex_adapter<GridIterator>(path, dx, dy) { } unsigned vertex(coord_type * x, coord_type * y) { int pix_x, pix_y; while (this->gi_.vertex(&pix_x, &pix_y)) { int recentered_x = pix_x - this->gi_.size_x_ / 2; int recentered_y = pix_y - this->gi_.size_y_ / 2; pix_x = this->gi_.center_.x + static_cast<double>(recentered_x) * this->dx_; pix_y = this->gi_.center_.y + static_cast<double>(recentered_y) * this->dy_; if (recentered_y % 2 != 0) { pix_x += this->dx_ / 2.0; } if (pix_x >= 0 && pix_x < this->img_.width() && pix_y >= 0 && pix_y < this->img_.height() && get_pixel<image_gray8::pixel_type>(this->img_, pix_x, pix_y)) { *x = pix_x; *y = pix_y; this->vt_.backward(x, y); return mapnik::SEG_MOVETO; } } return mapnik::SEG_END; } }; } } #endif //MAPNIK_GRID_ADAPTERS_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_GRID_ADAPTERS_HPP #define MAPNIK_GRID_ADAPTERS_HPP #include <mapnik/vertex.hpp> #include <mapnik/image.hpp> #include <mapnik/image_util.hpp> #include <mapnik/geom_util.hpp> #include <mapnik/view_transform.hpp> #include "agg_rendering_buffer.h" #include "agg_pixfmt_gray.h" #include "agg_renderer_base.h" #include "agg_renderer_scanline.h" #include "agg_rasterizer_scanline_aa.h" #include "agg_scanline_bin.h" namespace mapnik { namespace geometry { class spiral_iterator { public: spiral_iterator(int x, int y) : size_x(x), size_y(y), end_(std::max(x, y) * std::max(x, y)), i_(0), x_(0), y_(0) { } bool vertex(int * x, int * y) { while (i_ < end_) { int xp = x_ + size_x / 2; int yp = y_ + size_y / 2; if (std::abs(x_) <= std::abs(y_) && (x_ != y_ || x_ >= 0)) { x_ += ((y_ >= 0) ? 1 : -1); } else { y_ += ((x_ >= 0) ? -1 : 1); } ++i_; if (xp >= 0 && xp < size_x && yp >= 0 && yp < size_y) { *x = xp; *y = yp; return true; } } return false; } void rewind() { i_ = 0; x_ = 0; y_ = 0; } const int size_x, size_y; private: const int end_; int i_; int x_, y_; }; struct row_grid_iterator { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> row_grid_iterator( PathType & path, box2d<coord_type> const & envelope, coord_type dx, coord_type dy, view_transform const & vt) : center_(envelope.width() / 2.0, envelope.height() / 2.0), size_x_(std::ceil(vt.width() / dx)), size_y_(std::ceil(vt.height() / dy)), x_(0), y_(0) { } inline bool vertex(int * x, int * y) { for (; y_ < size_y_; ++y_, x_ = 0) { for (; x_ < size_x_; ) { *x = x_; *y = y_; ++x_; return true; } } return false; } inline void rewind() { x_ = 0; y_ = 0; } const coord2d_type center_; const int size_x_, size_y_; int x_, y_; }; struct spiral_grid_iterator { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> spiral_grid_iterator( PathType & path, box2d<coord_type> const & envelope, coord_type dx, coord_type dy, view_transform const & vt) : vt_(vt), center_(interior(path, envelope)), size_x_(std::ceil((vt.width() + std::abs((vt.width() / 2.0) - center_.x) * 2.0) / dx)), size_y_(std::ceil((vt.height() + std::abs((vt.height() / 2.0) - center_.y) * 2.0) / dy)), si_(size_x_, size_y_) { } template <typename PathType> coord2d_type interior(PathType & path, box2d<coord_type> const & envelope) const { coord2d_type pos; if (!label::interior_position(path, pos.x, pos.y)) { pos = envelope.center(); } vt_.forward(&pos.x, &pos.y); return pos; } inline bool vertex(int * x, int * y) { return si_.vertex(x, y); } inline void rewind() { si_.rewind(); } view_transform const & vt_; const coord2d_type center_; const int size_x_, size_y_; spiral_iterator si_; }; template <typename PathType, typename TransformType> class transform_path { public: using coord_type = double; transform_path(PathType & path, TransformType const & transform) : path_(path), transform_(transform) { } void rewind(unsigned) { path_.rewind(0); } unsigned vertex(coord_type * x, coord_type * y) { unsigned command = path_.vertex(x, y); if (command != mapnik::SEG_END) { transform_.forward(x, y); } return command; } private: PathType & path_; TransformType const & transform_; }; template <typename GridIterator> struct grid_vertex_adapter { using coord_type = double; using coord2d_type = coord<coord_type, 2>; template <typename PathType> grid_vertex_adapter(PathType & path, coord_type dx, coord_type dy) : grid_vertex_adapter(path, dx, dy, mapnik::envelope(path)) { } void rewind(unsigned) { gi_.rewind(); } unsigned vertex(coord_type * x, coord_type * y) { int pix_x, pix_y; while (gi_.vertex(&pix_x, &pix_y)) { pix_x = gi_.center_.x + static_cast<double>(pix_x - gi_.size_x_ / 2) * dx_; pix_y = gi_.center_.y + static_cast<double>(pix_y - gi_.size_y_ / 2) * dy_; if (pix_x >= 0 && pix_x < img_.width() && pix_y >= 0 && pix_y < img_.height() && get_pixel<image_gray8::pixel_type>(img_, pix_x, pix_y)) { *x = pix_x; *y = pix_y; vt_.backward(x, y); return mapnik::SEG_MOVETO; } } return mapnik::SEG_END; } geometry_types type() const { return geometry_types::MultiPoint; } protected: template <typename PathType> grid_vertex_adapter( PathType & path, coord_type dx, coord_type dy, box2d<coord_type> envelope) : scale_(get_scale(envelope)), dx_(dx * scale_), dy_(dy * scale_), img_(create_bitmap(envelope)), vt_(img_.width(), img_.height(), envelope), gi_(path, envelope, dx_, dy_, vt_) { transform_path<PathType, view_transform> tp(path, vt_); tp.rewind(0); agg::rasterizer_scanline_aa<> ras; ras.add_path(tp); agg::rendering_buffer buf(img_.data(), img_.width(), img_.height(), img_.row_size()); agg::pixfmt_gray8 pixfmt(buf); using renderer_base = agg::renderer_base<agg::pixfmt_gray8>; using renderer_bin = agg::renderer_scanline_bin_solid<renderer_base>; renderer_base rb(pixfmt); renderer_bin ren_bin(rb); ren_bin.color(agg::gray8(1)); agg::scanline_bin sl_bin; agg::render_scanlines(ras, sl_bin, ren_bin); } double get_scale(box2d<coord_type> const & envelope) const { coord_type size = std::max(envelope.width(), envelope.height()); const int max_size = 32768; if (size > max_size) { return max_size / size; } return 1; } image_gray8 create_bitmap(box2d<coord_type> const & box) const { if (!box.valid()) { return image_gray8(0, 0); } return image_gray8(box.width() * scale_, box.height() * scale_); } const double scale_; const coord_type dx_, dy_; image_gray8 img_; const view_transform vt_; GridIterator gi_; }; template <typename GridIterator> struct alternating_grid_vertex_adapter : grid_vertex_adapter<GridIterator> { using coord_type = double; template <typename PathType> alternating_grid_vertex_adapter(PathType & path, coord_type dx, coord_type dy) : grid_vertex_adapter<GridIterator>(path, dx, dy) { } unsigned vertex(coord_type * x, coord_type * y) { int pix_x, pix_y; while (this->gi_.vertex(&pix_x, &pix_y)) { int recentered_x = pix_x - this->gi_.size_x_ / 2; int recentered_y = pix_y - this->gi_.size_y_ / 2; pix_x = this->gi_.center_.x + static_cast<double>(recentered_x) * this->dx_; pix_y = this->gi_.center_.y + static_cast<double>(recentered_y) * this->dy_; if (recentered_y % 2 != 0) { pix_x += this->dx_ / 2.0; } if (pix_x >= 0 && pix_x < this->img_.width() && pix_y >= 0 && pix_y < this->img_.height() && get_pixel<image_gray8::pixel_type>(this->img_, pix_x, pix_y)) { *x = pix_x; *y = pix_y; this->vt_.backward(x, y); return mapnik::SEG_MOVETO; } } return mapnik::SEG_END; } }; } } #endif //MAPNIK_GRID_ADAPTERS_HPP
fix colliding names
fix colliding names
C++
lgpl-2.1
mapycz/mapnik,mapycz/mapnik,mapycz/mapnik
9325cfed9ecfbe19ceee54f59664a9b115f758c5
includes/reflex/reflectable/macros.hpp
includes/reflex/reflectable/macros.hpp
#pragma once #include "reflex/reflectable/reflectable.hpp" //! convert value to string #define __REFLEX_TO_STRING(val) #val //! macro "overloading" (up to 3 args) #define __REFLEX_GET_MACRO_3(_1, _2, _3, NAME, ...) NAME //! macro "overloading" (up to 2 args) #define __REFLEX_GET_MACRO_2(_1, _2, NAME, ...) NAME //! open namespace (Boost.PP "callback") #define __REFLEX_OPEN_NAMESPACE(r, data, namespace_) namespace namespace_ { //! close namespace (Boost.PP "callback") #define __REFLEX_CLOSE_NAMESPACE(r, data, namespace_) } //! Build namespace from Boost.PP list #define __REFLEX_GET_NAMESPACE(r, data, i, namespace_) BOOST_PP_IF(i, "::",)__REFLEX_TO_STRING(namespace_) # define __REFLEX_BUILD_NAMESPACE(namespace_) BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_GET_NAMESPACE,, namespace_ ) //! Boost.PP "callback" for each item //! generates a pair associating function name to function pointer #define __REFLEX_MAKE_REGISTERABLE_FUNCTION(r, type, i, function) \ BOOST_PP_COMMA_IF(i) std::make_pair(std::string(__REFLEX_TO_STRING(function)), &type::function) #define __REFLEX_MAKE_REGISTERABLE_FUNCTION_WITHOUT_TYPE(r, type, i, function) \ BOOST_PP_COMMA_IF(i) std::make_pair(std::string(__REFLEX_TO_STRING(function)), &function) //! Macro for generating static reflectable for namespaced class functions #define __REFLEX_REGISTER_NAMESPACED_CLASS_FUNCTIONS(namespace_, type, functions) \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_OPEN_NAMESPACE,, namespace_ ) \ static reflex::reflectable<type> \ reflectable_##type(__REFLEX_BUILD_NAMESPACE(namespace_) "::" #type, \ BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION, type, functions )); \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_CLOSE_NAMESPACE,, namespace_ ) //! Macro for generating static reflectable for namespaced functions #define __REFLEX_REGISTER_NAMESPACED_FUNCTIONS(namespace_, functions) \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_OPEN_NAMESPACE,, namespace_ ) \ static reflex::reflectable<> \ reflectable_##type(__REFLEX_BUILD_NAMESPACE(namespace_), \ BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION_WITHOUT_TYPE,, functions )); \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_CLOSE_NAMESPACE,, namespace_ ) //! Macro for generating static reflectable for class functions #define __REFLEX_REGISTER_GLOBAL_CLASS_FUNCTIONS(type, functions) \ static reflex::reflectable<type> \ reflectable_##type(#type, BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION, \ type, \ functions )); //! Macro for generating static reflectable for functions #define __REFLEX_REGISTER_GLOBAL_FUNCTIONS(functions) \ static reflex::reflectable<> \ reflectable_("", BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION,, functions )); //! Macros intended for library user //! Generates a static reflectable object initialized with list of functions to register for reflection //! Macros are overloaded in order to handle namespace if necessary #define REGISTER_CLASS_FUNCTIONS(...) __REFLEX_GET_MACRO_3(__VA_ARGS__, __REFLEX_REGISTER_NAMESPACED_CLASS_FUNCTIONS, __REFLEX_REGISTER_GLOBAL_CLASS_FUNCTIONS)(__VA_ARGS__) #define REGISTER_FUNCTIONS(...) __REFLEX_GET_MACRO_2(__VA_ARGS__, __REFLEX_REGISTER_NAMESPACED_FUNCTIONS, __REFLEX_REGISTER_GLOBAL_FUNCTIONS)(__VA_ARGS__)
#pragma once #include "reflex/reflectable/reflectable.hpp" //! convert value to string #define __REFLEX_TO_STRING(val) #val //! macro "overloading" (up to 3 args) #define __REFLEX_GET_MACRO_3(_1, _2, _3, NAME, ...) NAME //! macro "overloading" (up to 2 args) #define __REFLEX_GET_MACRO_2(_1, _2, NAME, ...) NAME //! open namespace (Boost.PP "callback") #define __REFLEX_OPEN_NAMESPACE(r, data, namespace_) namespace namespace_ { //! close namespace (Boost.PP "callback") #define __REFLEX_CLOSE_NAMESPACE(r, data, namespace_) } //! Build namespace from Boost.PP list #define __REFLEX_GET_NAMESPACE(r, data, i, namespace_) BOOST_PP_IF(i, "::",)__REFLEX_TO_STRING(namespace_) #define __REFLEX_BUILD_NAMESPACE(namespace_) BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_GET_NAMESPACE,, namespace_ ) //! Boost.PP "callback" for each item //! generates a pair associating function name to function pointer #define __REFLEX_MAKE_REGISTERABLE_FUNCTION(r, type, i, function) \ BOOST_PP_COMMA_IF(i) std::make_pair(std::string(__REFLEX_TO_STRING(function)), &type::function) #define __REFLEX_MAKE_REGISTERABLE_FUNCTION_WITHOUT_TYPE(r, type, i, function) \ BOOST_PP_COMMA_IF(i) std::make_pair(std::string(__REFLEX_TO_STRING(function)), &function) //! Macro for generating static reflectable for namespaced class functions #define __REFLEX_REGISTER_NAMESPACED_CLASS_FUNCTIONS(namespace_, type, functions) \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_OPEN_NAMESPACE,, namespace_ ) \ static reflex::reflectable<type> \ reflectable_##type(__REFLEX_BUILD_NAMESPACE(namespace_) "::" #type, \ BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION, type, functions )); \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_CLOSE_NAMESPACE,, namespace_ ) //! Macro for generating static reflectable for namespaced functions #define __REFLEX_REGISTER_NAMESPACED_FUNCTIONS(namespace_, functions) \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_OPEN_NAMESPACE,, namespace_ ) \ static reflex::reflectable<> \ reflectable_##type(__REFLEX_BUILD_NAMESPACE(namespace_), \ BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION_WITHOUT_TYPE,, functions )); \ BOOST_PP_SEQ_FOR_EACH( __REFLEX_CLOSE_NAMESPACE,, namespace_ ) //! Macro for generating static reflectable for class functions #define __REFLEX_REGISTER_GLOBAL_CLASS_FUNCTIONS(type, functions) \ static reflex::reflectable<type> \ reflectable_##type(#type, BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION, \ type, \ functions )); //! Macro for generating static reflectable for functions #define __REFLEX_REGISTER_GLOBAL_FUNCTIONS(functions) \ static reflex::reflectable<> \ reflectable_("", BOOST_PP_SEQ_FOR_EACH_I( __REFLEX_MAKE_REGISTERABLE_FUNCTION,, functions )); //! Macros intended for library user //! Generates a static reflectable object initialized with list of functions to register for reflection //! Macros are overloaded in order to handle namespace if necessary #define REGISTER_CLASS_FUNCTIONS(...) __REFLEX_GET_MACRO_3(__VA_ARGS__, __REFLEX_REGISTER_NAMESPACED_CLASS_FUNCTIONS, __REFLEX_REGISTER_GLOBAL_CLASS_FUNCTIONS)(__VA_ARGS__) #define REGISTER_FUNCTIONS(...) __REFLEX_GET_MACRO_2(__VA_ARGS__, __REFLEX_REGISTER_NAMESPACED_FUNCTIONS, __REFLEX_REGISTER_GLOBAL_FUNCTIONS)(__VA_ARGS__)
remove extra space in macro.h
remove extra space in macro.h
C++
mit
Cylix/Reflex,Cylix/Reflex
50f327073b49a83f0cf54b8d7f0f4363239b6559
test/test_Exporter.cpp
test/test_Exporter.cpp
#include <sstream> #include "gtest/gtest.h" #include "../src/Exporter.hpp" #include "../src/Assembler.hpp" TEST(ExporterTest, exportCOETest) { std::vector<std::string> instLiteral = { "start:", " add $t0, $zero, $zero", " addi $t0, $t0, 15", "loop: add $t1, $t0, $zero", " addi $t0, $t0, -1", " bne $t0, $zero, loop", "exit: j start" }; std::vector<std::string> coe = { "memory_initialization_radix=16;", "memory_initialization_vector=", "00004020,", "2108000f,", "01004820,", "2108ffff,", "1408fff4,", "08000000;" }; std::string coeString; for (auto it = coe.begin(); it != coe.end(); ++it) coeString += *it + "\n"; Assembler assembler(instLiteral); std::vector<Assembly> instAssembled = assembler.getInstAssembled(); Exporter exporter; std::stringstream stream; exporter.exportAssembly(instAssembled, stream, Exporter::COE); std::string exportedCOE = stream.str(); EXPECT_EQ(exportedCOE, coeString); }
#include <sstream> #include "gtest/gtest.h" #include "../src/Exporter.hpp" #include "../src/Assembler.hpp" class ExporterTest: public ::testing::Test { protected: ExporterTest() { std::vector<std::string> instLiteral = { "start:", " add $t0, $zero, $zero", " addi $t0, $t0, 15", "loop: add $t1, $t0, $zero", " addi $t0, $t0, -1", " bne $t0, $zero, loop", "exit: j start" }; Assembler assembler(instLiteral); instAssembled = assembler.getInstAssembled(); } std::vector<Assembly> instAssembled; }; TEST_F(ExporterTest, exportCOETest) { std::vector<std::string> coe = { "memory_initialization_radix=16;", "memory_initialization_vector=", "00004020,", "2108000f,", "01004820,", "2108ffff,", "1408fff4,", "08000000;" }; std::string coeString; for (auto c: coe) coeString += c + "\n"; Exporter exporter; std::stringstream stream; exporter.exportAssembly(instAssembled, stream, Exporter::COE); std::string exportedCOE = stream.str(); EXPECT_EQ(exportedCOE, coeString); } TEST_F(ExporterTest, exportHexTest) { std::vector<std::string> hex = { "00004020", "2108000f", "01004820", "2108ffff", "1408fff4", "08000000" }; std::string hexString; for (auto h: hex) hexString += h + "\n"; Exporter exporter; std::stringstream stream; exporter.exportAssembly(instAssembled, stream, Exporter::HEX); std::string exportedHex = stream.str(); EXPECT_EQ(exportedHex, hexString); } TEST_F(ExporterTest, exportASCIIBinTest) { std::vector<std::string> asciiBin = { "00000000000000000100000000100000", "00100001000010000000000000001111", "00000001000000000100100000100000", "00100001000010001111111111111111", "00010100000010001111111111110100", "00001000000000000000000000000000" }; std::string binString; for (auto b: asciiBin) binString += b + "\n"; Exporter exporter; std::stringstream stream; exporter.exportAssembly(instAssembled, stream, Exporter::ASCIIBIN); std::string exportedBin = stream.str(); EXPECT_EQ(exportedBin, binString); } TEST_F(ExporterTest, exportBinTest) { const unsigned char bin[] = { 0x20, 0x40, 0x00, 0x00, 0x0f, 0x00, 0x08, 0x21, 0x20, 0x48, 0x00, 0x01, 0xff, 0xff, 0x08, 0x21, 0xf4, 0xff, 0x08, 0x14, 0x00, 0x00, 0x00, 0x08 }; Exporter exporter; std::stringstream stream; exporter.exportAssembly(instAssembled, stream, Exporter::BIN); char exportedBin[24]; stream.read(&exportedBin[0], 24); unsigned char *exportedUnsignedBin = reinterpret_cast<unsigned char *>(exportedBin); for (int i = 0; i < 24; ++i) { EXPECT_EQ(bin[i], exportedUnsignedBin[i]); } }
Add Exporter test fixture
Add Exporter test fixture
C++
mit
MForever78/CamelusMips
de8e005f0415e2e3654d80a02cd9292b08cc3d41
thrift/lib/cpp2/test/StreamingTest.cpp
thrift/lib/cpp2/test/StreamingTest.cpp
/* * Copyright 2015 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 <thrift/lib/cpp2/test/gen-cpp2/StreamingService.h> #include <gtest/gtest.h> #include <thrift/lib/cpp2//util/ScopedServerInterfaceThread.h> using namespace apache::thrift; using namespace apache::thrift::test::cpp2; using apache::thrift::transport::TTransportException; using wangle::Observer; using wangle::ObservablePtr; using wangle::Error; namespace { class StreamingServiceInterface : public StreamingServiceSvIf { public: void async_tm_streamingMethod( std::unique_ptr<StreamingHandlerCallback<int32_t>> callback, int32_t count) override { for (int i = 0; i < count; i++) { callback->write(i); /* sleep override */ usleep((i+1) * 5*1000); } //callback->exception(folly::make_exception_wrapper<TApplicationException>("qwerty")); callback->done(); } void async_tm_streamingException( std::unique_ptr<StreamingHandlerCallback<int32_t>> callback, int32_t count) override { for (int i = 0; i < count; i++) { callback->write(i); /* sleep override */ usleep((i+1) * 5*1000); } callback->exception(folly::make_exception_wrapper<StreamingException>()); } }; static constexpr size_t kCount = 5; class StreamingTest : public testing::Test { public: std::shared_ptr<StreamingServiceInterface> handler { std::make_shared<StreamingServiceInterface>() }; apache::thrift::ScopedServerInterfaceThread runner { handler }; folly::EventBase eb; std::unique_ptr<StreamingServiceAsyncClient> newClient() { return runner.newClient<StreamingServiceAsyncClient>(&eb); } }; } TEST_F(StreamingTest, Callback) { auto client = newClient(); int n = 0; client->streamingMethod([&n](ClientReceiveState&& state) mutable { if (n < kCount) { EXPECT_FALSE(state.isStreamEnd()); } else { EXPECT_TRUE(state.isStreamEnd()); } // call recv_ before checking for isStreamEnd to distinguish exceptions // from normal stream end int x = StreamingServiceAsyncClient::recv_streamingMethod(state); if (state.isStreamEnd()) { return; } EXPECT_EQ(x, n); n++; }, kCount); eb.loop(); EXPECT_EQ(n, kCount); } TEST_F(StreamingTest, Observable) { auto client = newClient(); int n = 0; ObservablePtr<int> s = client->observable_streamingMethod(kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&n](Error e) { // onError FAIL(); }, [&n]() { // onCompleted EXPECT_EQ(n, kCount); } )); eb.loop(); EXPECT_EQ(n, kCount); } TEST_F(StreamingTest, Exception) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingException(kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.is_compatible_with<StreamingException>()); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_EQ(n, kCount); EXPECT_TRUE(error); } TEST_F(StreamingTest, GlobalTimeout) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingMethod( RpcOptions().setTimeout(std::chrono::milliseconds(10)), kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.with_exception([](TTransportException& ex) { EXPECT_EQ(ex.getType(), TTransportException::TIMED_OUT); })); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_LT(n, kCount); EXPECT_TRUE(error); } TEST_F(StreamingTest, ChunkTimeout) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingMethod( RpcOptions().setChunkTimeout(std::chrono::milliseconds(5)), kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.with_exception([](TTransportException& ex) { EXPECT_EQ(ex.getType(), TTransportException::TIMED_OUT); })); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_LT(n, kCount); EXPECT_TRUE(error); // n should have been incremented at least once because the delay on // the initial chunks is smaller EXPECT_GT(n, 0); }
/* * Copyright 2015 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 <thrift/lib/cpp2/test/gen-cpp2/StreamingService.h> #include <gtest/gtest.h> #include <thrift/lib/cpp2/util/ScopedServerInterfaceThread.h> using namespace apache::thrift; using namespace apache::thrift::test::cpp2; using apache::thrift::transport::TTransportException; using wangle::Observer; using wangle::ObservablePtr; using wangle::Error; namespace { class StreamingServiceInterface : public StreamingServiceSvIf { public: void async_tm_streamingMethod( std::unique_ptr<StreamingHandlerCallback<int32_t>> callback, int32_t count) override { for (int i = 0; i < count; i++) { callback->write(i); /* sleep override */ usleep((i+1) * 5*1000); } //callback->exception(folly::make_exception_wrapper<TApplicationException>("qwerty")); callback->done(); } void async_tm_streamingException( std::unique_ptr<StreamingHandlerCallback<int32_t>> callback, int32_t count) override { for (int i = 0; i < count; i++) { callback->write(i); /* sleep override */ usleep((i+1) * 5*1000); } callback->exception(folly::make_exception_wrapper<StreamingException>()); } }; static constexpr size_t kCount = 5; class StreamingTest : public testing::Test { public: std::shared_ptr<StreamingServiceInterface> handler { std::make_shared<StreamingServiceInterface>() }; apache::thrift::ScopedServerInterfaceThread runner { handler }; folly::EventBase eb; std::unique_ptr<StreamingServiceAsyncClient> newClient() { return runner.newClient<StreamingServiceAsyncClient>(&eb); } }; } TEST_F(StreamingTest, Callback) { auto client = newClient(); int n = 0; client->streamingMethod([&n](ClientReceiveState&& state) mutable { if (n < kCount) { EXPECT_FALSE(state.isStreamEnd()); } else { EXPECT_TRUE(state.isStreamEnd()); } // call recv_ before checking for isStreamEnd to distinguish exceptions // from normal stream end int x = StreamingServiceAsyncClient::recv_streamingMethod(state); if (state.isStreamEnd()) { return; } EXPECT_EQ(x, n); n++; }, kCount); eb.loop(); EXPECT_EQ(n, kCount); } TEST_F(StreamingTest, Observable) { auto client = newClient(); int n = 0; ObservablePtr<int> s = client->observable_streamingMethod(kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&n](Error e) { // onError FAIL(); }, [&n]() { // onCompleted EXPECT_EQ(n, kCount); } )); eb.loop(); EXPECT_EQ(n, kCount); } TEST_F(StreamingTest, Exception) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingException(kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.is_compatible_with<StreamingException>()); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_EQ(n, kCount); EXPECT_TRUE(error); } TEST_F(StreamingTest, GlobalTimeout) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingMethod( RpcOptions().setTimeout(std::chrono::milliseconds(10)), kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.with_exception([](TTransportException& ex) { EXPECT_EQ(ex.getType(), TTransportException::TIMED_OUT); })); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_LT(n, kCount); EXPECT_TRUE(error); } TEST_F(StreamingTest, ChunkTimeout) { auto client = newClient(); int n = 0; bool error = false; ObservablePtr<int> s = client->observable_streamingMethod( RpcOptions().setChunkTimeout(std::chrono::milliseconds(5)), kCount); s->observe(Observer<int>::create( [&n](int x) mutable { // onNext EXPECT_LT(n, kCount); EXPECT_EQ(x, n); n++; }, [&error](Error e) { // onError EXPECT_TRUE(e.with_exception([](TTransportException& ex) { EXPECT_EQ(ex.getType(), TTransportException::TIMED_OUT); })); error = true; }, [&n]() { // onCompleted FAIL(); } )); eb.loop(); EXPECT_LT(n, kCount); EXPECT_TRUE(error); // n should have been incremented at least once because the delay on // the initial chunks is smaller EXPECT_GT(n, 0); }
remove stray doubled "//" in #include path
thrift/lib/cpp2/test/StreamingTest.cpp: remove stray doubled "//" in #include path Summary: as above. Reviewed By: yfeldblum Differential Revision: D3021516 fb-gh-sync-id: 38a43eb0f9233dd6b5cc54b87ffe67f7606f6f8e shipit-source-id: 38a43eb0f9233dd6b5cc54b87ffe67f7606f6f8e
C++
apache-2.0
facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,LinusU/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,facebook/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,getyourguide/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,LinusU/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,facebook/fbthrift,LinusU/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,facebook/fbthrift,getyourguide/fbthrift,getyourguide/fbthrift,LinusU/fbthrift,getyourguide/fbthrift,LinusU/fbthrift,LinusU/fbthrift,SergeyMakarenko/fbthrift,SergeyMakarenko/fbthrift,getyourguide/fbthrift
bfbe1af8cadd2f8ce76f192fb4486c9cf7968ba4
Modules/System/Src/tMachine.cpp
Modules/System/Src/tMachine.cpp
// tMachine.cpp // // Hardware ans OS access functions like querying supported instruction sets, number or cores, and computer name/ip // accessors. // // Copyright (c) 2004-2006, 2017, 2019, 2020 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #ifdef PLATFORM_WINDOWS #include <Windows.h> #include <intrin.h> #else #include <unistd.h> #include <limits.h> #include <sys/sysinfo.h> #endif #include "Foundation/tStandard.h" #include "System/tFile.h" #include "System/tMachine.h" bool tSystem::tSupportsSSE() { #ifdef PLATFORM_WINDOWS int cpuInfo[4]; int infoType = 1; __cpuid(cpuInfo, infoType); int features = cpuInfo[3]; // SSE feature bit is 25. if (features & (1 << 25)) return true; else return false; #elif defined(PLATFORM_LINUX) // @todo Implement return true; #endif } bool tSystem::tSupportsSSE2() { #ifdef PLATFORM_WINDOWS int cpuInfo[4]; int infoType = 1; __cpuid(cpuInfo, infoType); int features = cpuInfo[3]; // SSE2 feature bit is 26. if (features & (1 << 26)) return true; else return false; #elif defined(PLATFORM_LINUX) // @todo Implement return true; #endif } tString tSystem::tGetCompName() { #ifdef PLATFORM_WINDOWS char name[128]; ulong nameSize = 128; WinBool success = GetComputerName(name, &nameSize); if (success) return name; #else char hostname[HOST_NAME_MAX]; int err = gethostname(hostname, HOST_NAME_MAX); if (!err) return hostname; #endif return tString(); } tString tSystem::tGetEnvVar(const tString& envVarName) { if (envVarName.IsEmpty()) return tString(); return tString(std::getenv(envVarName.ConstText())); } int tSystem::tGetNumCores() { // Lets cache this value as it never changes. static int numCores = 0; if (numCores > 0) return numCores; #ifdef PLATFORM_WINDOWS SYSTEM_INFO sysinfo; tStd::tMemset(&sysinfo, 0, sizeof(sysinfo)); GetSystemInfo(&sysinfo); // dwNumberOfProcessors is unsigned, so can't say just > 0. if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1)) numCores = 1; else numCores = sysinfo.dwNumberOfProcessors; #else numCores = get_nprocs_conf(); if (numCores < 1) numCores = 1; #endif return numCores; } bool tSystem::tOpenSystemFileExplorer(const tString& dir, const tString& file) { #ifdef PLATFORM_WINDOWS tString fullName = dir + file; HWND hWnd = ::GetActiveWindow(); // Just open an explorer window if the dir is invalid. if (!tSystem::tDirExists(dir)) { // 20D04FE0-3AEA-1069-A2D8-08002B30309D is the CLSID of "This PC" on Windows. ShellExecute(hWnd, "open", "explorer", "/n,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}", 0, SW_SHOWNORMAL); return false; } if (tSystem::tFileExists(fullName)) { fullName.Replace('/', '\\'); tString options; tsPrintf(options, "/select,\"%s\"", fullName.Chars()); ShellExecute(hWnd, "open", "explorer", options.ConstText(), 0, SW_SHOWNORMAL); } else { ShellExecute(hWnd, "open", dir.ConstText(), 0, dir.ConstText(), SW_SHOWNORMAL); } return true; #elif defined(PLATFORM_LINUX) if (!tFileExists("/usr/bin/nautilus")) return false; tString sysStr; tsPrintf(sysStr, "/usr/bin/nautilus %s%s", dir.Chars(), file.Chars()); system(sysStr.ConstText()); return true; #else return false; #endif } bool tSystem::tOpenSystemFileExplorer(const tString& fullFilename) { return tOpenSystemFileExplorer(tSystem::tGetDir(fullFilename), tSystem::tGetFileName(fullFilename)); }
// tMachine.cpp // // Hardware ans OS access functions like querying supported instruction sets, number or cores, and computer name/ip // accessors. // // Copyright (c) 2004-2006, 2017, 2019, 2020 Tristan Grimmer. // Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby // granted, provided that the above copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN // AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR // PERFORMANCE OF THIS SOFTWARE. #ifdef PLATFORM_WINDOWS #include <Windows.h> #include <intrin.h> #else #include <unistd.h> #include <limits.h> #include <sys/sysinfo.h> #endif #include <cstdlib> #include "Foundation/tStandard.h" #include "System/tFile.h" #include "System/tMachine.h" bool tSystem::tSupportsSSE() { #ifdef PLATFORM_WINDOWS int cpuInfo[4]; int infoType = 1; __cpuid(cpuInfo, infoType); int features = cpuInfo[3]; // SSE feature bit is 25. if (features & (1 << 25)) return true; else return false; #elif defined(PLATFORM_LINUX) // @todo Implement return true; #endif } bool tSystem::tSupportsSSE2() { #ifdef PLATFORM_WINDOWS int cpuInfo[4]; int infoType = 1; __cpuid(cpuInfo, infoType); int features = cpuInfo[3]; // SSE2 feature bit is 26. if (features & (1 << 26)) return true; else return false; #elif defined(PLATFORM_LINUX) // @todo Implement return true; #endif } tString tSystem::tGetCompName() { #ifdef PLATFORM_WINDOWS char name[128]; ulong nameSize = 128; WinBool success = GetComputerName(name, &nameSize); if (success) return name; #else char hostname[HOST_NAME_MAX]; int err = gethostname(hostname, HOST_NAME_MAX); if (!err) return hostname; #endif return tString(); } tString tSystem::tGetEnvVar(const tString& envVarName) { if (envVarName.IsEmpty()) return tString(); return tString(std::getenv(envVarName.ConstText())); } int tSystem::tGetNumCores() { // Lets cache this value as it never changes. static int numCores = 0; if (numCores > 0) return numCores; #ifdef PLATFORM_WINDOWS SYSTEM_INFO sysinfo; tStd::tMemset(&sysinfo, 0, sizeof(sysinfo)); GetSystemInfo(&sysinfo); // dwNumberOfProcessors is unsigned, so can't say just > 0. if ((sysinfo.dwNumberOfProcessors == 0) || (sysinfo.dwNumberOfProcessors == -1)) numCores = 1; else numCores = sysinfo.dwNumberOfProcessors; #else numCores = get_nprocs_conf(); if (numCores < 1) numCores = 1; #endif return numCores; } bool tSystem::tOpenSystemFileExplorer(const tString& dir, const tString& file) { #ifdef PLATFORM_WINDOWS tString fullName = dir + file; HWND hWnd = ::GetActiveWindow(); // Just open an explorer window if the dir is invalid. if (!tSystem::tDirExists(dir)) { // 20D04FE0-3AEA-1069-A2D8-08002B30309D is the CLSID of "This PC" on Windows. ShellExecute(hWnd, "open", "explorer", "/n,::{20D04FE0-3AEA-1069-A2D8-08002B30309D}", 0, SW_SHOWNORMAL); return false; } if (tSystem::tFileExists(fullName)) { fullName.Replace('/', '\\'); tString options; tsPrintf(options, "/select,\"%s\"", fullName.Chars()); ShellExecute(hWnd, "open", "explorer", options.ConstText(), 0, SW_SHOWNORMAL); } else { ShellExecute(hWnd, "open", dir.ConstText(), 0, dir.ConstText(), SW_SHOWNORMAL); } return true; #elif defined(PLATFORM_LINUX) if (!tFileExists("/usr/bin/nautilus")) return false; tString sysStr; tsPrintf(sysStr, "/usr/bin/nautilus %s%s", dir.Chars(), file.Chars()); system(sysStr.ConstText()); return true; #else return false; #endif } bool tSystem::tOpenSystemFileExplorer(const tString& fullFilename) { return tOpenSystemFileExplorer(tSystem::tGetDir(fullFilename), tSystem::tGetFileName(fullFilename)); }
Include cstdlib for win build.
Include cstdlib for win build.
C++
isc
bluescan/tacent
67d6a421e8095d67bdb165fabd2ec117811a2d85
Multi-layer_Perceptron/main.cpp
Multi-layer_Perceptron/main.cpp
#include <omp.h> #include <stdio.h> #include <time.h> #include "MLP.h" void Read_MNIST(char training_set_images[], char training_set_labels[], char test_set_images[], char test_set_labels[], int number_training, int number_test, double **input, double **target_output){ FILE *file; if(file = fopen(training_set_images, "rb")){ for(int h = 0, value;h < 4;h++){ fread(&value, sizeof(int), 1, file); } for(int h = 0;h < number_training;h++){ unsigned char pixel; for(int j = 0;j < 28 * 28;j++){ fread(&pixel, sizeof(unsigned char), 1, file); input[h][j] = pixel / 255.0; } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", training_set_images); } if(file = fopen(training_set_labels, "rb")){ for(int h = 0, value;h < 2;h++){ fread(&value, sizeof(int), 1, file); } for(int h = 0;h < number_training;h++){ unsigned char label; fread(&label, sizeof(unsigned char), 1, file); for(int j = 0;j < 10;j++){ target_output[h][j] = (j == label); } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", training_set_labels); } if(file = fopen(test_set_images, "rb")){ for(int h = 0, value;h < 4;h++){ fread(&value, sizeof(int), 1, file); } for(int h = number_training;h < number_training + number_test;h++){ unsigned char pixel; for(int j = 0;j < 28 * 28;j++){ fread(&pixel, sizeof(unsigned char), 1, file); input[h][j] = pixel / 255.0; } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", test_set_images); } if(file = fopen(test_set_labels, "rb")){ for(int h = 0, value;h < 2;h++){ fread(&value, sizeof(int), 1, file); } for(int h = number_training;h < number_training + number_test;h++){ unsigned char label; fread(&label, sizeof(unsigned char), 1, file); for(int j = 0;j < 10;j++){ target_output[h][j] = (j == label); } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", test_set_labels); } } int main(){ char *type_layer[] = {"MNIST", "Cbn", "Cbn,do.5", "Lce,sm"}; int batch_size = 60; int number_iterations = 100; int number_layers = sizeof(type_layer) / sizeof(type_layer[0]); int number_neurons[] = {28 * 28, 400, 400, 10}; int number_threads = 2; int number_training = 60000; int number_test = 10000; double epsilon = 0.001; double learning_rate = 0.005; double **input = new double*[number_training + number_test]; double **target_output = new double*[number_training + number_test]; Multilayer_Perceptron MLP = Multilayer_Perceptron(type_layer, number_layers, number_neurons); for(int h = 0;h < number_training + number_test;h++){ input[h] = new double[number_neurons[0]]; target_output[h] = new double[number_neurons[number_layers - 1]]; } Read_MNIST("train-images.idx3-ubyte", "train-labels.idx1-ubyte", "t10k-images.idx3-ubyte", "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output); MLP.Initialize_Parameter(0, 0.2, -0.1); omp_set_num_threads(number_threads); for(int h = 0, time = clock();h < number_iterations;h++){ int number_correct[2] = {0, }; double loss = MLP.Train(batch_size, number_training, epsilon, learning_rate, input, target_output); double *output = new double[number_neurons[number_layers - 1]]; for(int i = 0;i < number_training + number_test;i++){ int argmax; double max = 0; MLP.Test(input[i], output); for(int j = 0;j < number_neurons[number_layers - 1];j++){ if(max < output[j]){ argmax = j; max = output[j]; } } number_correct[(i < number_training) ? (0):(1)] += (int)target_output[i][argmax]; } printf("score: %d / %d, %d / %d loss: %lf step %d %.2lf sec\n", number_correct[0], number_training, number_correct[1], number_test, loss, h + 1, (double)(clock() - time) / CLOCKS_PER_SEC); learning_rate *= 0.993; delete[] output; } for(int h = 0;h < number_training + number_test;h++){ delete[] input[h]; delete[] target_output[h]; } delete[] input; delete[] target_output; return 0; }
#include <omp.h> #include <stdio.h> #include <time.h> #include "MLP.h" void Read_MNIST(char training_set_images[], char training_set_labels[], char test_set_images[], char test_set_labels[], int number_training, int number_test, double **input, double **target_output){ FILE *file; if(file = fopen(training_set_images, "rb")){ for(int h = 0, value;h < 4;h++){ fread(&value, sizeof(int), 1, file); } for(int h = 0;h < number_training;h++){ unsigned char pixel; for(int j = 0;j < 28 * 28;j++){ fread(&pixel, sizeof(unsigned char), 1, file); input[h][j] = pixel / 255.0; } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", training_set_images); } if(file = fopen(training_set_labels, "rb")){ for(int h = 0, value;h < 2;h++){ fread(&value, sizeof(int), 1, file); } for(int h = 0;h < number_training;h++){ unsigned char label; fread(&label, sizeof(unsigned char), 1, file); for(int j = 0;j < 10;j++){ target_output[h][j] = (j == label); } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", training_set_labels); } if(file = fopen(test_set_images, "rb")){ for(int h = 0, value;h < 4;h++){ fread(&value, sizeof(int), 1, file); } for(int h = number_training;h < number_training + number_test;h++){ unsigned char pixel; for(int j = 0;j < 28 * 28;j++){ fread(&pixel, sizeof(unsigned char), 1, file); input[h][j] = pixel / 255.0; } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", test_set_images); } if(file = fopen(test_set_labels, "rb")){ for(int h = 0, value;h < 2;h++){ fread(&value, sizeof(int), 1, file); } for(int h = number_training;h < number_training + number_test;h++){ unsigned char label; fread(&label, sizeof(unsigned char), 1, file); for(int j = 0;j < 10;j++){ target_output[h][j] = (j == label); } } fclose(file); } else{ fprintf(stderr, "[Read_MNIST], %s not found\n", test_set_labels); } } int main(){ char *type_layer[] = {"MNIST", "Cbn", "Cbn,do.5", "Lce,sm"}; int batch_size = 60; int number_iterations = 100; int number_layers = sizeof(type_layer) / sizeof(type_layer[0]); int number_neurons[] = {28 * 28, 400, 400, 10}; int number_threads = 2; int number_training = 60000; int number_test = 10000; double epsilon = 0.001; double learning_rate = 0.005; double decay_rate = 0.993; double **input = new double*[number_training + number_test]; double **target_output = new double*[number_training + number_test]; Multilayer_Perceptron MLP = Multilayer_Perceptron(type_layer, number_layers, number_neurons); for(int h = 0;h < number_training + number_test;h++){ input[h] = new double[number_neurons[0]]; target_output[h] = new double[number_neurons[number_layers - 1]]; } Read_MNIST("train-images.idx3-ubyte", "train-labels.idx1-ubyte", "t10k-images.idx3-ubyte", "t10k-labels.idx1-ubyte", number_training, number_test, input, target_output); MLP.Initialize_Parameter(0, 0.2, -0.1); omp_set_num_threads(number_threads); for(int h = 0, time = clock();h < number_iterations;h++){ int number_correct[2] = {0, }; double loss = MLP.Train(batch_size, number_training, epsilon, learning_rate, input, target_output); double *output = new double[number_neurons[number_layers - 1]]; for(int i = 0;i < number_training + number_test;i++){ int argmax; double max = 0; MLP.Test(input[i], output); for(int j = 0;j < number_neurons[number_layers - 1];j++){ if(max < output[j]){ argmax = j; max = output[j]; } } number_correct[(i < number_training) ? (0):(1)] += (int)target_output[i][argmax]; } printf("score: %d / %d, %d / %d loss: %lf step %d %.2lf sec\n", number_correct[0], number_training, number_correct[1], number_test, loss, h + 1, (double)(clock() - time) / CLOCKS_PER_SEC); learning_rate *= decay_rate; delete[] output; } for(int h = 0;h < number_training + number_test;h++){ delete[] input[h]; delete[] target_output[h]; } delete[] input; delete[] target_output; return 0; }
Update main.cpp
Update main.cpp
C++
mit
paperrune/Neural-Networks,paperrune/Neural-Networks
9d8056574968a47692a83d4ac20f3893a18a295c
OgreMain/src/OgreSerializer.cpp
OgreMain/src/OgreSerializer.cpp
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 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 "OgreStableHeaders.h" #include "OgreSerializer.h" #include "OgreLogManager.h" #include "OgreDataStream.h" #include "OgreException.h" #include "OgreVector3.h" #include "OgreQuaternion.h" namespace Ogre { const uint16 HEADER_STREAM_ID = 0x1000; const uint16 OTHER_ENDIAN_HEADER_STREAM_ID = 0x0010; //--------------------------------------------------------------------- Serializer::Serializer() : mVersion("[Serializer_v1.00]"), // Version number mFlipEndian(false) #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE , mReportChunkErrors(true) #endif { } //--------------------------------------------------------------------- Serializer::~Serializer() { } //--------------------------------------------------------------------- void Serializer::determineEndianness(DataStreamPtr& stream) { if (stream->tell() != 0) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can only determine the endianness of the input stream if it " "is at the start", "Serializer::determineEndianness"); } uint16 dest; // read header id manually (no conversion) size_t actually_read = stream->read(&dest, sizeof(uint16)); // skip back stream->skip(0 - (long)actually_read); if (actually_read != sizeof(uint16)) { // end of file? OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Couldn't read 16 bit header value from input stream.", "Serializer::determineEndianness"); } if (dest == HEADER_STREAM_ID) { mFlipEndian = false; } else if (dest == OTHER_ENDIAN_HEADER_STREAM_ID) { mFlipEndian = true; } else { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Header chunk didn't match either endian: Corrupted stream?", "Serializer::determineEndianness"); } } //--------------------------------------------------------------------- void Serializer::determineEndianness(Endian requestedEndian) { switch(requestedEndian) { case ENDIAN_NATIVE: mFlipEndian = false; break; case ENDIAN_BIG: #if OGRE_ENDIAN == OGRE_ENDIAN_BIG mFlipEndian = false; #else mFlipEndian = true; #endif break; case ENDIAN_LITTLE: #if OGRE_ENDIAN == OGRE_ENDIAN_BIG mFlipEndian = true; #else mFlipEndian = false; #endif break; } } //--------------------------------------------------------------------- void Serializer::writeFileHeader(void) { uint16 val = HEADER_STREAM_ID; writeShorts(&val, 1); writeString(mVersion); } //--------------------------------------------------------------------- void Serializer::writeChunkHeader(uint16 id, size_t size) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty()){ size_t pos = mStream->tell(); if (pos != static_cast<size_t>(mChunkSizeStack.back()) && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + mStream->getName() + "' Chunk id: " + StringConverter::toString(id)); } mChunkSizeStack.back() = pos + size; } #endif writeShorts(&id, 1); uint32 uint32size = static_cast<uint32>(size); writeInts(&uint32size, 1); } //--------------------------------------------------------------------- void Serializer::writeFloats(const float* const pFloat, size_t count) { if (mFlipEndian) { float * pFloatToWrite = (float *)malloc(sizeof(float) * count); memcpy(pFloatToWrite, pFloat, sizeof(float) * count); flipToLittleEndian(pFloatToWrite, sizeof(float), count); writeData(pFloatToWrite, sizeof(float), count); free(pFloatToWrite); } else { writeData(pFloat, sizeof(float), count); } } //--------------------------------------------------------------------- void Serializer::writeFloats(const double* const pDouble, size_t count) { // Convert to float, then write float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); for (unsigned int i = 0; i < count; ++i) { tmp[i] = static_cast<float>(pDouble[i]); } if(mFlipEndian) { flipToLittleEndian(tmp, sizeof(float), count); writeData(tmp, sizeof(float), count); } else { writeData(tmp, sizeof(float), count); } OGRE_FREE(tmp, MEMCATEGORY_GENERAL); } //--------------------------------------------------------------------- void Serializer::writeShorts(const uint16* const pShort, size_t count = 1) { if(mFlipEndian) { unsigned short * pShortToWrite = (unsigned short *)malloc(sizeof(unsigned short) * count); memcpy(pShortToWrite, pShort, sizeof(unsigned short) * count); flipToLittleEndian(pShortToWrite, sizeof(unsigned short), count); writeData(pShortToWrite, sizeof(unsigned short), count); free(pShortToWrite); } else { writeData(pShort, sizeof(unsigned short), count); } } //--------------------------------------------------------------------- void Serializer::writeInts(const uint32* const pInt, size_t count = 1) { if(mFlipEndian) { unsigned int * pIntToWrite = (unsigned int *)malloc(sizeof(unsigned int) * count); memcpy(pIntToWrite, pInt, sizeof(unsigned int) * count); flipToLittleEndian(pIntToWrite, sizeof(unsigned int), count); writeData(pIntToWrite, sizeof(unsigned int), count); free(pIntToWrite); } else { writeData(pInt, sizeof(unsigned int), count); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- void Serializer::writeBools(const bool* const pBool, size_t count = 1) { //no endian flipping for 1-byte bools //XXX Nasty Hack to convert to 1-byte bools # if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS char * pCharToWrite = (char *)malloc(sizeof(char) * count); for(unsigned int i = 0; i < count; i++) { *(char *)(pCharToWrite + i) = *(bool *)(pBool + i); } writeData(pCharToWrite, sizeof(char), count); free(pCharToWrite); # else writeData(pBool, sizeof(bool), count); # endif } //--------------------------------------------------------------------- void Serializer::writeData(const void* const buf, size_t size, size_t count) { mStream->write(buf, size * count); } //--------------------------------------------------------------------- void Serializer::writeString(const String& string) { // Old, backwards compatible way - \n terminated mStream->write(string.c_str(), string.length()); // Write terminating newline char char terminator = '\n'; mStream->write(&terminator, 1); } //--------------------------------------------------------------------- void Serializer::readFileHeader(DataStreamPtr& stream) { unsigned short headerID; // Read header ID readShorts(stream, &headerID, 1); if (headerID == HEADER_STREAM_ID) { // Read version String ver = readString(stream); if (ver != mVersion) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: version incompatible, file reports " + String(ver) + " Serializer is version " + mVersion, "Serializer::readFileHeader"); } } else { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: no header", "Serializer::readFileHeader"); } } //--------------------------------------------------------------------- unsigned short Serializer::readChunk(DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE size_t pos = stream->tell(); #endif unsigned short id; readShorts(stream, &id, 1); readInts(stream, &mCurrentstreamLen, 1); #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty() && !stream->eof()){ if (pos != static_cast<size_t>(mChunkSizeStack.back()) && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + stream->getName() + "' Chunk id: " + StringConverter::toString(id)); } mChunkSizeStack.back() = pos + mCurrentstreamLen; } #endif return id; } //--------------------------------------------------------------------- void Serializer::readBools(DataStreamPtr& stream, bool* pDest, size_t count) { //XXX Nasty Hack to convert 1 byte bools to 4 byte bools # if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS char * pTemp = (char *)malloc(1*count); // to hold 1-byte bools stream->read(pTemp, 1 * count); for(unsigned int i = 0; i < count; i++) *(bool *)(pDest + i) = *(char *)(pTemp + i); free (pTemp); # else stream->read(pDest, sizeof(bool) * count); # endif //no flipping on 1-byte datatypes } //--------------------------------------------------------------------- void Serializer::readFloats(DataStreamPtr& stream, float* pDest, size_t count) { stream->read(pDest, sizeof(float) * count); flipFromLittleEndian(pDest, sizeof(float), count); } //--------------------------------------------------------------------- void Serializer::readFloats(DataStreamPtr& stream, double* pDest, size_t count) { // Read from float, convert to double float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); float* ptmp = tmp; stream->read(tmp, sizeof(float) * count); flipFromLittleEndian(tmp, sizeof(float), count); // Convert to doubles (no cast required) while(count--) { *pDest++ = *ptmp++; } OGRE_FREE(tmp, MEMCATEGORY_GENERAL); } //--------------------------------------------------------------------- void Serializer::readShorts(DataStreamPtr& stream, unsigned short* pDest, size_t count) { stream->read(pDest, sizeof(unsigned short) * count); flipFromLittleEndian(pDest, sizeof(unsigned short), count); } //--------------------------------------------------------------------- void Serializer::readInts(DataStreamPtr& stream, unsigned int* pDest, size_t count) { stream->read(pDest, sizeof(unsigned int) * count); flipFromLittleEndian(pDest, sizeof(unsigned int), count); } //--------------------------------------------------------------------- String Serializer::readString(DataStreamPtr& stream, size_t numChars) { assert (numChars <= 255); char str[255]; stream->read(str, numChars); str[numChars] = '\0'; return str; } //--------------------------------------------------------------------- String Serializer::readString(DataStreamPtr& stream) { return stream->getLine(false); } //--------------------------------------------------------------------- void Serializer::writeObject(const Vector3& vec) { writeFloats(vec.ptr(), 3); } //--------------------------------------------------------------------- void Serializer::writeObject(const Quaternion& q) { float tmp[4] = { static_cast<float>(q.x), static_cast<float>(q.y), static_cast<float>(q.z), static_cast<float>(q.w) }; writeFloats(tmp, 4); } //--------------------------------------------------------------------- void Serializer::readObject(DataStreamPtr& stream, Vector3& pDest) { readFloats(stream, pDest.ptr(), 3); } //--------------------------------------------------------------------- void Serializer::readObject(DataStreamPtr& stream, Quaternion& pDest) { float tmp[4]; readFloats(stream, tmp, 4); pDest.x = tmp[0]; pDest.y = tmp[1]; pDest.z = tmp[2]; pDest.w = tmp[3]; } //--------------------------------------------------------------------- void Serializer::flipToLittleEndian(void* pData, size_t size, size_t count) { if(mFlipEndian) { flipEndian(pData, size, count); } } void Serializer::flipFromLittleEndian(void* pData, size_t size, size_t count) { if(mFlipEndian) { flipEndian(pData, size, count); } } void Serializer::flipEndian(void * pData, size_t size, size_t count) { for(unsigned int index = 0; index < count; index++) { flipEndian((void *)((size_t)pData + (index * size)), size); } } void Serializer::flipEndian(void * pData, size_t size) { for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++) { char swapByte = *(char *)((size_t)pData + byteIndex); *(char *)((size_t)pData + byteIndex) = *(char *)((size_t)pData + size - byteIndex - 1); *(char *)((size_t)pData + size - byteIndex - 1) = swapByte; } } size_t Serializer::calcChunkHeaderSize() { return sizeof(uint16) + sizeof(uint32); } size_t Serializer::calcStringSize( const String& string ) { // string + terminating \n character return string.length() + 1; } void Serializer::pushInnerChunk(const DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE mChunkSizeStack.push_back(stream->tell()); #endif } void Serializer::backpedalChunkHeader(DataStreamPtr& stream) { if (!stream->eof()){ stream->skip(-(int)calcChunkHeaderSize()); } #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE mChunkSizeStack.back() = stream->tell(); #endif } void Serializer::popInnerChunk(const DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty()){ size_t pos = stream->tell(); if (pos != static_cast<size_t>(mChunkSizeStack.back()) && !stream->eof() && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: " + stream->getName()); } mChunkSizeStack.pop_back(); } #endif } }
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2013 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 "OgreStableHeaders.h" #include "OgreSerializer.h" #include "OgreLogManager.h" #include "OgreDataStream.h" #include "OgreException.h" #include "OgreVector3.h" #include "OgreQuaternion.h" #include "OgreStringConverter.h" namespace Ogre { const uint16 HEADER_STREAM_ID = 0x1000; const uint16 OTHER_ENDIAN_HEADER_STREAM_ID = 0x0010; //--------------------------------------------------------------------- Serializer::Serializer() : mVersion("[Serializer_v1.00]"), // Version number mFlipEndian(false) #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE , mReportChunkErrors(true) #endif { } //--------------------------------------------------------------------- Serializer::~Serializer() { } //--------------------------------------------------------------------- void Serializer::determineEndianness(DataStreamPtr& stream) { if (stream->tell() != 0) { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Can only determine the endianness of the input stream if it " "is at the start", "Serializer::determineEndianness"); } uint16 dest; // read header id manually (no conversion) size_t actually_read = stream->read(&dest, sizeof(uint16)); // skip back stream->skip(0 - (long)actually_read); if (actually_read != sizeof(uint16)) { // end of file? OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Couldn't read 16 bit header value from input stream.", "Serializer::determineEndianness"); } if (dest == HEADER_STREAM_ID) { mFlipEndian = false; } else if (dest == OTHER_ENDIAN_HEADER_STREAM_ID) { mFlipEndian = true; } else { OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Header chunk didn't match either endian: Corrupted stream?", "Serializer::determineEndianness"); } } //--------------------------------------------------------------------- void Serializer::determineEndianness(Endian requestedEndian) { switch(requestedEndian) { case ENDIAN_NATIVE: mFlipEndian = false; break; case ENDIAN_BIG: #if OGRE_ENDIAN == OGRE_ENDIAN_BIG mFlipEndian = false; #else mFlipEndian = true; #endif break; case ENDIAN_LITTLE: #if OGRE_ENDIAN == OGRE_ENDIAN_BIG mFlipEndian = true; #else mFlipEndian = false; #endif break; } } //--------------------------------------------------------------------- void Serializer::writeFileHeader(void) { uint16 val = HEADER_STREAM_ID; writeShorts(&val, 1); writeString(mVersion); } //--------------------------------------------------------------------- void Serializer::writeChunkHeader(uint16 id, size_t size) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty()){ size_t pos = mStream->tell(); if (pos != static_cast<size_t>(mChunkSizeStack.back()) && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + mStream->getName() + "' Chunk id: " + StringConverter::toString(id)); } mChunkSizeStack.back() = pos + size; } #endif writeShorts(&id, 1); uint32 uint32size = static_cast<uint32>(size); writeInts(&uint32size, 1); } //--------------------------------------------------------------------- void Serializer::writeFloats(const float* const pFloat, size_t count) { if (mFlipEndian) { float * pFloatToWrite = (float *)malloc(sizeof(float) * count); memcpy(pFloatToWrite, pFloat, sizeof(float) * count); flipToLittleEndian(pFloatToWrite, sizeof(float), count); writeData(pFloatToWrite, sizeof(float), count); free(pFloatToWrite); } else { writeData(pFloat, sizeof(float), count); } } //--------------------------------------------------------------------- void Serializer::writeFloats(const double* const pDouble, size_t count) { // Convert to float, then write float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); for (unsigned int i = 0; i < count; ++i) { tmp[i] = static_cast<float>(pDouble[i]); } if(mFlipEndian) { flipToLittleEndian(tmp, sizeof(float), count); writeData(tmp, sizeof(float), count); } else { writeData(tmp, sizeof(float), count); } OGRE_FREE(tmp, MEMCATEGORY_GENERAL); } //--------------------------------------------------------------------- void Serializer::writeShorts(const uint16* const pShort, size_t count = 1) { if(mFlipEndian) { unsigned short * pShortToWrite = (unsigned short *)malloc(sizeof(unsigned short) * count); memcpy(pShortToWrite, pShort, sizeof(unsigned short) * count); flipToLittleEndian(pShortToWrite, sizeof(unsigned short), count); writeData(pShortToWrite, sizeof(unsigned short), count); free(pShortToWrite); } else { writeData(pShort, sizeof(unsigned short), count); } } //--------------------------------------------------------------------- void Serializer::writeInts(const uint32* const pInt, size_t count = 1) { if(mFlipEndian) { unsigned int * pIntToWrite = (unsigned int *)malloc(sizeof(unsigned int) * count); memcpy(pIntToWrite, pInt, sizeof(unsigned int) * count); flipToLittleEndian(pIntToWrite, sizeof(unsigned int), count); writeData(pIntToWrite, sizeof(unsigned int), count); free(pIntToWrite); } else { writeData(pInt, sizeof(unsigned int), count); } } //--------------------------------------------------------------------- //--------------------------------------------------------------------- void Serializer::writeBools(const bool* const pBool, size_t count = 1) { //no endian flipping for 1-byte bools //XXX Nasty Hack to convert to 1-byte bools # if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS char * pCharToWrite = (char *)malloc(sizeof(char) * count); for(unsigned int i = 0; i < count; i++) { *(char *)(pCharToWrite + i) = *(bool *)(pBool + i); } writeData(pCharToWrite, sizeof(char), count); free(pCharToWrite); # else writeData(pBool, sizeof(bool), count); # endif } //--------------------------------------------------------------------- void Serializer::writeData(const void* const buf, size_t size, size_t count) { mStream->write(buf, size * count); } //--------------------------------------------------------------------- void Serializer::writeString(const String& string) { // Old, backwards compatible way - \n terminated mStream->write(string.c_str(), string.length()); // Write terminating newline char char terminator = '\n'; mStream->write(&terminator, 1); } //--------------------------------------------------------------------- void Serializer::readFileHeader(DataStreamPtr& stream) { unsigned short headerID; // Read header ID readShorts(stream, &headerID, 1); if (headerID == HEADER_STREAM_ID) { // Read version String ver = readString(stream); if (ver != mVersion) { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: version incompatible, file reports " + String(ver) + " Serializer is version " + mVersion, "Serializer::readFileHeader"); } } else { OGRE_EXCEPT(Exception::ERR_INTERNAL_ERROR, "Invalid file: no header", "Serializer::readFileHeader"); } } //--------------------------------------------------------------------- unsigned short Serializer::readChunk(DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE size_t pos = stream->tell(); #endif unsigned short id; readShorts(stream, &id, 1); readInts(stream, &mCurrentstreamLen, 1); #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty() && !stream->eof()){ if (pos != static_cast<size_t>(mChunkSizeStack.back()) && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: '" + stream->getName() + "' Chunk id: " + StringConverter::toString(id)); } mChunkSizeStack.back() = pos + mCurrentstreamLen; } #endif return id; } //--------------------------------------------------------------------- void Serializer::readBools(DataStreamPtr& stream, bool* pDest, size_t count) { //XXX Nasty Hack to convert 1 byte bools to 4 byte bools # if OGRE_PLATFORM == OGRE_PLATFORM_APPLE || OGRE_PLATFORM == OGRE_PLATFORM_APPLE_IOS char * pTemp = (char *)malloc(1*count); // to hold 1-byte bools stream->read(pTemp, 1 * count); for(unsigned int i = 0; i < count; i++) *(bool *)(pDest + i) = *(char *)(pTemp + i); free (pTemp); # else stream->read(pDest, sizeof(bool) * count); # endif //no flipping on 1-byte datatypes } //--------------------------------------------------------------------- void Serializer::readFloats(DataStreamPtr& stream, float* pDest, size_t count) { stream->read(pDest, sizeof(float) * count); flipFromLittleEndian(pDest, sizeof(float), count); } //--------------------------------------------------------------------- void Serializer::readFloats(DataStreamPtr& stream, double* pDest, size_t count) { // Read from float, convert to double float* tmp = OGRE_ALLOC_T(float, count, MEMCATEGORY_GENERAL); float* ptmp = tmp; stream->read(tmp, sizeof(float) * count); flipFromLittleEndian(tmp, sizeof(float), count); // Convert to doubles (no cast required) while(count--) { *pDest++ = *ptmp++; } OGRE_FREE(tmp, MEMCATEGORY_GENERAL); } //--------------------------------------------------------------------- void Serializer::readShorts(DataStreamPtr& stream, unsigned short* pDest, size_t count) { stream->read(pDest, sizeof(unsigned short) * count); flipFromLittleEndian(pDest, sizeof(unsigned short), count); } //--------------------------------------------------------------------- void Serializer::readInts(DataStreamPtr& stream, unsigned int* pDest, size_t count) { stream->read(pDest, sizeof(unsigned int) * count); flipFromLittleEndian(pDest, sizeof(unsigned int), count); } //--------------------------------------------------------------------- String Serializer::readString(DataStreamPtr& stream, size_t numChars) { assert (numChars <= 255); char str[255]; stream->read(str, numChars); str[numChars] = '\0'; return str; } //--------------------------------------------------------------------- String Serializer::readString(DataStreamPtr& stream) { return stream->getLine(false); } //--------------------------------------------------------------------- void Serializer::writeObject(const Vector3& vec) { writeFloats(vec.ptr(), 3); } //--------------------------------------------------------------------- void Serializer::writeObject(const Quaternion& q) { float tmp[4] = { static_cast<float>(q.x), static_cast<float>(q.y), static_cast<float>(q.z), static_cast<float>(q.w) }; writeFloats(tmp, 4); } //--------------------------------------------------------------------- void Serializer::readObject(DataStreamPtr& stream, Vector3& pDest) { readFloats(stream, pDest.ptr(), 3); } //--------------------------------------------------------------------- void Serializer::readObject(DataStreamPtr& stream, Quaternion& pDest) { float tmp[4]; readFloats(stream, tmp, 4); pDest.x = tmp[0]; pDest.y = tmp[1]; pDest.z = tmp[2]; pDest.w = tmp[3]; } //--------------------------------------------------------------------- void Serializer::flipToLittleEndian(void* pData, size_t size, size_t count) { if(mFlipEndian) { flipEndian(pData, size, count); } } void Serializer::flipFromLittleEndian(void* pData, size_t size, size_t count) { if(mFlipEndian) { flipEndian(pData, size, count); } } void Serializer::flipEndian(void * pData, size_t size, size_t count) { for(unsigned int index = 0; index < count; index++) { flipEndian((void *)((size_t)pData + (index * size)), size); } } void Serializer::flipEndian(void * pData, size_t size) { for(unsigned int byteIndex = 0; byteIndex < size/2; byteIndex++) { char swapByte = *(char *)((size_t)pData + byteIndex); *(char *)((size_t)pData + byteIndex) = *(char *)((size_t)pData + size - byteIndex - 1); *(char *)((size_t)pData + size - byteIndex - 1) = swapByte; } } size_t Serializer::calcChunkHeaderSize() { return sizeof(uint16) + sizeof(uint32); } size_t Serializer::calcStringSize( const String& string ) { // string + terminating \n character return string.length() + 1; } void Serializer::pushInnerChunk(const DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE mChunkSizeStack.push_back(stream->tell()); #endif } void Serializer::backpedalChunkHeader(DataStreamPtr& stream) { if (!stream->eof()){ stream->skip(-(int)calcChunkHeaderSize()); } #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE mChunkSizeStack.back() = stream->tell(); #endif } void Serializer::popInnerChunk(const DataStreamPtr& stream) { #if OGRE_SERIALIZER_VALIDATE_CHUNKSIZE if (!mChunkSizeStack.empty()){ size_t pos = stream->tell(); if (pos != static_cast<size_t>(mChunkSizeStack.back()) && !stream->eof() && mReportChunkErrors){ LogManager::getSingleton().logMessage("Corrupted chunk detected! Stream name: " + stream->getName()); } mChunkSizeStack.pop_back(); } #endif } }
Fix build on MinGW.
[OGRE-350] Fix build on MinGW.
C++
mit
OGRECave/ogre,RealityFactory/ogre,paroj/ogre,RealityFactory/ogre,OGRECave/ogre,paroj/ogre,paroj/ogre,RealityFactory/ogre,RealityFactory/ogre,paroj/ogre,OGRECave/ogre,OGRECave/ogre,RealityFactory/ogre,OGRECave/ogre,paroj/ogre
e7473a5db5b4def4ceb6f07d0275c6734da8149e
PWG/EMCAL/AliEmcalSetupTask.cxx
PWG/EMCAL/AliEmcalSetupTask.cxx
// $Id$ // // Task to setup emcal related global objects. // // Author: C.Loizides #include "AliEmcalSetupTask.h" #include <TClonesArray.h> #include <TGeoGlobalMagField.h> #include <TGeoManager.h> #include <TRandom.h> #include "AliAODEvent.h" #include "AliAnalysisManager.h" #include "AliCDBManager.h" #include "AliEMCALGeometry.h" #include "AliESDEvent.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliMagF.h" #include "AliOADBContainer.h" #include "AliTender.h" ClassImp(AliEmcalSetupTask) //________________________________________________________________________ AliEmcalSetupTask::AliEmcalSetupTask() : AliAnalysisTaskSE(), fOcdbPath("uselocal"), fOadbPath("$ALICE_ROOT/OADB/EMCAL"), fGeoPath("$ALICE_ROOT/OADB/EMCAL"), fObjs("GRP ITS TPC TRD EMCAL"), fNoOCDB(kFALSE), fIsInit(kFALSE), fLocalOcdb(), fLocalOcdbStor() { // Constructor. } //________________________________________________________________________ AliEmcalSetupTask::AliEmcalSetupTask(const char *name) : AliAnalysisTaskSE(name), fOcdbPath("uselocal"), fOadbPath("$ALICE_ROOT/OADB/EMCAL"), fGeoPath("$ALICE_ROOT/OADB/EMCAL"), fObjs("GRP ITS TPC TRD EMCAL"), fNoOCDB(kFALSE), fIsInit(kFALSE), fLocalOcdb(), fLocalOcdbStor() { // Constructor. fBranchNames = "ESD:AliESDHeader.,AliESDRun."; } //________________________________________________________________________ AliEmcalSetupTask::~AliEmcalSetupTask() { // Destructor. } //________________________________________________________________________ void AliEmcalSetupTask::ConnectInputData(Option_t *option) { // Connect input data AliAnalysisTaskSE::ConnectInputData(option); if (fOcdbPath.Length()==0) return; AliCDBManager *man = AliCDBManager::Instance(); if (man->IsDefaultStorageSet()) return; if (fIsInit) return; AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) return; TObjArray *tasks = am->GetTasks(); if (!tasks) return; AliTender *tender = 0; for (Int_t i=0; i<tasks->GetEntries(); ++i) { tender = dynamic_cast<AliTender*>(tasks->At(i)); if (tender) break; } if (!tender) return; if (fOcdbPath != "uselocal") { tender->SetDefaultCDBStorage(fOcdbPath); return; } Int_t runno = AliAnalysisManager::GetAnalysisManager()->GetRunFromPath(); if (runno<=0) { AliWarning(Form("Disabling tender, ignore possible message from tender below")); tender->SetDefaultCDBStorage("donotuse"); return; } AliWarning(Form("Intercepting tender for run %d, ignore possible message from tender below", runno)); Setup(runno); tender->SetDefaultCDBStorage(fLocalOcdbStor); } //________________________________________________________________________ void AliEmcalSetupTask::UserExec(Option_t *) { // Main loop, called for each event. if (fIsInit) return; AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) { AliError("Manager zero, returning"); return; } am->LoadBranch("AliESDRun."); am->LoadBranch("AliESDHeader."); Int_t runno = InputEvent()->GetRunNumber(); Setup(runno); } //________________________________________________________________________ void AliEmcalSetupTask::Setup(Int_t runno) { // Setup everything // Setup AliEMCALGeometry corresponding to year TString geoname("EMCAL_COMPLETE12SMV1"); Int_t year = 2013; if (runno>0 && runno<=139517) { year = 2010; geoname = "EMCAL_FIRSTYEARV1"; } else if ((runno>139517) && (runno<=170593)) { year = 2011; geoname = "EMCAL_COMPLETEV1"; } else if ((runno>170593) && (runno<=193766)) { year = 2012; } AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname); if (!geom) { AliFatal(Form("Can not create geometry: %s",geoname.Data())); return; } if (runno<=0) return; // Setup CDB manager AliCDBManager *man = 0; if (!fNoOCDB) { man = AliCDBManager::Instance(); if (!man) AliFatal(Form("Did not get pointer to CDB manager")); if (man->IsDefaultStorageSet()) { AliInfo(Form("Default OCDB storage already set")); } else { if (fOcdbPath.Length()==0) { man = 0; // do not use OCDB } else if (fOcdbPath != "uselocal") { AliInfo(Form("Setting up OCDB to point to %s",fOcdbPath.Data())); man->SetDefaultStorage(fOcdbPath); } else { // use local copy of OCDB TString tmpdir=gSystem->WorkingDirectory(); if (gSystem->AccessPathName(tmpdir)) tmpdir = "/tmp"; tmpdir+="/"; tmpdir+=gSystem->GetUid(); tmpdir+="-"; TDatime t; tmpdir+=t.Get(); tmpdir+="-"; Int_t counter = 0; fLocalOcdb = tmpdir; fLocalOcdb += Form("%d%d%d",gRandom->Integer(999999999),gRandom->Integer(999999999),gRandom->Integer(999999999)); while (!gSystem->AccessPathName(fLocalOcdb)) { fLocalOcdb = tmpdir; fLocalOcdb += Form("%d%d%d",gRandom->Integer(999999999),gRandom->Integer(999999999),gRandom->Integer(999999999)); counter++; if (counter>100) { AliFatal(Form("Could not create local directory for OCDB at %s",tmpdir.Data())); } } gSystem->MakeDirectory(fLocalOcdb); TString filename(Form("$ALICE_ROOT/PWG/EMCAL/data/%d.dat",year)); TString cmd(Form("cd %s && tar -xf %s",fLocalOcdb.Data(),filename.Data())); Int_t ret = gSystem->Exec(cmd); if (ret==0) { TString locdb("local://"); locdb+=fLocalOcdb; locdb+="/"; locdb+=year; AliInfo(Form("Setting up local OCDB at %s",locdb.Data())); man->SetDefaultStorage(locdb); fLocalOcdbStor = locdb; } else { AliFatal(Form("Could not set up local OCDB at %s",fLocalOcdb.Data())); } } } } // Load geometry from OCDB if (man) { if (man->GetRun()!=runno) man->SetRun(runno); AliInfo(Form("Loading grp data from OCDB for run %d", runno)); AliGRPManager GRPManager; GRPManager.ReadGRPEntry(); GRPManager.SetMagField(); AliInfo(Form("Loading geometry from OCDB")); AliGeomManager::LoadGeometry(); if (!fObjs.IsNull()) AliGeomManager::ApplyAlignObjsFromCDB(fObjs); } // Load geometry from file (does not use misalignment of ITS/TPC!) TGeoManager *geo = AliGeomManager::GetGeometry(); if (!geo && fGeoPath.Length()>0) { TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year))); if (gSystem->AccessPathName(fname)==0) { AliInfo(Form("Loading geometry from file %s (should be avoided!)", fname.Data())); AliGeomManager::LoadGeometry(fname); geo = AliGeomManager::GetGeometry(); } } // Lock geometry if (geo) { AliInfo(Form("Locking geometry")); geo->LockGeometry(); } // Construct field map if (!TGeoGlobalMagField::Instance()->GetField()) { InputEvent()->InitMagneticField(); } // Apply mis-alignment matrices from OADB if (fOadbPath.Length()>0) { AliOADBContainer emcalgeoCont(Form("emcal")); emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()), Form("AliEMCALgeo")); TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices")); if (mobj) { for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){ //AliInfo(Form("Misalignment matrix %d", mod)); geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod); } } } fIsInit = kTRUE; } //________________________________________________________________________ void AliEmcalSetupTask::Terminate(Option_t *) { // Called at the end. if (fLocalOcdb.Length()>0) { TString cmd(Form("rm -rf %s", fLocalOcdb.Data())); gSystem->Exec(cmd); } }
// $Id$ // // Task to setup emcal related global objects. // // Author: C.Loizides #include "AliEmcalSetupTask.h" #include <TClonesArray.h> #include <TGeoGlobalMagField.h> #include <TGeoManager.h> #include <TRandom.h> #include "AliAODEvent.h" #include "AliAnalysisManager.h" #include "AliCDBManager.h" #include "AliEMCALGeometry.h" #include "AliESDEvent.h" #include "AliGRPManager.h" #include "AliGeomManager.h" #include "AliMagF.h" #include "AliOADBContainer.h" #include "AliTender.h" ClassImp(AliEmcalSetupTask) //________________________________________________________________________ AliEmcalSetupTask::AliEmcalSetupTask() : AliAnalysisTaskSE(), fOcdbPath("uselocal"), fOadbPath("$ALICE_ROOT/OADB/EMCAL"), fGeoPath("$ALICE_ROOT/OADB/EMCAL"), fObjs("GRP ITS TPC TRD EMCAL"), fNoOCDB(kFALSE), fIsInit(kFALSE), fLocalOcdb(), fLocalOcdbStor() { // Constructor. } //________________________________________________________________________ AliEmcalSetupTask::AliEmcalSetupTask(const char *name) : AliAnalysisTaskSE(name), fOcdbPath("uselocal"), fOadbPath("$ALICE_ROOT/OADB/EMCAL"), fGeoPath("$ALICE_ROOT/OADB/EMCAL"), fObjs("GRP ITS TPC TRD EMCAL"), fNoOCDB(kFALSE), fIsInit(kFALSE), fLocalOcdb(), fLocalOcdbStor() { // Constructor. fBranchNames = "ESD:AliESDHeader.,AliESDRun."; } //________________________________________________________________________ AliEmcalSetupTask::~AliEmcalSetupTask() { // Destructor. } //________________________________________________________________________ void AliEmcalSetupTask::ConnectInputData(Option_t *option) { // Connect input data AliAnalysisTaskSE::ConnectInputData(option); if (fOcdbPath.Length()==0) return; AliCDBManager *man = AliCDBManager::Instance(); if (man->IsDefaultStorageSet()) return; if (fIsInit) return; AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) return; TObjArray *tasks = am->GetTasks(); if (!tasks) return; AliTender *tender = 0; for (Int_t i=0; i<tasks->GetEntries(); ++i) { tender = dynamic_cast<AliTender*>(tasks->At(i)); if (tender) break; } if (!tender) return; if (fOcdbPath != "uselocal") { tender->SetDefaultCDBStorage(fOcdbPath); return; } Int_t runno = AliAnalysisManager::GetAnalysisManager()->GetRunFromPath(); if (runno<=0) { AliWarning(Form("Disabling tender, ignore possible message from tender below")); tender->SetDefaultCDBStorage("donotuse"); return; } AliWarning(Form("Intercepting tender for run %d, ignore possible message from tender below", runno)); Setup(runno); tender->SetDefaultCDBStorage(fLocalOcdbStor); } //________________________________________________________________________ void AliEmcalSetupTask::UserExec(Option_t *) { // Main loop, called for each event. if (fIsInit) return; AliAnalysisManager *am = AliAnalysisManager::GetAnalysisManager(); if (!am) { AliError("Manager zero, returning"); return; } am->LoadBranch("AliESDRun."); am->LoadBranch("AliESDHeader."); Int_t runno = InputEvent()->GetRunNumber(); Setup(runno); } //________________________________________________________________________ void AliEmcalSetupTask::Setup(Int_t runno) { // Setup everything // Setup AliEMCALGeometry corresponding to year TString geoname("EMCAL_COMPLETE12SMV1_DCAL_8SM"); Int_t year = 2015; if (runno>0 && runno<=139517) { year = 2010; geoname = "EMCAL_FIRSTYEARV1"; } else if ((runno>139517) && (runno<=170593)) { year = 2011; geoname = "EMCAL_COMPLETEV1"; } else if ((runno>170593) && (runno<=193766)) { year = 2012; } else if ((runno>193766) && (runno <= 199161)) { geoname = "EMCAL_COMPLETE12SMV1"; year = 2013; } AliEMCALGeometry *geom = AliEMCALGeometry::GetInstance(geoname); if (!geom) { AliFatal(Form("Can not create geometry: %s",geoname.Data())); return; } if (runno<0) // Run number 0 can occur for MC return; // Setup CDB manager AliCDBManager *man = 0; if (!fNoOCDB) { man = AliCDBManager::Instance(); if (!man) AliFatal(Form("Did not get pointer to CDB manager")); if (man->IsDefaultStorageSet()) { AliInfo(Form("Default OCDB storage already set")); } else { if (fOcdbPath.Length()==0) { man = 0; // do not use OCDB } else if (fOcdbPath != "uselocal") { AliInfo(Form("Setting up OCDB to point to %s",fOcdbPath.Data())); man->SetDefaultStorage(fOcdbPath); } else { // use local copy of OCDB TString tmpdir=gSystem->WorkingDirectory(); if (gSystem->AccessPathName(tmpdir)) tmpdir = "/tmp"; tmpdir+="/"; tmpdir+=gSystem->GetUid(); tmpdir+="-"; TDatime t; tmpdir+=t.Get(); tmpdir+="-"; Int_t counter = 0; fLocalOcdb = tmpdir; fLocalOcdb += Form("%d%d%d",gRandom->Integer(999999999),gRandom->Integer(999999999),gRandom->Integer(999999999)); while (!gSystem->AccessPathName(fLocalOcdb)) { fLocalOcdb = tmpdir; fLocalOcdb += Form("%d%d%d",gRandom->Integer(999999999),gRandom->Integer(999999999),gRandom->Integer(999999999)); counter++; if (counter>100) { AliFatal(Form("Could not create local directory for OCDB at %s",tmpdir.Data())); } } gSystem->MakeDirectory(fLocalOcdb); TString filename(Form("$ALICE_ROOT/PWG/EMCAL/data/%d.dat",year)); TString cmd(Form("cd %s && tar -xf %s",fLocalOcdb.Data(),filename.Data())); Int_t ret = gSystem->Exec(cmd); if (ret==0) { TString locdb("local://"); locdb+=fLocalOcdb; locdb+="/"; locdb+=year; AliInfo(Form("Setting up local OCDB at %s",locdb.Data())); man->SetDefaultStorage(locdb); fLocalOcdbStor = locdb; } else { AliFatal(Form("Could not set up local OCDB at %s",fLocalOcdb.Data())); } } } } // Load geometry from OCDB if (man) { if (man->GetRun()!=runno) man->SetRun(runno); AliInfo(Form("Loading grp data from OCDB for run %d", runno)); AliGRPManager GRPManager; GRPManager.ReadGRPEntry(); GRPManager.SetMagField(); AliInfo(Form("Loading geometry from OCDB")); AliGeomManager::LoadGeometry(); if (!fObjs.IsNull()) AliGeomManager::ApplyAlignObjsFromCDB(fObjs); } // Load geometry from file (does not use misalignment of ITS/TPC!) TGeoManager *geo = AliGeomManager::GetGeometry(); if (!geo && fGeoPath.Length()>0) { TString fname(gSystem->ExpandPathName(Form("%s/geometry_%d.root", fGeoPath.Data(), year))); if (gSystem->AccessPathName(fname)==0) { AliInfo(Form("Loading geometry from file %s (should be avoided!)", fname.Data())); AliGeomManager::LoadGeometry(fname); geo = AliGeomManager::GetGeometry(); } } // Lock geometry if (geo) { AliInfo(Form("Locking geometry")); geo->LockGeometry(); } // Construct field map if (!TGeoGlobalMagField::Instance()->GetField()) { InputEvent()->InitMagneticField(); } // Apply mis-alignment matrices from OADB if (fOadbPath.Length()>0) { AliOADBContainer emcalgeoCont(Form("emcal")); emcalgeoCont.InitFromFile(Form("%s/EMCALlocal2master.root",fOadbPath.Data()), Form("AliEMCALgeo")); TObjArray *mobj=dynamic_cast<TObjArray*>(emcalgeoCont.GetObject(runno,"EmcalMatrices")); if (mobj) { for(Int_t mod=0; mod < (geom->GetEMCGeometry())->GetNumberOfSuperModules(); mod++){ //AliInfo(Form("Misalignment matrix %d", mod)); geom->SetMisalMatrix((TGeoHMatrix*) mobj->At(mod),mod); } } } fIsInit = kTRUE; } //________________________________________________________________________ void AliEmcalSetupTask::Terminate(Option_t *) { // Called at the end. if (fLocalOcdb.Length()>0) { TString cmd(Form("rm -rf %s", fLocalOcdb.Data())); gSystem->Exec(cmd); } }
Set EMCAL+DCAL geometry for 2015
Set EMCAL+DCAL geometry for 2015
C++
bsd-3-clause
amatyja/AliPhysics,ppribeli/AliPhysics,rderradi/AliPhysics,adriansev/AliPhysics,kreisl/AliPhysics,btrzecia/AliPhysics,SHornung1/AliPhysics,lfeldkam/AliPhysics,rbailhac/AliPhysics,dmuhlhei/AliPhysics,carstooon/AliPhysics,mazimm/AliPhysics,dstocco/AliPhysics,pbatzing/AliPhysics,aaniin/AliPhysics,fcolamar/AliPhysics,aaniin/AliPhysics,nschmidtALICE/AliPhysics,jgronefe/AliPhysics,dlodato/AliPhysics,jmargutt/AliPhysics,mvala/AliPhysics,jgronefe/AliPhysics,lcunquei/AliPhysics,rihanphys/AliPhysics,fbellini/AliPhysics,sebaleh/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,pchrista/AliPhysics,victor-gonzalez/AliPhysics,fcolamar/AliPhysics,lcunquei/AliPhysics,rderradi/AliPhysics,AMechler/AliPhysics,fbellini/AliPhysics,pbatzing/AliPhysics,preghenella/AliPhysics,mvala/AliPhysics,pchrista/AliPhysics,akubera/AliPhysics,pchrista/AliPhysics,dstocco/AliPhysics,mpuccio/AliPhysics,ALICEHLT/AliPhysics,hzanoli/AliPhysics,dmuhlhei/AliPhysics,adriansev/AliPhysics,rihanphys/AliPhysics,preghenella/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,AudreyFrancisco/AliPhysics,mpuccio/AliPhysics,jmargutt/AliPhysics,amatyja/AliPhysics,lcunquei/AliPhysics,alisw/AliPhysics,amatyja/AliPhysics,akubera/AliPhysics,fbellini/AliPhysics,victor-gonzalez/AliPhysics,preghenella/AliPhysics,yowatana/AliPhysics,rbailhac/AliPhysics,SHornung1/AliPhysics,sebaleh/AliPhysics,hcab14/AliPhysics,ALICEHLT/AliPhysics,akubera/AliPhysics,mazimm/AliPhysics,btrzecia/AliPhysics,nschmidtALICE/AliPhysics,mbjadhav/AliPhysics,btrzecia/AliPhysics,yowatana/AliPhysics,pbatzing/AliPhysics,rbailhac/AliPhysics,AMechler/AliPhysics,ppribeli/AliPhysics,alisw/AliPhysics,AudreyFrancisco/AliPhysics,amaringarcia/AliPhysics,kreisl/AliPhysics,nschmidtALICE/AliPhysics,lfeldkam/AliPhysics,amatyja/AliPhysics,jgronefe/AliPhysics,dstocco/AliPhysics,dlodato/AliPhysics,mkrzewic/AliPhysics,pbuehler/AliPhysics,mvala/AliPhysics,pbuehler/AliPhysics,jgronefe/AliPhysics,rbailhac/AliPhysics,pbatzing/AliPhysics,fbellini/AliPhysics,jgronefe/AliPhysics,pchrista/AliPhysics,rderradi/AliPhysics,jgronefe/AliPhysics,yowatana/AliPhysics,jgronefe/AliPhysics,yowatana/AliPhysics,aaniin/AliPhysics,btrzecia/AliPhysics,jmargutt/AliPhysics,mkrzewic/AliPhysics,AudreyFrancisco/AliPhysics,ALICEHLT/AliPhysics,sebaleh/AliPhysics,sebaleh/AliPhysics,mkrzewic/AliPhysics,amaringarcia/AliPhysics,rbailhac/AliPhysics,kreisl/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,fcolamar/AliPhysics,ALICEHLT/AliPhysics,lfeldkam/AliPhysics,mazimm/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,AudreyFrancisco/AliPhysics,carstooon/AliPhysics,nschmidtALICE/AliPhysics,rderradi/AliPhysics,ALICEHLT/AliPhysics,victor-gonzalez/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,carstooon/AliPhysics,amatyja/AliPhysics,mbjadhav/AliPhysics,dlodato/AliPhysics,hcab14/AliPhysics,mvala/AliPhysics,mbjadhav/AliPhysics,AMechler/AliPhysics,jmargutt/AliPhysics,amatyja/AliPhysics,hcab14/AliPhysics,ppribeli/AliPhysics,mazimm/AliPhysics,lfeldkam/AliPhysics,hcab14/AliPhysics,hzanoli/AliPhysics,amaringarcia/AliPhysics,mvala/AliPhysics,AudreyFrancisco/AliPhysics,AudreyFrancisco/AliPhysics,kreisl/AliPhysics,hzanoli/AliPhysics,dstocco/AliPhysics,hzanoli/AliPhysics,mazimm/AliPhysics,rihanphys/AliPhysics,akubera/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,btrzecia/AliPhysics,pbuehler/AliPhysics,alisw/AliPhysics,akubera/AliPhysics,mazimm/AliPhysics,victor-gonzalez/AliPhysics,carstooon/AliPhysics,dlodato/AliPhysics,mpuccio/AliPhysics,sebaleh/AliPhysics,pchrista/AliPhysics,mbjadhav/AliPhysics,mazimm/AliPhysics,dmuhlhei/AliPhysics,rbailhac/AliPhysics,ppribeli/AliPhysics,AMechler/AliPhysics,kreisl/AliPhysics,lfeldkam/AliPhysics,rderradi/AliPhysics,SHornung1/AliPhysics,fcolamar/AliPhysics,jmargutt/AliPhysics,victor-gonzalez/AliPhysics,dstocco/AliPhysics,btrzecia/AliPhysics,SHornung1/AliPhysics,AMechler/AliPhysics,pbatzing/AliPhysics,fbellini/AliPhysics,ppribeli/AliPhysics,dstocco/AliPhysics,adriansev/AliPhysics,kreisl/AliPhysics,jmargutt/AliPhysics,fbellini/AliPhysics,mvala/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,mvala/AliPhysics,ALICEHLT/AliPhysics,pbatzing/AliPhysics,carstooon/AliPhysics,SHornung1/AliPhysics,preghenella/AliPhysics,amaringarcia/AliPhysics,nschmidtALICE/AliPhysics,mkrzewic/AliPhysics,AMechler/AliPhysics,dlodato/AliPhysics,preghenella/AliPhysics,sebaleh/AliPhysics,adriansev/AliPhysics,nschmidtALICE/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,akubera/AliPhysics,amatyja/AliPhysics,mkrzewic/AliPhysics,rderradi/AliPhysics,hcab14/AliPhysics,sebaleh/AliPhysics,carstooon/AliPhysics,pbuehler/AliPhysics,adriansev/AliPhysics,lcunquei/AliPhysics,ALICEHLT/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,rihanphys/AliPhysics,rderradi/AliPhysics,mpuccio/AliPhysics,yowatana/AliPhysics,lfeldkam/AliPhysics,preghenella/AliPhysics,fcolamar/AliPhysics,aaniin/AliPhysics,amaringarcia/AliPhysics,dmuhlhei/AliPhysics,aaniin/AliPhysics,pbatzing/AliPhysics,aaniin/AliPhysics,hzanoli/AliPhysics,lcunquei/AliPhysics,lfeldkam/AliPhysics,jmargutt/AliPhysics,akubera/AliPhysics,ppribeli/AliPhysics,hcab14/AliPhysics,yowatana/AliPhysics,pbuehler/AliPhysics,dmuhlhei/AliPhysics,mpuccio/AliPhysics,dlodato/AliPhysics,victor-gonzalez/AliPhysics,mbjadhav/AliPhysics,carstooon/AliPhysics,alisw/AliPhysics,ppribeli/AliPhysics,hzanoli/AliPhysics,amaringarcia/AliPhysics,dstocco/AliPhysics,SHornung1/AliPhysics,rihanphys/AliPhysics,rihanphys/AliPhysics,pbuehler/AliPhysics,dlodato/AliPhysics,rbailhac/AliPhysics,pbuehler/AliPhysics,dmuhlhei/AliPhysics,alisw/AliPhysics,lcunquei/AliPhysics,aaniin/AliPhysics,yowatana/AliPhysics,hcab14/AliPhysics,mkrzewic/AliPhysics,nschmidtALICE/AliPhysics,mbjadhav/AliPhysics,fcolamar/AliPhysics,fbellini/AliPhysics,hzanoli/AliPhysics,mpuccio/AliPhysics,mpuccio/AliPhysics,mkrzewic/AliPhysics,btrzecia/AliPhysics
d29394c1860fbdf8089508b8c822c310d88fdb41
PWGPP/TRD/macros/makeTrending.C
PWGPP/TRD/macros/makeTrending.C
void makeTrending(const Char_t *fl, const Char_t *db = "$ALICE_ROOT/PWGPP/TRD/data/TRD.Trend.root", Bool_t relative=kFALSE) { gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libTENDER.so"); gSystem->Load("libCORRFW.so"); gSystem->Load("libPWGPP.so"); gSystem->Load("libPWGmuon.so"); AliTRDtrendingManager *tm = AliTRDtrendingManager::Instance(); tm->Load(db); tm->SetRelativeMeanSigma(relative); tm->MakeTrends(fl); return; }
void makeTrending(const Char_t *fl, Bool_t relative=kFALSE, const Char_t *db = "$ALICE_ROOT/PWGPP/TRD/data/TRD.Trend.root") { gSystem->Load("libANALYSIS.so"); gSystem->Load("libANALYSISalice.so"); gSystem->Load("libTENDER.so"); gSystem->Load("libCORRFW.so"); gSystem->Load("libPWGPP.so"); gSystem->Load("libPWGmuon.so"); AliTRDtrendingManager *tm = AliTRDtrendingManager::Instance(); tm->Load(db); tm->SetRelativeMeanSigma(relative); tm->MakeTrends(fl); return; }
rearrange the order of input parameters
rearrange the order of input parameters
C++
bsd-3-clause
fbellini/AliPhysics,kreisl/AliPhysics,alisw/AliPhysics,rderradi/AliPhysics,mazimm/AliPhysics,btrzecia/AliPhysics,SHornung1/AliPhysics,SHornung1/AliPhysics,dmuhlhei/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,AudreyFrancisco/AliPhysics,aaniin/AliPhysics,jgronefe/AliPhysics,nschmidtALICE/AliPhysics,pbatzing/AliPhysics,yowatana/AliPhysics,btrzecia/AliPhysics,fbellini/AliPhysics,hcab14/AliPhysics,SHornung1/AliPhysics,mpuccio/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,dlodato/AliPhysics,amaringarcia/AliPhysics,AMechler/AliPhysics,alisw/AliPhysics,yowatana/AliPhysics,lcunquei/AliPhysics,SHornung1/AliPhysics,pbuehler/AliPhysics,jmargutt/AliPhysics,mpuccio/AliPhysics,sebaleh/AliPhysics,rderradi/AliPhysics,dstocco/AliPhysics,fcolamar/AliPhysics,hcab14/AliPhysics,dstocco/AliPhysics,sebaleh/AliPhysics,aaniin/AliPhysics,rderradi/AliPhysics,hzanoli/AliPhysics,AMechler/AliPhysics,carstooon/AliPhysics,adriansev/AliPhysics,mazimm/AliPhysics,AMechler/AliPhysics,hzanoli/AliPhysics,hcab14/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,carstooon/AliPhysics,AudreyFrancisco/AliPhysics,mvala/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,SHornung1/AliPhysics,dlodato/AliPhysics,ppribeli/AliPhysics,sebaleh/AliPhysics,lfeldkam/AliPhysics,ppribeli/AliPhysics,lcunquei/AliPhysics,akubera/AliPhysics,dlodato/AliPhysics,mkrzewic/AliPhysics,mpuccio/AliPhysics,mbjadhav/AliPhysics,ALICEHLT/AliPhysics,mbjadhav/AliPhysics,rderradi/AliPhysics,amatyja/AliPhysics,hzanoli/AliPhysics,hcab14/AliPhysics,mvala/AliPhysics,ppribeli/AliPhysics,dmuhlhei/AliPhysics,mpuccio/AliPhysics,nschmidtALICE/AliPhysics,dmuhlhei/AliPhysics,jgronefe/AliPhysics,pbuehler/AliPhysics,lcunquei/AliPhysics,amatyja/AliPhysics,rderradi/AliPhysics,mpuccio/AliPhysics,dstocco/AliPhysics,rbailhac/AliPhysics,lcunquei/AliPhysics,lcunquei/AliPhysics,lfeldkam/AliPhysics,jmargutt/AliPhysics,mazimm/AliPhysics,ALICEHLT/AliPhysics,sebaleh/AliPhysics,pchrista/AliPhysics,jmargutt/AliPhysics,ppribeli/AliPhysics,preghenella/AliPhysics,AudreyFrancisco/AliPhysics,SHornung1/AliPhysics,alisw/AliPhysics,akubera/AliPhysics,AMechler/AliPhysics,kreisl/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,yowatana/AliPhysics,lfeldkam/AliPhysics,aaniin/AliPhysics,rihanphys/AliPhysics,pbatzing/AliPhysics,dstocco/AliPhysics,mvala/AliPhysics,alisw/AliPhysics,akubera/AliPhysics,kreisl/AliPhysics,amatyja/AliPhysics,fbellini/AliPhysics,mbjadhav/AliPhysics,ALICEHLT/AliPhysics,pbuehler/AliPhysics,mkrzewic/AliPhysics,hzanoli/AliPhysics,dstocco/AliPhysics,rihanphys/AliPhysics,ALICEHLT/AliPhysics,dlodato/AliPhysics,pchrista/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,fbellini/AliPhysics,hzanoli/AliPhysics,jgronefe/AliPhysics,hcab14/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,aaniin/AliPhysics,amaringarcia/AliPhysics,pbatzing/AliPhysics,jmargutt/AliPhysics,jgronefe/AliPhysics,carstooon/AliPhysics,mkrzewic/AliPhysics,victor-gonzalez/AliPhysics,jgronefe/AliPhysics,alisw/AliPhysics,mvala/AliPhysics,lfeldkam/AliPhysics,hcab14/AliPhysics,aaniin/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,ALICEHLT/AliPhysics,fcolamar/AliPhysics,preghenella/AliPhysics,lcunquei/AliPhysics,mkrzewic/AliPhysics,hzanoli/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,amatyja/AliPhysics,pchrista/AliPhysics,yowatana/AliPhysics,AMechler/AliPhysics,pchrista/AliPhysics,alisw/AliPhysics,victor-gonzalez/AliPhysics,amaringarcia/AliPhysics,ppribeli/AliPhysics,victor-gonzalez/AliPhysics,rihanphys/AliPhysics,pbuehler/AliPhysics,AudreyFrancisco/AliPhysics,kreisl/AliPhysics,aaniin/AliPhysics,hcab14/AliPhysics,yowatana/AliPhysics,carstooon/AliPhysics,sebaleh/AliPhysics,mazimm/AliPhysics,carstooon/AliPhysics,dstocco/AliPhysics,ALICEHLT/AliPhysics,ppribeli/AliPhysics,preghenella/AliPhysics,rbailhac/AliPhysics,mvala/AliPhysics,nschmidtALICE/AliPhysics,pbatzing/AliPhysics,btrzecia/AliPhysics,carstooon/AliPhysics,akubera/AliPhysics,nschmidtALICE/AliPhysics,mbjadhav/AliPhysics,fbellini/AliPhysics,mbjadhav/AliPhysics,lfeldkam/AliPhysics,mkrzewic/AliPhysics,aaniin/AliPhysics,amatyja/AliPhysics,btrzecia/AliPhysics,fcolamar/AliPhysics,pbatzing/AliPhysics,pbatzing/AliPhysics,mpuccio/AliPhysics,mbjadhav/AliPhysics,dmuhlhei/AliPhysics,kreisl/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,rihanphys/AliPhysics,amaringarcia/AliPhysics,mazimm/AliPhysics,pbuehler/AliPhysics,amatyja/AliPhysics,dlodato/AliPhysics,akubera/AliPhysics,mazimm/AliPhysics,btrzecia/AliPhysics,hzanoli/AliPhysics,jmargutt/AliPhysics,nschmidtALICE/AliPhysics,nschmidtALICE/AliPhysics,AMechler/AliPhysics,amatyja/AliPhysics,akubera/AliPhysics,ALICEHLT/AliPhysics,preghenella/AliPhysics,mvala/AliPhysics,fbellini/AliPhysics,amaringarcia/AliPhysics,mazimm/AliPhysics,SHornung1/AliPhysics,lfeldkam/AliPhysics,rderradi/AliPhysics,pbuehler/AliPhysics,lcunquei/AliPhysics,dlodato/AliPhysics,ppribeli/AliPhysics,jmargutt/AliPhysics,jmargutt/AliPhysics,rbailhac/AliPhysics,pchrista/AliPhysics,pchrista/AliPhysics,lfeldkam/AliPhysics,adriansev/AliPhysics,rderradi/AliPhysics,AudreyFrancisco/AliPhysics,rihanphys/AliPhysics,pbuehler/AliPhysics,victor-gonzalez/AliPhysics,dmuhlhei/AliPhysics,rbailhac/AliPhysics,AudreyFrancisco/AliPhysics,victor-gonzalez/AliPhysics,btrzecia/AliPhysics,sebaleh/AliPhysics,kreisl/AliPhysics,sebaleh/AliPhysics,btrzecia/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,AMechler/AliPhysics,dstocco/AliPhysics,fcolamar/AliPhysics,amaringarcia/AliPhysics,dmuhlhei/AliPhysics,jgronefe/AliPhysics,dlodato/AliPhysics,rbailhac/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,adriansev/AliPhysics,preghenella/AliPhysics,dmuhlhei/AliPhysics,AudreyFrancisco/AliPhysics,pbatzing/AliPhysics,akubera/AliPhysics,preghenella/AliPhysics,jgronefe/AliPhysics,fbellini/AliPhysics,fcolamar/AliPhysics,rihanphys/AliPhysics,mbjadhav/AliPhysics
8d9550d471d69a548b8adfb1c8c04b370bd18bf6
python/stromx/imgutil/Image.cpp
python/stromx/imgutil/Image.cpp
/* * Copyright 2011 Matthias Fuchs * * 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 <stromx/runtime/DataContainer.h> #include <stromx/runtime/DataVariant.h> #include <stromx/runtime/Data.h> #include <stromx/runtime/Image.h> #include <stromx/imgutil/Image.h> #include <memory> #include <boost/python.hpp> using namespace boost::python; using namespace stromx::runtime; namespace { std::auto_ptr<stromx::imgutil::Image> allocateFromDimension(const unsigned int width, const unsigned int height, const Image::PixelType pixelType) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(width, height, pixelType)); } std::auto_ptr<stromx::imgutil::Image> allocateFromFile(const std::string & filename) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(filename)); } std::auto_ptr<stromx::imgutil::Image> allocateFromFileWithAccess(const std::string & filename, const stromx::imgutil::Image::FileAccess access) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(filename, access)); } } void exportImage() { enum_<stromx::imgutil::Image::FileAccess>("ImageFileAccess") .value("UNCHANGED", stromx::imgutil::Image::UNCHANGED) .value("GRAYSCALE", stromx::imgutil::Image::GRAYSCALE) .value("COLOR", stromx::imgutil::Image::COLOR) ; class_<stromx::imgutil::Image, bases<stromx::runtime::Image>, std::auto_ptr<stromx::imgutil::Image> >("Image", no_init) .def("__init__", make_constructor(&allocateFromFile)) .def("__init__", make_constructor(&allocateFromDimension)) .def("__init__", make_constructor(&allocateFromFileWithAccess)) .def<void (stromx::imgutil::Image::*)(const std::string &) const>("save", &stromx::imgutil::Image::save) .def<void (stromx::imgutil::Image::*)(const std::string &)>("open", &stromx::imgutil::Image::open) .def<void (stromx::imgutil::Image::*)(const std::string &, const stromx::imgutil::Image::FileAccess)>("open", &stromx::imgutil::Image::open) .def<void (stromx::imgutil::Image::*)(const unsigned int, const unsigned int, const Image::PixelType)>("resize", &stromx::imgutil::Image::resize) ; implicitly_convertible< std::auto_ptr<stromx::imgutil::Image>, std::auto_ptr<Data> >(); }
/* * Copyright 2011 Matthias Fuchs * * 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 <stromx/runtime/DataContainer.h> #include <stromx/runtime/DataVariant.h> #include <stromx/runtime/Data.h> #include <stromx/runtime/Image.h> #include <stromx/imgutil/Image.h> #include <memory> #include <boost/python.hpp> using namespace boost::python; using namespace stromx::runtime; namespace { std::auto_ptr<stromx::imgutil::Image> allocateFromDimension(const unsigned int width, const unsigned int height, const Image::PixelType pixelType) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(width, height, pixelType)); } std::auto_ptr<stromx::imgutil::Image> allocateFromFile(const std::string & filename) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(filename)); } std::auto_ptr<stromx::imgutil::Image> allocateFromFileWithAccess(const std::string & filename, const stromx::imgutil::Image::FileAccess access) { return std::auto_ptr<stromx::imgutil::Image>(new stromx::imgutil::Image(filename, access)); } } void exportImage() { enum_<stromx::imgutil::Image::FileAccess>("ImageFileAccess") .value("UNCHANGED", stromx::imgutil::Image::UNCHANGED) .value("GRAYSCALE", stromx::imgutil::Image::GRAYSCALE) .value("COLOR", stromx::imgutil::Image::COLOR) ; scope in_Operator = class_<stromx::imgutil::Image, bases<stromx::runtime::Image>, std::auto_ptr<stromx::imgutil::Image> >("Image", no_init) .def("__init__", make_constructor(&allocateFromFile)) .def("__init__", make_constructor(&allocateFromDimension)) .def("__init__", make_constructor(&allocateFromFileWithAccess)) .def<void (stromx::imgutil::Image::*)(const std::string &) const>("save", &stromx::imgutil::Image::save) .def<void (stromx::imgutil::Image::*)(const std::string &)>("open", &stromx::imgutil::Image::open) .def<void (stromx::imgutil::Image::*)(const std::string &, const stromx::imgutil::Image::FileAccess)>("open", &stromx::imgutil::Image::open) .def<void (stromx::imgutil::Image::*)(const unsigned int, const unsigned int, const Image::PixelType)>("resize", &stromx::imgutil::Image::resize) ; implicitly_convertible< std::auto_ptr<stromx::imgutil::Image>, std::auto_ptr<Data> >(); }
Fix file access enum in Python wrapper
Fix file access enum in Python wrapper
C++
apache-2.0
sparsebase/stromx,sparsebase/stromx,uboot/stromx,uboot/stromx
c9e14758bdb0ad65741afac57bbe7f9f82e9967f
dune/stuff/grid/periodicview.hh
dune/stuff/grid/periodicview.hh
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Tobias Leibner #ifndef DUNE_STUFF_GRID_PERIODICVIEW_HH #define DUNE_STUFF_GRID_PERIODICVIEW_HH #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/memory.hh> namespace Dune { namespace Stuff { namespace Grid { template< class RealGridViewImp > class PeriodicIntersection : public RealGridViewImp::Intersection { typedef PeriodicIntersection < RealGridViewImp > ThisType; typedef typename RealGridViewImp::Intersection BaseType; typedef typename BaseType::LocalGeometry LocalGeometry; typedef typename BaseType::EntityPointer EntityPointer; public: //! \brief Constructor from real intersection PeriodicIntersection ( const BaseType& real_intersection ) : BaseType(real_intersection) {} //! \brief Copy operator from existing PeriodicIntersection const ThisType operator=(ThisType other) { real = other.real; return *this; } // methods that differ from BaseType bool neighbor () const { return real.neighbor(); } EntityPointer outside() const { if (neighbor()) return ((BaseType*)this)->outside(); else // do fancy stuff return ((BaseType*)this)->outside(); } LocalGeometry geometryInOutside () const { if (((BaseType*)this)->neighbor()) return ((BaseType*)this)->geometryInOutside(); else return ((BaseType*)this)->geometryInOutside(); //find periodic neighbor entity and corresponding intersection and use geometryinInside for that Intersection } int indexInOutside () const { if (((BaseType*)this)->neighbor()) return ((BaseType*)this)->indexInOutside(); else return ((BaseType*)this)->indexInOutside(); //find periodic neighbor entity and corresponding intersection and use indexInInside for that Intersection } protected: using BaseType::real; }; // ... class PeriodicIntersection ... template< class RealGridViewImp > class PeriodicIntersectionIterator : public RealGridViewImp::IntersectionIterator { typedef RealGridViewImp GridViewType; typedef PeriodicIntersectionIterator< GridViewType > ThisType; typedef typename GridViewType::IntersectionIterator BaseType; typedef PeriodicIntersection< GridViewType > Intersection; public: /** Copy Constructor from real intersection iterator */ PeriodicIntersectionIterator ( BaseType& real_intersection_iterator ) : BaseType( real_intersection_iterator ) , current_intersection_(((BaseType*)this)->operator*()) {} /** Copy Constructor from real intersection iterator, pass by value */ PeriodicIntersectionIterator ( BaseType real_intersection_iterator ) : BaseType( real_intersection_iterator ) , current_intersection_(((BaseType*)this)->operator*()) {} // methods that differ from BaseType const Intersection& operator*() const { return current_intersection_; } const Intersection* operator->() const { return &current_intersection_; } ThisType& operator++() { BaseType::operator++(); current_intersection_ = Intersection(BaseType::operator*()); return *this; } bool operator==(const PeriodicIntersectionIterator& rhs) const { return rhs.equals(*this); } bool operator!=(const PeriodicIntersectionIterator& rhs) const { return ! rhs.equals(*this); } bool equals(const PeriodicIntersectionIterator& rhs) const { return ((BaseType*)this)->equals(BaseType(rhs)); } private: Intersection current_intersection_; }; // ... class PeriodicIntersectionIterator ... //forward template < class RealGridViewImp > class PeriodicGridViewImp; template < class RealGridViewImp > class PeriodicGridViewTraits { public: typedef RealGridViewImp RealGridViewType; // use types from RealGridViewType... typedef PeriodicGridViewImp < RealGridViewType > GridViewImp; typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; typedef typename RealGridViewType::Traits RealGridViewTraits; template< int cd > struct Codim { //TODO: replace this at least for cd == 1 later? typedef typename RealGridViewTraits::template Codim<cd>::Iterator Iterator; typedef typename RealGridViewTraits::template Codim<cd>::EntityPointer EntityPointer; typedef typename RealGridViewTraits::template Codim<cd>::Entity Entity; typedef typename RealGridViewTraits::template Codim<cd>::Geometry Geometry; typedef typename RealGridViewTraits::template Codim<cd>::LocalGeometry LocalGeometry; template< PartitionIteratorType pit > struct Partition { typedef typename RealGridViewTraits :: template Codim< cd > :: template Partition< pit > :: Iterator Iterator; }; }; // ... struct Codim ... enum { conforming = RealGridViewTraits :: conforming }; enum { dimension = Grid :: dimension }; enum { dimensionworld = Grid :: dimensionworld }; typedef typename Grid::ctype ctype; // ...except for the Intersection and IntersectionIterator typedef PeriodicIntersection < RealGridViewType > Intersection; typedef PeriodicIntersectionIterator < RealGridViewType > IntersectionIterator; }; // ... class PeriodicGridViewTraits ... template< class RealGridViewImp > class PeriodicGridViewImp { typedef RealGridViewImp RealGridViewType; typedef PeriodicGridViewImp< RealGridViewType > ThisType; typedef PeriodicGridViewTraits< RealGridViewType > Traits; public: typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename Dune::GeometryType GeometryType; typedef PeriodicIntersectionIterator< RealGridViewType > IntersectionIterator; typedef PeriodicIntersection< RealGridViewType > Intersection; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; template< int cd > struct Codim : public Traits::template Codim<cd> {}; /** Constructor from real grid view */ PeriodicGridViewImp ( const RealGridViewType& real_grid_view ) : real_grid_view_(real_grid_view) {} // forward methods to real grid view ... const Grid &grid () const { return real_grid_view_.grid(); } const IndexSet &indexSet () const { return real_grid_view_.indexSet(); } int size (int codim) const { return real_grid_view_.size( codim ); } int size (const GeometryType &type) const { return real_grid_view_.size(type); } template<class EntityType> bool contains (const EntityType& e) const { return real_grid_view_.indexSet().contains(e); } template< int cd > typename Codim< cd >::Iterator begin () const //TODO: change at least for cd == 1 to PeriodicIterator { return real_grid_view_.template begin< cd >(); } template< int cd > typename Codim< cd >::Iterator end () const { return real_grid_view_.template end< cd >(); } template< int cd , PartitionIteratorType pitype > typename Codim< cd >::template Partition< pitype >::Iterator begin () const { return real_grid_view_.template begin< cd, pitype >(); } template< int cd, PartitionIteratorType pitype > typename Codim< cd >::template Partition< pitype >::Iterator end () const { return real_grid_view_.template end< cd, pitype >(); } const CollectiveCommunication &comm () const { return real_grid_view_.comm(); } int overlapSize(int codim) const { return real_grid_view_.overlapSize(codim); } int ghostSize(int codim) const { return real_grid_view_.ghostSize(codim); } template< class DataHandleImp, class DataType > void communicate (CommDataHandleIF< DataHandleImp, DataType >& data, InterfaceType iftype, CommunicationDirection dir) const { real_grid_view_.communicate(data, iftype, dir); } // ... except for the intersection iterators IntersectionIterator ibegin (const typename Codim< 0 >::Entity &entity) const { return IntersectionIterator(real_grid_view_.ibegin(entity)); } IntersectionIterator iend (const typename Codim< 0 >::Entity &entity) const { return IntersectionIterator(real_grid_view_.iend(entity)); } private: const RealGridViewType& real_grid_view_; }; // ... class PeriodicGridViewImp ... template< class RealGridViewImp > class PeriodicGridView : Dune::Stuff::Common::ConstStorageProvider< PeriodicGridViewImp < RealGridViewImp > > , public Dune::GridView< PeriodicGridViewTraits < RealGridViewImp > > { typedef RealGridViewImp RealGridViewType; typedef typename Dune::GridView < PeriodicGridViewTraits < RealGridViewType > > BaseType; typedef typename Dune::Stuff::Common::ConstStorageProvider< PeriodicGridViewImp < RealGridViewImp > > ConstStorProv; public: PeriodicGridView(const RealGridViewType& real_grid_view) : ConstStorProv(new PeriodicGridViewImp< RealGridViewType >(real_grid_view)) , BaseType(ConstStorProv::access()) {} PeriodicGridView(const PeriodicGridView& other) : ConstStorProv(other.access()) , BaseType(ConstStorProv::access()) {} }; } // namespace Grid } // namespace Stuff } // namespace Dune #endif // #ifndef DUNE_STUFF_GRID_PERIODICVIEW_HH
// This file is part of the dune-stuff project: // https://github.com/wwu-numerik/dune-stuff/ // Copyright holders: Rene Milk, Felix Schindler // License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) // // Contributors: Tobias Leibner #ifndef DUNE_STUFF_GRID_PERIODICVIEW_HH #define DUNE_STUFF_GRID_PERIODICVIEW_HH #include <bitset> #include <vector> #include <dune/grid/common/gridview.hh> #include <dune/stuff/common/memory.hh> #include <dune/stuff/common/float_cmp.hh> #include <dune/stuff/grid/search.hh> #include <dune/stuff/common/string.hh> namespace Dune { namespace Stuff { namespace Grid { template< class RealGridViewImp > class PeriodicIntersection : public RealGridViewImp::Intersection { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersection< RealGridViewType > ThisType; typedef typename RealGridViewType::Intersection BaseType; typedef typename BaseType::LocalGeometry LocalGeometry; typedef typename BaseType::Geometry::GlobalCoordinate GlobalCoordinate; typedef typename BaseType::EntityPointer EntityPointer; static const size_t dimDomain = RealGridViewType::dimension; public: //! \brief Constructor from real intersection PeriodicIntersection(const BaseType& real_intersection, const RealGridViewType& real_grid_view, const std::bitset< dimDomain > periodic_directions) : BaseType(real_intersection) , periodic_(false) , real_grid_view_(&real_grid_view) , periodic_neighbor_coords_(1) , num_boundary_coords_(0) { if (BaseType::boundary()) { periodic_neighbor_coords_[0] = BaseType::geometry().center(); for (std::size_t ii = 0; ii < dimDomain; ++ii) { if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords_[0][ii], 0.0)) { if (periodic_directions[ii]) { periodic_ = true; periodic_neighbor_coords_[0][ii] = 1.0; ++num_boundary_coords_; } } else if (Dune::Stuff::Common::FloatCmp::eq(periodic_neighbor_coords_[0][ii], 1.0)) { if (periodic_directions[ii]) { periodic_ = true; periodic_neighbor_coords_[0][ii] = 0.0; ++num_boundary_coords_; } } } assert(num_boundary_coords_ = 1); } } // constructor //! \brief Copy operator from existing PeriodicIntersection const ThisType operator=(ThisType other) { real = other.real; periodic_ = other.periodic_; periodic_neighbor_coords_ = other.periodic_neighbor_coords_; real_grid_view_ = other.real_grid_view_; return *this; } // methods that differ from BaseType bool neighbor() const { if (periodic_) return true; else return BaseType::neighbor(); } bool boundary() const { if (periodic_) { return false; } else { if (BaseType::boundary()) { std::cout << "Komisch " << BaseType::geometry().center() << std::endl; } return BaseType::boundary(); } } EntityPointer outside() const { if (periodic_) return *(Dune::Stuff::Grid::EntityInlevelSearch< RealGridViewType >(*real_grid_view_).operator()(periodic_neighbor_coords_)[0]); else return BaseType::outside(); } LocalGeometry geometryInOutside() const { if (periodic_) { auto& outside_entity = outside(); for (auto i_it = real_grid_view_->ibegin(outside_entity); i_it != real_grid_view_->iend(outside_entity); ++i_it) { auto& intersection = *i_it; if (Dune::Stuff::Common::FloatCmp::eq(intersection.geometry().center(), periodic_neighbor_coords_[0])) return intersection.geometryInInside(); } } else return BaseType::geometryInOutside(); } //geometryInOutSide int indexInOutside() const { if (periodic_) { auto& outside_entity = outside(); for (auto i_it = *real_grid_view_->ibegin(outside_entity); i_it != real_grid_view_->iend(outside_entity); ++i_it) { auto& intersection = *i_it; if (Dune::Stuff::Common::FloatCmp::eq(intersection.geometry().center(), periodic_neighbor_coords_[0])) return intersection.indexInInside(); } } else return BaseType::indexInOutside(); } protected: using BaseType::real; bool periodic_; std::vector< GlobalCoordinate > periodic_neighbor_coords_; const RealGridViewType* real_grid_view_; std::size_t num_boundary_coords_; }; // ... class PeriodicIntersection ... template< class RealGridViewImp > class PeriodicIntersectionIterator : public RealGridViewImp::IntersectionIterator { typedef RealGridViewImp RealGridViewType; typedef PeriodicIntersectionIterator< RealGridViewType > ThisType; typedef typename RealGridViewType::IntersectionIterator BaseType; typedef PeriodicIntersection< RealGridViewType > Intersection; typedef typename RealGridViewType::template Codim< 0 >::Entity EntityType; static const size_t dimDomain = RealGridViewType::dimension; public: /** Copy Constructor from real intersection iterator */ PeriodicIntersectionIterator(BaseType& real_intersection_iterator, const RealGridViewType& real_grid_view, const std::bitset< dimDomain > periodic_directions, const EntityType& entity) : BaseType(real_intersection_iterator) , current_intersection_((real_intersection_iterator == real_grid_view.iend(entity)) ? *real_grid_view.ibegin(entity) : BaseType::operator*(), real_grid_view, periodic_directions) , periodic_directions_(periodic_directions) , real_grid_view_(real_grid_view) , entity_(entity) {} /** Copy Constructor from real intersection iterator, pass by value */ PeriodicIntersectionIterator(BaseType real_intersection_iterator, const RealGridViewType& real_grid_view, const std::bitset< dimDomain > periodic_directions, const EntityType& entity) : BaseType(real_intersection_iterator) , current_intersection_((real_intersection_iterator == real_grid_view.iend(entity)) ? *real_grid_view.ibegin(entity) : BaseType::operator*(), real_grid_view, periodic_directions) , periodic_directions_(periodic_directions) , real_grid_view_(real_grid_view) , entity_(entity) {} // methods that differ from BaseType const Intersection& operator*() const { return current_intersection_; } const Intersection* operator->() const { return &current_intersection_; } ThisType& operator++() { BaseType::operator++(); current_intersection_ = Intersection(BaseType::equals(real_grid_view_.iend(entity_)) ? *real_grid_view_.ibegin(entity_) : BaseType::operator*(), real_grid_view_, periodic_directions_); return *this; } bool operator==(const PeriodicIntersectionIterator& rhs) const { return rhs.equals(*this); } bool operator!=(const PeriodicIntersectionIterator& rhs) const { return ! rhs.equals(*this); } bool equals(const PeriodicIntersectionIterator& rhs) const { return BaseType::equals(BaseType(rhs)) && (current_intersection_ == rhs.current_intersection_); } private: Intersection current_intersection_; std::bitset< dimDomain > periodic_directions_; const RealGridViewType& real_grid_view_; const EntityType& entity_; }; // ... class PeriodicIntersectionIterator ... //forward template < class RealGridViewImp > class PeriodicGridViewImp; template < class RealGridViewImp > class PeriodicGridViewTraits { public: typedef RealGridViewImp RealGridViewType; // use types from RealGridViewType... typedef PeriodicGridViewImp< RealGridViewType > GridViewImp; typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; typedef typename RealGridViewType::Traits RealGridViewTraits; template< int cd > struct Codim { //TODO: replace this at least for cd == 1 later? typedef typename RealGridViewTraits::template Codim< cd >::Iterator Iterator; typedef typename RealGridViewTraits::template Codim< cd >::EntityPointer EntityPointer; typedef typename RealGridViewTraits::template Codim< cd >::Entity Entity; typedef typename RealGridViewTraits::template Codim< cd >::Geometry Geometry; typedef typename RealGridViewTraits::template Codim< cd >::LocalGeometry LocalGeometry; template< PartitionIteratorType pit > struct Partition { typedef typename RealGridViewTraits::template Codim< cd >::template Partition< pit >::Iterator Iterator; }; }; // ... struct Codim ... enum { conforming = RealGridViewTraits::conforming }; enum { dimension = Grid::dimension }; enum { dimensionworld = Grid::dimensionworld }; typedef typename Grid::ctype ctype; // ...except for the Intersection and IntersectionIterator typedef PeriodicIntersection< RealGridViewType > Intersection; typedef PeriodicIntersectionIterator< RealGridViewType > IntersectionIterator; }; // ... class PeriodicGridViewTraits ... template< class RealGridViewImp > class PeriodicGridViewImp { typedef RealGridViewImp RealGridViewType; typedef PeriodicGridViewImp< RealGridViewType > ThisType; typedef PeriodicGridViewTraits< RealGridViewType > Traits; public: typedef typename RealGridViewType::Grid Grid; typedef typename RealGridViewType::IndexSet IndexSet; typedef typename Dune::GeometryType GeometryType; typedef PeriodicIntersectionIterator< RealGridViewType > IntersectionIterator; typedef PeriodicIntersection< RealGridViewType > Intersection; typedef typename RealGridViewType::CollectiveCommunication CollectiveCommunication; static const size_t dimDomain = RealGridViewType::dimension; template< int cd > struct Codim : public Traits::template Codim< cd > {}; /** Constructor from real grid view */ PeriodicGridViewImp(const RealGridViewType& real_grid_view, const std::bitset< dimDomain > periodic_directions) : real_grid_view_(real_grid_view) , periodic_directions_(periodic_directions) {} // forward methods to real grid view ... const Grid &grid () const { return real_grid_view_.grid(); } const IndexSet &indexSet () const { return real_grid_view_.indexSet(); } int size (int codim) const { return real_grid_view_.size(codim); } int size (const GeometryType &type) const { return real_grid_view_.size(type); } template<class EntityType> bool contains (const EntityType& e) const { return real_grid_view_.indexSet().contains(e); } template< int cd > typename Codim< cd >::Iterator begin () const //TODO: change at least for cd == 1 to PeriodicIterator { return real_grid_view_.template begin< cd >(); } template< int cd > typename Codim< cd >::Iterator end () const { return real_grid_view_.template end< cd >(); } template< int cd , PartitionIteratorType pitype > typename Codim< cd >::template Partition< pitype >::Iterator begin () const { return real_grid_view_.template begin< cd, pitype >(); } template< int cd, PartitionIteratorType pitype > typename Codim< cd >::template Partition< pitype >::Iterator end () const { return real_grid_view_.template end< cd, pitype >(); } const CollectiveCommunication &comm () const { return real_grid_view_.comm(); } int overlapSize(int codim) const { return real_grid_view_.overlapSize(codim); } int ghostSize(int codim) const { return real_grid_view_.ghostSize(codim); } template< class DataHandleImp, class DataType > void communicate (CommDataHandleIF< DataHandleImp, DataType >& data, InterfaceType iftype, CommunicationDirection dir) const { real_grid_view_.communicate(data, iftype, dir); } // ... except for the intersection iterators IntersectionIterator ibegin (const typename Codim< 0 >::Entity &entity) const { return IntersectionIterator(real_grid_view_.ibegin(entity), real_grid_view_, periodic_directions_, entity); } IntersectionIterator iend (const typename Codim< 0 >::Entity &entity) const { return IntersectionIterator(real_grid_view_.iend(entity), real_grid_view_, periodic_directions_, entity); } private: const RealGridViewType& real_grid_view_; const std::bitset< dimDomain > periodic_directions_; }; // ... class PeriodicGridViewImp ... template< class RealGridViewImp > class PeriodicGridView : Dune::Stuff::Common::ConstStorageProvider< PeriodicGridViewImp< RealGridViewImp > > , public Dune::GridView< PeriodicGridViewTraits< RealGridViewImp > > { typedef RealGridViewImp RealGridViewType; typedef typename Dune::GridView < PeriodicGridViewTraits< RealGridViewType > > BaseType; typedef typename Dune::Stuff::Common::ConstStorageProvider< PeriodicGridViewImp< RealGridViewImp > > ConstStorProv; static const size_t dimDomain = RealGridViewType::dimension; public: PeriodicGridView(const RealGridViewType& real_grid_view, const std::bitset< dimDomain > periodic_directions = std::bitset< dimDomain >().set()) : ConstStorProv(new PeriodicGridViewImp< RealGridViewType >(real_grid_view, periodic_directions)) , BaseType(ConstStorProv::access()) {} PeriodicGridView(const PeriodicGridView& other) : ConstStorProv(other.access()) , BaseType(ConstStorProv::access()) {} }; // ... class PeriodicGridView ... } // namespace Grid } // namespace Stuff } // namespace Dune #endif //DUNE_STUFF_GRID_PERIODICVIEW_HH
fix errors, add bitset to choose periodic directions
[grid.periodicview] fix errors, add bitset to choose periodic directions
C++
bsd-2-clause
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
8a95a056f54164e19a90718ca4126611f2c0213c
api/java/jni/androidvideocapturer_jni.cc
api/java/jni/androidvideocapturer_jni.cc
/* * Copyright 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/api/java/jni/androidvideocapturer_jni.h" #include "webrtc/api/java/jni/classreferenceholder.h" #include "webrtc/api/java/jni/native_handle_impl.h" #include "webrtc/api/java/jni/surfacetexturehelper_jni.h" #include "third_party/libyuv/include/libyuv/convert.h" #include "third_party/libyuv/include/libyuv/scale.h" #include "webrtc/base/bind.h" namespace webrtc_jni { jobject AndroidVideoCapturerJni::application_context_ = nullptr; // static int AndroidVideoCapturerJni::SetAndroidObjects(JNIEnv* jni, jobject appliction_context) { if (application_context_) { jni->DeleteGlobalRef(application_context_); } application_context_ = NewGlobalRef(jni, appliction_context); return 0; } AndroidVideoCapturerJni::AndroidVideoCapturerJni(JNIEnv* jni, jobject j_video_capturer, jobject j_egl_context) : j_video_capturer_(jni, j_video_capturer), j_video_capturer_class_(jni, FindClass(jni, "org/webrtc/VideoCapturer")), j_observer_class_( jni, FindClass(jni, "org/webrtc/VideoCapturer$NativeObserver")), surface_texture_helper_(SurfaceTextureHelper::create( jni, "Camera SurfaceTextureHelper", j_egl_context)), capturer_(nullptr) { LOG(LS_INFO) << "AndroidVideoCapturerJni ctor"; thread_checker_.DetachFromThread(); } AndroidVideoCapturerJni::~AndroidVideoCapturerJni() { LOG(LS_INFO) << "AndroidVideoCapturerJni dtor"; jni()->CallVoidMethod( *j_video_capturer_, GetMethodID(jni(), *j_video_capturer_class_, "dispose", "()V")); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.dispose()"; } void AndroidVideoCapturerJni::Start(int width, int height, int framerate, webrtc::AndroidVideoCapturer* capturer) { LOG(LS_INFO) << "AndroidVideoCapturerJni start"; RTC_DCHECK(thread_checker_.CalledOnValidThread()); { rtc::CritScope cs(&capturer_lock_); RTC_CHECK(capturer_ == nullptr); RTC_CHECK(invoker_.get() == nullptr); capturer_ = capturer; invoker_.reset(new rtc::GuardedAsyncInvoker()); } jobject j_frame_observer = jni()->NewObject(*j_observer_class_, GetMethodID(jni(), *j_observer_class_, "<init>", "(J)V"), jlongFromPointer(this)); CHECK_EXCEPTION(jni()) << "error during NewObject"; jmethodID m = GetMethodID( jni(), *j_video_capturer_class_, "startCapture", "(IIILorg/webrtc/SurfaceTextureHelper;Landroid/content/Context;" "Lorg/webrtc/VideoCapturer$CapturerObserver;)V"); jni()->CallVoidMethod( *j_video_capturer_, m, width, height, framerate, surface_texture_helper_ ? surface_texture_helper_->GetJavaSurfaceTextureHelper() : nullptr, application_context_, j_frame_observer); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.startCapture"; } void AndroidVideoCapturerJni::Stop() { LOG(LS_INFO) << "AndroidVideoCapturerJni stop"; RTC_DCHECK(thread_checker_.CalledOnValidThread()); { rtc::CritScope cs(&capturer_lock_); // Destroying |invoker_| will cancel all pending calls to |capturer_|. invoker_ = nullptr; capturer_ = nullptr; } jmethodID m = GetMethodID(jni(), *j_video_capturer_class_, "stopCapture", "()V"); jni()->CallVoidMethod(*j_video_capturer_, m); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.stopCapture"; LOG(LS_INFO) << "AndroidVideoCapturerJni stop done"; } template <typename... Args> void AndroidVideoCapturerJni::AsyncCapturerInvoke( const char* method_name, void (webrtc::AndroidVideoCapturer::*method)(Args...), typename Identity<Args>::type... args) { rtc::CritScope cs(&capturer_lock_); if (!invoker_) { LOG(LS_WARNING) << method_name << "() called for closed capturer."; return; } invoker_->AsyncInvoke<void>(rtc::Bind(method, capturer_, args...)); } std::vector<cricket::VideoFormat> AndroidVideoCapturerJni::GetSupportedFormats() { JNIEnv* jni = AttachCurrentThreadIfNeeded(); jobject j_list_of_formats = jni->CallObjectMethod( *j_video_capturer_, GetMethodID(jni, *j_video_capturer_class_, "getSupportedFormats", "()Ljava/util/List;")); CHECK_EXCEPTION(jni) << "error during getSupportedFormats"; // Extract Java List<CaptureFormat> to std::vector<cricket::VideoFormat>. jclass j_list_class = jni->FindClass("java/util/List"); jclass j_format_class = jni->FindClass("org/webrtc/CameraEnumerationAndroid$CaptureFormat"); jclass j_framerate_class = jni->FindClass( "org/webrtc/CameraEnumerationAndroid$CaptureFormat$FramerateRange"); const int size = jni->CallIntMethod( j_list_of_formats, GetMethodID(jni, j_list_class, "size", "()I")); jmethodID j_get = GetMethodID(jni, j_list_class, "get", "(I)Ljava/lang/Object;"); jfieldID j_framerate_field = GetFieldID( jni, j_format_class, "framerate", "Lorg/webrtc/CameraEnumerationAndroid$CaptureFormat$FramerateRange;"); jfieldID j_width_field = GetFieldID(jni, j_format_class, "width", "I"); jfieldID j_height_field = GetFieldID(jni, j_format_class, "height", "I"); jfieldID j_max_framerate_field = GetFieldID(jni, j_framerate_class, "max", "I"); std::vector<cricket::VideoFormat> formats; formats.reserve(size); for (int i = 0; i < size; ++i) { jobject j_format = jni->CallObjectMethod(j_list_of_formats, j_get, i); jobject j_framerate = GetObjectField(jni, j_format, j_framerate_field); const int frame_interval = cricket::VideoFormat::FpsToInterval( (GetIntField(jni, j_framerate, j_max_framerate_field) + 999) / 1000); formats.emplace_back(GetIntField(jni, j_format, j_width_field), GetIntField(jni, j_format, j_height_field), frame_interval, cricket::FOURCC_NV21); } CHECK_EXCEPTION(jni) << "error while extracting formats"; return formats; } void AndroidVideoCapturerJni::OnCapturerStarted(bool success) { LOG(LS_INFO) << "AndroidVideoCapturerJni capture started: " << success; AsyncCapturerInvoke("OnCapturerStarted", &webrtc::AndroidVideoCapturer::OnCapturerStarted, success); } void AndroidVideoCapturerJni::OnMemoryBufferFrame(void* video_frame, int length, int width, int height, int rotation, int64_t timestamp_ns) { RTC_DCHECK(rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270); rtc::CritScope cs(&capturer_lock_); int adapted_width; int adapted_height; int crop_width; int crop_height; int crop_x; int crop_y; if (!capturer_->AdaptFrame(width, height, timestamp_ns, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) { return; } int rotated_width = crop_width; int rotated_height = crop_height; if (capturer_->apply_rotation() && (rotation == 90 || rotation == 270)) { std::swap(adapted_width, adapted_height); std::swap(rotated_width, rotated_height); } rtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer = pre_scale_pool_.CreateBuffer(rotated_width, rotated_height); const uint8_t* y_plane = static_cast<const uint8_t*>(video_frame); const uint8_t* uv_plane = y_plane + width * height; // Can only crop at even pixels. crop_x &= ~1; crop_y &= ~1; int uv_width = (width + 1) / 2; libyuv::NV12ToI420Rotate( y_plane + width * crop_y + crop_x, width, uv_plane + uv_width * crop_y + crop_x, width, buffer->MutableData(webrtc::kYPlane), buffer->stride(webrtc::kYPlane), // Swap U and V, since we have NV21, not NV12. buffer->MutableData(webrtc::kVPlane), buffer->stride(webrtc::kVPlane), buffer->MutableData(webrtc::kUPlane), buffer->stride(webrtc::kUPlane), crop_width, crop_height, static_cast<libyuv::RotationMode>( capturer_->apply_rotation() ? rotation : 0)); if (adapted_width != rotated_width || adapted_height != rotated_height) { rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled = post_scale_pool_.CreateBuffer(adapted_width, adapted_height); // TODO(nisse): This should be done by some Scale method in // I420Buffer, but we can't do that right now, since // I420BufferPool uses a wrapper object. if (libyuv::I420Scale(buffer->DataY(), buffer->StrideY(), buffer->DataU(), buffer->StrideU(), buffer->DataV(), buffer->StrideV(), rotated_width, rotated_height, scaled->MutableDataY(), scaled->StrideY(), scaled->MutableDataU(), scaled->StrideU(), scaled->MutableDataV(), scaled->StrideV(), adapted_width, adapted_height, libyuv::kFilterBox) < 0) { LOG(LS_WARNING) << "I420Scale failed"; return; } buffer = scaled; } // TODO(nisse): Use microsecond time instead. capturer_->OnFrame(cricket::WebRtcVideoFrame( buffer, timestamp_ns, capturer_->apply_rotation() ? webrtc::kVideoRotation_0 : static_cast<webrtc::VideoRotation>(rotation)), width, height); } void AndroidVideoCapturerJni::OnTextureFrame(int width, int height, int rotation, int64_t timestamp_ns, const NativeHandleImpl& handle) { RTC_DCHECK(rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270); rtc::CritScope cs(&capturer_lock_); int adapted_width; int adapted_height; int crop_width; int crop_height; int crop_x; int crop_y; if (!capturer_->AdaptFrame(width, height, timestamp_ns, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) { surface_texture_helper_->ReturnTextureFrame(); return; } Matrix matrix = handle.sampling_matrix; matrix.Crop(crop_width / static_cast<float>(width), crop_height / static_cast<float>(height), crop_x / static_cast<float>(width), crop_y / static_cast<float>(height)); if (capturer_->apply_rotation()) { if (rotation == webrtc::kVideoRotation_90 || rotation == webrtc::kVideoRotation_270) { std::swap(adapted_width, adapted_height); } matrix.Rotate(static_cast<webrtc::VideoRotation>(rotation)); } // TODO(nisse): Use microsecond time instead. capturer_->OnFrame( cricket::WebRtcVideoFrame( surface_texture_helper_->CreateTextureFrame( adapted_width, adapted_height, NativeHandleImpl(handle.oes_texture_id, matrix)), timestamp_ns, capturer_->apply_rotation() ? webrtc::kVideoRotation_0 : static_cast<webrtc::VideoRotation>(rotation)), width, height); } void AndroidVideoCapturerJni::OnOutputFormatRequest(int width, int height, int fps) { AsyncCapturerInvoke("OnOutputFormatRequest", &webrtc::AndroidVideoCapturer::OnOutputFormatRequest, width, height, fps); } JNIEnv* AndroidVideoCapturerJni::jni() { return AttachCurrentThreadIfNeeded(); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnByteBufferFrameCaptured) (JNIEnv* jni, jclass, jlong j_capturer, jbyteArray j_frame, jint length, jint width, jint height, jint rotation, jlong timestamp) { jboolean is_copy = true; jbyte* bytes = jni->GetByteArrayElements(j_frame, &is_copy); reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer) ->OnMemoryBufferFrame(bytes, length, width, height, rotation, timestamp); jni->ReleaseByteArrayElements(j_frame, bytes, JNI_ABORT); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnTextureFrameCaptured) (JNIEnv* jni, jclass, jlong j_capturer, jint j_width, jint j_height, jint j_oes_texture_id, jfloatArray j_transform_matrix, jint j_rotation, jlong j_timestamp) { reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer) ->OnTextureFrame(j_width, j_height, j_rotation, j_timestamp, NativeHandleImpl(jni, j_oes_texture_id, j_transform_matrix)); } JOW(void, VideoCapturer_00024NativeObserver_nativeCapturerStarted) (JNIEnv* jni, jclass, jlong j_capturer, jboolean j_success) { LOG(LS_INFO) << "NativeObserver_nativeCapturerStarted"; reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer)->OnCapturerStarted( j_success); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnOutputFormatRequest) (JNIEnv* jni, jclass, jlong j_capturer, jint j_width, jint j_height, jint j_fps) { LOG(LS_INFO) << "NativeObserver_nativeOnOutputFormatRequest"; reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer)->OnOutputFormatRequest( j_width, j_height, j_fps); } } // namespace webrtc_jni
/* * Copyright 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/api/java/jni/androidvideocapturer_jni.h" #include "webrtc/api/java/jni/classreferenceholder.h" #include "webrtc/api/java/jni/native_handle_impl.h" #include "webrtc/api/java/jni/surfacetexturehelper_jni.h" #include "third_party/libyuv/include/libyuv/convert.h" #include "third_party/libyuv/include/libyuv/scale.h" #include "webrtc/base/bind.h" namespace webrtc_jni { jobject AndroidVideoCapturerJni::application_context_ = nullptr; // static int AndroidVideoCapturerJni::SetAndroidObjects(JNIEnv* jni, jobject appliction_context) { if (application_context_) { jni->DeleteGlobalRef(application_context_); } application_context_ = NewGlobalRef(jni, appliction_context); return 0; } AndroidVideoCapturerJni::AndroidVideoCapturerJni(JNIEnv* jni, jobject j_video_capturer, jobject j_egl_context) : j_video_capturer_(jni, j_video_capturer), j_video_capturer_class_(jni, FindClass(jni, "org/webrtc/VideoCapturer")), j_observer_class_( jni, FindClass(jni, "org/webrtc/VideoCapturer$NativeObserver")), surface_texture_helper_(SurfaceTextureHelper::create( jni, "Camera SurfaceTextureHelper", j_egl_context)), capturer_(nullptr) { LOG(LS_INFO) << "AndroidVideoCapturerJni ctor"; thread_checker_.DetachFromThread(); } AndroidVideoCapturerJni::~AndroidVideoCapturerJni() { LOG(LS_INFO) << "AndroidVideoCapturerJni dtor"; jni()->CallVoidMethod( *j_video_capturer_, GetMethodID(jni(), *j_video_capturer_class_, "dispose", "()V")); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.dispose()"; } void AndroidVideoCapturerJni::Start(int width, int height, int framerate, webrtc::AndroidVideoCapturer* capturer) { LOG(LS_INFO) << "AndroidVideoCapturerJni start"; RTC_DCHECK(thread_checker_.CalledOnValidThread()); { rtc::CritScope cs(&capturer_lock_); RTC_CHECK(capturer_ == nullptr); RTC_CHECK(invoker_.get() == nullptr); capturer_ = capturer; invoker_.reset(new rtc::GuardedAsyncInvoker()); } jobject j_frame_observer = jni()->NewObject(*j_observer_class_, GetMethodID(jni(), *j_observer_class_, "<init>", "(J)V"), jlongFromPointer(this)); CHECK_EXCEPTION(jni()) << "error during NewObject"; jmethodID m = GetMethodID( jni(), *j_video_capturer_class_, "startCapture", "(IIILorg/webrtc/SurfaceTextureHelper;Landroid/content/Context;" "Lorg/webrtc/VideoCapturer$CapturerObserver;)V"); jni()->CallVoidMethod( *j_video_capturer_, m, width, height, framerate, surface_texture_helper_ ? surface_texture_helper_->GetJavaSurfaceTextureHelper() : nullptr, application_context_, j_frame_observer); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.startCapture"; } void AndroidVideoCapturerJni::Stop() { LOG(LS_INFO) << "AndroidVideoCapturerJni stop"; RTC_DCHECK(thread_checker_.CalledOnValidThread()); { // TODO(nisse): Consider moving this block until *after* the call to // stopCapturer. stopCapturer should ensure that we get no // more frames, and then we shouldn't need the if (!capturer_) // checks in OnMemoryBufferFrame and OnTextureFrame. rtc::CritScope cs(&capturer_lock_); // Destroying |invoker_| will cancel all pending calls to |capturer_|. invoker_ = nullptr; capturer_ = nullptr; } jmethodID m = GetMethodID(jni(), *j_video_capturer_class_, "stopCapture", "()V"); jni()->CallVoidMethod(*j_video_capturer_, m); CHECK_EXCEPTION(jni()) << "error during VideoCapturer.stopCapture"; LOG(LS_INFO) << "AndroidVideoCapturerJni stop done"; } template <typename... Args> void AndroidVideoCapturerJni::AsyncCapturerInvoke( const char* method_name, void (webrtc::AndroidVideoCapturer::*method)(Args...), typename Identity<Args>::type... args) { rtc::CritScope cs(&capturer_lock_); if (!invoker_) { LOG(LS_WARNING) << method_name << "() called for closed capturer."; return; } invoker_->AsyncInvoke<void>(rtc::Bind(method, capturer_, args...)); } std::vector<cricket::VideoFormat> AndroidVideoCapturerJni::GetSupportedFormats() { JNIEnv* jni = AttachCurrentThreadIfNeeded(); jobject j_list_of_formats = jni->CallObjectMethod( *j_video_capturer_, GetMethodID(jni, *j_video_capturer_class_, "getSupportedFormats", "()Ljava/util/List;")); CHECK_EXCEPTION(jni) << "error during getSupportedFormats"; // Extract Java List<CaptureFormat> to std::vector<cricket::VideoFormat>. jclass j_list_class = jni->FindClass("java/util/List"); jclass j_format_class = jni->FindClass("org/webrtc/CameraEnumerationAndroid$CaptureFormat"); jclass j_framerate_class = jni->FindClass( "org/webrtc/CameraEnumerationAndroid$CaptureFormat$FramerateRange"); const int size = jni->CallIntMethod( j_list_of_formats, GetMethodID(jni, j_list_class, "size", "()I")); jmethodID j_get = GetMethodID(jni, j_list_class, "get", "(I)Ljava/lang/Object;"); jfieldID j_framerate_field = GetFieldID( jni, j_format_class, "framerate", "Lorg/webrtc/CameraEnumerationAndroid$CaptureFormat$FramerateRange;"); jfieldID j_width_field = GetFieldID(jni, j_format_class, "width", "I"); jfieldID j_height_field = GetFieldID(jni, j_format_class, "height", "I"); jfieldID j_max_framerate_field = GetFieldID(jni, j_framerate_class, "max", "I"); std::vector<cricket::VideoFormat> formats; formats.reserve(size); for (int i = 0; i < size; ++i) { jobject j_format = jni->CallObjectMethod(j_list_of_formats, j_get, i); jobject j_framerate = GetObjectField(jni, j_format, j_framerate_field); const int frame_interval = cricket::VideoFormat::FpsToInterval( (GetIntField(jni, j_framerate, j_max_framerate_field) + 999) / 1000); formats.emplace_back(GetIntField(jni, j_format, j_width_field), GetIntField(jni, j_format, j_height_field), frame_interval, cricket::FOURCC_NV21); } CHECK_EXCEPTION(jni) << "error while extracting formats"; return formats; } void AndroidVideoCapturerJni::OnCapturerStarted(bool success) { LOG(LS_INFO) << "AndroidVideoCapturerJni capture started: " << success; AsyncCapturerInvoke("OnCapturerStarted", &webrtc::AndroidVideoCapturer::OnCapturerStarted, success); } void AndroidVideoCapturerJni::OnMemoryBufferFrame(void* video_frame, int length, int width, int height, int rotation, int64_t timestamp_ns) { RTC_DCHECK(rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270); rtc::CritScope cs(&capturer_lock_); if (!capturer_) { LOG(LS_WARNING) << "OnMemoryBufferFrame() called for closed capturer."; return; } int adapted_width; int adapted_height; int crop_width; int crop_height; int crop_x; int crop_y; if (!capturer_->AdaptFrame(width, height, timestamp_ns, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) { return; } int rotated_width = crop_width; int rotated_height = crop_height; if (capturer_->apply_rotation() && (rotation == 90 || rotation == 270)) { std::swap(adapted_width, adapted_height); std::swap(rotated_width, rotated_height); } rtc::scoped_refptr<webrtc::VideoFrameBuffer> buffer = pre_scale_pool_.CreateBuffer(rotated_width, rotated_height); const uint8_t* y_plane = static_cast<const uint8_t*>(video_frame); const uint8_t* uv_plane = y_plane + width * height; // Can only crop at even pixels. crop_x &= ~1; crop_y &= ~1; int uv_width = (width + 1) / 2; libyuv::NV12ToI420Rotate( y_plane + width * crop_y + crop_x, width, uv_plane + uv_width * crop_y + crop_x, width, buffer->MutableData(webrtc::kYPlane), buffer->stride(webrtc::kYPlane), // Swap U and V, since we have NV21, not NV12. buffer->MutableData(webrtc::kVPlane), buffer->stride(webrtc::kVPlane), buffer->MutableData(webrtc::kUPlane), buffer->stride(webrtc::kUPlane), crop_width, crop_height, static_cast<libyuv::RotationMode>( capturer_->apply_rotation() ? rotation : 0)); if (adapted_width != rotated_width || adapted_height != rotated_height) { rtc::scoped_refptr<webrtc::VideoFrameBuffer> scaled = post_scale_pool_.CreateBuffer(adapted_width, adapted_height); // TODO(nisse): This should be done by some Scale method in // I420Buffer, but we can't do that right now, since // I420BufferPool uses a wrapper object. if (libyuv::I420Scale(buffer->DataY(), buffer->StrideY(), buffer->DataU(), buffer->StrideU(), buffer->DataV(), buffer->StrideV(), rotated_width, rotated_height, scaled->MutableDataY(), scaled->StrideY(), scaled->MutableDataU(), scaled->StrideU(), scaled->MutableDataV(), scaled->StrideV(), adapted_width, adapted_height, libyuv::kFilterBox) < 0) { LOG(LS_WARNING) << "I420Scale failed"; return; } buffer = scaled; } // TODO(nisse): Use microsecond time instead. capturer_->OnFrame(cricket::WebRtcVideoFrame( buffer, timestamp_ns, capturer_->apply_rotation() ? webrtc::kVideoRotation_0 : static_cast<webrtc::VideoRotation>(rotation)), width, height); } void AndroidVideoCapturerJni::OnTextureFrame(int width, int height, int rotation, int64_t timestamp_ns, const NativeHandleImpl& handle) { RTC_DCHECK(rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270); rtc::CritScope cs(&capturer_lock_); if (!capturer_) { LOG(LS_WARNING) << "OnTextureFrame() called for closed capturer."; return; } int adapted_width; int adapted_height; int crop_width; int crop_height; int crop_x; int crop_y; if (!capturer_->AdaptFrame(width, height, timestamp_ns, &adapted_width, &adapted_height, &crop_width, &crop_height, &crop_x, &crop_y)) { surface_texture_helper_->ReturnTextureFrame(); return; } Matrix matrix = handle.sampling_matrix; matrix.Crop(crop_width / static_cast<float>(width), crop_height / static_cast<float>(height), crop_x / static_cast<float>(width), crop_y / static_cast<float>(height)); if (capturer_->apply_rotation()) { if (rotation == webrtc::kVideoRotation_90 || rotation == webrtc::kVideoRotation_270) { std::swap(adapted_width, adapted_height); } matrix.Rotate(static_cast<webrtc::VideoRotation>(rotation)); } // TODO(nisse): Use microsecond time instead. capturer_->OnFrame( cricket::WebRtcVideoFrame( surface_texture_helper_->CreateTextureFrame( adapted_width, adapted_height, NativeHandleImpl(handle.oes_texture_id, matrix)), timestamp_ns, capturer_->apply_rotation() ? webrtc::kVideoRotation_0 : static_cast<webrtc::VideoRotation>(rotation)), width, height); } void AndroidVideoCapturerJni::OnOutputFormatRequest(int width, int height, int fps) { AsyncCapturerInvoke("OnOutputFormatRequest", &webrtc::AndroidVideoCapturer::OnOutputFormatRequest, width, height, fps); } JNIEnv* AndroidVideoCapturerJni::jni() { return AttachCurrentThreadIfNeeded(); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnByteBufferFrameCaptured) (JNIEnv* jni, jclass, jlong j_capturer, jbyteArray j_frame, jint length, jint width, jint height, jint rotation, jlong timestamp) { jboolean is_copy = true; jbyte* bytes = jni->GetByteArrayElements(j_frame, &is_copy); reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer) ->OnMemoryBufferFrame(bytes, length, width, height, rotation, timestamp); jni->ReleaseByteArrayElements(j_frame, bytes, JNI_ABORT); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnTextureFrameCaptured) (JNIEnv* jni, jclass, jlong j_capturer, jint j_width, jint j_height, jint j_oes_texture_id, jfloatArray j_transform_matrix, jint j_rotation, jlong j_timestamp) { reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer) ->OnTextureFrame(j_width, j_height, j_rotation, j_timestamp, NativeHandleImpl(jni, j_oes_texture_id, j_transform_matrix)); } JOW(void, VideoCapturer_00024NativeObserver_nativeCapturerStarted) (JNIEnv* jni, jclass, jlong j_capturer, jboolean j_success) { LOG(LS_INFO) << "NativeObserver_nativeCapturerStarted"; reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer)->OnCapturerStarted( j_success); } JOW(void, VideoCapturer_00024NativeObserver_nativeOnOutputFormatRequest) (JNIEnv* jni, jclass, jlong j_capturer, jint j_width, jint j_height, jint j_fps) { LOG(LS_INFO) << "NativeObserver_nativeOnOutputFormatRequest"; reinterpret_cast<AndroidVideoCapturerJni*>(j_capturer)->OnOutputFormatRequest( j_width, j_height, j_fps); } } // namespace webrtc_jni
Handle Android stop capturer race.
Handle Android stop capturer race. With the current order of stop capture processing on Android, OnMemoryBufferFrame and OnTextureFrame may be called halfway through Stop(). They must therefore check for the case of a null capturer_. There used to be such checks, but they were accidantally removed in commit #12895, cl https://codereview.webrtc.org/1973873003. BUG=webrtc:5966 [email protected], [email protected] Review URL: https://codereview.webrtc.org/2033943004 . Cr-Original-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#13031} Cr-Mirrored-From: https://chromium.googlesource.com/external/webrtc Cr-Mirrored-Commit: 47183ba60bddfcdd1494d88f3c1fefc62eb9445b
C++
bsd-3-clause
jchavanton/webrtc,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,jchavanton/webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,jchavanton/webrtc,jchavanton/webrtc,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk,Alkalyne/webrtctrunk
639916df705fe1cd818fbf7b44826c247510d86a
rcl/test/rcl/test_publisher.cpp
rcl/test/rcl/test_publisher.cpp
// Copyright 2015 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include "rcl/publisher.h" #include "rcl/rcl.h" #include "std_msgs/msg/int64.h" #include "std_msgs/msg/string.h" #include "rosidl_generator_c/string_functions.h" #include "./failing_allocator_functions.hpp" #include "osrf_testing_tools_cpp/scope_exit.hpp" #include "rcl/error_handling.h" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif class CLASSNAME (TestPublisherFixture, RMW_IMPLEMENTATION) : public ::testing::Test { public: rcl_node_t * node_ptr; void SetUp() { rcl_ret_t ret; ret = rcl_init(0, nullptr, rcl_get_default_allocator()); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); this->node_ptr = new rcl_node_t; *this->node_ptr = rcl_get_zero_initialized_node(); const char * name = "test_publisher_node"; rcl_node_options_t node_options = rcl_node_get_default_options(); ret = rcl_node_init(this->node_ptr, name, "", &node_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } void TearDown() { rcl_ret_t ret = rcl_node_fini(this->node_ptr); delete this->node_ptr; EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); ret = rcl_shutdown(); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } }; /* Basic nominal test of a publisher. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_nominal) { rcl_ret_t ret; rcl_publisher_t publisher = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int64); // TODO(wjwwood): Change this back to just chatter when this OpenSplice problem is resolved: // ======================================================================================== // Report : WARNING // Date : Wed Feb 10 18:17:03 PST 2016 // Description : Create Topic "chatter" failed: typename <std_msgs::msg::dds_::Int64_> // differs exiting definition <std_msgs::msg::dds_::String_>. // Node : farl // Process : test_subscription__rmw_opensplice_cpp <23524> // Thread : main thread 7fff7342d000 // Internals : V6.4.140407OSS///v_topicNew/v_topic.c/448/21/1455157023.781423000 const char * topic_name = "chatter_int64"; const char * expected_topic_name = "/chatter_int64"; rcl_publisher_options_t publisher_options = rcl_publisher_get_default_options(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); EXPECT_EQ(strcmp(rcl_publisher_get_topic_name(&publisher), expected_topic_name), 0); std_msgs__msg__Int64 msg; std_msgs__msg__Int64__init(&msg); msg.data = 42; ret = rcl_publish(&publisher, &msg); std_msgs__msg__Int64__fini(&msg); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } /* Basic nominal test of a publisher with a string. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_nominal_string) { rcl_ret_t ret; rcl_publisher_t publisher = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, String); const char * topic_name = "chatter"; rcl_publisher_options_t publisher_options = rcl_publisher_get_default_options(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); std_msgs__msg__String msg; std_msgs__msg__String__init(&msg); ASSERT_TRUE(rosidl_generator_c__String__assign(&msg.data, "testing")); ret = rcl_publish(&publisher, &msg); std_msgs__msg__String__fini(&msg); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } /* Testing the publisher init and fini functions. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_init_fini) { rcl_ret_t ret; // Setup valid inputs. rcl_publisher_t publisher; const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int64); const char * topic_name = "chatter"; rcl_publisher_options_t default_publisher_options = rcl_publisher_get_default_options(); // Check if null publisher is valid EXPECT_FALSE(rcl_publisher_is_valid(nullptr, nullptr)); rcl_reset_error(); // Check if zero initialized node is valid publisher = rcl_get_zero_initialized_publisher(); EXPECT_FALSE(rcl_publisher_is_valid(&publisher, nullptr)); rcl_reset_error(); // Check that valid publisher is valid publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_TRUE(rcl_publisher_is_valid(&publisher, nullptr)); rcl_reset_error(); // Try passing null for publisher in init. ret = rcl_publisher_init(nullptr, this->node_ptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for a node pointer in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, nullptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing an invalid (uninitialized) node in init. publisher = rcl_get_zero_initialized_publisher(); rcl_node_t invalid_node = rcl_get_zero_initialized_node(); ret = rcl_publisher_init(&publisher, &invalid_node, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_NODE_INVALID, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the type support in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init( &publisher, this->node_ptr, nullptr, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the topic name in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, nullptr, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the options in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, nullptr); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing options with an invalid allocate in allocator with init. publisher = rcl_get_zero_initialized_publisher(); rcl_publisher_options_t publisher_options_with_invalid_allocator; publisher_options_with_invalid_allocator = rcl_publisher_get_default_options(); publisher_options_with_invalid_allocator.allocator.allocate = nullptr; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_invalid_allocator); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing options with an invalid deallocate in allocator with init. publisher = rcl_get_zero_initialized_publisher(); publisher_options_with_invalid_allocator = rcl_publisher_get_default_options(); publisher_options_with_invalid_allocator.allocator.deallocate = nullptr; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_invalid_allocator); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // An allocator with an invalid realloc will probably work (so we will not test it). // Try passing options with a failing allocator with init. publisher = rcl_get_zero_initialized_publisher(); rcl_publisher_options_t publisher_options_with_failing_allocator; publisher_options_with_failing_allocator = rcl_publisher_get_default_options(); publisher_options_with_failing_allocator.allocator.allocate = failing_malloc; publisher_options_with_failing_allocator.allocator.reallocate = failing_realloc; publisher_options_with_failing_allocator.allocator.zero_allocate = failing_calloc; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_failing_allocator); EXPECT_EQ(RCL_RET_BAD_ALLOC, ret) << rcl_get_error_string_safe(); rcl_reset_error(); }
// Copyright 2015 Open Source Robotics Foundation, 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 <gtest/gtest.h> #include "rcl/publisher.h" #include "rcl/rcl.h" #include "std_msgs/msg/int64.h" #include "std_msgs/msg/string.h" #include "rosidl_generator_c/string_functions.h" #include "./failing_allocator_functions.hpp" #include "osrf_testing_tools_cpp/scope_exit.hpp" #include "rcl/error_handling.h" #ifdef RMW_IMPLEMENTATION # define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX # define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX) #else # define CLASSNAME(NAME, SUFFIX) NAME #endif class CLASSNAME (TestPublisherFixture, RMW_IMPLEMENTATION) : public ::testing::Test { public: rcl_node_t * node_ptr; void SetUp() { rcl_ret_t ret; ret = rcl_init(0, nullptr, rcl_get_default_allocator()); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); this->node_ptr = new rcl_node_t; *this->node_ptr = rcl_get_zero_initialized_node(); const char * name = "test_publisher_node"; rcl_node_options_t node_options = rcl_node_get_default_options(); ret = rcl_node_init(this->node_ptr, name, "", &node_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } void TearDown() { rcl_ret_t ret = rcl_node_fini(this->node_ptr); delete this->node_ptr; EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); ret = rcl_shutdown(); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } }; /* Basic nominal test of a publisher. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_nominal) { rcl_ret_t ret; rcl_publisher_t publisher = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int64); // TODO(wjwwood): Change this back to just chatter when this OpenSplice problem is resolved: // ======================================================================================== // Report : WARNING // Date : Wed Feb 10 18:17:03 PST 2016 // Description : Create Topic "chatter" failed: typename <std_msgs::msg::dds_::Int64_> // differs exiting definition <std_msgs::msg::dds_::String_>. // Node : farl // Process : test_subscription__rmw_opensplice_cpp <23524> // Thread : main thread 7fff7342d000 // Internals : V6.4.140407OSS///v_topicNew/v_topic.c/448/21/1455157023.781423000 const char * topic_name = "chatter_int64"; const char * expected_topic_name = "/chatter_int64"; rcl_publisher_options_t publisher_options = rcl_publisher_get_default_options(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); EXPECT_EQ(strcmp(rcl_publisher_get_topic_name(&publisher), expected_topic_name), 0); std_msgs__msg__Int64 msg; std_msgs__msg__Int64__init(&msg); msg.data = 42; ret = rcl_publish(&publisher, &msg); std_msgs__msg__Int64__fini(&msg); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } /* Basic nominal test of a publisher with a string. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_nominal_string) { rcl_ret_t ret; rcl_publisher_t publisher = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, String); const char * topic_name = "chatter"; rcl_publisher_options_t publisher_options = rcl_publisher_get_default_options(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); std_msgs__msg__String msg; std_msgs__msg__String__init(&msg); ASSERT_TRUE(rosidl_generator_c__String__assign(&msg.data, "testing")); ret = rcl_publish(&publisher, &msg); std_msgs__msg__String__fini(&msg); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } /* Test two publishers using different message types with the same basename. * * Regression test for https://github.com/ros2/rmw_connext/issues/234, where rmw_connext_cpp could * not support publishers on topics with the same basename (but different namespaces) using * different message types, because at the time partitions were used for implementing namespaces. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publishers_different_types) { rcl_ret_t ret; rcl_publisher_t publisher = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts_int = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int64); const char * topic_name = "basename"; const char * expected_topic_name = "/basename"; rcl_publisher_options_t publisher_options = rcl_publisher_get_default_options(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts_int, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); EXPECT_EQ(strcmp(rcl_publisher_get_topic_name(&publisher), expected_topic_name), 0); rcl_publisher_t publisher_in_namespace = rcl_get_zero_initialized_publisher(); const rosidl_message_type_support_t * ts_string = ROSIDL_GET_MSG_TYPE_SUPPORT( std_msgs, msg, String); topic_name = "namespace/basename"; expected_topic_name = "/namespace/basename"; ret = rcl_publisher_init( &publisher_in_namespace, this->node_ptr, ts_string, topic_name, &publisher_options); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); OSRF_TESTING_TOOLS_CPP_SCOPE_EXIT({ rcl_ret_t ret = rcl_publisher_fini(&publisher_in_namespace, this->node_ptr); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); }); EXPECT_EQ(strcmp(rcl_publisher_get_topic_name(&publisher_in_namespace), expected_topic_name), 0); std_msgs__msg__Int64 msg_int; std_msgs__msg__Int64__init(&msg_int); msg_int.data = 42; ret = rcl_publish(&publisher, &msg_int); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); std_msgs__msg__Int64__fini(&msg_int); std_msgs__msg__String msg_string; std_msgs__msg__String__init(&msg_string); ASSERT_TRUE(rosidl_generator_c__String__assign(&msg_string.data, "testing")); ret = rcl_publish(&publisher_in_namespace, &msg_string); ASSERT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); } /* Testing the publisher init and fini functions. */ TEST_F(CLASSNAME(TestPublisherFixture, RMW_IMPLEMENTATION), test_publisher_init_fini) { rcl_ret_t ret; // Setup valid inputs. rcl_publisher_t publisher; const rosidl_message_type_support_t * ts = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int64); const char * topic_name = "chatter"; rcl_publisher_options_t default_publisher_options = rcl_publisher_get_default_options(); // Check if null publisher is valid EXPECT_FALSE(rcl_publisher_is_valid(nullptr, nullptr)); rcl_reset_error(); // Check if zero initialized node is valid publisher = rcl_get_zero_initialized_publisher(); EXPECT_FALSE(rcl_publisher_is_valid(&publisher, nullptr)); rcl_reset_error(); // Check that valid publisher is valid publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_OK, ret) << rcl_get_error_string_safe(); EXPECT_TRUE(rcl_publisher_is_valid(&publisher, nullptr)); rcl_reset_error(); // Try passing null for publisher in init. ret = rcl_publisher_init(nullptr, this->node_ptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for a node pointer in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, nullptr, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing an invalid (uninitialized) node in init. publisher = rcl_get_zero_initialized_publisher(); rcl_node_t invalid_node = rcl_get_zero_initialized_node(); ret = rcl_publisher_init(&publisher, &invalid_node, ts, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_NODE_INVALID, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the type support in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init( &publisher, this->node_ptr, nullptr, topic_name, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the topic name in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, nullptr, &default_publisher_options); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing null for the options in init. publisher = rcl_get_zero_initialized_publisher(); ret = rcl_publisher_init(&publisher, this->node_ptr, ts, topic_name, nullptr); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing options with an invalid allocate in allocator with init. publisher = rcl_get_zero_initialized_publisher(); rcl_publisher_options_t publisher_options_with_invalid_allocator; publisher_options_with_invalid_allocator = rcl_publisher_get_default_options(); publisher_options_with_invalid_allocator.allocator.allocate = nullptr; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_invalid_allocator); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // Try passing options with an invalid deallocate in allocator with init. publisher = rcl_get_zero_initialized_publisher(); publisher_options_with_invalid_allocator = rcl_publisher_get_default_options(); publisher_options_with_invalid_allocator.allocator.deallocate = nullptr; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_invalid_allocator); EXPECT_EQ(RCL_RET_INVALID_ARGUMENT, ret) << rcl_get_error_string_safe(); rcl_reset_error(); // An allocator with an invalid realloc will probably work (so we will not test it). // Try passing options with a failing allocator with init. publisher = rcl_get_zero_initialized_publisher(); rcl_publisher_options_t publisher_options_with_failing_allocator; publisher_options_with_failing_allocator = rcl_publisher_get_default_options(); publisher_options_with_failing_allocator.allocator.allocate = failing_malloc; publisher_options_with_failing_allocator.allocator.reallocate = failing_realloc; publisher_options_with_failing_allocator.allocator.zero_allocate = failing_calloc; ret = rcl_publisher_init( &publisher, this->node_ptr, ts, topic_name, &publisher_options_with_failing_allocator); EXPECT_EQ(RCL_RET_BAD_ALLOC, ret) << rcl_get_error_string_safe(); rcl_reset_error(); }
Add regression test for connext 'wrong type writer' error (#257)
Add regression test for connext 'wrong type writer' error (#257) * Add regression test for connext 'wrong type writer' error * Use osrf_testing_tools_cpp
C++
apache-2.0
ros2/rcl,ros2/rcl
41b585ca0e706a6d43ca185e88a609178e8629e7
lib/Target/Sparc/SparcISelDAGToDAG.cpp
lib/Target/Sparc/SparcISelDAGToDAG.cpp
//===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the SPARC target. // //===----------------------------------------------------------------------===// #include "SparcTargetMachine.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===--------------------------------------------------------------------===// /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine /// instructions for SelectionDAG operations. /// namespace { class SparcDAGToDAGISel : public SelectionDAGISel { /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can /// make the right decision when generating code for different targets. const SparcSubtarget &Subtarget; SparcTargetMachine& TM; public: explicit SparcDAGToDAGISel(SparcTargetMachine &tm) : SelectionDAGISel(tm), Subtarget(tm.getSubtarget<SparcSubtarget>()), TM(tm) { } SDNode *Select(SDNode *N); // Complex Pattern Selectors. bool SelectADDRrr(SDValue N, SDValue &R1, SDValue &R2); bool SelectADDRri(SDValue N, SDValue &Base, SDValue &Offset); /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for /// inline asm expressions. virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps); virtual const char *getPassName() const { return "SPARC DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "SparcGenDAGISel.inc" private: SDNode* getGlobalBaseReg(); }; } // end anonymous namespace SDNode* SparcDAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF); return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode(); } bool SparcDAGToDAGISel::SelectADDRri(SDValue Addr, SDValue &Base, SDValue &Offset) { if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } if (Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress) return false; // direct calls. if (Addr.getOpcode() == ISD::ADD) { if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) { if (isInt<13>(CN->getSExtValue())) { if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) { // Constant offset from frame ref. Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32); } else { Base = Addr.getOperand(0); } Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32); return true; } } if (Addr.getOperand(0).getOpcode() == SPISD::Lo) { Base = Addr.getOperand(1); Offset = Addr.getOperand(0).getOperand(0); return true; } if (Addr.getOperand(1).getOpcode() == SPISD::Lo) { Base = Addr.getOperand(0); Offset = Addr.getOperand(1).getOperand(0); return true; } } Base = Addr; Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } bool SparcDAGToDAGISel::SelectADDRrr(SDValue Addr, SDValue &R1, SDValue &R2) { if (Addr.getOpcode() == ISD::FrameIndex) return false; if (Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress) return false; // direct calls. if (Addr.getOpcode() == ISD::ADD) { if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) if (isInt<13>(CN->getSExtValue())) return false; // Let the reg+imm pattern catch this! if (Addr.getOperand(0).getOpcode() == SPISD::Lo || Addr.getOperand(1).getOpcode() == SPISD::Lo) return false; // Let the reg+imm pattern catch this! R1 = Addr.getOperand(0); R2 = Addr.getOperand(1); return true; } R1 = Addr; R2 = CurDAG->getRegister(SP::G0, MVT::i32); return true; } SDNode *SparcDAGToDAGISel::Select(SDNode *N) { DebugLoc dl = N->getDebugLoc(); if (N->isMachineOpcode()) return NULL; // Already selected. switch (N->getOpcode()) { default: break; case SPISD::GLOBAL_BASE_REG: return getGlobalBaseReg(); case ISD::SDIV: case ISD::UDIV: { // FIXME: should use a custom expander to expose the SRA to the dag. SDValue DivLHS = N->getOperand(0); SDValue DivRHS = N->getOperand(1); // Set the Y register to the high-part. SDValue TopPart; if (N->getOpcode() == ISD::SDIV) { TopPart = SDValue(CurDAG->getMachineNode(SP::SRAri, dl, MVT::i32, DivLHS, CurDAG->getTargetConstant(31, MVT::i32)), 0); } else { TopPart = CurDAG->getRegister(SP::G0, MVT::i32); } TopPart = SDValue(CurDAG->getMachineNode(SP::WRYrr, dl, MVT::Glue, TopPart, CurDAG->getRegister(SP::G0, MVT::i32)), 0); // FIXME: Handle div by immediate. unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr; return CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart); } case ISD::MULHU: case ISD::MULHS: { // FIXME: Handle mul by immediate. SDValue MulLHS = N->getOperand(0); SDValue MulRHS = N->getOperand(1); unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr; SDNode *Mul = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Glue, MulLHS, MulRHS); // The high part is in the Y register. return CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDValue(Mul, 1)); } } return SelectCode(N); } /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for /// inline asm expressions. bool SparcDAGToDAGISel::SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) { SDValue Op0, Op1; switch (ConstraintCode) { default: return true; case 'm': // memory if (!SelectADDRrr(Op, Op0, Op1)) SelectADDRri(Op, Op0, Op1); break; } OutOps.push_back(Op0); OutOps.push_back(Op1); return false; } /// createSparcISelDag - This pass converts a legalized DAG into a /// SPARC-specific DAG, ready for instruction scheduling. /// FunctionPass *llvm::createSparcISelDag(SparcTargetMachine &TM) { return new SparcDAGToDAGISel(TM); }
//===-- SparcISelDAGToDAG.cpp - A dag to dag inst selector for Sparc ------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the SPARC target. // //===----------------------------------------------------------------------===// #include "SparcTargetMachine.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/IR/Intrinsics.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" using namespace llvm; //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===--------------------------------------------------------------------===// /// SparcDAGToDAGISel - SPARC specific code to select SPARC machine /// instructions for SelectionDAG operations. /// namespace { class SparcDAGToDAGISel : public SelectionDAGISel { /// Subtarget - Keep a pointer to the Sparc Subtarget around so that we can /// make the right decision when generating code for different targets. const SparcSubtarget &Subtarget; SparcTargetMachine& TM; public: explicit SparcDAGToDAGISel(SparcTargetMachine &tm) : SelectionDAGISel(tm), Subtarget(tm.getSubtarget<SparcSubtarget>()), TM(tm) { } SDNode *Select(SDNode *N); // Complex Pattern Selectors. bool SelectADDRrr(SDValue N, SDValue &R1, SDValue &R2); bool SelectADDRri(SDValue N, SDValue &Base, SDValue &Offset); /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for /// inline asm expressions. virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps); virtual const char *getPassName() const { return "SPARC DAG->DAG Pattern Instruction Selection"; } // Include the pieces autogenerated from the target description. #include "SparcGenDAGISel.inc" private: SDNode* getGlobalBaseReg(); }; } // end anonymous namespace SDNode* SparcDAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = TM.getInstrInfo()->getGlobalBaseReg(MF); return CurDAG->getRegister(GlobalBaseReg, TLI.getPointerTy()).getNode(); } bool SparcDAGToDAGISel::SelectADDRri(SDValue Addr, SDValue &Base, SDValue &Offset) { if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), TLI.getPointerTy()); Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } if (Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress) return false; // direct calls. if (Addr.getOpcode() == ISD::ADD) { if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) { if (isInt<13>(CN->getSExtValue())) { if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) { // Constant offset from frame ref. Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), TLI.getPointerTy()); } else { Base = Addr.getOperand(0); } Offset = CurDAG->getTargetConstant(CN->getZExtValue(), MVT::i32); return true; } } if (Addr.getOperand(0).getOpcode() == SPISD::Lo) { Base = Addr.getOperand(1); Offset = Addr.getOperand(0).getOperand(0); return true; } if (Addr.getOperand(1).getOpcode() == SPISD::Lo) { Base = Addr.getOperand(0); Offset = Addr.getOperand(1).getOperand(0); return true; } } Base = Addr; Offset = CurDAG->getTargetConstant(0, MVT::i32); return true; } bool SparcDAGToDAGISel::SelectADDRrr(SDValue Addr, SDValue &R1, SDValue &R2) { if (Addr.getOpcode() == ISD::FrameIndex) return false; if (Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress) return false; // direct calls. if (Addr.getOpcode() == ISD::ADD) { if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1))) if (isInt<13>(CN->getSExtValue())) return false; // Let the reg+imm pattern catch this! if (Addr.getOperand(0).getOpcode() == SPISD::Lo || Addr.getOperand(1).getOpcode() == SPISD::Lo) return false; // Let the reg+imm pattern catch this! R1 = Addr.getOperand(0); R2 = Addr.getOperand(1); return true; } R1 = Addr; R2 = CurDAG->getRegister(SP::G0, TLI.getPointerTy()); return true; } SDNode *SparcDAGToDAGISel::Select(SDNode *N) { DebugLoc dl = N->getDebugLoc(); if (N->isMachineOpcode()) return NULL; // Already selected. switch (N->getOpcode()) { default: break; case SPISD::GLOBAL_BASE_REG: return getGlobalBaseReg(); case ISD::SDIV: case ISD::UDIV: { // FIXME: should use a custom expander to expose the SRA to the dag. SDValue DivLHS = N->getOperand(0); SDValue DivRHS = N->getOperand(1); // Set the Y register to the high-part. SDValue TopPart; if (N->getOpcode() == ISD::SDIV) { TopPart = SDValue(CurDAG->getMachineNode(SP::SRAri, dl, MVT::i32, DivLHS, CurDAG->getTargetConstant(31, MVT::i32)), 0); } else { TopPart = CurDAG->getRegister(SP::G0, MVT::i32); } TopPart = SDValue(CurDAG->getMachineNode(SP::WRYrr, dl, MVT::Glue, TopPart, CurDAG->getRegister(SP::G0, MVT::i32)), 0); // FIXME: Handle div by immediate. unsigned Opcode = N->getOpcode() == ISD::SDIV ? SP::SDIVrr : SP::UDIVrr; return CurDAG->SelectNodeTo(N, Opcode, MVT::i32, DivLHS, DivRHS, TopPart); } case ISD::MULHU: case ISD::MULHS: { // FIXME: Handle mul by immediate. SDValue MulLHS = N->getOperand(0); SDValue MulRHS = N->getOperand(1); unsigned Opcode = N->getOpcode() == ISD::MULHU ? SP::UMULrr : SP::SMULrr; SDNode *Mul = CurDAG->getMachineNode(Opcode, dl, MVT::i32, MVT::Glue, MulLHS, MulRHS); // The high part is in the Y register. return CurDAG->SelectNodeTo(N, SP::RDY, MVT::i32, SDValue(Mul, 1)); } } return SelectCode(N); } /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for /// inline asm expressions. bool SparcDAGToDAGISel::SelectInlineAsmMemoryOperand(const SDValue &Op, char ConstraintCode, std::vector<SDValue> &OutOps) { SDValue Op0, Op1; switch (ConstraintCode) { default: return true; case 'm': // memory if (!SelectADDRrr(Op, Op0, Op1)) SelectADDRri(Op, Op0, Op1); break; } OutOps.push_back(Op0); OutOps.push_back(Op1); return false; } /// createSparcISelDag - This pass converts a legalized DAG into a /// SPARC-specific DAG, ready for instruction scheduling. /// FunctionPass *llvm::createSparcISelDag(SparcTargetMachine &TM) { return new SparcDAGToDAGISel(TM); }
Use the correct types when matching ADDRri patterns from frame indexes.
Use the correct types when matching ADDRri patterns from frame indexes. It doesn't seem like anybody is checking types this late in isel, so no test case. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@179462 91177308-0d34-0410-b5e6-96231b3b80d8
C++
bsd-2-clause
chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap
f409f8134fa7222bc56f50a96cd541bb76ce75e9
dalvikvm/dalvikvm.cc
dalvikvm/dalvikvm.cc
/* * copyright (C) 2011 The Android Open Source Project * * 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 <signal.h> #include <cstdio> #include <cstring> #include <string> #include "jni.h" #include "JniInvocation.h" #include "ScopedLocalRef.h" #include "toStringArray.h" #include "UniquePtr.h" namespace art { // Determine whether or not the specified method is public. static bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) { ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE)); if (reflected.get() == NULL) { fprintf(stderr, "Failed to get reflected method\n"); return false; } // We now have a Method instance. We need to call its // getModifiers() method. jclass method_class = env->FindClass("java/lang/reflect/Method"); if (method_class == NULL) { fprintf(stderr, "Failed to find class java.lang.reflect.Method\n"); return false; } jmethodID mid = env->GetMethodID(method_class, "getModifiers", "()I"); if (mid == NULL) { fprintf(stderr, "Failed to find java.lang.reflect.Method.getModifiers\n"); return false; } int modifiers = env->CallIntMethod(reflected.get(), mid); static const int PUBLIC = 0x0001; // java.lang.reflect.Modifiers.PUBLIC if ((modifiers & PUBLIC) == 0) { return false; } return true; } static int InvokeMain(JNIEnv* env, char** argv) { // We want to call main() with a String array with our arguments in // it. Create an array and populate it. Note argv[0] is not // included. ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1)); if (args.get() == NULL) { env->ExceptionDescribe(); return EXIT_FAILURE; } // Find [class].main(String[]). // Convert "com.android.Blah" to "com/android/Blah". std::string class_name(argv[0]); std::replace(class_name.begin(), class_name.end(), '.', '/'); ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str())); if (klass.get() == NULL) { fprintf(stderr, "Unable to locate class '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } jmethodID method = env->GetStaticMethodID(klass.get(), "main", "([Ljava/lang/String;)V"); if (method == NULL) { fprintf(stderr, "Unable to find static main(String[]) in '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } // Make sure the method is public. JNI doesn't prevent us from // calling a private method, so we have to check it explicitly. if (!IsMethodPublic(env, klass.get(), method)) { fprintf(stderr, "Sorry, main() is not public in '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } // Invoke main(). env->CallStaticVoidMethod(klass.get(), method, args.get()); // Check whether there was an uncaught exception. We don't log any uncaught exception here; // detaching this thread will do that for us, but it will clear the exception (and invalidate // our JNIEnv), so we need to check here. return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS; } // Parse arguments. Most of it just gets passed through to the runtime. // The JNI spec defines a handful of standard arguments. static int dalvikvm(int argc, char** argv) { setvbuf(stdout, NULL, _IONBF, 0); // Skip over argv[0]. argv++; argc--; // If we're adding any additional stuff, e.g. function hook specifiers, // add them to the count here. // // We're over-allocating, because this includes the options to the runtime // plus the options to the program. int option_count = argc; UniquePtr<JavaVMOption[]> options(new JavaVMOption[option_count]()); // Copy options over. Everything up to the name of the class starts // with a '-' (the function hook stuff is strictly internal). // // [Do we need to catch & handle "-jar" here?] bool need_extra = false; const char* lib = NULL; const char* what = NULL; int curr_opt, arg_idx; for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) { if (argv[arg_idx][0] != '-' && !need_extra) { break; } if (strncmp(argv[arg_idx], "-XXlib:", strlen("-XXlib:")) == 0) { lib = argv[arg_idx] + strlen("-XXlib:"); continue; } options[curr_opt++].optionString = argv[arg_idx]; // Some options require an additional argument. need_extra = false; if (strcmp(argv[arg_idx], "-classpath") == 0 || strcmp(argv[arg_idx], "-cp") == 0) { need_extra = true; what = argv[arg_idx]; } } if (need_extra) { fprintf(stderr, "%s must be followed by an additional argument giving a value\n", what); return EXIT_FAILURE; } // Make sure they provided a class name. if (arg_idx == argc) { fprintf(stderr, "Class name required\n"); return EXIT_FAILURE; } // insert additional internal options here if (curr_opt >= option_count) { fprintf(stderr, "curr_opt(%d) >= option_count(%d)\n", curr_opt, option_count); abort(); return EXIT_FAILURE; } // Find the JNI_CreateJavaVM implementation. JniInvocation jni_invocation; if (!jni_invocation.Init(lib)) { fprintf(stderr, "Failed to initialize JNI invocation API from %s\n", lib); return EXIT_FAILURE; } JavaVMInitArgs init_args; init_args.version = JNI_VERSION_1_6; init_args.options = options.get(); init_args.nOptions = curr_opt; init_args.ignoreUnrecognized = JNI_FALSE; // Start the runtime. The current thread becomes the main thread. JavaVM* vm = NULL; JNIEnv* env = NULL; if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) { fprintf(stderr, "Failed to initialize runtime (check log for details)\n"); return EXIT_FAILURE; } int rc = InvokeMain(env, &argv[arg_idx]); #if defined(NDEBUG) // The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to // detach because detaching disables the CheckSafeToLockOrUnlock checking. if (vm->DetachCurrentThread() != JNI_OK) { fprintf(stderr, "Warning: unable to detach main thread\n"); rc = EXIT_FAILURE; } #endif if (vm->DestroyJavaVM() != 0) { fprintf(stderr, "Warning: runtime did not shut down cleanly\n"); rc = EXIT_FAILURE; } return rc; } } // namespace art int main(int argc, char** argv) { return art::dalvikvm(argc, argv); }
/* * copyright (C) 2011 The Android Open Source Project * * 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 <signal.h> #include <algorithm> #include <cstdio> #include <cstring> #include <string> #include "jni.h" #include "JniInvocation.h" #include "ScopedLocalRef.h" #include "toStringArray.h" #include "UniquePtr.h" namespace art { // Determine whether or not the specified method is public. static bool IsMethodPublic(JNIEnv* env, jclass c, jmethodID method_id) { ScopedLocalRef<jobject> reflected(env, env->ToReflectedMethod(c, method_id, JNI_FALSE)); if (reflected.get() == NULL) { fprintf(stderr, "Failed to get reflected method\n"); return false; } // We now have a Method instance. We need to call its // getModifiers() method. jclass method_class = env->FindClass("java/lang/reflect/Method"); if (method_class == NULL) { fprintf(stderr, "Failed to find class java.lang.reflect.Method\n"); return false; } jmethodID mid = env->GetMethodID(method_class, "getModifiers", "()I"); if (mid == NULL) { fprintf(stderr, "Failed to find java.lang.reflect.Method.getModifiers\n"); return false; } int modifiers = env->CallIntMethod(reflected.get(), mid); static const int PUBLIC = 0x0001; // java.lang.reflect.Modifiers.PUBLIC if ((modifiers & PUBLIC) == 0) { return false; } return true; } static int InvokeMain(JNIEnv* env, char** argv) { // We want to call main() with a String array with our arguments in // it. Create an array and populate it. Note argv[0] is not // included. ScopedLocalRef<jobjectArray> args(env, toStringArray(env, argv + 1)); if (args.get() == NULL) { env->ExceptionDescribe(); return EXIT_FAILURE; } // Find [class].main(String[]). // Convert "com.android.Blah" to "com/android/Blah". std::string class_name(argv[0]); std::replace(class_name.begin(), class_name.end(), '.', '/'); ScopedLocalRef<jclass> klass(env, env->FindClass(class_name.c_str())); if (klass.get() == NULL) { fprintf(stderr, "Unable to locate class '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } jmethodID method = env->GetStaticMethodID(klass.get(), "main", "([Ljava/lang/String;)V"); if (method == NULL) { fprintf(stderr, "Unable to find static main(String[]) in '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } // Make sure the method is public. JNI doesn't prevent us from // calling a private method, so we have to check it explicitly. if (!IsMethodPublic(env, klass.get(), method)) { fprintf(stderr, "Sorry, main() is not public in '%s'\n", class_name.c_str()); env->ExceptionDescribe(); return EXIT_FAILURE; } // Invoke main(). env->CallStaticVoidMethod(klass.get(), method, args.get()); // Check whether there was an uncaught exception. We don't log any uncaught exception here; // detaching this thread will do that for us, but it will clear the exception (and invalidate // our JNIEnv), so we need to check here. return env->ExceptionCheck() ? EXIT_FAILURE : EXIT_SUCCESS; } // Parse arguments. Most of it just gets passed through to the runtime. // The JNI spec defines a handful of standard arguments. static int dalvikvm(int argc, char** argv) { setvbuf(stdout, NULL, _IONBF, 0); // Skip over argv[0]. argv++; argc--; // If we're adding any additional stuff, e.g. function hook specifiers, // add them to the count here. // // We're over-allocating, because this includes the options to the runtime // plus the options to the program. int option_count = argc; UniquePtr<JavaVMOption[]> options(new JavaVMOption[option_count]()); // Copy options over. Everything up to the name of the class starts // with a '-' (the function hook stuff is strictly internal). // // [Do we need to catch & handle "-jar" here?] bool need_extra = false; const char* lib = NULL; const char* what = NULL; int curr_opt, arg_idx; for (curr_opt = arg_idx = 0; arg_idx < argc; arg_idx++) { if (argv[arg_idx][0] != '-' && !need_extra) { break; } if (strncmp(argv[arg_idx], "-XXlib:", strlen("-XXlib:")) == 0) { lib = argv[arg_idx] + strlen("-XXlib:"); continue; } options[curr_opt++].optionString = argv[arg_idx]; // Some options require an additional argument. need_extra = false; if (strcmp(argv[arg_idx], "-classpath") == 0 || strcmp(argv[arg_idx], "-cp") == 0) { need_extra = true; what = argv[arg_idx]; } } if (need_extra) { fprintf(stderr, "%s must be followed by an additional argument giving a value\n", what); return EXIT_FAILURE; } // Make sure they provided a class name. if (arg_idx == argc) { fprintf(stderr, "Class name required\n"); return EXIT_FAILURE; } // insert additional internal options here if (curr_opt >= option_count) { fprintf(stderr, "curr_opt(%d) >= option_count(%d)\n", curr_opt, option_count); abort(); return EXIT_FAILURE; } // Find the JNI_CreateJavaVM implementation. JniInvocation jni_invocation; if (!jni_invocation.Init(lib)) { fprintf(stderr, "Failed to initialize JNI invocation API from %s\n", lib); return EXIT_FAILURE; } JavaVMInitArgs init_args; init_args.version = JNI_VERSION_1_6; init_args.options = options.get(); init_args.nOptions = curr_opt; init_args.ignoreUnrecognized = JNI_FALSE; // Start the runtime. The current thread becomes the main thread. JavaVM* vm = NULL; JNIEnv* env = NULL; if (JNI_CreateJavaVM(&vm, &env, &init_args) != JNI_OK) { fprintf(stderr, "Failed to initialize runtime (check log for details)\n"); return EXIT_FAILURE; } int rc = InvokeMain(env, &argv[arg_idx]); #if defined(NDEBUG) // The DestroyJavaVM call will detach this thread for us. In debug builds, we don't want to // detach because detaching disables the CheckSafeToLockOrUnlock checking. if (vm->DetachCurrentThread() != JNI_OK) { fprintf(stderr, "Warning: unable to detach main thread\n"); rc = EXIT_FAILURE; } #endif if (vm->DestroyJavaVM() != 0) { fprintf(stderr, "Warning: runtime did not shut down cleanly\n"); rc = EXIT_FAILURE; } return rc; } } // namespace art int main(int argc, char** argv) { return art::dalvikvm(argc, argv); }
Add explicit dependency on algorithm
Add explicit dependency on algorithm Change-Id: I3edb34b3c3a1e89a195db18ad8e6a71bc7b4a570
C++
apache-2.0
treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst
1552b1dd1586212c48d268e03f2ab99afb62cf74
Week1/Prime-Factorization/primeFactorization.cpp
Week1/Prime-Factorization/primeFactorization.cpp
#include <cstdlib> #include <iostream> #include <algorithm> #include <vector> // STL #include <bitset> // STL using namespace std; vector<int> primes; void sieve(int size) { bitset<10000010> was; was.set(); was[0] = was[1] = 0; for (int i = 2; i <= size; i++) if (was[i]) { primes.push_back(i); for (int j = i * i; j <= size; j += i) was[j] = 0; } } vector<int> primeFactors(int N){ vector<int> vc; // Comment line below for using other method (iterator) // int idx = 0, f = primes[idx]; // f standing for FACTOR - idx is index that we will increment // // More advanced usage would be pointers : // vector<int>::iterator it = primes.begin(); int f = *it; ///// Uncomment for using iterator // while(N != 1 && N >= f * f){ while(N % f == 0){ N /= f; vc.push_back(f); } // // f = *(++it); ///// Uncomment for using iterator // f = primes[++idx]; // Comment this for using other method (iterator) // } if(N != 1) vc.push_back(N); // This case is for prime numbers itself. return vc; } int main(){ sieve(10000); int n = 18; // cin >> n; vector<int> pF = primeFactors(n); for(int i = 0; i < pF.size() ; ++i){ cout << pF[i] << " " ; } cout << endl; }
#include <cstdlib> #include <iostream> #include <algorithm> #include <vector> // STL #include <bitset> // STL using namespace std; vector<int> primes; void sieve(int size) { bitset<10000010> was; was.set(); was[0] = was[1] = 0; for (int i = 2; i <= size; i++) if (was[i]) { primes.push_back(i); for (int j = i * i; j <= size; j += i) was[j] = 0; } } vector<int> primeFactors(int N){ vector<int> vc; // Comment line below for using other method (iterator) // int idx = 0, f = primes[idx]; // f standing for FACTOR - idx is index that we will increment // // More advanced usage would be pointers : // vector<int>::iterator it = primes.begin(); int f = *it; ///// Uncomment for using iterator // while(N != 1 && N >= f * f){ while(N % f == 0){ N /= f; vc.push_back(f); } // // f = *(++it); ///// Uncomment for using iterator // f = primes[++idx]; // Comment this for using other method (iterator) // } if(N != 1) vc.push_back(N); // This case is for prime numbers itself. return vc; } int main(){ sieve(10000); int n = 18; // cin >> n; vector<int> pF = primeFactors(n); for(int i = 0; i < pF.size() ; ++i){ cout << pF[i] << " " ; } cout << endl; }
Update primeFactorization.cpp
Update primeFactorization.cpp
C++
mit
NAU-ACM/ACM-ICPC-Preparation,NAU-ACM/ACM-ICPC-Preparation
a472b2d26b6bf12f162d05827357cb3de4ba8e6c
modules/base/tests/unittests/volumevoronoi-test.cpp
modules/base/tests/unittests/volumevoronoi-test.cpp
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> namespace inviwo { TEST(Base, volumevoronoi_test) { EXPECT_EQ(1, 1); } } // namespace inviwo
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2020 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <warn/push> #include <warn/ignore/all> #include <gtest/gtest.h> #include <warn/pop> #include <modules/base/algorithm/volume/volumevoronoi.h> namespace inviwo { TEST(VolumeVoronoi, Voronoi_NoSeedPoints_ThrowsException) { const std::vector<std::pair<uint32_t, vec3>> seedPoints = {}; EXPECT_THROW( util::voronoiSegmentation(size3_t{3, 3, 3}, mat4(), seedPoints, std::nullopt, false), inviwo::Exception); } TEST(VolumeVoronoi, WeightedVoronoi_WeightsHasNoValue_ThrowsException) { const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{0.3, 0.2, 0.1}}, {2, vec3{0.1, 0.2, 0.3}}}; const auto weights = std::nullopt; EXPECT_THROW(util::voronoiSegmentation(size3_t{3, 3, 3}, mat4(), seedPoints, weights, true), inviwo::Exception); } TEST(VolumeVoronoi, WeightedVoronoi_WeightsAndSeedPointsDimensionMissmatch_ThrowsException) { const std::vector<std::pair<uint32_t, vec3>> seedPoints = {{1, vec3{0.3, 0.2, 0.1}}, {2, vec3{0.1, 0.2, 0.3}}}; const std::vector<float> weights = {3.0, 4.0, 5.0, 6.0, 7.0}; EXPECT_THROW(util::voronoiSegmentation(size3_t{3, 3, 3}, mat4(), seedPoints, weights, true), inviwo::Exception); } } // namespace inviwo
Test for when throwing exceptions
Test for when throwing exceptions
C++
bsd-2-clause
inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo,inviwo/inviwo
e53bd0aab2f7e011a84149d5b12d0ae010033879
pin/pin_sim.cc
pin/pin_sim.cc
// Jonathan Eastep, Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald, // Nathan Beckmann, David Wentzlaff, James Psota // 10.12.08 // // Carbon Computer Simulator // // This simulator models future multi-core computers with thousands of cores. // It runs on today's x86 multicores and will scale as more and more cores // and better inter-core communications mechanisms become available. // The simulator provides a platform for research in processor architecture, // compilers, network interconnect topologies, and some OS. // // The simulator runs on top of Intel's Pin dynamic binary instrumention engine. // Application code in the absence of instrumentation runs more or less // natively and is thus high performance. When instrumentation is used, models // can be hot-swapped or dynamically enabled and disabled as desired so that // performance tracks the level of simulation detail needed. #include <iostream> #include <assert.h> #include <set> #include <sys/syscall.h> #include <unistd.h> #include "pin.H" #include "log.h" #include "routine_replace.h" // FIXME: This list could probably be trimmed down a lot. #include "simulator.h" #include "core_manager.h" #include "core.h" #include "syscall_model.h" #include "thread_manager.h" #include "config_file.hpp" #include "handle_args.h" #include "thread_start.h" #include "pin_config.h" #include "log.h" #include "vm_manager.h" #include "instruction_modeling.h" #include "progress_trace.h" #include "redirect_memory.h" #include "handle_syscalls.h" #include "opcodes.h" #include <typeinfo> // --------------------------------------------------------------- // FIXME: // There should be a better place to keep these globals // -- a PinSimulator class or smthg bool done_app_initialization = false; config::ConfigFile *cfg; ADDRINT initial_reg_esp; // clone stuff extern int *parent_tidptr; extern struct user_desc *newtls; extern int *child_tidptr; extern PIN_LOCK clone_memory_update_lock; // --------------------------------------------------------------- // --------------------------------------------------------------- map <ADDRINT, string> rtn_map; PIN_LOCK rtn_map_lock; void printRtn (ADDRINT rtn_addr, bool enter) { GetLock (&rtn_map_lock, 1); map<ADDRINT, string>::iterator it = rtn_map.find (rtn_addr); string point = enter ? "Enter" : "Exit"; if (it != rtn_map.end()) { LOG_PRINT ("Stack trace : %s %s", point.c_str(), (it->second).c_str()); } else { LOG_PRINT ("Stack trace : %s UNKNOWN", point.c_str()); } ReleaseLock (&rtn_map_lock); } // --------------------------------------------------------------- INT32 usage() { cerr << "This tool implements a multicore simulator." << endl; cerr << KNOB_BASE::StringKnobSummary() << endl; return -1; } void initializeSyscallModeling () { // Initialize clone stuff parent_tidptr = NULL; newtls = NULL; child_tidptr = NULL; InitLock (&clone_memory_update_lock); } void routineCallback(RTN rtn, void *v) { string rtn_name = RTN_Name(rtn); replaceUserAPIFunction(rtn, rtn_name); // --------------------------------------------------------------- if (Config::getSingleton()->getLoggingEnabled() && Sim()->getCfg()->getBool("log/stack_trace",false)) { RTN_Open (rtn); ADDRINT rtn_addr = RTN_Address (rtn); GetLock (&rtn_map_lock, 1); rtn_map.insert (make_pair (rtn_addr, rtn_name)); ReleaseLock (&rtn_map_lock); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (printRtn), IARG_ADDRINT, rtn_addr, IARG_BOOL, true, IARG_END); RTN_InsertCall (rtn, IPOINT_AFTER, AFUNPTR (printRtn), IARG_ADDRINT, rtn_addr, IARG_BOOL, false, IARG_END); RTN_Close (rtn); } // --------------------------------------------------------------- if (rtn_name == "CarbonSpawnThreadSpawner") { RTN_Open (rtn); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (setupCarbonSpawnThreadSpawnerStack), IARG_CONTEXT, IARG_END); RTN_Close (rtn); } else if (rtn_name == "CarbonThreadSpawner") { RTN_Open (rtn); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (setupCarbonThreadSpawnerStack), IARG_CONTEXT, IARG_END); RTN_Close(rtn); } // TODO: // Commenting out performance modeling code since it causes multiple accesses to memory // when we are simulating shared memory. Fix perf model code to not cause any memory accesses // // bool did_func_replace = replaceUserAPIFunction(rtn, rtn_name); // if (!did_func_replace) // replaceInstruction(rtn, rtn_name); } void showInstructionInfo(INS ins) { if (Sim()->getCoreManager()->getCurrentCore()->getId() != 0) return; printf("\t"); if(INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins)) printf("* "); else printf(" "); // printf("%d - %s ", INS_Category(ins), CATEGORY_StringShort(INS_Category(ins)).c_str()); printf("%x - %s ", INS_Opcode(ins), OPCODE_StringShort(INS_Opcode(ins)).c_str()); printf(" %s ", INS_Disassemble(ins).c_str()); printf("\n"); } VOID instructionCallback (INS ins, void *v) { // showInstructionInfo(ins); if (Log::getSingleton()->isLoggingEnabled()) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(printInsInfo), IARG_CALL_ORDER, CALL_ORDER_FIRST, IARG_CONTEXT, IARG_END); } if (Config::getSingleton()->getEnablePerformanceModeling()) addInstructionModeling(ins); addProgressTrace(ins); if (INS_IsSyscall(ins)) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(handleFutexSyscall), IARG_CONTEXT, IARG_END); } // Emulate Stack Operations if (rewriteStringOp (ins)); else if (rewriteStackOp (ins)); else rewriteMemOp (ins); } // syscall model wrappers void SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v) { syscallEnterRunModel (ctxt, std); } void SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v) { syscallExitRunModel (ctxt, std); } void ApplicationStart() { } void ApplicationExit(int, void*) { LOG_PRINT("Application exit."); Simulator::release(); delete cfg; } VOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v) { ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR); // Conditions under which we must initialize a core // 1) (!done_app_initialization) && (curr_process_num == 0) // 2) (done_app_initialization) && (!thread_spawner) if (! done_app_initialization) { disablePerformanceModelsInCurrentProcess(); #ifdef REDIRECT_MEMORY allocateStackSpace(); #endif UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum(); ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR); if (curr_process_num == 0) { Sim()->getCoreManager()->initializeThread(0); #ifdef REDIRECT_MEMORY ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR); // 1) Copying over Static Data // Get the image first PIN_LockClient(); IMG img = IMG_FindByAddress(reg_eip); PIN_UnlockClient(); LOG_PRINT("Process: 0, Start Copying Static Data"); copyStaticData(img); LOG_PRINT("Process: 0, Finished Copying Static Data"); // 2) Copying over initial stack data LOG_PRINT("Process: 0, Start Copying Initial Stack Data"); copyInitialStackData(reg_esp, 0); LOG_PRINT("Process: 0, Finished Copying Initial Stack Data"); #endif } else { core_id_t core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreNum(); Sim()->getCoreManager()->initializeThread(core_id); // FIXME: // Even if this works, it's a hack. We will need this to be a 'ring' where // all processes initialize one after the other Core *core = Sim()->getCoreManager()->getCurrentCore(); // main thread clock is not affected by start-up time of other processes core->getPerformanceModel()->disable(); core->getNetwork()->netRecv (0, SYSTEM_INITIALIZATION_NOTIFY); core->getPerformanceModel()->enable(); LOG_PRINT("Process: %i, Start Copying Initial Stack Data"); copyInitialStackData(reg_esp, core_id); LOG_PRINT("Process: %i, Finished Copying Initial Stack Data"); } // All the real initialization is done in // replacement_start at the moment done_app_initialization = true; // Set the current ESP accordingly PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp); } else { // This is NOT the main thread // 'application' thread or 'thread spawner' core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp); LOG_ASSERT_ERROR(core_id != -1, "All application threads and thread spawner are cores now"); if (core_id == Sim()->getConfig()->getCurrentThreadSpawnerCoreNum()) { // 'Thread Spawner' thread Sim()->getCoreManager()->initializeThread(core_id); } else { // 'Application' thread ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq(); LOG_ASSERT_ERROR (req != NULL, "ThreadSpawnRequest is NULL !!") // This is an application thread LOG_ASSERT_ERROR(core_id == req->core_id, "Got 2 different core_ids: req->core_id = %i, core_id = %i", req->core_id, core_id); Sim()->getThreadManager()->onThreadStart(req); } // Restore the clone syscall arguments PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr); PIN_SetContextReg (ctxt, REG_GSI, (ADDRINT) newtls); PIN_SetContextReg (ctxt, REG_GDI, (ADDRINT) child_tidptr); Core *core = Sim()->getCoreManager()->getCurrentCore(); assert (core); // Wait to make sure that the spawner has written stuff back to memory // FIXME: What is this for(?) This seems arbitrary GetLock (&clone_memory_update_lock, 2); ReleaseLock (&clone_memory_update_lock); } } VOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v) { Sim()->getThreadManager()->onThreadExit(); } int main(int argc, char *argv[]) { // --------------------------------------------------------------- // FIXME: InitLock (&rtn_map_lock); // --------------------------------------------------------------- // Global initialization PIN_InitSymbols(); PIN_Init(argc,argv); string_vec args; // Set the default config path if it isn't // overwritten on the command line. std::string config_path = "carbon_sim.cfg"; parse_args(args, config_path, argc, argv); cfg = new config::ConfigFile(); cfg->load(config_path); handle_args(args, *cfg); Simulator::setConfig(cfg); Simulator::allocate(); Sim()->start(); PinConfig::allocate(); VMManager::allocate(); // Instrumentation LOG_PRINT("Start of instrumentation."); RTN_AddInstrumentFunction(routineCallback, 0); PIN_AddThreadStartFunction (threadStartCallback, 0); PIN_AddThreadFiniFunction (threadFiniCallback, 0); if(cfg->getBool("general/enable_syscall_modeling")) { initializeSyscallModeling(); PIN_AddSyscallEntryFunction(SyscallEntry, 0); PIN_AddSyscallExitFunction(SyscallExit, 0); PIN_AddContextChangeFunction (contextChange, NULL); } if (cfg->getBool("general/enable_shared_mem")) { INS_AddInstrumentFunction (instructionCallback, 0); } initProgressTrace(); PIN_AddFiniFunction(ApplicationExit, 0); // Just in case ... might not be strictly necessary Transport::getSingleton()->barrier(); // Never returns LOG_PRINT("Running program..."); PIN_StartProgram(); return 0; }
// Jonathan Eastep, Harshad Kasture, Jason Miller, Chris Celio, Charles Gruenwald, // Nathan Beckmann, David Wentzlaff, James Psota // 10.12.08 // // Carbon Computer Simulator // // This simulator models future multi-core computers with thousands of cores. // It runs on today's x86 multicores and will scale as more and more cores // and better inter-core communications mechanisms become available. // The simulator provides a platform for research in processor architecture, // compilers, network interconnect topologies, and some OS. // // The simulator runs on top of Intel's Pin dynamic binary instrumention engine. // Application code in the absence of instrumentation runs more or less // natively and is thus high performance. When instrumentation is used, models // can be hot-swapped or dynamically enabled and disabled as desired so that // performance tracks the level of simulation detail needed. #include <iostream> #include <assert.h> #include <set> #include <sys/syscall.h> #include <unistd.h> #include "pin.H" #include "log.h" #include "routine_replace.h" // FIXME: This list could probably be trimmed down a lot. #include "simulator.h" #include "core_manager.h" #include "core.h" #include "syscall_model.h" #include "thread_manager.h" #include "config_file.hpp" #include "handle_args.h" #include "thread_start.h" #include "pin_config.h" #include "log.h" #include "vm_manager.h" #include "instruction_modeling.h" #include "progress_trace.h" #include "redirect_memory.h" #include "handle_syscalls.h" #include "opcodes.h" #include <typeinfo> // --------------------------------------------------------------- // FIXME: // There should be a better place to keep these globals // -- a PinSimulator class or smthg bool done_app_initialization = false; config::ConfigFile *cfg; ADDRINT initial_reg_esp; // clone stuff extern int *parent_tidptr; extern struct user_desc *newtls; extern int *child_tidptr; extern PIN_LOCK clone_memory_update_lock; // --------------------------------------------------------------- // --------------------------------------------------------------- map <ADDRINT, string> rtn_map; PIN_LOCK rtn_map_lock; void printRtn (ADDRINT rtn_addr, bool enter) { GetLock (&rtn_map_lock, 1); map<ADDRINT, string>::iterator it = rtn_map.find (rtn_addr); string point = enter ? "Enter" : "Exit"; if (it != rtn_map.end()) { LOG_PRINT ("Stack trace : %s %s", point.c_str(), (it->second).c_str()); } else { LOG_PRINT ("Stack trace : %s UNKNOWN", point.c_str()); } ReleaseLock (&rtn_map_lock); } // --------------------------------------------------------------- INT32 usage() { cerr << "This tool implements a multicore simulator." << endl; cerr << KNOB_BASE::StringKnobSummary() << endl; return -1; } void initializeSyscallModeling () { // Initialize clone stuff parent_tidptr = NULL; newtls = NULL; child_tidptr = NULL; InitLock (&clone_memory_update_lock); } void routineCallback(RTN rtn, void *v) { string rtn_name = RTN_Name(rtn); replaceUserAPIFunction(rtn, rtn_name); // --------------------------------------------------------------- if (Config::getSingleton()->getLoggingEnabled() && Sim()->getCfg()->getBool("log/stack_trace",false)) { RTN_Open (rtn); ADDRINT rtn_addr = RTN_Address (rtn); GetLock (&rtn_map_lock, 1); rtn_map.insert (make_pair (rtn_addr, rtn_name)); ReleaseLock (&rtn_map_lock); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (printRtn), IARG_ADDRINT, rtn_addr, IARG_BOOL, true, IARG_END); RTN_InsertCall (rtn, IPOINT_AFTER, AFUNPTR (printRtn), IARG_ADDRINT, rtn_addr, IARG_BOOL, false, IARG_END); RTN_Close (rtn); } // --------------------------------------------------------------- if (rtn_name == "CarbonSpawnThreadSpawner") { RTN_Open (rtn); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (setupCarbonSpawnThreadSpawnerStack), IARG_CONTEXT, IARG_END); RTN_Close (rtn); } else if (rtn_name == "CarbonThreadSpawner") { RTN_Open (rtn); RTN_InsertCall (rtn, IPOINT_BEFORE, AFUNPTR (setupCarbonThreadSpawnerStack), IARG_CONTEXT, IARG_END); RTN_Close(rtn); } // TODO: // Commenting out performance modeling code since it causes multiple accesses to memory // when we are simulating shared memory. Fix perf model code to not cause any memory accesses // // bool did_func_replace = replaceUserAPIFunction(rtn, rtn_name); // if (!did_func_replace) // replaceInstruction(rtn, rtn_name); } void showInstructionInfo(INS ins) { if (Sim()->getCoreManager()->getCurrentCore()->getId() != 0) return; printf("\t"); if(INS_IsMemoryRead(ins) || INS_IsMemoryWrite(ins)) printf("* "); else printf(" "); // printf("%d - %s ", INS_Category(ins), CATEGORY_StringShort(INS_Category(ins)).c_str()); printf("%x - %s ", INS_Opcode(ins), OPCODE_StringShort(INS_Opcode(ins)).c_str()); printf(" %s ", INS_Disassemble(ins).c_str()); printf("\n"); } VOID instructionCallback (INS ins, void *v) { // showInstructionInfo(ins); if (Log::getSingleton()->isLoggingEnabled()) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(printInsInfo), IARG_CALL_ORDER, CALL_ORDER_FIRST, IARG_CONTEXT, IARG_END); } if (Config::getSingleton()->getEnablePerformanceModeling()) addInstructionModeling(ins); addProgressTrace(ins); if (INS_IsSyscall(ins)) { INS_InsertCall(ins, IPOINT_BEFORE, AFUNPTR(handleFutexSyscall), IARG_CONTEXT, IARG_END); } // Emulate Stack Operations if (rewriteStringOp (ins)); else if (rewriteStackOp (ins)); else rewriteMemOp (ins); } // syscall model wrappers void SyscallEntry(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v) { syscallEnterRunModel (ctxt, std); } void SyscallExit(THREADID threadIndex, CONTEXT *ctxt, SYSCALL_STANDARD std, void *v) { syscallExitRunModel (ctxt, std); } void ApplicationStart() { } void ApplicationExit(int, void*) { LOG_PRINT("Application exit."); Simulator::release(); delete cfg; } VOID threadStartCallback(THREADID threadIndex, CONTEXT *ctxt, INT32 flags, VOID *v) { ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR); // Conditions under which we must initialize a core // 1) (!done_app_initialization) && (curr_process_num == 0) // 2) (done_app_initialization) && (!thread_spawner) if (! done_app_initialization) { disablePerformanceModelsInCurrentProcess(); #ifdef REDIRECT_MEMORY allocateStackSpace(); #endif UInt32 curr_process_num = Sim()->getConfig()->getCurrentProcessNum(); ADDRINT reg_esp = PIN_GetContextReg(ctxt, REG_STACK_PTR); if (curr_process_num == 0) { Sim()->getCoreManager()->initializeThread(0); #ifdef REDIRECT_MEMORY ADDRINT reg_eip = PIN_GetContextReg(ctxt, REG_INST_PTR); // 1) Copying over Static Data // Get the image first PIN_LockClient(); IMG img = IMG_FindByAddress(reg_eip); PIN_UnlockClient(); LOG_PRINT("Process: 0, Start Copying Static Data"); copyStaticData(img); LOG_PRINT("Process: 0, Finished Copying Static Data"); // 2) Copying over initial stack data LOG_PRINT("Process: 0, Start Copying Initial Stack Data"); copyInitialStackData(reg_esp, 0); LOG_PRINT("Process: 0, Finished Copying Initial Stack Data"); #endif } else { core_id_t core_id = Sim()->getConfig()->getCurrentThreadSpawnerCoreNum(); Sim()->getCoreManager()->initializeThread(core_id); // FIXME: // Even if this works, it's a hack. We will need this to be a 'ring' where // all processes initialize one after the other Core *core = Sim()->getCoreManager()->getCurrentCore(); // main thread clock is not affected by start-up time of other processes core->getNetwork()->netRecv (0, SYSTEM_INITIALIZATION_NOTIFY); LOG_PRINT("Process: %i, Start Copying Initial Stack Data"); copyInitialStackData(reg_esp, core_id); LOG_PRINT("Process: %i, Finished Copying Initial Stack Data"); } // All the real initialization is done in // replacement_start at the moment done_app_initialization = true; // Set the current ESP accordingly PIN_SetContextReg(ctxt, REG_STACK_PTR, reg_esp); } else { // This is NOT the main thread // 'application' thread or 'thread spawner' core_id_t core_id = PinConfig::getSingleton()->getCoreIDFromStackPtr(reg_esp); LOG_ASSERT_ERROR(core_id != -1, "All application threads and thread spawner are cores now"); if (core_id == Sim()->getConfig()->getCurrentThreadSpawnerCoreNum()) { // 'Thread Spawner' thread Sim()->getCoreManager()->initializeThread(core_id); } else { // 'Application' thread ThreadSpawnRequest* req = Sim()->getThreadManager()->getThreadSpawnReq(); LOG_ASSERT_ERROR (req != NULL, "ThreadSpawnRequest is NULL !!") // This is an application thread LOG_ASSERT_ERROR(core_id == req->core_id, "Got 2 different core_ids: req->core_id = %i, core_id = %i", req->core_id, core_id); Sim()->getThreadManager()->onThreadStart(req); } // Restore the clone syscall arguments PIN_SetContextReg (ctxt, REG_GDX, (ADDRINT) parent_tidptr); PIN_SetContextReg (ctxt, REG_GSI, (ADDRINT) newtls); PIN_SetContextReg (ctxt, REG_GDI, (ADDRINT) child_tidptr); Core *core = Sim()->getCoreManager()->getCurrentCore(); assert (core); // Wait to make sure that the spawner has written stuff back to memory // FIXME: What is this for(?) This seems arbitrary GetLock (&clone_memory_update_lock, 2); ReleaseLock (&clone_memory_update_lock); } } VOID threadFiniCallback(THREADID threadIndex, const CONTEXT *ctxt, INT32 flags, VOID *v) { Sim()->getThreadManager()->onThreadExit(); } int main(int argc, char *argv[]) { // --------------------------------------------------------------- // FIXME: InitLock (&rtn_map_lock); // --------------------------------------------------------------- // Global initialization PIN_InitSymbols(); PIN_Init(argc,argv); string_vec args; // Set the default config path if it isn't // overwritten on the command line. std::string config_path = "carbon_sim.cfg"; parse_args(args, config_path, argc, argv); cfg = new config::ConfigFile(); cfg->load(config_path); handle_args(args, *cfg); Simulator::setConfig(cfg); Simulator::allocate(); Sim()->start(); PinConfig::allocate(); VMManager::allocate(); // Instrumentation LOG_PRINT("Start of instrumentation."); RTN_AddInstrumentFunction(routineCallback, 0); PIN_AddThreadStartFunction (threadStartCallback, 0); PIN_AddThreadFiniFunction (threadFiniCallback, 0); if(cfg->getBool("general/enable_syscall_modeling")) { initializeSyscallModeling(); PIN_AddSyscallEntryFunction(SyscallEntry, 0); PIN_AddSyscallExitFunction(SyscallExit, 0); PIN_AddContextChangeFunction (contextChange, NULL); } if (cfg->getBool("general/enable_shared_mem")) { INS_AddInstrumentFunction (instructionCallback, 0); } initProgressTrace(); PIN_AddFiniFunction(ApplicationExit, 0); // Just in case ... might not be strictly necessary Transport::getSingleton()->barrier(); // Never returns LOG_PRINT("Running program..."); PIN_StartProgram(); return 0; }
Remove old code for disabling perf model at start-up. Was interfering with new method and causing bugs.
[perf] Remove old code for disabling perf model at start-up. Was interfering with new method and causing bugs.
C++
mit
8l/Graphite,nkawahara/Graphite,fhijaz/Graphite,mit-carbon/Graphite,victorisildur/Graphite,mit-carbon/Graphite-Cycle-Level,nkawahara/Graphite,mit-carbon/Graphite-Cycle-Level,mit-carbon/Graphite-Cycle-Level,victorisildur/Graphite,8l/Graphite,victorisildur/Graphite,8l/Graphite,nkawahara/Graphite,fhijaz/Graphite,mit-carbon/Graphite-Cycle-Level,nkawahara/Graphite,victorisildur/Graphite,mit-carbon/Graphite,fhijaz/Graphite,mit-carbon/Graphite,8l/Graphite,fhijaz/Graphite,mit-carbon/Graphite
dc20f9e56b60926f66fa3146561a2b2b1cd275a9
tests/bits/gerold_1.cc
tests/bits/gerold_1.cc
//---------------------------- gerold_1.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2002, 2003, 2004 by the deal.II authors and Anna Schneebeli // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- gerold_1.cc --------------------------- // check whether we can read a 3d grid. this test used to fail until late // 2003, when the necessary infrastructure was created #include "../tests.h" #include <grid/tria.h> #include <dofs/dof_handler.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <fe/fe_q.h> #include <dofs/dof_tools.h> #include <fe/fe_values.h> #include <base/quadrature_lib.h> #include <base/function.h> #include <numerics/vectors.h> #include <numerics/matrices.h> #include <lac/vector.h> #include <lac/full_matrix.h> #include <lac/sparse_matrix.h> #include <lac/solver_cg.h> #include <lac/vector_memory.h> #include <lac/precondition.h> #include <numerics/data_out.h> #include <fstream> #include <iostream> #include <base/logstream.h> #include <grid/grid_in.h> #include <grid/tria_boundary_lib.h> #include <base/timer.h> template <int dim> class LaplaceProblem { public: LaplaceProblem (); void run (); private: Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; SparsityPattern sparsity_pattern; SparseMatrix<double> system_matrix; Vector<double> solution; Vector<double> system_rhs; }; template <int dim> LaplaceProblem<dim>::LaplaceProblem () : fe (1), dof_handler (triangulation) {}; template <int dim> void LaplaceProblem<dim>::run () { deallog << "Solving problem in " << dim << " space dimensions." << std::endl; GridIn<dim> grid_in; grid_in.attach_triangulation (triangulation); std::ifstream input_file("gerold_1.inp"); deallog << "read ucd data file" << std::endl; grid_in.read_ucd(input_file); deallog << "ucd data file readin exe" << std::endl; }; int main () { std::ofstream logfile("gerold_1.output"); deallog.attach(logfile); deallog.depth_console(0); try { LaplaceProblem<3> laplace_problem_3d; laplace_problem_3d.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; }; return 0; };
//---------------------------- gerold_1.cc --------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2002, 2003, 2004 by the deal.II authors and Anna Schneebeli // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------- gerold_1.cc --------------------------- // check whether we can read a 3d grid. this test used to fail until late // 2003, when the necessary infrastructure was created #include "../tests.h" #include <grid/tria.h> #include <dofs/dof_handler.h> #include <grid/grid_generator.h> #include <grid/tria_accessor.h> #include <grid/tria_iterator.h> #include <dofs/dof_accessor.h> #include <fe/fe_q.h> #include <dofs/dof_tools.h> #include <fe/fe_values.h> #include <base/quadrature_lib.h> #include <base/function.h> #include <numerics/vectors.h> #include <numerics/matrices.h> #include <lac/vector.h> #include <lac/full_matrix.h> #include <lac/sparse_matrix.h> #include <lac/solver_cg.h> #include <lac/vector_memory.h> #include <lac/precondition.h> #include <numerics/data_out.h> #include <fstream> #include <iostream> #include <base/logstream.h> #include <grid/grid_in.h> #include <grid/tria_boundary_lib.h> #include <base/timer.h> template <int dim> class LaplaceProblem { public: LaplaceProblem (); void run (); private: Triangulation<dim> triangulation; FE_Q<dim> fe; DoFHandler<dim> dof_handler; SparsityPattern sparsity_pattern; SparseMatrix<double> system_matrix; Vector<double> solution; Vector<double> system_rhs; }; template <int dim> LaplaceProblem<dim>::LaplaceProblem () : fe (1), dof_handler (triangulation) {} template <int dim> void LaplaceProblem<dim>::run () { deallog << "Solving problem in " << dim << " space dimensions." << std::endl; GridIn<dim> grid_in; grid_in.attach_triangulation (triangulation); std::ifstream input_file("gerold_1.inp"); deallog << "read ucd data file" << std::endl; grid_in.read_ucd(input_file); deallog << "ucd data file readin exe" << std::endl; } int main () { std::ofstream logfile("gerold_1.output"); deallog.attach(logfile); deallog.depth_console(0); try { LaplaceProblem<3> laplace_problem_3d; laplace_problem_3d.run (); } catch (std::exception &exc) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Exception on processing: " << std::endl << exc.what() << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; } catch (...) { std::cerr << std::endl << std::endl << "----------------------------------------------------" << std::endl; std::cerr << "Unknown exception!" << std::endl << "Aborting!" << std::endl << "----------------------------------------------------" << std::endl; return 1; }; return 0; }
Remove obsolete ;
Remove obsolete ; git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@8788 0785d39b-7218-0410-832d-ea1e28bc413d
C++
lgpl-2.1
spco/dealii,andreamola/dealii,JaeryunYim/dealii,rrgrove6/dealii,flow123d/dealii,andreamola/dealii,ESeNonFossiIo/dealii,adamkosik/dealii,ESeNonFossiIo/dealii,danshapero/dealii,sairajat/dealii,rrgrove6/dealii,naliboff/dealii,ibkim11/dealii,ibkim11/dealii,andreamola/dealii,shakirbsm/dealii,sairajat/dealii,pesser/dealii,naliboff/dealii,nicolacavallini/dealii,rrgrove6/dealii,angelrca/dealii,JaeryunYim/dealii,JaeryunYim/dealii,mtezzele/dealii,YongYang86/dealii,angelrca/dealii,natashasharma/dealii,flow123d/dealii,danshapero/dealii,shakirbsm/dealii,rrgrove6/dealii,adamkosik/dealii,gpitton/dealii,jperryhouts/dealii,lpolster/dealii,msteigemann/dealii,adamkosik/dealii,ibkim11/dealii,angelrca/dealii,natashasharma/dealii,maieneuro/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,lue/dealii,danshapero/dealii,mac-a/dealii,spco/dealii,maieneuro/dealii,natashasharma/dealii,johntfoster/dealii,kalj/dealii,sriharisundar/dealii,maieneuro/dealii,JaeryunYim/dealii,adamkosik/dealii,natashasharma/dealii,YongYang86/dealii,shakirbsm/dealii,sriharisundar/dealii,shakirbsm/dealii,nicolacavallini/dealii,rrgrove6/dealii,ibkim11/dealii,adamkosik/dealii,sairajat/dealii,Arezou-gh/dealii,natashasharma/dealii,johntfoster/dealii,nicolacavallini/dealii,msteigemann/dealii,gpitton/dealii,spco/dealii,mac-a/dealii,msteigemann/dealii,danshapero/dealii,gpitton/dealii,flow123d/dealii,lue/dealii,YongYang86/dealii,mtezzele/dealii,ESeNonFossiIo/dealii,kalj/dealii,adamkosik/dealii,mac-a/dealii,lpolster/dealii,mtezzele/dealii,maieneuro/dealii,gpitton/dealii,Arezou-gh/dealii,YongYang86/dealii,spco/dealii,EGP-CIG-REU/dealii,EGP-CIG-REU/dealii,JaeryunYim/dealii,johntfoster/dealii,ESeNonFossiIo/dealii,naliboff/dealii,maieneuro/dealii,angelrca/dealii,msteigemann/dealii,EGP-CIG-REU/dealii,maieneuro/dealii,lpolster/dealii,kalj/dealii,pesser/dealii,ESeNonFossiIo/dealii,YongYang86/dealii,mtezzele/dealii,johntfoster/dealii,spco/dealii,andreamola/dealii,msteigemann/dealii,kalj/dealii,spco/dealii,lue/dealii,lue/dealii,jperryhouts/dealii,johntfoster/dealii,sairajat/dealii,flow123d/dealii,nicolacavallini/dealii,jperryhouts/dealii,kalj/dealii,Arezou-gh/dealii,ibkim11/dealii,pesser/dealii,jperryhouts/dealii,danshapero/dealii,mac-a/dealii,lpolster/dealii,EGP-CIG-REU/dealii,JaeryunYim/dealii,rrgrove6/dealii,angelrca/dealii,gpitton/dealii,EGP-CIG-REU/dealii,ibkim11/dealii,lpolster/dealii,danshapero/dealii,naliboff/dealii,nicolacavallini/dealii,mtezzele/dealii,natashasharma/dealii,ibkim11/dealii,Arezou-gh/dealii,shakirbsm/dealii,naliboff/dealii,sriharisundar/dealii,flow123d/dealii,jperryhouts/dealii,gpitton/dealii,shakirbsm/dealii,ESeNonFossiIo/dealii,sairajat/dealii,rrgrove6/dealii,johntfoster/dealii,lue/dealii,sairajat/dealii,EGP-CIG-REU/dealii,mac-a/dealii,johntfoster/dealii,angelrca/dealii,nicolacavallini/dealii,YongYang86/dealii,naliboff/dealii,naliboff/dealii,lpolster/dealii,Arezou-gh/dealii,sairajat/dealii,natashasharma/dealii,andreamola/dealii,shakirbsm/dealii,JaeryunYim/dealii,lpolster/dealii,YongYang86/dealii,Arezou-gh/dealii,pesser/dealii,pesser/dealii,lue/dealii,kalj/dealii,andreamola/dealii,jperryhouts/dealii,mtezzele/dealii,EGP-CIG-REU/dealii,adamkosik/dealii,pesser/dealii,gpitton/dealii,lue/dealii,maieneuro/dealii,msteigemann/dealii,kalj/dealii,jperryhouts/dealii,mac-a/dealii,mac-a/dealii,nicolacavallini/dealii,sriharisundar/dealii,msteigemann/dealii,sriharisundar/dealii,mtezzele/dealii,angelrca/dealii,spco/dealii,andreamola/dealii,flow123d/dealii,danshapero/dealii,Arezou-gh/dealii,flow123d/dealii,pesser/dealii,sriharisundar/dealii
5ab4514fecd4a271015e339169114054974d025d
tests/common_tests.cpp
tests/common_tests.cpp
// // Created by thuanqin on 16/5/13. // #include "gtest/gtest.h" #include <fstream> #include <iostream> #include <string> #include "common/config.h" const std::string config_file_name = "controller.cfg"; void generate_test_config_file() { std::ofstream out; out.open(config_file_name, std::ios::out); if (out.is_open()) { out << "# test config file" << std::endl; out << " " << std::endl; out << "item_int=100" << std::endl; out << "item_str=http://test.com" << std::endl; out << "item_true=true" << std::endl; out << "item_falue=false" << std::endl; out << " item_int_with_space = 99" << std::endl; out.close(); } } TEST(ConfigMgr, GetItem) { generate_test_config_file(); ConfigMgr config_mgr("./", "controller.cfg"); EXPECT_EQ(100, config_mgr.get_item("item_int")->get_int()); EXPECT_EQ("http://test.com", config_mgr.get_item("item_str")->get_str()); EXPECT_EQ(true, config_mgr.get_item("item_true")->get_bool()); EXPECT_EQ(false, config_mgr.get_item("item_falue")->get_bool()); EXPECT_EQ(99, config_mgr.get_item("item_int_with_space")->get_int()); }
// // Created by thuanqin on 16/5/13. // #include "gtest/gtest.h" #include <fstream> #include <iostream> #include <string> #include "common/config.h" const std::string config_file_name = "controller.cfg"; void generate_test_config_file() { std::ofstream out; out.open(config_file_name, std::ios::out); if (out.is_open()) { out << "# test config file" << std::endl; out << " " << std::endl; out << "item_int=100" << std::endl; out << "item_str=http://test.com" << std::endl; out << "item_true=true" << std::endl; out << "item_falue=false" << std::endl; out << " item_int_with_space = 99" << std::endl; out.close(); } } TEST(ConfigMgr, GetItem) { generate_test_config_file(); ConfigMgr config_mgr("./", config_file_name); EXPECT_EQ(100, config_mgr.get_item("item_int")->get_int()); EXPECT_EQ("http://test.com", config_mgr.get_item("item_str")->get_str()); EXPECT_EQ(true, config_mgr.get_item("item_true")->get_bool()); EXPECT_EQ(false, config_mgr.get_item("item_falue")->get_bool()); EXPECT_EQ(99, config_mgr.get_item("item_int_with_space")->get_int()); }
use constant var
use constant var
C++
apache-2.0
QthCN/opsguide_ogp
ca0dfa0e6046ddd71bd57b72b857c5fad63efd00
Code/Common/mvdImageViewManipulator.cxx
Code/Common/mvdImageViewManipulator.cxx
/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdImageViewManipulator.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) namespace mvd { /* TRANSLATOR mvd::ImageViewManipulator Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ ImageViewManipulator ::ImageViewManipulator( QObject* parent ) : AbstractViewManipulator( parent ), m_PreviousIsotropicZoom(1.) { } /*****************************************************************************/ ImageViewManipulator ::~ImageViewManipulator() { } /*****************************************************************************/ bool ImageViewManipulator ::HasZoomChanged() const { bool res = false; if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 ) { res = true; } return res; } /******************************************************************************/ void ImageViewManipulator ::mousePressEvent(QMouseEvent * event) { // Update the context with the pressed position m_MouseContext.x = event->x(); m_MouseContext.y = event->y(); // Update the context with the pressed position for the mouseMoveEvent m_MouseContext.xMove = event->x(); m_MouseContext.yMove = event->y(); } /******************************************************************************/ void ImageViewManipulator ::mouseMoveEvent( QMouseEvent * event) { m_PreviousIsotropicZoom = m_IsotropicZoom; // Update the context with the pressed position m_MouseContext.x = event->x(); m_MouseContext.y = event->y(); // Update the mouse context m_MouseContext.dx = m_MouseContext.xMove - m_MouseContext.x; m_MouseContext.dy = m_MouseContext.yMove - m_MouseContext.y; // moveRegion this->moveRegion( m_MouseContext.dx, m_MouseContext.dy); // update the position of the first press to take into account the // last drag m_MouseContext.xMove = m_MouseContext.x; m_MouseContext.yMove = m_MouseContext.y; } /******************************************************************************/ void ImageViewManipulator ::moveRegion(double dx, double dy) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Apply the offset to the (start) index of the stored region ImageRegionType::OffsetType offset; offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5); offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5); // Apply the offset to the (start) index of the stored region IndexType index = currentRegion.GetIndex() + offset; currentRegion.SetIndex(index); // Constraint the region to the largestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); } /******************************************************************************/ void ImageViewManipulator ::mouseReleaseEvent( QMouseEvent * event) { //TODO: Implement mouseReleaseEvent. //std::cout <<" Not Implemented yet ..." << std::endl; } /******************************************************************************/ void ImageViewManipulator ::resizeEvent( QResizeEvent * event ) { this->ResizeRegion( event->size().width(), event->size().height()); } /******************************************************************************/ void ImageViewManipulator ::ResizeRegion(unsigned int w, unsigned int h) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Get the new widget size ImageRegionType::SizeType size; size[0] = w; size[1] = h; // Update the stored region with the new size currentRegion.SetSize(size); // Recompute the size before m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom(); m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom(); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // call the rescale method with the same zoom as before (scale = 1) this->Zoom(1.); } /******************************************************************************/ void ImageViewManipulator ::wheelEvent( QWheelEvent * event) { // compute the new scale double scaleRatio = 1.25; double numDegrees = event->delta() / 8.; int nbSteps = static_cast<int>(numDegrees / 15.); double scale = vcl_pow(scaleRatio, nbSteps); // center the region on the center of the previous region this->CenterRegion(scale); // rescale the viewport region this->Zoom(scale); } /******************************************************************************/ void ImageViewManipulator ::Zoom(const double scale) { m_PreviousIsotropicZoom = m_IsotropicZoom; // compute the new size double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale; double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale; // check that the new size is greater than 30x30 // check that the new isoZoom is not too low and not too large // TODO : compute automatically the minSize and the isoZoom range ??? if (sizeX > 30 && sizeY > 30 && m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.) { // Update the the sizeBeforeConstrain m_NavigationContext.m_SizeXBeforeConstrain = sizeX; m_NavigationContext.m_SizeYBeforeConstrain = sizeY; // Update the viewort region with the new size ImageRegionType::SizeType size; size[0] = static_cast<unsigned int>(sizeX); size[1] = static_cast<unsigned int>(sizeY); // The viewPort Region must be adapted to this zoom ratio ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Update the stored region with the new size currentRegion.SetSize(size); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // Update the isotropicZoom m_IsotropicZoom *= scale; // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); } } /******************************************************************************/ void ImageViewManipulator ::CenterRegion(double scale) { if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.) { // The viewPort Region must be adapted to this zoom ratio ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // center the region on the position under the cursor IndexType origin = currentRegion.GetIndex(); double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.; double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.; // new origin IndexType newIndex; newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.; if (newIndex[0] < 0) newIndex[0] = 0; newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.; if (newIndex[1] < 0) newIndex[1] = 0; // set the new origin currentRegion.SetIndex(newIndex); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); } } /******************************************************************************/ void ImageViewManipulator ::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest) { ImageRegionType::SizeType zeroSize; zeroSize.Fill(0); if (largest.GetSize() != zeroSize) { // Else we can constrain it IndexType index = region.GetIndex(); ImageRegionType::SizeType size = region.GetSize(); // If region is larger than big, then crop if (region.GetSize()[0] > largest.GetSize()[0]) { size[0] = largest.GetSize()[0]; } if (region.GetSize()[1] > largest.GetSize()[1]) { size[1] = largest.GetSize()[1]; } // Else we can constrain it // For each dimension for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim) { // push left if necessary if (region.GetIndex()[dim] < largest.GetIndex()[dim]) { index[dim] = largest.GetIndex()[dim]; } // push right if necessary if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim]) { index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim]; } } region.SetSize(size); region.SetIndex(index); } } /******************************************************************************/ void ImageViewManipulator ::keyPressEvent( QKeyEvent * event ) { switch(event->key()) { case Qt::Key_Minus: CenterRegion(0.8); Zoom(0.8); break; case Qt::Key_Plus: CenterRegion(1.25); Zoom(1.25); break; case Qt::Key_Left: moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0); break; case Qt::Key_Right: moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0); break; case Qt::Key_Up: moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 ); break; case Qt::Key_Down: moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 ); break; default: break; } } /*****************************************************************************/ void ImageViewManipulator ::PropagateViewportRegionChanged(const ImageRegionType& region) { // the region computed in this class are relative to the lod 0 of // the input image. We need then, to transform the indicies to // physical points, the native spacing (lod 0) // of the method PointType ul, lr; ul[0] = (double)(region.GetIndex()[0]) * m_NativeSpacing[0]; ul[1] = (double)(region.GetIndex()[1]) * vcl_abs(m_NativeSpacing[1]); lr[0] = (double)( region.GetIndex()[0] + region.GetSize()[0] ) * m_NativeSpacing[0]; lr[1] = (double)( region.GetIndex()[1] + region.GetSize()[1] ) * vcl_abs(m_NativeSpacing[1]); emit ViewportRegionRepresentationChanged(ul, lr); } /*****************************************************************************/ void ImageViewManipulator ::PropagatePointUnderCursorCoordinates(const QPoint & point ) { // screen index to image (at resol 0) coordinates double px = (point.x() - GetViewportOrigin()[0] ) / GetIsotropicZoom() + m_NavigationContext.m_ViewportImageRegion.GetIndex()[0]; double py = (point.y() - GetViewportOrigin()[1] ) / GetIsotropicZoom() + m_NavigationContext.m_ViewportImageRegion.GetIndex()[1]; // // compose the label to send to the status bar std::ostringstream oss; oss<<" Index : " << px <<" , "<< py; QString coordinates(oss.str().c_str()); // update the status bar emit CurrentCoordinatesUpdated(coordinates); } /*****************************************************************************/ /* SLOTS */ /*****************************************************************************/ /*****************************************************************************/ void ImageViewManipulator ::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing) { // update the spacing SetSpacing(spacing); // store the native spacing too (for physical coordinate // computations) m_NativeSpacing = spacing; // set back the zoom to 1 m_IsotropicZoom = 1.; m_PreviousIsotropicZoom = 1.; // store the image largest region m_NavigationContext.m_ModelImageRegion = largestRegion; // set back the origin to O IndexType nullIndex; nullIndex.Fill(0); m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex); // get the widget size and use it to resize the Viewport region QWidget* parent_widget = qobject_cast< QWidget* >( parent() ); if (parent_widget) { this->ResizeRegion(parent_widget->width(), parent_widget->height()); } // compute the intial scale factor to fit to screen double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0] /(double)(largestRegion.GetSize()[0]); double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1] /(double)(largestRegion.GetSize()[1]); double scale = std::min(factorX, factorY); this->Zoom(scale); } /*****************************************************************************/ void ImageViewManipulator ::OnViewportRegionChanged(double Xpc, double Ypc) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // center the region on the position under the cursor IndexType origin; origin[0] = static_cast<unsigned int>(( Xpc / vcl_abs(m_NativeSpacing[0]) )) - currentRegion.GetSize()[0] / 2 ; origin[1] = static_cast<unsigned int>(( Ypc / vcl_abs(m_NativeSpacing[1]) )) - currentRegion.GetSize()[1] / 2 ; currentRegion.SetIndex(origin); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); // force repaintGL qobject_cast< QWidget* >( parent() )->update(); } /*****************************************************************************/ void ImageViewManipulator ::OnPhysicalCursorPositionChanged(double Xpc, double Ypc) { // From physcial point to original image at res 0 index unsigned int idx = static_cast<unsigned int>(( Xpc / vcl_abs(m_NativeSpacing[0]) )); unsigned int idy = static_cast<unsigned int>(( Ypc / vcl_abs(m_NativeSpacing[1]) )); // compose the label to send to the status bar std::ostringstream oss; oss<<" Index : " << idx <<" , "<< idy; QString coordinates(oss.str().c_str()); // update the status bar emit CurrentCoordinatesUpdated(coordinates); } } // end namespace 'mvd'
/*========================================================================= Program: Monteverdi2 Language: C++ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See Copyright.txt for details. Monteverdi2 is distributed under the CeCILL licence version 2. See Licence_CeCILL_V2-en.txt or http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more 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 "mvdImageViewManipulator.h" // // Qt includes (sorted by alphabetic order) //// Must be included before system/custom includes. // // System includes (sorted by alphabetic order) // // ITK includes (sorted by alphabetic order) // // OTB includes (sorted by alphabetic order) // // Monteverdi includes (sorted by alphabetic order) namespace mvd { /* TRANSLATOR mvd::ImageViewManipulator Necessary for lupdate to be aware of C++ namespaces. Context comment for translator. */ /*****************************************************************************/ ImageViewManipulator ::ImageViewManipulator( QObject* parent ) : AbstractViewManipulator( parent ), m_PreviousIsotropicZoom(1.) { } /*****************************************************************************/ ImageViewManipulator ::~ImageViewManipulator() { } /*****************************************************************************/ bool ImageViewManipulator ::HasZoomChanged() const { bool res = false; if (vcl_abs(m_IsotropicZoom - m_PreviousIsotropicZoom) > 0.00000001 ) { res = true; } return res; } /******************************************************************************/ void ImageViewManipulator ::mousePressEvent(QMouseEvent * event) { // Update the context with the pressed position m_MouseContext.x = event->x(); m_MouseContext.y = event->y(); // Update the context with the pressed position for the mouseMoveEvent m_MouseContext.xMove = event->x(); m_MouseContext.yMove = event->y(); } /******************************************************************************/ void ImageViewManipulator ::mouseMoveEvent( QMouseEvent * event) { m_PreviousIsotropicZoom = m_IsotropicZoom; // Update the context with the pressed position m_MouseContext.x = event->x(); m_MouseContext.y = event->y(); // Update the mouse context m_MouseContext.dx = m_MouseContext.xMove - m_MouseContext.x; m_MouseContext.dy = m_MouseContext.yMove - m_MouseContext.y; // moveRegion this->moveRegion( m_MouseContext.dx, m_MouseContext.dy); // update the position of the first press to take into account the // last drag m_MouseContext.xMove = m_MouseContext.x; m_MouseContext.yMove = m_MouseContext.y; } /******************************************************************************/ void ImageViewManipulator ::moveRegion(double dx, double dy) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Apply the offset to the (start) index of the stored region ImageRegionType::OffsetType offset; offset[0] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dx/m_IsotropicZoom + 0.5); offset[1] = static_cast<ImageRegionType::OffsetType::OffsetValueType> (dy/m_IsotropicZoom + 0.5); // Apply the offset to the (start) index of the stored region IndexType index = currentRegion.GetIndex() + offset; currentRegion.SetIndex(index); // Constraint the region to the largestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); } /******************************************************************************/ void ImageViewManipulator ::mouseReleaseEvent( QMouseEvent * event) { //TODO: Implement mouseReleaseEvent. //std::cout <<" Not Implemented yet ..." << std::endl; } /******************************************************************************/ void ImageViewManipulator ::resizeEvent( QResizeEvent * event ) { this->ResizeRegion( event->size().width(), event->size().height()); } /******************************************************************************/ void ImageViewManipulator ::ResizeRegion(unsigned int w, unsigned int h) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Get the new widget size ImageRegionType::SizeType size; size[0] = w; size[1] = h; // Update the stored region with the new size currentRegion.SetSize(size); // Recompute the size before m_NavigationContext.m_SizeXBeforeConstrain = (double)size[0] / this->GetIsotropicZoom(); m_NavigationContext.m_SizeYBeforeConstrain = (double)size[1] / this->GetIsotropicZoom(); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // call the rescale method with the same zoom as before (scale = 1) this->Zoom(1.); } /******************************************************************************/ void ImageViewManipulator ::wheelEvent( QWheelEvent * event) { // compute the new scale double scaleRatio = 1.25; double numDegrees = event->delta() / 8.; int nbSteps = static_cast<int>(numDegrees / 15.); double scale = vcl_pow(scaleRatio, nbSteps); // center the region on the center of the previous region this->CenterRegion(scale); // rescale the viewport region this->Zoom(scale); } /******************************************************************************/ void ImageViewManipulator ::Zoom(const double scale) { m_PreviousIsotropicZoom = m_IsotropicZoom; // compute the new size double sizeX = m_NavigationContext.m_SizeXBeforeConstrain / scale; double sizeY = m_NavigationContext.m_SizeYBeforeConstrain / scale; // check that the new size is greater than 30x30 // check that the new isoZoom is not too low and not too large // TODO : compute automatically the minSize and the isoZoom range ??? if (sizeX > 30 && sizeY > 30 && m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.) { // Update the the sizeBeforeConstrain m_NavigationContext.m_SizeXBeforeConstrain = sizeX; m_NavigationContext.m_SizeYBeforeConstrain = sizeY; // Update the viewort region with the new size ImageRegionType::SizeType size; size[0] = static_cast<unsigned int>(sizeX); size[1] = static_cast<unsigned int>(sizeY); // The viewPort Region must be adapted to this zoom ratio ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // Update the stored region with the new size currentRegion.SetSize(size); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // Update the isotropicZoom m_IsotropicZoom *= scale; // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); } } /******************************************************************************/ void ImageViewManipulator ::CenterRegion(double scale) { if( m_IsotropicZoom * scale > 0.01 && m_IsotropicZoom * scale < 10.) { // The viewPort Region must be adapted to this zoom ratio ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // center the region on the position under the cursor IndexType origin = currentRegion.GetIndex(); double centerX = (double)(origin[0]) + (double)(currentRegion.GetSize()[0])/2.; double centerY = (double)(origin[1]) + (double)(currentRegion.GetSize()[1])/2.; // new origin IndexType newIndex; newIndex[0] = centerX - currentRegion.GetSize()[0]/scale/2.; if (newIndex[0] < 0) newIndex[0] = 0; newIndex[1] = centerY - currentRegion.GetSize()[1]/scale/2.; if (newIndex[1] < 0) newIndex[1] = 0; // set the new origin currentRegion.SetIndex(newIndex); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); } } /******************************************************************************/ void ImageViewManipulator ::ConstrainRegion( ImageRegionType& region, const ImageRegionType& largest) { ImageRegionType::SizeType zeroSize; zeroSize.Fill(0); if (largest.GetSize() != zeroSize) { // Else we can constrain it IndexType index = region.GetIndex(); ImageRegionType::SizeType size = region.GetSize(); // If region is larger than big, then crop if (region.GetSize()[0] > largest.GetSize()[0]) { size[0] = largest.GetSize()[0]; } if (region.GetSize()[1] > largest.GetSize()[1]) { size[1] = largest.GetSize()[1]; } // Else we can constrain it // For each dimension for (unsigned int dim = 0; dim < ImageRegionType::ImageDimension; ++dim) { // push left if necessary if (region.GetIndex()[dim] < largest.GetIndex()[dim]) { index[dim] = largest.GetIndex()[dim]; } // push right if necessary if (index[dim] + size[dim] >= largest.GetIndex()[dim] + largest.GetSize()[dim]) { index[dim] = largest.GetIndex()[dim] + largest.GetSize()[dim] - size[dim]; } } region.SetSize(size); region.SetIndex(index); } } /******************************************************************************/ void ImageViewManipulator ::keyPressEvent( QKeyEvent * event ) { switch(event->key()) { case Qt::Key_Minus: CenterRegion(0.8); Zoom(0.8); break; case Qt::Key_Plus: CenterRegion(1.25); Zoom(1.25); break; case Qt::Key_Left: moveRegion(-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0); break; case Qt::Key_Right: moveRegion(static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(0))*m_IsotropicZoom/4 ,0); break; case Qt::Key_Up: moveRegion(0,-static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 ); break; case Qt::Key_Down: moveRegion(0,static_cast<double>(m_NavigationContext.m_ViewportImageRegion.GetSize(1))*m_IsotropicZoom/4 ); break; default: break; } } /*****************************************************************************/ void ImageViewManipulator ::PropagateViewportRegionChanged(const ImageRegionType& region) { // the region computed in this class are relative to the lod 0 of // the input image. We need then, to transform the indicies to // physical points, the native spacing (lod 0) // of the method PointType ul, lr; ul[0] = (double)(region.GetIndex()[0]) * m_NativeSpacing[0]; ul[1] = (double)(region.GetIndex()[1]) * vcl_abs(m_NativeSpacing[1]); lr[0] = (double)( region.GetIndex()[0] + region.GetSize()[0] ) * m_NativeSpacing[0]; lr[1] = (double)( region.GetIndex()[1] + region.GetSize()[1] ) * vcl_abs(m_NativeSpacing[1]); emit ViewportRegionRepresentationChanged(ul, lr); } /*****************************************************************************/ void ImageViewManipulator ::PropagatePointUnderCursorCoordinates(const QPoint & point ) { // screen index to image (at resol 0) coordinates double px = (point.x() - GetViewportOrigin()[0] ) / GetIsotropicZoom() + m_NavigationContext.m_ViewportImageRegion.GetIndex()[0]; double py = (point.y() - GetViewportOrigin()[1] ) / GetIsotropicZoom() + m_NavigationContext.m_ViewportImageRegion.GetIndex()[1]; // // compose the label to send to the status bar std::ostringstream oss; oss<<" Index : " << static_cast<int>(px) <<" , "<< static_cast<int>(py); QString coordinates(oss.str().c_str()); // update the status bar emit CurrentCoordinatesUpdated(coordinates); } /*****************************************************************************/ /* SLOTS */ /*****************************************************************************/ /*****************************************************************************/ void ImageViewManipulator ::OnModelImageRegionChanged(const ImageRegionType & largestRegion, const SpacingType& spacing) { // update the spacing SetSpacing(spacing); // store the native spacing too (for physical coordinate // computations) m_NativeSpacing = spacing; // set back the zoom to 1 m_IsotropicZoom = 1.; m_PreviousIsotropicZoom = 1.; // store the image largest region m_NavigationContext.m_ModelImageRegion = largestRegion; // set back the origin to O IndexType nullIndex; nullIndex.Fill(0); m_NavigationContext.m_ViewportImageRegion.SetIndex(nullIndex); // get the widget size and use it to resize the Viewport region QWidget* parent_widget = qobject_cast< QWidget* >( parent() ); if (parent_widget) { this->ResizeRegion(parent_widget->width(), parent_widget->height()); } // compute the intial scale factor to fit to screen double factorX = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[0] /(double)(largestRegion.GetSize()[0]); double factorY = (double)m_NavigationContext.m_ViewportImageRegion.GetSize()[1] /(double)(largestRegion.GetSize()[1]); double scale = std::min(factorX, factorY); this->Zoom(scale); } /*****************************************************************************/ void ImageViewManipulator ::OnViewportRegionChanged(double Xpc, double Ypc) { // Update the navigation context ImageRegionType & currentRegion = m_NavigationContext.m_ViewportImageRegion; // center the region on the position under the cursor IndexType origin; origin[0] = static_cast<unsigned int>(( Xpc / vcl_abs(m_NativeSpacing[0]) )) - currentRegion.GetSize()[0] / 2 ; origin[1] = static_cast<unsigned int>(( Ypc / vcl_abs(m_NativeSpacing[1]) )) - currentRegion.GetSize()[1] / 2 ; currentRegion.SetIndex(origin); // Constraint this region to the LargestPossibleRegion this->ConstrainRegion(currentRegion, m_NavigationContext.m_ModelImageRegion); // tell the quicklook renderer to update the red square rendering this->PropagateViewportRegionChanged(currentRegion); // force repaintGL qobject_cast< QWidget* >( parent() )->update(); } /*****************************************************************************/ void ImageViewManipulator ::OnPhysicalCursorPositionChanged(double Xpc, double Ypc) { // From physcial point to original image at res 0 index int idx = static_cast<unsigned int>(( Xpc / vcl_abs(m_NativeSpacing[0]) )); int idy = static_cast<unsigned int>(( Ypc / vcl_abs(m_NativeSpacing[1]) )); // compose the label to send to the status bar std::ostringstream oss; oss<<" Index : " << idx <<" , "<< idy; QString coordinates(oss.str().c_str()); // update the status bar emit CurrentCoordinatesUpdated(coordinates); } } // end namespace 'mvd'
print indicies as integer
ENH: print indicies as integer
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
1959b81d34c92a2615c47a19051cd7c04def5ad5
experimental/Pomdog.Experimental/Rendering/Renderer.hpp
experimental/Pomdog.Experimental/Rendering/Renderer.hpp
// Copyright (c) 2013-2017 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Graphics/detail/ForwardDeclarations.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include <memory> namespace Pomdog { class RenderCommand; class RenderCommandProcessor; class Renderer final { public: explicit Renderer(const std::shared_ptr<GraphicsDevice>& graphicsDevice); ~Renderer(); void SetViewMatrix(const Matrix4x4& viewMatrix); void SetProjectionMatrix(const Matrix4x4& projectionMatrix); std::shared_ptr<GraphicsCommandList> Render(); void PushCommand(std::reference_wrapper<RenderCommand> && command); void Reset(); void AddProcessor(std::unique_ptr<RenderCommandProcessor> && processor); int GetDrawCallCount() const noexcept; public: class Impl; std::unique_ptr<Impl> impl; }; } // namespace Pomdog
// Copyright (c) 2013-2017 mogemimi. Distributed under the MIT license. #pragma once #include "Pomdog/Graphics/detail/ForwardDeclarations.hpp" #include "Pomdog/Math/Matrix4x4.hpp" #include <memory> namespace Pomdog { class RenderCommand; class RenderCommandProcessor; class Renderer final { public: explicit Renderer(const std::shared_ptr<GraphicsDevice>& graphicsDevice); ~Renderer(); void SetViewMatrix(const Matrix4x4& viewMatrix); void SetProjectionMatrix(const Matrix4x4& projectionMatrix); std::shared_ptr<GraphicsCommandList> Render(); void PushCommand(std::reference_wrapper<RenderCommand> && command); void Reset(); void AddProcessor(std::unique_ptr<RenderCommandProcessor> && processor); int GetDrawCallCount() const noexcept; private: class Impl; std::unique_ptr<Impl> impl; }; } // namespace Pomdog
Make a PIMPL member private
Make a PIMPL member private
C++
mit
mogemimi/pomdog,mogemimi/pomdog,mogemimi/pomdog
f4352c470175ed41328c85e93e9b2b7f1de18c08
plotwidget.cpp
plotwidget.cpp
#include "plotwidget.h" #include <QPainter> #include "mytablemodel.h" #include <QtMath> #include <QTimer> PlotWidget::PlotWidget(MyTableModel *table, QWidget *parent) :QWidget(parent) ,m_table(table) ,m_shift(0) ,m_angle(0.5) ,m_timer(new QTimer()) { connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimer())); m_timer->start(1000.0 / 60); } PlotWidget::~PlotWidget() { m_timer->stop(); delete m_timer; } void PlotWidget::setAngle(int angle) { m_angle = 1.0 * angle / 100; } const QVector<QColor> colors = { "orange", "yellow", "green", "blue", "violet", "pink" }; double DegAngleToRadAngle(double deg) { return (deg / 180 * M_PI); } double RadAngleToDegAngle(double rad) { return (rad / M_PI * 180); } QPolygonF GenerateSidePolygon(QVector<QPointF> const& line, QPointF const& shift) { Q_ASSERT(!line.empty()); QPolygonF result; for (auto &point : line) result << point; for (int i = line.size() - 1; i >= 0; --i) result << line[i] + shift; return result; } QPointF GetEllipsePoint(QRectF const& rect, double angle) { return rect.center() + QPointF( rect.width() / 2 * cos(angle), rect.height() / 2 * sin(angle) ); } int RadAngleToPieAngle(double angle) { return RadAngleToDegAngle(angle) * 16; } void DrawPieHelper(QPainter &painter, QRectF const& rect, double astart, double aend) { double alen = aend - astart; painter.drawPie(rect, RadAngleToPieAngle(-aend), RadAngleToPieAngle(alen)); } double ConstrainAngle(double x) { x = fmod(x, 2 * M_PI); if (x < 0) x += 2 * M_PI; return x; } double SmallestAngleDifference(double a, double b) { double r = ConstrainAngle(a - b); if (r > M_PI) r -= 2 * M_PI; if (r < -M_PI) r += 2 * M_PI; return fabs(r); } void DrawPie(QPainter &painter, QRectF const& rect, QPointF const& shift, double astart, double aend) { { double first, second; if (SmallestAngleDifference(astart, 3 * M_PI / 2) < SmallestAngleDifference(aend, 3 * M_PI / 2)) { first = astart; second = aend; } else { first = aend; second = astart; } painter.drawPolygon(GenerateSidePolygon( { rect.center(), GetEllipsePoint(rect, first) }, shift )); painter.drawPolygon(GenerateSidePolygon( { rect.center(), GetEllipsePoint(rect, second) }, shift )); } { QVector<QPointF> arc; for (double angle = astart; angle <= aend; angle += 0.01) { if (ConstrainAngle(angle) <= M_PI) arc.push_back(GetEllipsePoint(rect, angle)); } if (!arc.empty()) painter.drawPolygon(GenerateSidePolygon(arc, shift)); } DrawPieHelper(painter, rect, astart, aend); } struct PieInfo { double astart; double alen; int number; PieInfo() :astart(0) ,alen(0) ,number(0) {} PieInfo(double astart, double alen, int number) :astart(astart) ,alen(alen) ,number(number) {} double Key() const { return SmallestAngleDifference(astart + alen / 2, 3 * M_PI / 2); } bool operator<(PieInfo const& other) const { return Key() < other.Key(); } }; double LinearFunc(double k, double x, double b) { return k * x + b; } double HeightScaleFunc(double angle) { return LinearFunc(0.8 - 0.2, angle, 0.2); } double ThicknessScaleFunc(double angle) { return LinearFunc(0.02 - 0.1, angle, 0.1); } void PlotWidget::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); QPainter painter(this); painter.setRenderHints(painter.renderHints() | QPainter::Antialiasing); painter.drawRect(0, 0, size().width(), size().height()); const int HGAP = 10; double heightScale = HeightScaleFunc(m_angle); double thicknessScale = ThicknessScaleFunc(m_angle); double vgap = size().height() * (1 - heightScale) / 2; QRectF rect(HGAP, vgap, size().width() - 2 * HGAP, size().height() * heightScale); QPointF shift(0, size().height() * thicknessScale); int sum = 0; for (int row = 0; row < m_table->getSize(); ++row) sum += m_table->getNumber(row); if (sum == 0) return; QVector<PieInfo> pies; { double start = 0; for (int row = 0; row < m_table->getSize(); ++row) { double curSize = 2 * M_PI * m_table->getNumber(row) / sum; pies.push_back(PieInfo(start + m_shift, curSize, row)); start += curSize; } } qSort(pies); for (int pieId = 0; pieId < pies.size(); ++pieId) { PieInfo &pie = pies[pieId]; if (pie.number == 0) painter.setBrush(QBrush("red")); else painter.setBrush(QBrush(colors[(pie.number - 1) % colors.size()])); DrawPie(painter, rect, shift, pie.astart, pie.astart + pie.alen); } } void PlotWidget::onTimer() { m_shift = ConstrainAngle(m_shift + 0.01); repaint(); }
#include "plotwidget.h" #include <QPainter> #include "mytablemodel.h" #include <QtMath> #include <QTimer> PlotWidget::PlotWidget(MyTableModel *table, QWidget *parent) :QWidget(parent) ,m_table(table) ,m_shift(0) ,m_angle(0.5) ,m_timer(new QTimer()) { connect(m_timer, SIGNAL(timeout()), this, SLOT(onTimer())); m_timer->start(1000.0 / 60); } PlotWidget::~PlotWidget() { m_timer->stop(); delete m_timer; } void PlotWidget::setAngle(int angle) { m_angle = 1.0 * angle / 100; } const QVector<QColor> colors = { "orange", "yellow", "green", "blue", "violet", "pink" }; double DegAngleToRadAngle(double deg) { return (deg / 180 * M_PI); } double RadAngleToDegAngle(double rad) { return (rad / M_PI * 180); } QPolygonF GenerateSidePolygon(QVector<QPointF> const& line, QPointF const& shift) { Q_ASSERT(!line.empty()); QPolygonF result; for (auto &point : line) result << point; for (int i = line.size() - 1; i >= 0; --i) result << line[i] + shift; return result; } QPointF GetEllipsePoint(QRectF const& rect, double angle) { return rect.center() + QPointF( rect.width() / 2 * cos(angle), rect.height() / 2 * sin(angle) ); } int RadAngleToPieAngle(double angle) { return RadAngleToDegAngle(angle) * 16; } void DrawPieHelper(QPainter &painter, QRectF const& rect, double astart, double aend) { double alen = aend - astart; painter.drawPie(rect, RadAngleToPieAngle(-aend), RadAngleToPieAngle(alen)); } double ConstrainAngle(double x) { x = fmod(x, 2 * M_PI); if (x < 0) x += 2 * M_PI; return x; } double SmallestAngleDifference(double a, double b) { double r = ConstrainAngle(a - b); if (r > M_PI) r -= 2 * M_PI; if (r < -M_PI) r += 2 * M_PI; return fabs(r); } void DrawPie(QPainter &painter, QRectF rect, QPointF const& shift, double astart, double aend) { QPointF cshift(GetEllipsePoint(rect, (astart + aend) / 2) - rect.center()); cshift *= 0.2; rect.setX(rect.x() + cshift.x()); rect.setY(rect.y() + cshift.y()); { double first, second; if (SmallestAngleDifference(astart, 3 * M_PI / 2) < SmallestAngleDifference(aend, 3 * M_PI / 2)) { first = astart; second = aend; } else { first = aend; second = astart; } painter.drawPolygon(GenerateSidePolygon( { rect.center(), GetEllipsePoint(rect, first) }, shift )); painter.drawPolygon(GenerateSidePolygon( { rect.center(), GetEllipsePoint(rect, second) }, shift )); } { QVector<QPointF> arc; for (double angle = astart; angle <= aend; angle += 0.01) { if (ConstrainAngle(angle) <= M_PI) arc.push_back(GetEllipsePoint(rect, angle)); } if (!arc.empty()) painter.drawPolygon(GenerateSidePolygon(arc, shift)); } DrawPieHelper(painter, rect, astart, aend); } struct PieInfo { double astart; double alen; int number; PieInfo() :astart(0) ,alen(0) ,number(0) {} PieInfo(double astart, double alen, int number) :astart(astart) ,alen(alen) ,number(number) {} double Key() const { return SmallestAngleDifference(astart + alen / 2, 3 * M_PI / 2); } bool operator<(PieInfo const& other) const { return Key() < other.Key(); } }; double LinearFunc(double k, double x, double b) { return k * x + b; } double HeightScaleFunc(double angle) { return LinearFunc(0.8 - 0.2, angle, 0.2); } double ThicknessScaleFunc(double angle) { return LinearFunc(0.02 - 0.1, angle, 0.1); } void PlotWidget::paintEvent(QPaintEvent *event) { QWidget::paintEvent(event); QPainter painter(this); painter.setRenderHints(painter.renderHints() | QPainter::Antialiasing); painter.drawRect(0, 0, size().width(), size().height()); const int HGAP = 50; double heightScale = HeightScaleFunc(m_angle); double thicknessScale = ThicknessScaleFunc(m_angle); double vgap = size().height() * (1 - heightScale) / 2; QRectF rect(HGAP, vgap, size().width() - 2 * HGAP, size().height() * heightScale); QPointF shift(0, size().height() * thicknessScale); int sum = 0; for (int row = 0; row < m_table->getSize(); ++row) sum += m_table->getNumber(row); if (sum == 0) return; QVector<PieInfo> pies; { double start = 0; for (int row = 0; row < m_table->getSize(); ++row) { double curSize = 2 * M_PI * m_table->getNumber(row) / sum; pies.push_back(PieInfo(start + m_shift, curSize, row)); start += curSize; } } qSort(pies); for (int pieId = 0; pieId < pies.size(); ++pieId) { PieInfo &pie = pies[pieId]; if (pie.number == 0) painter.setBrush(QBrush("red")); else painter.setBrush(QBrush(colors[(pie.number - 1) % colors.size()])); DrawPie(painter, rect, shift, pie.astart, pie.astart + pie.alen); } } void PlotWidget::onTimer() { m_shift = ConstrainAngle(m_shift + 0.01); repaint(); }
Add spaces between pies
Add spaces between pies
C++
mit
bogdanov-d-a/TableEditor
98e31a2daa8392516f1a9125dfcf8df22ade3f7c
JPetTaskLoader/JPetTaskLoader.cpp
JPetTaskLoader/JPetTaskLoader.cpp
/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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 JPetTaskLoader.cpp * @brief Class loads user task and execute in a loop of events */ #include "JPetTaskLoader.h" #include <iostream> #include "../JPetTask/JPetTask.h" //ClassImp(JPetTaskLoader); #include <boost/filesystem.hpp> JPetTaskLoader::JPetTaskLoader(const char* in_file_type, const char* out_file_type, JPetTask* taskToExecute): JPetTaskIO(), fInFileType(in_file_type), fOutFileType(out_file_type) { addSubTask(taskToExecute); } void JPetTaskLoader::init(const JPetOptions::Options& opts) { auto newOpts(opts); auto inFile = newOpts.at("inputFile"); auto outFile = inFile; inFile = generateProperNameFile(inFile, fInFileType); outFile = generateProperNameFile(outFile, fOutFileType); newOpts.at("inputFile") = inFile; newOpts.at("inputFileType") = fInFileType; newOpts.at("outputFile") = outFile; newOpts.at("outputFileType") = fOutFileType; setOptions(JPetOptions(newOpts)); //here we should call some function to parse options auto inputFilename = fOptions.getInputFile(); auto outputFilename = fOptions.getOutputFile(); createInputObjects(inputFilename); createOutputObjects(outputFilename); } std::string JPetTaskLoader::generateProperNameFile(const std::string& srcFilename, const std::string& fileType) const { auto baseFileName = getBaseFilePath(srcFilename); return baseFileName + "." + fileType + ".root"; } std::string JPetTaskLoader::getBaseFilePath(const std::string& srcName) const { boost::filesystem::path p(srcName); // the file name and path are treated separately not to strip dots from the path std::string name = p.filename().native(); boost::filesystem::path dir = p.parent_path().native(); //strip the "extension" starting from the first dot in the file name auto pos = name.find("."); if ( pos != std::string::npos ) { name.erase( pos ); } boost::filesystem::path bare_name(name); return (dir / bare_name).native(); } JPetTaskLoader::~JPetTaskLoader() { }
/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * 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 JPetTaskLoader.cpp * @brief Class loads user task and execute in a loop of events */ #include "JPetTaskLoader.h" #include <iostream> #include "../JPetTask/JPetTask.h" //ClassImp(JPetTaskLoader); #include <boost/filesystem.hpp> JPetTaskLoader::JPetTaskLoader(const char* in_file_type, const char* out_file_type, JPetTask* taskToExecute): JPetTaskIO(), fInFileType(in_file_type), fOutFileType(out_file_type) { addSubTask(taskToExecute); } void JPetTaskLoader::init(const JPetOptions::Options& opts) { auto newOpts(opts); auto inFile = newOpts.at("inputFile"); auto outFile = inFile; inFile = generateProperNameFile(inFile, fInFileType); outFile = generateProperNameFile(outFile, fOutFileType); newOpts.at("inputFile") = inFile; newOpts.at("inputFileType") = fInFileType; newOpts.at("outputFile") = outFile; newOpts.at("outputFileType") = fOutFileType; setOptions(JPetOptions(newOpts)); //here we should call some function to parse options auto inputFilename = fOptions.getInputFile(); auto outputFilename = fOptions.getOutputFile(); createInputObjects(inputFilename); createOutputObjects(outputFilename); } std::string JPetTaskLoader::generateProperNameFile(const std::string& srcFilename, const std::string& fileType) const { auto baseFileName = getBaseFilePath(srcFilename); return baseFileName + "." + fileType + ".root"; } std::string JPetTaskLoader::getBaseFilePath(const std::string& srcName) const { boost::filesystem::path p(srcName); // the file name and path are treated separately not to strip dots from the path std::string name = p.filename().native(); boost::filesystem::path dir = p.parent_path().native(); //strip the "extension" starting from the first dot in the file name auto pos = name.find("."); if ( pos != std::string::npos ) { name.erase( pos ); } boost::filesystem::path bare_name(name); return (dir / bare_name).native(); } JPetTaskLoader::~JPetTaskLoader() { }
Remove cout call from JPetTaskLoader
Remove cout call from JPetTaskLoader Former-commit-id: fcdb31bd03555d9b2832e164e91da0c4f1a9bd7b
C++
apache-2.0
kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework,kmuzalewska/j-pet-framework
e81c832146d24a21428eb30570d4fb536b25476c
windows/src/SearchResultPoi/View/SearchResultPoiView.cpp
windows/src/SearchResultPoi/View/SearchResultPoiView.cpp
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchResultPoiController.h" #include "SearchResultPoiView.h" #include "WindowsAppThreadAssertionMacros.h" #include "SearchResultModelCLI.h" #include "ReflectionHelpers.h" using namespace ExampleApp::Helpers::ReflectionHelpers; using namespace System; using namespace System::Reflection; namespace ExampleApp { namespace SearchResultPoi { namespace View { namespace { const std::string VendorViewClassNames[] = { "ExampleAppWPF.YelpSearchResultsPoiView", "ExampleAppWPF.eeGeoSearchResultsPoiView", "ExampleAppWPF.GeoNamesSearchResultsPoiView" }; } SearchResultPoiView::SearchResultPoiView(WindowsNativeState& nativeState) : m_nativeState(nativeState) , m_currentVendor(-1) { for (int i = 0; i < SearchVendors::Num; ++i) { m_uiViewClass[i] = GetTypeFromEntryAssembly(Helpers::ReflectionHelpers::ConvertUTF8ToManagedString(VendorViewClassNames[i])); ConstructorInfo^ ctor = m_uiViewClass[i]->GetConstructor(CreateTypes(IntPtr::typeid)); m_uiView[i] = ctor->Invoke(CreateObjects(gcnew IntPtr(this))); DisplayPoiInfo[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "DisplayPoiInfo"); DismissPoiInfo[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "DismissPoiInfo"); UpdateImageData[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "UpdateImageData"); } } SearchResultPoiView::~SearchResultPoiView() { } void SearchResultPoiView::Show(const Search::SdkModel::SearchResultModel& model, bool isPinned) { m_model = model; CreateVendorSpecificPoiView(m_model.GetVendor()); DisplayPoiInfo[m_currentVendor](gcnew SearchResultModelCLI(m_model), isPinned); } void SearchResultPoiView::Hide() { DismissPoiInfo[m_currentVendor](); } void SearchResultPoiView::UpdateImage(const std::string& url, bool hasImage, const std::vector<unsigned char>* pImageBytes) { array<System::Byte>^ imageDataArray = gcnew array<System::Byte>(static_cast<int>(pImageBytes->size())); for (size_t i = 0; i < pImageBytes->size(); ++i) { imageDataArray[static_cast<int>(i)] = System::Byte(pImageBytes->at(i)); } UpdateImageData[m_currentVendor](gcnew System::String(url.c_str()), hasImage, imageDataArray); } void SearchResultPoiView::InsertClosedCallback(Eegeo::Helpers::ICallback0& callback) { m_closedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveClosedCallback(Eegeo::Helpers::ICallback0& callback) { ASSERT_UI_THREAD m_closedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandleCloseClicked() { m_closedCallbacks.ExecuteCallbacks(); } void SearchResultPoiView::InsertTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandlePinToggleClicked() { ASSERT_UI_THREAD m_togglePinClickedCallbacks.ExecuteCallbacks(m_model); } void SearchResultPoiView::CreateVendorSpecificPoiView(const std::string& vendor) { ASSERT_UI_THREAD std::string viewClassName = ""; if(vendor == "Yelp") { m_currentVendor = SearchVendors::Yelp; } else if(vendor == "GeoNames") { m_currentVendor = SearchVendors::GeoNames; } else if (vendor == "eeGeo") { m_currentVendor = SearchVendors::eeGeo; } else { Eegeo_ASSERT(false, "Unknown POI vendor %s, cannot create view instance.\n", vendor.c_str()); } } } } }
// Copyright eeGeo Ltd (2012-2015), All Rights Reserved #include "SearchResultPoiController.h" #include "SearchResultPoiView.h" #include "WindowsAppThreadAssertionMacros.h" #include "SearchResultModelCLI.h" #include "ReflectionHelpers.h" #include "SearchVendorNames.h" using namespace ExampleApp::Helpers::ReflectionHelpers; using namespace System; using namespace System::Reflection; namespace ExampleApp { namespace SearchResultPoi { namespace View { namespace { const std::string VendorViewClassNames[] = { "ExampleAppWPF.YelpSearchResultsPoiView", "ExampleAppWPF.eeGeoSearchResultsPoiView", "ExampleAppWPF.GeoNamesSearchResultsPoiView" }; } SearchResultPoiView::SearchResultPoiView(WindowsNativeState& nativeState) : m_nativeState(nativeState) , m_currentVendor(-1) { for (int i = 0; i < SearchVendors::Num; ++i) { m_uiViewClass[i] = GetTypeFromEntryAssembly(Helpers::ReflectionHelpers::ConvertUTF8ToManagedString(VendorViewClassNames[i])); ConstructorInfo^ ctor = m_uiViewClass[i]->GetConstructor(CreateTypes(IntPtr::typeid)); m_uiView[i] = ctor->Invoke(CreateObjects(gcnew IntPtr(this))); DisplayPoiInfo[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "DisplayPoiInfo"); DismissPoiInfo[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "DismissPoiInfo"); UpdateImageData[i].SetupMethod(m_uiViewClass[i], m_uiView[i], "UpdateImageData"); } } SearchResultPoiView::~SearchResultPoiView() { } void SearchResultPoiView::Show(const Search::SdkModel::SearchResultModel& model, bool isPinned) { m_model = model; CreateVendorSpecificPoiView(m_model.GetVendor()); DisplayPoiInfo[m_currentVendor](gcnew SearchResultModelCLI(m_model), isPinned); } void SearchResultPoiView::Hide() { DismissPoiInfo[m_currentVendor](); } void SearchResultPoiView::UpdateImage(const std::string& url, bool hasImage, const std::vector<unsigned char>* pImageBytes) { array<System::Byte>^ imageDataArray = gcnew array<System::Byte>(static_cast<int>(pImageBytes->size())); for (size_t i = 0; i < pImageBytes->size(); ++i) { imageDataArray[static_cast<int>(i)] = System::Byte(pImageBytes->at(i)); } UpdateImageData[m_currentVendor](gcnew System::String(url.c_str()), hasImage, imageDataArray); } void SearchResultPoiView::InsertClosedCallback(Eegeo::Helpers::ICallback0& callback) { m_closedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveClosedCallback(Eegeo::Helpers::ICallback0& callback) { ASSERT_UI_THREAD m_closedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandleCloseClicked() { m_closedCallbacks.ExecuteCallbacks(); } void SearchResultPoiView::InsertTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.AddCallback(callback); } void SearchResultPoiView::RemoveTogglePinnedCallback(Eegeo::Helpers::ICallback1<Search::SdkModel::SearchResultModel>& callback) { ASSERT_UI_THREAD m_togglePinClickedCallbacks.RemoveCallback(callback); } void SearchResultPoiView::HandlePinToggleClicked() { ASSERT_UI_THREAD m_togglePinClickedCallbacks.ExecuteCallbacks(m_model); } void SearchResultPoiView::CreateVendorSpecificPoiView(const std::string& vendor) { ASSERT_UI_THREAD if(vendor == Search::YelpVendorName) { m_currentVendor = SearchVendors::Yelp; } else if(vendor == Search::GeoNamesVendorName) { m_currentVendor = SearchVendors::GeoNames; } else if (vendor == Search::EegeoVendorName) { m_currentVendor = SearchVendors::eeGeo; } else if (vendor == Search::ExampleTourVendorName) { Eegeo_ASSERT(false, "Unable to creaate view instance for %s. Tour views are not yet implemented on Windows - please refer to iOS example.\n", vendor.c_str()); m_currentVendor = -1; } else { Eegeo_ASSERT(false, "Unknown POI vendor %s, cannot create view instance.\n", vendor.c_str()); m_currentVendor = -1; } } } } }
add additional assert for Tours views creation on Windows - not yet implemented. Buddy: Vimmy
add additional assert for Tours views creation on Windows - not yet implemented. Buddy: Vimmy
C++
bsd-2-clause
eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app
698e8a7ff6315b2bb885f58cbbd0e7eb9e01c4ca
dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp
dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.cpp
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/integration-api/gl-abstraction.h> #ifdef ECORE_WAYLAND2 #include <Ecore_Wl2.h> #else #include <Ecore_Wayland.h> #endif #include <tbm_bufmgr.h> #include <tbm_surface_internal.h> // INTERNAL INCLUDES #include <dali/integration-api/adaptor-framework/thread-synchronization-interface.h> #include <dali/internal/adaptor/common/adaptor-impl.h> #include <dali/internal/adaptor/common/adaptor-internal-services.h> #include <dali/internal/graphics/gles/egl-graphics.h> #include <dali/internal/graphics/gles/egl-implementation.h> #include <dali/internal/system/common/trigger-event.h> #include <dali/internal/window-system/common/display-connection.h> #include <dali/internal/window-system/common/window-system.h> namespace Dali { namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gNativeSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_NATIVE_RENDER_SURFACE"); #endif } // unnamed namespace NativeRenderSurfaceEcoreWl::NativeRenderSurfaceEcoreWl(SurfaceSize surfaceSize, Any surface, bool isTransparent) : mRenderNotification(NULL), mGraphics(NULL), mEGL(nullptr), mEGLSurface(nullptr), mEGLContext(nullptr), mOwnSurface(false), mDrawableCompleted(false), mTbmQueue(NULL), mConsumeSurface(NULL), mThreadSynchronization(NULL) { Dali::Internal::Adaptor::WindowSystem::Initialize(); if(surface.Empty()) { mSurfaceSize = surfaceSize; mColorDepth = isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24; mTbmFormat = isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888; CreateNativeRenderable(); } else { mTbmQueue = AnyCast<tbm_surface_queue_h>(surface); uint16_t width = static_cast<uint16_t>(tbm_surface_queue_get_width(mTbmQueue)); uint16_t height = static_cast<uint16_t>(tbm_surface_queue_get_height(mTbmQueue)); mSurfaceSize = SurfaceSize(width, height); mTbmFormat = tbm_surface_queue_get_format(mTbmQueue); mColorDepth = (mTbmFormat == TBM_FORMAT_ARGB8888) ? COLOR_DEPTH_32 : COLOR_DEPTH_24; } } NativeRenderSurfaceEcoreWl::~NativeRenderSurfaceEcoreWl() { if(mEGLSurface) { DestroySurface(); } // release the surface if we own one if(mOwnSurface) { ReleaseDrawable(); if(mTbmQueue) { tbm_surface_queue_destroy(mTbmQueue); } DALI_LOG_INFO(gNativeSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n"); } Dali::Internal::Adaptor::WindowSystem::Shutdown(); } Any NativeRenderSurfaceEcoreWl::GetDrawable() { return mConsumeSurface; } void NativeRenderSurfaceEcoreWl::SetRenderNotification(TriggerEventInterface* renderNotification) { mRenderNotification = renderNotification; } void NativeRenderSurfaceEcoreWl::WaitUntilSurfaceReplaced() { ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); while(!mDrawableCompleted) { mTbmSurfaceCondition.Wait(lock); } mDrawableCompleted = false; } Any NativeRenderSurfaceEcoreWl::GetNativeRenderable() { return mTbmQueue; } PositionSize NativeRenderSurfaceEcoreWl::GetPositionSize() const { return PositionSize(0, 0, static_cast<int>(mSurfaceSize.GetWidth()), static_cast<int>(mSurfaceSize.GetHeight())); } void NativeRenderSurfaceEcoreWl::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; // 1 inch = 25.4 millimeters #ifdef ECORE_WAYLAND2 // TODO: Application should set dpi value in wayland2 xres = 96; yres = 96; #else xres = ecore_wl_dpi_get(); yres = ecore_wl_dpi_get(); #endif dpiHorizontal = int(xres + 0.5f); // rounding dpiVertical = int(yres + 0.5f); } int NativeRenderSurfaceEcoreWl::GetOrientation() const { return 0; } void NativeRenderSurfaceEcoreWl::InitializeGraphics() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); mGraphics = &mAdaptor->GetGraphicsInterface(); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); mEGL = &eglGraphics->GetEglInterface(); if(mEGLContext == NULL) { // Create the OpenGL context for this window Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>(*mEGL); eglImpl.CreateWindowContext(mEGLContext); // Create the OpenGL surface CreateSurface(); } } void NativeRenderSurfaceEcoreWl::CreateSurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); mEGLSurface = eglImpl.CreateSurfaceWindow(reinterpret_cast<EGLNativeWindowType>(mTbmQueue), mColorDepth); } void NativeRenderSurfaceEcoreWl::DestroySurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); eglImpl.DestroySurface(mEGLSurface); } bool NativeRenderSurfaceEcoreWl::ReplaceGraphicsSurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); if(!mTbmQueue) { return false; } auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); return eglImpl.ReplaceSurfaceWindow(reinterpret_cast<EGLNativeWindowType>(mTbmQueue), mEGLSurface, mEGLContext); } void NativeRenderSurfaceEcoreWl::MoveResize(Dali::PositionSize positionSize) { tbm_surface_queue_error_e error = TBM_SURFACE_QUEUE_ERROR_NONE; error = tbm_surface_queue_reset(mTbmQueue, positionSize.width, positionSize.height, mTbmFormat); if(error != TBM_SURFACE_QUEUE_ERROR_NONE) { DALI_LOG_ERROR("Failed to resize tbm_surface_queue"); } mSurfaceSize.SetWidth(static_cast<uint16_t>(positionSize.width)); mSurfaceSize.SetHeight(static_cast<uint16_t>(positionSize.height)); } void NativeRenderSurfaceEcoreWl::StartRender() { } bool NativeRenderSurfaceEcoreWl::PreRender(bool resizingSurface, const std::vector<Rect<int>>& damagedRects, Rect<int>& clippingRect) { //TODO: Need to support partial update return true; } void NativeRenderSurfaceEcoreWl::PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector<Rect<int>>& damagedRects) { auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); if(eglGraphics) { Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); eglImpl.SwapBuffers(mEGLSurface, damagedRects); } //TODO: Move calling tbm_surface_queue_acruie to OffscreenWindow and Scene in EvasPlugin if(mOwnSurface) { if(mThreadSynchronization) { mThreadSynchronization->PostRenderStarted(); } if(tbm_surface_queue_can_acquire(mTbmQueue, 1)) { if(tbm_surface_queue_acquire(mTbmQueue, &mConsumeSurface) != TBM_SURFACE_QUEUE_ERROR_NONE) { DALI_LOG_ERROR("Failed to acquire a tbm_surface\n"); return; } } if(mConsumeSurface) { tbm_surface_internal_ref(mConsumeSurface); } if(replacingSurface) { ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); mDrawableCompleted = true; mTbmSurfaceCondition.Notify(lock); } // create damage for client applications which wish to know the update timing if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface mRenderNotification->Trigger(); } if(mThreadSynchronization) { // wait until the event-thread completed to use the tbm_surface mThreadSynchronization->PostRenderWaitForCompletion(); } // release the consumed surface after post render was completed ReleaseDrawable(); } else { // create damage for client applications which wish to know the update timing if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface mRenderNotification->Trigger(); } } } void NativeRenderSurfaceEcoreWl::StopRender() { ReleaseLock(); } void NativeRenderSurfaceEcoreWl::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) { mThreadSynchronization = &threadSynchronization; } Dali::RenderSurfaceInterface::Type NativeRenderSurfaceEcoreWl::GetSurfaceType() { return Dali::RenderSurfaceInterface::NATIVE_RENDER_SURFACE; } void NativeRenderSurfaceEcoreWl::MakeContextCurrent() { if(mEGL != nullptr) { mEGL->MakeContextCurrent(mEGLSurface, mEGLContext); } } Integration::DepthBufferAvailable NativeRenderSurfaceEcoreWl::GetDepthBufferRequired() { return mGraphics ? mGraphics->GetDepthBufferRequired() : Integration::DepthBufferAvailable::FALSE; } Integration::StencilBufferAvailable NativeRenderSurfaceEcoreWl::GetStencilBufferRequired() { return mGraphics ? mGraphics->GetStencilBufferRequired() : Integration::StencilBufferAvailable::FALSE; } void NativeRenderSurfaceEcoreWl::ReleaseLock() { if(mThreadSynchronization) { mThreadSynchronization->PostRenderComplete(); } } void NativeRenderSurfaceEcoreWl::CreateNativeRenderable() { int width = static_cast<int>(mSurfaceSize.GetWidth()); int height = static_cast<int>(mSurfaceSize.GetHeight()); // check we're creating one with a valid size DALI_ASSERT_ALWAYS(width > 0 && height > 0 && "tbm_surface size is invalid"); mTbmQueue = tbm_surface_queue_create(3, width, height, mTbmFormat, TBM_BO_DEFAULT); if(mTbmQueue) { mOwnSurface = true; } else { mOwnSurface = false; } } void NativeRenderSurfaceEcoreWl::ReleaseDrawable() { if(mConsumeSurface) { tbm_surface_internal_unref(mConsumeSurface); if(tbm_surface_internal_is_valid(mConsumeSurface)) { tbm_surface_queue_release(mTbmQueue, mConsumeSurface); } mConsumeSurface = NULL; } } } // namespace Dali
/* * Copyright (c) 2021 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include <dali/internal/window-system/tizen-wayland/native-render-surface-ecore-wl.h> // EXTERNAL INCLUDES #include <dali/integration-api/debug.h> #include <dali/integration-api/gl-abstraction.h> #ifdef ECORE_WAYLAND2 #include <Ecore_Wl2.h> #else #include <Ecore_Wayland.h> #endif #include <tbm_bufmgr.h> #include <tbm_surface_internal.h> // INTERNAL INCLUDES #include <dali/integration-api/adaptor-framework/thread-synchronization-interface.h> #include <dali/internal/adaptor/common/adaptor-impl.h> #include <dali/internal/adaptor/common/adaptor-internal-services.h> #include <dali/internal/graphics/gles/egl-graphics.h> #include <dali/internal/graphics/gles/egl-implementation.h> #include <dali/internal/system/common/trigger-event.h> #include <dali/internal/window-system/common/display-connection.h> #include <dali/internal/window-system/common/window-system.h> namespace Dali { namespace { #if defined(DEBUG_ENABLED) Debug::Filter* gNativeSurfaceLogFilter = Debug::Filter::New(Debug::Verbose, false, "LOG_NATIVE_RENDER_SURFACE"); #endif } // unnamed namespace NativeRenderSurfaceEcoreWl::NativeRenderSurfaceEcoreWl(SurfaceSize surfaceSize, Any surface, bool isTransparent) : mRenderNotification(NULL), mGraphics(NULL), mEGL(nullptr), mEGLSurface(nullptr), mEGLContext(nullptr), mOwnSurface(false), mDrawableCompleted(false), mTbmQueue(NULL), mConsumeSurface(NULL), mThreadSynchronization(NULL) { Dali::Internal::Adaptor::WindowSystem::Initialize(); if(surface.Empty()) { mSurfaceSize = surfaceSize; mColorDepth = isTransparent ? COLOR_DEPTH_32 : COLOR_DEPTH_24; mTbmFormat = isTransparent ? TBM_FORMAT_ARGB8888 : TBM_FORMAT_RGB888; CreateNativeRenderable(); } else { mTbmQueue = AnyCast<tbm_surface_queue_h>(surface); uint16_t width = static_cast<uint16_t>(tbm_surface_queue_get_width(mTbmQueue)); uint16_t height = static_cast<uint16_t>(tbm_surface_queue_get_height(mTbmQueue)); mSurfaceSize = SurfaceSize(width, height); mTbmFormat = tbm_surface_queue_get_format(mTbmQueue); mColorDepth = (mTbmFormat == TBM_FORMAT_ARGB8888) ? COLOR_DEPTH_32 : COLOR_DEPTH_24; } } NativeRenderSurfaceEcoreWl::~NativeRenderSurfaceEcoreWl() { if(mEGLSurface) { DestroySurface(); } // release the surface if we own one if(mOwnSurface) { ReleaseDrawable(); if(mTbmQueue) { tbm_surface_queue_destroy(mTbmQueue); } DALI_LOG_INFO(gNativeSurfaceLogFilter, Debug::General, "Own tbm surface queue destroy\n"); } Dali::Internal::Adaptor::WindowSystem::Shutdown(); } Any NativeRenderSurfaceEcoreWl::GetDrawable() { return mConsumeSurface; } void NativeRenderSurfaceEcoreWl::SetRenderNotification(TriggerEventInterface* renderNotification) { mRenderNotification = renderNotification; } void NativeRenderSurfaceEcoreWl::WaitUntilSurfaceReplaced() { ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); while(!mDrawableCompleted) { mTbmSurfaceCondition.Wait(lock); } mDrawableCompleted = false; } Any NativeRenderSurfaceEcoreWl::GetNativeRenderable() { return mTbmQueue; } PositionSize NativeRenderSurfaceEcoreWl::GetPositionSize() const { return PositionSize(0, 0, static_cast<int>(mSurfaceSize.GetWidth()), static_cast<int>(mSurfaceSize.GetHeight())); } void NativeRenderSurfaceEcoreWl::GetDpi(unsigned int& dpiHorizontal, unsigned int& dpiVertical) { // calculate DPI float xres, yres; // 1 inch = 25.4 millimeters #ifdef ECORE_WAYLAND2 // TODO: Application should set dpi value in wayland2 xres = 96; yres = 96; #else xres = ecore_wl_dpi_get(); yres = ecore_wl_dpi_get(); #endif dpiHorizontal = int(xres + 0.5f); // rounding dpiVertical = int(yres + 0.5f); } int NativeRenderSurfaceEcoreWl::GetOrientation() const { return 0; } void NativeRenderSurfaceEcoreWl::InitializeGraphics() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); mGraphics = &mAdaptor->GetGraphicsInterface(); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); mEGL = &eglGraphics->GetEglInterface(); if(mEGLContext == NULL) { // Create the OpenGL context for this window Internal::Adaptor::EglImplementation& eglImpl = static_cast<Internal::Adaptor::EglImplementation&>(*mEGL); eglImpl.CreateWindowContext(mEGLContext); // Create the OpenGL surface CreateSurface(); } } void NativeRenderSurfaceEcoreWl::CreateSurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); mEGLSurface = eglImpl.CreateSurfaceWindow(reinterpret_cast<EGLNativeWindowType>(mTbmQueue), mColorDepth); } void NativeRenderSurfaceEcoreWl::DestroySurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); eglImpl.DestroySurface(mEGLSurface); } bool NativeRenderSurfaceEcoreWl::ReplaceGraphicsSurface() { DALI_LOG_TRACE_METHOD(gNativeSurfaceLogFilter); if(!mTbmQueue) { return false; } auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); return eglImpl.ReplaceSurfaceWindow(reinterpret_cast<EGLNativeWindowType>(mTbmQueue), mEGLSurface, mEGLContext); } void NativeRenderSurfaceEcoreWl::MoveResize(Dali::PositionSize positionSize) { tbm_surface_queue_error_e error = TBM_SURFACE_QUEUE_ERROR_NONE; error = tbm_surface_queue_reset(mTbmQueue, positionSize.width, positionSize.height, mTbmFormat); if(error != TBM_SURFACE_QUEUE_ERROR_NONE) { DALI_LOG_ERROR("Failed to resize tbm_surface_queue"); } mSurfaceSize.SetWidth(static_cast<uint16_t>(positionSize.width)); mSurfaceSize.SetHeight(static_cast<uint16_t>(positionSize.height)); } void NativeRenderSurfaceEcoreWl::StartRender() { } bool NativeRenderSurfaceEcoreWl::PreRender(bool resizingSurface, const std::vector<Rect<int>>& damagedRects, Rect<int>& clippingRect) { //TODO: Need to support partial update MakeContextCurrent(); return true; } void NativeRenderSurfaceEcoreWl::PostRender(bool renderToFbo, bool replacingSurface, bool resizingSurface, const std::vector<Rect<int>>& damagedRects) { auto eglGraphics = static_cast<Internal::Adaptor::EglGraphics*>(mGraphics); if(eglGraphics) { Internal::Adaptor::EglImplementation& eglImpl = eglGraphics->GetEglImplementation(); eglImpl.SwapBuffers(mEGLSurface, damagedRects); } //TODO: Move calling tbm_surface_queue_acruie to OffscreenWindow and Scene in EvasPlugin if(mOwnSurface) { if(mThreadSynchronization) { mThreadSynchronization->PostRenderStarted(); } if(tbm_surface_queue_can_acquire(mTbmQueue, 1)) { if(tbm_surface_queue_acquire(mTbmQueue, &mConsumeSurface) != TBM_SURFACE_QUEUE_ERROR_NONE) { DALI_LOG_ERROR("Failed to acquire a tbm_surface\n"); return; } } if(mConsumeSurface) { tbm_surface_internal_ref(mConsumeSurface); } if(replacingSurface) { ConditionalWait::ScopedLock lock(mTbmSurfaceCondition); mDrawableCompleted = true; mTbmSurfaceCondition.Notify(lock); } // create damage for client applications which wish to know the update timing if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface mRenderNotification->Trigger(); } if(mThreadSynchronization) { // wait until the event-thread completed to use the tbm_surface mThreadSynchronization->PostRenderWaitForCompletion(); } // release the consumed surface after post render was completed ReleaseDrawable(); } else { // create damage for client applications which wish to know the update timing if(!replacingSurface && mRenderNotification) { // use notification trigger // Tell the event-thread to render the tbm_surface mRenderNotification->Trigger(); } } } void NativeRenderSurfaceEcoreWl::StopRender() { ReleaseLock(); } void NativeRenderSurfaceEcoreWl::SetThreadSynchronization(ThreadSynchronizationInterface& threadSynchronization) { mThreadSynchronization = &threadSynchronization; } Dali::RenderSurfaceInterface::Type NativeRenderSurfaceEcoreWl::GetSurfaceType() { return Dali::RenderSurfaceInterface::NATIVE_RENDER_SURFACE; } void NativeRenderSurfaceEcoreWl::MakeContextCurrent() { if(mEGL != nullptr) { mEGL->MakeContextCurrent(mEGLSurface, mEGLContext); } } Integration::DepthBufferAvailable NativeRenderSurfaceEcoreWl::GetDepthBufferRequired() { return mGraphics ? mGraphics->GetDepthBufferRequired() : Integration::DepthBufferAvailable::FALSE; } Integration::StencilBufferAvailable NativeRenderSurfaceEcoreWl::GetStencilBufferRequired() { return mGraphics ? mGraphics->GetStencilBufferRequired() : Integration::StencilBufferAvailable::FALSE; } void NativeRenderSurfaceEcoreWl::ReleaseLock() { if(mThreadSynchronization) { mThreadSynchronization->PostRenderComplete(); } } void NativeRenderSurfaceEcoreWl::CreateNativeRenderable() { int width = static_cast<int>(mSurfaceSize.GetWidth()); int height = static_cast<int>(mSurfaceSize.GetHeight()); // check we're creating one with a valid size DALI_ASSERT_ALWAYS(width > 0 && height > 0 && "tbm_surface size is invalid"); mTbmQueue = tbm_surface_queue_create(3, width, height, mTbmFormat, TBM_BO_DEFAULT); if(mTbmQueue) { mOwnSurface = true; } else { mOwnSurface = false; } } void NativeRenderSurfaceEcoreWl::ReleaseDrawable() { if(mConsumeSurface) { tbm_surface_internal_unref(mConsumeSurface); if(tbm_surface_internal_is_valid(mConsumeSurface)) { tbm_surface_queue_release(mTbmQueue, mConsumeSurface); } mConsumeSurface = NULL; } } } // namespace Dali
Call MakeContextCurrent in PreRender
Call MakeContextCurrent in PreRender When creating multiple NativeRenderSurface, Dali didn't render from second RenderSurface. Change-Id: I536e831bfbd6d2e5a2a1cb7e31ec5a505c91ca22
C++
apache-2.0
dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor,dalihub/dali-adaptor
9d3ab9719cdabea9e2f8a577c683d9d35bfe0686
chrome/browser/extensions/extension_startup_browsertest.cc
chrome/browser/extensions/extension_startup_browsertest.cc
// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, Test) { WaitForServicesToStart(1, false); TestInjection(true, true); }
// Copyright (c) 2008 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 <vector> #include "base/command_line.h" #include "base/file_path.h" #include "base/file_util.h" #include "base/path_service.h" #include "chrome/browser/browser.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/user_script_master.h" #include "chrome/browser/profile.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/notification_details.h" #include "chrome/common/notification_observer.h" #include "chrome/common/notification_registrar.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "chrome/test/in_process_browser_test.h" #include "chrome/test/ui_test_utils.h" #include "net/base/net_util.h" // This file contains high-level startup tests for the extensions system. We've // had many silly bugs where command line flags did not get propagated correctly // into the services, so we didn't start correctly. class ExtensionStartupTestBase : public InProcessBrowserTest { public: ExtensionStartupTestBase() : enable_extensions_(false) { } protected: // InProcessBrowserTest virtual void SetUpCommandLine(CommandLine* command_line) { EnableDOMAutomation(); FilePath profile_dir; PathService::Get(chrome::DIR_USER_DATA, &profile_dir); profile_dir = profile_dir.AppendASCII("Default"); file_util::CreateDirectory(profile_dir); preferences_file_ = profile_dir.AppendASCII("Preferences"); user_scripts_dir_ = profile_dir.AppendASCII("User Scripts"); extensions_dir_ = profile_dir.AppendASCII("Extensions"); if (enable_extensions_) { FilePath src_dir; PathService::Get(chrome::DIR_TEST_DATA, &src_dir); src_dir = src_dir.AppendASCII("extensions").AppendASCII("good"); file_util::CopyFile(src_dir.AppendASCII("Preferences"), preferences_file_); file_util::CopyDirectory(src_dir.AppendASCII("Extensions"), profile_dir, true); // recursive } else { command_line->AppendSwitch(switches::kDisableExtensions); } if (!load_extension_.value().empty()) { command_line->AppendSwitchWithValue(switches::kLoadExtension, load_extension_.ToWStringHack()); } } virtual void TearDown() { EXPECT_TRUE(file_util::Delete(preferences_file_, false)); // TODO(phajdan.jr): Check return values of the functions below, carefully. file_util::Delete(user_scripts_dir_, true); file_util::Delete(extensions_dir_, true); } void WaitForServicesToStart(int num_expected_extensions, bool expect_extensions_enabled) { ExtensionsService* service = browser()->profile()->GetExtensionsService(); if (!service->is_ready()) ui_test_utils::WaitForNotification(NotificationType::EXTENSIONS_READY); ASSERT_TRUE(service->is_ready()); ASSERT_EQ(static_cast<uint32>(num_expected_extensions), service->extensions()->size()); ASSERT_EQ(expect_extensions_enabled, service->extensions_enabled()); UserScriptMaster* master = browser()->profile()->GetUserScriptMaster(); if (!master->ScriptsReady()) { ui_test_utils::WaitForNotification( NotificationType::USER_SCRIPTS_UPDATED); } ASSERT_TRUE(master->ScriptsReady()); } void TestInjection(bool expect_css, bool expect_script) { // Load a page affected by the content script and test to see the effect. FilePath test_file; PathService::Get(chrome::DIR_TEST_DATA, &test_file); test_file = test_file.AppendASCII("extensions") .AppendASCII("test_file.html"); ui_test_utils::NavigateToURL(browser(), net::FilePathToFileURL(test_file)); bool result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(" L"document.defaultView.getComputedStyle(document.body, null)." L"getPropertyValue('background-color') == 'rgb(245, 245, 220)')", &result); EXPECT_EQ(expect_css, result); result = false; ui_test_utils::ExecuteJavaScriptAndExtractBool( browser()->GetSelectedTabContents()->render_view_host(), L"", L"window.domAutomationController.send(document.title == 'Modified')", &result); EXPECT_EQ(expect_script, result); } FilePath preferences_file_; FilePath extensions_dir_; FilePath user_scripts_dir_; bool enable_extensions_; FilePath load_extension_; }; // ExtensionsStartupTest // Ensures that we can startup the browser with --enable-extensions and some // extensions installed and see them run and do basic things. class ExtensionsStartupTest : public ExtensionStartupTestBase { public: ExtensionsStartupTest() { enable_extensions_ = true; } }; IN_PROC_BROWSER_TEST_F(ExtensionsStartupTest, MAYBE_Test) { WaitForServicesToStart(4, true); // 1 component extension and 3 others. TestInjection(true, true); } // ExtensionsLoadTest // Ensures that we can startup the browser with --load-extension and see them // run. class ExtensionsLoadTest : public ExtensionStartupTestBase { public: ExtensionsLoadTest() { PathService::Get(chrome::DIR_TEST_DATA, &load_extension_); load_extension_ = load_extension_ .AppendASCII("extensions") .AppendASCII("good") .AppendASCII("Extensions") .AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj") .AppendASCII("1.0.0.0"); } }; // Flaky (times out) on Mac/Windows. http://crbug.com/46301. #if defined(OS_MAC) || defined(OS_WIN) #define MAYBE_Test FLAKY_Test #else #define MAYBE_Test Test #endif IN_PROC_BROWSER_TEST_F(ExtensionsLoadTest, MAYBE_Test) { WaitForServicesToStart(1, false); TestInjection(true, true); }
Mark ExtensionsLoadTest.Test as flaky on Win/Mac
Mark ExtensionsLoadTest.Test as flaky on Win/Mac BUG=46301 TEST=greener tree TBR=jcivelli Review URL: http://codereview.chromium.org/2727007 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@49472 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium
ef25a6b6f3f387a119ab9261f37479fe415702d4
examples/xorg-gtest-example.cpp
examples/xorg-gtest-example.cpp
#include <xorg/gtest/xorg-gtest.h> using namespace xorg::testing; /** * @example xorg-gtest-example.cpp * * This is an example for using the fixture * xorg::testing::Test for your own tests. Please * make sure that you have the X.org dummy display * driver installed on your system and that you execute * the test with root privileges. */ TEST_F(Test, DummyXorgServerTest) { EXPECT_NE(0, DefaultRootWindow(Display())); }
#include <xorg/gtest/xorg-gtest.h> using namespace xorg::testing; /** * @example xorg-gtest-example.cpp * * This is an example for using the fixture * xorg::testing::Test for your own tests. Please * make sure that you have the X.org dummy display * driver installed on your system and that you execute * the test with root privileges. */ TEST_F(Test, DummyXorgServerTest) { EXPECT_NE((Window)None, DefaultRootWindow(Display())); }
fix compiler warning
examples: fix compiler warning ../gtest/include/gtest/gtest.h:18470:136: warning: comparison between signed and unsigned integer expressions [-Wsign-compare] Signed-off-by: Peter Hutterer <[email protected]>
C++
mit
freedesktop-unofficial-mirror/xorg__test__xorg-gtest,freedesktop-unofficial-mirror/xorg__test__xorg-gtest,freedesktop-unofficial-mirror/xorg__test__xorg-gtest
2a3f6884746f920c07a736a7239b1501165759ee
chainx/AccountManager.cpp
chainx/AccountManager.cpp
This file is part of chainx blockchain cpp-chainx 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 3 of the License, or (at your option) any later version. cpp-chainx 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 cpp-chainx. If not, see <http://www.gnu.org/licenses/>. */ /** @file AccountManager.cpp * @date 2016 */ #include <libdevcore/SHA3.h> #include <libdevcore/FileSystem.h> #include "AccountManager.h" using namespace std; using namespace dev; using namespace dev::; void AccountManager::streamAccountHelp(ostream& _out) { _out << " account list List all keys available in wallet." << endl << " account new Create a new key and add it to the wallet." << endl << " account update [<uuid>|<address> , ... ] Decrypt and re-encrypt given keys." << endl << " account import [<uuid>|<file>|<secret-hex>] Import keys from given source and place in wallet." << endl; } void AccountManager::streamWalletHelp(ostream& _out) { _out << " wallet import <file> Import a presale wallet." << endl; } bool AccountManager::execute(int argc, char** argv) { if (string(argv[1]) == "wallet") { if (3 < argc && string(argv[2]) == "import") { if (!openWallet()) return false; string file = argv[3]; string name = "presale wallet"; string pw; try { KeyPair k = m_keyManager->presaleSecret( contentsString(file), [&](bool){ return (pw = getPassword("Enter the passphrase for the presale key: "));} ); m_keyManager->import(k.secret(), name, pw, "Same passphrase as used for presale key"); cout << " Address: {" << k.address().hex() << "}" << endl; } catch (Exception const& _e) { if (auto err = boost::get_error_info<errinfo_comment>(_e)) cout << " Decryption failed: " << *err << endl; else cout << " Decryption failed: Unknown reason." << endl; return false; } } else streamWalletHelp(cout); return true; } else if (string(argv[1]) == "account") { if (argc < 3 || string(argv[2]) == "list") { openWallet(); if (m_keyManager->store().keys().empty()) cout << "No keys found." << endl; else { vector<u128> bare; AddressHash got; int k = 0; for (auto const& u: m_keyManager->store().keys()) { if (Address a = m_keyManager->address(u)) { got.insert(a); cout << "Account #" << k << ": {" << a.hex() << "}" << endl; k++; } else bare.push_back(u); } for (auto const& a: m_keyManager->accounts()) if (!got.count(a)) { cout << "Account #" << k << ": {" << a.hex() << "}" << " (Brain)" << endl; k++; } for (auto const& u: bare) { cout << "Account #" << k << ": " << toUUID(u) << " (Bare)" << endl; k++; } } } else if (2 < argc && string(argv[2]) == "new") { openWallet(); string name; string lock; string lockHint; lock = createPassword("Enter a passphrase with which to secure this account:"); auto k = makeKey(); h128 u = m_keyManager->import(k.secret(), name, lock, lockHint); cout << "Created key " << toUUID(u) << endl; cout << " ICAP: " << ICAP(k.address()).encoded() << endl; cout << " Address: {" << k.address().hex() << "}" << endl; } else if (3 < argc && string(argv[2]) == "import") { openWallet(); h128 u = m_keyManager->store().importKey(argv[3]); if (!u) { cerr << "Error: reading key file failed" << endl; return false; } string pw; bytesSec s = m_keyManager->store().secret(u, [&](){ return (pw = getPassword("Enter the passphrase for the key: ")); }); if (s.empty()) { cerr << "Error: couldn't decode key or invalid secret size." << endl; return false; } else { string lockHint; string name; m_keyManager->importExisting(u, name, pw, lockHint); auto a = m_keyManager->address(u); cout << "Imported key " << toUUID(u) << endl; cout << " ICAP: " << ICAP(a).encoded() << endl; cout << " Address: {" << a.hex() << "}" << endl; } } else if (3 < argc && string(argv[2]) == "update") { openWallet(); for (int k = 3; k < argc; k++) { string i = argv[k]; h128 u = fromUUID(i); if (isHex(i) || u != h128()) { string newP = createPassword("Enter the new passphrase for the account " + i); auto oldP = [&](){ return getPassword("Enter the current passphrase for the account " + i + ": "); }; bool recoded = false; if (isHex(i)) { recoded = m_keyManager->store().recode( Address(i), newP, oldP, dev::KDF::Scrypt ); } else if (u != h128()) { recoded = m_keyManager->store().recode( u, newP, oldP, dev::KDF::Scrypt ); } if (recoded) cerr << "Re-encoded " << i << endl; else cerr << "Couldn't re-encode " << i << "; key does not exist, corrupt or incorrect passphrase supplied." << endl; } else cerr << "Couldn't re-encode " << i << "; does not represent an address or uuid." << endl; } } else streamAccountHelp(cout); return true; } else return false; } string AccountManager::createPassword(string const& _prompt) const { string ret; while (true) { ret = getPassword(_prompt); string confirm = getPassword("Please confirm the passphrase by entering it again: "); if (ret == confirm) break; cout << "Passwords were different. Try again." << endl; } return ret; } KeyPair AccountManager::makeKey() const {
This file is part of chainx blockchain cpp-chainx 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 3 of the License, or (at your option) any later version. cpp-chainx 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 cpp-chainx. If not, see <http://www.gnu.org/licenses/>. */ /** @file AccountManager.cpp * @date 2016 #include <libdevcore/SHA3.h> #include <libdevcore/FileSystem.h> #include "AccountManager.h" using namespace std; using namespace dev; using namespace dev::; void AccountManager::streamAccountHelp(ostream& _out) { _out << " account list List all keys available in wallet." << endl << " account new Create a new key and add it to the wallet." << endl << " account update [<uuid>|<address> , ... ] Decrypt and re-encrypt given keys." << endl << " account import [<uuid>|<file>|<secret-hex>] Import keys from given source and place in wallet." << endl; } void AccountManager::streamWalletHelp(ostream& _out) { _out << " wallet import <file> Import a presale wallet." << endl; } bool AccountManager::execute(int argc, char** argv) { if (string(argv[1]) == "wallet") { if (3 < argc && string(argv[2]) == "import") { if (!openWallet()) return false; string file = argv[3]; string name = "presale wallet"; string pw; try { KeyPair k = m_keyManager->presaleSecret( contentsString(file), [&](bool){ return (pw = getPassword("Enter the passphrase for the presale key: "));} ); m_keyManager->import(k.secret(), name, pw, "Same passphrase as used for presale key"); cout << " Address: {" << k.address().hex() << "}" << endl; } catch (Exception const& _e) { if (auto err = boost::get_error_info<errinfo_comment>(_e)) cout << " Decryption failed: " << *err << endl; else cout << " Decryption failed: Unknown reason." << endl; return false; } } else streamWalletHelp(cout); return true; } else if (string(argv[1]) == "account") { if (argc < 3 || string(argv[2]) == "list") { openWallet(); if (m_keyManager->store().keys().empty()) cout << "No keys found." << endl; else { vector<u128> bare; AddressHash got; int k = 0; for (auto const& u: m_keyManager->store().keys()) { if (Address a = m_keyManager->address(u)) { got.insert(a); cout << "Account #" << k << ": {" << a.hex() << "}" << endl; k++; } else bare.push_back(u); } for (auto const& a: m_keyManager->accounts()) if (!got.count(a)) { cout << "Account #" << k << ": {" << a.hex() << "}" << " (Brain)" << endl; k++; } for (auto const& u: bare) { cout << "Account #" << k << ": " << toUUID(u) << " (Bare)" << endl; k++; } } } else if (2 < argc && string(argv[2]) == "new") { openWallet(); string name; string lock; string lockHint; lock = createPassword("Enter a passphrase with which to secure this account:"); auto k = makeKey(); h128 u = m_keyManager->import(k.secret(), name, lock, lockHint); cout << "Created key " << toUUID(u) << endl; cout << " ICAP: " << ICAP(k.address()).encoded() << endl; cout << " Address: {" << k.address().hex() << "}" << endl; } else if (3 < argc && string(argv[2]) == "import") { openWallet(); h128 u = m_keyManager->store().importKey(argv[3]); if (!u) { cerr << "Error: reading key file failed" << endl; return false; } string pw; bytesSec s = m_keyManager->store().secret(u, [&](){ return (pw = getPassword("Enter the passphrase for the key: ")); }); if (s.empty()) { cerr << "Error: couldn't decode key or invalid secret size." << endl; return false; } else { string lockHint; string name; m_keyManager->importExisting(u, name, pw, lockHint); auto a = m_keyManager->address(u); cout << "Imported key " << toUUID(u) << endl; cout << " ICAP: " << ICAP(a).encoded() << endl; cout << " Address: {" << a.hex() << "}" << endl; } } else if (3 < argc && string(argv[2]) == "update") { openWallet(); for (int k = 3; k < argc; k++) { string i = argv[k]; h128 u = fromUUID(i); if (isHex(i) || u != h128()) { string newP = createPassword("Enter the new passphrase for the account " + i); auto oldP = [&](){ return getPassword("Enter the current passphrase for the account " + i + ": "); }; bool recoded = false; if (isHex(i)) { recoded = m_keyManager->store().recode( Address(i), newP, oldP, dev::KDF::Scrypt ); } else if (u != h128()) { recoded = m_keyManager->store().recode( u, newP, oldP, dev::KDF::Scrypt ); } if (recoded) cerr << "Re-encoded " << i << endl; else cerr << "Couldn't re-encode " << i << "; key does not exist, corrupt or incorrect passphrase supplied." << endl; } else cerr << "Couldn't re-encode " << i << "; does not represent an address or uuid." << endl; } } else streamAccountHelp(cout); return true; } else return false; } string AccountManager::createPassword(string const& _prompt) const { string ret; while (true) { ret = getPassword(_prompt); string confirm = getPassword("Please confirm the passphrase by entering it again: "); if (ret == confirm) break; cout << "Passwords were different. Try again." << endl; } return ret; } KeyPair AccountManager::makeKey() const {
Update AccountManager.cpp
Update AccountManager.cpp
C++
mit
SmartChainX/ChainBlockchain,SmartChainX/ChainBlockchain,SmartChainX/ChainBlockchain,SmartChainX/ChainBlockchain
84676eab0ba67bd5608e5b3aac2ad3f324b12e52
toml/region.hpp
toml/region.hpp
#ifndef TOML11_REGION_H #define TOML11_REGION_H #include "exception.hpp" #include <memory> #include <algorithm> #include <iterator> #include <iostream> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // location in a container, normally in a file content. // shared_ptr points the resource that the iter points. // it can be used not only for resource handling, but also error message. template<typename Container> struct location { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; const_iterator& iter() noexcept {return iter_;} const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string const& name() const noexcept {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator iter_; }; // region in a container, normally in a file content. // shared_ptr points the resource that the iter points. // combinators returns this. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("");} virtual std::string name() const {return std::string("");} virtual std::string line() const {return std::string("");} virtual std::string line_num() const {return std::string("?");} virtual std::size_t before() const noexcept {return 0;} virtual std::size_t size() const noexcept {return 0;} virtual std::size_t after() const noexcept {return 0;} }; template<typename Container> struct region final : public region_base { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const region_base& reg, const std::string& comment_for_underline) { const auto line = reg.line(); const auto line_number = reg.line_num(); std::string retval; retval += message; retval += "\n --> "; retval += reg.name(); retval += "\n "; retval += line_number; retval += " | "; retval += line; retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(reg.before(), ' '); retval += make_string(reg.size(), '~'); retval += ' '; retval += comment_for_underline; return retval; } // to show a better error message. template<typename Container> std::string format_underline(const std::string& message, const location<Container>& loc, const std::string& comment_for_underline) { using const_iterator = typename location<Container>::const_iterator; using reverse_iterator = std::reverse_iterator<const_iterator>; const auto line_begin = std::find(reverse_iterator(loc.iter()), reverse_iterator(loc.begin()), '\n').base(); const auto line_end = std::find(loc.iter(), loc.end(), '\n'); const auto line_number = std::to_string( 1 + std::count(loc.begin(), loc.iter(), '\n')); std::string retval; retval += message; retval += "\n --> "; retval += loc.name(); retval += "\n "; retval += line_number; retval += " | "; retval += make_string(line_begin, line_end); retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(std::distance(line_begin, loc.iter()),' '); retval += '^'; retval += make_string(std::distance(loc.iter(), line_end), '~'); retval += ' '; retval += comment_for_underline; return retval; } } // detail } // toml #endif// TOML11_REGION_H
#ifndef TOML11_REGION_H #define TOML11_REGION_H #include "exception.hpp" #include <memory> #include <algorithm> #include <initializer_list> #include <iterator> #include <iostream> namespace toml { namespace detail { // helper function to avoid std::string(0, 'c') template<typename Iterator> std::string make_string(Iterator first, Iterator last) { if(first == last) {return "";} return std::string(first, last); } inline std::string make_string(std::size_t len, char c) { if(len == 0) {return "";} return std::string(len, c); } // location in a container, normally in a file content. // shared_ptr points the resource that the iter points. // it can be used not only for resource handling, but also error message. template<typename Container> struct location { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; location(std::string name, Container cont) : source_(std::make_shared<Container>(std::move(cont))), source_name_(std::move(name)), iter_(source_->cbegin()) {} location(const location&) = default; location(location&&) = default; location& operator=(const location&) = default; location& operator=(location&&) = default; ~location() = default; const_iterator& iter() noexcept {return iter_;} const_iterator iter() const noexcept {return iter_;} const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string const& name() const noexcept {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator iter_; }; // region in a container, normally in a file content. // shared_ptr points the resource that the iter points. // combinators returns this. // it will be used to generate better error messages. struct region_base { region_base() = default; virtual ~region_base() = default; region_base(const region_base&) = default; region_base(region_base&& ) = default; region_base& operator=(const region_base&) = default; region_base& operator=(region_base&& ) = default; virtual bool is_ok() const noexcept {return false;} virtual std::string str() const {return std::string("");} virtual std::string name() const {return std::string("unknown location");} virtual std::string line() const {return std::string("unknown line");} virtual std::string line_num() const {return std::string("?");} virtual std::size_t before() const noexcept {return 0;} virtual std::size_t size() const noexcept {return 0;} virtual std::size_t after() const noexcept {return 0;} }; template<typename Container> struct region final : public region_base { static_assert(std::is_same<char, typename Container::value_type>::value,""); using const_iterator = typename Container::const_iterator; using source_ptr = std::shared_ptr<const Container>; // delete default constructor. source_ never be null. region() = delete; region(const location<Container>& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(location<Container>&& loc) : source_(loc.source()), source_name_(loc.name()), first_(loc.iter()), last_(loc.iter()) {} region(const location<Container>& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(location<Container>&& loc, const_iterator f, const_iterator l) : source_(loc.source()), source_name_(loc.name()), first_(f), last_(l) {} region(const region&) = default; region(region&&) = default; region& operator=(const region&) = default; region& operator=(region&&) = default; ~region() = default; region& operator+=(const region& other) { if(this->begin() != other.begin() || this->end() != other.end() || this->last_ != other.first_) { throw internal_error("invalid region concatenation"); } this->last_ = other.last_; return *this; } bool is_ok() const noexcept override {return static_cast<bool>(source_);} std::string str() const override {return make_string(first_, last_);} std::string line() const override { return make_string(this->line_begin(), this->line_end()); } std::string line_num() const override { return std::to_string(1 + std::count(this->begin(), this->first(), '\n')); } std::size_t size() const noexcept override { return std::distance(first_, last_); } std::size_t before() const noexcept override { return std::distance(this->line_begin(), this->first()); } std::size_t after() const noexcept override { return std::distance(this->last(), this->line_end()); } const_iterator line_begin() const noexcept { using reverse_iterator = std::reverse_iterator<const_iterator>; return std::find(reverse_iterator(this->first()), reverse_iterator(this->begin()), '\n').base(); } const_iterator line_end() const noexcept { return std::find(this->last(), this->end(), '\n'); } const_iterator begin() const noexcept {return source_->cbegin();} const_iterator end() const noexcept {return source_->cend();} const_iterator first() const noexcept {return first_;} const_iterator last() const noexcept {return last_;} source_ptr const& source() const& noexcept {return source_;} source_ptr&& source() && noexcept {return std::move(source_);} std::string name() const override {return source_name_;} private: source_ptr source_; std::string source_name_; const_iterator first_, last_; }; // to show a better error message. inline std::string format_underline(const std::string& message, const region_base& reg, const std::string& comment_for_underline) { const auto line = reg.line(); const auto line_number = reg.line_num(); std::string retval; retval += message; retval += "\n --> "; retval += reg.name(); retval += "\n "; retval += line_number; retval += " | "; retval += line; retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(reg.before(), ' '); retval += make_string(reg.size(), '~'); retval += ' '; retval += comment_for_underline; return retval; } // to show a better error message. template<typename Container> std::string format_underline(const std::string& message, const location<Container>& loc, const std::string& comment_for_underline, std::initializer_list<std::string> helps = {}) { using const_iterator = typename location<Container>::const_iterator; using reverse_iterator = std::reverse_iterator<const_iterator>; const auto line_begin = std::find(reverse_iterator(loc.iter()), reverse_iterator(loc.begin()), '\n').base(); const auto line_end = std::find(loc.iter(), loc.end(), '\n'); const auto line_number = std::to_string( 1 + std::count(loc.begin(), loc.iter(), '\n')); std::string retval; retval += message; retval += "\n --> "; retval += loc.name(); retval += "\n "; retval += line_number; retval += " | "; retval += make_string(line_begin, line_end); retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; retval += make_string(std::distance(line_begin, loc.iter()),' '); retval += '^'; retval += make_string(std::distance(loc.iter(), line_end), '-'); retval += ' '; retval += comment_for_underline; if(helps.size() != 0) { retval += '\n'; retval += make_string(line_number.size() + 1, ' '); retval += " | "; for(const auto help : helps) { retval += "\nHint: "; retval += help; } } return retval; } } // detail } // toml #endif// TOML11_REGION_H
improve quality of error message
improve quality of error message
C++
mit
ToruNiina/toml11
3e94c85c59558699812ef6d062bcca875f15ea01
android/jni/main.cpp
android/jni/main.cpp
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include <jni.h> #include "AppRunner.h" #include "main.h" #include <android/native_window.h> #include <android/native_window_jni.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <pthread.h> using namespace Eegeo::Android; using namespace Eegeo::Android::Input; const std::string ApiKey = "c93bd872c1e600d53d458b59bc797b51"; AndroidNativeState g_nativeState; AppRunner* g_pAppRunner; namespace { void FillEventFromJniData( JNIEnv* jenv, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex, TouchInputEvent& event); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* pvt) { g_nativeState.vm = vm; return JNI_VERSION_1_6; } //lifecycle JNIEXPORT long JNICALL Java_com_eegeo_NativeJniCalls_createNativeCode(JNIEnv* jenv, jobject obj, jobject activity, jobject assetManager, jfloat dpi) { Eegeo_TTY("startNativeCode\n"); g_nativeState.javaMainThread = pthread_self(); g_nativeState.mainThreadEnv = jenv; g_nativeState.activity = jenv->NewGlobalRef(activity); g_nativeState.activityClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("com/eegeo/MainActivity")); g_nativeState.deviceDpi = dpi; jmethodID getClassLoader = jenv->GetMethodID(g_nativeState.activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;"); g_nativeState.classLoader = jenv->NewGlobalRef(jenv->CallObjectMethod(activity, getClassLoader)); g_nativeState.classLoaderClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("java/lang/ClassLoader")); g_nativeState.classLoaderLoadClassMethod = jenv->GetMethodID(g_nativeState.classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); g_nativeState.DetermineDeviceModel(jenv); jthrowable exc; exc = jenv->ExceptionOccurred(); if (exc) { jenv->ExceptionDescribe(); jenv->ExceptionClear(); return 0; } g_nativeState.assetManagerGlobalRef = jenv->NewGlobalRef(assetManager); g_nativeState.assetManager = AAssetManager_fromJava(jenv, g_nativeState.assetManagerGlobalRef); g_pAppRunner = Eegeo_NEW(AppRunner)(ApiKey, &g_nativeState); return ((long)g_pAppRunner); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCallsy_destroyNativeCode(JNIEnv* jenv, jobject obj) { Eegeo_TTY("stopNativeCode()\n"); delete g_pAppRunner; g_pAppRunner = NULL; jenv->DeleteGlobalRef(g_nativeState.assetManagerGlobalRef); jenv->DeleteGlobalRef(g_nativeState.activity); jenv->DeleteGlobalRef(g_nativeState.activityClass); jenv->DeleteGlobalRef(g_nativeState.classLoaderClass); jenv->DeleteGlobalRef(g_nativeState.classLoader); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_pauseNativeCode(JNIEnv* jenv, jobject obj) { g_pAppRunner->Pause(); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_resumeNativeCode(JNIEnv* jenv, jobject obj) { g_pAppRunner->Resume(); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_updateNativeCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds) { g_pAppRunner->Update((float)deltaSeconds); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_setNativeSurface(JNIEnv* jenv, jobject obj, jobject surface) { if(g_nativeState.window != NULL) { ANativeWindow_release(g_nativeState.window); g_nativeState.window = NULL; } if (surface != NULL) { g_nativeState.window = ANativeWindow_fromSurface(jenv, surface); g_pAppRunner->ActivateSurface(); } } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerDown(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(false, true, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerUp(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(true, false, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerMove(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(false, false, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } namespace { void FillEventFromJniData( JNIEnv* jenv, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex, TouchInputEvent& event) { jfloat* xBuffer = jenv->GetFloatArrayElements(x, 0); jfloat* yBuffer = jenv->GetFloatArrayElements(y, 0); jint* identityBuffer = jenv->GetIntArrayElements(pointerIdentity, 0); jint* indexBuffer = jenv->GetIntArrayElements(pointerIndex, 0); for(int i = 0; i < numPointers; ++ i) { TouchInputPointerEvent p(xBuffer[i], yBuffer[i], identityBuffer[i], indexBuffer[i]); event.pointerEvents.push_back(p); } jenv->ReleaseFloatArrayElements(x, xBuffer, 0); jenv->ReleaseFloatArrayElements(y, yBuffer, 0); jenv->ReleaseIntArrayElements(pointerIdentity, identityBuffer, 0); jenv->ReleaseIntArrayElements(pointerIndex, indexBuffer, 0); } }
// Copyright eeGeo Ltd (2012-2014), All Rights Reserved #include <jni.h> #include "AppRunner.h" #include "main.h" #include <android/native_window.h> #include <android/native_window_jni.h> #include <android/asset_manager.h> #include <android/asset_manager_jni.h> #include <pthread.h> using namespace Eegeo::Android; using namespace Eegeo::Android::Input; const std::string ApiKey = "OBTAIN API_KEY FROM https://appstore.eegeo.com AND INSERT IT HERE"; AndroidNativeState g_nativeState; AppRunner* g_pAppRunner; namespace { void FillEventFromJniData( JNIEnv* jenv, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex, TouchInputEvent& event); } JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void* pvt) { g_nativeState.vm = vm; return JNI_VERSION_1_6; } //lifecycle JNIEXPORT long JNICALL Java_com_eegeo_NativeJniCalls_createNativeCode(JNIEnv* jenv, jobject obj, jobject activity, jobject assetManager, jfloat dpi) { Eegeo_TTY("startNativeCode\n"); g_nativeState.javaMainThread = pthread_self(); g_nativeState.mainThreadEnv = jenv; g_nativeState.activity = jenv->NewGlobalRef(activity); g_nativeState.activityClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("com/eegeo/MainActivity")); g_nativeState.deviceDpi = dpi; jmethodID getClassLoader = jenv->GetMethodID(g_nativeState.activityClass,"getClassLoader", "()Ljava/lang/ClassLoader;"); g_nativeState.classLoader = jenv->NewGlobalRef(jenv->CallObjectMethod(activity, getClassLoader)); g_nativeState.classLoaderClass = (jclass)jenv->NewGlobalRef(jenv->FindClass("java/lang/ClassLoader")); g_nativeState.classLoaderLoadClassMethod = jenv->GetMethodID(g_nativeState.classLoaderClass, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;"); g_nativeState.DetermineDeviceModel(jenv); jthrowable exc; exc = jenv->ExceptionOccurred(); if (exc) { jenv->ExceptionDescribe(); jenv->ExceptionClear(); return 0; } g_nativeState.assetManagerGlobalRef = jenv->NewGlobalRef(assetManager); g_nativeState.assetManager = AAssetManager_fromJava(jenv, g_nativeState.assetManagerGlobalRef); g_pAppRunner = Eegeo_NEW(AppRunner)(ApiKey, &g_nativeState); return ((long)g_pAppRunner); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCallsy_destroyNativeCode(JNIEnv* jenv, jobject obj) { Eegeo_TTY("stopNativeCode()\n"); delete g_pAppRunner; g_pAppRunner = NULL; jenv->DeleteGlobalRef(g_nativeState.assetManagerGlobalRef); jenv->DeleteGlobalRef(g_nativeState.activity); jenv->DeleteGlobalRef(g_nativeState.activityClass); jenv->DeleteGlobalRef(g_nativeState.classLoaderClass); jenv->DeleteGlobalRef(g_nativeState.classLoader); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_pauseNativeCode(JNIEnv* jenv, jobject obj) { g_pAppRunner->Pause(); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_resumeNativeCode(JNIEnv* jenv, jobject obj) { g_pAppRunner->Resume(); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_updateNativeCode(JNIEnv* jenv, jobject obj, jfloat deltaSeconds) { g_pAppRunner->Update((float)deltaSeconds); } JNIEXPORT void JNICALL Java_com_eegeo_NativeJniCalls_setNativeSurface(JNIEnv* jenv, jobject obj, jobject surface) { if(g_nativeState.window != NULL) { ANativeWindow_release(g_nativeState.window); g_nativeState.window = NULL; } if (surface != NULL) { g_nativeState.window = ANativeWindow_fromSurface(jenv, surface); g_pAppRunner->ActivateSurface(); } } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerDown(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(false, true, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerUp(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(true, false, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } JNIEXPORT void JNICALL Java_com_eegeo_EegeoSurfaceView_processNativePointerMove(JNIEnv* jenv, jobject obj, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex) { TouchInputEvent event(false, false, primaryActionIndex, primaryActionIdentifier); FillEventFromJniData(jenv, primaryActionIndex, primaryActionIdentifier, numPointers, x, y, pointerIdentity, pointerIndex, event); g_pAppRunner->HandleTouchEvent(event); } namespace { void FillEventFromJniData( JNIEnv* jenv, jint primaryActionIndex, jint primaryActionIdentifier, jint numPointers, jfloatArray x, jfloatArray y, jintArray pointerIdentity, jintArray pointerIndex, TouchInputEvent& event) { jfloat* xBuffer = jenv->GetFloatArrayElements(x, 0); jfloat* yBuffer = jenv->GetFloatArrayElements(y, 0); jint* identityBuffer = jenv->GetIntArrayElements(pointerIdentity, 0); jint* indexBuffer = jenv->GetIntArrayElements(pointerIndex, 0); for(int i = 0; i < numPointers; ++ i) { TouchInputPointerEvent p(xBuffer[i], yBuffer[i], identityBuffer[i], indexBuffer[i]); event.pointerEvents.push_back(p); } jenv->ReleaseFloatArrayElements(x, xBuffer, 0); jenv->ReleaseFloatArrayElements(y, yBuffer, 0); jenv->ReleaseIntArrayElements(pointerIdentity, identityBuffer, 0); jenv->ReleaseIntArrayElements(pointerIndex, indexBuffer, 0); } }
Remove checkin of dev api key.
Remove checkin of dev api key.
C++
bsd-2-clause
eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,eegeo/eegeo-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app,wrld3d/wrld-example-app
d88ed32f702853b4ea9f9b5c09d420d1ea99093f
test/match_results.cpp
test/match_results.cpp
#include <gtest/gtest.h> #include "pcre2++/pcre2pp.h" TEST(MatchResults, basic) { pcre2::smatch m; EXPECT_FALSE(m.ready()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.size()); EXPECT_EQ(m.begin(), m.end()); EXPECT_EQ(m.cbegin(), m.cend()); }
#include <gtest/gtest.h> #include <string> #include "pcre2++/pcre2pp.h" TEST(MatchResults, basic) { pcre2::smatch m; EXPECT_FALSE(m.ready()); EXPECT_TRUE(m.empty()); EXPECT_EQ(0, m.size()); EXPECT_EQ(m.begin(), m.end()); EXPECT_EQ(m.cbegin(), m.cend()); } /** * @see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03 */ TEST(MatchResults, format_sed) { std::string email("Something <[email protected]> anything"); pcre2::regex re("<([^@]++)@([^>]++)>"); pcre2::smatch m; bool f = pcre2::regex_search(email, m, re); EXPECT_TRUE(f); EXPECT_EQ(std::string("someone"), m[1].str()); EXPECT_EQ(std::string("example.com"), m[2].str()); std::string actual; // An <ampersand> ( '&' ) appearing in the replacement shall be replaced by the string matching the BRE. actual = m.format("!&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<[email protected]>!"), actual); // The special meaning of '&' in this context can be suppressed by preceding it by a <backslash>. actual = m.format("!&\\&!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!<[email protected]>&!"), actual); // The characters "\n", where n is a digit, shall be replaced by the text matched by the corresponding back-reference expression. actual = m.format("!\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!someone example.com!"), actual); // If the corresponding back-reference expression does not match, then the characters "\n" shall be replaced by the empty string. actual = m.format("!\\3!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!!"), actual); // The special meaning of "\n" where n is a digit in this context, can be suppressed by preceding it by a <backslash>. actual = m.format("!\\\\1 \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\1 example.com!"), actual); /* */ actual = m.format("!\\x \\2!", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("!\\x example.com!"), actual); /* Corner case - backslash is the last character */ actual = m.format("\\1 \\", pcre2::regex_constants::format_sed); EXPECT_EQ(std::string("someone \\"), actual); } TEST(MatchResults, format_default) { { // http://en.cppreference.com/w/cpp/regex/match_results/format std::string s = "for a good time, call 867-5309"; pcre2::regex phone_regex("\\d{3}-\\d{4}"); pcre2::smatch phone_match; bool f = pcre2::regex_search(s, phone_match, phone_regex); EXPECT_TRUE(f); std::string actual = phone_match.format( "<$`>" // $` means characters before the match "[$&]" // $& means the matched characters "<$'>" // $' means characters following the match ); EXPECT_EQ(std::string("<for a good time, call >[867-5309]<>"), actual); } { std::string s = "IP: 127.0.0.1 localhost"; pcre2::regex re("([0-9]++)\\.([0-9]++)\\.([0-9]++)\\.([0-9]++)"); pcre2::smatch m; std::string actual; bool f = pcre2::regex_search(s, m, re); EXPECT_TRUE(f); actual = m.format("$`"); EXPECT_EQ(std::string("IP: "), actual); actual = m.format("$'"); EXPECT_EQ(std::string(" localhost"), actual); actual = m.format("$&"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$0"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$00"); EXPECT_EQ(std::string("127.0.0.1"), actual); actual = m.format("$x $$ $1 $5 $4 $"); EXPECT_EQ(std::string("$x $ 127 1 $"), actual); } }
Test cases
Test cases
C++
mit
sjinks/pcre2pp,sjinks/pcre2pp,sjinks/pcre2pp
c9a881ecc6f304b586bf13f54a7cff7119b04070
test/val/val_primitives_test.cpp
test/val/val_primitives_test.cpp
// Copyright (c) 2017 LunarG 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 <sstream> #include <string> #include "gmock/gmock.h" #include "unit_spirv.h" #include "val_fixtures.h" namespace { using ::testing::HasSubstr; using ::testing::Not; using ValidatePrimitives = spvtest::ValidateBase<bool>; std::string GenerateShaderCode( const std::string& body, const std::string& capabilities_and_extensions = "OpCapability GeometryStreams", const std::string& execution_model = "Geometry") { std::ostringstream ss; ss << capabilities_and_extensions << "\n"; ss << "OpMemoryModel Logical GLSL450\n"; ss << "OpEntryPoint " << execution_model << " %main \"main\"\n"; ss << R"( %void = OpTypeVoid %func = OpTypeFunction %void %f32 = OpTypeFloat 32 %u32 = OpTypeInt 32 0 %u32vec4 = OpTypeVector %u32 4 %f32_0 = OpConstant %f32 0 %u32_0 = OpConstant %u32 0 %u32_1 = OpConstant %u32 1 %u32_2 = OpConstant %u32 2 %u32_3 = OpConstant %u32 3 %u32vec4_0123 = OpConstantComposite %u32vec4 %u32_0 %u32_1 %u32_2 %u32_3 %main = OpFunction %void None %func %main_entry = OpLabel )"; ss << body; ss << R"( OpReturn OpFunctionEnd)"; return ss.str(); } // Returns SPIR-V assembly fragment representing a function call, // the end of the callee body, and the preamble and body of the called // function with the given body, but missing the final return and // function-end. The result is of the form where it can be used in the // |body| argument to GenerateShaderCode. std::string CallAndCallee(std::string body) { std::ostringstream ss; ss << R"( %dummy = OpFunctionCall %void %foo OpReturn OpFunctionEnd %foo = OpFunction %void None %func %foo_entry = OpLabel )"; ss << body; return ss.str(); } // OpEmitVertex doesn't have any parameters, so other validation // is handled by the binary parser, and generic dominance checks. TEST_F(ValidatePrimitives, EmitVertexSuccess) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Geometry")); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EmitVertexFailMissingCapability) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "Opcode EmitVertex requires one of these capabilities: Geometry")); } TEST_F(ValidatePrimitives, EmitVertexFailWrongExecutionMode) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EmitVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitVertexFailWrongExecutionModeNestedFunction) { CompileSuccessfully(GenerateShaderCode(CallAndCallee("OpEmitVertex"), "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EmitVertex instructions require Geometry execution model")); } // OpEndPrimitive doesn't have any parameters, so other validation // is handled by the binary parser, and generic dominance checks. TEST_F(ValidatePrimitives, EndPrimitiveSuccess) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Geometry")); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EndPrimitiveFailMissingCapability) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "Opcode EndPrimitive requires one of these capabilities: Geometry")); } TEST_F(ValidatePrimitives, EndPrimitiveFailWrongExecutionMode) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EndPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndPrimitiveFailWrongExecutionModeNestedFunction) { CompileSuccessfully(GenerateShaderCode(CallAndCallee("OpEndPrimitive"), "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EndPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexSuccess) { const std::string body = R"( OpEmitStreamVertex %u32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EmitStreamVertexFailMissingCapability) { CompileSuccessfully(GenerateShaderCode("OpEmitStreamVertex %u32_0", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Opcode EmitStreamVertex requires one of these " "capabilities: GeometryStreams")); } TEST_F(ValidatePrimitives, EmitStreamVertexFailWrongExecutionMode) { CompileSuccessfully(GenerateShaderCode( "OpEmitStreamVertex %u32_0", "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EmitStreamVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexFailWrongExecutionModeNestedFunction) { CompileSuccessfully( GenerateShaderCode(CallAndCallee("OpEmitStreamVertex %u32_0"), "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EmitStreamVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonInt) { const std::string body = R"( OpEmitStreamVertex %f32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonScalar) { const std::string body = R"( OpEmitStreamVertex %u32vec4_0123 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonConstant) { const std::string body = R"( %val1 = OpIAdd %u32 %u32_0 %u32_1 OpEmitStreamVertex %val1 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be constant instruction")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveSuccess) { const std::string body = R"( OpEndStreamPrimitive %u32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailMissingCapability) { CompileSuccessfully(GenerateShaderCode("OpEndStreamPrimitive %u32_0", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Opcode EndStreamPrimitive requires one of these " "capabilities: GeometryStreams")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailWrongExecutionMode) { CompileSuccessfully(GenerateShaderCode( "OpEndStreamPrimitive %u32_0", "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EndStreamPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailWrongExecutionModeNestedFunction) { CompileSuccessfully( GenerateShaderCode(CallAndCallee("OpEndStreamPrimitive %u32_0"), "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EndStreamPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonInt) { const std::string body = R"( OpEndStreamPrimitive %f32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonScalar) { const std::string body = R"( OpEndStreamPrimitive %u32vec4_0123 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonConstant) { const std::string body = R"( %val1 = OpIAdd %u32 %u32_0 %u32_1 OpEndStreamPrimitive %val1 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be constant instruction")); } } // anonymous namespace
// Copyright (c) 2017 LunarG 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 <sstream> #include <string> #include "gmock/gmock.h" #include "unit_spirv.h" #include "val_fixtures.h" namespace { using ::testing::HasSubstr; using ::testing::Not; using ValidatePrimitives = spvtest::ValidateBase<bool>; std::string GenerateShaderCode( const std::string& body, const std::string& capabilities_and_extensions = "OpCapability GeometryStreams", const std::string& execution_model = "Geometry") { std::ostringstream ss; ss << capabilities_and_extensions << "\n"; ss << "OpMemoryModel Logical GLSL450\n"; ss << "OpEntryPoint " << execution_model << " %main \"main\"\n"; ss << R"( %void = OpTypeVoid %func = OpTypeFunction %void %f32 = OpTypeFloat 32 %u32 = OpTypeInt 32 0 %u32vec4 = OpTypeVector %u32 4 %f32_0 = OpConstant %f32 0 %u32_0 = OpConstant %u32 0 %u32_1 = OpConstant %u32 1 %u32_2 = OpConstant %u32 2 %u32_3 = OpConstant %u32 3 %u32vec4_0123 = OpConstantComposite %u32vec4 %u32_0 %u32_1 %u32_2 %u32_3 %main = OpFunction %void None %func %main_entry = OpLabel )"; ss << body; ss << R"( OpReturn OpFunctionEnd)"; return ss.str(); } // Returns SPIR-V assembly fragment representing a function call, // the end of the callee body, and the preamble and body of the called // function with the given body, but missing the final return and // function-end. The result is of the form where it can be used in the // |body| argument to GenerateShaderCode. std::string CallAndCallee(const std::string& body) { std::ostringstream ss; ss << R"( %dummy = OpFunctionCall %void %foo OpReturn OpFunctionEnd %foo = OpFunction %void None %func %foo_entry = OpLabel )"; ss << body; return ss.str(); } // OpEmitVertex doesn't have any parameters, so other validation // is handled by the binary parser, and generic dominance checks. TEST_F(ValidatePrimitives, EmitVertexSuccess) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Geometry")); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EmitVertexFailMissingCapability) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "Opcode EmitVertex requires one of these capabilities: Geometry")); } TEST_F(ValidatePrimitives, EmitVertexFailWrongExecutionMode) { CompileSuccessfully( GenerateShaderCode("OpEmitVertex", "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EmitVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitVertexFailWrongExecutionModeNestedFunction) { CompileSuccessfully(GenerateShaderCode(CallAndCallee("OpEmitVertex"), "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EmitVertex instructions require Geometry execution model")); } // OpEndPrimitive doesn't have any parameters, so other validation // is handled by the binary parser, and generic dominance checks. TEST_F(ValidatePrimitives, EndPrimitiveSuccess) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Geometry")); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EndPrimitiveFailMissingCapability) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "Opcode EndPrimitive requires one of these capabilities: Geometry")); } TEST_F(ValidatePrimitives, EndPrimitiveFailWrongExecutionMode) { CompileSuccessfully( GenerateShaderCode("OpEndPrimitive", "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EndPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndPrimitiveFailWrongExecutionModeNestedFunction) { CompileSuccessfully(GenerateShaderCode(CallAndCallee("OpEndPrimitive"), "OpCapability Geometry", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr("EndPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexSuccess) { const std::string body = R"( OpEmitStreamVertex %u32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EmitStreamVertexFailMissingCapability) { CompileSuccessfully(GenerateShaderCode("OpEmitStreamVertex %u32_0", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Opcode EmitStreamVertex requires one of these " "capabilities: GeometryStreams")); } TEST_F(ValidatePrimitives, EmitStreamVertexFailWrongExecutionMode) { CompileSuccessfully(GenerateShaderCode( "OpEmitStreamVertex %u32_0", "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EmitStreamVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexFailWrongExecutionModeNestedFunction) { CompileSuccessfully( GenerateShaderCode(CallAndCallee("OpEmitStreamVertex %u32_0"), "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EmitStreamVertex instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonInt) { const std::string body = R"( OpEmitStreamVertex %f32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonScalar) { const std::string body = R"( OpEmitStreamVertex %u32vec4_0123 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EmitStreamVertexNonConstant) { const std::string body = R"( %val1 = OpIAdd %u32 %u32_0 %u32_1 OpEmitStreamVertex %val1 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EmitStreamVertex: " "expected Stream to be constant instruction")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveSuccess) { const std::string body = R"( OpEndStreamPrimitive %u32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_SUCCESS, ValidateInstructions()); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailMissingCapability) { CompileSuccessfully(GenerateShaderCode("OpEndStreamPrimitive %u32_0", "OpCapability Shader", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_CAPABILITY, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("Opcode EndStreamPrimitive requires one of these " "capabilities: GeometryStreams")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailWrongExecutionMode) { CompileSuccessfully(GenerateShaderCode( "OpEndStreamPrimitive %u32_0", "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EndStreamPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveFailWrongExecutionModeNestedFunction) { CompileSuccessfully( GenerateShaderCode(CallAndCallee("OpEndStreamPrimitive %u32_0"), "OpCapability GeometryStreams", "Vertex")); EXPECT_EQ(SPV_ERROR_INVALID_ID, ValidateInstructions()); EXPECT_THAT( getDiagnosticString(), HasSubstr( "EndStreamPrimitive instructions require Geometry execution model")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonInt) { const std::string body = R"( OpEndStreamPrimitive %f32_0 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonScalar) { const std::string body = R"( OpEndStreamPrimitive %u32vec4_0123 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be int scalar")); } TEST_F(ValidatePrimitives, EndStreamPrimitiveNonConstant) { const std::string body = R"( %val1 = OpIAdd %u32 %u32_0 %u32_1 OpEndStreamPrimitive %val1 )"; CompileSuccessfully(GenerateShaderCode(body)); EXPECT_EQ(SPV_ERROR_INVALID_DATA, ValidateInstructions()); EXPECT_THAT(getDiagnosticString(), HasSubstr("EndStreamPrimitive: " "expected Stream to be constant instruction")); } } // anonymous namespace
Make a string parameter const ref
Make a string parameter const ref
C++
apache-2.0
pierremoreau/SPIRV-Tools,dneto0/SPIRV-Tools,dneto0/SPIRV-Tools,LukasBanana/SPIRV-Tools,pierremoreau/SPIRV-Tools,LukasBanana/SPIRV-Tools,dneto0/SPIRV-Tools,pierremoreau/SPIRV-Tools,antiagainst/SPIRV-Tools,dneto0/SPIRV-Tools,pierremoreau/SPIRV-Tools,dneto0/SPIRV-Tools,pierremoreau/SPIRV-Tools,pierremoreau/SPIRV-Tools,antiagainst/SPIRV-Tools,KhronosGroup/SPIRV-Tools,dneto0/SPIRV-Tools,KhronosGroup/SPIRV-Tools,KhronosGroup/SPIRV-Tools,KhronosGroup/SPIRV-Tools,KhronosGroup/SPIRV-Tools,KhronosGroup/SPIRV-Tools,dneto0/SPIRV-Tools,KhronosGroup/SPIRV-Tools,pierremoreau/SPIRV-Tools,pierremoreau/SPIRV-Tools,antiagainst/SPIRV-Tools,dneto0/SPIRV-Tools,LukasBanana/SPIRV-Tools,antiagainst/SPIRV-Tools,KhronosGroup/SPIRV-Tools,antiagainst/SPIRV-Tools
b51472214d6f8233664929fae4ca8e5f1f184c70
test/test_normpath.cpp
test/test_normpath.cpp
// // Created by 王晓辰 on 15/10/2. // #include "test_normpath.h" #include <ftxpath.h> #include "tester.h" bool test_normpath_normal() { std::string path = "/a/b/c"; return path == ftxpath::normpath(path); } bool test_normpath_pardir() { std::string path = "../a/b/c/../.."; std::string normpath = "../a"; return normpath == ftxpath::normpath(path); } bool test_normpath_curdir() { std::string path = "./a/b"; std::string normpath = "a/b"; return normpath == ftxpath::normpath(path); } bool test_normpath() { LOG_TEST_STRING(""); TEST_BOOL_TO_BOOL(test_normpath_normal(), "normal path error"); TEST_BOOL_TO_BOOL(test_normpath_pardir(), "pardir path normal path error"); TEST_BOOL_TO_BOOL(test_normpath_curdir(), "curdir path normal path error"); return true; }
// // Created by 王晓辰 on 15/10/2. // #include "test_normpath.h" #include <ftxpath.h> #include "tester.h" bool test_normpath_normal() { std::string path = "/a/b/c"; #ifdef WIN32 path = "\\a\\b\\c"; #endif return path == ftxpath::normpath(path); } bool test_normpath_pardir() { std::string path = "../a/b/c/../.."; std::string normpath = "../a"; #ifdef WIN32 normpath = "..\\a"; #endif return normpath == ftxpath::normpath(path); } bool test_normpath_curdir() { std::string path = "./a/b"; std::string normpath = "a/b"; #ifdef WIN32 normpath = "a\\b"; #endif return normpath == ftxpath::normpath(path); } bool test_normpath() { LOG_TEST_STRING(""); TEST_BOOL_TO_BOOL(test_normpath_normal(), "normal path error"); TEST_BOOL_TO_BOOL(test_normpath_pardir(), "pardir path normal path error"); TEST_BOOL_TO_BOOL(test_normpath_curdir(), "curdir path normal path error"); return true; }
fix test normpath
fix test normpath
C++
bsd-2-clause
XiaochenFTX/ftxpath,XiaochenFTX/libpath
c24d9118471f5de1e9a42f4d113d3d93f196aea3
test/vp9_scale_test.cc
test/vp9_scale_test.cc
/* * Copyright (c) 2017 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <assert.h> #include <stdio.h> #include <string.h> #include "third_party/googletest/src/include/gtest/gtest.h" #include "./vp9_rtcd.h" #include "./vpx_config.h" #include "./vpx_scale_rtcd.h" #include "test/clear_system_state.h" #include "test/register_state_check.h" #include "test/vpx_scale_test.h" #include "vpx_mem/vpx_mem.h" #include "vpx_ports/vpx_timer.h" #include "vpx_scale/yv12config.h" namespace libvpx_test { typedef void (*ScaleFrameFunc)(const YV12_BUFFER_CONFIG *src, YV12_BUFFER_CONFIG *dst, INTERP_FILTER filter_type, int phase_scaler); class ScaleTest : public VpxScaleBase, public ::testing::TestWithParam<ScaleFrameFunc> { public: virtual ~ScaleTest() {} protected: virtual void SetUp() { scale_fn_ = GetParam(); } void ReferenceScaleFrame(INTERP_FILTER filter_type, int phase_scaler) { vp9_scale_and_extend_frame_c(&img_, &ref_img_, filter_type, phase_scaler); } void ScaleFrame(INTERP_FILTER filter_type, int phase_scaler) { ASM_REGISTER_STATE_CHECK( scale_fn_(&img_, &dst_img_, filter_type, phase_scaler)); } void RunTest() { static const int kNumSizesToTest = 4; static const int kNumScaleFactorsToTest = 4; static const int kWidthsToTest[] = { 16, 32, 48, 64 }; static const int kHeightsToTest[] = { 16, 20, 24, 28 }; static const int kScaleFactors[] = { 1, 2, 3, 4 }; for (INTERP_FILTER filter_type = 0; filter_type < 4; ++filter_type) { for (int phase_scaler = 0; phase_scaler < 16; ++phase_scaler) { for (int h = 0; h < kNumSizesToTest; ++h) { const int src_height = kHeightsToTest[h]; for (int w = 0; w < kNumSizesToTest; ++w) { const int src_width = kWidthsToTest[w]; for (int sf_up_idx = 0; sf_up_idx < kNumScaleFactorsToTest; ++sf_up_idx) { const int sf_up = kScaleFactors[sf_up_idx]; for (int sf_down_idx = 0; sf_down_idx < kNumScaleFactorsToTest; ++sf_down_idx) { const int sf_down = kScaleFactors[sf_down_idx]; const int dst_width = src_width * sf_up / sf_down; const int dst_height = src_height * sf_up / sf_down; if (sf_up == sf_down && sf_up != 1) { continue; } // I420 frame width and height must be even. if (dst_width & 1 || dst_height & 1) { continue; } ASSERT_NO_FATAL_FAILURE(ResetScaleImages( src_width, src_height, dst_width, dst_height)); ReferenceScaleFrame(filter_type, phase_scaler); ScaleFrame(filter_type, phase_scaler); PrintDiff(); CompareImages(dst_img_); DeallocScaleImages(); } } } } } } } void PrintDiffComponent(const uint8_t *const ref, const uint8_t *const opt, const int stride, const int width, const int height, const int plane_idx) const { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (ref[y * stride + x] != opt[y * stride + x]) { printf("Plane %d pixel[%d][%d] diff:%6d (ref),%6d (opt)\n", plane_idx, y, x, ref[y * stride + x], opt[y * stride + x]); break; } } } } void PrintDiff() const { assert(ref_img_.y_stride == dst_img_.y_stride); assert(ref_img_.y_width == dst_img_.y_width); assert(ref_img_.y_height == dst_img_.y_height); assert(ref_img_.uv_stride == dst_img_.uv_stride); assert(ref_img_.uv_width == dst_img_.uv_width); assert(ref_img_.uv_height == dst_img_.uv_height); if (memcmp(dst_img_.buffer_alloc, ref_img_.buffer_alloc, ref_img_.frame_size)) { PrintDiffComponent(ref_img_.y_buffer, dst_img_.y_buffer, ref_img_.y_stride, ref_img_.y_width, ref_img_.y_height, 0); PrintDiffComponent(ref_img_.u_buffer, dst_img_.u_buffer, ref_img_.uv_stride, ref_img_.uv_width, ref_img_.uv_height, 1); PrintDiffComponent(ref_img_.v_buffer, dst_img_.v_buffer, ref_img_.uv_stride, ref_img_.uv_width, ref_img_.uv_height, 2); } } ScaleFrameFunc scale_fn_; }; TEST_P(ScaleTest, ScaleFrame) { ASSERT_NO_FATAL_FAILURE(RunTest()); } TEST_P(ScaleTest, DISABLED_Speed) { static const int kCountSpeedTestBlock = 100; static const int kNumScaleFactorsToTest = 4; static const int kScaleFactors[] = { 1, 2, 3, 4 }; const int src_height = 1280; const int src_width = 720; for (INTERP_FILTER filter_type = 2; filter_type < 4; ++filter_type) { for (int phase_scaler = 0; phase_scaler < 2; ++phase_scaler) { for (int sf_up_idx = 0; sf_up_idx < kNumScaleFactorsToTest; ++sf_up_idx) { const int sf_up = kScaleFactors[sf_up_idx]; for (int sf_down_idx = 0; sf_down_idx < kNumScaleFactorsToTest; ++sf_down_idx) { const int sf_down = kScaleFactors[sf_down_idx]; const int dst_width = src_width * sf_up / sf_down; const int dst_height = src_height * sf_up / sf_down; if (sf_up == sf_down && sf_up != 1) { continue; } // I420 frame width and height must be even. if (dst_width & 1 || dst_height & 1) { continue; } ASSERT_NO_FATAL_FAILURE( ResetScaleImages(src_width, src_height, dst_width, dst_height)); ASM_REGISTER_STATE_CHECK( ReferenceScaleFrame(filter_type, phase_scaler)); vpx_usec_timer timer; vpx_usec_timer_start(&timer); for (int i = 0; i < kCountSpeedTestBlock; ++i) { ScaleFrame(filter_type, phase_scaler); } libvpx_test::ClearSystemState(); vpx_usec_timer_mark(&timer); const int elapsed_time = static_cast<int>(vpx_usec_timer_elapsed(&timer) / 1000); CompareImages(dst_img_); DeallocScaleImages(); printf( "filter_type = %d, phase_scaler = %d, src_width = %4d, " "src_height = %4d, dst_width = %4d, dst_height = %4d, " "scale factor = %d:%d, scale time: %5d ms\n", filter_type, phase_scaler, src_width, src_height, dst_width, dst_height, sf_down, sf_up, elapsed_time); } } } } } #if HAVE_SSSE3 INSTANTIATE_TEST_CASE_P(SSSE3, ScaleTest, ::testing::Values(vp9_scale_and_extend_frame_ssse3)); #endif // HAVE_SSSE3 #if HAVE_NEON INSTANTIATE_TEST_CASE_P(NEON, ScaleTest, ::testing::Values(vp9_scale_and_extend_frame_neon)); #endif // HAVE_NEON } // namespace libvpx_test
/* * Copyright (c) 2017 The WebM project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <assert.h> #include <stdio.h> #include <string.h> #include "third_party/googletest/src/include/gtest/gtest.h" #include "./vp9_rtcd.h" #include "./vpx_config.h" #include "./vpx_scale_rtcd.h" #include "test/clear_system_state.h" #include "test/register_state_check.h" #include "test/vpx_scale_test.h" #include "vpx_mem/vpx_mem.h" #include "vpx_ports/vpx_timer.h" #include "vpx_scale/yv12config.h" namespace libvpx_test { typedef void (*ScaleFrameFunc)(const YV12_BUFFER_CONFIG *src, YV12_BUFFER_CONFIG *dst, INTERP_FILTER filter_type, int phase_scaler); class ScaleTest : public VpxScaleBase, public ::testing::TestWithParam<ScaleFrameFunc> { public: virtual ~ScaleTest() {} protected: virtual void SetUp() { scale_fn_ = GetParam(); } void ReferenceScaleFrame(INTERP_FILTER filter_type, int phase_scaler) { vp9_scale_and_extend_frame_c(&img_, &ref_img_, filter_type, phase_scaler); } void ScaleFrame(INTERP_FILTER filter_type, int phase_scaler) { ASM_REGISTER_STATE_CHECK( scale_fn_(&img_, &dst_img_, filter_type, phase_scaler)); } void RunTest() { static const int kNumSizesToTest = 4; static const int kNumScaleFactorsToTest = 4; static const int kWidthsToTest[] = { 16, 32, 48, 64 }; static const int kHeightsToTest[] = { 16, 20, 24, 28 }; static const int kScaleFactors[] = { 1, 2, 3, 4 }; for (INTERP_FILTER filter_type = 0; filter_type < 4; ++filter_type) { for (int phase_scaler = 0; phase_scaler < 16; ++phase_scaler) { for (int h = 0; h < kNumSizesToTest; ++h) { const int src_height = kHeightsToTest[h]; for (int w = 0; w < kNumSizesToTest; ++w) { const int src_width = kWidthsToTest[w]; for (int sf_up_idx = 0; sf_up_idx < kNumScaleFactorsToTest; ++sf_up_idx) { const int sf_up = kScaleFactors[sf_up_idx]; for (int sf_down_idx = 0; sf_down_idx < kNumScaleFactorsToTest; ++sf_down_idx) { const int sf_down = kScaleFactors[sf_down_idx]; const int dst_width = src_width * sf_up / sf_down; const int dst_height = src_height * sf_up / sf_down; if (sf_up == sf_down && sf_up != 1) { continue; } // I420 frame width and height must be even. if (dst_width & 1 || dst_height & 1) { continue; } ASSERT_NO_FATAL_FAILURE(ResetScaleImages( src_width, src_height, dst_width, dst_height)); ReferenceScaleFrame(filter_type, phase_scaler); ScaleFrame(filter_type, phase_scaler); PrintDiff(); CompareImages(dst_img_); DeallocScaleImages(); } } } } } } } void PrintDiffComponent(const uint8_t *const ref, const uint8_t *const opt, const int stride, const int width, const int height, const int plane_idx) const { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { if (ref[y * stride + x] != opt[y * stride + x]) { printf("Plane %d pixel[%d][%d] diff:%6d (ref),%6d (opt)\n", plane_idx, y, x, ref[y * stride + x], opt[y * stride + x]); break; } } } } void PrintDiff() const { assert(ref_img_.y_stride == dst_img_.y_stride); assert(ref_img_.y_width == dst_img_.y_width); assert(ref_img_.y_height == dst_img_.y_height); assert(ref_img_.uv_stride == dst_img_.uv_stride); assert(ref_img_.uv_width == dst_img_.uv_width); assert(ref_img_.uv_height == dst_img_.uv_height); if (memcmp(dst_img_.buffer_alloc, ref_img_.buffer_alloc, ref_img_.frame_size)) { PrintDiffComponent(ref_img_.y_buffer, dst_img_.y_buffer, ref_img_.y_stride, ref_img_.y_width, ref_img_.y_height, 0); PrintDiffComponent(ref_img_.u_buffer, dst_img_.u_buffer, ref_img_.uv_stride, ref_img_.uv_width, ref_img_.uv_height, 1); PrintDiffComponent(ref_img_.v_buffer, dst_img_.v_buffer, ref_img_.uv_stride, ref_img_.uv_width, ref_img_.uv_height, 2); } } ScaleFrameFunc scale_fn_; }; TEST_P(ScaleTest, ScaleFrame) { ASSERT_NO_FATAL_FAILURE(RunTest()); } TEST_P(ScaleTest, DISABLED_Speed) { static const int kCountSpeedTestBlock = 100; static const int kNumScaleFactorsToTest = 4; static const int kScaleFactors[] = { 1, 2, 3, 4 }; const int src_height = 1280; const int src_width = 720; for (INTERP_FILTER filter_type = 2; filter_type < 4; ++filter_type) { for (int phase_scaler = 0; phase_scaler < 2; ++phase_scaler) { for (int sf_up_idx = 0; sf_up_idx < kNumScaleFactorsToTest; ++sf_up_idx) { const int sf_up = kScaleFactors[sf_up_idx]; for (int sf_down_idx = 0; sf_down_idx < kNumScaleFactorsToTest; ++sf_down_idx) { const int sf_down = kScaleFactors[sf_down_idx]; const int dst_width = src_width * sf_up / sf_down; const int dst_height = src_height * sf_up / sf_down; if (sf_up == sf_down && sf_up != 1) { continue; } // I420 frame width and height must be even. if (dst_width & 1 || dst_height & 1) { continue; } ASSERT_NO_FATAL_FAILURE( ResetScaleImages(src_width, src_height, dst_width, dst_height)); ASM_REGISTER_STATE_CHECK( ReferenceScaleFrame(filter_type, phase_scaler)); vpx_usec_timer timer; vpx_usec_timer_start(&timer); for (int i = 0; i < kCountSpeedTestBlock; ++i) { ScaleFrame(filter_type, phase_scaler); } libvpx_test::ClearSystemState(); vpx_usec_timer_mark(&timer); const int elapsed_time = static_cast<int>(vpx_usec_timer_elapsed(&timer) / 1000); CompareImages(dst_img_); DeallocScaleImages(); printf( "filter_type = %d, phase_scaler = %d, src_width = %4d, " "src_height = %4d, dst_width = %4d, dst_height = %4d, " "scale factor = %d:%d, scale time: %5d ms\n", filter_type, phase_scaler, src_width, src_height, dst_width, dst_height, sf_down, sf_up, elapsed_time); } } } } } INSTANTIATE_TEST_CASE_P(C, ScaleTest, ::testing::Values(vp9_scale_and_extend_frame_c)); #if HAVE_SSSE3 INSTANTIATE_TEST_CASE_P(SSSE3, ScaleTest, ::testing::Values(vp9_scale_and_extend_frame_ssse3)); #endif // HAVE_SSSE3 #if HAVE_NEON INSTANTIATE_TEST_CASE_P(NEON, ScaleTest, ::testing::Values(vp9_scale_and_extend_frame_neon)); #endif // HAVE_NEON } // namespace libvpx_test
add C config
vp9_scale_test: add C config Change-Id: I9dfe8255d1c096d246bf9719729f57dbae779ffc
C++
bsd-3-clause
ShiftMediaProject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx,webmproject/libvpx,ShiftMediaProject/libvpx,ShiftMediaProject/libvpx,webmproject/libvpx
0fc8f1f822b67a56c72dc574693ec439c47680e3
tests/FontHostTest.cpp
tests/FontHostTest.cpp
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkPaint.h" #include "SkFontStream.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkTypeface.h" #include "SkEndian.h" //#define DUMP_TABLES //#define DUMP_TTC_TABLES #define kFontTableTag_head SkSetFourByteTag('h', 'e', 'a', 'd') #define kFontTableTag_hhea SkSetFourByteTag('h', 'h', 'e', 'a') #define kFontTableTag_maxp SkSetFourByteTag('m', 'a', 'x', 'p') static const struct TagSize { SkFontTableTag fTag; size_t fSize; } gKnownTableSizes[] = { { kFontTableTag_head, 54 }, { kFontTableTag_hhea, 36 }, { kFontTableTag_maxp, 32 }, }; // Test that getUnitsPerEm() agrees with a direct lookup in the 'head' table // (if that table is available). static void test_unitsPerEm(skiatest::Reporter* reporter, SkTypeface* face) { int nativeUPEM = face->getUnitsPerEm(); int tableUPEM = -1; size_t size = face->getTableSize(kFontTableTag_head); if (size) { // unitsPerEm is at offset 18 into the 'head' table. uint16_t rawUPEM; face->getTableData(kFontTableTag_head, 18, sizeof(rawUPEM), &rawUPEM); tableUPEM = SkEndian_SwapBE16(rawUPEM); } if (tableUPEM >= 0) { REPORTER_ASSERT(reporter, tableUPEM == nativeUPEM); } else { // not sure this is a bug, but lets report it for now as info. SkDebugf("--- typeface returned 0 upem [%X]\n", face->uniqueID()); } } // Test that countGlyphs() agrees with a direct lookup in the 'maxp' table // (if that table is available). static void test_countGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { int nativeGlyphs = face->countGlyphs(); int tableGlyphs = -1; size_t size = face->getTableSize(kFontTableTag_maxp); if (size) { // glyphs is at offset 4 into the 'maxp' table. uint16_t rawGlyphs; face->getTableData(kFontTableTag_maxp, 4, sizeof(rawGlyphs), &rawGlyphs); tableGlyphs = SkEndian_SwapBE16(rawGlyphs); } if (tableGlyphs >= 0) { REPORTER_ASSERT(reporter, tableGlyphs == nativeGlyphs); } else { // not sure this is a bug, but lets report it for now as info. SkDebugf("--- typeface returned 0 glyphs [%X]\n", face->uniqueID()); } } // The following three are all the same code points in various encodings. static uint8_t utf8Chars[] = { 0x61, 0xE4, 0xB8, 0xAD, 0xD0, 0xAF, 0xD7, 0x99, 0xD7, 0x95, 0xF0, 0x9D, 0x84, 0x9E, 0x61 }; static uint16_t utf16Chars[] = { 0x0061, 0x4E2D, 0x042F, 0x05D9, 0x05D5, 0xD834, 0xDD1E, 0x0061 }; static uint32_t utf32Chars[] = { 0x00000061, 0x00004E2D, 0x0000042F, 0x000005D9, 0x000005D5, 0x0001D11E, 0x00000061 }; struct CharsToGlyphs_TestData { const void* chars; int charCount; size_t charsByteLength; SkTypeface::Encoding typefaceEncoding; const char* name; } static charsToGlyphs_TestData[] = { { utf8Chars, 7, sizeof(utf8Chars), SkTypeface::kUTF8_Encoding, "Simple UTF-8" }, { utf16Chars, 7, sizeof(utf16Chars), SkTypeface::kUTF16_Encoding, "Simple UTF-16" }, { utf32Chars, 7, sizeof(utf32Chars), SkTypeface::kUTF32_Encoding, "Simple UTF-32" }, }; // Test that SkPaint::textToGlyphs agrees with SkTypeface::charsToGlyphs. static void test_charsToGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { uint16_t paintGlyphIds[256]; uint16_t faceGlyphIds[256]; for (size_t testIndex = 0; testIndex < SK_ARRAY_COUNT(charsToGlyphs_TestData); ++testIndex) { CharsToGlyphs_TestData& test = charsToGlyphs_TestData[testIndex]; SkPaint paint; paint.setTypeface(face); paint.setTextEncoding((SkPaint::TextEncoding)test.typefaceEncoding); paint.textToGlyphs(test.chars, test.charsByteLength, paintGlyphIds); face->charsToGlyphs(test.chars, test.typefaceEncoding, faceGlyphIds, test.charCount); for (int i = 0; i < test.charCount; ++i) { SkString name; face->getFamilyName(&name); SkString a; a.appendf("%s, paintGlyphIds[%d] = %d, faceGlyphIds[%d] = %d, face = %s", test.name, i, (int)paintGlyphIds[i], i, (int)faceGlyphIds[i], name.c_str()); REPORTER_ASSERT_MESSAGE(reporter, paintGlyphIds[i] == faceGlyphIds[i], a.c_str()); } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream, int ttcIndex) { int n = SkFontStream::GetTableTags(stream, ttcIndex, NULL); SkAutoTArray<SkFontTableTag> array(n); int n2 = SkFontStream::GetTableTags(stream, ttcIndex, array.get()); REPORTER_ASSERT(reporter, n == n2); for (int i = 0; i < n; ++i) { #ifdef DUMP_TTC_TABLES SkString str; SkFontTableTag t = array[i]; str.appendUnichar((t >> 24) & 0xFF); str.appendUnichar((t >> 16) & 0xFF); str.appendUnichar((t >> 8) & 0xFF); str.appendUnichar((t >> 0) & 0xFF); SkDebugf("[%d:%d] '%s'\n", ttcIndex, i, str.c_str()); #endif size_t size = SkFontStream::GetTableSize(stream, ttcIndex, array[i]); for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == array[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream) { int count = SkFontStream::CountTTCEntries(stream); #ifdef DUMP_TTC_TABLES SkDebugf("CountTTCEntries %d\n", count); #endif for (int i = 0; i < count; ++i) { test_fontstream(reporter, stream, i); } } static void test_fontstream(skiatest::Reporter* reporter) { // This test cannot run if there is no resource path. SkString resourcePath = skiatest::Test::GetResourcePath(); if (resourcePath.isEmpty()) { SkDebugf("Could not run fontstream test because resourcePath not specified."); return; } SkString filename = SkOSPath::SkPathJoin(resourcePath.c_str(), "test.ttc"); SkFILEStream stream(filename.c_str()); if (stream.isValid()) { test_fontstream(reporter, &stream); } else { SkDebugf("Could not run fontstream test because test.ttc not found."); } } static void test_tables(skiatest::Reporter* reporter, SkTypeface* face) { if (false) { // avoid bit rot, suppress warning SkFontID fontID = face->uniqueID(); REPORTER_ASSERT(reporter, fontID); } int count = face->countTables(); SkAutoTMalloc<SkFontTableTag> storage(count); SkFontTableTag* tags = storage.get(); int count2 = face->getTableTags(tags); REPORTER_ASSERT(reporter, count2 == count); for (int i = 0; i < count; ++i) { size_t size = face->getTableSize(tags[i]); REPORTER_ASSERT(reporter, size > 0); #ifdef DUMP_TABLES char name[5]; name[0] = (tags[i] >> 24) & 0xFF; name[1] = (tags[i] >> 16) & 0xFF; name[2] = (tags[i] >> 8) & 0xFF; name[3] = (tags[i] >> 0) & 0xFF; name[4] = 0; SkDebugf("%s %d\n", name, size); #endif for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == tags[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } // do we get the same size from GetTableData and GetTableSize { SkAutoMalloc data(size); size_t size2 = face->getTableData(tags[i], 0, size, data.get()); REPORTER_ASSERT(reporter, size2 == size); } } } static void test_tables(skiatest::Reporter* reporter) { static const char* const gNames[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Terminal", "MS Sans Serif", }; for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal)); if (face) { #ifdef DUMP_TABLES SkDebugf("%s\n", gNames[i]); #endif test_tables(reporter, face); test_unitsPerEm(reporter, face); test_countGlyphs(reporter, face); test_charsToGlyphs(reporter, face); } } } /* * Verifies that the advance values returned by generateAdvance and * generateMetrics match. */ static void test_advances(skiatest::Reporter* reporter) { static const char* const faces[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Verdana", "monospace", }; static const struct { SkPaint::Hinting hinting; unsigned flags; } settings[] = { { SkPaint::kNo_Hinting, 0 }, { SkPaint::kNo_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNo_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kSlight_Hinting, 0 }, { SkPaint::kSlight_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kSlight_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kNormal_Hinting, 0 }, { SkPaint::kNormal_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNormal_Hinting, SkPaint::kSubpixelText_Flag }, }; static const struct { SkScalar fScaleX; SkScalar fSkewX; } gScaleRec[] = { { SK_Scalar1, 0 }, { SK_Scalar1/2, 0 }, // these two exercise obliquing (skew) { SK_Scalar1, -SK_Scalar1/4 }, { SK_Scalar1/2, -SK_Scalar1/4 }, }; SkPaint paint; char txt[] = "long.text.with.lots.of.dots."; for (size_t i = 0; i < SK_ARRAY_COUNT(faces); i++) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(faces[i], SkTypeface::kNormal)); paint.setTypeface(face); for (size_t j = 0; j < SK_ARRAY_COUNT(settings); j++) { paint.setHinting(settings[j].hinting); paint.setLinearText((settings[j].flags & SkPaint::kLinearText_Flag) != 0); paint.setSubpixelText((settings[j].flags & SkPaint::kSubpixelText_Flag) != 0); for (size_t k = 0; k < SK_ARRAY_COUNT(gScaleRec); ++k) { paint.setTextScaleX(gScaleRec[k].fScaleX); paint.setTextSkewX(gScaleRec[k].fSkewX); SkRect bounds; // For no hinting and light hinting this should take the // optimized generateAdvance path. SkScalar width1 = paint.measureText(txt, strlen(txt)); // Requesting the bounds forces a generateMetrics call. SkScalar width2 = paint.measureText(txt, strlen(txt), &bounds); // SkDebugf("Font: %s, generateAdvance: %f, generateMetrics: %f\n", // faces[i], SkScalarToFloat(width1), SkScalarToFloat(width2)); REPORTER_ASSERT(reporter, width1 == width2); } } } } static void TestFontHost(skiatest::Reporter* reporter) { test_tables(reporter); test_fontstream(reporter); test_advances(reporter); } // need tests for SkStrSearch #include "TestClassDef.h" DEFINE_TESTCLASS("FontHost", FontHostTestClass, TestFontHost)
/* * Copyright 2012 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "Test.h" #include "SkPaint.h" #include "SkFontStream.h" #include "SkOSFile.h" #include "SkStream.h" #include "SkTypeface.h" #include "SkEndian.h" //#define DUMP_TABLES //#define DUMP_TTC_TABLES #define kFontTableTag_head SkSetFourByteTag('h', 'e', 'a', 'd') #define kFontTableTag_hhea SkSetFourByteTag('h', 'h', 'e', 'a') #define kFontTableTag_maxp SkSetFourByteTag('m', 'a', 'x', 'p') static const struct TagSize { SkFontTableTag fTag; size_t fSize; } gKnownTableSizes[] = { { kFontTableTag_head, 54 }, { kFontTableTag_hhea, 36 }, { kFontTableTag_maxp, 32 }, }; // Test that getUnitsPerEm() agrees with a direct lookup in the 'head' table // (if that table is available). static void test_unitsPerEm(skiatest::Reporter* reporter, SkTypeface* face) { int nativeUPEM = face->getUnitsPerEm(); int tableUPEM = -1; size_t size = face->getTableSize(kFontTableTag_head); if (size) { // unitsPerEm is at offset 18 into the 'head' table. uint16_t rawUPEM; face->getTableData(kFontTableTag_head, 18, sizeof(rawUPEM), &rawUPEM); tableUPEM = SkEndian_SwapBE16(rawUPEM); } if (tableUPEM >= 0) { REPORTER_ASSERT(reporter, tableUPEM == nativeUPEM); } else { // not sure this is a bug, but lets report it for now as info. SkDebugf("--- typeface returned 0 upem [%X]\n", face->uniqueID()); } } // Test that countGlyphs() agrees with a direct lookup in the 'maxp' table // (if that table is available). static void test_countGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { int nativeGlyphs = face->countGlyphs(); int tableGlyphs = -1; size_t size = face->getTableSize(kFontTableTag_maxp); if (size) { // glyphs is at offset 4 into the 'maxp' table. uint16_t rawGlyphs; face->getTableData(kFontTableTag_maxp, 4, sizeof(rawGlyphs), &rawGlyphs); tableGlyphs = SkEndian_SwapBE16(rawGlyphs); } if (tableGlyphs >= 0) { REPORTER_ASSERT(reporter, tableGlyphs == nativeGlyphs); } else { // not sure this is a bug, but lets report it for now as info. SkDebugf("--- typeface returned 0 glyphs [%X]\n", face->uniqueID()); } } // The following three are all the same code points in various encodings. static uint8_t utf8Chars[] = { 0x61, 0xE4, 0xB8, 0xAD, 0xD0, 0xAF, 0xD7, 0x99, 0xD7, 0x95, 0xF0, 0x9D, 0x84, 0x9E, 0x61 }; static uint16_t utf16Chars[] = { 0x0061, 0x4E2D, 0x042F, 0x05D9, 0x05D5, 0xD834, 0xDD1E, 0x0061 }; static uint32_t utf32Chars[] = { 0x00000061, 0x00004E2D, 0x0000042F, 0x000005D9, 0x000005D5, 0x0001D11E, 0x00000061 }; struct CharsToGlyphs_TestData { const void* chars; int charCount; size_t charsByteLength; SkTypeface::Encoding typefaceEncoding; const char* name; } static charsToGlyphs_TestData[] = { { utf8Chars, 7, sizeof(utf8Chars), SkTypeface::kUTF8_Encoding, "Simple UTF-8" }, { utf16Chars, 7, sizeof(utf16Chars), SkTypeface::kUTF16_Encoding, "Simple UTF-16" }, { utf32Chars, 7, sizeof(utf32Chars), SkTypeface::kUTF32_Encoding, "Simple UTF-32" }, }; // Test that SkPaint::textToGlyphs agrees with SkTypeface::charsToGlyphs. static void test_charsToGlyphs(skiatest::Reporter* reporter, SkTypeface* face) { uint16_t paintGlyphIds[256]; uint16_t faceGlyphIds[256]; for (size_t testIndex = 0; testIndex < SK_ARRAY_COUNT(charsToGlyphs_TestData); ++testIndex) { CharsToGlyphs_TestData& test = charsToGlyphs_TestData[testIndex]; SkPaint paint; paint.setTypeface(face); paint.setTextEncoding((SkPaint::TextEncoding)test.typefaceEncoding); paint.textToGlyphs(test.chars, test.charsByteLength, paintGlyphIds); face->charsToGlyphs(test.chars, test.typefaceEncoding, faceGlyphIds, test.charCount); for (int i = 0; i < test.charCount; ++i) { SkString name; face->getFamilyName(&name); SkString a; a.appendf("%s, paintGlyphIds[%d] = %d, faceGlyphIds[%d] = %d, face = %s", test.name, i, (int)paintGlyphIds[i], i, (int)faceGlyphIds[i], name.c_str()); REPORTER_ASSERT_MESSAGE(reporter, paintGlyphIds[i] == faceGlyphIds[i], a.c_str()); } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream, int ttcIndex) { int n = SkFontStream::GetTableTags(stream, ttcIndex, NULL); SkAutoTArray<SkFontTableTag> array(n); int n2 = SkFontStream::GetTableTags(stream, ttcIndex, array.get()); REPORTER_ASSERT(reporter, n == n2); for (int i = 0; i < n; ++i) { #ifdef DUMP_TTC_TABLES SkString str; SkFontTableTag t = array[i]; str.appendUnichar((t >> 24) & 0xFF); str.appendUnichar((t >> 16) & 0xFF); str.appendUnichar((t >> 8) & 0xFF); str.appendUnichar((t >> 0) & 0xFF); SkDebugf("[%d:%d] '%s'\n", ttcIndex, i, str.c_str()); #endif size_t size = SkFontStream::GetTableSize(stream, ttcIndex, array[i]); for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == array[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } } } static void test_fontstream(skiatest::Reporter* reporter, SkStream* stream) { int count = SkFontStream::CountTTCEntries(stream); #ifdef DUMP_TTC_TABLES SkDebugf("CountTTCEntries %d\n", count); #endif for (int i = 0; i < count; ++i) { test_fontstream(reporter, stream, i); } } static void test_fontstream(skiatest::Reporter* reporter) { // This test cannot run if there is no resource path. SkString resourcePath = skiatest::Test::GetResourcePath(); if (resourcePath.isEmpty()) { SkDebugf("Could not run fontstream test because resourcePath not specified."); return; } SkString filename = SkOSPath::SkPathJoin(resourcePath.c_str(), "test.ttc"); SkFILEStream stream(filename.c_str()); if (stream.isValid()) { test_fontstream(reporter, &stream); } else { SkDebugf("Could not run fontstream test because test.ttc not found."); } } static void test_tables(skiatest::Reporter* reporter, SkTypeface* face) { if (false) { // avoid bit rot, suppress warning SkFontID fontID = face->uniqueID(); REPORTER_ASSERT(reporter, fontID); } int count = face->countTables(); SkAutoTMalloc<SkFontTableTag> storage(count); SkFontTableTag* tags = storage.get(); int count2 = face->getTableTags(tags); REPORTER_ASSERT(reporter, count2 == count); for (int i = 0; i < count; ++i) { size_t size = face->getTableSize(tags[i]); REPORTER_ASSERT(reporter, size > 0); #ifdef DUMP_TABLES char name[5]; name[0] = (tags[i] >> 24) & 0xFF; name[1] = (tags[i] >> 16) & 0xFF; name[2] = (tags[i] >> 8) & 0xFF; name[3] = (tags[i] >> 0) & 0xFF; name[4] = 0; SkDebugf("%s %d\n", name, size); #endif for (size_t j = 0; j < SK_ARRAY_COUNT(gKnownTableSizes); ++j) { if (gKnownTableSizes[j].fTag == tags[i]) { REPORTER_ASSERT(reporter, gKnownTableSizes[j].fSize == size); } } // do we get the same size from GetTableData and GetTableSize { SkAutoMalloc data(size); size_t size2 = face->getTableData(tags[i], 0, size, data.get()); REPORTER_ASSERT(reporter, size2 == size); } } } static void test_tables(skiatest::Reporter* reporter) { static const char* const gNames[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Terminal", "MS Sans Serif", }; for (size_t i = 0; i < SK_ARRAY_COUNT(gNames); ++i) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(gNames[i], SkTypeface::kNormal)); if (face) { #ifdef DUMP_TABLES SkDebugf("%s\n", gNames[i]); #endif test_tables(reporter, face); test_unitsPerEm(reporter, face); test_countGlyphs(reporter, face); //test_charsToGlyphs(reporter, face); } } } /* * Verifies that the advance values returned by generateAdvance and * generateMetrics match. */ static void test_advances(skiatest::Reporter* reporter) { static const char* const faces[] = { NULL, // default font "Arial", "Times", "Times New Roman", "Helvetica", "Courier", "Courier New", "Verdana", "monospace", }; static const struct { SkPaint::Hinting hinting; unsigned flags; } settings[] = { { SkPaint::kNo_Hinting, 0 }, { SkPaint::kNo_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNo_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kSlight_Hinting, 0 }, { SkPaint::kSlight_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kSlight_Hinting, SkPaint::kSubpixelText_Flag }, { SkPaint::kNormal_Hinting, 0 }, { SkPaint::kNormal_Hinting, SkPaint::kLinearText_Flag }, { SkPaint::kNormal_Hinting, SkPaint::kSubpixelText_Flag }, }; static const struct { SkScalar fScaleX; SkScalar fSkewX; } gScaleRec[] = { { SK_Scalar1, 0 }, { SK_Scalar1/2, 0 }, // these two exercise obliquing (skew) { SK_Scalar1, -SK_Scalar1/4 }, { SK_Scalar1/2, -SK_Scalar1/4 }, }; SkPaint paint; char txt[] = "long.text.with.lots.of.dots."; for (size_t i = 0; i < SK_ARRAY_COUNT(faces); i++) { SkAutoTUnref<SkTypeface> face(SkTypeface::CreateFromName(faces[i], SkTypeface::kNormal)); paint.setTypeface(face); for (size_t j = 0; j < SK_ARRAY_COUNT(settings); j++) { paint.setHinting(settings[j].hinting); paint.setLinearText((settings[j].flags & SkPaint::kLinearText_Flag) != 0); paint.setSubpixelText((settings[j].flags & SkPaint::kSubpixelText_Flag) != 0); for (size_t k = 0; k < SK_ARRAY_COUNT(gScaleRec); ++k) { paint.setTextScaleX(gScaleRec[k].fScaleX); paint.setTextSkewX(gScaleRec[k].fSkewX); SkRect bounds; // For no hinting and light hinting this should take the // optimized generateAdvance path. SkScalar width1 = paint.measureText(txt, strlen(txt)); // Requesting the bounds forces a generateMetrics call. SkScalar width2 = paint.measureText(txt, strlen(txt), &bounds); // SkDebugf("Font: %s, generateAdvance: %f, generateMetrics: %f\n", // faces[i], SkScalarToFloat(width1), SkScalarToFloat(width2)); REPORTER_ASSERT(reporter, width1 == width2); } } } } static void TestFontHost(skiatest::Reporter* reporter) { test_tables(reporter); test_fontstream(reporter); test_advances(reporter); } // need tests for SkStrSearch #include "TestClassDef.h" DEFINE_TESTCLASS("FontHost", FontHostTestClass, TestFontHost)
Disable charsToGlyphs test until Mac can pass.
Disable charsToGlyphs test until Mac can pass. git-svn-id: e8541e15acce502a64c929015570ad1648e548cd@11960 2bbb7eff-a529-9590-31e7-b0007b416f81
C++
bsd-3-clause
nfxosp/platform_external_skia,MinimalOS/external_skia,MyAOSP/external_chromium_org_third_party_skia,samuelig/skia,nox/skia,akiss77/skia,mydongistiny/external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,AndroidOpenDevelopment/android_external_skia,samuelig/skia,todotodoo/skia,MinimalOS/external_chromium_org_third_party_skia,samuelig/skia,fire855/android_external_skia,w3nd1go/android_external_skia,MarshedOut/android_external_skia,pcwalton/skia,BrokenROM/external_skia,HalCanary/skia-hc,nvoron23/skia,AOSP-YU/platform_external_skia,nvoron23/skia,suyouxin/android_external_skia,HalCanary/skia-hc,YUPlayGodDev/platform_external_skia,mmatyas/skia,AOSPA-L/android_external_skia,Hikari-no-Tenshi/android_external_skia,aospo/platform_external_skia,codeaurora-unoffical/platform-external-skia,ench0/external_skia,akiss77/skia,Khaon/android_external_skia,HalCanary/skia-hc,sombree/android_external_skia,zhaochengw/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,nvoron23/skia,InfinitiveOS/external_skia,jtg-gg/skia,Euphoria-OS-Legacy/android_external_skia,rubenvb/skia,Igalia/skia,Purity-Lollipop/platform_external_skia,Fusion-Rom/android_external_skia,AOSPB/external_skia,AOSPB/external_skia,VentureROM-L/android_external_skia,MarshedOut/android_external_skia,byterom/android_external_skia,Fusion-Rom/external_chromium_org_third_party_skia,shahrzadmn/skia,MinimalOS/android_external_chromium_org_third_party_skia,F-AOSP/platform_external_skia,noselhq/skia,HalCanary/skia-hc,Fusion-Rom/external_chromium_org_third_party_skia,pacerom/external_skia,Omegaphora/external_skia,TeamEOS/external_chromium_org_third_party_skia,boulzordev/android_external_skia,TeslaOS/android_external_skia,mydongistiny/android_external_skia,MarshedOut/android_external_skia,Android-AOSP/external_skia,TeamEOS/external_chromium_org_third_party_skia,noselhq/skia,temasek/android_external_skia,todotodoo/skia,TeslaOS/android_external_skia,fire855/android_external_skia,byterom/android_external_skia,samuelig/skia,suyouxin/android_external_skia,YUPlayGodDev/platform_external_skia,boulzordev/android_external_skia,Hikari-no-Tenshi/android_external_skia,google/skia,GladeRom/android_external_skia,PAC-ROM/android_external_skia,aospo/platform_external_skia,YUPlayGodDev/platform_external_skia,byterom/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,MinimalOS/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,chenlian2015/skia_from_google,MinimalOS/android_external_skia,FusionSP/android_external_skia,HealthyHoney/temasek_SKIA,pacerom/external_skia,zhaochengw/platform_external_skia,timduru/platform-external-skia,MonkeyZZZZ/platform_external_skia,wildermason/external_skia,PAC-ROM/android_external_skia,TeslaOS/android_external_skia,RadonX-ROM/external_skia,Jichao/skia,Purity-Lollipop/platform_external_skia,amyvmiwei/skia,invisiblek/android_external_skia,spezi77/android_external_skia,Fusion-Rom/android_external_skia,OneRom/external_skia,MarshedOut/android_external_skia,mmatyas/skia,sombree/android_external_skia,DesolationStaging/android_external_skia,TeslaOS/android_external_skia,HealthyHoney/temasek_SKIA,mmatyas/skia,MyAOSP/external_chromium_org_third_party_skia,pacerom/external_skia,invisiblek/android_external_skia,rubenvb/skia,vvuk/skia,MyAOSP/external_chromium_org_third_party_skia,pcwalton/skia,timduru/platform-external-skia,samuelig/skia,MyAOSP/external_chromium_org_third_party_skia,NamelessRom/android_external_skia,scroggo/skia,boulzordev/android_external_skia,OneRom/external_skia,larsbergstrom/skia,MarshedOut/android_external_skia,sudosurootdev/external_skia,qrealka/skia-hc,vanish87/skia,Samsung/skia,MonkeyZZZZ/platform_external_skia,w3nd1go/android_external_skia,UBERMALLOW/external_skia,Android-AOSP/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,TeslaProject/external_skia,SlimSaber/android_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,Omegaphora/external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,boulzordev/android_external_skia,larsbergstrom/skia,MIPS/external-chromium_org-third_party-skia,AOSPB/external_skia,rubenvb/skia,Samsung/skia,boulzordev/android_external_skia,NamelessRom/android_external_skia,google/skia,mydongistiny/android_external_skia,Android-AOSP/external_skia,google/skia,wildermason/external_skia,MinimalOS-AOSP/platform_external_skia,vanish87/skia,AOSP-YU/platform_external_skia,akiss77/skia,codeaurora-unoffical/platform-external-skia,CyanogenMod/android_external_chromium_org_third_party_skia,ominux/skia,OptiPop/external_skia,Igalia/skia,TeamEOS/external_chromium_org_third_party_skia,houst0nn/external_skia,qrealka/skia-hc,MyAOSP/external_chromium_org_third_party_skia,HalCanary/skia-hc,Tesla-Redux/android_external_skia,HalCanary/skia-hc,Omegaphora/external_chromium_org_third_party_skia,FusionSP/android_external_skia,nox/skia,InfinitiveOS/external_skia,MonkeyZZZZ/platform_external_skia,DesolationStaging/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,jtg-gg/skia,wildermason/external_skia,Hikari-no-Tenshi/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,vvuk/skia,SlimSaber/android_external_skia,boulzordev/android_external_skia,AsteroidOS/android_external_skia,AOSP-YU/platform_external_skia,DesolationStaging/android_external_skia,Omegaphora/external_skia,Pure-Aosp/android_external_skia,amyvmiwei/skia,OneRom/external_skia,vvuk/skia,DiamondLovesYou/skia-sys,Jichao/skia,UBERMALLOW/external_skia,Plain-Andy/android_platform_external_skia,DesolationStaging/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,Asteroid-Project/android_external_skia,VRToxin-AOSP/android_external_skia,AOSPU/external_chromium_org_third_party_skia,TeamEOS/external_skia,TeamExodus/external_skia,byterom/android_external_skia,mydongistiny/external_chromium_org_third_party_skia,MyAOSP/external_chromium_org_third_party_skia,xzzz9097/android_external_skia,MinimalOS/android_external_skia,RadonX-ROM/external_skia,ench0/external_chromium_org_third_party_skia,sombree/android_external_skia,MinimalOS/android_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,SlimSaber/android_external_skia,ench0/external_skia,noselhq/skia,aosp-mirror/platform_external_skia,Asteroid-Project/android_external_skia,nfxosp/platform_external_skia,nvoron23/skia,Omegaphora/external_chromium_org_third_party_skia,DiamondLovesYou/skia-sys,DiamondLovesYou/skia-sys,TeslaProject/external_skia,TeamTwisted/external_skia,suyouxin/android_external_skia,geekboxzone/mmallow_external_skia,rubenvb/skia,ominux/skia,Fusion-Rom/external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,AsteroidOS/android_external_skia,zhaochengw/platform_external_skia,sudosurootdev/external_skia,tmpvar/skia.cc,akiss77/skia,vanish87/skia,VRToxin-AOSP/android_external_skia,UBERMALLOW/external_skia,Khaon/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,mozilla-b2g/external_skia,timduru/platform-external-skia,geekboxzone/lollipop_external_skia,pacerom/external_skia,wildermason/external_skia,OptiPop/external_chromium_org_third_party_skia,TeamEOS/external_skia,Purity-Lollipop/platform_external_skia,Igalia/skia,android-ia/platform_external_chromium_org_third_party_skia,mmatyas/skia,SlimSaber/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,ctiao/platform-external-skia,MarshedOut/android_external_skia,vanish87/skia,ominux/skia,MonkeyZZZZ/platform_external_skia,byterom/android_external_skia,GladeRom/android_external_skia,AsteroidOS/android_external_skia,MinimalOS/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,scroggo/skia,xzzz9097/android_external_skia,OptiPop/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,android-ia/platform_external_chromium_org_third_party_skia,temasek/android_external_skia,Pure-Aosp/android_external_skia,sigysmund/platform_external_skia,NamelessRom/android_external_skia,ominux/skia,NamelessRom/android_external_skia,Hikari-no-Tenshi/android_external_skia,TeamBliss-LP/android_external_skia,pcwalton/skia,SlimSaber/android_external_skia,sudosurootdev/external_skia,mydongistiny/android_external_skia,codeaurora-unoffical/platform-external-skia,FusionSP/android_external_skia,qrealka/skia-hc,sigysmund/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,AndroidOpenDevelopment/android_external_skia,AndroidOpenDevelopment/android_external_skia,FusionSP/external_chromium_org_third_party_skia,OptiPop/external_chromium_org_third_party_skia,google/skia,ominux/skia,Tesla-Redux/android_external_skia,VRToxin-AOSP/android_external_skia,Fusion-Rom/android_external_skia,VentureROM-L/android_external_skia,F-AOSP/platform_external_skia,SlimSaber/android_external_skia,aospo/platform_external_skia,amyvmiwei/skia,TeslaOS/android_external_skia,vvuk/skia,MonkeyZZZZ/platform_external_skia,OneRom/external_skia,RadonX-ROM/external_skia,AOSPB/external_skia,aospo/platform_external_skia,MIPS/external-chromium_org-third_party-skia,PAC-ROM/android_external_skia,pcwalton/skia,FusionSP/android_external_skia,TeamExodus/external_skia,todotodoo/skia,codeaurora-unoffical/platform-external-skia,F-AOSP/platform_external_skia,ench0/external_chromium_org_third_party_skia,Pure-Aosp/android_external_skia,InfinitiveOS/external_skia,android-ia/platform_external_skia,Infusion-OS/android_external_skia,Tesla-Redux/android_external_skia,aosp-mirror/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,mmatyas/skia,qrealka/skia-hc,YUPlayGodDev/platform_external_skia,amyvmiwei/skia,akiss77/skia,Omegaphora/external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,geekboxzone/mmallow_external_skia,Fusion-Rom/android_external_skia,Purity-Lollipop/platform_external_skia,fire855/android_external_skia,pcwalton/skia,boulzordev/android_external_skia,HealthyHoney/temasek_SKIA,Tesla-Redux/android_external_skia,Khaon/android_external_skia,jtg-gg/skia,Asteroid-Project/android_external_skia,Igalia/skia,samuelig/skia,houst0nn/external_skia,RadonX-ROM/external_skia,sudosurootdev/external_skia,Infinitive-OS/platform_external_skia,Purity-Lollipop/platform_external_skia,AOSP-YU/platform_external_skia,noselhq/skia,HalCanary/skia-hc,zhaochengw/platform_external_skia,Android-AOSP/external_skia,Hybrid-Rom/external_skia,sudosurootdev/external_skia,AsteroidOS/android_external_skia,TeslaOS/android_external_skia,mozilla-b2g/external_skia,aosp-mirror/platform_external_skia,mydongistiny/android_external_skia,chenlian2015/skia_from_google,MarshedOut/android_external_skia,NamelessRom/android_external_skia,android-ia/platform_external_skia,mydongistiny/external_chromium_org_third_party_skia,TeamTwisted/external_skia,Infusion-OS/android_external_skia,geekboxzone/mmallow_external_skia,NamelessRom/android_external_skia,noselhq/skia,sombree/android_external_skia,sigysmund/platform_external_skia,mozilla-b2g/external_skia,MIPS/external-chromium_org-third_party-skia,Jichao/skia,aospo/platform_external_skia,tmpvar/skia.cc,VentureROM-L/android_external_skia,TeamTwisted/external_skia,nfxosp/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,VentureROM-L/android_external_skia,GladeRom/android_external_skia,Jichao/skia,YUPlayGodDev/platform_external_skia,TeslaOS/android_external_skia,AOSPU/external_chromium_org_third_party_skia,Fusion-Rom/android_external_skia,GladeRom/android_external_skia,Khaon/android_external_skia,VentureROM-L/android_external_skia,invisiblek/android_external_skia,Android-AOSP/external_skia,GladeRom/android_external_skia,chenlian2015/skia_from_google,AsteroidOS/android_external_skia,geekboxzone/lollipop_external_skia,Euphoria-OS-Legacy/android_external_skia,TeamTwisted/external_skia,TeslaProject/external_skia,FusionSP/android_external_skia,OptiPop/external_chromium_org_third_party_skia,Jichao/skia,MarshedOut/android_external_skia,noselhq/skia,w3nd1go/android_external_skia,TeamExodus/external_skia,Hybrid-Rom/external_skia,temasek/android_external_skia,MonkeyZZZZ/platform_external_skia,DiamondLovesYou/skia-sys,amyvmiwei/skia,invisiblek/android_external_skia,Pure-Aosp/android_external_skia,aosp-mirror/platform_external_skia,AsteroidOS/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,BrokenROM/external_skia,TeamEOS/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Plain-Andy/android_platform_external_skia,scroggo/skia,Infinitive-OS/platform_external_skia,byterom/android_external_skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,DesolationStaging/android_external_skia,DARKPOP/external_chromium_org_third_party_skia,byterom/android_external_skia,DiamondLovesYou/skia-sys,geekboxzone/lollipop_external_chromium_org_third_party_skia,nox/skia,ench0/external_skia,Infinitive-OS/platform_external_skia,Igalia/skia,Infinitive-OS/platform_external_skia,scroggo/skia,chenlian2015/skia_from_google,HalCanary/skia-hc,RadonX-ROM/external_skia,Infinitive-OS/platform_external_skia,akiss77/skia,todotodoo/skia,Pure-Aosp/android_external_skia,Purity-Lollipop/platform_external_skia,SlimSaber/android_external_skia,TeslaOS/android_external_skia,Plain-Andy/android_platform_external_skia,MinimalOS/external_skia,timduru/platform-external-skia,Infinitive-OS/platform_external_skia,VRToxin-AOSP/android_external_skia,sombree/android_external_skia,qrealka/skia-hc,vanish87/skia,spezi77/android_external_skia,Khaon/android_external_skia,nvoron23/skia,nfxosp/platform_external_skia,fire855/android_external_skia,larsbergstrom/skia,TeslaProject/external_skia,ench0/external_chromium_org_third_party_skia,codeaurora-unoffical/platform-external-skia,BrokenROM/external_skia,mozilla-b2g/external_skia,Hikari-no-Tenshi/android_external_skia,wildermason/external_skia,nvoron23/skia,android-ia/platform_external_skia,Euphoria-OS-Legacy/android_external_skia,TeslaProject/external_skia,MyAOSP/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,BrokenROM/external_skia,invisiblek/android_external_skia,MonkeyZZZZ/platform_external_skia,geekboxzone/lollipop_external_skia,MinimalOS-AOSP/platform_external_skia,F-AOSP/platform_external_skia,Omegaphora/external_chromium_org_third_party_skia,spezi77/android_external_skia,MinimalOS/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,TeslaProject/external_skia,temasek/android_external_skia,RadonX-ROM/external_skia,MinimalOS-AOSP/platform_external_skia,Purity-Lollipop/platform_external_skia,sigysmund/platform_external_skia,MinimalOS/external_skia,Omegaphora/external_chromium_org_third_party_skia,ctiao/platform-external-skia,VentureROM-L/android_external_skia,OptiPop/external_skia,NamelessRom/android_external_skia,TeamExodus/external_skia,MinimalOS/android_external_skia,houst0nn/external_skia,AOSPB/external_skia,TeamEOS/external_skia,FusionSP/android_external_skia,mmatyas/skia,qrealka/skia-hc,houst0nn/external_skia,ench0/external_skia,UBERMALLOW/external_skia,pcwalton/skia,InfinitiveOS/external_skia,TeamEOS/external_skia,AOSPU/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,TeamTwisted/external_skia,MinimalOS/external_chromium_org_third_party_skia,pacerom/external_skia,w3nd1go/android_external_skia,TeamExodus/external_skia,OneRom/external_skia,google/skia,Omegaphora/external_skia,Plain-Andy/android_platform_external_skia,shahrzadmn/skia,pacerom/external_skia,geekboxzone/lollipop_external_skia,TeamTwisted/external_skia,google/skia,google/skia,aospo/platform_external_skia,Infusion-OS/android_external_skia,Fusion-Rom/android_external_skia,OneRom/external_skia,Omegaphora/external_skia,boulzordev/android_external_skia,YUPlayGodDev/platform_external_skia,noselhq/skia,Infusion-OS/android_external_skia,Khaon/android_external_skia,wildermason/external_skia,Samsung/skia,MIPS/external-chromium_org-third_party-skia,shahrzadmn/skia,TeamEOS/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,FusionSP/external_chromium_org_third_party_skia,scroggo/skia,Fusion-Rom/external_chromium_org_third_party_skia,YUPlayGodDev/platform_external_skia,TeamExodus/external_skia,android-ia/platform_external_skia,GladeRom/android_external_skia,rubenvb/skia,DARKPOP/external_chromium_org_third_party_skia,scroggo/skia,AndroidOpenDevelopment/android_external_skia,larsbergstrom/skia,xzzz9097/android_external_skia,FusionSP/external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,timduru/platform-external-skia,TeamExodus/external_skia,android-ia/platform_external_skia,jtg-gg/skia,Samsung/skia,geekboxzone/mmallow_external_skia,pcwalton/skia,ctiao/platform-external-skia,Hikari-no-Tenshi/android_external_skia,AOSPA-L/android_external_skia,sombree/android_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Fusion-Rom/external_chromium_org_third_party_skia,TeamExodus/external_skia,rubenvb/skia,jtg-gg/skia,wildermason/external_skia,Igalia/skia,HalCanary/skia-hc,PAC-ROM/android_external_skia,amyvmiwei/skia,MinimalOS-AOSP/platform_external_skia,android-ia/platform_external_chromium_org_third_party_skia,OptiPop/external_skia,ominux/skia,scroggo/skia,todotodoo/skia,samuelig/skia,Khaon/android_external_skia,PAC-ROM/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,MinimalOS/android_external_chromium_org_third_party_skia,vanish87/skia,MinimalOS/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,TeamEOS/external_skia,F-AOSP/platform_external_skia,mozilla-b2g/external_skia,PAC-ROM/android_external_skia,Asteroid-Project/android_external_skia,todotodoo/skia,rubenvb/skia,ctiao/platform-external-skia,mydongistiny/external_chromium_org_third_party_skia,chenlian2015/skia_from_google,TeamTwisted/external_skia,google/skia,ctiao/platform-external-skia,AndroidOpenDevelopment/android_external_skia,mmatyas/skia,TeamEOS/external_skia,pacerom/external_skia,geekboxzone/mmallow_external_skia,mmatyas/skia,Fusion-Rom/external_chromium_org_third_party_skia,nox/skia,AOSP-YU/platform_external_skia,invisiblek/android_external_skia,vvuk/skia,Plain-Andy/android_platform_external_skia,noselhq/skia,nfxosp/platform_external_skia,MinimalOS-AOSP/platform_external_skia,android-ia/platform_external_skia,OptiPop/external_skia,spezi77/android_external_skia,ench0/external_chromium_org_third_party_skia,jtg-gg/skia,Omegaphora/external_chromium_org_third_party_skia,temasek/android_external_skia,vanish87/skia,rubenvb/skia,Samsung/skia,mydongistiny/android_external_skia,UBERMALLOW/external_skia,mmatyas/skia,Omegaphora/external_skia,MinimalOS/external_skia,BrokenROM/external_skia,OptiPop/external_chromium_org_third_party_skia,TeamTwisted/external_skia,Jichao/skia,aospo/platform_external_skia,ctiao/platform-external-skia,CyanogenMod/android_external_chromium_org_third_party_skia,AOSPA-L/android_external_skia,AOSPU/external_chromium_org_third_party_skia,todotodoo/skia,Hybrid-Rom/external_skia,akiss77/skia,MinimalOS/external_chromium_org_third_party_skia,sudosurootdev/external_skia,larsbergstrom/skia,ominux/skia,MIPS/external-chromium_org-third_party-skia,MarshedOut/android_external_skia,nox/skia,Jichao/skia,NamelessRom/android_external_skia,VRToxin-AOSP/android_external_skia,OneRom/external_skia,suyouxin/android_external_skia,xzzz9097/android_external_skia,OneRom/external_skia,Omegaphora/external_skia,ench0/external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,ctiao/platform-external-skia,google/skia,AOSPA-L/android_external_skia,todotodoo/skia,fire855/android_external_skia,codeaurora-unoffical/platform-external-skia,Fusion-Rom/android_external_skia,timduru/platform-external-skia,android-ia/platform_external_chromium_org_third_party_skia,Tesla-Redux/android_external_skia,akiss77/skia,HealthyHoney/temasek_SKIA,AndroidOpenDevelopment/android_external_skia,UBERMALLOW/external_skia,VentureROM-L/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,aosp-mirror/platform_external_skia,Infinitive-OS/platform_external_skia,TeamEOS/external_skia,ench0/external_chromium_org_third_party_skia,AOSPU/external_chromium_org_third_party_skia,mozilla-b2g/external_skia,nvoron23/skia,TeslaProject/external_skia,TeamEOS/external_chromium_org_third_party_skia,vvuk/skia,vanish87/skia,Hybrid-Rom/external_skia,Asteroid-Project/android_external_skia,pcwalton/skia,AsteroidOS/android_external_skia,Euphoria-OS-Legacy/android_external_skia,Igalia/skia,pcwalton/skia,sigysmund/platform_external_skia,AOSPB/external_skia,mydongistiny/android_external_skia,MinimalOS/external_chromium_org_third_party_skia,PAC-ROM/android_external_skia,jtg-gg/skia,Tesla-Redux/android_external_skia,samuelig/skia,Plain-Andy/android_platform_external_skia,VRToxin-AOSP/android_external_skia,fire855/android_external_skia,shahrzadmn/skia,Infusion-OS/android_external_skia,FusionSP/external_chromium_org_third_party_skia,MonkeyZZZZ/platform_external_skia,tmpvar/skia.cc,ench0/external_skia,OptiPop/external_skia,temasek/android_external_skia,MinimalOS-AOSP/platform_external_skia,OptiPop/external_chromium_org_third_party_skia,InfinitiveOS/external_skia,ominux/skia,MinimalOS-AOSP/platform_external_skia,sigysmund/platform_external_skia,spezi77/android_external_skia,sombree/android_external_skia,Samsung/skia,tmpvar/skia.cc,nox/skia,InfinitiveOS/external_skia,TeamBliss-LP/android_external_skia,nvoron23/skia,TeslaProject/external_skia,nfxosp/platform_external_skia,mozilla-b2g/external_skia,GladeRom/android_external_skia,geekboxzone/lollipop_external_skia,xin3liang/platform_external_chromium_org_third_party_skia,Hybrid-Rom/external_skia,amyvmiwei/skia,F-AOSP/platform_external_skia,MinimalOS/android_external_skia,AOSPA-L/android_external_skia,tmpvar/skia.cc,mozilla-b2g/external_skia,MinimalOS/android_external_chromium_org_third_party_skia,suyouxin/android_external_skia,scroggo/skia,tmpvar/skia.cc,codeaurora-unoffical/platform-external-skia,AOSPU/external_chromium_org_third_party_skia,DARKPOP/external_chromium_org_third_party_skia,geekboxzone/lollipop_external_skia,OptiPop/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,rubenvb/skia,xin3liang/platform_external_chromium_org_third_party_skia,VRToxin-AOSP/android_external_skia,nvoron23/skia,Hybrid-Rom/external_skia,VRToxin-AOSP/android_external_skia,chenlian2015/skia_from_google,OptiPop/external_skia,Fusion-Rom/android_external_skia,AOSP-YU/platform_external_skia,w3nd1go/android_external_skia,Euphoria-OS-Legacy/android_external_skia,sigysmund/platform_external_skia,houst0nn/external_skia,Samsung/skia,android-ia/platform_external_skia,MinimalOS-AOSP/platform_external_skia,DiamondLovesYou/skia-sys,aospo/platform_external_skia,Infusion-OS/android_external_skia,fire855/android_external_skia,byterom/android_external_skia,android-ia/platform_external_chromium_org_third_party_skia,MinimalOS/external_skia,AOSPU/external_chromium_org_third_party_skia,AOSP-YU/platform_external_skia,spezi77/android_external_skia,ench0/external_chromium_org_third_party_skia,larsbergstrom/skia,MinimalOS/external_skia,FusionSP/android_external_skia,F-AOSP/platform_external_skia,MinimalOS/external_skia,suyouxin/android_external_skia,Pure-Aosp/android_external_skia,Asteroid-Project/android_external_skia,MinimalOS/external_skia,PAC-ROM/android_external_skia,vanish87/skia,HalCanary/skia-hc,mydongistiny/external_chromium_org_third_party_skia,RadonX-ROM/external_skia,geekboxzone/mmallow_external_skia,tmpvar/skia.cc,qrealka/skia-hc,VentureROM-L/android_external_skia,AOSPB/external_skia,mydongistiny/android_external_skia,Hybrid-Rom/external_skia,vvuk/skia,Tesla-Redux/android_external_skia,sombree/android_external_skia,vvuk/skia,MinimalOS/android_external_chromium_org_third_party_skia,w3nd1go/android_external_skia,zhaochengw/platform_external_skia,w3nd1go/android_external_skia,Pure-Aosp/android_external_skia,Infinitive-OS/platform_external_skia,SlimSaber/android_external_skia,houst0nn/external_skia,nox/skia,sudosurootdev/external_skia,Plain-Andy/android_platform_external_skia,xzzz9097/android_external_skia,fire855/android_external_skia,FusionSP/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,shahrzadmn/skia,mydongistiny/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,Euphoria-OS-Legacy/android_external_skia,MinimalOS/android_external_skia,AOSPA-L/android_external_skia,TeamExodus/external_skia,android-ia/platform_external_skia,CyanogenMod/android_external_chromium_org_third_party_skia,nox/skia,MinimalOS/external_chromium_org_third_party_skia,zhaochengw/platform_external_skia,AOSPB/external_skia,ench0/external_skia,Pure-Aosp/android_external_skia,TeamBliss-LP/android_external_skia,geekboxzone/lollipop_external_skia,mydongistiny/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,larsbergstrom/skia,DesolationStaging/android_external_skia,OptiPop/external_skia,Omegaphora/external_skia,Asteroid-Project/android_external_skia,wildermason/external_skia,ench0/external_skia,HealthyHoney/temasek_SKIA,F-AOSP/platform_external_skia,TeamBliss-LP/android_external_skia,InfinitiveOS/external_skia,sudosurootdev/external_skia,mydongistiny/external_chromium_org_third_party_skia,Hikari-no-Tenshi/android_external_skia,xzzz9097/android_external_skia,AOSPA-L/android_external_skia,HealthyHoney/temasek_SKIA,geekboxzone/lollipop_external_skia,geekboxzone/mmallow_external_skia,UBERMALLOW/external_skia,TeamEOS/external_chromium_org_third_party_skia,TeamBliss-LP/android_external_skia,UBERMALLOW/external_skia,google/skia,Euphoria-OS-Legacy/android_external_skia,rubenvb/skia,Infusion-OS/android_external_skia,MinimalOS-AOSP/platform_external_skia,qrealka/skia-hc,invisiblek/android_external_skia,chenlian2015/skia_from_google,FusionSP/external_chromium_org_third_party_skia,MonkeyZZZZ/platform_external_skia,houst0nn/external_skia,GladeRom/android_external_skia,HealthyHoney/temasek_SKIA,temasek/android_external_skia,Tesla-Redux/android_external_skia,OneRom/external_skia,Purity-Lollipop/platform_external_skia,MIPS/external-chromium_org-third_party-skia,invisiblek/android_external_skia,nox/skia,AOSPB/external_skia,Infinitive-OS/platform_external_skia,DARKPOP/external_chromium_org_third_party_skia,OptiPop/external_skia,UBERMALLOW/external_skia,Samsung/skia,MIPS/external-chromium_org-third_party-skia,ench0/external_chromium_org_third_party_skia,nfxosp/platform_external_skia,YUPlayGodDev/platform_external_skia,BrokenROM/external_skia,MIPS/external-chromium_org-third_party-skia,aosp-mirror/platform_external_skia,vvuk/skia,tmpvar/skia.cc,Android-AOSP/external_skia,MyAOSP/external_chromium_org_third_party_skia,larsbergstrom/skia,mydongistiny/android_external_skia,Asteroid-Project/android_external_skia,temasek/android_external_skia,DesolationStaging/android_external_skia,Android-AOSP/external_skia,shahrzadmn/skia,DiamondLovesYou/skia-sys,FusionSP/external_chromium_org_third_party_skia,larsbergstrom/skia,amyvmiwei/skia,timduru/platform-external-skia,MinimalOS/external_chromium_org_third_party_skia,DesolationStaging/android_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Khaon/android_external_skia,TeamTwisted/external_skia,Igalia/skia,xin3liang/platform_external_chromium_org_third_party_skia,shahrzadmn/skia,zhaochengw/platform_external_skia,suyouxin/android_external_skia,shahrzadmn/skia,w3nd1go/android_external_skia,tmpvar/skia.cc,todotodoo/skia,ominux/skia,AsteroidOS/android_external_skia,shahrzadmn/skia,akiss77/skia,w3nd1go/android_external_skia,Jichao/skia,InfinitiveOS/external_skia,HealthyHoney/temasek_SKIA,sigysmund/platform_external_skia,zhaochengw/platform_external_skia,AndroidOpenDevelopment/android_external_skia,xzzz9097/android_external_skia,TeamEOS/external_chromium_org_third_party_skia,boulzordev/android_external_skia,noselhq/skia,BrokenROM/external_skia,BrokenROM/external_skia,geekboxzone/mmallow_external_skia,OptiPop/external_chromium_org_third_party_skia,Omegaphora/external_skia,codeaurora-unoffical/platform-external-skia,AOSP-YU/platform_external_skia,geekboxzone/lollipop_external_chromium_org_third_party_skia,Infusion-OS/android_external_skia,xzzz9097/android_external_skia,ench0/external_skia,Jichao/skia,xin3liang/platform_external_chromium_org_third_party_skia,CyanogenMod/android_external_chromium_org_third_party_skia
0b87d16699698ce46208087a9ea15389e66cd0a9
tests/compound_test.cc
tests/compound_test.cc
/* * 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/>. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include "compound.hh" #include "compound_compat.hh" #include "tests/range_assert.hh" #include "disk-error-handler.hh" thread_local disk_error_signal_type commit_error; thread_local disk_error_signal_type general_disk_error; static std::vector<bytes> to_bytes_vec(std::vector<sstring> values) { std::vector<bytes> result; for (auto&& v : values) { result.emplace_back(to_bytes(v)); } return result; } template <typename Compound> static range_assert<typename Compound::iterator> assert_that_components(Compound& t, bytes packed) { return assert_that_range(t.begin(packed), t.end(packed)); } template <typename Compound> static void test_sequence(Compound& t, std::vector<sstring> strings) { auto packed = t.serialize_value(to_bytes_vec(strings)); assert_that_components(t, packed).equals(to_bytes_vec(strings)); }; BOOST_AUTO_TEST_CASE(test_iteration_over_non_prefixable_tuple) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type, bytes_type}); test_sequence(t, {"el1", "el2", "el3"}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"", "el2", "el3"}); test_sequence(t, {"el1", "", ""}); test_sequence(t, {"", "", "el3"}); test_sequence(t, {"el1", "", "el3"}); test_sequence(t, {"", "", ""}); } BOOST_AUTO_TEST_CASE(test_iteration_over_prefixable_tuple) { compound_type<allow_prefixes::yes> t({bytes_type, bytes_type, bytes_type}); test_sequence(t, {"el1", "el2", "el3"}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"", "el2", "el3"}); test_sequence(t, {"el1", "", ""}); test_sequence(t, {"", "", "el3"}); test_sequence(t, {"el1", "", "el3"}); test_sequence(t, {"", "", ""}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"el1", "el2"}); test_sequence(t, {"el1", ""}); test_sequence(t, {"el1"}); test_sequence(t, {""}); test_sequence(t, {}); } BOOST_AUTO_TEST_CASE(test_iteration_over_non_prefixable_singular_tuple) { compound_type<allow_prefixes::no> t({bytes_type}); test_sequence(t, {"el1"}); test_sequence(t, {""}); } BOOST_AUTO_TEST_CASE(test_iteration_over_prefixable_singular_tuple) { compound_type<allow_prefixes::yes> t({bytes_type}); test_sequence(t, {"elem1"}); test_sequence(t, {""}); test_sequence(t, {}); } template <allow_prefixes AllowPrefixes> void do_test_conversion_methods_for_singular_compound() { compound_type<AllowPrefixes> t({bytes_type}); { assert_that_components(t, t.serialize_value(to_bytes_vec({"asd"}))) // r-value version .equals(to_bytes_vec({"asd"})); } { auto vec = to_bytes_vec({"asd"}); assert_that_components(t, t.serialize_value(vec)) // l-value version .equals(to_bytes_vec({"asd"})); } { std::vector<bytes_opt> vec = { bytes_opt("asd") }; assert_that_components(t, t.serialize_optionals(vec)) .equals(to_bytes_vec({"asd"})); } { std::vector<bytes_opt> vec = { bytes_opt("asd") }; assert_that_components(t, t.serialize_optionals(std::move(vec))) // r-value .equals(to_bytes_vec({"asd"})); } { assert_that_components(t, t.serialize_single(bytes("asd"))) .equals(to_bytes_vec({"asd"})); } } BOOST_AUTO_TEST_CASE(test_conversion_methods_for_singular_compound) { do_test_conversion_methods_for_singular_compound<allow_prefixes::yes>(); do_test_conversion_methods_for_singular_compound<allow_prefixes::no>(); } template <allow_prefixes AllowPrefixes> void do_test_conversion_methods_for_non_singular_compound() { compound_type<AllowPrefixes> t({bytes_type, bytes_type, bytes_type}); { assert_that_components(t, t.serialize_value(to_bytes_vec({"el1", "el2", "el2"}))) // r-value version .equals(to_bytes_vec({"el1", "el2", "el2"})); } { auto vec = to_bytes_vec({"el1", "el2", "el3"}); assert_that_components(t, t.serialize_value(vec)) // l-value version .equals(to_bytes_vec({"el1", "el2", "el3"})); } { std::vector<bytes_opt> vec = { bytes_opt("el1"), bytes_opt("el2"), bytes_opt("el3") }; assert_that_components(t, t.serialize_optionals(vec)) .equals(to_bytes_vec({"el1", "el2", "el3"})); } { std::vector<bytes_opt> vec = { bytes_opt("el1"), bytes_opt("el2"), bytes_opt("el3") }; assert_that_components(t, t.serialize_optionals(std::move(vec))) // r-value .equals(to_bytes_vec({"el1", "el2", "el3"})); } } BOOST_AUTO_TEST_CASE(test_conversion_methods_for_non_singular_compound) { do_test_conversion_methods_for_non_singular_compound<allow_prefixes::yes>(); do_test_conversion_methods_for_non_singular_compound<allow_prefixes::no>(); } BOOST_AUTO_TEST_CASE(test_component_iterator_post_incrementation) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type, bytes_type}); auto packed = t.serialize_value(to_bytes_vec({"el1", "el2", "el3"})); auto i = t.begin(packed); auto end = t.end(packed); BOOST_REQUIRE_EQUAL(to_bytes("el1"), *i++); BOOST_REQUIRE_EQUAL(to_bytes("el2"), *i++); BOOST_REQUIRE_EQUAL(to_bytes("el3"), *i++); BOOST_REQUIRE(i == end); } BOOST_AUTO_TEST_CASE(test_conversion_to_legacy_form) { compound_type<allow_prefixes::no> singular({bytes_type}); BOOST_REQUIRE_EQUAL(to_legacy(singular, singular.serialize_single(to_bytes("asd"))), bytes("asd")); BOOST_REQUIRE_EQUAL(to_legacy(singular, singular.serialize_single(to_bytes(""))), bytes("")); compound_type<allow_prefixes::no> two_components({bytes_type, bytes_type}); BOOST_REQUIRE_EQUAL(to_legacy(two_components, two_components.serialize_value(to_bytes_vec({"el1", "elem2"}))), bytes({'\x00', '\x03', 'e', 'l', '1', '\x00', '\x00', '\x05', 'e', 'l', 'e', 'm', '2', '\x00'})); BOOST_REQUIRE_EQUAL(to_legacy(two_components, two_components.serialize_value(to_bytes_vec({"el1", ""}))), bytes({'\x00', '\x03', 'e', 'l', '1', '\x00', '\x00', '\x00', '\x00'})); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_of_singular) { compound_type<allow_prefixes::no> t({bytes_type}); auto make = [&t] (sstring value) -> bytes { return t.serialize_single(to_bytes(value)); }; legacy_compound_view<decltype(t)>::tri_comparator cmp(t); BOOST_REQUIRE(cmp(make("A"), make("B")) < 0); BOOST_REQUIRE(cmp(make("AA"), make("B")) < 0); BOOST_REQUIRE(cmp(make("B"), make("AB")) > 0); BOOST_REQUIRE(cmp(make("B"), make("A")) > 0); BOOST_REQUIRE(cmp(make("A"), make("A")) == 0); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_of_composites) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type}); auto make = [&t] (sstring v1, sstring v2) -> bytes { return t.serialize_value(std::vector<bytes>{to_bytes(v1), to_bytes(v2)}); }; legacy_compound_view<decltype(t)>::tri_comparator cmp(t); BOOST_REQUIRE(cmp(make("A", "B"), make("A", "B")) == 0); BOOST_REQUIRE(cmp(make("A", "B"), make("A", "C")) < 0); BOOST_REQUIRE(cmp(make("A", "B"), make("B", "B")) < 0); BOOST_REQUIRE(cmp(make("A", "C"), make("B", "B")) < 0); BOOST_REQUIRE(cmp(make("B", "A"), make("A", "A")) > 0); BOOST_REQUIRE(cmp(make("AA", "B"), make("B", "B")) > 0); BOOST_REQUIRE(cmp(make("A", "AA"), make("A", "A")) > 0); BOOST_REQUIRE(cmp(make("", "A"), make("A", "A")) < 0); BOOST_REQUIRE(cmp(make("A", ""), make("A", "A")) < 0); }
/* * 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/>. */ #define BOOST_TEST_DYN_LINK #define BOOST_TEST_MODULE core #include <boost/test/unit_test.hpp> #include "compound.hh" #include "compound_compat.hh" #include "tests/range_assert.hh" #include "schema_builder.hh" #include "disk-error-handler.hh" thread_local disk_error_signal_type commit_error; thread_local disk_error_signal_type general_disk_error; static std::vector<bytes> to_bytes_vec(std::vector<sstring> values) { std::vector<bytes> result; for (auto&& v : values) { result.emplace_back(to_bytes(v)); } return result; } template <typename Compound> static range_assert<typename Compound::iterator> assert_that_components(Compound& t, bytes packed) { return assert_that_range(t.begin(packed), t.end(packed)); } template <typename Compound> static void test_sequence(Compound& t, std::vector<sstring> strings) { auto packed = t.serialize_value(to_bytes_vec(strings)); assert_that_components(t, packed).equals(to_bytes_vec(strings)); }; BOOST_AUTO_TEST_CASE(test_iteration_over_non_prefixable_tuple) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type, bytes_type}); test_sequence(t, {"el1", "el2", "el3"}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"", "el2", "el3"}); test_sequence(t, {"el1", "", ""}); test_sequence(t, {"", "", "el3"}); test_sequence(t, {"el1", "", "el3"}); test_sequence(t, {"", "", ""}); } BOOST_AUTO_TEST_CASE(test_iteration_over_prefixable_tuple) { compound_type<allow_prefixes::yes> t({bytes_type, bytes_type, bytes_type}); test_sequence(t, {"el1", "el2", "el3"}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"", "el2", "el3"}); test_sequence(t, {"el1", "", ""}); test_sequence(t, {"", "", "el3"}); test_sequence(t, {"el1", "", "el3"}); test_sequence(t, {"", "", ""}); test_sequence(t, {"el1", "el2", ""}); test_sequence(t, {"el1", "el2"}); test_sequence(t, {"el1", ""}); test_sequence(t, {"el1"}); test_sequence(t, {""}); test_sequence(t, {}); } BOOST_AUTO_TEST_CASE(test_iteration_over_non_prefixable_singular_tuple) { compound_type<allow_prefixes::no> t({bytes_type}); test_sequence(t, {"el1"}); test_sequence(t, {""}); } BOOST_AUTO_TEST_CASE(test_iteration_over_prefixable_singular_tuple) { compound_type<allow_prefixes::yes> t({bytes_type}); test_sequence(t, {"elem1"}); test_sequence(t, {""}); test_sequence(t, {}); } template <allow_prefixes AllowPrefixes> void do_test_conversion_methods_for_singular_compound() { compound_type<AllowPrefixes> t({bytes_type}); { assert_that_components(t, t.serialize_value(to_bytes_vec({"asd"}))) // r-value version .equals(to_bytes_vec({"asd"})); } { auto vec = to_bytes_vec({"asd"}); assert_that_components(t, t.serialize_value(vec)) // l-value version .equals(to_bytes_vec({"asd"})); } { std::vector<bytes_opt> vec = { bytes_opt("asd") }; assert_that_components(t, t.serialize_optionals(vec)) .equals(to_bytes_vec({"asd"})); } { std::vector<bytes_opt> vec = { bytes_opt("asd") }; assert_that_components(t, t.serialize_optionals(std::move(vec))) // r-value .equals(to_bytes_vec({"asd"})); } { assert_that_components(t, t.serialize_single(bytes("asd"))) .equals(to_bytes_vec({"asd"})); } } BOOST_AUTO_TEST_CASE(test_conversion_methods_for_singular_compound) { do_test_conversion_methods_for_singular_compound<allow_prefixes::yes>(); do_test_conversion_methods_for_singular_compound<allow_prefixes::no>(); } template <allow_prefixes AllowPrefixes> void do_test_conversion_methods_for_non_singular_compound() { compound_type<AllowPrefixes> t({bytes_type, bytes_type, bytes_type}); { assert_that_components(t, t.serialize_value(to_bytes_vec({"el1", "el2", "el2"}))) // r-value version .equals(to_bytes_vec({"el1", "el2", "el2"})); } { auto vec = to_bytes_vec({"el1", "el2", "el3"}); assert_that_components(t, t.serialize_value(vec)) // l-value version .equals(to_bytes_vec({"el1", "el2", "el3"})); } { std::vector<bytes_opt> vec = { bytes_opt("el1"), bytes_opt("el2"), bytes_opt("el3") }; assert_that_components(t, t.serialize_optionals(vec)) .equals(to_bytes_vec({"el1", "el2", "el3"})); } { std::vector<bytes_opt> vec = { bytes_opt("el1"), bytes_opt("el2"), bytes_opt("el3") }; assert_that_components(t, t.serialize_optionals(std::move(vec))) // r-value .equals(to_bytes_vec({"el1", "el2", "el3"})); } } BOOST_AUTO_TEST_CASE(test_conversion_methods_for_non_singular_compound) { do_test_conversion_methods_for_non_singular_compound<allow_prefixes::yes>(); do_test_conversion_methods_for_non_singular_compound<allow_prefixes::no>(); } BOOST_AUTO_TEST_CASE(test_component_iterator_post_incrementation) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type, bytes_type}); auto packed = t.serialize_value(to_bytes_vec({"el1", "el2", "el3"})); auto i = t.begin(packed); auto end = t.end(packed); BOOST_REQUIRE_EQUAL(to_bytes("el1"), *i++); BOOST_REQUIRE_EQUAL(to_bytes("el2"), *i++); BOOST_REQUIRE_EQUAL(to_bytes("el3"), *i++); BOOST_REQUIRE(i == end); } BOOST_AUTO_TEST_CASE(test_conversion_to_legacy_form) { compound_type<allow_prefixes::no> singular({bytes_type}); BOOST_REQUIRE_EQUAL(to_legacy(singular, singular.serialize_single(to_bytes("asd"))), bytes("asd")); BOOST_REQUIRE_EQUAL(to_legacy(singular, singular.serialize_single(to_bytes(""))), bytes("")); compound_type<allow_prefixes::no> two_components({bytes_type, bytes_type}); BOOST_REQUIRE_EQUAL(to_legacy(two_components, two_components.serialize_value(to_bytes_vec({"el1", "elem2"}))), bytes({'\x00', '\x03', 'e', 'l', '1', '\x00', '\x00', '\x05', 'e', 'l', 'e', 'm', '2', '\x00'})); BOOST_REQUIRE_EQUAL(to_legacy(two_components, two_components.serialize_value(to_bytes_vec({"el1", ""}))), bytes({'\x00', '\x03', 'e', 'l', '1', '\x00', '\x00', '\x00', '\x00'})); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_of_singular) { compound_type<allow_prefixes::no> t({bytes_type}); auto make = [&t] (sstring value) -> bytes { return t.serialize_single(to_bytes(value)); }; legacy_compound_view<decltype(t)>::tri_comparator cmp(t); BOOST_REQUIRE(cmp(make("A"), make("B")) < 0); BOOST_REQUIRE(cmp(make("AA"), make("B")) < 0); BOOST_REQUIRE(cmp(make("B"), make("AB")) > 0); BOOST_REQUIRE(cmp(make("B"), make("A")) > 0); BOOST_REQUIRE(cmp(make("A"), make("A")) == 0); } BOOST_AUTO_TEST_CASE(test_legacy_ordering_of_composites) { compound_type<allow_prefixes::no> t({bytes_type, bytes_type}); auto make = [&t] (sstring v1, sstring v2) -> bytes { return t.serialize_value(std::vector<bytes>{to_bytes(v1), to_bytes(v2)}); }; legacy_compound_view<decltype(t)>::tri_comparator cmp(t); BOOST_REQUIRE(cmp(make("A", "B"), make("A", "B")) == 0); BOOST_REQUIRE(cmp(make("A", "B"), make("A", "C")) < 0); BOOST_REQUIRE(cmp(make("A", "B"), make("B", "B")) < 0); BOOST_REQUIRE(cmp(make("A", "C"), make("B", "B")) < 0); BOOST_REQUIRE(cmp(make("B", "A"), make("A", "A")) > 0); BOOST_REQUIRE(cmp(make("AA", "B"), make("B", "B")) > 0); BOOST_REQUIRE(cmp(make("A", "AA"), make("A", "A")) > 0); BOOST_REQUIRE(cmp(make("", "A"), make("A", "A")) < 0); BOOST_REQUIRE(cmp(make("A", ""), make("A", "A")) < 0); } BOOST_AUTO_TEST_CASE(test_enconding_of_legacy_composites) { using components = std::vector<composite::component>; BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x03', 'e', 'l', '1', '\x00'})).components(), components({std::make_pair(bytes("el1"), composite::eoc::none)})); BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x00', '\x01'})).components(), components({std::make_pair(bytes(""), composite::eoc::end)})); BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x05', 'e', 'l', 'e', 'm', '1', '\xff'})).components(), components({std::make_pair(bytes("elem1"), composite::eoc::start)})); BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x03', 'e', 'l', '1', '\x05'})).components(), components({std::make_pair(bytes("el1"), composite::eoc::end)})); BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x03', 'e', 'l', '1', '\x00', '\x00', '\x05', 'e', 'l', 'e', 'm', '2', '\x01'})).components(), components({std::make_pair(bytes("el1"), composite::eoc::none), std::make_pair(bytes("elem2"), composite::eoc::end)})); BOOST_REQUIRE_EQUAL(composite(bytes({'\x00', '\x03', 'e', 'l', '1', '\xff', '\x00', '\x00', '\x01'})).components(), components({std::make_pair(bytes("el1"), composite::eoc::start), std::make_pair(bytes(""), composite::eoc::end)})); } BOOST_AUTO_TEST_CASE(test_enconding_of_singular_composite) { using components = std::vector<composite::component>; BOOST_REQUIRE_EQUAL(composite(bytes({'e', 'l', '1'}), false).components(), components({std::make_pair(bytes("el1"), composite::eoc::none)})); BOOST_REQUIRE_EQUAL(composite(composite::serialize_value(std::vector<bytes>({bytes({'e', 'l', '1'})}), false), false).components(), components({std::make_pair(bytes("el1"), composite::eoc::none)})); } BOOST_AUTO_TEST_CASE(test_enconding_of_static_composite) { using components = std::vector<composite::component>; auto s = schema_builder("ks", "cf") .with_column("pk", bytes_type, column_kind::partition_key) .with_column("ck", bytes_type, column_kind::clustering_key) .with_column("v", bytes_type, column_kind::regular_column) .build(); auto c = composite::static_prefix(*s); BOOST_REQUIRE(c.is_static()); components cs; for (auto&& p : c.components()) { cs.push_back(std::make_pair(to_bytes(p.first), p.second)); } BOOST_REQUIRE_EQUAL(cs, components({std::make_pair(bytes(""), composite::eoc::none)})); } BOOST_AUTO_TEST_CASE(test_composite_serialize_value) { BOOST_REQUIRE_EQUAL(composite::serialize_value(std::vector<bytes>({bytes({'e', 'l', '1'})})), bytes({'\x00', '\x03', 'e', 'l', '1', '\x00'})); } BOOST_AUTO_TEST_CASE(test_composite_from_exploded) { using components = std::vector<composite::component>; BOOST_REQUIRE_EQUAL(composite::from_exploded({bytes_view(bytes({'e', 'l', '1'}))}, composite::eoc::start).components(), components({std::make_pair(bytes("el1"), composite::eoc::start)})); } BOOST_AUTO_TEST_CASE(test_composite_view_explode) { BOOST_REQUIRE_EQUAL(composite_view(composite(bytes({'\x00', '\x03', 'e', 'l', '1', '\x00'}))).explode(), std::vector<bytes>({bytes({'e', 'l', '1'})})); }
Add unit tests
composite: Add unit tests Signed-off-by: Duarte Nunes <[email protected]>
C++
agpl-3.0
duarten/scylla,kjniemi/scylla,scylladb/scylla,raphaelsc/scylla,avikivity/scylla,avikivity/scylla,kjniemi/scylla,avikivity/scylla,raphaelsc/scylla,scylladb/scylla,kjniemi/scylla,scylladb/scylla,raphaelsc/scylla,duarten/scylla,duarten/scylla,scylladb/scylla
67520ab61ec49b2aae0911bf7fe834125fb0651e
tests/pointer_test.cpp
tests/pointer_test.cpp
/* pointer_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 20 Apr 2014 FreeBSD-style copyright and disclaimer apply Tests for pointer reflection. Note: Disabled tests are the ones that are currently failing due to lackluster pointer support. \todo Pointers aren't const-checked at the moment. Turns out that this is rather difficult to get right because with pointers we get multi-layering of constness which makes it impossible to have a single bool represent const-ness. As an example: int const* * const* & int * const* * const& Should they both be const? What would that even mean? What we'd need is a list of argument objects that understands both pointer and references. But that's just way too complicated for the small feature gain we'd get. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "test_types.h" #include "types/primitives.h" #include "types/std/smart_ptr.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; /******************************************************************************/ /* BASICS */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(basics) { const Type* tPtr = type<int*>(); std::cerr << tPtr->print() << std::endl; BOOST_CHECK_EQUAL(type<int const*>(), tPtr); BOOST_CHECK(tPtr->isPointer()); BOOST_CHECK_EQUAL(tPtr->pointer(), "*"); BOOST_CHECK_EQUAL(tPtr->pointee(), type<int>()); const Type* tPtrPtr = type<int**>(); BOOST_CHECK(tPtrPtr->isPointer()); BOOST_CHECK_EQUAL(tPtrPtr->pointer(), "*"); BOOST_CHECK_EQUAL(tPtrPtr->pointee(), tPtr); BOOST_CHECK_EQUAL(type<int const* const*>(), tPtrPtr); BOOST_CHECK_EQUAL(type<int * const*>(), tPtrPtr); BOOST_CHECK_EQUAL(type<int const* *>(), tPtrPtr); } /******************************************************************************/ /* POINTER */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(pointer_test) { typedef test::Object Obj; auto doPtr = [] (Obj* obj) { return obj; }; Function ptrFn("ptr", doPtr); auto doPtrPtr = [] (Obj** obj) { return obj; }; Function ptrPtrFn("ptrPtr", doPtrPtr); auto doConstPtr = [] (Obj const* const obj) { return obj; }; Function constPtrFn("constPtr", doConstPtr); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj * )>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj ** )>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<Obj (Obj*)>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<Obj * (Obj*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<Obj ** (Obj*)>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<Obj const*(Obj*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj * )>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj ** )>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj (Obj**)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj * (Obj**)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj ** (Obj**)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj const*(Obj**)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj * )>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj ** )>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<Obj (Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<Obj * (Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<Obj ** (Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<Obj const*(Obj const*)>(), Match::Exact); } BOOST_AUTO_TEST_CASE(pointer_call) { typedef test::Object Obj; auto doPtr = [] (Obj* obj) { return obj; }; Function ptrFn("ptr", doPtr); auto doPtrPtr = [] (Obj** obj) { return obj; }; Function ptrPtrFn("ptrPtr", doPtrPtr); auto doConstPtr = [] (Obj const* const obj) { return obj; }; Function constPtrFn("constPtr", doConstPtr); Obj o; Obj* po = &o; Obj** ppo = &po; Obj const* cpo = &o; BOOST_CHECK_THROW(ptrFn.call<Obj*>(o ), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(po ), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj*>(ppo), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(cpo), doPtr(po)); // Not an error. BOOST_CHECK_THROW(ptrFn.call<Obj*>(Value(o )), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(Value(po )), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj*>(Value(ppo)), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(Value(cpo)), doPtr(po)); // not an error. BOOST_CHECK_THROW(ptrFn.call<Obj >(po), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj * >(po), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj ** >(po), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj const*>(po), doPtr(po)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(o ), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(po ), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj**>(ppo), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(cpo), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(o )), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(po )), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj**>(Value(ppo)), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(cpo)), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj >(ppo), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj * >(ppo), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj ** >(ppo), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj const*>(ppo), ReflectError); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(o ), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(po ), doConstPtr(po)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(ppo), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(cpo), doConstPtr(cpo)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(Value(o )), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(Value(po )), doConstPtr(po)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(Value(ppo)), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(Value(cpo)), doConstPtr(cpo)); BOOST_CHECK_THROW(constPtrFn.call<Obj >(cpo), ReflectError); constPtrFn.call<Obj * >(cpo); BOOST_CHECK_THROW(constPtrFn.call<Obj ** >(cpo), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(cpo), doConstPtr(cpo)); } /******************************************************************************/ /* SHARED PTR */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(sharedPtr) { typedef test::NotConstructible Obj; const Type* tSharedPtr = type< std::shared_ptr<Obj> >(); std::cerr << tSharedPtr->print() << std::endl; BOOST_CHECK(tSharedPtr->isPointer()); BOOST_CHECK_EQUAL(tSharedPtr->pointee(), type<Obj>()); Obj* po = Obj::make(); Value vSharedPtr = tSharedPtr->construct(po); BOOST_CHECK_THROW(vSharedPtr.get< std::shared_ptr<int> >(), ReflectError); auto& obj = (*vSharedPtr).get<Obj>(); auto& sharedPtr = vSharedPtr.get< std::shared_ptr<Obj> >(); BOOST_CHECK(vSharedPtr); // operator bool() BOOST_CHECK(vSharedPtr == sharedPtr); // operator== BOOST_CHECK_EQUAL(&obj, po); BOOST_CHECK_EQUAL(sharedPtr.get(), po); BOOST_CHECK_EQUAL(vSharedPtr.call<Obj*>("get"), po); vSharedPtr.call<void>("reset", Obj::make()); BOOST_CHECK(vSharedPtr); // operator bool() BOOST_CHECK_NE(vSharedPtr.call<Obj*>("get"), po); vSharedPtr.call<void>("reset"); BOOST_CHECK(!vSharedPtr); // operator bool() BOOST_CHECK(vSharedPtr.call<Obj*>("get") == nullptr); } /******************************************************************************/ /* UNIQUE PTR */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(uniquePtr) { typedef test::NotConstructible Obj; const Type* tUniquePtr = type< std::unique_ptr<Obj> >(); std::cerr << tUniquePtr->print() << std::endl; BOOST_CHECK(tUniquePtr->isPointer()); BOOST_CHECK_EQUAL(tUniquePtr->pointee(), type<Obj>()); Obj* po = Obj::make(); Value vUniquePtr = tUniquePtr->construct(po); BOOST_CHECK_THROW(vUniquePtr.get< std::unique_ptr<int> >(), ReflectError); auto& obj = (*vUniquePtr).get<Obj>(); auto& uniquePtr = vUniquePtr.get< std::unique_ptr<Obj> >(); BOOST_CHECK(vUniquePtr); // operator bool() BOOST_CHECK(vUniquePtr == uniquePtr); // operator== BOOST_CHECK_EQUAL(&obj, po); BOOST_CHECK_EQUAL(uniquePtr.get(), po); BOOST_CHECK_EQUAL(vUniquePtr.call<Obj*>("get"), po); vUniquePtr.call<void>("reset", Obj::make()); BOOST_CHECK(vUniquePtr); // operator bool() BOOST_CHECK_NE(vUniquePtr.call<Obj*>("get"), po); vUniquePtr.call<void>("reset"); BOOST_CHECK(!vUniquePtr); // operator bool() BOOST_CHECK(vUniquePtr.call<Obj*>("get") == nullptr); } /******************************************************************************/ /* TODO */ /******************************************************************************/ #if 0 // \todo Useful use cases that are currenty not supported. BOOST_AUTO_TEST_CASE(null) { Function nullFn("null", [] (test::Object* o) {}); nullFn.call<void>(nullptr); } // should also work with smart ptr. BOOST_AUTO_TEST_CASE(parentChild) { auto doParent = [] (test::Parent* p) { return p; }; Function parentFn("parent", doParent); auto doChild = [] (test::Child* c) { return c; }; Function childFn("child", doChild); test::Parent parent; test::Child child; BOOST_CHECK_EQUAL(childFn.call<test::Child>(&child), doChild(&child)); BOOST_CHECK_EQUAL(childFn.call<test::Child>(&parent), doChild(&parent)); BOOST_CHECK_EQUAL(parentFn.call<test::Parent>(&child), doParent(&child)); BOOST_CHECK_EQUAL(parentFn.call<test::Parent>(&parent), doParent(&parent)); } #endif
/* pointer_test.cpp -*- C++ -*- Rémi Attab ([email protected]), 20 Apr 2014 FreeBSD-style copyright and disclaimer apply Tests for pointer reflection. Note: Disabled tests are the ones that are currently failing due to lackluster pointer support. \todo Pointers aren't const-checked at the moment. Turns out that this is rather difficult to get right because with pointers we get multi-layering of constness which makes it impossible to have a single bool represent const-ness. As an example: int const* * const* & int * const* * const& Should they both be const? What would that even mean? What we'd need is a list of argument objects that understands both pointer and references. But that's just way too complicated for the small feature gain we'd get. */ #define BOOST_TEST_MAIN #define BOOST_TEST_DYN_LINK #define REFLECT_USE_EXCEPTIONS 1 #include "reflect.h" #include "test_types.h" #include "types/primitives.h" #include "types/std/smart_ptr.h" #include <boost/test/unit_test.hpp> using namespace std; using namespace reflect; /******************************************************************************/ /* BASICS */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(basics) { const Type* tPtr = type<int*>(); std::cerr << tPtr->print() << std::endl; BOOST_CHECK_EQUAL(type<int const*>(), tPtr); BOOST_CHECK(tPtr->isPointer()); BOOST_CHECK_EQUAL(tPtr->pointer(), "*"); BOOST_CHECK_EQUAL(tPtr->pointee(), type<int>()); const Type* tPtrPtr = type<int**>(); BOOST_CHECK(tPtrPtr->isPointer()); BOOST_CHECK_EQUAL(tPtrPtr->pointer(), "*"); BOOST_CHECK_EQUAL(tPtrPtr->pointee(), tPtr); BOOST_CHECK_EQUAL(type<int const* const*>(), tPtrPtr); BOOST_CHECK_EQUAL(type<int * const*>(), tPtrPtr); BOOST_CHECK_EQUAL(type<int const* *>(), tPtrPtr); } /******************************************************************************/ /* POINTER */ /******************************************************************************/ BOOST_AUTO_TEST_CASE(pointer_test) { typedef test::Object Obj; auto doPtr = [] (Obj* obj) { return obj; }; Function ptrFn("ptr", doPtr); auto doPtrPtr = [] (Obj** obj) { return obj; }; Function ptrPtrFn("ptrPtr", doPtrPtr); auto doConstPtr = [] (Obj const* const obj) { return obj; }; Function constPtrFn("constPtr", doConstPtr); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj * )>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj ** )>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<void(Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<Obj (Obj*)>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<Obj * (Obj*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrFn.test<Obj ** (Obj*)>(), Match::None); BOOST_CHECK_EQUAL(ptrFn.test<Obj const*(Obj*)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj * )>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj ** )>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<void(Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj (Obj**)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj * (Obj**)>(), Match::None); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj ** (Obj**)>(), Match::Exact); BOOST_CHECK_EQUAL(ptrPtrFn.test<Obj const*(Obj**)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj )>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj * )>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj ** )>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<void(Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<Obj (Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<Obj * (Obj const*)>(), Match::Exact); BOOST_CHECK_EQUAL(constPtrFn.test<Obj ** (Obj const*)>(), Match::None); BOOST_CHECK_EQUAL(constPtrFn.test<Obj const*(Obj const*)>(), Match::Exact); } BOOST_AUTO_TEST_CASE(pointer_call) { typedef test::Object Obj; auto doPtr = [] (Obj* obj) { return obj; }; Function ptrFn("ptr", doPtr); auto doPtrPtr = [] (Obj** obj) { return obj; }; Function ptrPtrFn("ptrPtr", doPtrPtr); auto doConstPtr = [] (Obj const* const obj) { return obj; }; Function constPtrFn("constPtr", doConstPtr); Obj o; Obj* po = &o; Obj** ppo = &po; Obj const* cpo = &o; BOOST_CHECK_THROW(ptrFn.call<Obj*>(o ), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(po ), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj*>(ppo), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(cpo), doPtr(po)); // Not an error. BOOST_CHECK_THROW(ptrFn.call<Obj*>(Value(o )), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(Value(po )), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj*>(Value(ppo)), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj*>(Value(cpo)), doPtr(po)); // not an error. BOOST_CHECK_THROW(ptrFn.call<Obj >(po), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj * >(po), doPtr(po)); BOOST_CHECK_THROW(ptrFn.call<Obj ** >(po), ReflectError); BOOST_CHECK_EQUAL(ptrFn.call<Obj const*>(po), doPtr(po)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(o ), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(po ), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj**>(ppo), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(cpo), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(o )), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(po )), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj**>(Value(ppo)), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj**>(Value(cpo)), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj >(ppo), ReflectError); BOOST_CHECK_THROW(ptrPtrFn.call<Obj * >(ppo), ReflectError); BOOST_CHECK_EQUAL(ptrPtrFn.call<Obj ** >(ppo), doPtrPtr(ppo)); BOOST_CHECK_THROW(ptrPtrFn.call<Obj const*>(ppo), ReflectError); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(o ), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(po ), doConstPtr(po)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(ppo), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(cpo), doConstPtr(cpo)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(Value(o )), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(Value(po )), doConstPtr(po)); BOOST_CHECK_THROW(constPtrFn.call<Obj const*>(Value(ppo)), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(Value(cpo)), doConstPtr(cpo)); BOOST_CHECK_THROW(constPtrFn.call<Obj >(cpo), ReflectError); constPtrFn.call<Obj * >(cpo); BOOST_CHECK_THROW(constPtrFn.call<Obj ** >(cpo), ReflectError); BOOST_CHECK_EQUAL(constPtrFn.call<Obj const*>(cpo), doConstPtr(cpo)); } /******************************************************************************/ /* SMART PTR */ /******************************************************************************/ template<typename Ptr> void testSmartPtr(const std::string& pointer) { typedef test::NotConstructible Obj; const Type* tPtr = type<Ptr>(); std::cerr << tPtr->print() << std::endl; BOOST_CHECK(tPtr->isPointer()); BOOST_CHECK_EQUAL(tPtr->pointer(), pointer); BOOST_CHECK_EQUAL(tPtr->pointee(), type<Obj>()); Obj* po = Obj::make(); Value vPtr = tPtr->construct(po); auto& obj = (*vPtr).get<Obj>(); auto& sharedPtr = vPtr.get<Ptr>(); BOOST_CHECK(vPtr); // operator bool() BOOST_CHECK(vPtr == sharedPtr); // operator== BOOST_CHECK_EQUAL(&obj, po); BOOST_CHECK_EQUAL(sharedPtr.get(), po); BOOST_CHECK_EQUAL(vPtr.call<Obj*>("get"), po); vPtr.call<void>("reset", Obj::make()); BOOST_CHECK(vPtr); // operator bool() BOOST_CHECK_NE(vPtr.call<Obj*>("get"), po); vPtr.call<void>("reset"); BOOST_CHECK(!vPtr); // operator bool() BOOST_CHECK(vPtr.call<Obj*>("get") == nullptr); } BOOST_AUTO_TEST_CASE(sharedPtr) { typedef test::NotConstructible Obj; testSmartPtr< std::shared_ptr<Obj> >("std::shared_ptr"); } BOOST_AUTO_TEST_CASE(uniquePtr) { typedef test::NotConstructible Obj; testSmartPtr< std::unique_ptr<Obj> >("std::unique_ptr"); } /******************************************************************************/ /* TODO */ /******************************************************************************/ #if 0 // \todo Useful use cases that are currenty not supported. BOOST_AUTO_TEST_CASE(null) { Function nullFn("null", [] (test::Object* o) {}); nullFn.call<void>(nullptr); } // should also work with smart ptr. BOOST_AUTO_TEST_CASE(parentChild) { auto doParent = [] (test::Parent* p) { return p; }; Function parentFn("parent", doParent); auto doChild = [] (test::Child* c) { return c; }; Function childFn("child", doChild); test::Parent parent; test::Child child; BOOST_CHECK_EQUAL(childFn.call<test::Child>(&child), doChild(&child)); BOOST_CHECK_EQUAL(childFn.call<test::Child>(&parent), doChild(&parent)); BOOST_CHECK_EQUAL(parentFn.call<test::Parent>(&child), doParent(&child)); BOOST_CHECK_EQUAL(parentFn.call<test::Parent>(&parent), doParent(&parent)); } #endif
Clean up in aisle smartPtr.
Clean up in aisle smartPtr.
C++
bsd-2-clause
RAttab/reflect,Remotion/reflect,jkhoogland/reflect,Remotion/reflect,jkhoogland/reflect,RAttab/reflect
ce3244862ba5d0e546d3030336439afc219c9d6c
CoreUI/Qmitk/QmitkRegisterClasses.cpp
CoreUI/Qmitk/QmitkRegisterClasses.cpp
/*========================================================================= 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 "QmitkRegisterClasses.h" #include "QmitkApplicationCursor.h" #include "QmitkRenderingManagerFactory.h" #include "mitkGlobalInteraction.h" #include <iostream> void QmitkRegisterClasses() { static bool alreadyDone = false; if (!alreadyDone) { std::cout << "QmitkRegisterClasses()" << std::endl; //We have to put this in a file containing a class that is directly used //somewhere. Otherwise, e.g. when put in VtkRenderWindowInteractor.cpp, //it is removed by the linker. // Create and initialize GlobalInteraction if(! (mitk::GlobalInteraction::GetInstance()->IsInitialized())) mitk::GlobalInteraction::GetInstance()->Initialize("global"); // Create and register RenderingManagerFactory for this platform. static QmitkRenderingManagerFactory qmitkRenderingManagerFactory; static QmitkApplicationCursor globalQmitkApplicationCursor; // create one instance alreadyDone = true; } }
/*========================================================================= 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 "QmitkRegisterClasses.h" #include "QmitkApplicationCursor.h" #include "QmitkRenderingManagerFactory.h" #include "mitkGlobalInteraction.h" #include <iostream> void QmitkRegisterClasses() { static bool alreadyDone = false; if (!alreadyDone) { LOG_INFO << "QmitkRegisterClasses()"; //We have to put this in a file containing a class that is directly used //somewhere. Otherwise, e.g. when put in VtkRenderWindowInteractor.cpp, //it is removed by the linker. // Create and initialize GlobalInteraction if(! (mitk::GlobalInteraction::GetInstance()->IsInitialized())) mitk::GlobalInteraction::GetInstance()->Initialize("global"); // Create and register RenderingManagerFactory for this platform. static QmitkRenderingManagerFactory qmitkRenderingManagerFactory; static QmitkApplicationCursor globalQmitkApplicationCursor; // create one instance alreadyDone = true; } }
use LOG_INFO for startup messages
STYLE: use LOG_INFO for startup messages
C++
bsd-3-clause
rfloca/MITK,lsanzdiaz/MITK-BiiG,NifTK/MITK,nocnokneo/MITK,fmilano/mitk,NifTK/MITK,danielknorr/MITK,iwegner/MITK,RabadanLab/MITKats,NifTK/MITK,nocnokneo/MITK,RabadanLab/MITKats,RabadanLab/MITKats,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,rfloca/MITK,NifTK/MITK,nocnokneo/MITK,rfloca/MITK,nocnokneo/MITK,iwegner/MITK,danielknorr/MITK,rfloca/MITK,iwegner/MITK,fmilano/mitk,fmilano/mitk,rfloca/MITK,MITK/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,MITK/MITK,danielknorr/MITK,MITK/MITK,iwegner/MITK,NifTK/MITK,RabadanLab/MITKats,rfloca/MITK,danielknorr/MITK,fmilano/mitk,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,MITK/MITK,NifTK/MITK,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,RabadanLab/MITKats,fmilano/mitk,MITK/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,fmilano/mitk,danielknorr/MITK,danielknorr/MITK,rfloca/MITK,nocnokneo/MITK
3eace7061b8a854b5d0566d15646302da57caf75
src/native/sun_misc_Unsafe.cc
src/native/sun_misc_Unsafe.cc
/* * Copyright (C) 2008 The Android Open Source Project * * 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 "jni_internal.h" #include "object.h" #include "scoped_thread_state_change.h" namespace art { static jlong Unsafe_objectFieldOffset0(JNIEnv* env, jclass, jobject javaField) { // TODO: move to Java code jfieldID fid = env->FromReflectedField(javaField); ScopedObjectAccess soa(env); Field* field = soa.DecodeField(fid); return field->GetOffset().Int32Value(); } static jint Unsafe_arrayBaseOffset0(JNIEnv* env, jclass, jclass javaArrayClass) { // TODO: move to Java code ScopedObjectAccess soa(env); Class* array_class = soa.Decode<Class*>(javaArrayClass); return Array::DataOffset(array_class->GetComponentSize()).Int32Value(); } static jint Unsafe_arrayIndexScale0(JNIEnv* env, jclass, jclass javaClass) { ScopedObjectAccess soa(env); Class* c = soa.Decode<Class*>(javaClass); return c->GetComponentSize(); } static jboolean Unsafe_compareAndSwapInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint expectedValue, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int32_t* address = reinterpret_cast<volatile int32_t*>(raw_addr); // Note: android_atomic_release_cas() returns 0 on success, not failure. int result = android_atomic_release_cas(expectedValue, newValue, address); return (result == 0); } static jboolean Unsafe_compareAndSwapLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong expectedValue, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int64_t* address = reinterpret_cast<volatile int64_t*>(raw_addr); // Note: android_atomic_cmpxchg() returns 0 on success, not failure. int result = QuasiAtomic::Cas64(expectedValue, newValue, address); return (result == 0); } static jboolean Unsafe_compareAndSwapObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaExpectedValue, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* expectedValue = soa.Decode<Object*>(javaExpectedValue); Object* newValue = soa.Decode<Object*>(javaNewValue); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; int32_t* address = reinterpret_cast<int32_t*>(raw_addr); // Note: android_atomic_cmpxchg() returns 0 on success, not failure. int result = android_atomic_release_cas(reinterpret_cast<int32_t>(expectedValue), reinterpret_cast<int32_t>(newValue), address); if (result == 0) { Runtime::Current()->GetHeap()->WriteBarrierField(obj, MemberOffset(offset), newValue); } return (result == 0); } static jint Unsafe_getInt(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField32(MemberOffset(offset), false); } static jint Unsafe_getIntVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int32_t* address = reinterpret_cast<volatile int32_t*>(raw_addr); return android_atomic_acquire_load(address); } static void Unsafe_putInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField32(MemberOffset(offset), newValue, false); } static void Unsafe_putIntVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int32_t* address = reinterpret_cast<volatile int32_t*>(raw_addr); android_atomic_release_store(newValue, address); } static void Unsafe_putOrderedInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); ANDROID_MEMBAR_STORE(); obj->SetField32(MemberOffset(offset), newValue, false); } static jlong Unsafe_getLong(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; int64_t* address = reinterpret_cast<int64_t*>(raw_addr); return *address; } static jlong Unsafe_getLongVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField64(MemberOffset(offset), true); } static void Unsafe_putLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField64(MemberOffset(offset), newValue, false); } static void Unsafe_putLongVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField64(MemberOffset(offset), newValue, true); } static void Unsafe_putOrderedLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); ANDROID_MEMBAR_STORE(); obj->SetField64(MemberOffset(offset), newValue, false); } static jobject Unsafe_getObjectVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* value = obj->GetFieldObject<Object*>(MemberOffset(offset), true); return soa.AddLocalReference<jobject>(value); } static jobject Unsafe_getObject(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* value = obj->GetFieldObject<Object*>(MemberOffset(offset), false); return soa.AddLocalReference<jobject>(value); } static void Unsafe_putObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); obj->SetFieldObject(MemberOffset(offset), newValue, false); } static void Unsafe_putObjectVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); obj->SetFieldObject(MemberOffset(offset), newValue, true); } static void Unsafe_putOrderedObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); ANDROID_MEMBAR_STORE(); obj->SetFieldObject(MemberOffset(offset), newValue, false); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Unsafe, objectFieldOffset0, "(Ljava/lang/reflect/Field;)J"), NATIVE_METHOD(Unsafe, arrayBaseOffset0, "(Ljava/lang/Class;)I"), NATIVE_METHOD(Unsafe, arrayIndexScale0, "(Ljava/lang/Class;)I"), NATIVE_METHOD(Unsafe, compareAndSwapInt, "(Ljava/lang/Object;JII)Z"), NATIVE_METHOD(Unsafe, compareAndSwapLong, "(Ljava/lang/Object;JJJ)Z"), NATIVE_METHOD(Unsafe, compareAndSwapObject, "(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z"), NATIVE_METHOD(Unsafe, getIntVolatile, "(Ljava/lang/Object;J)I"), NATIVE_METHOD(Unsafe, putIntVolatile, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, getLongVolatile, "(Ljava/lang/Object;J)J"), NATIVE_METHOD(Unsafe, putLongVolatile, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, getObjectVolatile, "(Ljava/lang/Object;J)Ljava/lang/Object;"), NATIVE_METHOD(Unsafe, putObjectVolatile, "(Ljava/lang/Object;JLjava/lang/Object;)V"), NATIVE_METHOD(Unsafe, getInt, "(Ljava/lang/Object;J)I"), NATIVE_METHOD(Unsafe, putInt, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, putOrderedInt, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, getLong, "(Ljava/lang/Object;J)J"), NATIVE_METHOD(Unsafe, putLong, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, putOrderedLong, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, getObject, "(Ljava/lang/Object;J)Ljava/lang/Object;"), NATIVE_METHOD(Unsafe, putObject, "(Ljava/lang/Object;JLjava/lang/Object;)V"), NATIVE_METHOD(Unsafe, putOrderedObject, "(Ljava/lang/Object;JLjava/lang/Object;)V"), }; void register_sun_misc_Unsafe(JNIEnv* env) { REGISTER_NATIVE_METHODS("sun/misc/Unsafe"); } } // namespace art
/* * Copyright (C) 2008 The Android Open Source Project * * 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 "jni_internal.h" #include "object.h" #include "scoped_thread_state_change.h" namespace art { static jlong Unsafe_objectFieldOffset0(JNIEnv* env, jclass, jobject javaField) { // TODO: move to Java code jfieldID fid = env->FromReflectedField(javaField); ScopedObjectAccess soa(env); Field* field = soa.DecodeField(fid); return field->GetOffset().Int32Value(); } static jint Unsafe_arrayBaseOffset0(JNIEnv* env, jclass, jclass javaArrayClass) { // TODO: move to Java code ScopedObjectAccess soa(env); Class* array_class = soa.Decode<Class*>(javaArrayClass); return Array::DataOffset(array_class->GetComponentSize()).Int32Value(); } static jint Unsafe_arrayIndexScale0(JNIEnv* env, jclass, jclass javaClass) { ScopedObjectAccess soa(env); Class* c = soa.Decode<Class*>(javaClass); return c->GetComponentSize(); } static jboolean Unsafe_compareAndSwapInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint expectedValue, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int32_t* address = reinterpret_cast<volatile int32_t*>(raw_addr); // Note: android_atomic_release_cas() returns 0 on success, not failure. int result = android_atomic_release_cas(expectedValue, newValue, address); return (result == 0); } static jboolean Unsafe_compareAndSwapLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong expectedValue, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; volatile int64_t* address = reinterpret_cast<volatile int64_t*>(raw_addr); // Note: android_atomic_cmpxchg() returns 0 on success, not failure. int result = QuasiAtomic::Cas64(expectedValue, newValue, address); return (result == 0); } static jboolean Unsafe_compareAndSwapObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaExpectedValue, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* expectedValue = soa.Decode<Object*>(javaExpectedValue); Object* newValue = soa.Decode<Object*>(javaNewValue); byte* raw_addr = reinterpret_cast<byte*>(obj) + offset; int32_t* address = reinterpret_cast<int32_t*>(raw_addr); // Note: android_atomic_cmpxchg() returns 0 on success, not failure. int result = android_atomic_release_cas(reinterpret_cast<int32_t>(expectedValue), reinterpret_cast<int32_t>(newValue), address); if (result == 0) { Runtime::Current()->GetHeap()->WriteBarrierField(obj, MemberOffset(offset), newValue); } return (result == 0); } static jint Unsafe_getInt(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField32(MemberOffset(offset), false); } static jint Unsafe_getIntVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField32(MemberOffset(offset), true); } static void Unsafe_putInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField32(MemberOffset(offset), newValue, false); } static void Unsafe_putIntVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField32(MemberOffset(offset), newValue, true); } static void Unsafe_putOrderedInt(JNIEnv* env, jobject, jobject javaObj, jlong offset, jint newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); ANDROID_MEMBAR_STORE(); obj->SetField32(MemberOffset(offset), newValue, false); } static jlong Unsafe_getLong(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField64(MemberOffset(offset), false); } static jlong Unsafe_getLongVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); return obj->GetField64(MemberOffset(offset), true); } static void Unsafe_putLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField64(MemberOffset(offset), newValue, false); } static void Unsafe_putLongVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); obj->SetField64(MemberOffset(offset), newValue, true); } static void Unsafe_putOrderedLong(JNIEnv* env, jobject, jobject javaObj, jlong offset, jlong newValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); ANDROID_MEMBAR_STORE(); obj->SetField64(MemberOffset(offset), newValue, false); } static jobject Unsafe_getObjectVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* value = obj->GetFieldObject<Object*>(MemberOffset(offset), true); return soa.AddLocalReference<jobject>(value); } static jobject Unsafe_getObject(JNIEnv* env, jobject, jobject javaObj, jlong offset) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* value = obj->GetFieldObject<Object*>(MemberOffset(offset), false); return soa.AddLocalReference<jobject>(value); } static void Unsafe_putObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); obj->SetFieldObject(MemberOffset(offset), newValue, false); } static void Unsafe_putObjectVolatile(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); obj->SetFieldObject(MemberOffset(offset), newValue, true); } static void Unsafe_putOrderedObject(JNIEnv* env, jobject, jobject javaObj, jlong offset, jobject javaNewValue) { ScopedObjectAccess soa(env); Object* obj = soa.Decode<Object*>(javaObj); Object* newValue = soa.Decode<Object*>(javaNewValue); ANDROID_MEMBAR_STORE(); obj->SetFieldObject(MemberOffset(offset), newValue, false); } static JNINativeMethod gMethods[] = { NATIVE_METHOD(Unsafe, objectFieldOffset0, "(Ljava/lang/reflect/Field;)J"), NATIVE_METHOD(Unsafe, arrayBaseOffset0, "(Ljava/lang/Class;)I"), NATIVE_METHOD(Unsafe, arrayIndexScale0, "(Ljava/lang/Class;)I"), NATIVE_METHOD(Unsafe, compareAndSwapInt, "(Ljava/lang/Object;JII)Z"), NATIVE_METHOD(Unsafe, compareAndSwapLong, "(Ljava/lang/Object;JJJ)Z"), NATIVE_METHOD(Unsafe, compareAndSwapObject, "(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z"), NATIVE_METHOD(Unsafe, getIntVolatile, "(Ljava/lang/Object;J)I"), NATIVE_METHOD(Unsafe, putIntVolatile, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, getLongVolatile, "(Ljava/lang/Object;J)J"), NATIVE_METHOD(Unsafe, putLongVolatile, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, getObjectVolatile, "(Ljava/lang/Object;J)Ljava/lang/Object;"), NATIVE_METHOD(Unsafe, putObjectVolatile, "(Ljava/lang/Object;JLjava/lang/Object;)V"), NATIVE_METHOD(Unsafe, getInt, "(Ljava/lang/Object;J)I"), NATIVE_METHOD(Unsafe, putInt, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, putOrderedInt, "(Ljava/lang/Object;JI)V"), NATIVE_METHOD(Unsafe, getLong, "(Ljava/lang/Object;J)J"), NATIVE_METHOD(Unsafe, putLong, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, putOrderedLong, "(Ljava/lang/Object;JJ)V"), NATIVE_METHOD(Unsafe, getObject, "(Ljava/lang/Object;J)Ljava/lang/Object;"), NATIVE_METHOD(Unsafe, putObject, "(Ljava/lang/Object;JLjava/lang/Object;)V"), NATIVE_METHOD(Unsafe, putOrderedObject, "(Ljava/lang/Object;JLjava/lang/Object;)V"), }; void register_sun_misc_Unsafe(JNIEnv* env) { REGISTER_NATIVE_METHODS("sun/misc/Unsafe"); } } // namespace art
Tidy up some raw Object access cruft.
Tidy up some raw Object access cruft. Change-Id: I42fee7eb1f549a795a6c83d3f971ed478e9e5ee5
C++
apache-2.0
treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst,treadstoneproject/artinst
aa9f38a66ef0f879a291607399f5e0493aed0123
all/native/layers/SolidLayer.cpp
all/native/layers/SolidLayer.cpp
#include "SolidLayer.h" #include "components/Exceptions.h" #include "graphics/Bitmap.h" #include "renderers/SolidRenderer.cpp" #include "utils/Log.h" #include <vector> namespace carto { SolidLayer::SolidLayer(const Color& color) : Layer(), _color(color), _bitmap(), _bitmapScale(1.0f), _solidRenderer(std::make_shared<SolidRenderer>()) { } SolidLayer::SolidLayer(const std::shared_ptr<Bitmap>& bitmap) : Layer(), _color(Color(255, 255, 255, 255)), _bitmap(bitmap), _bitmapScale(1.0f), _solidRenderer(std::make_shared<SolidRenderer>()) { } SolidLayer::~SolidLayer() { } Color SolidLayer::getColor() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _color; } void SolidLayer::setColor(const Color& color) { std::lock_guard<std::recursive_mutex> lock(_mutex); _color = color; } std::shared_ptr<Bitmap> SolidLayer::getBitmap() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _bitmap; } void SolidLayer::setBitmap(const std::shared_ptr<Bitmap>& bitmap) { std::lock_guard<std::recursive_mutex> lock(_mutex); _bitmap = bitmap; } float SolidLayer::getBitmapScale() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _bitmapScale; } void SolidLayer::setBitmapScale(float scale) { std::lock_guard<std::recursive_mutex> lock(_mutex); _bitmapScale = scale; } bool SolidLayer::isUpdateInProgress() const { return false; } void SolidLayer::setComponents(const std::shared_ptr<CancelableThreadPool>& envelopeThreadPool, const std::shared_ptr<CancelableThreadPool>& tileThreadPool, const std::weak_ptr<Options>& options, const std::weak_ptr<MapRenderer>& mapRenderer, const std::weak_ptr<TouchHandler>& touchHandler) { Layer::setComponents(envelopeThreadPool, tileThreadPool, options, mapRenderer, touchHandler); } void SolidLayer::loadData(const std::shared_ptr<CullState>& cullState) { } void SolidLayer::offsetLayerHorizontally(double offset) { } void SolidLayer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) { Layer::onSurfaceCreated(shaderManager, textureManager); _solidRenderer->onSurfaceCreated(shaderManager, textureManager); } bool SolidLayer::onDrawFrame(float deltaSeconds, BillboardSorter& billboardSorter, StyleTextureCache& styleCache, const ViewState& viewState) { { std::lock_guard<std::recursive_mutex> lock(_mutex); _solidRenderer->setColor(_color); _solidRenderer->setBitmap(_bitmap, _bitmapScale); } _solidRenderer->onDrawFrame(viewState); return false; } void SolidLayer::onSurfaceDestroyed(){ _solidRenderer->onSurfaceDestroyed(); Layer::onSurfaceDestroyed(); } void SolidLayer::calculateRayIntersectedElements(const Projection& projection, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const { } bool SolidLayer::processClick(ClickType::ClickType clickType, const RayIntersectedElement& intersectedElement, const ViewState& viewState) const { return clickType == ClickType::CLICK_TYPE_SINGLE || clickType == ClickType::CLICK_TYPE_LONG; // by default, disable 'click through' for single and long clicks } void SolidLayer::registerDataSourceListener() { } void SolidLayer::unregisterDataSourceListener() { } }
#include "SolidLayer.h" #include "components/Exceptions.h" #include "graphics/Bitmap.h" #include "renderers/SolidRenderer.h" #include "utils/Log.h" #include <vector> namespace carto { SolidLayer::SolidLayer(const Color& color) : Layer(), _color(color), _bitmap(), _bitmapScale(1.0f), _solidRenderer(std::make_shared<SolidRenderer>()) { } SolidLayer::SolidLayer(const std::shared_ptr<Bitmap>& bitmap) : Layer(), _color(Color(255, 255, 255, 255)), _bitmap(bitmap), _bitmapScale(1.0f), _solidRenderer(std::make_shared<SolidRenderer>()) { } SolidLayer::~SolidLayer() { } Color SolidLayer::getColor() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _color; } void SolidLayer::setColor(const Color& color) { std::lock_guard<std::recursive_mutex> lock(_mutex); _color = color; } std::shared_ptr<Bitmap> SolidLayer::getBitmap() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _bitmap; } void SolidLayer::setBitmap(const std::shared_ptr<Bitmap>& bitmap) { std::lock_guard<std::recursive_mutex> lock(_mutex); _bitmap = bitmap; } float SolidLayer::getBitmapScale() const { std::lock_guard<std::recursive_mutex> lock(_mutex); return _bitmapScale; } void SolidLayer::setBitmapScale(float scale) { std::lock_guard<std::recursive_mutex> lock(_mutex); _bitmapScale = scale; } bool SolidLayer::isUpdateInProgress() const { return false; } void SolidLayer::setComponents(const std::shared_ptr<CancelableThreadPool>& envelopeThreadPool, const std::shared_ptr<CancelableThreadPool>& tileThreadPool, const std::weak_ptr<Options>& options, const std::weak_ptr<MapRenderer>& mapRenderer, const std::weak_ptr<TouchHandler>& touchHandler) { Layer::setComponents(envelopeThreadPool, tileThreadPool, options, mapRenderer, touchHandler); } void SolidLayer::loadData(const std::shared_ptr<CullState>& cullState) { } void SolidLayer::offsetLayerHorizontally(double offset) { } void SolidLayer::onSurfaceCreated(const std::shared_ptr<ShaderManager>& shaderManager, const std::shared_ptr<TextureManager>& textureManager) { Layer::onSurfaceCreated(shaderManager, textureManager); _solidRenderer->onSurfaceCreated(shaderManager, textureManager); } bool SolidLayer::onDrawFrame(float deltaSeconds, BillboardSorter& billboardSorter, StyleTextureCache& styleCache, const ViewState& viewState) { { std::lock_guard<std::recursive_mutex> lock(_mutex); _solidRenderer->setColor(_color); _solidRenderer->setBitmap(_bitmap, _bitmapScale); } _solidRenderer->onDrawFrame(viewState); return false; } void SolidLayer::onSurfaceDestroyed(){ _solidRenderer->onSurfaceDestroyed(); Layer::onSurfaceDestroyed(); } void SolidLayer::calculateRayIntersectedElements(const Projection& projection, const cglib::ray3<double>& ray, const ViewState& viewState, std::vector<RayIntersectedElement>& results) const { } bool SolidLayer::processClick(ClickType::ClickType clickType, const RayIntersectedElement& intersectedElement, const ViewState& viewState) const { return clickType == ClickType::CLICK_TYPE_SINGLE || clickType == ClickType::CLICK_TYPE_LONG; // by default, disable 'click through' for single and long clicks } void SolidLayer::registerDataSourceListener() { } void SolidLayer::unregisterDataSourceListener() { } }
Fix build issue
Fix build issue
C++
bsd-3-clause
CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk,CartoDB/mobile-sdk
558bc47fab19763ebad9b03f2f01ed83716a1fcb
include/util/datastream/topk/cms/TopKItemEstimation.hpp
include/util/datastream/topk/cms/TopKItemEstimation.hpp
/* * @file TopKItemEstimation.hpp * @author Kuilong Liu * @date 2013.04.24 * @ TopKItem by count min sketch */ #ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #include <list> #include <iterator> #include <iostream> #include <boost/unordered_map.hpp> #include <boost/shared_ptr.hpp> namespace izenelib { namespace util { template<typename ElemType, typename CountType> class Bucket; template<typename ElemType, typename CountType> class Item { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; Item(ElemType e, BucketT* b, ItemT* p, ItemT* n) :elem_(e), b_(b), prev_(p), next_(n) { } ~Item() { b_ = NULL; if(next_)delete next_; } ElemType elem_; BucketT* b_; ItemT* prev_; ItemT* next_; }; template<typename ElemType, typename CountType> class Bucket { public: typedef Item<ElemType, CountType> ItemT; typedef Bucket<ElemType, CountType> BucketT; Bucket(CountType c, BucketT* p, BucketT* n) :size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n) { } ~Bucket() { if(head_)delete head_; if(next_)delete next_; } bool insert(ItemT* i) { if(size_==0) { head_=end_=i; i->prev_=NULL; } else { end_->next_=i; i->prev_=end_; end_=i; } i->b_=this; i->next_=NULL; size_++; return true; } bool erase(ItemT* i) { if(size_==1) { head_=end_=NULL; } else if(i->next_==NULL) { end_=end_->prev_; end_->next_=NULL; } else if(i->prev_==NULL) { head_=i->next_; head_->prev_=NULL; } else { i->prev_->next_=i->next_; i->next_->prev_=i->prev_; } size_--; i->prev_=i->next_=NULL; i->b_=NULL; return true; } CountType size_; CountType c_; ItemT* head_; ItemT* end_; BucketT* prev_; BucketT* next_; }; template<typename ElemType, typename CountType> class TopKEstimation { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; TopKEstimation(CountType m) :MAXSIZE_(m), size_(0), th_(0) { bs_ = new BucketT(0, NULL, NULL); } ~TopKEstimation() { if(bs_)delete bs_; gps_.clear(); } bool reset() { if(bs_) delete bs_; bs_=new BucketT(0, NULL, NULL); gps_.clear(); size_=th_=0; return true; } bool insert(ElemType elem, CountType count) { if(gps_.find(elem) != gps_.end()) { return update(elem, count); } else if(size_ >= MAXSIZE_ && count <= th_) return true; else if(size_ >= MAXSIZE_) { return replace(elem, count); } else { return additem(elem, count); } } bool get(std::list<ElemType>& elem, std::list<CountType>& count) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { elem.push_front(i->elem_); count.push_front(i->b_->c_); i=i->next_; } bp=bp->next_; } return true; } bool get(std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { topk.push_front(make_pair(i->elem_, i->b_->c_)); i=i->next_; } bp=bp->next_; } return true; } bool get(CountType k, std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = end_; CountType tempk=0; while(bp!=bs_) { ItemT* i=bp->head_; while(i) { topk.push_back(make_pair(i->elem_, i->b_->c_)); tempk++; if(tempk >= k || tempk >= size_)break; i=i->next_; } if(tempk >= k || tempk >= size_)break; bp=bp->prev_; } return true; } private: bool update(ElemType elem, CountType count) { ItemT* i = gps_[elem]; BucketT* bp = i->b_; count = bp->c_+1; if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count)) { bp->c_++; th_ = bs_->next_->c_; return true; } bp->erase(i); if(!(bp->next_)) { bp->next_=new BucketT(count, bp, NULL); end_=bp->next_; } else if(bp->next_->c_ > count) { BucketT* tp=new BucketT(count, bp, bp->next_); bp->next_=tp; tp->next_->prev_=tp; } bp->next_->insert(i); if(bp->size_==0) { bp->prev_->next_=bp->next_; bp->next_->prev_=bp->prev_; bp->next_=bp->prev_=NULL; delete bp; } return true; } bool replace(ElemType elem, CountType count) { count = bs_->next_->c_+1; ItemT* i = bs_->next_->end_; gps_.erase(gps_.find(i->elem_)); gps_[elem] = i; i->elem_=elem; return update(elem,count); } bool additem(ElemType elem, CountType count) { count=1; if(bs_->next_==NULL) { bs_->next_=new BucketT(count, bs_, NULL); end_=bs_->next_; } BucketT* bp=bs_->next_; ItemT* i=new ItemT(elem, bp, NULL, NULL); if(bp->c_ == count) { bp->insert(i); } else { BucketT* nbp = new BucketT(count, bs_, bs_->next_); bs_->next_ = nbp; nbp->next_->prev_=nbp; nbp->insert(i); } size_++; gps_[elem]=i; th_=bs_->next_->c_; return true; } CountType MAXSIZE_; //current size CountType size_; //threshold CountType th_; BucketT* bs_; BucketT* end_; boost::unordered_map<ElemType, ItemT* > gps_; }; } //end of namespace util } //end of namespace izenelib #endif
/* * @file TopKItemEstimation.hpp * @author Kuilong Liu * @date 2013.04.24 * @ TopKItem by count min sketch */ #ifndef IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #define IZENELIB_UTIL_TOPKITEM_ESTIMATION_H_ #include <list> #include <iterator> #include <iostream> #include <boost/unordered_map.hpp> #include <boost/shared_ptr.hpp> namespace izenelib { namespace util { template<typename ElemType, typename CountType> class Bucket; template<typename ElemType, typename CountType> class Item { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; Item(ElemType e, BucketT* b, ItemT* p, ItemT* n) :elem_(e), b_(b), prev_(p), next_(n) { } ~Item() { b_ = NULL; if(next_)delete next_; } ElemType elem_; BucketT* b_; ItemT* prev_; ItemT* next_; }; template<typename ElemType, typename CountType> class Bucket { public: typedef Item<ElemType, CountType> ItemT; typedef Bucket<ElemType, CountType> BucketT; Bucket(CountType c, BucketT* p, BucketT* n) :size_(0), c_(c), head_(NULL), end_(NULL), prev_(p), next_(n) { } ~Bucket() { if(head_)delete head_; if(next_)delete next_; } bool insert(ItemT* i) { if(size_==0) { head_=end_=i; i->prev_=NULL; } else { end_->next_=i; i->prev_=end_; end_=i; } i->b_=this; i->next_=NULL; size_++; return true; } bool erase(ItemT* i) { if(size_==1) { head_=end_=NULL; } else if(i->next_==NULL) { end_=end_->prev_; end_->next_=NULL; } else if(i->prev_==NULL) { head_=i->next_; head_->prev_=NULL; } else { i->prev_->next_=i->next_; i->next_->prev_=i->prev_; } size_--; i->prev_=i->next_=NULL; i->b_=NULL; return true; } CountType size_; CountType c_; ItemT* head_; ItemT* end_; BucketT* prev_; BucketT* next_; }; template<typename ElemType, typename CountType> class TopKEstimation { public: typedef Bucket<ElemType, CountType> BucketT; typedef Item<ElemType, CountType> ItemT; TopKEstimation(CountType m) :MAXSIZE_(m), size_(0), th_(0) { bs_ = new BucketT(0, NULL, NULL); end_=bs_; } ~TopKEstimation() { if(bs_)delete bs_; gps_.clear(); } bool reset() { if(bs_) delete bs_; bs_=new BucketT(0, NULL, NULL); gps_.clear(); size_=th_=0; return true; } bool insert(ElemType elem, CountType count) { if(gps_.find(elem) != gps_.end()) { return update(elem, count); } else if(size_ >= MAXSIZE_ && count <= th_) return true; else if(size_ >= MAXSIZE_) { return replace(elem, count); } else { return additem(elem, count); } } bool get(std::list<ElemType>& elem, std::list<CountType>& count) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { elem.push_front(i->elem_); count.push_front(i->b_->c_); i=i->next_; } bp=bp->next_; } return true; } bool get(std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = bs_->next_; while(bp) { ItemT* i=bp->head_; while(i) { topk.push_front(make_pair(i->elem_, i->b_->c_)); i=i->next_; } bp=bp->next_; } return true; } bool get(CountType k, std::list<std::pair<ElemType, CountType> >& topk) { BucketT* bp = end_; CountType tempk=0; while(bp!=bs_) { ItemT* i=bp->head_; while(i) { topk.push_back(make_pair(i->elem_, i->b_->c_)); tempk++; if(tempk >= k || tempk >= size_)break; i=i->next_; } if(tempk >= k || tempk >= size_)break; bp=bp->prev_; } return true; } private: bool update(ElemType elem, CountType count) { ItemT* i = gps_[elem]; BucketT* bp = i->b_; count = bp->c_+1; if(bp->size_==1 && (!(bp->next_) || bp->next_->c_ > count)) { bp->c_++; th_ = bs_->next_->c_; return true; } bp->erase(i); if(!(bp->next_)) { bp->next_=new BucketT(count, bp, NULL); end_=bp->next_; } else if(bp->next_->c_ > count) { BucketT* tp=new BucketT(count, bp, bp->next_); bp->next_=tp; tp->next_->prev_=tp; } bp->next_->insert(i); if(bp->size_==0) { bp->prev_->next_=bp->next_; bp->next_->prev_=bp->prev_; bp->next_=bp->prev_=NULL; delete bp; } return true; } bool replace(ElemType elem, CountType count) { count = bs_->next_->c_+1; ItemT* i = bs_->next_->end_; gps_.erase(gps_.find(i->elem_)); gps_[elem] = i; i->elem_=elem; return update(elem,count); } bool additem(ElemType elem, CountType count) { count=1; if(bs_->next_==NULL) { bs_->next_=new BucketT(count, bs_, NULL); end_=bs_->next_; } BucketT* bp=bs_->next_; ItemT* i=new ItemT(elem, bp, NULL, NULL); if(bp->c_ == count) { bp->insert(i); } else { BucketT* nbp = new BucketT(count, bs_, bs_->next_); bs_->next_ = nbp; nbp->next_->prev_=nbp; nbp->insert(i); } size_++; gps_[elem]=i; th_=bs_->next_->c_; return true; } CountType MAXSIZE_; //current size CountType size_; //threshold CountType th_; BucketT* bs_; BucketT* end_; boost::unordered_map<ElemType, ItemT* > gps_; }; } //end of namespace util } //end of namespace izenelib #endif
fix a small bug
fix a small bug
C++
apache-2.0
pombredanne/izenelib,izenecloud/izenelib,pombredanne/izenelib,pombredanne/izenelib,pombredanne/izenelib,izenecloud/izenelib,izenecloud/izenelib,izenecloud/izenelib
4d6214383e8221f00850bae8b1805c58cd3738ec
raven.cpp
raven.cpp
#include "raven.h" #include <QHostInfo> #include <QDebug> #include <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #define RAVEN_CLIENT_NAME QString("QRaven") #define RAVEN_CLIENT_VERSION QString("0.1") const static QNetworkRequest::Attribute RavenUuidAttribute = static_cast<QNetworkRequest::Attribute>(QNetworkRequest::User + 19); Raven::Raven(const QString& dsn) : m_initialized(false) , m_networkAccessManager(new QNetworkAccessManager(this)) { m_eventTemplate["server_name"] = QHostInfo::localHostName(); m_eventTemplate["logger"] = RAVEN_CLIENT_NAME; m_eventTemplate["platform"] = "c"; m_eventTemplate["release"] = QCoreApplication::applicationVersion(); parseDsn(dsn); connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, &Raven::requestFinished); connect(m_networkAccessManager, &QNetworkAccessManager::sslErrors, this, &Raven::sslErrors); } Raven::~Raven() { QEventLoop loop; connect(this, &Raven::eventSent, &loop, &QEventLoop::quit); while (!m_pendingRequest.isEmpty()) { loop.exec(QEventLoop::ExcludeUserInputEvents); } } void Raven::parseDsn(const QString& dsn) { if (dsn.isEmpty()) { qWarning() << "DSN is empty, client disabled"; return; } QUrl url(dsn); if (!url.isValid()) { qWarning() << "DSN is not valid, client disabled"; return; } m_protocol = url.scheme(); m_publicKey = url.userName(); m_secretKey = url.password(); m_host = url.host(); m_path = url.path(); m_projectId = url.fileName(); int i = m_path.lastIndexOf('/'); if (i >= 0) m_path = m_path.left(i); int port = url.port(80); if (port != 80) m_host.append(":").append(QString::number(port)); qDebug() << "Raven client is ready"; m_initialized = true; } QString levelString(Raven::RavenLevel level) { switch (level) { case Raven::Fatal: return "fatal"; case Raven::Error: return "error"; case Raven::Warning: return "warning"; case Raven::Info: return "info"; case Raven::Debug: return "debug"; } return "debug"; } RavenMessage Raven::operator()(Raven::RavenLevel level, QString culprit) { RavenMessage event; event.m_body = QJsonObject(m_eventTemplate); event.m_tags = QJsonObject(m_tagsTemplate); event.m_body["event_id"] = QUuid::createUuid().toString().remove('{').remove('}').remove('-'); event.m_body["level"] = levelString(level); event.m_body["timestamp"] = QDateTime::currentDateTimeUtc().toString(Qt::ISODate); event.m_body["culprit"] = culprit; event.m_instance = this; return event; } Raven* Raven::operator<<(const RavenTag& tag) { m_tagsTemplate[tag.first] = tag.second; return this; } bool Raven::isInitialized() const { return m_initialized; } static const QList<QString> _requiredAttributes = { "event_id", "message", "timestamp", "level", "logger", "platform", "sdk", "device" }; void Raven::capture(const RavenMessage& message) { if (!isInitialized()) return; QJsonObject body = QJsonObject(message.m_body); body["tags"] = message.m_tags; for (const auto& attributeName : _requiredAttributes) { Q_ASSERT(body.contains(attributeName)); } send(body); } void Raven::send(QJsonObject& message) { QString clientInfo = QString("%1/%2").arg(RAVEN_CLIENT_NAME, RAVEN_CLIENT_VERSION); QString authInfo = QString("Sentry sentry_version=5," "sentry_client=%1," "sentry_timestamp=%2," "sentry_key=%3," "sentry_secret=%4") .arg(clientInfo, QString::number(time(NULL)), m_publicKey, m_secretKey); QString url = QString("%1://%2%3/api/%4/store/") .arg(m_protocol, m_host, m_path, m_projectId); QString uuid = message["event_id"].toString(); qDebug() << "url=" << url << ",uuid=" << uuid; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::UserAgentHeader, clientInfo); request.setAttribute(RavenUuidAttribute, uuid); request.setRawHeader("X-Sentry-Auth", authInfo.toUtf8()); QByteArray body = QJsonDocument(message).toJson(QJsonDocument::Indented); qDebug() << body; { QMutexLocker lk(&m_pendingMutex); m_pendingRequest[uuid] = body; } m_networkAccessManager->post(request, body); } void Raven::requestFinished(QNetworkReply* reply) { QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute) .toUrl(); QString uuid = reply->request().attribute(RavenUuidAttribute).toString(); QByteArray body = m_pendingRequest[uuid]; if (!redirectUrl.isEmpty() && redirectUrl != reply->url()) { QNetworkRequest request = reply->request(); request.setUrl(redirectUrl); m_networkAccessManager->post(request, body); } else { if (reply->error() == QNetworkReply::NoError) { qDebug() << "Event sent " << reply->readAll(); } else { qDebug() << "Failed to send message to sentry: " << reply->error(); qDebug() << "Sentry answer: " << reply->readAll(); save(uuid, body); } { QMutexLocker lk(&m_pendingMutex); m_pendingRequest.remove(uuid); } emit eventSent(uuid); } reply->deleteLater(); } void Raven::sslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { reply->ignoreSslErrors(); } void Raven::save(const QString& uuid, QByteArray& message) { QString messageDir = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation); messageDir = QDir::cleanPath(messageDir + QDir::separator() + "messages"); QString messageFile = QDir::cleanPath(messageDir + QDir::separator() + uuid); QFile file(messageFile); if (file.open(QIODevice::WriteOnly)) { file.write(message); } else { qWarning() << "Could not save message, it will be discarded"; } } RavenMessage& Raven::send(RavenMessage& message) { message.m_instance->capture(message); return message; } RavenTag Raven::tag(const QString& name, const QString& value) { return RavenTag(name, value); } void Raven::sendAllPending() { QString messageDir = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation); messageDir = QDir::cleanPath(messageDir + QDir::separator() + "messages"); QDirIterator it(messageDir, QDir::Files); while (it.hasNext()) { auto messageFile = it.next(); QFile file(messageFile); if (file.open(QIODevice::ReadOnly)) { QByteArray body = file.readAll(); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(body, &error); if (error.error == QJsonParseError::NoError) { QJsonObject object = doc.object(); send(object); } else { qDebug() << "Could not parse message " << messageFile << ": " << error.errorString(); } } else { qDebug() << "Could not open file " << messageFile; } } } RavenMessage& RavenMessage::operator<<(const QString& message) { m_body["message"] = message; return *this; } RavenMessage& RavenMessage::operator<<(const std::exception& exc) { m_body["message"] = exc.what(); return *this; } RavenMessage& RavenMessage::operator<<(const RavenTag& tag) { m_tags[tag.first] = tag.second; return *this; } RavenMessage& RavenMessage::operator<<(RavenMessage& (*pf)(RavenMessage&)) { return (*pf)(*this); } QString Raven::locationInfo(const char* file, const char* func, int line) { return QString("%1 in %2 at %3") .arg(file) .arg(func) .arg(QString::number(line)); }
#include "raven.h" #include <QHostInfo> #include <QDebug> #include <QUrl> #include <QNetworkRequest> #include <QNetworkReply> #include <QSysInfo> #define RAVEN_CLIENT_NAME QString("QRaven") #define RAVEN_CLIENT_VERSION QString("0.1") const static QNetworkRequest::Attribute RavenUuidAttribute = static_cast<QNetworkRequest::Attribute>(QNetworkRequest::User + 19); Raven::Raven(const QString& dsn) : m_initialized(false) , m_networkAccessManager(new QNetworkAccessManager(this)) { m_eventTemplate["server_name"] = QHostInfo::localHostName(); m_eventTemplate["logger"] = RAVEN_CLIENT_NAME; m_eventTemplate["platform"] = "c"; m_eventTemplate["release"] = QCoreApplication::applicationVersion(); m_tagsTemplate["os_type"] = QSysInfo::productType(); m_tagsTemplate["os_version"] = QSysInfo::productVersion(); parseDsn(dsn); connect(m_networkAccessManager, &QNetworkAccessManager::finished, this, &Raven::requestFinished); connect(m_networkAccessManager, &QNetworkAccessManager::sslErrors, this, &Raven::sslErrors); } Raven::~Raven() { QEventLoop loop; connect(this, &Raven::eventSent, &loop, &QEventLoop::quit); while (!m_pendingRequest.isEmpty()) { loop.exec(QEventLoop::ExcludeUserInputEvents); } } void Raven::parseDsn(const QString& dsn) { if (dsn.isEmpty()) { qWarning() << "DSN is empty, client disabled"; return; } QUrl url(dsn); if (!url.isValid()) { qWarning() << "DSN is not valid, client disabled"; return; } m_protocol = url.scheme(); m_publicKey = url.userName(); m_secretKey = url.password(); m_host = url.host(); m_path = url.path(); m_projectId = url.fileName(); int i = m_path.lastIndexOf('/'); if (i >= 0) m_path = m_path.left(i); int port = url.port(80); if (port != 80) m_host.append(":").append(QString::number(port)); qDebug() << "Raven client is ready"; m_initialized = true; } QString levelString(Raven::RavenLevel level) { switch (level) { case Raven::Fatal: return "fatal"; case Raven::Error: return "error"; case Raven::Warning: return "warning"; case Raven::Info: return "info"; case Raven::Debug: return "debug"; } return "debug"; } RavenMessage Raven::operator()(Raven::RavenLevel level, QString culprit) { RavenMessage event; event.m_body = QJsonObject(m_eventTemplate); event.m_tags = QJsonObject(m_tagsTemplate); event.m_body["event_id"] = QUuid::createUuid().toString().remove('{').remove('}').remove('-'); event.m_body["level"] = levelString(level); event.m_body["timestamp"] = QDateTime::currentDateTimeUtc().toString(Qt::ISODate); event.m_body["culprit"] = culprit; event.m_instance = this; return event; } Raven* Raven::operator<<(const RavenTag& tag) { m_tagsTemplate[tag.first] = tag.second; return this; } bool Raven::isInitialized() const { return m_initialized; } static const QList<QString> _requiredAttributes = { "event_id", "message", "timestamp", "level", "logger", "platform", "sdk", "device" }; void Raven::capture(const RavenMessage& message) { if (!isInitialized()) return; QJsonObject body = QJsonObject(message.m_body); body["tags"] = message.m_tags; for (const auto& attributeName : _requiredAttributes) { Q_ASSERT(body.contains(attributeName)); } send(body); } void Raven::send(QJsonObject& message) { QString clientInfo = QString("%1/%2").arg(RAVEN_CLIENT_NAME, RAVEN_CLIENT_VERSION); QString authInfo = QString("Sentry sentry_version=7," "sentry_client=%1," "sentry_timestamp=%2," "sentry_key=%3," "sentry_secret=%4") .arg(clientInfo, QString::number(time(NULL)), m_publicKey, m_secretKey); QString url = QString("%1://%2%3/api/%4/store/") .arg(m_protocol, m_host, m_path, m_projectId); QString uuid = message["event_id"].toString(); qDebug() << "url=" << url << ",uuid=" << uuid; QNetworkRequest request(url); request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json"); request.setHeader(QNetworkRequest::UserAgentHeader, clientInfo); request.setAttribute(RavenUuidAttribute, uuid); request.setRawHeader("X-Sentry-Auth", authInfo.toUtf8()); QByteArray body = QJsonDocument(message).toJson(QJsonDocument::Indented); qDebug() << body; { QMutexLocker lk(&m_pendingMutex); m_pendingRequest[uuid] = body; } m_networkAccessManager->post(request, body); } void Raven::requestFinished(QNetworkReply* reply) { QUrl redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute) .toUrl(); QString uuid = reply->request().attribute(RavenUuidAttribute).toString(); QByteArray body = m_pendingRequest[uuid]; if (!redirectUrl.isEmpty() && redirectUrl != reply->url()) { QNetworkRequest request = reply->request(); request.setUrl(redirectUrl); m_networkAccessManager->post(request, body); } else { if (reply->error() == QNetworkReply::NoError) { qDebug() << "Event sent " << reply->readAll(); } else { qDebug() << "Failed to send message to sentry: " << reply->error(); qDebug() << "Sentry answer: " << reply->readAll(); save(uuid, body); } { QMutexLocker lk(&m_pendingMutex); m_pendingRequest.remove(uuid); } emit eventSent(uuid); } reply->deleteLater(); } void Raven::sslErrors(QNetworkReply* reply, const QList<QSslError>& errors) { reply->ignoreSslErrors(); } void Raven::save(const QString& uuid, QByteArray& message) { QString messageDir = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation); messageDir = QDir::cleanPath(messageDir + QDir::separator() + "messages"); QString messageFile = QDir::cleanPath(messageDir + QDir::separator() + uuid); QFile file(messageFile); if (file.open(QIODevice::WriteOnly)) { file.write(message); } else { qWarning() << "Could not save message, it will be discarded"; } } RavenMessage& Raven::send(RavenMessage& message) { message.m_instance->capture(message); return message; } RavenTag Raven::tag(const QString& name, const QString& value) { return RavenTag(name, value); } void Raven::sendAllPending() { QString messageDir = QStandardPaths::writableLocation( QStandardPaths::AppLocalDataLocation); messageDir = QDir::cleanPath(messageDir + QDir::separator() + "messages"); QDirIterator it(messageDir, QDir::Files); while (it.hasNext()) { auto messageFile = it.next(); QFile file(messageFile); if (file.open(QIODevice::ReadOnly)) { QByteArray body = file.readAll(); QJsonParseError error; QJsonDocument doc = QJsonDocument::fromJson(body, &error); if (error.error == QJsonParseError::NoError) { QJsonObject object = doc.object(); send(object); } else { qDebug() << "Could not parse message " << messageFile << ": " << error.errorString(); } } else { qDebug() << "Could not open file " << messageFile; } } } RavenMessage& RavenMessage::operator<<(const QString& message) { m_body["message"] = message; return *this; } RavenMessage& RavenMessage::operator<<(const std::exception& exc) { m_body["message"] = exc.what(); return *this; } RavenMessage& RavenMessage::operator<<(const RavenTag& tag) { m_tags[tag.first] = tag.second; return *this; } RavenMessage& RavenMessage::operator<<(RavenMessage& (*pf)(RavenMessage&)) { return (*pf)(*this); } QString Raven::locationInfo(const char* file, const char* func, int line) { return QString("%1 in %2 at %3") .arg(file) .arg(func) .arg(QString::number(line)); }
Send OS version and type using QSysInfo
Send OS version and type using QSysInfo
C++
mit
TruePositiveLab/qraven
7c3b57dbf3098f0971b617478fa1ae42d83f9ca0
libplugins/libintradisplayfilter/intradisplayfilter.cpp
libplugins/libintradisplayfilter/intradisplayfilter.cpp
#include "intradisplayfilter.h" #include <QDebug> #include <QMap> #include <qmath.h> /// Intra direction rotation degree static qreal s_aiIntraRotation[] = { 0, 0, ///< [0, 1] Planar, DC (Invalid) 225.00, 219.09, 213.27, 207.98, 202.11, 195.71, 188.88, 183.57, ///< [2, 9] 180.00, 176.43, 171.12, 164.29, 157.89, 152.02, 146.73, 140.91, 135, ///< [10, 18] 129.09, 123.27, 117.98, 112.11, 105.71, 98.88, 93.57, 90.00, ///< [19, 26] 86.43, 81.12, 74.29, 67.89, 62.02, 56.73, 50.91, 45.00 ///< [27, 34] }; //3.57,8.88,15.71,22.11,27.98,33.27,39.09,45 IntraDisplayFilter::IntraDisplayFilter(QObject *parent) : QObject(parent) { setName("Intra Mode Display"); m_cConfigDialog.setWindowTitle("Intra Mode Filter"); m_cConfigDialog.addColorPicker("Color", &m_cConfig.getColor()); m_cConfigDialog.addSlider("Opaque", 0.0, 1.0, &m_cConfig.getOpaque()); } bool IntraDisplayFilter::config (FilterContext* pcContext) { m_cConfigDialog.exec(); m_cConfig.applyOpaque(); return true; } bool IntraDisplayFilter::drawPU (FilterContext* pcContext, QPainter* pcPainter, ComPU *pcPU, double dScale, QRect* pcScaledArea) { /// Set Pen pcPainter->setBrush(Qt::NoBrush); pcPainter->setPen(m_cConfig.getColor()); /// Draw intra mode if(pcPU->getPredMode() == MODE_INTRA) { int iIntraDir = pcPU->getIntraDirLuma(); pcPainter->setClipRect(*pcScaledArea, Qt::ReplaceClip); pcPainter->setClipping(true); if(iIntraDir == 0) /// PLANAR { pcPainter->drawEllipse(pcScaledArea->center(), pcScaledArea->width()/2-1, pcScaledArea->width()/2-1); } else if(iIntraDir == 1) /// DC { pcPainter->drawEllipse(pcScaledArea->topLeft(), pcScaledArea->width()/2-1, pcScaledArea->width()/2-1); } else if(iIntraDir >= 2 && iIntraDir <= 34) /// Angular { double dRotation = -s_aiIntraRotation[iIntraDir]; int iLength = pcScaledArea->width(); const QLine cLine(QPoint(0,0), QPoint(iLength, 0)); pcPainter->translate(pcScaledArea->center()); pcPainter->rotate(dRotation); pcPainter->drawLine(cLine); pcPainter->rotate(180); pcPainter->drawLine(cLine); pcPainter->resetMatrix(); } else { qCritical() << QString("Unexpected Intra Angular: %1").arg(iIntraDir); } pcPainter->setClipping(false); } return true; }
#include "intradisplayfilter.h" #include <QDebug> #include <QMap> #include <qmath.h> /// Intra direction rotation degree static qreal s_aiIntraRotation[] = { 0, 0, ///< [0, 1] Planar, DC (Invalid) 225.00, 219.09, 213.27, 207.98, 202.11, 195.71, 188.88, 183.57, ///< [2, 9] 180.00, 176.43, 171.12, 164.29, 157.89, 152.02, 146.73, 140.91, 135, ///< [10, 18] 129.09, 123.27, 117.98, 112.11, 105.71, 98.88, 93.57, 90.00, ///< [19, 26] 86.43, 81.12, 74.29, 67.89, 62.02, 56.73, 50.91, 45.00 ///< [27, 34] }; //3.57,8.88,15.71,22.11,27.98,33.27,39.09,45 IntraDisplayFilter::IntraDisplayFilter(QObject *parent) : QObject(parent) { setName("Intra Mode Display"); m_cConfigDialog.setWindowTitle("Intra Mode Filter"); m_cConfigDialog.addColorPicker("Color", &m_cConfig.getColor()); m_cConfigDialog.addSlider("Opaque", 0.0, 1.0, &m_cConfig.getOpaque()); } bool IntraDisplayFilter::config (FilterContext* pcContext) { m_cConfigDialog.exec(); m_cConfig.applyOpaque(); return true; } bool IntraDisplayFilter::drawPU (FilterContext* pcContext, QPainter* pcPainter, ComPU *pcPU, double dScale, QRect* pcScaledArea) { /// Set Pen pcPainter->setBrush(Qt::NoBrush); pcPainter->setPen(m_cConfig.getColor()); /// Draw intra mode if(pcPU->getPredMode() == MODE_INTRA) { int iIntraDir = pcPU->getIntraDirLuma(); pcPainter->setClipRect(*pcScaledArea, Qt::ReplaceClip); pcPainter->setClipping(true); if(iIntraDir == 0) /// PLANAR { pcPainter->drawEllipse(pcScaledArea->center(), pcScaledArea->width()/2-1, pcScaledArea->width()/2-1); } else if(iIntraDir == 1) /// DC { pcPainter->drawEllipse(pcScaledArea->topLeft(), pcScaledArea->width()/2-1, pcScaledArea->width()/2-1); } else if(iIntraDir >= 2 && iIntraDir <= 34) /// Angular { double dRotation = -s_aiIntraRotation[iIntraDir]; int iLength = pcScaledArea->width(); const QLine cLine(QPoint(0,0), QPoint(iLength, 0)); pcPainter->translate(pcScaledArea->center()); pcPainter->rotate(dRotation); pcPainter->drawLine(cLine); pcPainter->resetMatrix(); } else { qCritical() << QString("Unexpected Intra Angular: %1").arg(iIntraDir); } pcPainter->setClipping(false); } return true; }
improve intra filter (angular mode)
improve intra filter (angular mode)
C++
apache-2.0
linqiaozhou/GitlHEVCAnalyzer,lheric/GitlHEVCAnalyzer,linqiaozhou/GitlHEVCAnalyzer,lheric/GitlHEVCAnalyzer,lheric/GitlHEVCAnalyzer,linqiaozhou/GitlHEVCAnalyzer
41092135380beee467c38b6a36f2791e7b4d7803
opencog/reasoning/pln/rules/auxiliary/SubsetEvalRule.cc
opencog/reasoning/pln/rules/auxiliary/SubsetEvalRule.cc
/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "SubsetEvalRule.h" #include <opencog/util/platform.h> #include "../../PLN.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" namespace opencog { namespace pln { using std::set; using std::find; using std::find_if; const strength_t MIN_MEMBERS_STRENGTH = 0.000001; const strength_t MIN_MEMBERS_COUNT = 1; SubsetEvalRule::SubsetEvalRule(AtomSpaceWrapper* asw, Type argType) : Rule(asw, false, true, "SubsetEvalRule"), ArgType(argType), _asw(asw) { inputFilter.push_back(meta(new tree<Vertex>(mva((pHandle)ArgType)))); inputFilter.push_back(meta(new tree<Vertex>(mva((pHandle)ArgType)))); } Rule::setOfMPs SubsetEvalRule::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { if(!_asw->inheritsType((Type)_v2h(*outh->begin()), SUBSET_LINK)) return setOfMPs(); tree<Vertex>::iterator head_it = outh->begin(); Rule::MPs ret; // Return the two arguments; if they're ATOM, make them more specific. if (_v2h(*outh->begin(head_it)) == ATOM) ret.push_back(BBvtree(new BoundVTree(mva((pHandle)ArgType)))); else ret.push_back(BBvtree(new BoundVTree(outh->begin(head_it)))); if (_v2h(*outh->last_child(head_it)) == ATOM) ret.push_back(BBvtree(new BoundVTree(mva((pHandle)ArgType)))); else ret.push_back(BBvtree(new BoundVTree(outh->last_child(head_it)))); overrideInputFilter = true; return makeSingletonSet(ret); } meta SubsetEvalRule::i2oType(const vector<Vertex>& h_vec) const { OC_ASSERT(h_vec.size()==2); return meta(new tree<Vertex>(mva((pHandle)SUBSET_LINK, vtree(h_vec[0]), vtree(h_vec[1]) ))); } TruthValue** SubsetEvalRule::formatTVarray(const std::vector<Vertex>& premises, int* newN) const { OC_ASSERT(premises.size() == 2); pHandle sub_h = _v2h(premises[0]); pHandle super_h = _v2h(premises[1]); // OC_ASSERT(_asw->isSubType(sub_h, CONCEPT_NODE)); // OC_ASSERT(_asw->isSubType(super_h, CONCEPT_NODE)); pHandleSet used; pHandleSet mlSetSub = memberLinkSet(sub_h, MIN_MEMBERS_STRENGTH, MIN_MEMBERS_COUNT, _asw); pHandleSet mlSetSuper = memberLinkSet(super_h, MIN_MEMBERS_STRENGTH, MIN_MEMBERS_COUNT, _asw); vector<TruthValue*> tvsSub; vector<TruthValue*> tvsSuper; // We fill tvsSub and tvsSuper by padding the missing TVs with zeros // so that each element of tvsSub and tvsSuper are aligned foreach(const pHandle& h_ml_sub, mlSetSub) { //std::cout << _asw->pHandleToString(h_ml_sub) << std::endl; tvsSub.push_back(_asw->getTV(h_ml_sub).clone()); EqOutgoing eqMember(h_ml_sub, 0, _asw); pHandleSetConstIt h_ml_super_cit = find_if(mlSetSuper.begin(), mlSetSuper.end(), eqMember); if (h_ml_super_cit == mlSetSuper.end()) tvsSuper.push_back(new SimpleTruthValue(0, 0)); else { tvsSuper.push_back(_asw->getTV(*h_ml_super_cit).clone()); used.insert(*h_ml_super_cit); } } foreach(const pHandle& h_ml_super, mlSetSuper) { //std::cout << _asw->pHandleToString(h_ml_super) << std::endl; if (!STLhas(used, h_ml_super)) { tvsSuper.push_back(_asw->getTV(h_ml_super).clone()); tvsSub.push_back(new SimpleTruthValue(0, 0)); } } assert(tvsSub.size() == tvsSuper.size()); unsigned int N = tvsSub.size(); // std::cout << "SUB" << std::endl; // for(unsigned int i = 0; i < N; i++) { // std::cout << tvsSub[i]->toString() << std::endl; // } // std::cout << "SUPER" << std::endl; // for(unsigned int i = 0; i < N; i++) { // std::cout << tvsSuper[i]->toString() << std::endl; // } *newN = 2 * N; TruthValue** tvs = new TruthValue*[*newN]; std::copy(tvsSub.begin(), tvsSub.end(), tvs); std::copy(tvsSuper.begin(), tvsSuper.end(), tvs + N); return tvs; } BoundVertex SubsetEvalRule::compute(const vector<Vertex>& premiseArray, pHandle CX, bool fresh) const { int N; TruthValue** tvs = formatTVarray(premiseArray, &N); TruthValue* retTV = formula.compute(tvs, N); for (unsigned int i = 0; i < (unsigned int)N; i++) { delete tvs[i]; } delete tvs; pHandle ret = _asw->addAtom(*i2oType(premiseArray), *retTV, fresh); return BoundVertex(ret); } }} // namespace opencog { namespace pln {
/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * 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 Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "SubsetEvalRule.h" #include <opencog/util/platform.h> #include "../../PLN.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" namespace opencog { namespace pln { using std::set; using std::find; using std::find_if; const strength_t MIN_MEMBERS_STRENGTH = 0.000001; const strength_t MIN_MEMBERS_COUNT = 1; SubsetEvalRule::SubsetEvalRule(AtomSpaceWrapper* asw, Type argType) : Rule(asw, false, true, "SubsetEvalRule"), ArgType(argType), _asw(asw) { inputFilter.push_back(meta(new tree<Vertex>(mva((pHandle)ArgType)))); inputFilter.push_back(meta(new tree<Vertex>(mva((pHandle)ArgType)))); } Rule::setOfMPs SubsetEvalRule::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { if(!_asw->inheritsType((Type)_v2h(*outh->begin()), SUBSET_LINK)) return setOfMPs(); tree<Vertex>::iterator head_it = outh->begin(); Rule::MPs ret; // Return the two arguments; if they're ATOM, make them more specific. if (_v2h(*outh->begin(head_it)) == ATOM) ret.push_back(BBvtree(new BoundVTree(mva((pHandle)ArgType)))); else ret.push_back(BBvtree(new BoundVTree(outh->begin(head_it)))); if (_v2h(*outh->last_child(head_it)) == ATOM) ret.push_back(BBvtree(new BoundVTree(mva((pHandle)ArgType)))); else ret.push_back(BBvtree(new BoundVTree(outh->last_child(head_it)))); overrideInputFilter = true; return makeSingletonSet(ret); } meta SubsetEvalRule::i2oType(const vector<Vertex>& h_vec) const { OC_ASSERT(h_vec.size()==2); return meta(new tree<Vertex>(mva((pHandle)SUBSET_LINK, vtree(h_vec[0]), vtree(h_vec[1]) ))); } TruthValue** SubsetEvalRule::formatTVarray(const std::vector<Vertex>& premises, int* newN) const { OC_ASSERT(premises.size() == 2); pHandle sub_h = _v2h(premises[0]); pHandle super_h = _v2h(premises[1]); // OC_ASSERT(_asw->isSubType(sub_h, CONCEPT_NODE)); // OC_ASSERT(_asw->isSubType(super_h, CONCEPT_NODE)); pHandleSet used; pHandleSet mlSetSub = memberLinkSet(sub_h, MIN_MEMBERS_STRENGTH, MIN_MEMBERS_COUNT, _asw); pHandleSet mlSetSuper = memberLinkSet(super_h, MIN_MEMBERS_STRENGTH, MIN_MEMBERS_COUNT, _asw); vector<TruthValue*> tvsSub; vector<TruthValue*> tvsSuper; // We fill tvsSub and tvsSuper by padding the missing TVs with zeros // so that each element of tvsSub and tvsSuper are aligned foreach(const pHandle& h_ml_sub, mlSetSub) { //std::cout << _asw->pHandleToString(h_ml_sub) << std::endl; tvsSub.push_back(_asw->getTV(h_ml_sub).clone()); EqOutgoing eqMember(h_ml_sub, 0, _asw); pHandleSetConstIt h_ml_super_cit = find_if(mlSetSuper.begin(), mlSetSuper.end(), eqMember); if (h_ml_super_cit == mlSetSuper.end()) tvsSuper.push_back(new SimpleTruthValue(0, 0)); else { tvsSuper.push_back(_asw->getTV(*h_ml_super_cit).clone()); used.insert(*h_ml_super_cit); } } foreach(const pHandle& h_ml_super, mlSetSuper) { //std::cout << _asw->pHandleToString(h_ml_super) << std::endl; if (!STLhas(used, h_ml_super)) { tvsSuper.push_back(_asw->getTV(h_ml_super).clone()); tvsSub.push_back(new SimpleTruthValue(0, 0)); } } assert(tvsSub.size() == tvsSuper.size()); unsigned int N = tvsSub.size(); // std::cout << "SUB" << std::endl; // for(unsigned int i = 0; i < N; i++) { // std::cout << tvsSub[i]->toString() << std::endl; // } // std::cout << "SUPER" << std::endl; // for(unsigned int i = 0; i < N; i++) { // std::cout << tvsSuper[i]->toString() << std::endl; // } *newN = 2 * N; TruthValue** tvs = new TruthValue*[*newN]; std::copy(tvsSub.begin(), tvsSub.end(), tvs); std::copy(tvsSuper.begin(), tvsSuper.end(), tvs + N); return tvs; } BoundVertex SubsetEvalRule::compute(const vector<Vertex>& premiseArray, pHandle CX, bool fresh) const { int N; TruthValue** tvs = formatTVarray(premiseArray, &N); TruthValue* retTV = formula.compute(tvs, N); for (unsigned int i = 0; i < (unsigned int)N; i++) { delete tvs[i]; } delete[] tvs; pHandle ret = _asw->addAtom(*i2oType(premiseArray), *retTV, fresh); return BoundVertex(ret); } }} // namespace opencog { namespace pln {
Use correct deletion on SubsetEvalRule.
Use correct deletion on SubsetEvalRule.
C++
agpl-3.0
jlegendary/opencog,williampma/opencog,inflector/opencog,TheNameIsNigel/opencog,eddiemonroe/opencog,UIKit0/atomspace,ceefour/atomspace,rohit12/opencog,Allend575/opencog,rohit12/opencog,ruiting/opencog,jswiergo/atomspace,ArvinPan/atomspace,virneo/atomspace,jlegendary/opencog,AmeBel/opencog,cosmoharrigan/atomspace,anitzkin/opencog,eddiemonroe/atomspace,ruiting/opencog,williampma/atomspace,williampma/opencog,virneo/opencog,andre-senna/opencog,rodsol/atomspace,kinoc/opencog,prateeksaxena2809/opencog,Allend575/opencog,ArvinPan/opencog,rohit12/opencog,tim777z/opencog,rohit12/opencog,zhaozengguang/opencog,anitzkin/opencog,andre-senna/opencog,virneo/atomspace,sumitsourabh/opencog,eddiemonroe/opencog,williampma/opencog,ceefour/opencog,Selameab/opencog,iAMr00t/opencog,yantrabuddhi/atomspace,zhaozengguang/opencog,ceefour/opencog,rohit12/atomspace,kim135797531/opencog,rTreutlein/atomspace,Selameab/opencog,virneo/atomspace,rohit12/opencog,kinoc/opencog,ArvinPan/opencog,andre-senna/opencog,inflector/opencog,printedheart/atomspace,Selameab/atomspace,UIKit0/atomspace,inflector/atomspace,misgeatgit/opencog,yantrabuddhi/opencog,Tiggels/opencog,printedheart/opencog,rodsol/atomspace,gavrieltal/opencog,gavrieltal/opencog,rodsol/opencog,prateeksaxena2809/opencog,roselleebarle04/opencog,sanuj/opencog,iAMr00t/opencog,MarcosPividori/atomspace,jlegendary/opencog,ceefour/atomspace,yantrabuddhi/opencog,williampma/atomspace,kinoc/opencog,gaapt/opencog,ArvinPan/opencog,ArvinPan/atomspace,sumitsourabh/opencog,anitzkin/opencog,virneo/atomspace,rTreutlein/atomspace,virneo/opencog,yantrabuddhi/opencog,rTreutlein/atomspace,virneo/opencog,printedheart/opencog,andre-senna/opencog,Allend575/opencog,UIKit0/atomspace,inflector/atomspace,cosmoharrigan/atomspace,zhaozengguang/opencog,prateeksaxena2809/opencog,ArvinPan/atomspace,gavrieltal/opencog,AmeBel/atomspace,kinoc/opencog,yantrabuddhi/atomspace,ceefour/opencog,AmeBel/atomspace,AmeBel/atomspace,sumitsourabh/opencog,anitzkin/opencog,eddiemonroe/opencog,shujingke/opencog,gaapt/opencog,AmeBel/atomspace,misgeatgit/opencog,printedheart/atomspace,williampma/opencog,MarcosPividori/atomspace,rodsol/atomspace,rodsol/opencog,yantrabuddhi/opencog,AmeBel/opencog,inflector/opencog,UIKit0/atomspace,gaapt/opencog,gaapt/opencog,williampma/atomspace,printedheart/opencog,misgeatgit/opencog,yantrabuddhi/opencog,Selameab/atomspace,printedheart/atomspace,kinoc/opencog,printedheart/opencog,sanuj/opencog,prateeksaxena2809/opencog,kim135797531/opencog,roselleebarle04/opencog,Selameab/atomspace,sumitsourabh/opencog,eddiemonroe/opencog,yantrabuddhi/atomspace,AmeBel/atomspace,cosmoharrigan/opencog,yantrabuddhi/opencog,Selameab/opencog,andre-senna/opencog,misgeatgit/atomspace,printedheart/atomspace,yantrabuddhi/atomspace,yantrabuddhi/opencog,sumitsourabh/opencog,ArvinPan/opencog,zhaozengguang/opencog,ceefour/atomspace,shujingke/opencog,inflector/atomspace,misgeatgit/opencog,williampma/atomspace,tim777z/opencog,virneo/opencog,sanuj/opencog,misgeatgit/opencog,Selameab/opencog,inflector/opencog,zhaozengguang/opencog,printedheart/opencog,rTreutlein/atomspace,inflector/opencog,cosmoharrigan/atomspace,jswiergo/atomspace,TheNameIsNigel/opencog,Tiggels/opencog,Tiggels/opencog,anitzkin/opencog,Allend575/opencog,ArvinPan/atomspace,sanuj/opencog,shujingke/opencog,ceefour/opencog,virneo/opencog,roselleebarle04/opencog,jlegendary/opencog,inflector/opencog,gavrieltal/opencog,Allend575/opencog,iAMr00t/opencog,eddiemonroe/atomspace,rodsol/opencog,virneo/opencog,tim777z/opencog,AmeBel/opencog,AmeBel/opencog,rohit12/atomspace,roselleebarle04/opencog,roselleebarle04/opencog,jlegendary/opencog,yantrabuddhi/atomspace,rohit12/opencog,eddiemonroe/opencog,ruiting/opencog,rodsol/opencog,ArvinPan/opencog,roselleebarle04/opencog,cosmoharrigan/opencog,rohit12/atomspace,sumitsourabh/opencog,roselleebarle04/opencog,jlegendary/opencog,cosmoharrigan/opencog,inflector/atomspace,shujingke/opencog,zhaozengguang/opencog,kinoc/opencog,kim135797531/opencog,andre-senna/opencog,kim135797531/opencog,AmeBel/opencog,anitzkin/opencog,ruiting/opencog,rTreutlein/atomspace,AmeBel/opencog,shujingke/opencog,inflector/atomspace,ceefour/opencog,Allend575/opencog,prateeksaxena2809/opencog,cosmoharrigan/opencog,TheNameIsNigel/opencog,ArvinPan/opencog,cosmoharrigan/opencog,Tiggels/opencog,Selameab/atomspace,tim777z/opencog,ceefour/atomspace,Selameab/opencog,ceefour/opencog,cosmoharrigan/atomspace,eddiemonroe/atomspace,rodsol/opencog,ruiting/opencog,AmeBel/opencog,inflector/opencog,tim777z/opencog,virneo/opencog,kim135797531/opencog,inflector/opencog,tim777z/opencog,misgeatgit/atomspace,shujingke/opencog,gaapt/opencog,printedheart/opencog,iAMr00t/opencog,eddiemonroe/atomspace,rodsol/atomspace,Tiggels/opencog,Allend575/opencog,rohit12/atomspace,Selameab/opencog,kim135797531/opencog,kinoc/opencog,misgeatgit/atomspace,iAMr00t/opencog,misgeatgit/atomspace,misgeatgit/opencog,jlegendary/opencog,shujingke/opencog,cosmoharrigan/opencog,gavrieltal/opencog,sanuj/opencog,misgeatgit/atomspace,anitzkin/opencog,jswiergo/atomspace,gaapt/opencog,gaapt/opencog,jswiergo/atomspace,eddiemonroe/opencog,ruiting/opencog,kim135797531/opencog,rodsol/opencog,ceefour/opencog,prateeksaxena2809/opencog,misgeatgit/opencog,iAMr00t/opencog,TheNameIsNigel/opencog,MarcosPividori/atomspace,MarcosPividori/atomspace,sanuj/opencog,andre-senna/opencog,eddiemonroe/atomspace,Tiggels/opencog,misgeatgit/opencog,gavrieltal/opencog,williampma/opencog,ruiting/opencog,TheNameIsNigel/opencog,williampma/opencog,misgeatgit/opencog,eddiemonroe/opencog,gavrieltal/opencog,TheNameIsNigel/opencog,sumitsourabh/opencog,prateeksaxena2809/opencog
f43a3af5291a5f3d4f96d9233f8a0c354f23872d
moveit_ros/visualization/rviz_plugin_render_tools/src/robot_state_visualization.cpp
moveit_ros/visualization/rviz_plugin_render_tools/src/robot_state_visualization.cpp
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <QApplication> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property) , octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS) , octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR) , visible_(true) , visual_visible_(true) , collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface& descr, bool visual, bool collision) { // clear previously loaded model clear(); robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::clear() { render_shapes_->clear(); robot_.clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA& default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::updateAttachedObjectColors(const std_msgs::ColorRGBA& attached_object_color) { render_shapes_->updateShapeColors(attached_object_color.r, attached_object_color.g, attached_object_color.b, robot_.getAlpha()); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, nullptr); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, nullptr); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>& color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>* color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const moveit::core::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (const moveit::core::AttachedBody* attached_body : attached_bodies) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_body->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Isometry3d& ab_t = attached_body->getGlobalCollisionBodyTransforms(); const std::vector<shapes::ShapeConstPtr>& ab_shapes = attached_body->getShapes(); for (std::size_t j = 0; j < ab_shapes.size(); ++j) { render_shapes_->renderShape(robot_.getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(robot_.getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } } // namespace moveit_rviz_plugin
/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2012, Willow Garage, 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 Willow Garage 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. *********************************************************************/ /* Author: Ioan Sucan */ #include <moveit/rviz_plugin_render_tools/robot_state_visualization.h> #include <moveit/rviz_plugin_render_tools/planning_link_updater.h> #include <moveit/rviz_plugin_render_tools/render_shapes.h> #include <QApplication> namespace moveit_rviz_plugin { RobotStateVisualization::RobotStateVisualization(Ogre::SceneNode* root_node, rviz::DisplayContext* context, const std::string& name, rviz::Property* parent_property) : robot_(root_node, context, name, parent_property) , octree_voxel_render_mode_(OCTOMAP_OCCUPIED_VOXELS) , octree_voxel_color_mode_(OCTOMAP_Z_AXIS_COLOR) , visible_(true) , visual_visible_(true) , collision_visible_(false) { default_attached_object_color_.r = 0.0f; default_attached_object_color_.g = 0.7f; default_attached_object_color_.b = 0.0f; default_attached_object_color_.a = 1.0f; render_shapes_.reset(new RenderShapes(context)); } void RobotStateVisualization::load(const urdf::ModelInterface& descr, bool visual, bool collision) { // clear previously loaded model clear(); robot_.load(descr, visual, collision); robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::clear() { render_shapes_->clear(); robot_.clear(); } void RobotStateVisualization::setDefaultAttachedObjectColor(const std_msgs::ColorRGBA& default_attached_object_color) { default_attached_object_color_ = default_attached_object_color; } void RobotStateVisualization::updateAttachedObjectColors(const std_msgs::ColorRGBA& attached_object_color) { render_shapes_->updateShapeColors(attached_object_color.r, attached_object_color.g, attached_object_color.b, robot_.getAlpha()); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state) { updateHelper(kinematic_state, default_attached_object_color_, nullptr); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color) { updateHelper(kinematic_state, default_attached_object_color, nullptr); } void RobotStateVisualization::update(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>& color_map) { updateHelper(kinematic_state, default_attached_object_color, &color_map); } void RobotStateVisualization::updateHelper(const moveit::core::RobotStateConstPtr& kinematic_state, const std_msgs::ColorRGBA& default_attached_object_color, const std::map<std::string, std_msgs::ColorRGBA>* color_map) { robot_.update(PlanningLinkUpdater(kinematic_state)); render_shapes_->clear(); std::vector<const moveit::core::AttachedBody*> attached_bodies; kinematic_state->getAttachedBodies(attached_bodies); for (const moveit::core::AttachedBody* attached_body : attached_bodies) { std_msgs::ColorRGBA color = default_attached_object_color; float alpha = robot_.getAlpha(); if (color_map) { std::map<std::string, std_msgs::ColorRGBA>::const_iterator it = color_map->find(attached_body->getName()); if (it != color_map->end()) { // render attached bodies with a color that is a bit different color.r = std::max(1.0f, it->second.r * 1.05f); color.g = std::max(1.0f, it->second.g * 1.05f); color.b = std::max(1.0f, it->second.b * 1.05f); alpha = color.a = it->second.a; } } rviz::RobotLink* link = robot_.getLink(attached_body->getAttachedLinkName()); if (!link) { ROS_ERROR_STREAM("Link " << attached_body->getAttachedLinkName() << " not found in rviz::Robot"); continue; } rviz::Color rcolor(color.r, color.g, color.b); const EigenSTL::vector_Isometry3d& ab_t = attached_body->getFixedTransforms(); const std::vector<shapes::ShapeConstPtr>& ab_shapes = attached_body->getShapes(); for (std::size_t j = 0; j < ab_shapes.size(); ++j) { render_shapes_->renderShape(link->getVisualNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); render_shapes_->renderShape(link->getCollisionNode(), ab_shapes[j].get(), ab_t[j], octree_voxel_render_mode_, octree_voxel_color_mode_, rcolor, alpha); } } robot_.setVisualVisible(visual_visible_); robot_.setCollisionVisible(collision_visible_); robot_.setVisible(visible_); } void RobotStateVisualization::setVisible(bool visible) { visible_ = visible; robot_.setVisible(visible); } void RobotStateVisualization::setVisualVisible(bool visible) { visual_visible_ = visible; robot_.setVisualVisible(visible); } void RobotStateVisualization::setCollisionVisible(bool visible) { collision_visible_ = visible; robot_.setCollisionVisible(visible); } void RobotStateVisualization::setAlpha(float alpha) { robot_.setAlpha(alpha); } } // namespace moveit_rviz_plugin
attach objects to the corresponding link
attach objects to the corresponding link instead of the robots root node, this will move them automatically
C++
bsd-3-clause
ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit,ros-planning/moveit
6c8deaccda7f1d4aaa72184b366ec2b92929de40
source/FAST/Algorithms/ModelBasedSegmentation/AppearanceModels/StepEdge/StepEdgeModel.cpp
source/FAST/Algorithms/ModelBasedSegmentation/AppearanceModels/StepEdge/StepEdgeModel.cpp
#include "StepEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" namespace fast { StepEdgeModel::StepEdgeModel() { mLineLength = 0; mLineSampleSpacing = 0; } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile) { // Pre calculate partial sum float * sum_k = new float[intensityProfile.size()](); float totalSum = 0.0f; for(int k = 0; k < intensityProfile.size(); ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int k = 0; k < intensityProfile.size()-1; ++k) { float score = 0.0f; for(int t = 0; t <= k; ++t) { score += fabs((1.0f/(k+1))*sum_k[k] - intensityProfile[t]); } for(int t = k+1; t < intensityProfile.size(); ++t) { score += fabs((1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; bestHeightDifference = (((1.0/(k+1))*sum_k[bestK] - (1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[bestK]))); } } delete[] sum_k; DetectedEdge edge; const float differenceThreshold = 20; if(bestHeightDifference >= 0) { // Black inside, white outside edge.edgeIndex = -1; } else if(fabs(bestHeightDifference) < differenceThreshold) { edge.edgeIndex = -1; } else { edge.edgeIndex = bestK; edge.uncertainty = 1.0f/fabs(bestHeightDifference); } return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the StepEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y() / spacing.y())); try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void StepEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void StepEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } }
#include "StepEdgeModel.hpp" #include "FAST/Data/Image.hpp" #include "FAST/Algorithms/ModelBasedSegmentation/Shape.hpp" #include <boost/shared_array.hpp> namespace fast { StepEdgeModel::StepEdgeModel() { mLineLength = 0; mLineSampleSpacing = 0; } typedef struct DetectedEdge { int edgeIndex; float uncertainty; } DetectedEdge; inline DetectedEdge findEdge( std::vector<float> intensityProfile) { // Pre calculate partial sum boost::shared_array<float> sum_k(new float[intensityProfile.size()]()); float totalSum = 0.0f; for(int k = 0; k < intensityProfile.size(); ++k) { if(k == 0) { sum_k[k] = intensityProfile[0]; }else{ sum_k[k] = sum_k[k-1] + intensityProfile[k]; } totalSum += intensityProfile[k]; } float bestScore = std::numeric_limits<float>::max(); int bestK = -1; float bestHeightDifference = 0; for(int k = 0; k < intensityProfile.size()-1; ++k) { float score = 0.0f; for(int t = 0; t <= k; ++t) { score += fabs((1.0f/(k+1))*sum_k[k] - intensityProfile[t]); } for(int t = k+1; t < intensityProfile.size(); ++t) { score += fabs((1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[k]) - intensityProfile[t]); } if(score < bestScore) { bestScore = score; bestK = k; bestHeightDifference = (((1.0/(k+1))*sum_k[bestK] - (1.0f/(intensityProfile.size()-k))*(totalSum-sum_k[bestK]))); } } DetectedEdge edge; const float differenceThreshold = 20; if(bestHeightDifference >= 0) { // Black inside, white outside edge.edgeIndex = -1; } else if(fabs(bestHeightDifference) < differenceThreshold) { edge.edgeIndex = -1; } else { edge.edgeIndex = bestK; edge.uncertainty = 1.0f/fabs(bestHeightDifference); } return edge; } inline bool isInBounds(Image::pointer image, const Vector4f& position) { return position(0) >= 0 && position(1) >= 0 && position(2) >= 0 && position(0) < image->getWidth() && position(1) < image->getHeight() && position(2) < image->getDepth(); } inline float getValue(void* pixelPointer, Image::pointer image, const Vector4f& position) { uint index = (int)position(0)+(int)position(1)*image->getWidth()+(int)position(2)*image->getWidth()*image->getHeight(); float value; switch(image->getDataType()) { // This macro creates a case statement for each data type and sets FAST_TYPE to the correct C++ data type fastSwitchTypeMacro(value = ((FAST_TYPE*)pixelPointer)[index]); } return value; } std::vector<Measurement> StepEdgeModel::getMeasurements(SharedPointer<Image> image, SharedPointer<Shape> shape) { if(mLineLength == 0 || mLineSampleSpacing == 0) throw Exception("Line length and sample spacing must be given to the StepEdgeModel"); std::vector<Measurement> measurements; Mesh::pointer predictedMesh = shape->getMesh(); MeshAccess::pointer predictedMeshAccess = predictedMesh->getMeshAccess(ACCESS_READ); std::vector<MeshVertex> points = predictedMeshAccess->getVertices(); ImageAccess::pointer access = image->getImageAccess(ACCESS_READ); // For each point on the shape do a line search in the direction of the normal // Return set of displacements and uncertainties if(image->getDimensions() == 3) { AffineTransformation::pointer transformMatrix = SceneGraph::getAffineTransformationFromData(image); transformMatrix->scale(image->getSpacing()); Matrix4f inverseTransformMatrix = transformMatrix->matrix().inverse(); // Get model scene graph transform AffineTransformation::pointer modelTransformation = SceneGraph::getAffineTransformationFromData(shape->getMesh()); MatrixXf modelTransformMatrix = modelTransformation->affine(); // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector3f position = points[i].getPosition() + points[i].getNormal()*d; // Apply model transform // TODO the line search normal*d should propably be applied after this transform, so that we know that is correct units? position = modelTransformMatrix*position.homogeneous(); const Vector4f longPosition(position(0), position(1), position(2), 1); // Apply image inverse transform to get image voxel position const Vector4f positionInt = inverseTransformMatrix*longPosition; try { const float value = access->getScalar(positionInt.cast<int>()); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector3f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector3f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } else { Vector3f spacing = image->getSpacing(); // For 2D images // For 2D, we probably want to ignore scene graph, and only use spacing. // Do edge detection for each vertex int counter = 0; for(int i = 0; i < points.size(); ++i) { std::vector<float> intensityProfile; unsigned int startPos = 0; bool startFound = false; for(float d = -mLineLength/2; d < mLineLength/2; d += mLineSampleSpacing) { Vector2f position = points[i].getPosition() + points[i].getNormal()*d; const Vector2i pixelPosition(round(position.x() / spacing.x()), round(position.y() / spacing.y())); try { const float value = access->getScalar(pixelPosition); if(value > 0) { intensityProfile.push_back(value); startFound = true; } else if(!startFound) { startPos++; } } catch(Exception &e) { if(!startFound) { startPos++; } } } Measurement m; m.uncertainty = 1; m.displacement = 0; if(startFound){ DetectedEdge edge = findEdge(intensityProfile); if(edge.edgeIndex != -1) { float d = -mLineLength/2.0f + (startPos + edge.edgeIndex)*mLineSampleSpacing; const Vector2f position = points[i].getPosition() + points[i].getNormal()*d; m.uncertainty = edge.uncertainty; const Vector2f normal = points[i].getNormal(); m.displacement = normal.dot(position-points[i].getPosition()); counter++; } } measurements.push_back(m); } } return measurements; } void StepEdgeModel::setLineLength(float length) { if(length <= 0) throw Exception("Length must be > 0"); mLineLength = length; } void StepEdgeModel::setLineSampleSpacing(float spacing) { if(spacing <= 0) throw Exception("Sample spacing must be > 0"); mLineSampleSpacing = spacing; } }
use boost shared array
use boost shared array
C++
bsd-2-clause
smistad/FAST,smistad/FAST,smistad/FAST
cec70c8b4f07ecca295b8db45cc09198f54b9e7c
quic/congestion_control/CongestionControlFunctions.cpp
quic/congestion_control/CongestionControlFunctions.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/congestion_control/CongestionControlFunctions.h> #include <quic/QuicConstants.h> #include <quic/common/TimeUtil.h> #include <algorithm> namespace quic { uint64_t boundedCwnd( uint64_t cwndBytes, uint64_t packetLength, uint64_t maxCwndInMss, uint64_t minCwndInMss) noexcept { return std::max( std::min(cwndBytes, maxCwndInMss * packetLength), minCwndInMss * packetLength); } std::pair<std::chrono::microseconds, uint64_t> calculatePacingRate( const QuicConnectionStateBase& conn, uint64_t cwnd, std::chrono::microseconds minimalInterval, std::chrono::microseconds rtt) { if (minimalInterval > rtt) { // We cannot really pace in this case. return std::make_pair( std::chrono::microseconds::zero(), conn.transportSettings.writeConnectionDataPacketsLimit); } uint64_t cwndInPackets = std::max( conn.transportSettings.minCwndInMss, cwnd / conn.udpSendPacketLen); // Each interval we want to send cwndInpackets / (rtt / minimalInverval) // number of packets. uint64_t burstPerInterval = std::min( conn.transportSettings.maxBurstPackets, std::max( conn.transportSettings.minCwndInMss, (uint64_t)std::ceil( (double)cwndInPackets * (double)minimalInterval.count() / (double)std::chrono::duration_cast<std::chrono::microseconds>(rtt) .count()))); auto interval = std::max( minimalInterval, std::chrono::duration_cast<std::chrono::microseconds>( rtt * burstPerInterval / cwndInPackets)); return std::make_pair(interval, burstPerInterval); } } // namespace quic
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * */ #include <quic/congestion_control/CongestionControlFunctions.h> #include <quic/QuicConstants.h> #include <quic/common/TimeUtil.h> #include <algorithm> namespace quic { uint64_t boundedCwnd( uint64_t cwndBytes, uint64_t packetLength, uint64_t maxCwndInMss, uint64_t minCwndInMss) noexcept { return std::max( std::min(cwndBytes, maxCwndInMss * packetLength), minCwndInMss * packetLength); } std::pair<std::chrono::microseconds, uint64_t> calculatePacingRate( const QuicConnectionStateBase& conn, uint64_t cwnd, std::chrono::microseconds minimalInterval, std::chrono::microseconds rtt) { if (minimalInterval > rtt) { // We cannot really pace in this case. return std::make_pair( std::chrono::microseconds::zero(), conn.transportSettings.writeConnectionDataPacketsLimit); } uint64_t cwndInPackets = std::max( conn.transportSettings.minCwndInMss, cwnd / conn.udpSendPacketLen); // Each interval we want to send cwndInpackets / (rtt / minimalInverval) // number of packets. uint64_t burstPerInterval = std::min( conn.transportSettings.maxBurstPackets, std::max( conn.transportSettings.minCwndInMss, (uint64_t)std::ceil( (double)cwndInPackets * (double)minimalInterval.count() / (double)rtt.count()))); auto interval = timeMax(minimalInterval, rtt * burstPerInterval / cwndInPackets); return std::make_pair(interval, burstPerInterval); } } // namespace quic
Use microseconds in bandwidth and rtt and BDP calculations in Quic BBR
Use microseconds in bandwidth and rtt and BDP calculations in Quic BBR Summary: This was stupid. bytes/s * s is bytes. bytes/us * us is also bytes. Thus there was no need to do the us to s conversion. The conversion also loses accuracy and can lead to over-/under-flows. Reviewed By: siyengar Differential Revision: D15216443 fbshipit-source-id: 8cb9318c87b553a496ee22e04cc835f77df409ba
C++
mit
facebookincubator/mvfst,facebookincubator/mvfst,facebookincubator/mvfst,facebookincubator/mvfst,facebookincubator/mvfst
94fedc41f3c6ef60647a6b81d1b5942a1be828fc
firmware/particle-functions.cpp
firmware/particle-functions.cpp
#include "particle-functions.h" int DST_offset = -7; void particleInit() { Particle.function ("ghData" , ghData); Particle.function ("passProgram" , passProgramParam); Particle.function ("motor" , motor); Particle.function ("dst" , setDST); setTimezone(DST_offset); } int ghData(String data) { //Expected parameters in CSV format // 1. Unix time stamp // 2. current greenhouse temperature // 3. current greenhouse humidity // 4. backup sensor current greenhouse temperature // 5. backup sensor current greenhouse humidity // 6. current outside temperature // 7. current outside humidity // 8. solar radiation // 9. forecast high // 10. forecast low char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); unsigned int weatherTime = atoi(p); p = strtok(NULL,","); int greenhouseTemp = atoi(p); p = strtok(NULL,","); int greenhouseHumidity = atoi(p); p = strtok(NULL,","); int backupGreenhouseTemp = atoi(p); p = strtok(NULL,","); int backupGreenhouseHumidity = atoi(p); p = strtok(NULL,","); int outsideTemp = atoi(p); p = strtok(NULL,","); int outsideHumidity = atoi(p); p = strtok(NULL,","); int solar = atoi(p); p = strtok(NULL,","); int high = atoi(p); p = strtok(NULL,","); int low = atoi(p); /*weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp, backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low); */ Serial.println("data loaded to greenhouseData"); Serial.println(data); return 1; } int passProgramParam(String data) { char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); int AMsetback = atoi(p); p = strtok(NULL,","); int PMsetback = atoi(p); p = strtok(NULL,","); int dayProgram = atoi(p); p = strtok(NULL,","); int nightProgram = atoi(p); Serial.println("data loaded to setProgram"); Serial.println(data); return 1; } int motor(String data) { Serial.println("motor function called"); char copyStr[64]; data.toCharArray(copyStr,64); int pass_param = atoi(copyStr); // converts character array into int, subtracts 1 to get index # of program row from programParam array //char * param = new char[5]; // creates character array to store program variable from RESTful call //strcpy(param, data.c_str()); // copies program variable into character array //int pass_param = atoi(param); // converts character array into int, subtracts 1 to get index # of program row from programParam array //motor.setM1Speed(pass_param); Serial.println("data loaded to Test Function"); Serial.println(data); return 1; } int setDST(String data) { char copyStr[64]; data.toCharArray(copyStr,64); DST_offset = atoi(copyStr); setTimezone(DST_offset); // call to reset timezone Serial.println("dst function called"); Serial.println(DST_offset); } void setTimezone(int DST_offset) // call to set timezone offset from UTC { Time.zone(DST_offset); }
#include "TimeAlarms/TimeAlarms.h" #include "particle-functions.h" #include "weather/weather.h" #include "DualMC33926MotorShield/DualMC33926MotorShield.h" // default startup values int DST_offset = -7; int AMsetback = 7; int PMsetback = 15; int dayProgram = 2; int nightProgram = 4; int targetVentPosition = 0; int currentVentPosition; int liveProgram [5][2]; int motorStatus; int ventdiff; // used for proxy of motor run time int magnetSensor = D4; void particleInit() { Spark.function ("ghData" , ghData); //used to pass greenhouse/weather data from HA system Spark.function ("passProgram" , passProgramParam); //used to pass program parameters from HA system Spark.function ("motor" , runMotor); //used to test motor Spark.function ("offsetUTC" , offsetUTC); //used to pass UTC offset parameter from HA system setTimezone(DST_offset); // set default time zone offset Alarm.alarmRepeat(0,0,0, synchTime); // synch time every 24hrs at midnight Alarm.timerRepeat(0,1,0, runProgram); setAlarms(AMsetback, PMsetback); // set initial setback times setProgramSeason(); initializeDefaultSetbacks(); pinMode(magnetSensor, INPUT); } int ghData(String data) { //Expected parameters in CSV format // 1. Unix time stamp // 2. current greenhouse temperature // 3. current greenhouse humidity // 4. backup sensor current greenhouse temperature // 5. backup sensor current greenhouse humidity // 6. current outside temperature // 7. current outside humidity // 8. solar radiation // 9. forecast high // 10. forecast low char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); unsigned int weatherTime = atoi(p); p = strtok(NULL,","); int greenhouseTemp = atoi(p); p = strtok(NULL,","); int greenhouseHumidity = atoi(p); p = strtok(NULL,","); int backupGreenhouseTemp = atoi(p); p = strtok(NULL,","); int backupGreenhouseHumidity = atoi(p); p = strtok(NULL,","); int outsideTemp = atoi(p); p = strtok(NULL,","); int outsideHumidity = atoi(p); p = strtok(NULL,","); int solar = atoi(p); p = strtok(NULL,","); int high = atoi(p); p = strtok(NULL,","); int low = atoi(p); weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp, backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low); Serial.println("data loaded to greenhouseData: "); Serial.println(data); return 1; } int passProgramParam(String data) { char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); int AMsetback = atoi(p); p = strtok(NULL,","); int PMsetback = atoi(p); p = strtok(NULL,","); dayProgram = atoi(p); p = strtok(NULL,","); nightProgram = atoi(p); Serial.print("data loaded to setProgram: "); Serial.println(data); // used for testing remove later setAlarms(AMsetback, PMsetback); // pass setback values to function return 1; } int runMotor(String data) { Serial.print("motor function called: "); Serial.println(data); // used for testing remove later char copyStr[64]; data.toCharArray(copyStr,64); int pass_param = atoi(copyStr); // converts character array into int, subtracts 1 to get index # of program row from programParam array //char * param = new char[5]; // creates character array to store program variable from RESTful call //strcpy(param, data.c_str()); // copies program variable into character array //int pass_param = atoi(param); // converts character array into int, subtracts 1 to get index # of program row from programParam array motor.setM1Speed(pass_param); return 1; } int offsetUTC(String data) { char copyStr[64]; data.toCharArray(copyStr,64); int DST_offset = atoi(copyStr); if (DST_offset >= -12 && DST_offset <= 12) { setTimezone(DST_offset); // call to reset timezone Serial.println("offsetUTC function called"); // used for testing remove later Serial.println(DST_offset); // used for testing remove later return 1; } else { Serial.println("offsetUTC function error"); // used for testing remove later return 0; } } void setTimezone(int offset) // call to set timezone offset from UTC { Time.zone(offset); Serial.print("Time.zone(offset) called TZ: "); Serial.println(now()); // used for testing remove later } void setAlarms(int AMsetback, int PMsetback) { if ((AMsetback >= 0 && AMsetback < 24) && (PMsetback >= 0 && PMsetback < 24)) { if (Alarm.isAllocated(2)) { Alarm.free(2); Alarm.free(3); } Alarm.alarmRepeat(AMsetback,0,0, MorningAlarm); // 8:30am every day Alarm.alarmRepeat(PMsetback,0,0,EveningAlarm); Serial.println("setAlarms code called"); } else { Serial.println("setAlarms code error"); } } void MorningAlarm() { Serial.println("Morning alarm code called"); ventProgram(dayProgram); } void EveningAlarm() { Serial.println("Evening alarm code called"); ventProgram(nightProgram); } void synchTime() { Spark.syncTime(); setProgramSeason(); } //--------------------------// int ventProgram(int passedProgram) // call once per hour on the hour // the program number is passed from setTimePeriod and the coresponding // temperature,vent position combos are loaded into an array { if (passedProgram == 1) { // warm day program July 1 - Oct 5 int program[5][2] = { // program 0 {85,5}, {82,4}, {79,3}, {77,2}, {76,0} }; for (int i=0; i<5; i++) { Serial.print("Temp: ");Serial.print(program[i][0]); Serial.print(" Vent: ");Serial.println(program[i][1]); liveProgram[i][0] = program[i][0]; liveProgram[i][1] = program[i][1]; } } else if (passedProgram == 2) { // normal day program Oct 6 - June 30 int program[5][2]= { // program 1 {85,5}, {83,4}, {81,2}, {79,1}, {77,0} }; for (int i=0; i<5; i++) { Serial.print("Temp: ");Serial.print(program[i][0]); Serial.print(" Vent: ");Serial.println(program[i][1]); liveProgram[i][0] = program[i][0]; liveProgram[i][1] = program[i][1]; } } else if (passedProgram == 3) { // warm nights program July 1 - Oct 5 int program[5][2]= { // program 3 {67,5}, {65,4}, {64,2}, {63,0}, {63,0} }; for (int i=0; i<5; i++) { Serial.print("Temp: ");Serial.print(program[i][0]); Serial.print(" Vent: ");Serial.println(program[i][1]); liveProgram[i][0] = program[i][0]; liveProgram[i][1] = program[i][1]; } } else if (passedProgram == 4) { // normal nights program Oct 6 - June 30 int program[5][2]= { // program 2 {75,5}, {73,4}, {71,3}, {69,2}, {67,0} }; for (int i=0; i<5; i++) { Serial.print("Temp: ");Serial.print(program[i][0]); Serial.print(" Vent: ");Serial.println(program[i][1]); liveProgram[i][0] = program[i][0]; liveProgram[i][1] = program[i][1]; } } return 1; } void runProgram() { for (int i=0; i<5; i++) { Serial.print("Temp: ");Serial.print(liveProgram[i][0]); Serial.print(" Vent: ");Serial.println(liveProgram[i][1]); } int gh_temperature = weather.greenhouseTemp(); Serial.print("gh_temp: "); Serial.println(gh_temperature); if (gh_temperature >= liveProgram[0][0]) { Serial.print("runprogram >= triggered comparator: ");Serial.println(liveProgram[0][0]); targetVentPosition = liveProgram[0][1]; } else if (gh_temperature <= liveProgram[4][0]) { Serial.print("runprogram <= triggered comparator: ");Serial.println(liveProgram[4][0]); targetVentPosition = liveProgram[4][1]; } else { for (int i=1; i<4; i++){ if (gh_temperature <= liveProgram[i][0] && gh_temperature > liveProgram[i+1][0]) { Serial.print("runprogram == triggered comparator: ");Serial.println(liveProgram[i][0]); targetVentPosition = liveProgram[i][1]; break; } } } Serial.print("vent position : ");Serial.println(targetVentPosition); } //-------------------------- // used to set program parameters based upon date and time void setProgramSeason() { if (Time.month() < 4 || Time.month() > 11 || (Time.month() == 11 && Time.day() >9)) // wintertime setbacks { AMsetback = 7; PMsetback = 23; dayProgram = 2; nightProgram = 4; Serial.println("wintertime program"); } else if ((Time.month() > 6 && Time.month() < 10) || (Time.month() == 10 && Time.day() < 6)) // summertime setbacks { AMsetback = 10; PMsetback = 15; dayProgram = 1; nightProgram = 3; Serial.println("summertime program"); } else { AMsetback = 9; PMsetback = 20; dayProgram = 2; nightProgram = 4; Serial.println("spring/fall program"); } } void initializeDefaultSetbacks() { if (Time.hour() >= PMsetback || Time.hour() < AMsetback) { ventProgram(nightProgram); Serial.println("vents set to night program"); } else { ventProgram(dayProgram); Serial.println("vents set to day program"); } } //--------------------------- //motor functions here void ventMotor(int currentVentPosition, int targetVentPosition) { if (currentVentPosition == targetVentPosition) { motor.setM1Speed(0); motorStatus = 0; } else if (currentVentPosition > targetVentPosition) { motor.setM1Speed(-255); motorStatus = 1; Alarm.timerOnce(10*(currentVentPosition-targetVentPosition), tempVentIncrementDown); ventdiff = currentVentPosition-targetVentPosition; } else if (currentVentPosition < targetVentPosition) { motor.setM1Speed(255); motorStatus = 1; Alarm.timerOnce(10*(targetVentPosition-currentVentPosition), tempVentIncrementUp); ventdiff = targetVentPosition-currentVentPosition; } else Serial.println("ventMotor error"); } // write function to set motor back to position zero at startup // write function to check if torque is too high, stop motor and throw error // write funcion to sense position 0 and 5 to stop motor and throw error void tempVentIncrementUp() { currentVentPosition = currentVentPosition + ventdiff; Serial.println("ventMotor run forward for "); Serial.print(ventdiff); Serial.println(" positions"); } void tempVentIncrementDown() { currentVentPosition = currentVentPosition - ventdiff; Serial.print("ventMotor run backward for "); Serial.print(ventdiff); Serial.println(" positions"); }
Update particle-functions.cpp
Update particle-functions.cpp
C++
mit
geoffsharris/particle-functions
bbf6ed9a97d7ced2d5f237190fded09546790fda
firmware/particle-functions.cpp
firmware/particle-functions.cpp
#include "particle-functions.h" int DST_offset = -7; void particleInit() { Particle.function ("ghData" , ghData); Particle.function ("passProgram" , passProgramParam); Particle.function ("motor" , motor); Particle.function ("dst" , setDST); setTimezone(DST_offset); } int ghData(String data) { //Expected parameters in CSV format // 1. Unix time stamp // 2. current greenhouse temperature // 3. current greenhouse humidity // 4. backup sensor current greenhouse temperature // 5. backup sensor current greenhouse humidity // 6. current outside temperature // 7. current outside humidity // 8. solar radiation // 9. forecast high // 10. forecast low char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); unsigned int weatherTime = atoi(p); p = strtok(NULL,","); int greenhouseTemp = atoi(p); p = strtok(NULL,","); int greenhouseHumidity = atoi(p); p = strtok(NULL,","); int backupGreenhouseTemp = atoi(p); p = strtok(NULL,","); int backupGreenhouseHumidity = atoi(p); p = strtok(NULL,","); int outsideTemp = atoi(p); p = strtok(NULL,","); int outsideHumidity = atoi(p); p = strtok(NULL,","); int solar = atoi(p); p = strtok(NULL,","); int high = atoi(p); p = strtok(NULL,","); int low = atoi(p); /*weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp, backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low); */ Serial.println("data loaded to greenhouseData"); Serial.println(data); return 1; } int passProgramParam(String data) { char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); int AMsetback = atoi(p); p = strtok(NULL,","); int PMsetback = atoi(p); p = strtok(NULL,","); int dayProgram = atoi(p); p = strtok(NULL,","); int nightProgram = atoi(p); Serial.println("data loaded to setProgram"); Serial.println(data); return 1; } int motor(String data) { Serial.println("motor function called"); char copyStr[64]; data.toCharArray(copyStr,64); int pass_param = atoi(copyStr); // converts character array into int, subtracts 1 to get index # of program row from programParam array //char * param = new char[5]; // creates character array to store program variable from RESTful call //strcpy(param, data.c_str()); // copies program variable into character array //int pass_param = atoi(param); // converts character array into int, subtracts 1 to get index # of program row from programParam array //motor.setM1Speed(pass_param); Serial.println("data loaded to Test Function"); Serial.println(data); return 1; } int setDST(String data) { char copyStr[64]; data.toCharArray(copyStr,64); DST_offset = atoi(copyStr); setTimezone(); // call to reste timezone Serial.println("dst function called"); Serial.println(DST_offset); } void setTimezone(DST_offset) // call to set timezone offset from UTC { Time.zone(DST_offset); }
#include "particle-functions.h" int DST_offset = -7; void particleInit() { Particle.function ("ghData" , ghData); Particle.function ("passProgram" , passProgramParam); Particle.function ("motor" , motor); Particle.function ("dst" , setDST); setTimezone(DST_offset); } int ghData(String data) { //Expected parameters in CSV format // 1. Unix time stamp // 2. current greenhouse temperature // 3. current greenhouse humidity // 4. backup sensor current greenhouse temperature // 5. backup sensor current greenhouse humidity // 6. current outside temperature // 7. current outside humidity // 8. solar radiation // 9. forecast high // 10. forecast low char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); unsigned int weatherTime = atoi(p); p = strtok(NULL,","); int greenhouseTemp = atoi(p); p = strtok(NULL,","); int greenhouseHumidity = atoi(p); p = strtok(NULL,","); int backupGreenhouseTemp = atoi(p); p = strtok(NULL,","); int backupGreenhouseHumidity = atoi(p); p = strtok(NULL,","); int outsideTemp = atoi(p); p = strtok(NULL,","); int outsideHumidity = atoi(p); p = strtok(NULL,","); int solar = atoi(p); p = strtok(NULL,","); int high = atoi(p); p = strtok(NULL,","); int low = atoi(p); /*weather.weatherData(weatherTime, greenhouseTemp, greenhouseHumidity, backupGreenhouseTemp, backupGreenhouseHumidity, outsideTemp, outsideHumidity, solar, high, low); */ Serial.println("data loaded to greenhouseData"); Serial.println(data); return 1; } int passProgramParam(String data) { char copyStr[64]; data.toCharArray(copyStr,64); char *p = strtok(copyStr, ","); int AMsetback = atoi(p); p = strtok(NULL,","); int PMsetback = atoi(p); p = strtok(NULL,","); int dayProgram = atoi(p); p = strtok(NULL,","); int nightProgram = atoi(p); Serial.println("data loaded to setProgram"); Serial.println(data); return 1; } int motor(String data) { Serial.println("motor function called"); char copyStr[64]; data.toCharArray(copyStr,64); int pass_param = atoi(copyStr); // converts character array into int, subtracts 1 to get index # of program row from programParam array //char * param = new char[5]; // creates character array to store program variable from RESTful call //strcpy(param, data.c_str()); // copies program variable into character array //int pass_param = atoi(param); // converts character array into int, subtracts 1 to get index # of program row from programParam array //motor.setM1Speed(pass_param); Serial.println("data loaded to Test Function"); Serial.println(data); return 1; } int setDST(String data) { char copyStr[64]; data.toCharArray(copyStr,64); DST_offset = atoi(copyStr); setTimezone(DST_offset); // call to reste timezone Serial.println("dst function called"); Serial.println(DST_offset); } void setTimezone(int DST_offset) // call to set timezone offset from UTC { Time.zone(DST_offset); }
Update particle-functions.cpp
Update particle-functions.cpp
C++
mit
geoffsharris/particle-functions
808aa0f0497b36b99cd2584b33c7a9cb3a0bfe81
src/CLR/Core/CLR_RT_HeapBlock_Timer.cpp
src/CLR/Core/CLR_RT_HeapBlock_Timer.cpp
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "Core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// HRESULT CLR_RT_HeapBlock_Timer::CreateInstance( CLR_UINT32 flags, CLR_RT_HeapBlock& owner, CLR_RT_HeapBlock& tmRef ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_HeapBlock_Timer* timer = NULL; // // Create a request and stop the calling thread. // timer = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache,CLR_RT_HeapBlock_Timer,DATATYPE_TIMER_HEAD); CHECK_ALLOCATION(timer); { CLR_RT_ProtectFromGC gc( *timer ); timer->Initialize(); timer->m_flags = flags; timer->m_timeExpire = TIMEOUT_INFINITE; timer->m_timeFrequency = TIMEOUT_INFINITE; timer->m_timeLastExpiration = 0; timer->m_ticksLastExpiration = 0; g_CLR_RT_ExecutionEngine.m_timers.LinkAtBack( timer ); NANOCLR_SET_AND_LEAVE(CLR_RT_ObjectToEvent_Source::CreateInstance( timer, owner, tmRef )); } NANOCLR_CLEANUP(); if(FAILED(hr)) { if(timer) timer->ReleaseWhenDead(); } NANOCLR_CLEANUP_END(); } HRESULT CLR_RT_HeapBlock_Timer::ExtractInstance( CLR_RT_HeapBlock& ref, CLR_RT_HeapBlock_Timer*& timer ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_ObjectToEvent_Source* src = CLR_RT_ObjectToEvent_Source::ExtractInstance( ref ); FAULT_ON_NULL(src); timer = (CLR_RT_HeapBlock_Timer*)src->m_eventPtr; NANOCLR_NOCLEANUP(); } //--// void CLR_RT_HeapBlock_Timer::RecoverFromGC() { NATIVE_PROFILE_CLR_CORE(); CheckAll(); ReleaseWhenDead(); } //--// void CLR_RT_HeapBlock_Timer::Trigger() { NATIVE_PROFILE_CLR_CORE(); if(m_references.IsEmpty()) return; if(m_flags & CLR_RT_HeapBlock_Timer::c_Executing) { return; } m_flags |= CLR_RT_HeapBlock_Timer::c_Triggered; } void CLR_RT_HeapBlock_Timer::SpawnTimer( CLR_RT_Thread* th ) { NATIVE_PROFILE_CLR_CORE(); //Only one managed timer max _ASSERTE(m_references.NumOfNodes() == 1); CLR_RT_ObjectToEvent_Source* ref = (CLR_RT_ObjectToEvent_Source*)m_references.FirstValidNode(); CLR_RT_HeapBlock* managedTimer = ref->m_objectPtr; CLR_RT_HeapBlock* callback = &managedTimer[ Library_corlib_native_System_Threading_Timer::FIELD___callback ]; CLR_RT_HeapBlock* state = &managedTimer[ Library_corlib_native_System_Threading_Timer::FIELD___state ]; CLR_RT_HeapBlock_Delegate* delegate = callback->DereferenceDelegate(); CLR_RT_ProtectFromGC gc( *managedTimer ); _ASSERTE(delegate != NULL); if(delegate == NULL) return; _ASSERTE(delegate->DataType() == DATATYPE_DELEGATE_HEAD); m_ticksLastExpiration = HAL_Time_CurrentTime(); m_timeLastExpiration = m_timeExpire; m_timeExpire = TIMEOUT_INFINITE; if(SUCCEEDED(th->PushThreadProcDelegate( delegate ))) { CLR_RT_StackFrame* stack = th->FirstFrame(); if(stack->Next() != NULL) { int numArgs = stack->m_call.m_target->numArgs; if(numArgs > 0) { stack->m_arguments[ numArgs-1 ].Assign( *state ); } } // // Associate the timer with the thread. // m_flags |= CLR_RT_HeapBlock_Timer::c_Executing; m_flags &= ~CLR_RT_HeapBlock_Timer::c_Triggered; th->m_terminationCallback = CLR_RT_HeapBlock_Timer::ThreadTerminationCallback; th->m_terminationParameter = this; } } void CLR_RT_HeapBlock_Timer::ThreadTerminationCallback( void* param ) { NATIVE_PROFILE_CLR_CORE(); CLR_RT_HeapBlock_Timer* pThis = (CLR_RT_HeapBlock_Timer*)param; pThis->m_flags &= ~CLR_RT_HeapBlock_Timer::c_Executing; pThis->Reschedule(); g_CLR_RT_ExecutionEngine.SpawnTimer(); } void CLR_RT_HeapBlock_Timer::Reschedule() { NATIVE_PROFILE_CLR_CORE(); if((m_flags & CLR_RT_HeapBlock_Timer::c_Recurring ) && (m_flags & CLR_RT_HeapBlock_Timer::c_EnabledTimer) ) { CLR_UINT64 expire = m_timeLastExpiration + m_timeFrequency; // // Normally, adding the 'timeFrequency' will put the expiration in the future. // // If we fall back too much, we need to compute the next expiration in the future, to avoid an avalanche effect. // if(expire < HAL_Time_CurrentTime()) { expire = HAL_Time_CurrentTime() - ((HAL_Time_CurrentTime() - expire) % m_timeFrequency) + m_timeFrequency; } m_timeExpire = expire; CLR_RT_ExecutionEngine::InvalidateTimerCache(); } } //--// void CLR_RT_HeapBlock_Timer::AdjustNextFixedExpire( const SYSTEMTIME& systemTime, bool fNext ) { NATIVE_PROFILE_CLR_CORE(); SYSTEMTIME st = systemTime; CLR_INT64 baseTime; CLR_INT64 add; CLR_RT_ExecutionEngine::InvalidateTimerCache(); switch(m_flags & CLR_RT_HeapBlock_Timer::c_AnyChange) { case CLR_RT_HeapBlock_Timer::c_SecondChange: add = TIME_CONVERSION__ONESECOND * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; break; case CLR_RT_HeapBlock_Timer::c_MinuteChange: add = TIME_CONVERSION__ONEMINUTE * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; break; case CLR_RT_HeapBlock_Timer::c_HourChange : add = TIME_CONVERSION__ONEHOUR * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; st.wMinute = 0; break; case CLR_RT_HeapBlock_Timer::c_DayChange : add = TIME_CONVERSION__ONEDAY * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; st.wMinute = 0; st.wHour = 0; break; default : return; } st.wMilliseconds = 0; baseTime = HAL_Time_ConvertFromSystemTime( &st ); m_timeExpire = fNext ? baseTime + add : baseTime; m_timeFrequency = add; m_flags |= CLR_RT_HeapBlock_Timer::c_Recurring; } bool CLR_RT_HeapBlock_Timer::CheckDisposed( CLR_RT_StackFrame& stack ) { CLR_RT_HeapBlock* pThis = stack.This(); CLR_RT_HeapBlock_Timer* timer; if(!FAILED(CLR_RT_HeapBlock_Timer::ExtractInstance( pThis[ Library_corlib_native_System_Threading_Timer::FIELD___timer ], timer ))) { if((timer->m_flags & CLR_RT_HeapBlock_Timer::c_ACTION_Destroy) == 0) { return false; } } return true; } HRESULT CLR_RT_HeapBlock_Timer::ConfigureObject( CLR_RT_StackFrame& stack, CLR_UINT32 flags ) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_HeapBlock* pThis = stack.This(); CLR_RT_HeapBlock* args = &(stack.Arg1()); CLR_RT_HeapBlock_Timer* timer; const CLR_INT64 maxTime = (CLR_INT64)0x7FFFFFFF * (CLR_INT64)TIME_CONVERSION__TO_MILLISECONDS; const CLR_INT64 minTime = 0; if(flags & CLR_RT_HeapBlock_Timer::c_ACTION_Create) { FAULT_ON_NULL(args[ 0 ].DereferenceDelegate()); NANOCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Timer::CreateInstance( 0, *pThis, pThis[ Library_corlib_native_System_Threading_Timer::FIELD___timer ] )); pThis[ Library_corlib_native_System_Threading_Timer::FIELD___callback ].Assign( args[ 0 ] ); pThis[ Library_corlib_native_System_Threading_Timer::FIELD___state ].Assign( args[ 1 ] ); args += 2; } NANOCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Timer::ExtractInstance( pThis[ Library_corlib_native_System_Threading_Timer::FIELD___timer ], timer )); if(flags & CLR_RT_HeapBlock_Timer::c_ACTION_Create) { CLR_UINT32 anyChange = (flags & CLR_RT_HeapBlock_Timer::c_AnyChange); if(anyChange) { SYSTEMTIME systemTime; HAL_Time_ToSystemTime( HAL_Time_CurrentTime(), &systemTime ); timer->m_flags |= anyChange | CLR_RT_HeapBlock_Timer::c_EnabledTimer; timer->AdjustNextFixedExpire( systemTime, true ); } else { flags |= CLR_RT_HeapBlock_Timer::c_ACTION_Change; } } if(flags & CLR_RT_HeapBlock_Timer::c_ACTION_Destroy) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_EnabledTimer; } if(flags & CLR_RT_HeapBlock_Timer::c_ACTION_Change) { // // You cannot change a fixed timer after creation. // if(timer->m_flags & CLR_RT_HeapBlock_Timer::c_AnyChange) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); if(flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) { timer->m_timeExpire = args[ 0 ].NumericByRef().s4; timer->m_timeFrequency = args[ 1 ].NumericByRef().s4; if (timer->m_timeExpire == -1) timer->m_timeExpire = TIMEOUT_INFINITE; if (timer->m_timeFrequency == -1) timer->m_timeFrequency = TIMEOUT_INFINITE; } else if(flags & CLR_RT_HeapBlock_Timer::c_INPUT_TimeSpan) { CLR_INT64* pVal; pVal = Library_corlib_native_System_TimeSpan::GetValuePtr( args[ 0 ] ); FAULT_ON_NULL(pVal); if (*pVal == -c_TickPerMillisecond) timer->m_timeExpire = TIMEOUT_INFINITE; else timer->m_timeExpire = *pVal; pVal = Library_corlib_native_System_TimeSpan::GetValuePtr( args[ 1 ] ); FAULT_ON_NULL(pVal); if (*pVal == -c_TickPerMillisecond) timer->m_timeFrequency = TIMEOUT_INFINITE; else timer->m_timeFrequency = *pVal; } if(timer->m_timeExpire == TIMEOUT_INFINITE) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_EnabledTimer; } else { if(flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) timer->m_timeExpire *= TIME_CONVERSION__TO_MILLISECONDS; if (minTime <= timer->m_timeExpire && timer->m_timeExpire <= maxTime) { timer->m_timeExpire += HAL_Time_CurrentTime(); timer->m_flags |= CLR_RT_HeapBlock_Timer::c_EnabledTimer; } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); } } if(timer->m_timeFrequency == 0 || timer->m_timeFrequency == TIMEOUT_INFINITE) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_Recurring; } else { if(flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) timer->m_timeFrequency *= TIME_CONVERSION__TO_MILLISECONDS; if(minTime <= timer->m_timeFrequency && timer->m_timeFrequency <= maxTime ) { timer->m_flags |= CLR_RT_HeapBlock_Timer::c_Recurring; } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); } } } CLR_RT_ExecutionEngine::InvalidateTimerCache(); NANOCLR_NOCLEANUP(); }
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include "Core.h" //////////////////////////////////////////////////////////////////////////////////////////////////// HRESULT CLR_RT_HeapBlock_Timer::CreateInstance(CLR_UINT32 flags, CLR_RT_HeapBlock &owner, CLR_RT_HeapBlock &tmRef) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_HeapBlock_Timer *timer = NULL; // // Create a request and stop the calling thread. // timer = EVENTCACHE_EXTRACT_NODE(g_CLR_RT_EventCache, CLR_RT_HeapBlock_Timer, DATATYPE_TIMER_HEAD); CHECK_ALLOCATION(timer); { CLR_RT_ProtectFromGC gc(*timer); timer->Initialize(); timer->m_flags = flags; timer->m_timeExpire = TIMEOUT_INFINITE; timer->m_timeFrequency = TIMEOUT_INFINITE; timer->m_timeLastExpiration = 0; timer->m_ticksLastExpiration = 0; g_CLR_RT_ExecutionEngine.m_timers.LinkAtBack(timer); NANOCLR_SET_AND_LEAVE(CLR_RT_ObjectToEvent_Source::CreateInstance(timer, owner, tmRef)); } NANOCLR_CLEANUP(); if (FAILED(hr)) { if (timer) timer->ReleaseWhenDead(); } NANOCLR_CLEANUP_END(); } HRESULT CLR_RT_HeapBlock_Timer::ExtractInstance(CLR_RT_HeapBlock &ref, CLR_RT_HeapBlock_Timer *&timer) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_ObjectToEvent_Source *src = CLR_RT_ObjectToEvent_Source::ExtractInstance(ref); FAULT_ON_NULL(src); timer = (CLR_RT_HeapBlock_Timer *)src->m_eventPtr; NANOCLR_NOCLEANUP(); } //--// void CLR_RT_HeapBlock_Timer::RecoverFromGC() { NATIVE_PROFILE_CLR_CORE(); CheckAll(); ReleaseWhenDead(); } //--// void CLR_RT_HeapBlock_Timer::Trigger() { NATIVE_PROFILE_CLR_CORE(); if (m_references.IsEmpty()) return; if (m_flags & CLR_RT_HeapBlock_Timer::c_Executing) { return; } m_flags |= CLR_RT_HeapBlock_Timer::c_Triggered; } void CLR_RT_HeapBlock_Timer::SpawnTimer(CLR_RT_Thread *th) { NATIVE_PROFILE_CLR_CORE(); // Only one managed timer max _ASSERTE(m_references.NumOfNodes() == 1); CLR_RT_ObjectToEvent_Source *ref = (CLR_RT_ObjectToEvent_Source *)m_references.FirstValidNode(); CLR_RT_HeapBlock *managedTimer = ref->m_objectPtr; CLR_RT_HeapBlock *callback = &managedTimer[Library_corlib_native_System_Threading_Timer::FIELD___callback]; CLR_RT_HeapBlock *state = &managedTimer[Library_corlib_native_System_Threading_Timer::FIELD___state]; CLR_RT_HeapBlock_Delegate *delegate = callback->DereferenceDelegate(); CLR_RT_ProtectFromGC gc(*managedTimer); _ASSERTE(delegate != NULL); if (delegate == NULL) return; _ASSERTE(delegate->DataType() == DATATYPE_DELEGATE_HEAD); m_ticksLastExpiration = HAL_Time_CurrentTime(); m_timeLastExpiration = m_timeExpire; m_timeExpire = TIMEOUT_INFINITE; if (SUCCEEDED(th->PushThreadProcDelegate(delegate))) { CLR_RT_StackFrame *stack = th->FirstFrame(); if (stack->Next() != NULL) { int numArgs = stack->m_call.m_target->numArgs; if (numArgs > 0) { stack->m_arguments[numArgs - 1].Assign(*state); } } // // Associate the timer with the thread. // m_flags |= CLR_RT_HeapBlock_Timer::c_Executing; m_flags &= ~CLR_RT_HeapBlock_Timer::c_Triggered; th->m_terminationCallback = CLR_RT_HeapBlock_Timer::ThreadTerminationCallback; th->m_terminationParameter = this; } } void CLR_RT_HeapBlock_Timer::ThreadTerminationCallback(void *param) { NATIVE_PROFILE_CLR_CORE(); CLR_RT_HeapBlock_Timer *pThis = (CLR_RT_HeapBlock_Timer *)param; pThis->m_flags &= ~CLR_RT_HeapBlock_Timer::c_Executing; pThis->Reschedule(); g_CLR_RT_ExecutionEngine.SpawnTimer(); } void CLR_RT_HeapBlock_Timer::Reschedule() { NATIVE_PROFILE_CLR_CORE(); if ((m_flags & CLR_RT_HeapBlock_Timer::c_Recurring) && (m_flags & CLR_RT_HeapBlock_Timer::c_EnabledTimer)) { CLR_UINT64 expire = m_timeLastExpiration + m_timeFrequency; // // Normally, adding the 'timeFrequency' will put the expiration in the future. // // If we fall back too much, we need to compute the next expiration in the future, to avoid an avalanche effect. // if (expire < HAL_Time_CurrentTime()) { expire = HAL_Time_CurrentTime() - ((HAL_Time_CurrentTime() - expire) % m_timeFrequency) + m_timeFrequency; } m_timeExpire = expire; CLR_RT_ExecutionEngine::InvalidateTimerCache(); } } //--// void CLR_RT_HeapBlock_Timer::AdjustNextFixedExpire(const SYSTEMTIME &systemTime, bool fNext) { NATIVE_PROFILE_CLR_CORE(); SYSTEMTIME st = systemTime; CLR_INT64 baseTime; CLR_INT64 add; CLR_RT_ExecutionEngine::InvalidateTimerCache(); switch (m_flags & CLR_RT_HeapBlock_Timer::c_AnyChange) { case CLR_RT_HeapBlock_Timer::c_SecondChange: add = TIME_CONVERSION__ONESECOND * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; break; case CLR_RT_HeapBlock_Timer::c_MinuteChange: add = TIME_CONVERSION__ONEMINUTE * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; break; case CLR_RT_HeapBlock_Timer::c_HourChange: add = TIME_CONVERSION__ONEHOUR * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; st.wMinute = 0; break; case CLR_RT_HeapBlock_Timer::c_DayChange: add = TIME_CONVERSION__ONEDAY * (CLR_INT64)TIME_CONVERSION__TO_SECONDS; st.wSecond = 0; st.wMinute = 0; st.wHour = 0; break; default: return; } st.wMilliseconds = 0; baseTime = HAL_Time_ConvertFromSystemTime(&st); m_timeExpire = fNext ? baseTime + add : baseTime; m_timeFrequency = add; m_flags |= CLR_RT_HeapBlock_Timer::c_Recurring; } bool CLR_RT_HeapBlock_Timer::CheckDisposed(CLR_RT_StackFrame &stack) { CLR_RT_HeapBlock *pThis = stack.This(); CLR_RT_HeapBlock_Timer *timer; if (!FAILED(CLR_RT_HeapBlock_Timer::ExtractInstance( pThis[Library_corlib_native_System_Threading_Timer::FIELD___timer], timer))) { if ((timer->m_flags & CLR_RT_HeapBlock_Timer::c_ACTION_Destroy) == 0) { return false; } } return true; } HRESULT CLR_RT_HeapBlock_Timer::ConfigureObject(CLR_RT_StackFrame &stack, CLR_UINT32 flags) { NATIVE_PROFILE_CLR_CORE(); NANOCLR_HEADER(); CLR_RT_HeapBlock *pThis = stack.This(); CLR_RT_HeapBlock *args = &(stack.Arg1()); CLR_RT_HeapBlock_Timer *timer; const CLR_INT64 maxTime = (CLR_INT64)0x7FFFFFFF * (CLR_INT64)TIME_CONVERSION__TO_MILLISECONDS; const CLR_INT64 minTime = 0; if (flags & CLR_RT_HeapBlock_Timer::c_ACTION_Create) { FAULT_ON_NULL_ARG(args[0].DereferenceDelegate()); NANOCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Timer::CreateInstance( 0, *pThis, pThis[Library_corlib_native_System_Threading_Timer::FIELD___timer])); pThis[Library_corlib_native_System_Threading_Timer::FIELD___callback].Assign(args[0]); pThis[Library_corlib_native_System_Threading_Timer::FIELD___state].Assign(args[1]); args += 2; } NANOCLR_CHECK_HRESULT(CLR_RT_HeapBlock_Timer::ExtractInstance( pThis[Library_corlib_native_System_Threading_Timer::FIELD___timer], timer)); if (flags & CLR_RT_HeapBlock_Timer::c_ACTION_Create) { CLR_UINT32 anyChange = (flags & CLR_RT_HeapBlock_Timer::c_AnyChange); if (anyChange) { SYSTEMTIME systemTime; HAL_Time_ToSystemTime(HAL_Time_CurrentTime(), &systemTime); timer->m_flags |= anyChange | CLR_RT_HeapBlock_Timer::c_EnabledTimer; timer->AdjustNextFixedExpire(systemTime, true); } else { flags |= CLR_RT_HeapBlock_Timer::c_ACTION_Change; } } if (flags & CLR_RT_HeapBlock_Timer::c_ACTION_Destroy) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_EnabledTimer; } if (flags & CLR_RT_HeapBlock_Timer::c_ACTION_Change) { // // You cannot change a fixed timer after creation. // if (timer->m_flags & CLR_RT_HeapBlock_Timer::c_AnyChange) NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); if (flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) { timer->m_timeExpire = args[0].NumericByRef().s4; timer->m_timeFrequency = args[1].NumericByRef().s4; if (timer->m_timeExpire == -1) timer->m_timeExpire = TIMEOUT_INFINITE; if (timer->m_timeFrequency == -1) timer->m_timeFrequency = TIMEOUT_INFINITE; } else if (flags & CLR_RT_HeapBlock_Timer::c_INPUT_TimeSpan) { CLR_INT64 *pVal; pVal = Library_corlib_native_System_TimeSpan::GetValuePtr(args[0]); FAULT_ON_NULL(pVal); if (*pVal == -c_TickPerMillisecond) timer->m_timeExpire = TIMEOUT_INFINITE; else timer->m_timeExpire = *pVal; pVal = Library_corlib_native_System_TimeSpan::GetValuePtr(args[1]); FAULT_ON_NULL(pVal); if (*pVal == -c_TickPerMillisecond) timer->m_timeFrequency = TIMEOUT_INFINITE; else timer->m_timeFrequency = *pVal; } if (timer->m_timeExpire == TIMEOUT_INFINITE) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_EnabledTimer; } else { if (flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) timer->m_timeExpire *= TIME_CONVERSION__TO_MILLISECONDS; if (minTime <= timer->m_timeExpire && timer->m_timeExpire <= maxTime) { timer->m_timeExpire += HAL_Time_CurrentTime(); timer->m_flags |= CLR_RT_HeapBlock_Timer::c_EnabledTimer; } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); } } if (timer->m_timeFrequency == 0 || timer->m_timeFrequency == TIMEOUT_INFINITE) { timer->m_flags &= ~CLR_RT_HeapBlock_Timer::c_Recurring; } else { if (flags & CLR_RT_HeapBlock_Timer::c_INPUT_Int32) timer->m_timeFrequency *= TIME_CONVERSION__TO_MILLISECONDS; if (minTime <= timer->m_timeFrequency && timer->m_timeFrequency <= maxTime) { timer->m_flags |= CLR_RT_HeapBlock_Timer::c_Recurring; } else { NANOCLR_SET_AND_LEAVE(CLR_E_OUT_OF_RANGE); } } } CLR_RT_ExecutionEngine::InvalidateTimerCache(); NANOCLR_NOCLEANUP(); }
Fix exception thrown on Timer constructor (#1851)
Fix exception thrown on Timer constructor (#1851) ***NO_CI***
C++
mit
Eclo/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter,nanoframework/nf-interpreter,Eclo/nf-interpreter,nanoframework/nf-interpreter
8d6294d566ba69d79e1bea8f936458784a63feb5
src/platform/windows/file.cpp
src/platform/windows/file.cpp
#include "../file.h" #include <yttrium/storage/source.h> #include <yttrium/storage/temporary_file.h> #include "../../storage/writer.h" #include <system_error> #include "windows.h" namespace Yttrium { class FileSource final : public Source { public: FileSource(uint64_t size, const std::string& name, HANDLE handle) : Source{size, name} , _handle{handle} { } ~FileSource() noexcept override { if (!::CloseHandle(_handle)) ::OutputDebugStringA("ERROR! 'CloseHandle' failed"); } size_t read_at(uint64_t offset, void* data, size_t size) const override { DWORD result = 0; OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32); return ::ReadFile(_handle, data, static_cast<DWORD>(size), &result, &overlapped) ? result : 0; } private: const HANDLE _handle; }; class FileWriter final : public WriterPrivate { public: FileWriter(const std::string& name, HANDLE handle) : _name{name} , _handle{handle} { } ~FileWriter() noexcept override { if (!::CloseHandle(_handle)) ::OutputDebugStringA("ERROR! 'CloseHandle' failed"); if (_unlink && !::DeleteFileA(_name.c_str())) ::OutputDebugStringA("ERROR! 'DeleteFile' failed"); } void reserve(uint64_t) override { } void resize(uint64_t size) override { LARGE_INTEGER offset; offset.QuadPart = size; if (!::SetFilePointerEx(_handle, offset, nullptr, FILE_BEGIN) || !::SetEndOfFile(_handle)) // TODO: Synchronization? throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; } void unlink() override { _unlink = true; } size_t write_at(uint64_t offset, const void* data, size_t size) override { DWORD result = 0; OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32); return ::WriteFile(_handle, data, static_cast<DWORD>(size), &result, &overlapped) ? result : 0; } private: const std::string _name; const HANDLE _handle; bool _unlink = false; }; std::unique_ptr<Source> Source::from(const std::string& path) { const auto handle = ::CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) return {}; LARGE_INTEGER size; if (!::GetFileSizeEx(handle, &size)) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; return std::make_unique<FileSource>(size.QuadPart, path, handle); } std::unique_ptr<Source> Source::from(const TemporaryFile& file) { return from(file.name()); } std::unique_ptr<WriterPrivate> create_file_writer(const std::string& path) { const auto handle = ::CreateFileA(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) return {}; return std::make_unique<FileWriter>(path, handle); } std::unique_ptr<WriterPrivate> create_file_writer(TemporaryFile& file) { return create_file_writer(file.name()); } }
#include "../file.h" #include <yttrium/storage/source.h> #include <yttrium/storage/temporary_file.h> #include "../../storage/writer.h" #include <system_error> #include "windows.h" namespace Yttrium { class FileSource final : public Source { public: FileSource(uint64_t size, const std::string& name, HANDLE handle) : Source{size, name} , _handle{handle} { } ~FileSource() noexcept override { if (!::CloseHandle(_handle)) ::OutputDebugStringA("ERROR! 'CloseHandle' failed"); } size_t read_at(uint64_t offset, void* data, size_t size) const override { DWORD result = 0; OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32); return ::ReadFile(_handle, data, static_cast<DWORD>(size), &result, &overlapped) ? result : 0; } private: const HANDLE _handle; }; class FileWriter final : public WriterPrivate { public: FileWriter(const std::string& name, HANDLE handle) : _name{name} , _handle{handle} { } ~FileWriter() noexcept override { if (!::CloseHandle(_handle)) ::OutputDebugStringA("ERROR! 'CloseHandle' failed"); if (_unlink && !::DeleteFileA(_name.c_str())) ::OutputDebugStringA("ERROR! 'DeleteFile' failed"); } void reserve(uint64_t) override { } void resize(uint64_t size) override { LARGE_INTEGER offset; offset.QuadPart = size; if (!::SetFilePointerEx(_handle, offset, nullptr, FILE_BEGIN) || !::SetEndOfFile(_handle)) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; } void unlink() override { _unlink = true; } size_t write_at(uint64_t offset, const void* data, size_t size) override { DWORD result = 0; OVERLAPPED overlapped = {}; overlapped.Offset = static_cast<DWORD>(offset); overlapped.OffsetHigh = static_cast<DWORD>(offset >> 32); return ::WriteFile(_handle, data, static_cast<DWORD>(size), &result, &overlapped) ? result : 0; } private: const std::string _name; const HANDLE _handle; bool _unlink = false; }; std::unique_ptr<Source> Source::from(const std::string& path) { const auto handle = ::CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) return {}; LARGE_INTEGER size; if (!::GetFileSizeEx(handle, &size)) throw std::system_error{static_cast<int>(::GetLastError()), std::system_category()}; return std::make_unique<FileSource>(size.QuadPart, path, handle); } std::unique_ptr<Source> Source::from(const TemporaryFile& file) { return from(file.name()); } std::unique_ptr<WriterPrivate> create_file_writer(const std::string& path) { const auto handle = ::CreateFileA(path.c_str(), GENERIC_WRITE, FILE_SHARE_READ, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); if (handle == INVALID_HANDLE_VALUE) return {}; return std::make_unique<FileWriter>(path, handle); } std::unique_ptr<WriterPrivate> create_file_writer(TemporaryFile& file) { return create_file_writer(file.name()); } }
Remove pointless TODO.
Remove pointless TODO.
C++
apache-2.0
blagodarin/yttrium,blagodarin/yttrium
c636fc2efed8ec16ce8e7ac6e86ccd4154db527d
src/plugins/coreplugin/id.cpp
src/plugins/coreplugin/id.cpp
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "id.h" #include "coreconstants.h" #include <utils/qtcassert.h> #include <QByteArray> #include <QHash> #include <QVector> #include <string.h> namespace Core { /*! \class Core::Id \brief The class Id encapsulates an identifier. It is used as a type-safe helper class instead of a \c QString or \c QByteArray. The internal representation of the id is assumed to be plain 7-bit-clean ASCII. */ class StringHolder { public: explicit StringHolder(const char *s) : str(s) { n = strlen(s); int m = n; h = 0; while (m--) { h = (h << 4) + *s++; h ^= (h & 0xf0000000) >> 23; h &= 0x0fffffff; } } int n; const char *str; uint h; }; static bool operator==(const StringHolder &sh1, const StringHolder &sh2) { // sh.n is unlikely to discriminate better than the hash. return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0; } static uint qHash(const StringHolder &sh) { return sh.h; } struct IdCache : public QHash<StringHolder, int> { #ifndef QTC_ALLOW_STATIC_LEAKS ~IdCache() { for (IdCache::iterator it = begin(); it != end(); ++it) free(const_cast<char *>(it.key().str)); } #endif }; static int lastUid = 0; static QVector<QByteArray> stringFromId; static IdCache idFromString; static int theId(const char *str) { QTC_ASSERT(str && *str, return 0); StringHolder sh(str); int res = idFromString.value(sh, 0); if (res == 0) { if (lastUid == 0) stringFromId.append(QByteArray()); res = ++lastUid; sh.str = strdup(sh.str); idFromString[sh] = res; stringFromId.append(QByteArray::fromRawData(sh.str, sh.n)); } return res; } Id::Id(const char *name) : m_id(theId(name)) {} Id::Id(const QString &name) : m_id(theId(name.toUtf8())) {} QByteArray Id::name() const { return stringFromId.at(m_id); } QString Id::toString() const { return QString::fromUtf8(stringFromId.at(m_id)); } bool Id::operator==(const char *name) const { return strcmp(stringFromId.at(m_id).constData(), name) == 0; } // For debugging purposes CORE_EXPORT const char *nameForId(int id) { return (stringFromId.constData() + id)->constData(); } } // namespace Core
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: http://www.qt-project.org/ ** ** ** GNU Lesser General Public License Usage ** ** 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, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** **************************************************************************/ #include "id.h" #include "coreconstants.h" #include <utils/qtcassert.h> #include <QByteArray> #include <QHash> #include <QVector> #include <string.h> namespace Core { /*! \class Core::Id \brief The class Id encapsulates an identifier. It is used as a type-safe helper class instead of a \c QString or \c QByteArray. The internal representation of the id is assumed to be plain 7-bit-clean ASCII. */ class StringHolder { public: explicit StringHolder(const char *s) : str(s) { n = strlen(s); int m = n; h = 0; while (m--) { h = (h << 4) + *s++; h ^= (h & 0xf0000000) >> 23; h &= 0x0fffffff; } } int n; const char *str; uint h; }; static bool operator==(const StringHolder &sh1, const StringHolder &sh2) { // sh.n is unlikely to discriminate better than the hash. return sh1.h == sh2.h && strcmp(sh1.str, sh1.str) == 0; } static uint qHash(const StringHolder &sh) { return sh.h; } struct IdCache : public QHash<StringHolder, int> { #ifndef QTC_ALLOW_STATIC_LEAKS ~IdCache() { for (IdCache::iterator it = begin(); it != end(); ++it) free(const_cast<char *>(it.key().str)); } #endif }; static int lastUid = 0; static QVector<QByteArray> stringFromId; static IdCache idFromString; static int theId(const char *str) { QTC_ASSERT(str && *str, return 0); StringHolder sh(str); int res = idFromString.value(sh, 0); if (res == 0) { if (lastUid == 0) stringFromId.append(QByteArray()); res = ++lastUid; sh.str = qstrdup(sh.str); idFromString[sh] = res; stringFromId.append(QByteArray::fromRawData(sh.str, sh.n)); } return res; } Id::Id(const char *name) : m_id(theId(name)) {} Id::Id(const QString &name) : m_id(theId(name.toUtf8())) {} QByteArray Id::name() const { return stringFromId.at(m_id); } QString Id::toString() const { return QString::fromUtf8(stringFromId.at(m_id)); } bool Id::operator==(const char *name) const { return strcmp(stringFromId.at(m_id).constData(), name) == 0; } // For debugging purposes CORE_EXPORT const char *nameForId(int id) { return (stringFromId.constData() + id)->constData(); } } // namespace Core
Fix MSVC compiler warning about strdup
Core: Fix MSVC compiler warning about strdup Fix warning: C4996: 'strdup': The POSIX name for this item is deprecated. Instead, use the ISO C++ conformant name: _strdup. By just using qstrdup. Change-Id: I40664b6ed763b27951d983ec13dcc638270a1beb Reviewed-by: hjk <[email protected]>
C++
lgpl-2.1
maui-packages/qt-creator,malikcjm/qtcreator,kuba1/qtcreator,amyvmiwei/qt-creator,richardmg/qtcreator,amyvmiwei/qt-creator,duythanhphan/qt-creator,maui-packages/qt-creator,farseerri/git_code,xianian/qt-creator,kuba1/qtcreator,AltarBeastiful/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,duythanhphan/qt-creator,Distrotech/qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,farseerri/git_code,omniacreator/qtcreator,syntheticpp/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,farseerri/git_code,danimo/qt-creator,danimo/qt-creator,martyone/sailfish-qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,syntheticpp/qt-creator,malikcjm/qtcreator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,xianian/qt-creator,syntheticpp/qt-creator,duythanhphan/qt-creator,danimo/qt-creator,danimo/qt-creator,colede/qtcreator,richardmg/qtcreator,Distrotech/qtcreator,richardmg/qtcreator,darksylinc/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,martyone/sailfish-qtcreator,darksylinc/qt-creator,xianian/qt-creator,maui-packages/qt-creator,martyone/sailfish-qtcreator,richardmg/qtcreator,malikcjm/qtcreator,martyone/sailfish-qtcreator,colede/qtcreator,richardmg/qtcreator,darksylinc/qt-creator,darksylinc/qt-creator,martyone/sailfish-qtcreator,maui-packages/qt-creator,malikcjm/qtcreator,amyvmiwei/qt-creator,xianian/qt-creator,farseerri/git_code,maui-packages/qt-creator,kuba1/qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,Distrotech/qtcreator,darksylinc/qt-creator,omniacreator/qtcreator,xianian/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,kuba1/qtcreator,syntheticpp/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,syntheticpp/qt-creator,malikcjm/qtcreator,Distrotech/qtcreator,omniacreator/qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,danimo/qt-creator,xianian/qt-creator,colede/qtcreator,colede/qtcreator,kuba1/qtcreator,farseerri/git_code,kuba1/qtcreator,kuba1/qtcreator,kuba1/qtcreator,Distrotech/qtcreator,amyvmiwei/qt-creator,richardmg/qtcreator,farseerri/git_code,AltarBeastiful/qt-creator,malikcjm/qtcreator,farseerri/git_code,martyone/sailfish-qtcreator,xianian/qt-creator,colede/qtcreator,martyone/sailfish-qtcreator,danimo/qt-creator,Distrotech/qtcreator,Distrotech/qtcreator,AltarBeastiful/qt-creator,AltarBeastiful/qt-creator,danimo/qt-creator,darksylinc/qt-creator,syntheticpp/qt-creator,AltarBeastiful/qt-creator,xianian/qt-creator,duythanhphan/qt-creator,maui-packages/qt-creator,AltarBeastiful/qt-creator,farseerri/git_code,colede/qtcreator,kuba1/qtcreator,omniacreator/qtcreator,duythanhphan/qt-creator,maui-packages/qt-creator,colede/qtcreator
0e23f0c674f95802bd9f5fb0e1ada65c1cae032e
base/trace_event_win_unittest.cc
base/trace_event_win_unittest.cc
// Copyright (c) 2010 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 "base/trace_event.h" #include <strstream> #include "base/basictypes.h" #include "base/file_util.h" #include "base/event_trace_consumer_win.h" #include "base/event_trace_controller_win.h" #include "base/win_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include <initguid.h> // NOLINT - must be last include. namespace { using testing::_; using testing::AnyNumber; using testing::InSequence; using testing::Ge; using testing::Le; using testing::NotNull; // Data for unittests traces. const char kEmpty[] = ""; const char kName[] = "unittest.trace_name"; const char kExtra[] = "UnittestDummyExtraString"; const void* kId = kName; const wchar_t kTestSessionName[] = L"TraceEvent unittest session"; MATCHER_P(BufferStartsWith, str, "Buffer starts with") { return memcmp(arg, str.c_str(), str.length()) == 0; } // Duplicated from <evntrace.h> to fix link problems. DEFINE_GUID( /* 68fdd900-4a3e-11d1-84f4-0000f80464e3 */ kEventTraceGuid, 0x68fdd900, 0x4a3e, 0x11d1, 0x84, 0xf4, 0x00, 0x00, 0xf8, 0x04, 0x64, 0xe3); class TestEventConsumer: public EtwTraceConsumerBase<TestEventConsumer> { public: TestEventConsumer() { EXPECT_TRUE(current_ == NULL); current_ = this; } ~TestEventConsumer() { EXPECT_TRUE(current_ == this); current_ = NULL; } MOCK_METHOD4(Event, void(REFGUID event_class, EtwEventType event_type, size_t buf_len, const void* buf)); static void ProcessEvent(EVENT_TRACE* event) { ASSERT_TRUE(current_ != NULL); current_->Event(event->Header.Guid, event->Header.Class.Type, event->MofLength, event->MofData); } private: static TestEventConsumer* current_; }; TestEventConsumer* TestEventConsumer::current_ = NULL; class TraceEventTest: public testing::Test { public: void SetUp() { bool is_xp = win_util::GetWinVersion() < win_util::WINVERSION_VISTA; // Resurrect and initialize the TraceLog singleton instance. // On Vista and better, we need the provider registered before we // start the private, in-proc session, but on XP we need the global // session created and the provider enabled before we register our // provider. if (!is_xp) { base::TraceLog::Resurrect(); base::TraceLog* tracelog = base::TraceLog::Get(); ASSERT_TRUE(tracelog != NULL); } // Create the log file. ASSERT_TRUE(file_util::CreateTemporaryFile(&log_file_)); // Create a private log session on the file. EtwTraceProperties prop; ASSERT_HRESULT_SUCCEEDED(prop.SetLoggerFileName(log_file_.value().c_str())); EVENT_TRACE_PROPERTIES& p = *prop.get(); p.Wnode.ClientContext = 1; // QPC timer accuracy. p.LogFileMode = EVENT_TRACE_FILE_MODE_SEQUENTIAL; // Sequential log. // On Vista and later, we create a private in-process log session, because // otherwise we'd need administrator privileges. Unfortunately we can't // do the same on XP and better, because the semantics of a private // logger session are different, and the IN_PROC flag is not supported. if (!is_xp) { p.LogFileMode |= EVENT_TRACE_PRIVATE_IN_PROC | // In-proc for non-admin. EVENT_TRACE_PRIVATE_LOGGER_MODE; // Process-private log. } p.MaximumFileSize = 100; // 100M file size. p.FlushTimer = 1; // 1 second flush lag. ASSERT_HRESULT_SUCCEEDED(controller_.Start(kTestSessionName, &prop)); // Enable the TraceLog provider GUID. ASSERT_HRESULT_SUCCEEDED( controller_.EnableProvider(base::kChromeTraceProviderName, TRACE_LEVEL_INFORMATION, 0)); if (is_xp) { base::TraceLog::Resurrect(); base::TraceLog* tracelog = base::TraceLog::Get(); ASSERT_TRUE(tracelog != NULL); } } void TearDown() { EtwTraceProperties prop; if (controller_.session() != 0) EXPECT_HRESULT_SUCCEEDED(controller_.Stop(&prop)); if (!log_file_.value().empty()) file_util::Delete(log_file_, false); } void ExpectEvent(REFGUID guid, EtwEventType type, const char* name, size_t name_len, const void* id, const char* extra, size_t extra_len) { // Build the trace event buffer we expect will result from this. std::stringbuf str; str.sputn(name, name_len + 1); str.sputn(reinterpret_cast<const char*>(&id), sizeof(id)); str.sputn(extra, extra_len + 1); // And set up the expectation for the event callback. EXPECT_CALL(consumer_, Event(guid, type, testing::Ge(str.str().length()), BufferStartsWith(str.str()))); } void ExpectPlayLog() { // Ignore EventTraceGuid events. EXPECT_CALL(consumer_, Event(kEventTraceGuid, _, _, _)) .Times(AnyNumber()); } void PlayLog() { EtwTraceProperties prop; EXPECT_HRESULT_SUCCEEDED(controller_.Stop(&prop)); ASSERT_HRESULT_SUCCEEDED( consumer_.OpenFileSession(log_file_.value().c_str())); ASSERT_HRESULT_SUCCEEDED(consumer_.Consume()); } private: EtwTraceController controller_; FilePath log_file_; TestEventConsumer consumer_; }; } // namespace TEST_F(TraceEventTest, TraceLog) { ExpectPlayLog(); // The events should arrive in the same sequence as the expects. InSequence in_sequence; // Full argument version, passing lengths explicitly. base::TraceLog::Trace(kName, strlen(kName), base::TraceLog::EVENT_BEGIN, kId, kExtra, strlen(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // Const char* version. base::TraceLog::Trace(static_cast<const char*>(kName), base::TraceLog::EVENT_END, kId, static_cast<const char*>(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // std::string extra version. base::TraceLog::Trace(static_cast<const char*>(kName), base::TraceLog::EVENT_INSTANT, kId, std::string(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeInstant, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // Test for sanity on NULL inputs. base::TraceLog::Trace(NULL, 0, base::TraceLog::EVENT_BEGIN, kId, NULL, 0); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kEmpty, 0, kId, kEmpty, 0); base::TraceLog::Trace(NULL, -1, base::TraceLog::EVENT_END, kId, NULL, -1); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kEmpty, 0, kId, kEmpty, 0); PlayLog(); } TEST_F(TraceEventTest, Macros) { ExpectPlayLog(); // The events should arrive in the same sequence as the expects. InSequence in_sequence; TRACE_EVENT_BEGIN(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kName, strlen(kName), kId, kExtra, strlen(kExtra)); TRACE_EVENT_END(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kName, strlen(kName), kId, kExtra, strlen(kExtra)); TRACE_EVENT_INSTANT(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeInstant, kName, strlen(kName), kId, kExtra, strlen(kExtra)); PlayLog(); }
// Copyright (c) 2010 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 "base/trace_event.h" #include <strstream> #include "base/basictypes.h" #include "base/file_util.h" #include "base/event_trace_consumer_win.h" #include "base/event_trace_controller_win.h" #include "base/win_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include <initguid.h> // NOLINT - must be last include. namespace { using testing::_; using testing::AnyNumber; using testing::InSequence; using testing::Ge; using testing::Le; using testing::NotNull; // Data for unittests traces. const char kEmpty[] = ""; const char kName[] = "unittest.trace_name"; const char kExtra[] = "UnittestDummyExtraString"; const void* kId = kName; const wchar_t kTestSessionName[] = L"TraceEvent unittest session"; MATCHER_P(BufferStartsWith, str, "Buffer starts with") { return memcmp(arg, str.c_str(), str.length()) == 0; } // Duplicated from <evntrace.h> to fix link problems. DEFINE_GUID( /* 68fdd900-4a3e-11d1-84f4-0000f80464e3 */ kEventTraceGuid, 0x68fdd900, 0x4a3e, 0x11d1, 0x84, 0xf4, 0x00, 0x00, 0xf8, 0x04, 0x64, 0xe3); class TestEventConsumer: public EtwTraceConsumerBase<TestEventConsumer> { public: TestEventConsumer() { EXPECT_TRUE(current_ == NULL); current_ = this; } ~TestEventConsumer() { EXPECT_TRUE(current_ == this); current_ = NULL; } MOCK_METHOD4(Event, void(REFGUID event_class, EtwEventType event_type, size_t buf_len, const void* buf)); static void ProcessEvent(EVENT_TRACE* event) { ASSERT_TRUE(current_ != NULL); current_->Event(event->Header.Guid, event->Header.Class.Type, event->MofLength, event->MofData); } private: static TestEventConsumer* current_; }; TestEventConsumer* TestEventConsumer::current_ = NULL; class TraceEventTest: public testing::Test { public: void SetUp() { bool is_xp = win_util::GetWinVersion() < win_util::WINVERSION_VISTA; // Resurrect and initialize the TraceLog singleton instance. // On Vista and better, we need the provider registered before we // start the private, in-proc session, but on XP we need the global // session created and the provider enabled before we register our // provider. if (!is_xp) { base::TraceLog::Resurrect(); base::TraceLog* tracelog = base::TraceLog::Get(); ASSERT_TRUE(tracelog != NULL); } // Create the log file. ASSERT_TRUE(file_util::CreateTemporaryFile(&log_file_)); // Create a private log session on the file. EtwTraceProperties prop; ASSERT_HRESULT_SUCCEEDED(prop.SetLoggerFileName(log_file_.value().c_str())); EVENT_TRACE_PROPERTIES& p = *prop.get(); p.Wnode.ClientContext = 1; // QPC timer accuracy. p.LogFileMode = EVENT_TRACE_FILE_MODE_SEQUENTIAL; // Sequential log. // On Vista and later, we create a private in-process log session, because // otherwise we'd need administrator privileges. Unfortunately we can't // do the same on XP and better, because the semantics of a private // logger session are different, and the IN_PROC flag is not supported. if (!is_xp) { p.LogFileMode |= EVENT_TRACE_PRIVATE_IN_PROC | // In-proc for non-admin. EVENT_TRACE_PRIVATE_LOGGER_MODE; // Process-private log. } p.MaximumFileSize = 100; // 100M file size. p.FlushTimer = 1; // 1 second flush lag. ASSERT_HRESULT_SUCCEEDED(controller_.Start(kTestSessionName, &prop)); // Enable the TraceLog provider GUID. ASSERT_HRESULT_SUCCEEDED( controller_.EnableProvider(base::kChromeTraceProviderName, TRACE_LEVEL_INFORMATION, 0)); if (is_xp) { base::TraceLog::Resurrect(); base::TraceLog* tracelog = base::TraceLog::Get(); ASSERT_TRUE(tracelog != NULL); } } void TearDown() { EtwTraceProperties prop; if (controller_.session() != 0) EXPECT_HRESULT_SUCCEEDED(controller_.Stop(&prop)); if (!log_file_.value().empty()) file_util::Delete(log_file_, false); } void ExpectEvent(REFGUID guid, EtwEventType type, const char* name, size_t name_len, const void* id, const char* extra, size_t extra_len) { // Build the trace event buffer we expect will result from this. std::stringbuf str; str.sputn(name, name_len + 1); str.sputn(reinterpret_cast<const char*>(&id), sizeof(id)); str.sputn(extra, extra_len + 1); // And set up the expectation for the event callback. EXPECT_CALL(consumer_, Event(guid, type, testing::Ge(str.str().length()), BufferStartsWith(str.str()))); } void ExpectPlayLog() { // Ignore EventTraceGuid events. EXPECT_CALL(consumer_, Event(kEventTraceGuid, _, _, _)) .Times(AnyNumber()); } void PlayLog() { EtwTraceProperties prop; EXPECT_HRESULT_SUCCEEDED(controller_.Stop(&prop)); ASSERT_HRESULT_SUCCEEDED( consumer_.OpenFileSession(log_file_.value().c_str())); ASSERT_HRESULT_SUCCEEDED(consumer_.Consume()); } private: EtwTraceController controller_; FilePath log_file_; TestEventConsumer consumer_; }; } // namespace TEST_F(TraceEventTest, TraceLog) { ExpectPlayLog(); // The events should arrive in the same sequence as the expects. InSequence in_sequence; // Full argument version, passing lengths explicitly. base::TraceLog::Trace(kName, strlen(kName), base::TraceLog::EVENT_BEGIN, kId, kExtra, strlen(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // Const char* version. base::TraceLog::Trace(static_cast<const char*>(kName), base::TraceLog::EVENT_END, kId, static_cast<const char*>(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // std::string extra version. base::TraceLog::Trace(static_cast<const char*>(kName), base::TraceLog::EVENT_INSTANT, kId, std::string(kExtra)); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeInstant, kName, strlen(kName), kId, kExtra, strlen(kExtra)); // Test for sanity on NULL inputs. base::TraceLog::Trace(NULL, 0, base::TraceLog::EVENT_BEGIN, kId, NULL, 0); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kEmpty, 0, kId, kEmpty, 0); base::TraceLog::Trace(NULL, -1, base::TraceLog::EVENT_END, kId, NULL, -1); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kEmpty, 0, kId, kEmpty, 0); PlayLog(); } TEST_F(TraceEventTest, Macros_FLAKY) { ExpectPlayLog(); // The events should arrive in the same sequence as the expects. InSequence in_sequence; TRACE_EVENT_BEGIN(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeBegin, kName, strlen(kName), kId, kExtra, strlen(kExtra)); TRACE_EVENT_END(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeEnd, kName, strlen(kName), kId, kExtra, strlen(kExtra)); TRACE_EVENT_INSTANT(kName, kId, kExtra); ExpectEvent(base::kTraceEventClass32, base::kTraceEventTypeInstant, kName, strlen(kName), kId, kExtra, strlen(kExtra)); PlayLog(); }
Mark TraceEventTest.Macros which has started mysteriously failing.
Mark TraceEventTest.Macros which has started mysteriously failing. BUG=52388 TBR=mpcomplete Review URL: http://codereview.chromium.org/3130025 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@56293 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium
43cb3cee7030bb71eef9cf1ebf0c9f1ff43f63db
Rpr/WrapObject/CameraObject.cpp
Rpr/WrapObject/CameraObject.cpp
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 "WrapObject/CameraObject.h" #include "SceneGraph/camera.h" #include "radeon_rays.h" #include <assert.h> #include "WrapObject/SceneObject.h" using namespace Baikal; using namespace RadeonRays; CameraObject::CameraObject() : m_cam(nullptr) { } CameraObject::~CameraObject() { } void CameraObject::SetTransform(const RadeonRays::matrix& m) { //default values RadeonRays::float4 eye(0.f, 0.f, 0.f, 1.0f); RadeonRays::float4 at(0.f, 0.f, -1.f, 0.0f); RadeonRays::float4 up(0.f, 1.f, 0.f, 0.0f); m_eye = m * eye; m_at = m * at; m_up = m * up; UpdateCameraParams(); } void CameraObject::GetLookAt(RadeonRays::float3& eye, RadeonRays::float3& at, RadeonRays::float3& up) { eye = m_eye; at = m_at; up = m_up; } Baikal::Camera::Ptr CameraObject::GetCamera() { if (m_mode == RPR_CAMERA_MODE_PERSPECTIVE) { Baikal::PerspectiveCamera::Ptr camera = PerspectiveCamera::Create(m_eye, m_at, m_up); camera->SetSensorSize(m_camera_sensor_size); camera->SetDepthRange(m_camera_zcap); camera->SetFocalLength(m_camera_focal_length); camera->SetFocusDistance(m_camera_focus_distance); camera->SetAperture(m_camera_aperture); m_cam = camera; return m_cam; } else if (m_mode == RPR_CAMERA_MODE_ORTHOGRAPHIC) { Baikal::OrthographicCamera::Ptr camera = OrthographicCamera::Create(m_eye, m_at, m_up); camera->SetSensorSize(m_camera_sensor_size); camera->SetDepthRange(m_camera_zcap); m_cam = camera; return m_cam; } assert(!"Usupported camera type"); return nullptr; } void CameraObject::LookAt(RadeonRays::float3 const& eye, RadeonRays::float3 const& at, RadeonRays::float3 const& up) { m_eye = eye; m_at = at; m_up = up; UpdateCameraParams(); } void CameraObject::SetMode(rpr_camera_mode mode) { m_mode = mode; UpdateCameraParams(); } void CameraObject::UpdateCameraParams() { // Replace camera in all scenes that have it for (::SceneObject* scene : m_scenes) { scene->SetCamera(this); } } void CameraObject::AddToScene(::SceneObject* scene) { auto it = std::find(m_scenes.begin(), m_scenes.end(), scene); if (it != m_scenes.end()) return; m_scenes.push_back(scene); } void CameraObject::RemoveFromScene(::SceneObject* scene) { m_scenes.remove(scene); } void CameraObject::SetFocalLength(rpr_float flen) { m_camera_focal_length = flen / 1000.f; UpdateCameraParams(); } void CameraObject::SetFocusDistance(rpr_float fdist) { m_camera_focus_distance = fdist; UpdateCameraParams(); } void CameraObject::SetSensorSize(RadeonRays::float2 size) { m_camera_sensor_size = size * 0.001f; UpdateCameraParams(); } void CameraObject::SetOrthoWidth(float width) { //m_camera_sensor_size.x = width; UpdateCameraParams(); } void CameraObject::SetOrthoHeight(float height) { //m_camera_sensor_size.y = height; UpdateCameraParams(); } void CameraObject::SetAperture(rpr_float fstop) { m_camera_aperture = 100000.f;//fstop / 1000.f; UpdateCameraParams(); }
/********************************************************************** Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. 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 "WrapObject/CameraObject.h" #include "SceneGraph/camera.h" #include "radeon_rays.h" #include <assert.h> #include "WrapObject/SceneObject.h" using namespace Baikal; using namespace RadeonRays; CameraObject::CameraObject() : m_cam(nullptr) { } CameraObject::~CameraObject() { } void CameraObject::SetTransform(const RadeonRays::matrix& m) { //default values RadeonRays::float4 eye(0.f, 0.f, 0.f, 1.0f); RadeonRays::float4 at(0.f, 0.f, -1.f, 0.0f); RadeonRays::float4 up(0.f, 1.f, 0.f, 0.0f); m_eye = m * eye; m_at = m * at; m_up = m * up; UpdateCameraParams(); } void CameraObject::GetLookAt(RadeonRays::float3& eye, RadeonRays::float3& at, RadeonRays::float3& up) { eye = m_eye; at = m_at; up = m_up; } Baikal::Camera::Ptr CameraObject::GetCamera() { if (m_mode == RPR_CAMERA_MODE_PERSPECTIVE) { Baikal::PerspectiveCamera::Ptr camera = PerspectiveCamera::Create(m_eye, m_at, m_up); camera->SetSensorSize(m_camera_sensor_size); camera->SetDepthRange(m_camera_zcap); camera->SetFocalLength(m_camera_focal_length); camera->SetFocusDistance(m_camera_focus_distance); camera->SetAperture(m_camera_aperture); m_cam = camera; return m_cam; } else if (m_mode == RPR_CAMERA_MODE_ORTHOGRAPHIC) { Baikal::OrthographicCamera::Ptr camera = OrthographicCamera::Create(m_eye, m_at, m_up); camera->SetSensorSize(m_camera_sensor_size); camera->SetDepthRange(m_camera_zcap); m_cam = camera; return m_cam; } assert(!"Usupported camera type"); return nullptr; } void CameraObject::LookAt(RadeonRays::float3 const& eye, RadeonRays::float3 const& at, RadeonRays::float3 const& up) { m_eye = eye; m_at = at; m_up = up; UpdateCameraParams(); } void CameraObject::SetMode(rpr_camera_mode mode) { m_mode = mode; UpdateCameraParams(); } void CameraObject::UpdateCameraParams() { // Replace camera in all scenes that have it for (::SceneObject* scene : m_scenes) { scene->SetCamera(this); } } void CameraObject::AddToScene(::SceneObject* scene) { auto it = std::find(m_scenes.begin(), m_scenes.end(), scene); if (it != m_scenes.end()) return; m_scenes.push_back(scene); } void CameraObject::RemoveFromScene(::SceneObject* scene) { m_scenes.remove(scene); } void CameraObject::SetFocalLength(rpr_float flen) { m_camera_focal_length = flen / 1000.f; UpdateCameraParams(); } void CameraObject::SetFocusDistance(rpr_float fdist) { m_camera_focus_distance = fdist; UpdateCameraParams(); } void CameraObject::SetSensorSize(RadeonRays::float2 size) { m_camera_sensor_size = size * 0.001f; UpdateCameraParams(); } void CameraObject::SetOrthoWidth(float width) { m_camera_sensor_size.x = width; UpdateCameraParams(); } void CameraObject::SetOrthoHeight(float height) { m_camera_sensor_size.y = height; UpdateCameraParams(); } void CameraObject::SetAperture(rpr_float fstop) { if (fstop > 1000.f) { fstop = 0.f; } m_camera_aperture = fstop / 1000.f; UpdateCameraParams(); }
Fix gltf loading
Fix gltf loading
C++
mit
GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal,GPUOpen-LibrariesAndSDKs/RadeonProRender-Baikal
b05e0c011ce0112f5ac647e5179457ba3d8c6a75
game/apocresources/apocfont.cpp
game/apocresources/apocfont.cpp
#include "library/sp.h" #include "game/apocresources/apocfont.h" #include "framework/framework.h" #include "framework/image.h" #include "framework/palette.h" #include <boost/locale.hpp> namespace OpenApoc { sp<BitmapFont> ApocalypseFont::loadFont(tinyxml2::XMLElement *fontElement) { int spacewidth = 0; int height = 0; UString fontName; std::map<UniChar, UString> charMap; const char *attr = fontElement->Attribute("name"); if (!attr) { LogError("apocfont element with no \"name\" attribute"); return nullptr; } fontName = attr; auto err = fontElement->QueryIntAttribute("height", &height); if (err != tinyxml2::XML_NO_ERROR || height <= 0) { LogError("apocfont \"%s\" with invalid \"height\" attribute", fontName.c_str()); return nullptr; } err = fontElement->QueryIntAttribute("spacewidth", &spacewidth); if (err != tinyxml2::XML_NO_ERROR || spacewidth <= 0) { LogError("apocfont \"%s\" with invalid \"spacewidth\" attribute", fontName.c_str()); return nullptr; } for (auto *glyphNode = fontElement->FirstChildElement(); glyphNode; glyphNode = glyphNode->NextSiblingElement()) { UString nodeName = glyphNode->Name(); if (nodeName != "glyph") { LogError("apocfont \"%s\" has unexpected child node \"%s\", skipping", fontName.c_str(), nodeName.c_str()); continue; } int offset; auto *glyphPath = glyphNode->Attribute("glyph"); if (!glyphPath) { LogError("Font \"%s\" has glyph with missing string attribute - skipping glyph", fontName.c_str()); continue; } auto *glyphString = glyphNode->Attribute("string"); if (!glyphString) { LogError("apocfont \"%s\" has glyph with missing string attribute - skipping glyph", fontName.c_str()); continue; } auto pointString = boost::locale::conv::utf_to_utf<UniChar>(glyphString); if (pointString.length() != 1) { LogError("apocfont \"%s\" glyph w/offset %d has %d codepoints, expected one - skipping " "glyph", fontName.c_str(), offset, pointString.length()); continue; } UniChar c = pointString[0]; if (charMap.find(c) != charMap.end()) { LogError("Font \"%s\" has multiple glyphs for string \"%s\" - skipping glyph", fontName.c_str(), glyphString); continue; } charMap[c] = glyphPath; } auto font = BitmapFont::loadFont(charMap, spacewidth, height, fontName, fw().data->load_palette(fontElement->Attribute("palette"))); return font; } }; // namespace OpenApoc
#include "library/sp.h" #include "game/apocresources/apocfont.h" #include "framework/framework.h" #include "framework/image.h" #include "framework/palette.h" #include <boost/locale.hpp> namespace OpenApoc { sp<BitmapFont> ApocalypseFont::loadFont(tinyxml2::XMLElement *fontElement) { int spacewidth = 0; int height = 0; UString fontName; std::map<UniChar, UString> charMap; const char *attr = fontElement->Attribute("name"); if (!attr) { LogError("apocfont element with no \"name\" attribute"); return nullptr; } fontName = attr; auto err = fontElement->QueryIntAttribute("height", &height); if (err != tinyxml2::XML_NO_ERROR || height <= 0) { LogError("apocfont \"%s\" with invalid \"height\" attribute", fontName.c_str()); return nullptr; } err = fontElement->QueryIntAttribute("spacewidth", &spacewidth); if (err != tinyxml2::XML_NO_ERROR || spacewidth <= 0) { LogError("apocfont \"%s\" with invalid \"spacewidth\" attribute", fontName.c_str()); return nullptr; } for (auto *glyphNode = fontElement->FirstChildElement(); glyphNode; glyphNode = glyphNode->NextSiblingElement()) { UString nodeName = glyphNode->Name(); if (nodeName != "glyph") { LogError("apocfont \"%s\" has unexpected child node \"%s\", skipping", fontName.c_str(), nodeName.c_str()); continue; } auto *glyphPath = glyphNode->Attribute("glyph"); if (!glyphPath) { LogError("Font \"%s\" has glyph with missing string attribute - skipping glyph", fontName.c_str()); continue; } auto *glyphString = glyphNode->Attribute("string"); if (!glyphString) { LogError("apocfont \"%s\" has glyph with missing string attribute - skipping glyph", fontName.c_str()); continue; } auto pointString = boost::locale::conv::utf_to_utf<UniChar>(glyphString); if (pointString.length() != 1) { LogError("apocfont \"%s\" glyph \"%s\" has %d codepoints, expected one - skipping " "glyph", fontName.c_str(), glyphString, pointString.length()); continue; } UniChar c = pointString[0]; if (charMap.find(c) != charMap.end()) { LogError("Font \"%s\" has multiple glyphs for string \"%s\" - skipping glyph", fontName.c_str(), glyphString); continue; } charMap[c] = glyphPath; } auto font = BitmapFont::loadFont(charMap, spacewidth, height, fontName, fw().data->load_palette(fontElement->Attribute("palette"))); return font; } }; // namespace OpenApoc
Fix apocfont error print if multiple codepoints
Fix apocfont error print if multiple codepoints It would print out an 'offset' that was actually an unset local int
C++
mit
steveschnepp/OpenApoc,Istrebitel/OpenApoc,Istrebitel/OpenApoc,FranciscoDA/OpenApoc,pmprog/OpenApoc,pmprog/OpenApoc,ShadowDancer/OpenApoc,ShadowDancer/OpenApoc,steveschnepp/OpenApoc,FranciscoDA/OpenApoc,FranciscoDA/OpenApoc
f9dc1ffab25f50993024937c02bcc0bfd3592e42
chrome/browser/debugger/debugger_node.cc
chrome/browser/debugger/debugger_node.cc
// Copyright (c) 2006-2008 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 "chrome/browser/debugger/debugger_node.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/debugger/debugger_shell.h" #include "chrome/common/notification_service.h" DebuggerNode::DebuggerNode() : data_(NULL), valid_(true) { } void DebuggerNode::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { registrar_.RemoveAll(); data_ = NULL; Invalidate(); } DebuggerNode::~DebuggerNode() { } v8::Handle<v8::Value> DebuggerNode::IndexGetter(uint32_t index, const v8::AccessorInfo& info) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::Function(const v8::Arguments& args) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::NewInstance() { DebuggerNodeWrapper *wrap = new DebuggerNodeWrapper(this); wrap->AddRef(); v8::Local<v8::External> node = v8::External::New(wrap); // TODO(erikkay): cache these templates? v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(); if (IsFunction()) { templ->SetCallHandler(&DebuggerNode::NodeFunc, node); v8::Local<v8::Function> f = templ->GetFunction(); return f; } v8::Local<v8::ObjectTemplate> instance = templ->InstanceTemplate(); if (IsObject()) { instance->SetNamedPropertyHandler(&DebuggerNode::NodeGetter, 0, 0, 0, 0, node); // TODO(erikkay): verify that the interceptor does not have to be // behind the object } if (IsCollection()) { instance->SetIndexedPropertyHandler(&DebuggerNode::NodeIndex, 0, 0, 0, 0, node); } v8::Local<v8::Object> ret = instance->NewInstance(); v8::Persistent<v8::Object> p = v8::Persistent<v8::Object>::New(ret); p.MakeWeak(wrap, &DebuggerShell::HandleWeakReference); return ret; } v8::Handle<v8::Value> DebuggerNode::NodeGetter(v8::Local<v8::String> prop, const v8::AccessorInfo& info) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *info.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsObject()) ? n->PropGetter(prop, info) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } v8::Handle<v8::Value> DebuggerNode::NodeIndex(uint32_t index, const v8::AccessorInfo& info) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *info.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsCollection()) ? n->IndexGetter(index, info) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } v8::Handle<v8::Value> DebuggerNode::NodeFunc(const v8::Arguments& args) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *args.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsFunction()) ? n->Function(args) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } ///////////////////////////////////////////// ChromeNode::ChromeNode(DebuggerShell* debugger) { debugger_ = debugger; } ChromeNode::~ChromeNode() { } v8::Handle<v8::Value> ChromeNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { if (prop->Equals(v8::String::New("pid"))) return v8::Number::New(base::GetCurrentProcId()); if (prop->Equals(v8::String::New("browser"))) return BrowserListNode::BrowserList()->NewInstance(); if (prop->Equals(v8::String::New("setDebuggerReady"))) { return (new FunctionNode<DebuggerShell>(DebuggerShell::SetDebuggerReady, debugger_))->NewInstance(); } if (prop->Equals(v8::String::New("setDebuggerBreak"))) { return (new FunctionNode<DebuggerShell>(DebuggerShell::SetDebuggerBreak, debugger_))->NewInstance(); } return (prop->Equals(v8::String::New("foo"))) ? static_cast<v8::Handle<v8::Value> >(v8::Undefined()) : prop; } ///////////////////////////////////////////// BrowserNode::BrowserNode(Browser *b) { data_ = b; registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(b)); } BrowserNode* BrowserNode::BrowserAtIndex(int index) { if (index >= 0) { BrowserList::const_iterator iter = BrowserList::begin(); for (; (iter != BrowserList::end()) && (index > 0); ++iter, --index) ; if (iter != BrowserList::end()) return new BrowserNode(*iter); } return NULL; } BrowserNode::~BrowserNode() { } Browser* BrowserNode::GetBrowser() { return IsValid() ? static_cast<Browser*>(data_) : NULL; } v8::Handle<v8::Value> BrowserNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { Browser* b = GetBrowser(); if (b != NULL) { if (prop->Equals(v8::String::New("title"))) { return v8::String::New(UTF16ToUTF8( b->GetSelectedTabContents()->GetTitle()).c_str()); } if (prop->Equals(v8::String::New("tab"))) return TabListNode::TabList(b)->NewInstance(); } return v8::Undefined(); } ///////////////////////////////////////////// BrowserListNode* BrowserListNode::BrowserList() { // TODO(erikkay): cache return new BrowserListNode(); } BrowserListNode::BrowserListNode() { } BrowserListNode::~BrowserListNode() { } v8::Handle<v8::Value> BrowserListNode::IndexGetter( uint32_t index, const v8::AccessorInfo& info) { BrowserNode* b = BrowserNode::BrowserAtIndex(index); return b ? b->NewInstance() : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } ///////////////////////////////////////////// TabListNode::TabListNode(Browser* b) { data_ = b; registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(b)); } TabListNode::~TabListNode() { } TabListNode* TabListNode::TabList(Browser* b) { return new TabListNode(b); } Browser* TabListNode::GetBrowser() { return IsValid() ? static_cast<Browser*>(data_) : NULL; } v8::Handle<v8::Value> TabListNode::IndexGetter(uint32_t index, const v8::AccessorInfo& info) { Browser* b = GetBrowser(); if (b != NULL) { TabContents* tab_contents = b->GetTabContentsAt(index); if (tab_contents) return (new TabNode(tab_contents))->NewInstance(); } return v8::Undefined(); } ///////////////////////////////////////////// TabNode::TabNode(TabContents* c) { NavigationController* controller = &c->controller(); data_ = controller; registrar_.Add(this, NotificationType::TAB_CLOSING, Source<NavigationController>(controller)); } TabNode::~TabNode() { } TabContents* TabNode::GetTab() { return IsValid() ? static_cast<NavigationController*>(data_)->tab_contents() : NULL; } v8::Handle<v8::Value> TabNode::SendToDebugger(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); if (args.Length() == 1) { std::wstring cmd; v8::Handle<v8::Value> obj = args[0]; DebuggerShell::ObjectToString(obj, &cmd); host->DebugCommand(cmd); } return v8::Undefined(); } v8::Handle<v8::Value> TabNode::Attach(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); host->DebugAttach(); return v8::Int32::New(host->process()->process().pid()); } v8::Handle<v8::Value> TabNode::Detach(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); host->DebugDetach(); return v8::Int32::New(host->process()->process().pid()); } v8::Handle<v8::Value> TabNode::Break(const v8::Arguments& args, TabContents* tab) { tab->render_view_host()->DebugBreak((args.Length() >= 1) ? args[0]->BooleanValue() : false); return v8::Undefined(); } v8::Handle<v8::Value> TabNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { TabContents* tab = GetTab(); if (tab != NULL) { if (prop->Equals(v8::String::New("title"))) return v8::String::New(UTF16ToUTF8(tab->GetTitle()).c_str()); if (prop->Equals(v8::String::New("attach"))) { return (new FunctionNode<TabContents>(TabNode::Attach, tab))->NewInstance(); } if (prop->Equals(v8::String::New("detach"))) { return (new FunctionNode<TabContents>(TabNode::Detach, tab))->NewInstance(); } if (prop->Equals(v8::String::New("sendToDebugger"))) { return (new FunctionNode<TabContents>(TabNode::SendToDebugger, tab))->NewInstance(); } if (prop->Equals(v8::String::New("debugBreak"))) { return (new FunctionNode<TabContents>(TabNode::Break, tab))->NewInstance(); } } return v8::Undefined(); } ////////////////////////////////// template<class T> v8::Handle<v8::Value> FunctionNode<T>::Function(const v8::Arguments &args) { return function_(args, data_); }
// Copyright (c) 2006-2008 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 "chrome/browser/debugger/debugger_node.h" #include "base/process_util.h" #include "base/string_util.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_list.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/renderer_host/render_process_host.h" #include "chrome/browser/renderer_host/render_view_host.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/browser/debugger/debugger_shell.h" #include "chrome/common/notification_service.h" DebuggerNode::DebuggerNode() : data_(NULL), valid_(true) { } void DebuggerNode::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { registrar_.RemoveAll(); data_ = NULL; Invalidate(); } DebuggerNode::~DebuggerNode() { } v8::Handle<v8::Value> DebuggerNode::IndexGetter(uint32_t index, const v8::AccessorInfo& info) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::Function(const v8::Arguments& args) { return v8::Undefined(); } v8::Handle<v8::Value> DebuggerNode::NewInstance() { DebuggerNodeWrapper *wrap = new DebuggerNodeWrapper(this); wrap->AddRef(); v8::Local<v8::External> node = v8::External::New(wrap); // TODO(erikkay): cache these templates? v8::Local<v8::FunctionTemplate> templ = v8::FunctionTemplate::New(); if (IsFunction()) { templ->SetCallHandler(&DebuggerNode::NodeFunc, node); v8::Local<v8::Function> f = templ->GetFunction(); return f; } v8::Local<v8::ObjectTemplate> instance = templ->InstanceTemplate(); if (IsObject()) { instance->SetNamedPropertyHandler(&DebuggerNode::NodeGetter, 0, 0, 0, 0, node); // TODO(erikkay): verify that the interceptor does not have to be // behind the object } if (IsCollection()) { instance->SetIndexedPropertyHandler(&DebuggerNode::NodeIndex, 0, 0, 0, 0, node); } v8::Local<v8::Object> ret = instance->NewInstance(); v8::Persistent<v8::Object> p = v8::Persistent<v8::Object>::New(ret); p.MakeWeak(wrap, &DebuggerShell::HandleWeakReference); return ret; } v8::Handle<v8::Value> DebuggerNode::NodeGetter(v8::Local<v8::String> prop, const v8::AccessorInfo& info) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *info.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsObject()) ? n->PropGetter(prop, info) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } v8::Handle<v8::Value> DebuggerNode::NodeIndex(uint32_t index, const v8::AccessorInfo& info) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *info.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsCollection()) ? n->IndexGetter(index, info) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } v8::Handle<v8::Value> DebuggerNode::NodeFunc(const v8::Arguments& args) { DebuggerNodeWrapper* w = static_cast<DebuggerNodeWrapper*>(v8::External::Cast( *args.Data())->Value()); DebuggerNode* n = w->node(); return (n->IsValid() && n->IsFunction()) ? n->Function(args) : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } ///////////////////////////////////////////// ChromeNode::ChromeNode(DebuggerShell* debugger) { debugger_ = debugger; } ChromeNode::~ChromeNode() { } v8::Handle<v8::Value> ChromeNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { if (prop->Equals(v8::String::New("pid"))) return v8::Number::New(base::GetCurrentProcId()); if (prop->Equals(v8::String::New("browser"))) return BrowserListNode::BrowserList()->NewInstance(); if (prop->Equals(v8::String::New("setDebuggerReady"))) { return (new FunctionNode<DebuggerShell>(DebuggerShell::SetDebuggerReady, debugger_))->NewInstance(); } if (prop->Equals(v8::String::New("setDebuggerBreak"))) { return (new FunctionNode<DebuggerShell>(DebuggerShell::SetDebuggerBreak, debugger_))->NewInstance(); } return static_cast<v8::Handle<v8::Value> >( prop->Equals(v8::String::New("foo")) ? v8::Undefined() : prop); } ///////////////////////////////////////////// BrowserNode::BrowserNode(Browser *b) { data_ = b; registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(b)); } BrowserNode* BrowserNode::BrowserAtIndex(int index) { if (index >= 0) { BrowserList::const_iterator iter = BrowserList::begin(); for (; (iter != BrowserList::end()) && (index > 0); ++iter, --index) ; if (iter != BrowserList::end()) return new BrowserNode(*iter); } return NULL; } BrowserNode::~BrowserNode() { } Browser* BrowserNode::GetBrowser() { return IsValid() ? static_cast<Browser*>(data_) : NULL; } v8::Handle<v8::Value> BrowserNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { Browser* b = GetBrowser(); if (b != NULL) { if (prop->Equals(v8::String::New("title"))) { return v8::String::New(UTF16ToUTF8( b->GetSelectedTabContents()->GetTitle()).c_str()); } if (prop->Equals(v8::String::New("tab"))) return TabListNode::TabList(b)->NewInstance(); } return v8::Undefined(); } ///////////////////////////////////////////// BrowserListNode* BrowserListNode::BrowserList() { // TODO(erikkay): cache return new BrowserListNode(); } BrowserListNode::BrowserListNode() { } BrowserListNode::~BrowserListNode() { } v8::Handle<v8::Value> BrowserListNode::IndexGetter( uint32_t index, const v8::AccessorInfo& info) { BrowserNode* b = BrowserNode::BrowserAtIndex(index); return b ? b->NewInstance() : static_cast<v8::Handle<v8::Value> >(v8::Undefined()); } ///////////////////////////////////////////// TabListNode::TabListNode(Browser* b) { data_ = b; registrar_.Add(this, NotificationType::BROWSER_CLOSED, Source<Browser>(b)); } TabListNode::~TabListNode() { } TabListNode* TabListNode::TabList(Browser* b) { return new TabListNode(b); } Browser* TabListNode::GetBrowser() { return IsValid() ? static_cast<Browser*>(data_) : NULL; } v8::Handle<v8::Value> TabListNode::IndexGetter(uint32_t index, const v8::AccessorInfo& info) { Browser* b = GetBrowser(); if (b != NULL) { TabContents* tab_contents = b->GetTabContentsAt(index); if (tab_contents) return (new TabNode(tab_contents))->NewInstance(); } return v8::Undefined(); } ///////////////////////////////////////////// TabNode::TabNode(TabContents* c) { NavigationController* controller = &c->controller(); data_ = controller; registrar_.Add(this, NotificationType::TAB_CLOSING, Source<NavigationController>(controller)); } TabNode::~TabNode() { } TabContents* TabNode::GetTab() { return IsValid() ? static_cast<NavigationController*>(data_)->tab_contents() : NULL; } v8::Handle<v8::Value> TabNode::SendToDebugger(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); if (args.Length() == 1) { std::wstring cmd; v8::Handle<v8::Value> obj = args[0]; DebuggerShell::ObjectToString(obj, &cmd); host->DebugCommand(cmd); } return v8::Undefined(); } v8::Handle<v8::Value> TabNode::Attach(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); host->DebugAttach(); return v8::Int32::New(host->process()->process().pid()); } v8::Handle<v8::Value> TabNode::Detach(const v8::Arguments& args, TabContents* tab) { RenderViewHost* host = tab->render_view_host(); host->DebugDetach(); return v8::Int32::New(host->process()->process().pid()); } v8::Handle<v8::Value> TabNode::Break(const v8::Arguments& args, TabContents* tab) { tab->render_view_host()->DebugBreak((args.Length() >= 1) ? args[0]->BooleanValue() : false); return v8::Undefined(); } v8::Handle<v8::Value> TabNode::PropGetter(v8::Handle<v8::String> prop, const v8::AccessorInfo& info) { TabContents* tab = GetTab(); if (tab != NULL) { if (prop->Equals(v8::String::New("title"))) return v8::String::New(UTF16ToUTF8(tab->GetTitle()).c_str()); if (prop->Equals(v8::String::New("attach"))) { return (new FunctionNode<TabContents>(TabNode::Attach, tab))->NewInstance(); } if (prop->Equals(v8::String::New("detach"))) { return (new FunctionNode<TabContents>(TabNode::Detach, tab))->NewInstance(); } if (prop->Equals(v8::String::New("sendToDebugger"))) { return (new FunctionNode<TabContents>(TabNode::SendToDebugger, tab))->NewInstance(); } if (prop->Equals(v8::String::New("debugBreak"))) { return (new FunctionNode<TabContents>(TabNode::Break, tab))->NewInstance(); } } return v8::Undefined(); } ////////////////////////////////// template<class T> v8::Handle<v8::Value> FunctionNode<T>::Function(const v8::Arguments &args) { return function_(args, data_); }
Fix Linux build
Fix Linux build git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@16654 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,yitian134/chromium
e2fbaeb2784c1b9cf19c335d46abdc1e1be2f17f
mcppalloc_bitmap/mcppalloc_bitmap/include/mcppalloc/mcppalloc_bitmap/integer_block_impl.hpp
mcppalloc_bitmap/mcppalloc_bitmap/include/mcppalloc/mcppalloc_bitmap/integer_block_impl.hpp
#pragma once #include "integer_block.hpp" #include <limits> #include <mcpputil/mcpputil/intrinsics.hpp> #include <mcpputil/mcpputil/unsafe_cast.hpp> #include <numeric> namespace mcppalloc::bitmap::details { template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::clear() noexcept { ::std::fill(m_array.begin(), m_array.end(), 0); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::fill(uint64_t word) noexcept { ::std::fill(m_array.begin(), m_array.end(), word); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::set_bit(size_t i, bool value) noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); m_array[pos] = (m_array[pos] & (~(1ll << sub_pos))) | (static_cast<size_t>(value) << sub_pos); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::set_bit_atomic(size_t i, bool value, ::std::memory_order ordering) noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); auto &bits = mcpputil::unsafe_reference_cast<::std::atomic<uint64_t>>(m_array[pos]); bool success = false; while (!success) { auto cur = bits.load(::std::memory_order_relaxed); auto new_val = (cur & (~(1ll << sub_pos))) | (static_cast<uint64_t>(value) << sub_pos); success = bits.compare_exchange_weak(cur, new_val, ordering); } } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::get_bit(size_t i) const noexcept -> bool { auto pos = i / 64; auto sub_pos = i - (pos * 64); return (m_array[pos] & (1ll << sub_pos)) > sub_pos; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE bool integer_block_t<Quads>::get_bit_atomic(size_t i, ::std::memory_order ordering) const noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); auto &bits = mcpputil::unsafe_reference_cast<::std::atomic<uint64_t>>(m_array[pos]); return (bits.load(ordering) & (1ll << sub_pos)) > sub_pos; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::all_set() const noexcept -> bool { for (auto &&val : m_array) { if (val != ::std::numeric_limits<value_type>::max()) { return false; } } return true; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::any_set() const noexcept -> bool { for (auto &&it : m_array) { if (it) { return true; } } return false; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::none_set() const noexcept -> bool { for (auto &&it : m_array) { if (it) { return false; } } return true; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::first_set() const noexcept -> size_t { #if defined(__AVX__) && !defined(__APPLE__) __m256i m = *unsafe_cast<__m256i>(&m_array[0]); static_assert(size() >= 8, ""); __m256i m2 = *unsafe_cast<__m256i>(&m_array[4]); if (!_mm256_testz_si256(m, m)) { for (size_t i = 0; i < 4; ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } else if (!_mm256_testz_si256(m2, m2)) { for (size_t i = 4; i < 8; ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } else { for (size_t i = 8; i < m_array.size(); ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } #else for (size_t i = 0; i < m_array.size(); ++i) { const uint64_t &it = m_array[i]; auto first = mcpputil::ffs(it); if (first != 0) { return (64 * i) + (first - 1); } } #endif return ::std::numeric_limits<size_t>::max(); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::first_not_set() const noexcept -> size_t { return (~*this).first_set(); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::popcount() const noexcept -> size_t { return ::std::accumulate(m_array.begin(), m_array.end(), static_cast<size_t>(0), [](size_t b, auto x) { return static_cast<size_t>(mcpputil::popcount(x)) + b; }); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator~() const noexcept -> integer_block_t { integer_block_t ret = *this; for (auto &&i : ret.m_array) { i = ~i; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::negate() noexcept -> integer_block_t & { for (auto &&i : m_array) { i = ~i; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator|(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] | b.m_array[i]; } } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator|=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] |= b.m_array[i]; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator&(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] & b.m_array[i]; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator&=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] &= b.m_array[i]; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator^(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] ^ b.m_array[i]; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator^=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] ^= b.m_array[i]; } return *this; } template <size_t Quads> template <typename Func> void integer_block_t<Quads>::for_set_bits(size_t offset, size_t limit, Func &&func) { limit = ::std::min(limit, size_in_bits()); for (size_t i = 0; i < limit; ++i) { if (i % 64 == 0 && m_array[i / 64] == 0) { continue; } if (get_bit(i)) { func(offset + i); } } } template <size_t Quads> template <typename Func> void integer_block_t<Quads>::for_some_contiguous_bits_flip(size_t offset, Func &&func) { #if defined(__AVX2__) && !defined(__APPLE__) const __m256i ones = _mm256_set1_epi64x(-1); for (size_t i = 0; i + 3 < size(); i += 4) { __m256i m = *unsafe_cast<__m256i>(&m_array[i]); m = _mm256_andnot_si256(m, ones); if (_mm256_testz_si256(m, m)) { func(offset + i * 64, offset + ((i + 4) * 64)); } } #elif defined(__SSE4__) for (size_t i = 0; i + 1 < size(); i += 2) { __m128i *m = unsafe_cast<__m128i>(&m_array[i]); if (_mm_test_all_ones(*m)) { func(offset + i * 64, offset + ((i + 2) * 64)); } } #else for (size_t i = 0; i + 1 < size(); i += 2) { if (m_array[i] == ::std::numeric_limits<uint64_t>::max()) { func(offset + i * 64, offset + ((i + 1) * 64)); } } #endif } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size() noexcept { return cs_quad_words; } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size_in_bytes() noexcept { return sizeof(m_array); } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size_in_bits() noexcept { return size_in_bytes() * 8; } }
#pragma once #include "integer_block.hpp" #include <limits> #include <mcpputil/mcpputil/intrinsics.hpp> #include <mcpputil/mcpputil/unsafe_cast.hpp> #include <numeric> #include <immintrin.h> namespace mcppalloc::bitmap::details { template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::clear() noexcept { ::std::fill(m_array.begin(), m_array.end(), 0); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::fill(uint64_t word) noexcept { ::std::fill(m_array.begin(), m_array.end(), word); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::set_bit(size_t i, bool value) noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); m_array[pos] = (m_array[pos] & (~(1ll << sub_pos))) | (static_cast<size_t>(value) << sub_pos); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE void integer_block_t<Quads>::set_bit_atomic(size_t i, bool value, ::std::memory_order ordering) noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); auto &bits = mcpputil::unsafe_reference_cast<::std::atomic<uint64_t>>(m_array[pos]); bool success = false; while (!success) { auto cur = bits.load(::std::memory_order_relaxed); auto new_val = (cur & (~(1ll << sub_pos))) | (static_cast<uint64_t>(value) << sub_pos); success = bits.compare_exchange_weak(cur, new_val, ordering); } } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::get_bit(size_t i) const noexcept -> bool { auto pos = i / 64; auto sub_pos = i - (pos * 64); return (m_array[pos] & (1ll << sub_pos)) > sub_pos; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE bool integer_block_t<Quads>::get_bit_atomic(size_t i, ::std::memory_order ordering) const noexcept { auto pos = i / 64; auto sub_pos = i - (pos * 64); auto &bits = mcpputil::unsafe_reference_cast<::std::atomic<uint64_t>>(m_array[pos]); return (bits.load(ordering) & (1ll << sub_pos)) > sub_pos; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::all_set() const noexcept -> bool { for (auto &&val : m_array) { if (val != ::std::numeric_limits<value_type>::max()) { return false; } } return true; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::any_set() const noexcept -> bool { for (auto &&it : m_array) { if (it) { return true; } } return false; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::none_set() const noexcept -> bool { for (auto &&it : m_array) { if (it) { return false; } } return true; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::first_set() const noexcept -> size_t { #if defined(__AVX__) && !defined(__APPLE__) __m256i m = *mcpputil::unsafe_cast<__m256i>(&m_array[0]); static_assert(size() >= 8, ""); __m256i m2 = *mcpputil::unsafe_cast<__m256i>(&m_array[4]); if (!_mm256_testz_si256(m, m)) { for (size_t i = 0; i < 4; ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } else if (!_mm256_testz_si256(m2, m2)) { for (size_t i = 4; i < 8; ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } else { for (size_t i = 8; i < m_array.size(); ++i) { const uint64_t &it = m_array[i]; auto first = static_cast<size_t>(__builtin_ffsll(static_cast<long long>(it))); if (first) return (64 * i) + (first - 1); } } #else for (size_t i = 0; i < m_array.size(); ++i) { const uint64_t &it = m_array[i]; auto first = mcpputil::ffs(it); if (first != 0) { return (64 * i) + (first - 1); } } #endif return ::std::numeric_limits<size_t>::max(); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::first_not_set() const noexcept -> size_t { return (~*this).first_set(); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::popcount() const noexcept -> size_t { return ::std::accumulate(m_array.begin(), m_array.end(), static_cast<size_t>(0), [](size_t b, auto x) { return static_cast<size_t>(mcpputil::popcount(x)) + b; }); } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator~() const noexcept -> integer_block_t { integer_block_t ret = *this; for (auto &&i : ret.m_array) { i = ~i; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::negate() noexcept -> integer_block_t & { for (auto &&i : m_array) { i = ~i; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator|(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] | b.m_array[i]; } } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator|=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] |= b.m_array[i]; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator&(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] & b.m_array[i]; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator&=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] &= b.m_array[i]; } return *this; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator^(const integer_block_t &b) const noexcept -> integer_block_t { integer_block_t ret; for (size_t i = 0; i < m_array.size(); ++i) { ret.m_array[i] = m_array[i] ^ b.m_array[i]; } return ret; } template <size_t Quads> MCPPALLOC_ALWAYS_INLINE auto integer_block_t<Quads>::operator^=(const integer_block_t &b) noexcept -> integer_block_t & { for (size_t i = 0; i < m_array.size(); ++i) { m_array[i] ^= b.m_array[i]; } return *this; } template <size_t Quads> template <typename Func> void integer_block_t<Quads>::for_set_bits(size_t offset, size_t limit, Func &&func) { limit = ::std::min(limit, size_in_bits()); for (size_t i = 0; i < limit; ++i) { if (i % 64 == 0 && m_array[i / 64] == 0) { continue; } if (get_bit(i)) { func(offset + i); } } } template <size_t Quads> template <typename Func> void integer_block_t<Quads>::for_some_contiguous_bits_flip(size_t offset, Func &&func) { #if defined(__AVX2__) && !defined(__APPLE__) const __m256i ones = _mm256_set1_epi64x(-1); for (size_t i = 0; i + 3 < size(); i += 4) { __m256i m = *unsafe_cast<__m256i>(&m_array[i]); m = _mm256_andnot_si256(m, ones); if (_mm256_testz_si256(m, m)) { func(offset + i * 64, offset + ((i + 4) * 64)); } } #elif defined(__SSE4__) for (size_t i = 0; i + 1 < size(); i += 2) { __m128i *m = unsafe_cast<__m128i>(&m_array[i]); if (_mm_test_all_ones(*m)) { func(offset + i * 64, offset + ((i + 2) * 64)); } } #else for (size_t i = 0; i + 1 < size(); i += 2) { if (m_array[i] == ::std::numeric_limits<uint64_t>::max()) { func(offset + i * 64, offset + ((i + 1) * 64)); } } #endif } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size() noexcept { return cs_quad_words; } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size_in_bytes() noexcept { return sizeof(m_array); } template <size_t Quads> constexpr size_t integer_block_t<Quads>::size_in_bits() noexcept { return size_in_bytes() * 8; } }
Fix AVX
Fix AVX
C++
mit
garyfurnish/mcppalloc
c443af66651ada4f9221c6f7d479b23880ff9651
src/profiling/memory/socket_listener.cc
src/profiling/memory/socket_listener.cc
/* * Copyright (C) 2018 The Android Open Source Project * * 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 "src/profiling/memory/socket_listener.h" #include "perfetto/base/utils.h" namespace perfetto { namespace profiling { void SocketListener::OnDisconnect(base::UnixSocket* self) { bookkeeping_thread_->NotifyClientDisconnected(self->peer_pid()); auto it = process_info_.find(self->peer_pid()); if (it != process_info_.end()) { ProcessInfo& process_info = it->second; process_info.sockets.erase(self); } else { PERFETTO_DFATAL("Disconnect from socket without ProcessInfo."); } sockets_.erase(self); } void SocketListener::OnNewIncomingConnection( base::UnixSocket*, std::unique_ptr<base::UnixSocket> new_connection) { base::UnixSocket* new_connection_raw = new_connection.get(); pid_t pid = new_connection_raw->peer_pid(); auto it = process_info_.find(pid); if (it == process_info_.end()) { PERFETTO_DFATAL("Unexpected connection."); return; } ProcessInfo& process_info = it->second; sockets_.emplace(new_connection_raw, std::move(new_connection)); process_info.sockets.emplace(new_connection_raw); // TODO(fmayer): Move destruction of bookkeeping data to // HeapprofdProducer. bookkeeping_thread_->NotifyClientConnected(pid); } void SocketListener::OnDataAvailable(base::UnixSocket* self) { auto socket_it = sockets_.find(self); if (socket_it == sockets_.end()) return; pid_t peer_pid = self->peer_pid(); Entry& entry = socket_it->second; RecordReader::ReceiveBuffer buf = entry.record_reader.BeginReceive(); auto process_info_it = process_info_.find(peer_pid); if (process_info_it == process_info_.end()) { PERFETTO_DFATAL("This should not happen."); return; } ProcessInfo& process_info = process_info_it->second; size_t rd; if (PERFETTO_LIKELY(entry.recv_fds)) { rd = self->Receive(buf.data, buf.size); } else { auto it = unwinding_metadata_.find(peer_pid); if (it != unwinding_metadata_.end() && !it->second.expired()) { entry.recv_fds = true; // If the process already has metadata, this is an additional socket for // an existing process. Reuse existing metadata and close the received // file descriptors. entry.unwinding_metadata = std::shared_ptr<UnwindingMetadata>(it->second); rd = self->Receive(buf.data, buf.size); } else { base::ScopedFile fds[2]; rd = self->Receive(buf.data, buf.size, fds, base::ArraySize(fds)); if (fds[0] && fds[1]) { PERFETTO_DLOG("%d: Received FDs.", peer_pid); entry.recv_fds = true; entry.unwinding_metadata = std::make_shared<UnwindingMetadata>( peer_pid, std::move(fds[0]), std::move(fds[1])); unwinding_metadata_[peer_pid] = entry.unwinding_metadata; self->Send(&process_info.client_config, sizeof(process_info.client_config), -1, base::UnixSocket::BlockingMode::kBlocking); } else if (fds[0] || fds[1]) { PERFETTO_DLOG("%d: Received partial FDs.", peer_pid); } else { PERFETTO_DLOG("%d: Received no FDs.", peer_pid); } } } RecordReader::Record record; auto status = entry.record_reader.EndReceive(rd, &record); switch (status) { case (RecordReader::Result::Noop): break; case (RecordReader::Result::RecordReceived): RecordReceived(self, static_cast<size_t>(record.size), std::move(record.data)); break; case (RecordReader::Result::KillConnection): self->Shutdown(true); break; } } SocketListener::ProfilingSession SocketListener::ExpectPID( pid_t pid, ClientConfiguration cfg) { PERFETTO_DLOG("Expecting connection from %d", pid); bool inserted; std::tie(std::ignore, inserted) = process_info_.emplace(pid, std::move(cfg)); if (!inserted) return ProfilingSession(0, nullptr); return ProfilingSession(pid, this); } void SocketListener::ShutdownPID(pid_t pid) { PERFETTO_DLOG("Shutting down connecting from %d", pid); auto it = process_info_.find(pid); if (it == process_info_.end()) { PERFETTO_DFATAL("Shutting down nonexistant pid."); return; } ProcessInfo& process_info = it->second; // Disconnect all sockets for process. for (base::UnixSocket* socket : process_info.sockets) socket->Shutdown(true); } void SocketListener::RecordReceived(base::UnixSocket* self, size_t size, std::unique_ptr<uint8_t[]> buf) { auto it = sockets_.find(self); if (it == sockets_.end()) { // This happens for zero-length records, because the callback gets called // in the first call to Read. Because zero length records are useless, // this is not a problem. return; } Entry& entry = it->second; if (!entry.unwinding_metadata) { PERFETTO_DLOG("Received record without process metadata."); return; } if (size == 0) { PERFETTO_DLOG("Dropping empty record."); return; } // This needs to be a weak_ptr for two reasons: // 1) most importantly, the weak_ptr in unwinding_metadata_ should expire as // soon as the last socket for a process goes away. Otherwise, a recycled // PID might reuse incorrect metadata. // 2) it is a waste to unwind for a process that had already gone away. std::weak_ptr<UnwindingMetadata> weak_metadata(entry.unwinding_metadata); callback_function_({entry.unwinding_metadata->pid, size, std::move(buf), std::move(weak_metadata)}); } } // namespace profiling } // namespace perfetto
/* * Copyright (C) 2018 The Android Open Source Project * * 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 "src/profiling/memory/socket_listener.h" #include "perfetto/base/utils.h" namespace perfetto { namespace profiling { void SocketListener::OnDisconnect(base::UnixSocket* self) { bookkeeping_thread_->NotifyClientDisconnected(self->peer_pid()); auto it = process_info_.find(self->peer_pid()); if (it != process_info_.end()) { ProcessInfo& process_info = it->second; process_info.sockets.erase(self); if (process_info.sockets.empty()) process_info_.erase(it); } else { PERFETTO_DFATAL("Disconnect from socket without ProcessInfo."); } sockets_.erase(self); } void SocketListener::OnNewIncomingConnection( base::UnixSocket*, std::unique_ptr<base::UnixSocket> new_connection) { base::UnixSocket* new_connection_raw = new_connection.get(); pid_t pid = new_connection_raw->peer_pid(); auto it = process_info_.find(pid); if (it == process_info_.end()) { PERFETTO_DFATAL("Unexpected connection."); return; } ProcessInfo& process_info = it->second; sockets_.emplace(new_connection_raw, std::move(new_connection)); process_info.sockets.emplace(new_connection_raw); // TODO(fmayer): Move destruction of bookkeeping data to // HeapprofdProducer. bookkeeping_thread_->NotifyClientConnected(pid); } void SocketListener::OnDataAvailable(base::UnixSocket* self) { auto socket_it = sockets_.find(self); if (socket_it == sockets_.end()) return; pid_t peer_pid = self->peer_pid(); Entry& entry = socket_it->second; RecordReader::ReceiveBuffer buf = entry.record_reader.BeginReceive(); auto process_info_it = process_info_.find(peer_pid); if (process_info_it == process_info_.end()) { PERFETTO_DFATAL("This should not happen."); return; } ProcessInfo& process_info = process_info_it->second; size_t rd; if (PERFETTO_LIKELY(entry.recv_fds)) { rd = self->Receive(buf.data, buf.size); } else { auto it = unwinding_metadata_.find(peer_pid); if (it != unwinding_metadata_.end() && !it->second.expired()) { entry.recv_fds = true; // If the process already has metadata, this is an additional socket for // an existing process. Reuse existing metadata and close the received // file descriptors. entry.unwinding_metadata = std::shared_ptr<UnwindingMetadata>(it->second); rd = self->Receive(buf.data, buf.size); } else { base::ScopedFile fds[2]; rd = self->Receive(buf.data, buf.size, fds, base::ArraySize(fds)); if (fds[0] && fds[1]) { PERFETTO_DLOG("%d: Received FDs.", peer_pid); entry.recv_fds = true; entry.unwinding_metadata = std::make_shared<UnwindingMetadata>( peer_pid, std::move(fds[0]), std::move(fds[1])); unwinding_metadata_[peer_pid] = entry.unwinding_metadata; self->Send(&process_info.client_config, sizeof(process_info.client_config), -1, base::UnixSocket::BlockingMode::kBlocking); } else if (fds[0] || fds[1]) { PERFETTO_DLOG("%d: Received partial FDs.", peer_pid); } else { PERFETTO_DLOG("%d: Received no FDs.", peer_pid); } } } RecordReader::Record record; auto status = entry.record_reader.EndReceive(rd, &record); switch (status) { case (RecordReader::Result::Noop): break; case (RecordReader::Result::RecordReceived): RecordReceived(self, static_cast<size_t>(record.size), std::move(record.data)); break; case (RecordReader::Result::KillConnection): self->Shutdown(true); break; } } SocketListener::ProfilingSession SocketListener::ExpectPID( pid_t pid, ClientConfiguration cfg) { PERFETTO_DLOG("Expecting connection from %d", pid); bool inserted; std::tie(std::ignore, inserted) = process_info_.emplace(pid, std::move(cfg)); if (!inserted) return ProfilingSession(0, nullptr); return ProfilingSession(pid, this); } void SocketListener::ShutdownPID(pid_t pid) { PERFETTO_DLOG("Shutting down connecting from %d", pid); auto it = process_info_.find(pid); if (it == process_info_.end()) { PERFETTO_DFATAL("Shutting down nonexistant pid."); return; } ProcessInfo& process_info = it->second; // Disconnect all sockets for process. for (base::UnixSocket* socket : process_info.sockets) socket->Shutdown(true); } void SocketListener::RecordReceived(base::UnixSocket* self, size_t size, std::unique_ptr<uint8_t[]> buf) { auto it = sockets_.find(self); if (it == sockets_.end()) { // This happens for zero-length records, because the callback gets called // in the first call to Read. Because zero length records are useless, // this is not a problem. return; } Entry& entry = it->second; if (!entry.unwinding_metadata) { PERFETTO_DLOG("Received record without process metadata."); return; } if (size == 0) { PERFETTO_DLOG("Dropping empty record."); return; } // This needs to be a weak_ptr for two reasons: // 1) most importantly, the weak_ptr in unwinding_metadata_ should expire as // soon as the last socket for a process goes away. Otherwise, a recycled // PID might reuse incorrect metadata. // 2) it is a waste to unwind for a process that had already gone away. std::weak_ptr<UnwindingMetadata> weak_metadata(entry.unwinding_metadata); callback_function_({entry.unwinding_metadata->pid, size, std::move(buf), std::move(weak_metadata)}); } } // namespace profiling } // namespace perfetto
Fix cleanup of profiling state.
profiling: Fix cleanup of profiling state. This allows to profile the same process after it has finished profiling. A resource was left behind that made it appear like the process was still being profiled. Change-Id: I73e402dff7b9d91e82433ac1aa1a590e00a3f78d
C++
apache-2.0
google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto,google/perfetto
e3a4d3dbf00b0f82fed13dbd7cb15157d4af81c5
questions/layout-iterator-adapter-31546511/main.cpp
questions/layout-iterator-adapter-31546511/main.cpp
#include <QLayout> #include <QDebug> #include <QPointer> #include <utility> template<class WT> class IterableLayoutAdapter; template<typename WT> class LayoutIterator { QPointer<QLayout> m_layout; int m_index; friend class IterableLayoutAdapter<WT>; LayoutIterator(QLayout * layout, int dir) : m_layout(layout), m_index(dir>0 ? -1 : m_layout->count()) { if (dir > 0) ++*this; } friend QDebug operator<<(QDebug dbg, const LayoutIterator & it) { return dbg << it.m_layout << it.m_index; } friend void swap(LayoutIterator& a, LayoutIterator& b) { std::swap(a.m_layout, b.m_layout); std::swap(a.m_index, b.m_index); } public: LayoutIterator() : m_index(0) {} LayoutIterator(const LayoutIterator & o) : m_layout(o.m_layout), m_index(o.m_index) {} LayoutIterator(LayoutIterator && o) { swap(*this, o); } LayoutIterator & operator=(LayoutIterator o) { swap(*this, o); return *this; } WT * operator*() const { return static_cast<WT*>(m_layout->itemAt(m_index)->widget()); } const LayoutIterator & operator++() { while (++m_index < m_layout->count() && !qobject_cast<WT*>(m_layout->itemAt(m_index)->widget())); return *this; } LayoutIterator operator++(int) { LayoutIterator temp(*this); ++*this; return temp; } const LayoutIterator & operator--() { while (!qobject_cast<WT*>(m_layout->itemAt(--m_index)->widget()) && m_index > 0); return *this; } LayoutIterator operator--(int) { LayoutIterator temp(*this); --*this; return temp; } bool operator==(const LayoutIterator & o) const { return m_index == o.m_index; } bool operator!=(const LayoutIterator & o) const { return m_index != o.m_index; } }; template <class WT = QWidget> class IterableLayoutAdapter { QPointer<QLayout> m_layout; public: typedef LayoutIterator<WT> const_iterator; IterableLayoutAdapter(QLayout * layout) : m_layout(layout) {} const_iterator begin() const { return const_iterator(m_layout, 1); } const_iterator end() const { return const_iterator(m_layout, -1); } }; #include <QApplication> #include <QLabel> #include <QHBoxLayout> void tests() { QWidget a, b1, b3; QLabel b2; QHBoxLayout l(&a); IterableLayoutAdapter<> l0(&l); auto i0 = l0.begin(); qDebug() << i0; Q_ASSERT(i0 == l0.begin() && i0 == l0.end()); l.addWidget(&b1); l.addWidget(&b2); l.addWidget(&b3); IterableLayoutAdapter<> l1(&l); auto i1 = l1.begin(); qDebug() << i1; Q_ASSERT(i1 == l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 == l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 == l1.begin() && i1 != l1.end()); IterableLayoutAdapter<QLabel> l2(&l); auto i2 = l2.begin(); qDebug() << i2; Q_ASSERT(i2 == l2.begin() && i2 != l2.end()); ++i2; qDebug() << i2; Q_ASSERT(i2 != l2.begin() && i2 == l2.end()); --i2; qDebug() << i2; Q_ASSERT(i2 == l2.begin() && i2 != l2.end()); } int main(int argc, char ** argv) { QApplication app(argc, argv); tests(); QWidget a, b1, b3; QLabel b2; QHBoxLayout l(&a); l.addWidget(&b1); l.addWidget(&b2); l.addWidget(&b3); // Iterate all widget types qDebug() << "all, range-for"; for (auto widget : IterableLayoutAdapter<>(&l)) qDebug() << widget; qDebug() << "all, Q_FOREACH"; Q_FOREACH (QWidget * widget, IterableLayoutAdapter<>(&l)) qDebug() << widget; // Iterate labels only qDebug() << "labels, range-for"; for (auto label : IterableLayoutAdapter<QLabel>(&l)) qDebug() << label; qDebug() << "labels, Q_FOREACH"; Q_FOREACH (QLabel * label, IterableLayoutAdapter<QLabel>(&l)) qDebug() << label; }
// https://github.com/KubaO/stackoverflown/tree/master/questions/layout-iterator-adapter-31546511 #include <QLayout> #include <QDebug> #include <QPointer> #include <utility> template<class> class IterableLayoutAdapter; template<typename WT> class LayoutIterator { QPointer<QLayout> m_layout; int m_index; friend class IterableLayoutAdapter<WT>; LayoutIterator(QLayout * layout, int dir) : m_layout(layout), m_index(dir>0 ? -1 : m_layout->count()) { if (dir > 0) ++*this; } friend QDebug operator<<(QDebug dbg, const LayoutIterator & it) { return dbg << it.m_layout << it.m_index; } friend void swap(LayoutIterator& a, LayoutIterator& b) { std::swap(a.m_layout, b.m_layout); std::swap(a.m_index, b.m_index); } public: LayoutIterator() : m_index(0) {} LayoutIterator(const LayoutIterator & o) : m_layout(o.m_layout), m_index(o.m_index) {} LayoutIterator(LayoutIterator && o) { swap(*this, o); } LayoutIterator & operator=(LayoutIterator o) { swap(*this, o); return *this; } WT * operator*() const { return static_cast<WT*>(m_layout->itemAt(m_index)->widget()); } const LayoutIterator & operator++() { while (++m_index < m_layout->count() && !qobject_cast<WT*>(m_layout->itemAt(m_index)->widget())); return *this; } LayoutIterator operator++(int) { LayoutIterator temp(*this); ++*this; return temp; } const LayoutIterator & operator--() { while (!qobject_cast<WT*>(m_layout->itemAt(--m_index)->widget()) && m_index > 0); return *this; } LayoutIterator operator--(int) { LayoutIterator temp(*this); --*this; return temp; } bool operator==(const LayoutIterator & o) const { return m_index == o.m_index; } bool operator!=(const LayoutIterator & o) const { return m_index != o.m_index; } }; template <class WT = QWidget> class IterableLayoutAdapter { QPointer<QLayout> m_layout; public: typedef LayoutIterator<WT> iterator; typedef iterator const_iterator; IterableLayoutAdapter(QLayout * layout) : m_layout(layout) {} const_iterator begin() const { return const_iterator(m_layout, 1); } const_iterator end() const { return const_iterator(m_layout, -1); } const_iterator cbegin() const { return const_iterator(m_layout, 1); } const_iterator cend() const { return const_iterator(m_layout, -1); } }; template <class WT = QWidget> class ConstIterableLayoutAdapter : public IterableLayoutAdapter<const WT> { public: ConstIterableLayoutAdapter(QLayout * layout) : IterableLayoutAdapter<const WT>(layout) {} }; #include <QApplication> #include <QLabel> #include <QHBoxLayout> void tests() { QWidget a, b1, b3; QLabel b2; QHBoxLayout l(&a); IterableLayoutAdapter<> l0(&l); auto i0 = l0.begin(); qDebug() << i0; Q_ASSERT(i0 == l0.begin() && i0 == l0.end()); l.addWidget(&b1); l.addWidget(&b2); l.addWidget(&b3); IterableLayoutAdapter<> l1(&l); auto i1 = l1.begin(); qDebug() << i1; Q_ASSERT(i1 == l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); ++i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 == l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 != l1.begin() && i1 != l1.end()); --i1; qDebug() << i1; Q_ASSERT(i1 == l1.begin() && i1 != l1.end()); IterableLayoutAdapter<QLabel> l2(&l); auto i2 = l2.begin(); qDebug() << i2; Q_ASSERT(i2 == l2.begin() && i2 != l2.end()); ++i2; qDebug() << i2; Q_ASSERT(i2 != l2.begin() && i2 == l2.end()); --i2; qDebug() << i2; Q_ASSERT(i2 == l2.begin() && i2 != l2.end()); } int main(int argc, char ** argv) { QApplication app(argc, argv); tests(); QWidget a, b1, b3; QLabel b2; QHBoxLayout l(&a); l.addWidget(&b1); l.addWidget(&b2); l.addWidget(&b3); // Iterate all widget types as constants qDebug() << "all, range-for"; for (auto widget : ConstIterableLayoutAdapter<>(&l)) qDebug() << widget; qDebug() << "all, Q_FOREACH"; Q_FOREACH (const QWidget * widget, ConstIterableLayoutAdapter<>(&l)) qDebug() << widget; // Iterate labels only qDebug() << "labels, range-for"; for (auto label : IterableLayoutAdapter<QLabel>(&l)) qDebug() << label; qDebug() << "labels, Q_FOREACH"; Q_FOREACH (QLabel * label, IterableLayoutAdapter<QLabel>(&l)) qDebug() << label; }
Support constant iteration.
Support constant iteration.
C++
unlicense
KubaO/stackoverflown,KubaO/stackoverflown,KubaO/stackoverflown
9055c70fd555eb2cfc4b8313688521ac89537d7a
src/providers/verbs/completionqueue.cpp
src/providers/verbs/completionqueue.cpp
// Copyright 2016 Peter Georg // // 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 "completionqueue.hpp" #include <stdexcept> #include "../../misc/string.hpp" #include "../../arch/processor.hpp" pMR::verbs::CompletionQueue::CompletionQueue(Context &context, int const size) { mCompletionQueue = ibv_create_cq(context.get(), size, NULL, NULL, 0); if(!mCompletionQueue) { throw std::runtime_error("pMR: Could not create Completion Queue."); } } pMR::verbs::CompletionQueue::~CompletionQueue() { ibv_destroy_cq(mCompletionQueue); } ibv_cq* pMR::verbs::CompletionQueue::get() { return mCompletionQueue; } ibv_cq const* pMR::verbs::CompletionQueue::get() const { return mCompletionQueue; } void pMR::verbs::CompletionQueue::poll() { ibv_wc workCompletion; int numCompletion; do { numCompletion = ibv_poll_cq(mCompletionQueue, 1, &workCompletion); CPURelax(); } while(numCompletion == 0); if(numCompletion < 0) { throw std::runtime_error("pMR: Failed to poll CQ."); } if(workCompletion.status != IBV_WC_SUCCESS) { throw std::runtime_error(toString("pMR: Completion Queue ID", workCompletion.wr_id, "failed with status", workCompletion.status)); } } bool pMR::verbs::CompletionQueue::poll(int retry) { ibv_wc workCompletion; int numCompletion; do { numCompletion = ibv_poll_cq(mCompletionQueue, 1, &workCompletion); CPURelax(); } while(numCompletion == 0 && --retry); if(numCompletion < 0) { throw std::runtime_error("pMR: Failed to poll CQ."); } if(workCompletion.status != IBV_WC_SUCCESS) { throw std::runtime_error(toString("pMR: Completion Queue ID", workCompletion.wr_id, "failed with status", workCompletion.status)); } if(numCompletion) { return true; } else { return false; } }
// Copyright 2016 Peter Georg // // 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 "completionqueue.hpp" #include <stdexcept> #include "../../misc/string.hpp" #include "../../arch/processor.hpp" pMR::verbs::CompletionQueue::CompletionQueue(Context &context, int const size) { mCompletionQueue = ibv_create_cq(context.get(), size, NULL, NULL, 0); if(!mCompletionQueue) { throw std::runtime_error("pMR: Could not create Completion Queue."); } } pMR::verbs::CompletionQueue::~CompletionQueue() { ibv_destroy_cq(mCompletionQueue); } ibv_cq* pMR::verbs::CompletionQueue::get() { return mCompletionQueue; } ibv_cq const* pMR::verbs::CompletionQueue::get() const { return mCompletionQueue; } void pMR::verbs::CompletionQueue::poll() { ibv_wc workCompletion; int numCompletion; do { numCompletion = ibv_poll_cq(mCompletionQueue, 1, &workCompletion); CPURelax(); } while(numCompletion == 0); if(numCompletion < 0) { throw std::runtime_error("pMR: Failed to poll CQ."); } if(workCompletion.status != IBV_WC_SUCCESS) { throw std::runtime_error(toString("pMR: Work Request ID", workCompletion.wr_id, "failed with status:", ibv_wc_status_str(workCompletion.status))); } } bool pMR::verbs::CompletionQueue::poll(int retry) { ibv_wc workCompletion; int numCompletion; do { numCompletion = ibv_poll_cq(mCompletionQueue, 1, &workCompletion); CPURelax(); } while(numCompletion == 0 && --retry); if(numCompletion < 0) { throw std::runtime_error("pMR: Failed to poll CQ."); } if(workCompletion.status != IBV_WC_SUCCESS) { throw std::runtime_error(toString("pMR: Work Request ID", workCompletion.wr_id, "failed with status:", ibv_wc_status_str(workCompletion.status))); } if(numCompletion) { return true; } else { return false; } }
Improve error message
Improve error message
C++
apache-2.0
pjgeorg/pMR,pjgeorg/pMR,pjgeorg/pMR
147a4508fba63fbec05cc8fde115088e94b8496c
common/network/network.cc
common/network/network.cc
#include <queue> #include "transport.h" #include "core.h" #include "network.h" #include "log.h" #define LOG_DEFAULT_RANK (_transport->ptCommID()) #define LOG_DEFAULT_MODULE NETWORK // -- NetQueue -- // // // A priority queue for network packets. struct NetQueueEntry { NetPacket packet; UInt64 time; }; class Earlier { public: bool operator() (const NetQueueEntry& first, const NetQueueEntry& second) const { return first.time > second.time; } }; class NetQueue : public priority_queue <NetQueueEntry, vector<NetQueueEntry>, Earlier> { }; // -- Ctor -- // Network::Network(Core *core) : _core(core) { _numMod = g_config->totalMods(); _tid = _core->getRank(); _transport = new Transport(); _transport->ptInit(_core->getId(), _numMod); _netQueue = new NetQueue* [_numMod]; for (SInt32 i = 0; i < _numMod; i++) _netQueue[i] = new NetQueue [NUM_PACKET_TYPES]; _callbacks = new NetworkCallback [NUM_PACKET_TYPES]; _callbackObjs = new void* [NUM_PACKET_TYPES]; for (SInt32 i = 0; i < NUM_PACKET_TYPES; i++) _callbacks[i] = NULL; UInt32 modelTypes[NUM_STATIC_NETWORKS]; g_config->getNetworkModels(modelTypes); for (SInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) _models[i] = NetworkModel::createModel(this, modelTypes[i]); LOG_PRINT("Initialized %x.", _transport); } // -- Dtor -- // Network::~Network() { for (SInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) delete _models[i]; delete [] _callbackObjs; delete [] _callbacks; for (SInt32 i = 0; i < _numMod; i++) delete [] _netQueue[i]; delete [] _netQueue; // FIXME: We *SHOULD* be deleting the transport, but for some // reason this causes the simulator to bork itself!? LOG_PRINT("Destroyed."); } // -- callbacks -- // void Network::registerCallback(PacketType type, NetworkCallback callback, void *obj) { assert((UInt32)type < NUM_PACKET_TYPES); _callbacks[type] = callback; _callbackObjs[type] = obj; } void Network::unregisterCallback(PacketType type) { assert((UInt32)type < NUM_PACKET_TYPES); _callbacks[type] = NULL; } // -- outputSummary -- // void Network::outputSummary(std::ostream &out) const { out << "Network summary:\n"; for (UInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) { out << " Network model " << i << ":\n"; _models[i]->outputSummary(out); } } // -- netPullFromTransport -- // // Polling function that performs background activities, such as // pulling from the physical transport layer and routing packets to // the appropriate queues. void Network::netPullFromTransport() { bool packetsEnqueued = false; do { NetQueueEntry entry; { void *buffer; buffer = _transport->ptRecv(); netExPacket(buffer, entry.packet, entry.time); } LOG_PRINT("Pull packet : type %i, from %i, time %llu", (SInt32)entry.packet.type, entry.packet.sender, entry.time); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); // was this packet sent to us, or should it just be forwarded? if (entry.packet.receiver != _transport->ptCommID()) { forwardPacket(entry.packet); // if this isn't a broadcast message, then we shouldn't process it further if (entry.packet.receiver != NetPacket::BROADCAST) continue; } // asynchronous I/O support NetworkCallback callback = _callbacks[entry.packet.type]; if (callback != NULL) { LOG_PRINT("Executing callback on packet : type %i, from %i, time %llu.", (SInt32)entry.packet.type, entry.packet.sender, entry.time); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); _core->getPerfModel()->updateCycleCount(entry.time); callback(_callbackObjs[entry.packet.type], entry.packet); delete [] (Byte*)entry.packet.data; } // synchronous I/O support else { LOG_PRINT("Enqueuing packet : type %i, from %i, time %llu.", (SInt32)entry.packet.type, entry.packet.sender, entry.time); _netQueueCond.acquire(); _netQueue[entry.packet.sender][entry.packet.type].push(entry); _netQueueCond.release(); packetsEnqueued = true; } } while (_transport->ptQuery()); // wake up waiting threads if (packetsEnqueued) _netQueueCond.broadcast(); } // -- forwardPacket -- // // FIXME: Can forwardPacket be subsumed by netSend? void Network::forwardPacket(const NetPacket &packet) { NetworkModel *model = _models[g_type_to_static_network_map[packet.type]]; vector<NetworkModel::Hop> hopVec; model->routePacket(packet, hopVec); void *forwardBuffer; UInt32 forwardBufferSize; forwardBuffer = netCreateBuf(packet, &forwardBufferSize, 0xBEEFCAFE); UInt64 *timeStamp = (UInt64*)forwardBuffer; assert(*timeStamp == 0xBEEFCAFE); for (UInt32 i = 0; i < hopVec.size(); i++) { *timeStamp = hopVec[i].time; _transport->ptSend(hopVec[i].dest, (char*)forwardBuffer, forwardBufferSize); } delete [] (UInt8*)forwardBuffer; } // -- netSend -- // SInt32 Network::netSend(NetPacket packet) { void *buffer; UInt32 bufSize; assert(packet.type >= 0 && packet.type < NUM_PACKET_TYPES); assert(packet.sender == _transport->ptCommID()); NetworkModel *model = _models[g_type_to_static_network_map[packet.type]]; vector<NetworkModel::Hop> hopVec; model->routePacket(packet, hopVec); buffer = netCreateBuf(packet, &bufSize, 0xBEEFCAFE); UInt64 *timeStamp = (UInt64*)buffer; assert(*timeStamp == 0xBEEFCAFE); for (UInt32 i = 0; i < hopVec.size(); i++) { LOG_PRINT("Send packet : type %i, to %i, time %llu", (SInt32)packet.type, packet.receiver, hopVec[i].time); *timeStamp = hopVec[i].time; _transport->ptSend(hopVec[i].dest, (char*)buffer, bufSize); } delete [] (UInt8*)buffer; LOG_PRINT("Sent packet"); return packet.length; } // -- netRecv -- // NetPacket Network::netRecv(const NetMatch &match) { LOG_PRINT("Entering netRecv."); NetQueueEntry entry; Boolean loop; loop = true; entry.time = (UInt64)-1; _netQueueCond.acquire(); // anything goes... if (match.senders.empty() && match.types.empty()) { while (loop) { entry.time = 0; for (SInt32 i = 0; i < _numMod; i++) { for (UInt32 j = 0; j < NUM_PACKET_TYPES; j++) { if (!(_netQueue[i][j].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[i][j].top().time)) { entry = _netQueue[i][j].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for any sender, multiple packet types else if (match.senders.empty()) { while (loop) { entry.time = 0; for (SInt32 i = 0; i < _numMod; i++) { for (UInt32 j = 0; j < match.types.size(); j++) { PacketType type = match.types[j]; if (!(_netQueue[i][type].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[i][type].top().time)) { entry = _netQueue[i][type].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for any packet type from several senders else if (match.types.empty()) { while (loop) { entry.time = 0; for (UInt32 i = 0; i < match.senders.size(); i++) { SInt32 sender = match.senders[i]; for (SInt32 j = 0; j < NUM_PACKET_TYPES; j++) { if (!(_netQueue[sender][j].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[sender][j].top().time)) { entry = _netQueue[sender][j].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for several senders with several packet types else { while (loop) { entry.time = 0; for (UInt32 i = 0; i < match.senders.size(); i++) { SInt32 sender = match.senders[i]; for (UInt32 j = 0; j < match.types.size(); j++) { PacketType type = match.types[j]; if (!(_netQueue[sender][type].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[sender][type].top().time)) { entry = _netQueue[sender][type].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } assert(loop == false && entry.time != (UInt64)-1); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); assert(entry.packet.receiver == _transport->ptCommID()); _netQueue[entry.packet.sender][entry.packet.type].pop(); _netQueueCond.release(); // Atomically update the time is the packet time is newer _core->getPerfModel()->updateCycleCount(entry.time); LOG_PRINT("Exiting netRecv : type %i, from %i", (SInt32)entry.packet.type, entry.packet.sender); return entry.packet; } // -- Wrappers -- // SInt32 Network::netSend(SInt32 dest, PacketType type, const void *buf, UInt32 len) { NetPacket packet; packet.sender = _transport->ptCommID(); packet.receiver = dest; packet.length = len; packet.type = type; packet.data = (void*)buf; return netSend(packet); } SInt32 Network::netBroadcast(PacketType type, const void *buf, UInt32 len) { return netSend(NetPacket::BROADCAST, type, buf, len); } NetPacket Network::netRecv(SInt32 src, PacketType type) { NetMatch match; match.senders.push_back(src); match.types.push_back(type); return netRecv(match); } NetPacket Network::netRecvFrom(SInt32 src) { NetMatch match; match.senders.push_back(src); return netRecv(match); } NetPacket Network::netRecvType(PacketType type) { NetMatch match; match.types.push_back(type); return netRecv(match); } // -- Internal functions -- // void* Network::netCreateBuf(const NetPacket &packet, UInt32* buffer_size, UInt64 time) { Byte *buffer; *buffer_size = sizeof(packet.type) + sizeof(packet.sender) + sizeof(packet.receiver) + sizeof(packet.length) + packet.length + sizeof(time); buffer = new Byte [*buffer_size]; Byte *dest = buffer; // Time MUST be first based on usage in netSend memcpy(dest, (Byte*)&time, sizeof(time)); dest += sizeof(time); memcpy(dest, (Byte*)&packet.type, sizeof(packet.type)); dest += sizeof(packet.type); memcpy(dest, (Byte*)&packet.sender, sizeof(packet.sender)); dest += sizeof(packet.sender); memcpy(dest, (Byte*)&packet.receiver, sizeof(packet.receiver)); dest += sizeof(packet.receiver); memcpy(dest, (Byte*)&packet.length, sizeof(packet.length)); dest += sizeof(packet.length); memcpy(dest, (Byte*)packet.data, packet.length); dest += packet.length; return (void*)buffer; } void Network::netExPacket(void* buffer, NetPacket &packet, UInt64 &time) { Byte *ptr = (Byte*)buffer; memcpy((Byte *) &time, ptr, sizeof(time)); ptr += sizeof(time); memcpy((Byte *) &packet.type, ptr, sizeof(packet.type)); ptr += sizeof(packet.type); memcpy((Byte *) &packet.sender, ptr, sizeof(packet.sender)); ptr += sizeof(packet.sender); memcpy((Byte *) &packet.receiver, ptr, sizeof(packet.receiver)); ptr += sizeof(packet.receiver); memcpy((Byte *) &packet.length, ptr, sizeof(packet.length)); ptr += sizeof(packet.length); packet.data = new Byte[packet.length]; memcpy((Byte *) packet.data, ptr, packet.length); ptr += packet.length; delete [] (Byte*)buffer; }
#include <queue> #include "transport.h" #include "core.h" #include "network.h" #include "log.h" #define LOG_DEFAULT_RANK (_transport->ptCommID()) #define LOG_DEFAULT_MODULE NETWORK // -- NetQueue -- // // // A priority queue for network packets. struct NetQueueEntry { NetPacket packet; UInt64 time; }; class Earlier { public: bool operator() (const NetQueueEntry& first, const NetQueueEntry& second) const { return first.time > second.time; } }; class NetQueue : public priority_queue <NetQueueEntry, vector<NetQueueEntry>, Earlier> { }; // -- Ctor -- // Network::Network(Core *core) : _core(core) { _numMod = g_config->totalMods(); _tid = _core->getRank(); _transport = new Transport(); _transport->ptInit(_core->getId(), _numMod); _netQueue = new NetQueue* [_numMod]; for (SInt32 i = 0; i < _numMod; i++) _netQueue[i] = new NetQueue [NUM_PACKET_TYPES]; _callbacks = new NetworkCallback [NUM_PACKET_TYPES]; _callbackObjs = new void* [NUM_PACKET_TYPES]; for (SInt32 i = 0; i < NUM_PACKET_TYPES; i++) _callbacks[i] = NULL; UInt32 modelTypes[NUM_STATIC_NETWORKS]; g_config->getNetworkModels(modelTypes); for (SInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) _models[i] = NetworkModel::createModel(this, modelTypes[i]); LOG_PRINT("Initialized."); } // -- Dtor -- // Network::~Network() { for (SInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) delete _models[i]; delete [] _callbackObjs; delete [] _callbacks; for (SInt32 i = 0; i < _numMod; i++) delete [] _netQueue[i]; delete [] _netQueue; delete _transport; LOG_PRINT("Destroyed."); } // -- callbacks -- // void Network::registerCallback(PacketType type, NetworkCallback callback, void *obj) { assert((UInt32)type < NUM_PACKET_TYPES); _callbacks[type] = callback; _callbackObjs[type] = obj; } void Network::unregisterCallback(PacketType type) { assert((UInt32)type < NUM_PACKET_TYPES); _callbacks[type] = NULL; } // -- outputSummary -- // void Network::outputSummary(std::ostream &out) const { out << "Network summary:\n"; for (UInt32 i = 0; i < NUM_STATIC_NETWORKS; i++) { out << " Network model " << i << ":\n"; _models[i]->outputSummary(out); } } // -- netPullFromTransport -- // // Polling function that performs background activities, such as // pulling from the physical transport layer and routing packets to // the appropriate queues. void Network::netPullFromTransport() { bool packetsEnqueued = false; do { NetQueueEntry entry; { void *buffer; buffer = _transport->ptRecv(); netExPacket(buffer, entry.packet, entry.time); } LOG_PRINT("Pull packet : type %i, from %i, time %llu", (SInt32)entry.packet.type, entry.packet.sender, entry.time); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); // was this packet sent to us, or should it just be forwarded? if (entry.packet.receiver != _transport->ptCommID()) { forwardPacket(entry.packet); // if this isn't a broadcast message, then we shouldn't process it further if (entry.packet.receiver != NetPacket::BROADCAST) continue; } // asynchronous I/O support NetworkCallback callback = _callbacks[entry.packet.type]; if (callback != NULL) { LOG_PRINT("Executing callback on packet : type %i, from %i, time %llu.", (SInt32)entry.packet.type, entry.packet.sender, entry.time); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); _core->getPerfModel()->updateCycleCount(entry.time); callback(_callbackObjs[entry.packet.type], entry.packet); delete [] (Byte*)entry.packet.data; } // synchronous I/O support else { LOG_PRINT("Enqueuing packet : type %i, from %i, time %llu.", (SInt32)entry.packet.type, entry.packet.sender, entry.time); _netQueueCond.acquire(); _netQueue[entry.packet.sender][entry.packet.type].push(entry); _netQueueCond.release(); packetsEnqueued = true; } } while (_transport->ptQuery()); // wake up waiting threads if (packetsEnqueued) _netQueueCond.broadcast(); } // -- forwardPacket -- // // FIXME: Can forwardPacket be subsumed by netSend? void Network::forwardPacket(const NetPacket &packet) { NetworkModel *model = _models[g_type_to_static_network_map[packet.type]]; vector<NetworkModel::Hop> hopVec; model->routePacket(packet, hopVec); void *forwardBuffer; UInt32 forwardBufferSize; forwardBuffer = netCreateBuf(packet, &forwardBufferSize, 0xBEEFCAFE); UInt64 *timeStamp = (UInt64*)forwardBuffer; assert(*timeStamp == 0xBEEFCAFE); for (UInt32 i = 0; i < hopVec.size(); i++) { *timeStamp = hopVec[i].time; _transport->ptSend(hopVec[i].dest, (char*)forwardBuffer, forwardBufferSize); } delete [] (UInt8*)forwardBuffer; } // -- netSend -- // SInt32 Network::netSend(NetPacket packet) { void *buffer; UInt32 bufSize; assert(packet.type >= 0 && packet.type < NUM_PACKET_TYPES); assert(packet.sender == _transport->ptCommID()); NetworkModel *model = _models[g_type_to_static_network_map[packet.type]]; vector<NetworkModel::Hop> hopVec; model->routePacket(packet, hopVec); buffer = netCreateBuf(packet, &bufSize, 0xBEEFCAFE); UInt64 *timeStamp = (UInt64*)buffer; assert(*timeStamp == 0xBEEFCAFE); for (UInt32 i = 0; i < hopVec.size(); i++) { LOG_PRINT("Send packet : type %i, to %i, time %llu", (SInt32)packet.type, packet.receiver, hopVec[i].time); *timeStamp = hopVec[i].time; _transport->ptSend(hopVec[i].dest, (char*)buffer, bufSize); } delete [] (UInt8*)buffer; LOG_PRINT("Sent packet"); return packet.length; } // -- netRecv -- // NetPacket Network::netRecv(const NetMatch &match) { LOG_PRINT("Entering netRecv."); NetQueueEntry entry; Boolean loop; loop = true; entry.time = (UInt64)-1; _netQueueCond.acquire(); // anything goes... if (match.senders.empty() && match.types.empty()) { while (loop) { entry.time = 0; for (SInt32 i = 0; i < _numMod; i++) { for (UInt32 j = 0; j < NUM_PACKET_TYPES; j++) { if (!(_netQueue[i][j].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[i][j].top().time)) { entry = _netQueue[i][j].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for any sender, multiple packet types else if (match.senders.empty()) { while (loop) { entry.time = 0; for (SInt32 i = 0; i < _numMod; i++) { for (UInt32 j = 0; j < match.types.size(); j++) { PacketType type = match.types[j]; if (!(_netQueue[i][type].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[i][type].top().time)) { entry = _netQueue[i][type].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for any packet type from several senders else if (match.types.empty()) { while (loop) { entry.time = 0; for (UInt32 i = 0; i < match.senders.size(); i++) { SInt32 sender = match.senders[i]; for (SInt32 j = 0; j < NUM_PACKET_TYPES; j++) { if (!(_netQueue[sender][j].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[sender][j].top().time)) { entry = _netQueue[sender][j].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } // look for several senders with several packet types else { while (loop) { entry.time = 0; for (UInt32 i = 0; i < match.senders.size(); i++) { SInt32 sender = match.senders[i]; for (UInt32 j = 0; j < match.types.size(); j++) { PacketType type = match.types[j]; if (!(_netQueue[sender][type].empty())) { loop = false; if ((entry.time == 0) || (entry.time > _netQueue[sender][type].top().time)) { entry = _netQueue[sender][type].top(); } } } } // No match found if (loop) { _netQueueCond.wait(); } } } assert(loop == false && entry.time != (UInt64)-1); assert(0 <= entry.packet.sender && entry.packet.sender < _numMod); assert(0 <= entry.packet.type && entry.packet.type < NUM_PACKET_TYPES); assert(entry.packet.receiver == _transport->ptCommID()); _netQueue[entry.packet.sender][entry.packet.type].pop(); _netQueueCond.release(); // Atomically update the time is the packet time is newer _core->getPerfModel()->updateCycleCount(entry.time); LOG_PRINT("Exiting netRecv : type %i, from %i", (SInt32)entry.packet.type, entry.packet.sender); return entry.packet; } // -- Wrappers -- // SInt32 Network::netSend(SInt32 dest, PacketType type, const void *buf, UInt32 len) { NetPacket packet; packet.sender = _transport->ptCommID(); packet.receiver = dest; packet.length = len; packet.type = type; packet.data = (void*)buf; return netSend(packet); } SInt32 Network::netBroadcast(PacketType type, const void *buf, UInt32 len) { return netSend(NetPacket::BROADCAST, type, buf, len); } NetPacket Network::netRecv(SInt32 src, PacketType type) { NetMatch match; match.senders.push_back(src); match.types.push_back(type); return netRecv(match); } NetPacket Network::netRecvFrom(SInt32 src) { NetMatch match; match.senders.push_back(src); return netRecv(match); } NetPacket Network::netRecvType(PacketType type) { NetMatch match; match.types.push_back(type); return netRecv(match); } // -- Internal functions -- // void* Network::netCreateBuf(const NetPacket &packet, UInt32* buffer_size, UInt64 time) { Byte *buffer; *buffer_size = sizeof(packet.type) + sizeof(packet.sender) + sizeof(packet.receiver) + sizeof(packet.length) + packet.length + sizeof(time); buffer = new Byte [*buffer_size]; Byte *dest = buffer; // Time MUST be first based on usage in netSend memcpy(dest, (Byte*)&time, sizeof(time)); dest += sizeof(time); memcpy(dest, (Byte*)&packet.type, sizeof(packet.type)); dest += sizeof(packet.type); memcpy(dest, (Byte*)&packet.sender, sizeof(packet.sender)); dest += sizeof(packet.sender); memcpy(dest, (Byte*)&packet.receiver, sizeof(packet.receiver)); dest += sizeof(packet.receiver); memcpy(dest, (Byte*)&packet.length, sizeof(packet.length)); dest += sizeof(packet.length); memcpy(dest, (Byte*)packet.data, packet.length); dest += packet.length; return (void*)buffer; } void Network::netExPacket(void* buffer, NetPacket &packet, UInt64 &time) { Byte *ptr = (Byte*)buffer; memcpy((Byte *) &time, ptr, sizeof(time)); ptr += sizeof(time); memcpy((Byte *) &packet.type, ptr, sizeof(packet.type)); ptr += sizeof(packet.type); memcpy((Byte *) &packet.sender, ptr, sizeof(packet.sender)); ptr += sizeof(packet.sender); memcpy((Byte *) &packet.receiver, ptr, sizeof(packet.receiver)); ptr += sizeof(packet.receiver); memcpy((Byte *) &packet.length, ptr, sizeof(packet.length)); ptr += sizeof(packet.length); packet.data = new Byte[packet.length]; memcpy((Byte *) packet.data, ptr, packet.length); ptr += packet.length; delete [] (Byte*)buffer; }
Revert "[network] Don't delete _transport. This is wrong, but for some reason necessary \?\!"
Revert "[network] Don't delete _transport. This is wrong, but for some reason necessary \?\!" This reverts commit aaf9b2bc3eddbed34902bde4b16ad0a1c4234f7a.
C++
mit
mit-carbon/Graphite,mit-carbon/Graphite,8l/Graphite,victorisildur/Graphite,mit-carbon/Graphite-Cycle-Level,8l/Graphite,8l/Graphite,fhijaz/Graphite,victorisildur/Graphite,mit-carbon/Graphite-Cycle-Level,nkawahara/Graphite,8l/Graphite,fhijaz/Graphite,mit-carbon/Graphite,nkawahara/Graphite,fhijaz/Graphite,nkawahara/Graphite,fhijaz/Graphite,nkawahara/Graphite,victorisildur/Graphite,mit-carbon/Graphite-Cycle-Level,victorisildur/Graphite,mit-carbon/Graphite,mit-carbon/Graphite-Cycle-Level
bd6346f62d9a3638893f6344a684d65459bef93d
source/common/network/transport_socket_options_impl.cc
source/common/network/transport_socket_options_impl.cc
#include "common/network/transport_socket_options_impl.h" #include "common/common/scalar_to_byte_vector.h" #include "common/common/utility.h" #include "common/network/application_protocol.h" #include "common/network/upstream_server_name.h" namespace Envoy { namespace Network { void TransportSocketOptionsImpl::hashKey(std::vector<uint8_t>& key) const { if (override_server_name_.has_value()) { pushScalarToByteVector(StringUtil::CaseInsensitiveHash()(override_server_name_.value()), key); } if (!override_alpn_list_.empty()) { for (const auto& protocol : override_alpn_list_) { pushScalarToByteVector(StringUtil::CaseInsensitiveHash()(protocol), key); } } } TransportSocketOptionsSharedPtr TransportSocketOptionsUtility::fromFilterState(const StreamInfo::FilterState& filter_state) { absl::string_view server_name; std::vector<std::string> application_protocols; bool needs_transport_socket_options = false; if (filter_state.hasData<UpstreamServerName>(UpstreamServerName::key())) { const auto& upstream_server_name = filter_state.getDataReadOnly<UpstreamServerName>(UpstreamServerName::key()); server_name = upstream_server_name.value(); needs_transport_socket_options = true; } if (filter_state.hasData<Network::ApplicationProtocols>(Network::ApplicationProtocols::key())) { const auto& alpn = filter_state.getDataReadOnly<Network::ApplicationProtocols>( Network::ApplicationProtocols::key()); application_protocols = alpn.value(); needs_transport_socket_options = true; } if (needs_transport_socket_options) { return std::make_shared<Network::TransportSocketOptionsImpl>( server_name, std::vector<std::string>{}, std::vector<std::string>{application_protocols}); } else { return nullptr; } } } // namespace Network } // namespace Envoy
#include "common/network/transport_socket_options_impl.h" #include <memory> #include <string> #include <utility> #include <vector> #include "common/common/scalar_to_byte_vector.h" #include "common/common/utility.h" #include "common/network/application_protocol.h" #include "common/network/upstream_server_name.h" namespace Envoy { namespace Network { void TransportSocketOptionsImpl::hashKey(std::vector<uint8_t>& key) const { if (override_server_name_.has_value()) { pushScalarToByteVector(StringUtil::CaseInsensitiveHash()(override_server_name_.value()), key); } if (!override_alpn_list_.empty()) { for (const auto& protocol : override_alpn_list_) { pushScalarToByteVector(StringUtil::CaseInsensitiveHash()(protocol), key); } } } TransportSocketOptionsSharedPtr TransportSocketOptionsUtility::fromFilterState(const StreamInfo::FilterState& filter_state) { absl::string_view server_name; std::vector<std::string> application_protocols; bool needs_transport_socket_options = false; if (filter_state.hasData<UpstreamServerName>(UpstreamServerName::key())) { const auto& upstream_server_name = filter_state.getDataReadOnly<UpstreamServerName>(UpstreamServerName::key()); server_name = upstream_server_name.value(); needs_transport_socket_options = true; } if (filter_state.hasData<Network::ApplicationProtocols>(Network::ApplicationProtocols::key())) { const auto& alpn = filter_state.getDataReadOnly<Network::ApplicationProtocols>( Network::ApplicationProtocols::key()); application_protocols = alpn.value(); needs_transport_socket_options = true; } if (needs_transport_socket_options) { return std::make_shared<Network::TransportSocketOptionsImpl>( server_name, std::vector<std::string>{}, std::move(application_protocols)); } else { return nullptr; } } } // namespace Network } // namespace Envoy
use std::move instead of constructing a copy (#9415)
misc: use std::move instead of constructing a copy (#9415) Signed-off-by: Derek Argueta <[email protected]>
C++
apache-2.0
envoyproxy/envoy,lizan/envoy,lizan/envoy,istio/envoy,lyft/envoy,jrajahalme/envoy,lyft/envoy,istio/envoy,lizan/envoy,envoyproxy/envoy-wasm,istio/envoy,lyft/envoy,jrajahalme/envoy,jrajahalme/envoy,eklitzke/envoy,eklitzke/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy-wasm,istio/envoy,lizan/envoy,envoyproxy/envoy-wasm,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,istio/envoy,lyft/envoy,eklitzke/envoy,eklitzke/envoy,lizan/envoy,envoyproxy/envoy-wasm,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,lizan/envoy,envoyproxy/envoy,istio/envoy,envoyproxy/envoy,jrajahalme/envoy,eklitzke/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm,eklitzke/envoy,envoyproxy/envoy,envoyproxy/envoy,jrajahalme/envoy,jrajahalme/envoy,istio/envoy,envoyproxy/envoy,envoyproxy/envoy-wasm
760d732487e7fb1794bd1727ed4aab93cb2bd055
source/image_processing/computed_field_ImageFilter.cpp
source/image_processing/computed_field_ImageFilter.cpp
/******************************************************************************* FILE : computed_field_binaryThresholdFilter.c LAST MODIFIED : 9 September 2006 DESCRIPTION : Wraps itk::MeanImageFilter ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ extern "C" { #include "computed_field/computed_field.h" } #include "computed_field/computed_field_private.hpp" #include "image_processing/computed_field_ImageFilter.hpp" extern "C" { #include "general/debug.h" #include "general/mystring.h" #include "user_interface/message.h" } namespace CMISS { int Computed_field_ImageFilter::evaluate_cache_at_location( Field_location* location) /******************************************************************************* LAST MODIFIED : 7 September 2006 DESCRIPTION : Evaluate the fields cache at the location ==============================================================================*/ { int return_code; ENTER(Computed_field_meanImageFilter::evaluate_cache_at_location); if (field && location) { return_code = functor->update_and_evaluate_filter(location); } else { display_message(ERROR_MESSAGE, "Computed_field_meanImageFilter::evaluate_cache_at_location. " "Invalid argument(s)"); return_code = 0; } LEAVE; return (return_code); } /* Computed_field_meanImageFilter::evaluate_cache_at_location */ } // namespace CMISS
/******************************************************************************* FILE : computed_field_ImageFilter.cpp LAST MODIFIED : 9 September 2006 DESCRIPTION : Wraps itk::MeanImageFilter ==============================================================================*/ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public 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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is cmgui. * * The Initial Developer of the Original Code is * Auckland Uniservices Ltd, Auckland, New Zealand. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ extern "C" { #include "computed_field/computed_field.h" } #include "computed_field/computed_field_private.hpp" #include "image_processing/computed_field_ImageFilter.hpp" extern "C" { #include "general/debug.h" #include "general/mystring.h" #include "user_interface/message.h" } namespace CMISS { int Computed_field_ImageFilter::evaluate_cache_at_location( Field_location* location) /******************************************************************************* LAST MODIFIED : 7 September 2006 DESCRIPTION : Evaluate the fields cache at the location ==============================================================================*/ { int return_code; ENTER(Computed_field_meanImageFilter::evaluate_cache_at_location); if (field && location) { return_code = functor->update_and_evaluate_filter(location); } else { display_message(ERROR_MESSAGE, "Computed_field_meanImageFilter::evaluate_cache_at_location. " "Invalid argument(s)"); return_code = 0; } LEAVE; return (return_code); } /* Computed_field_meanImageFilter::evaluate_cache_at_location */ } // namespace CMISS
Fix up header comment.
Fix up header comment.
C++
mpl-2.0
cmiss/cmgui,cmiss/cmgui
18dc6384d4f030f690e7b061b9e26f0c96f2ca91
src/shrpx_spdy_downstream_connection.cc
src/shrpx_spdy_downstream_connection.cc
/* * Spdylay - SPDY Library * * Copyright (c) 2012 Tatsuhiro Tsujikawa * * 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 "shrpx_spdy_downstream_connection.h" #include <unistd.h> #include <openssl/err.h> #include <event2/bufferevent_ssl.h> #include "http-parser/http_parser.h" #include "shrpx_client_handler.h" #include "shrpx_upstream.h" #include "shrpx_downstream.h" #include "shrpx_config.h" #include "shrpx_error.h" #include "shrpx_http.h" #include "shrpx_spdy_session.h" #include "util.h" using namespace spdylay; namespace shrpx { SpdyDownstreamConnection::SpdyDownstreamConnection (ClientHandler *client_handler) : DownstreamConnection(client_handler), spdy_(client_handler->get_spdy_session()), request_body_buf_(0), sd_(0), recv_window_size_(0) {} SpdyDownstreamConnection::~SpdyDownstreamConnection() { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Deleting"; } if(request_body_buf_) { evbuffer_free(request_body_buf_); } if(downstream_) { if(submit_rst_stream(downstream_) == 0) { spdy_->notify(); } } spdy_->remove_downstream_connection(this); // Downstream and DownstreamConnection may be deleted // asynchronously. if(downstream_) { downstream_->set_downstream_connection(0); } if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Deleted"; } } int SpdyDownstreamConnection::init_request_body_buf() { int rv; if(request_body_buf_) { rv = evbuffer_drain(request_body_buf_, evbuffer_get_length(request_body_buf_)); if(rv != 0) { return -1; } } else { request_body_buf_ = evbuffer_new(); if(request_body_buf_ == 0) { return -1; } evbuffer_setcb(request_body_buf_, 0, this); } return 0; } int SpdyDownstreamConnection::attach_downstream(Downstream *downstream) { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Attaching to DOWNSTREAM:" << downstream; } if(init_request_body_buf() == -1) { return -1; } spdy_->add_downstream_connection(this); if(spdy_->get_state() == SpdySession::DISCONNECTED) { spdy_->notify(); } downstream->set_downstream_connection(this); downstream_ = downstream; recv_window_size_ = 0; return 0; } void SpdyDownstreamConnection::detach_downstream(Downstream *downstream) { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Detaching from DOWNSTREAM:" << downstream; } if(submit_rst_stream(downstream) == 0) { spdy_->notify(); } downstream->set_downstream_connection(0); downstream_ = 0; client_handler_->pool_downstream_connection(this); } int SpdyDownstreamConnection::submit_rst_stream(Downstream *downstream) { int rv = -1; if(spdy_->get_state() == SpdySession::CONNECTED && downstream->get_downstream_stream_id() != -1) { switch(downstream->get_response_state()) { case Downstream::MSG_RESET: case Downstream::MSG_COMPLETE: break; default: if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Submit RST_STREAM for DOWNSTREAM:" << downstream; } rv = spdy_->submit_rst_stream(this, downstream->get_downstream_stream_id(), SPDYLAY_CANCEL); } } return rv; } namespace { ssize_t spdy_data_read_callback(spdylay_session *session, int32_t stream_id, uint8_t *buf, size_t length, int *eof, spdylay_data_source *source, void *user_data) { StreamData *sd; sd = reinterpret_cast<StreamData*> (spdylay_session_get_stream_user_data(session, stream_id)); if(!sd || !sd->dconn) { return SPDYLAY_ERR_DEFERRED; } SpdyDownstreamConnection *dconn; dconn = reinterpret_cast<SpdyDownstreamConnection*>(source->ptr); Downstream *downstream = dconn->get_downstream(); if(!downstream) { // In this case, RST_STREAM should have been issued. But depending // on the priority, DATA frame may come first. return SPDYLAY_ERR_DEFERRED; } evbuffer *body = dconn->get_request_body_buf(); int nread = 0; for(;;) { nread = evbuffer_remove(body, buf, length); if(nread == 0) { if(downstream->get_request_state() == Downstream::MSG_COMPLETE) { *eof = 1; break; } else { // This is important because it will handle flow control // stuff. if(downstream->get_upstream()->resume_read(SHRPX_NO_BUFFER, downstream) == -1) { // In this case, downstream may be deleted. return SPDYLAY_ERR_DEFERRED; } if(evbuffer_get_length(body) == 0) { return SPDYLAY_ERR_DEFERRED; } } } else { break; } } return nread; } } // namespace int SpdyDownstreamConnection::push_request_headers() { int rv; if(spdy_->get_state() != SpdySession::CONNECTED) { // The SPDY session to the backend has not been established. This // function will be called again just after it is established. return 0; } if(!downstream_) { return 0; } size_t nheader = downstream_->get_request_headers().size(); // 14 means :method, :scheme, :path, :version and possible via, // x-forwarded-for and x-forwarded-proto header fields. We rename // host header field as :host. const char **nv = new const char*[nheader * 2 + 14 + 1]; size_t hdidx = 0; std::string via_value; std::string xff_value; std::string scheme, path, query; if(downstream_->get_request_method() == "CONNECT") { // No :scheme header field for CONNECT method. nv[hdidx++] = ":path"; nv[hdidx++] = downstream_->get_request_path().c_str(); } else { http_parser_url u; const char *url = downstream_->get_request_path().c_str(); memset(&u, 0, sizeof(u)); rv = http_parser_parse_url(url, downstream_->get_request_path().size(), 0, &u); if(rv == 0) { http::copy_url_component(scheme, &u, UF_SCHEMA, url); http::copy_url_component(path, &u, UF_PATH, url); http::copy_url_component(query, &u, UF_QUERY, url); if(path.empty()) { path = "/"; } if(!query.empty()) { path += "?"; path += query; } } nv[hdidx++] = ":scheme"; if(scheme.empty()) { // The default scheme is http. For SPDY upstream, the path must // be absolute URI, so scheme should be provided. nv[hdidx++] = "http"; } else { nv[hdidx++] = scheme.c_str(); } nv[hdidx++] = ":path"; if(path.empty()) { nv[hdidx++] = downstream_->get_request_path().c_str(); } else { nv[hdidx++] = path.c_str(); } } nv[hdidx++] = ":method"; nv[hdidx++] = downstream_->get_request_method().c_str(); nv[hdidx++] = ":version"; nv[hdidx++] = "HTTP/1.1"; bool chunked_encoding = false; bool content_length = false; for(Headers::const_iterator i = downstream_->get_request_headers().begin(); i != downstream_->get_request_headers().end(); ++i) { if(util::strieq((*i).first.c_str(), "transfer-encoding")) { if(util::strieq((*i).second.c_str(), "chunked")) { chunked_encoding = true; } // Ignore transfer-encoding } else if(util::strieq((*i).first.c_str(), "x-forwarded-proto") || util::strieq((*i).first.c_str(), "keep-alive") || util::strieq((*i).first.c_str(), "connection") || util:: strieq((*i).first.c_str(), "proxy-connection")) { // These are ignored } else if(!get_config()->no_via && util::strieq((*i).first.c_str(), "via")) { via_value = (*i).second; } else if(util::strieq((*i).first.c_str(), "x-forwarded-for")) { xff_value = (*i).second; } else if(util::strieq((*i).first.c_str(), "expect") && util::strifind((*i).second.c_str(), "100-continue")) { // Ignore } else if(util::strieq((*i).first.c_str(), "host")) { nv[hdidx++] = ":host"; nv[hdidx++] = (*i).second.c_str(); } else { if(util::strieq((*i).first.c_str(), "content-length")) { content_length = true; } nv[hdidx++] = (*i).first.c_str(); nv[hdidx++] = (*i).second.c_str(); } } if(get_config()->add_x_forwarded_for) { nv[hdidx++] = "x-forwarded-for"; if(!xff_value.empty()) { xff_value += ", "; } xff_value += downstream_->get_upstream()->get_client_handler()-> get_ipaddr(); nv[hdidx++] = xff_value.c_str(); } else if(!xff_value.empty()) { nv[hdidx++] = "x-forwarded-for"; nv[hdidx++] = xff_value.c_str(); } if(downstream_->get_request_method() != "CONNECT") { // Currently, HTTP connection is used as upstream, so we just // specify it here. nv[hdidx++] = "x-forwarded-proto"; nv[hdidx++] = "http"; } if(!get_config()->no_via) { if(!via_value.empty()) { via_value += ", "; } via_value += http::create_via_header_value (downstream_->get_request_major(), downstream_->get_request_minor()); nv[hdidx++] = "via"; nv[hdidx++] = via_value.c_str(); } nv[hdidx++] = 0; if(LOG_ENABLED(INFO)) { std::stringstream ss; for(size_t i = 0; nv[i]; i += 2) { ss << TTY_HTTP_HD << nv[i] << TTY_RST << ": " << nv[i+1] << "\n"; } DCLOG(INFO, this) << "HTTP request headers\n" << ss.str(); } if(downstream_->get_request_method() == "CONNECT" || chunked_encoding || content_length) { // Request-body is expected. spdylay_data_provider data_prd; data_prd.source.ptr = this; data_prd.read_callback = spdy_data_read_callback; rv = spdy_->submit_request(this, 0, nv, &data_prd); } else { rv = spdy_->submit_request(this, 0, nv, 0); } delete [] nv; if(rv != 0) { DCLOG(FATAL, this) << "spdylay_submit_request() failed"; return -1; } spdy_->notify(); return 0; } int SpdyDownstreamConnection::push_upload_data_chunk(const uint8_t *data, size_t datalen) { int rv = evbuffer_add(request_body_buf_, data, datalen); if(rv != 0) { DCLOG(FATAL, this) << "evbuffer_add() failed"; return -1; } if(downstream_->get_downstream_stream_id() != -1) { rv = spdy_->resume_data(this); if(rv != 0) { return -1; } spdy_->notify(); } return 0; } int SpdyDownstreamConnection::end_upload_data() { int rv; if(downstream_->get_downstream_stream_id() != -1) { rv = spdy_->resume_data(this); if(rv != 0) { return -1; } spdy_->notify(); } return 0; } int SpdyDownstreamConnection::resume_read(IOCtrlReason reason) { int rv; if(spdy_->get_state() == SpdySession::CONNECTED && spdy_->get_flow_control() && downstream_ && downstream_->get_downstream_stream_id() != -1 && recv_window_size_ >= spdy_->get_initial_window_size()/2) { rv = spdy_->submit_window_update(this, recv_window_size_); if(rv == -1) { return -1; } spdy_->notify(); recv_window_size_ = 0; } return 0; } int SpdyDownstreamConnection::on_read() { return 0; } int SpdyDownstreamConnection::on_write() { return 0; } evbuffer* SpdyDownstreamConnection::get_request_body_buf() const { return request_body_buf_; } void SpdyDownstreamConnection::attach_stream_data(StreamData *sd) { assert(sd_ == 0 && sd->dconn == 0); sd_ = sd; sd_->dconn = this; } StreamData* SpdyDownstreamConnection::detach_stream_data() { if(sd_) { StreamData *sd = sd_; sd_ = 0; sd->dconn = 0; return sd; } else { return 0; } } bool SpdyDownstreamConnection::get_output_buffer_full() { if(request_body_buf_) { return evbuffer_get_length(request_body_buf_) >= Downstream::OUTPUT_UPPER_THRES; } else { return false; } } int32_t SpdyDownstreamConnection::get_recv_window_size() const { return recv_window_size_; } void SpdyDownstreamConnection::inc_recv_window_size(int32_t amount) { recv_window_size_ += amount; } } // namespace shrpx
/* * Spdylay - SPDY Library * * Copyright (c) 2012 Tatsuhiro Tsujikawa * * 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 "shrpx_spdy_downstream_connection.h" #include <unistd.h> #include <openssl/err.h> #include <event2/bufferevent_ssl.h> #include "http-parser/http_parser.h" #include "shrpx_client_handler.h" #include "shrpx_upstream.h" #include "shrpx_downstream.h" #include "shrpx_config.h" #include "shrpx_error.h" #include "shrpx_http.h" #include "shrpx_spdy_session.h" #include "util.h" using namespace spdylay; namespace shrpx { SpdyDownstreamConnection::SpdyDownstreamConnection (ClientHandler *client_handler) : DownstreamConnection(client_handler), spdy_(client_handler->get_spdy_session()), request_body_buf_(0), sd_(0), recv_window_size_(0) {} SpdyDownstreamConnection::~SpdyDownstreamConnection() { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Deleting"; } if(request_body_buf_) { evbuffer_free(request_body_buf_); } if(downstream_) { if(submit_rst_stream(downstream_) == 0) { spdy_->notify(); } } spdy_->remove_downstream_connection(this); // Downstream and DownstreamConnection may be deleted // asynchronously. if(downstream_) { downstream_->set_downstream_connection(0); } if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Deleted"; } } int SpdyDownstreamConnection::init_request_body_buf() { int rv; if(request_body_buf_) { rv = evbuffer_drain(request_body_buf_, evbuffer_get_length(request_body_buf_)); if(rv != 0) { return -1; } } else { request_body_buf_ = evbuffer_new(); if(request_body_buf_ == 0) { return -1; } evbuffer_setcb(request_body_buf_, 0, this); } return 0; } int SpdyDownstreamConnection::attach_downstream(Downstream *downstream) { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Attaching to DOWNSTREAM:" << downstream; } if(init_request_body_buf() == -1) { return -1; } spdy_->add_downstream_connection(this); if(spdy_->get_state() == SpdySession::DISCONNECTED) { spdy_->notify(); } downstream->set_downstream_connection(this); downstream_ = downstream; recv_window_size_ = 0; return 0; } void SpdyDownstreamConnection::detach_downstream(Downstream *downstream) { if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Detaching from DOWNSTREAM:" << downstream; } if(submit_rst_stream(downstream) == 0) { spdy_->notify(); } downstream->set_downstream_connection(0); downstream_ = 0; client_handler_->pool_downstream_connection(this); } int SpdyDownstreamConnection::submit_rst_stream(Downstream *downstream) { int rv = -1; if(spdy_->get_state() == SpdySession::CONNECTED && downstream->get_downstream_stream_id() != -1) { switch(downstream->get_response_state()) { case Downstream::MSG_RESET: case Downstream::MSG_COMPLETE: break; default: if(LOG_ENABLED(INFO)) { DCLOG(INFO, this) << "Submit RST_STREAM for DOWNSTREAM:" << downstream; } rv = spdy_->submit_rst_stream(this, downstream->get_downstream_stream_id(), SPDYLAY_CANCEL); } } return rv; } namespace { ssize_t spdy_data_read_callback(spdylay_session *session, int32_t stream_id, uint8_t *buf, size_t length, int *eof, spdylay_data_source *source, void *user_data) { StreamData *sd; sd = reinterpret_cast<StreamData*> (spdylay_session_get_stream_user_data(session, stream_id)); if(!sd || !sd->dconn) { return SPDYLAY_ERR_DEFERRED; } SpdyDownstreamConnection *dconn; dconn = reinterpret_cast<SpdyDownstreamConnection*>(source->ptr); Downstream *downstream = dconn->get_downstream(); if(!downstream) { // In this case, RST_STREAM should have been issued. But depending // on the priority, DATA frame may come first. return SPDYLAY_ERR_DEFERRED; } evbuffer *body = dconn->get_request_body_buf(); int nread = 0; for(;;) { nread = evbuffer_remove(body, buf, length); if(nread == 0) { if(downstream->get_request_state() == Downstream::MSG_COMPLETE) { *eof = 1; break; } else { // This is important because it will handle flow control // stuff. if(downstream->get_upstream()->resume_read(SHRPX_NO_BUFFER, downstream) == -1) { // In this case, downstream may be deleted. return SPDYLAY_ERR_DEFERRED; } if(evbuffer_get_length(body) == 0) { return SPDYLAY_ERR_DEFERRED; } } } else { break; } } return nread; } } // namespace int SpdyDownstreamConnection::push_request_headers() { int rv; if(spdy_->get_state() != SpdySession::CONNECTED) { // The SPDY session to the backend has not been established. This // function will be called again just after it is established. return 0; } if(!downstream_) { return 0; } size_t nheader = downstream_->get_request_headers().size(); // 12 means :method, :scheme, :path, :version and possible via and // x-forwarded-for header fields. We rename host header field as // :host. const char **nv = new const char*[nheader * 2 + 12 + 1]; size_t hdidx = 0; std::string via_value; std::string xff_value; std::string scheme, path, query; if(downstream_->get_request_method() == "CONNECT") { // No :scheme header field for CONNECT method. nv[hdidx++] = ":path"; nv[hdidx++] = downstream_->get_request_path().c_str(); } else { http_parser_url u; const char *url = downstream_->get_request_path().c_str(); memset(&u, 0, sizeof(u)); rv = http_parser_parse_url(url, downstream_->get_request_path().size(), 0, &u); if(rv == 0) { http::copy_url_component(scheme, &u, UF_SCHEMA, url); http::copy_url_component(path, &u, UF_PATH, url); http::copy_url_component(query, &u, UF_QUERY, url); if(path.empty()) { path = "/"; } if(!query.empty()) { path += "?"; path += query; } } nv[hdidx++] = ":scheme"; if(scheme.empty()) { // The default scheme is http. For SPDY upstream, the path must // be absolute URI, so scheme should be provided. nv[hdidx++] = "http"; } else { nv[hdidx++] = scheme.c_str(); } nv[hdidx++] = ":path"; if(path.empty()) { nv[hdidx++] = downstream_->get_request_path().c_str(); } else { nv[hdidx++] = path.c_str(); } } nv[hdidx++] = ":method"; nv[hdidx++] = downstream_->get_request_method().c_str(); nv[hdidx++] = ":version"; nv[hdidx++] = "HTTP/1.1"; bool chunked_encoding = false; bool content_length = false; for(Headers::const_iterator i = downstream_->get_request_headers().begin(); i != downstream_->get_request_headers().end(); ++i) { if(util::strieq((*i).first.c_str(), "transfer-encoding")) { if(util::strieq((*i).second.c_str(), "chunked")) { chunked_encoding = true; } // Ignore transfer-encoding } else if(util::strieq((*i).first.c_str(), "x-forwarded-proto") || util::strieq((*i).first.c_str(), "keep-alive") || util::strieq((*i).first.c_str(), "connection") || util:: strieq((*i).first.c_str(), "proxy-connection")) { // These are ignored } else if(!get_config()->no_via && util::strieq((*i).first.c_str(), "via")) { via_value = (*i).second; } else if(util::strieq((*i).first.c_str(), "x-forwarded-for")) { xff_value = (*i).second; } else if(util::strieq((*i).first.c_str(), "expect") && util::strifind((*i).second.c_str(), "100-continue")) { // Ignore } else if(util::strieq((*i).first.c_str(), "host")) { nv[hdidx++] = ":host"; nv[hdidx++] = (*i).second.c_str(); } else { if(util::strieq((*i).first.c_str(), "content-length")) { content_length = true; } nv[hdidx++] = (*i).first.c_str(); nv[hdidx++] = (*i).second.c_str(); } } if(get_config()->add_x_forwarded_for) { nv[hdidx++] = "x-forwarded-for"; if(!xff_value.empty()) { xff_value += ", "; } xff_value += downstream_->get_upstream()->get_client_handler()-> get_ipaddr(); nv[hdidx++] = xff_value.c_str(); } else if(!xff_value.empty()) { nv[hdidx++] = "x-forwarded-for"; nv[hdidx++] = xff_value.c_str(); } if(!get_config()->no_via) { if(!via_value.empty()) { via_value += ", "; } via_value += http::create_via_header_value (downstream_->get_request_major(), downstream_->get_request_minor()); nv[hdidx++] = "via"; nv[hdidx++] = via_value.c_str(); } nv[hdidx++] = 0; if(LOG_ENABLED(INFO)) { std::stringstream ss; for(size_t i = 0; nv[i]; i += 2) { ss << TTY_HTTP_HD << nv[i] << TTY_RST << ": " << nv[i+1] << "\n"; } DCLOG(INFO, this) << "HTTP request headers\n" << ss.str(); } if(downstream_->get_request_method() == "CONNECT" || chunked_encoding || content_length) { // Request-body is expected. spdylay_data_provider data_prd; data_prd.source.ptr = this; data_prd.read_callback = spdy_data_read_callback; rv = spdy_->submit_request(this, 0, nv, &data_prd); } else { rv = spdy_->submit_request(this, 0, nv, 0); } delete [] nv; if(rv != 0) { DCLOG(FATAL, this) << "spdylay_submit_request() failed"; return -1; } spdy_->notify(); return 0; } int SpdyDownstreamConnection::push_upload_data_chunk(const uint8_t *data, size_t datalen) { int rv = evbuffer_add(request_body_buf_, data, datalen); if(rv != 0) { DCLOG(FATAL, this) << "evbuffer_add() failed"; return -1; } if(downstream_->get_downstream_stream_id() != -1) { rv = spdy_->resume_data(this); if(rv != 0) { return -1; } spdy_->notify(); } return 0; } int SpdyDownstreamConnection::end_upload_data() { int rv; if(downstream_->get_downstream_stream_id() != -1) { rv = spdy_->resume_data(this); if(rv != 0) { return -1; } spdy_->notify(); } return 0; } int SpdyDownstreamConnection::resume_read(IOCtrlReason reason) { int rv; if(spdy_->get_state() == SpdySession::CONNECTED && spdy_->get_flow_control() && downstream_ && downstream_->get_downstream_stream_id() != -1 && recv_window_size_ >= spdy_->get_initial_window_size()/2) { rv = spdy_->submit_window_update(this, recv_window_size_); if(rv == -1) { return -1; } spdy_->notify(); recv_window_size_ = 0; } return 0; } int SpdyDownstreamConnection::on_read() { return 0; } int SpdyDownstreamConnection::on_write() { return 0; } evbuffer* SpdyDownstreamConnection::get_request_body_buf() const { return request_body_buf_; } void SpdyDownstreamConnection::attach_stream_data(StreamData *sd) { assert(sd_ == 0 && sd->dconn == 0); sd_ = sd; sd_->dconn = this; } StreamData* SpdyDownstreamConnection::detach_stream_data() { if(sd_) { StreamData *sd = sd_; sd_ = 0; sd->dconn = 0; return sd; } else { return 0; } } bool SpdyDownstreamConnection::get_output_buffer_full() { if(request_body_buf_) { return evbuffer_get_length(request_body_buf_) >= Downstream::OUTPUT_UPPER_THRES; } else { return false; } } int32_t SpdyDownstreamConnection::get_recv_window_size() const { return recv_window_size_; } void SpdyDownstreamConnection::inc_recv_window_size(int32_t amount) { recv_window_size_ += amount; } } // namespace shrpx
Remove x-forwarded-proto header from SPDY downstream
shrpx: Remove x-forwarded-proto header from SPDY downstream SPDY frame has :scheme header field, so x-forwarded-proto is not necessary.
C++
mit
lukw00/nghttp2,mixianghang/spdylay,dxq-git/nghttp2,wzyboy/nghttp2,serioussam/nghttp2,lukw00/nghttp2,wzyboy/nghttp2,yuki-kodama/nghttp2,thinred/nghttp2,serioussam/nghttp2,bxshi/nghttp2,ohyeah521/nghttp2,wzyboy/nghttp2,ohyeah521/nghttp2,thinred/nghttp2,lukw00/nghttp2,minhoryang/nghttp2,bxshi/nghttp2,ahnan4arch/spdylay,icing/nghttp2,dxq-git/nghttp2,tatsuhiro-t/spdylay,ahnan4arch/spdylay,serioussam/nghttp2,serioussam/nghttp2,thinred/nghttp2,serioussam/nghttp2,yuki-kodama/nghttp2,wzyboy/nghttp2,bxshi/nghttp2,mixianghang/spdylay,icing/nghttp2,minhoryang/nghttp2,mixianghang/spdylay,yuki-kodama/nghttp2,mixianghang/nghttp2,ohyeah521/nghttp2,minhoryang/nghttp2,tatsuhiro-t/spdylay,yuki-kodama/nghttp2,icing/nghttp2,mixianghang/nghttp2,tatsuhiro-t/spdylay,tatsuhiro-t/spdylay,mixianghang/nghttp2,wzyboy/nghttp2,mixianghang/nghttp2,kelbyludwig/nghttp2,icing/nghttp2,lukw00/nghttp2,icing/nghttp2,ohyeah521/nghttp2,serioussam/nghttp2,shines77/nghttp2,tatsuhiro-t/spdylay,syohex/nghttp2,thinred/nghttp2,mixianghang/nghttp2,ahnan4arch/spdylay,shines77/nghttp2,syohex/nghttp2,dxq-git/nghttp2,yuki-kodama/nghttp2,lukw00/nghttp2,bxshi/nghttp2,shines77/nghttp2,minhoryang/nghttp2,bxshi/nghttp2,ahnan4arch/spdylay,shines77/nghttp2,dxq-git/nghttp2,wzyboy/nghttp2,ohyeah521/nghttp2,syohex/nghttp2,shines77/nghttp2,wzyboy/nghttp2,mixianghang/spdylay,thinred/nghttp2,minhoryang/nghttp2,lukw00/nghttp2,lukw00/nghttp2,icing/nghttp2,syohex/nghttp2,kelbyludwig/nghttp2,kelbyludwig/nghttp2,bxshi/nghttp2,dxq-git/nghttp2,kelbyludwig/nghttp2,ohyeah521/nghttp2,ahnan4arch/spdylay,thinred/nghttp2,kelbyludwig/nghttp2,minhoryang/nghttp2,thinred/nghttp2,shines77/nghttp2,yuki-kodama/nghttp2,syohex/nghttp2,syohex/nghttp2,mixianghang/spdylay,kelbyludwig/nghttp2,dxq-git/nghttp2,mixianghang/nghttp2,serioussam/nghttp2,icing/nghttp2
914805101317fa490890146e29ae68654506aa94
example/src/render.cpp
example/src/render.cpp
#include "physics.h" #include "player.h" #include "render.h" #include "shader.h" #include "input.h" #include "planet.h" #include "gui.h" #include <atomic> #include <glm/gtc/matrix_transform.hpp> #define GL3_PROTOTYPES 1 #include <GL/glew.h> #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> namespace render { struct qbRenderable_ { qbMesh mesh; qbMaterial material; }; struct Camera { float ratio; float fov; float znear; float zfar; glm::mat4 view_mat; glm::mat4 projection_mat; glm::mat4 inv_projection_mat; glm::mat4 rotation_mat; glm::vec3 from; glm::vec3 to; glm::vec3 origin; float yaw = 0.0f; float pitch = 0.0f; const glm::vec4 front = { 1.0f, 0.0f, 0.0f, 1.0f }; const glm::vec4 up = { 0.0f, 0.0f, 1.0f, 1.0f }; } camera; // Collections qbComponent renderables; // Channels qbEvent render_event; // Systems qbSystem render_system; int width; int height; SDL_Window *win = nullptr; SDL_GLContext context; qbComponent component() { return renderables; } bool check_for_gl_errors() { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return false; } while (error != GL_NO_ERROR) { const GLubyte* error_str = gluErrorString(error); std::cout << "Error(" << error << "): " << error_str << std::endl; error = glGetError(); } return true; } void render_event_handler(qbInstance* insts, qbFrame* f) { RenderEvent* e = (RenderEvent*)f->event; qbRenderable* renderable; qb_instance_getconst(insts[0], &renderable); physics::Transform* transform; qb_instance_getconst(insts[1], &transform); glm::vec3 v = transform->v * (float)e->alpha; glm::mat4 mvp; glm::mat4 m = glm::translate(glm::mat4(1.0f), transform->p + v); qb_material_use((*renderable)->material); mvp = camera.projection_mat * camera.view_mat * m; qbShader shader = qb_material_getshader((*renderable)->material); qb_shader_setmat4(shader, "uMvp", mvp); qb_mesh_draw((*renderable)->mesh, (*renderable)->material); if (check_for_gl_errors()) { std::cout << "Renderable entity: " << qb_instance_getentity(insts[0]) << "\n"; } } void present(RenderEvent* event) { qb_render_makecurrent(); // Initial rotation matrix. camera.rotation_mat = glm::mat4(1.0f); glm::vec3 look_from = camera.from + camera.origin; glm::vec3 look_to = camera.origin; glm::vec3 direction = glm::normalize(look_from - look_to); glm::vec3 up = camera.up; glm::vec3 right = glm::normalize(glm::cross(up, direction)); up = glm::cross(direction, right); camera.view_mat = glm::lookAt(look_from, look_to, up); glViewport(0, 0, window_width(), window_height()); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glClearColor(0.1, 0.1, 0.1, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); qb_event_sendsync(render_event, event); gui::Render(); SDL_GL_SwapWindow(win); qb_render_makenull(); } qbRenderable create(qbMesh mesh, qbMaterial material) { return new qbRenderable_{mesh, material}; } void initialize_context(const Settings& settings) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // Request an OpenGL 3.3 context SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); win = SDL_CreateWindow(settings.title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, settings.width, settings.height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); context = SDL_GL_CreateContext(win); // Enable vsync. SDL_GL_SetSwapInterval(-1); glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != 0) { std::cout << "Failed to intialize Glew\n" << "Error code: " << glewError; exit(1); } std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl; // Setting glewExperimental can cause an "INVALID_ENUM" OpenGL error. Swallow // that error here and carry on. glGetError(); gui::Settings gui_settings; gui_settings.asset_dir = "./resources"; gui_settings.width = settings.width; gui_settings.height = settings.height; gui::Initialize(win, gui_settings); SDL_GL_SwapWindow(win); } void initialize(const Settings& settings) { std::cout << "Initializing rendering context\n"; initialize_context(settings); height = settings.height; width = settings.width; camera.ratio = (float) width / (float) height; camera.fov = settings.fov; camera.znear = settings.znear; camera.zfar = settings.zfar; camera.projection_mat = glm::perspective( glm::radians(camera.fov), camera.ratio, camera.znear, camera.zfar); camera.origin = { 0.0f, 0.0f, 0.0f }; // There's a closed form solution that might be faster, but this is performed // only once here. camera.inv_projection_mat = glm::inverse(camera.projection_mat); camera.from = {0.0f, 0.0f, 750.0f}; camera.to = {0.0f, 0.0f, 0.0f}; camera.rotation_mat = glm::mat4(1.0f); camera.yaw = 0.0f; camera.pitch = 0.0f; // Initialize collections. { std::cout << "Intializing renderables collection\n"; qbComponentAttr attr; qb_componentattr_create(&attr); qb_componentattr_setdatatype(attr, qbRenderable); qb_component_create(&renderables, attr); qb_componentattr_destroy(&attr); } // Initialize systems. { qbSystemAttr attr; qb_systemattr_create(&attr); qb_systemattr_settrigger(attr, qbTrigger::QB_TRIGGER_EVENT); qb_systemattr_setpriority(attr, QB_MIN_PRIORITY); qb_systemattr_addconst(attr, renderables); qb_systemattr_addconst(attr, physics::component()); qb_systemattr_setjoin(attr, qbComponentJoin::QB_JOIN_INNER); qb_systemattr_setfunction(attr, render_event_handler); qb_system_create(&render_system, attr); qb_systemattr_destroy(&attr); } // Initialize events. { qbEventAttr attr; qb_eventattr_create(&attr); qb_eventattr_setmessagesize(attr, sizeof(RenderEvent)); qb_event_create(&render_event, attr); qb_event_subscribe(render_event, render_system); qb_eventattr_destroy(&attr); } std::cout << "Finished initializing render\n"; } void shutdown() { gui::Shutdown(); SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); } int window_height() { return height; } int window_width() { return width; } qbResult qb_camera_setorigin(glm::vec3 new_origin) { camera.origin = new_origin; return QB_OK; } qbResult qb_camera_setposition(glm::vec3 new_position) { glm::vec3 delta = new_position - camera.from; camera.from += delta; camera.to += delta; return QB_OK; } qbResult qb_camera_setyaw(float new_yaw) { camera.yaw = new_yaw; return QB_OK; } qbResult qb_camera_setpitch(float new_pitch) { camera.pitch = new_pitch; return QB_OK; } qbResult qb_camera_incposition(glm::vec3 delta) { camera.from += delta; camera.to += delta; return QB_OK; } qbResult qb_camera_incyaw(float delta) { camera.yaw += delta; return QB_OK; } qbResult qb_camera_incpitch(float delta) { camera.pitch += delta; return QB_OK; } glm::vec3 qb_camera_getposition() { return camera.from; } glm::mat4 qb_camera_getorientation() { return camera.rotation_mat; } glm::mat4 qb_camera_getprojection() { return camera.projection_mat; } glm::mat4 qb_camera_getinvprojection() { return camera.inv_projection_mat; } qbResult qb_camera_screentoworld(glm::vec2 screen, glm::vec3* world) { // NORMALISED DEVICE SPACE double x = 2.0 * screen.x / window_width() - 1; double y = 2.0 * screen.y / window_height() - 1; // HOMOGENEOUS SPACE glm::vec4 screenPos = glm::vec4(x, -y, 1.0f, 1.0f); // Projection/Eye Space glm::mat4 project_view = camera.projection_mat * camera.view_mat; glm::mat4 view_projection_inverse = glm::inverse(project_view); glm::vec4 world_coord = view_projection_inverse * screenPos; world_coord.w = 1.0f / world_coord.w; world_coord.x *= world_coord.w; world_coord.y *= world_coord.w; world_coord.z *= world_coord.w; *world = world_coord; *world = glm::normalize(*world); return QB_OK; } glm::vec3 qb_camera_getorigin() { return camera.origin; } float qb_camera_getyaw() { return camera.yaw; } float qb_camera_getpitch() { return camera.pitch; } float qb_camera_getznear() { return camera.znear; } float qb_camera_getzfar() { return camera.zfar; } qbResult qb_render_makecurrent() { int ret = SDL_GL_MakeCurrent(win, context); if (ret < 0) { std::cout << "SDL_GL_MakeCurrent failed: " << SDL_GetError() << std::endl; } return QB_OK; } qbResult qb_render_makenull() { int ret = SDL_GL_MakeCurrent(win, nullptr); if (ret < 0) { std::cout << "SDL_GL_MakeCurrent failed: " << SDL_GetError() << std::endl; } return QB_OK; } } // namespace render
#include "physics.h" #include "player.h" #include "render.h" #include "shader.h" #include "input.h" #include "planet.h" #include "gui.h" #include <atomic> #include <glm/gtc/matrix_transform.hpp> #define GL3_PROTOTYPES 1 #include <GL/glew.h> #include <stdio.h> #include <stdlib.h> #include <SDL2/SDL.h> #include <SDL2/SDL_opengl.h> namespace render { struct qbRenderable_ { qbMesh mesh; qbMaterial material; }; struct Camera { float ratio; float fov; float znear; float zfar; glm::mat4 view_mat; glm::mat4 projection_mat; glm::mat4 inv_projection_mat; glm::mat4 rotation_mat; glm::vec3 from; glm::vec3 to; glm::vec3 origin; float yaw = 0.0f; float pitch = 0.0f; const glm::vec4 front = { 1.0f, 0.0f, 0.0f, 1.0f }; const glm::vec4 up = { 0.0f, 0.0f, 1.0f, 1.0f }; } camera; // Collections qbComponent renderables; // Channels qbEvent render_event; // Systems qbSystem render_system; int width; int height; SDL_Window *win = nullptr; SDL_GLContext context; qbComponent component() { return renderables; } bool check_for_gl_errors() { GLenum error = glGetError(); if (error == GL_NO_ERROR) { return false; } while (error != GL_NO_ERROR) { const GLubyte* error_str = gluErrorString(error); std::cout << "Error(" << error << "): " << error_str << std::endl; error = glGetError(); } return true; } void render_event_handler(qbInstance* insts, qbFrame* f) { RenderEvent* e = (RenderEvent*)f->event; qbRenderable* renderable; qb_instance_getconst(insts[0], &renderable); physics::Transform* transform; qb_instance_getconst(insts[1], &transform); glm::vec3 v = transform->v * (float)e->alpha; glm::mat4 mvp; glm::mat4 m = glm::translate(glm::mat4(1.0f), transform->p + v); qb_material_use((*renderable)->material); mvp = camera.projection_mat * camera.view_mat * m; qbShader shader = qb_material_getshader((*renderable)->material); qb_shader_setmat4(shader, "uMvp", mvp); qb_mesh_draw((*renderable)->mesh, (*renderable)->material); if (check_for_gl_errors()) { std::cout << "Renderable entity: " << qb_instance_getentity(insts[0]) << "\n"; } } void present(RenderEvent* event) { qb_render_makecurrent(); // Initial rotation matrix. camera.rotation_mat = glm::mat4(1.0f); glm::vec3 look_from = camera.from + camera.origin; glm::vec3 look_to = camera.origin; glm::vec3 direction = glm::normalize(look_from - look_to); glm::vec3 up = camera.up; glm::vec3 right = glm::normalize(glm::cross(up, direction)); up = glm::cross(direction, right); camera.view_mat = glm::lookAt(look_from, look_to, up); glViewport(0, 0, window_width(), window_height()); glCullFace(GL_BACK); glFrontFace(GL_CCW); glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glDepthFunc(GL_LESS); glClearColor(0.1, 0.1, 0.1, 0.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); qb_event_sendsync(render_event, event); gui::Render(); SDL_GL_SwapWindow(win); qb_render_makenull(); } qbRenderable create(qbMesh mesh, qbMaterial material) { return new qbRenderable_{mesh, material}; } void initialize_context(const Settings& settings) { SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS); // Request an OpenGL 3.3 context SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16); win = SDL_CreateWindow(settings.title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, settings.width, settings.height, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); context = SDL_GL_CreateContext(win); // Enable vsync. SDL_GL_SetSwapInterval(-1); glewExperimental = GL_TRUE; GLenum glewError = glewInit(); if (glewError != 0) { std::cout << "Failed to intialize Glew\n" << "Error code: " << glewError; exit(1); } std::cout << "Using OpenGL " << glGetString(GL_VERSION) << std::endl; // Setting glewExperimental can cause an "INVALID_ENUM" OpenGL error. Swallow // that error here and carry on. glGetError(); gui::Settings gui_settings; gui_settings.asset_dir = "resources/"; gui_settings.width = settings.width; gui_settings.height = settings.height; gui::Initialize(win, gui_settings); SDL_GL_SwapWindow(win); } void initialize(const Settings& settings) { std::cout << "Initializing rendering context\n"; initialize_context(settings); height = settings.height; width = settings.width; camera.ratio = (float) width / (float) height; camera.fov = settings.fov; camera.znear = settings.znear; camera.zfar = settings.zfar; camera.projection_mat = glm::perspective( glm::radians(camera.fov), camera.ratio, camera.znear, camera.zfar); camera.origin = { 0.0f, 0.0f, 0.0f }; // There's a closed form solution that might be faster, but this is performed // only once here. camera.inv_projection_mat = glm::inverse(camera.projection_mat); camera.from = {0.0f, 0.0f, 750.0f}; camera.to = {0.0f, 0.0f, 0.0f}; camera.rotation_mat = glm::mat4(1.0f); camera.yaw = 0.0f; camera.pitch = 0.0f; // Initialize collections. { std::cout << "Intializing renderables collection\n"; qbComponentAttr attr; qb_componentattr_create(&attr); qb_componentattr_setdatatype(attr, qbRenderable); qb_component_create(&renderables, attr); qb_componentattr_destroy(&attr); } // Initialize systems. { qbSystemAttr attr; qb_systemattr_create(&attr); qb_systemattr_settrigger(attr, qbTrigger::QB_TRIGGER_EVENT); qb_systemattr_setpriority(attr, QB_MIN_PRIORITY); qb_systemattr_addconst(attr, renderables); qb_systemattr_addconst(attr, physics::component()); qb_systemattr_setjoin(attr, qbComponentJoin::QB_JOIN_INNER); qb_systemattr_setfunction(attr, render_event_handler); qb_system_create(&render_system, attr); qb_systemattr_destroy(&attr); } // Initialize events. { qbEventAttr attr; qb_eventattr_create(&attr); qb_eventattr_setmessagesize(attr, sizeof(RenderEvent)); qb_event_create(&render_event, attr); qb_event_subscribe(render_event, render_system); qb_eventattr_destroy(&attr); } std::cout << "Finished initializing render\n"; } void shutdown() { gui::Shutdown(); SDL_GL_DeleteContext(context); SDL_DestroyWindow(win); } int window_height() { return height; } int window_width() { return width; } qbResult qb_camera_setorigin(glm::vec3 new_origin) { camera.origin = new_origin; return QB_OK; } qbResult qb_camera_setposition(glm::vec3 new_position) { glm::vec3 delta = new_position - camera.from; camera.from += delta; camera.to += delta; return QB_OK; } qbResult qb_camera_setyaw(float new_yaw) { camera.yaw = new_yaw; return QB_OK; } qbResult qb_camera_setpitch(float new_pitch) { camera.pitch = new_pitch; return QB_OK; } qbResult qb_camera_incposition(glm::vec3 delta) { camera.from += delta; camera.to += delta; return QB_OK; } qbResult qb_camera_incyaw(float delta) { camera.yaw += delta; return QB_OK; } qbResult qb_camera_incpitch(float delta) { camera.pitch += delta; return QB_OK; } glm::vec3 qb_camera_getposition() { return camera.from; } glm::mat4 qb_camera_getorientation() { return camera.rotation_mat; } glm::mat4 qb_camera_getprojection() { return camera.projection_mat; } glm::mat4 qb_camera_getinvprojection() { return camera.inv_projection_mat; } qbResult qb_camera_screentoworld(glm::vec2 screen, glm::vec3* world) { // NORMALISED DEVICE SPACE double x = 2.0 * screen.x / window_width() - 1; double y = 2.0 * screen.y / window_height() - 1; // HOMOGENEOUS SPACE glm::vec4 screenPos = glm::vec4(x, -y, 1.0f, 1.0f); // Projection/Eye Space glm::mat4 project_view = camera.projection_mat * camera.view_mat; glm::mat4 view_projection_inverse = glm::inverse(project_view); glm::vec4 world_coord = view_projection_inverse * screenPos; world_coord.w = 1.0f / world_coord.w; world_coord.x *= world_coord.w; world_coord.y *= world_coord.w; world_coord.z *= world_coord.w; *world = world_coord; *world = glm::normalize(*world); return QB_OK; } glm::vec3 qb_camera_getorigin() { return camera.origin; } float qb_camera_getyaw() { return camera.yaw; } float qb_camera_getpitch() { return camera.pitch; } float qb_camera_getznear() { return camera.znear; } float qb_camera_getzfar() { return camera.zfar; } qbResult qb_render_makecurrent() { int ret = SDL_GL_MakeCurrent(win, context); if (ret < 0) { std::cout << "SDL_GL_MakeCurrent failed: " << SDL_GetError() << std::endl; } return QB_OK; } qbResult qb_render_makenull() { int ret = SDL_GL_MakeCurrent(win, nullptr); if (ret < 0) { std::cout << "SDL_GL_MakeCurrent failed: " << SDL_GetError() << std::endl; } return QB_OK; } } // namespace render
Change resources asset dir
Change resources asset dir
C++
apache-2.0
rohdesamuel/cubez,rohdesamuel/cubez,rohdesamuel/cubez,rohdesamuel/cubez
cb15dc7c051be082323b7add3cd39092284efd2e
searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp
searchsummary/src/tests/docsummary/matched_elements_filter/matched_elements_filter_test.cpp
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/document/datatype/documenttype.h> #include <vespa/document/datatype/arraydatatype.h> #include <vespa/document/datatype/mapdatatype.h> #include <vespa/document/fieldvalue/stringfieldvalue.h> #include <vespa/document/fieldvalue/intfieldvalue.h> #include <vespa/document/fieldvalue/rawfieldvalue.h> #include <vespa/document/fieldvalue/arrayfieldvalue.h> #include <vespa/document/fieldvalue/mapfieldvalue.h> #include <vespa/document/fieldvalue//document.h> #include <vespa/searchcommon/attribute/config.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/attribute/attributevector.h> #include <vespa/searchlib/common/matching_elements.h> #include <vespa/searchlib/common/matching_elements_fields.h> #include <vespa/searchsummary/docsummary/docsum_store_document.h> #include <vespa/searchsummary/docsummary/docsumstate.h> #include <vespa/searchsummary/docsummary/idocsumenvironment.h> #include <vespa/searchsummary/docsummary/matched_elements_filter_dfw.h> #include <vespa/searchsummary/docsummary/resultclass.h> #include <vespa/searchsummary/docsummary/resultconfig.h> #include <vespa/searchsummary/docsummary/summaryfieldconverter.h> #include <vespa/searchsummary/test/slime_value.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/vespalib/gtest/gtest.h> #include <vespa/log/log.h> LOG_SETUP("matched_elements_filter_test"); using search::AttributeFactory; using search::AttributeVector; using search::MatchingElements; using search::MatchingElementsFields; using search::attribute::BasicType; using search::attribute::CollectionType; using search::attribute::Config; using search::attribute::IAttributeContext; using search::attribute::IAttributeVector; using search::docsummary::IDocsumStoreDocument; using search::docsummary::DocsumStoreDocument; using search::docsummary::test::SlimeValue; using vespalib::Slime; using namespace document; using namespace search::docsummary; using namespace vespalib::slime; using ElementVector = std::vector<uint32_t>; StructDataType::UP make_struct_elem_type() { auto result = std::make_unique<StructDataType>("elem"); result->addField(Field("name", *DataType::STRING)); result->addField(Field("weight", *DataType::INT)); return result; } constexpr uint32_t class_id = 3; constexpr uint32_t doc_id = 2; class DocsumStore { private: ResultConfig _config; DocumentType _doc_type; StructDataType::UP _elem_type; ArrayDataType _array_type; MapDataType _map_type; StructFieldValue::UP make_elem_value(const std::string& name, int weight) const { auto result = std::make_unique<StructFieldValue>(*_elem_type); result->setValue("name", StringFieldValue(name)); result->setValue("weight", IntFieldValue(weight)); return result; } public: DocsumStore() : _config(), _doc_type("test"), _elem_type(make_struct_elem_type()), _array_type(*_elem_type), _map_type(*DataType::STRING, *_elem_type) { _doc_type.addField(Field("array", _array_type)); _doc_type.addField(Field("map", _map_type)); _doc_type.addField(Field("map2", _map_type)); auto* result_class = _config.AddResultClass("test", class_id); EXPECT_TRUE(result_class->AddConfigEntry("array", ResType::RES_JSONSTRING)); EXPECT_TRUE(result_class->AddConfigEntry("map", ResType::RES_JSONSTRING)); EXPECT_TRUE(result_class->AddConfigEntry("map2", ResType::RES_JSONSTRING)); _config.CreateEnumMaps(); } ~DocsumStore(); const ResultConfig& get_config() const { return _config; } const ResultClass* get_class() const { return _config.LookupResultClass(class_id); } std::unique_ptr<IDocsumStoreDocument> getMappedDocsum() { auto doc = std::make_unique<Document>(_doc_type, DocumentId("id:test:test::0")); { ArrayFieldValue array_value(_array_type); array_value.append(make_elem_value("a", 3)); array_value.append(make_elem_value("b", 5)); array_value.append(make_elem_value("c", 7)); doc->setValue("array", array_value); } { MapFieldValue map_value(_map_type); map_value.put(StringFieldValue("a"), *make_elem_value("a", 3)); map_value.put(StringFieldValue("b"), *make_elem_value("b", 5)); map_value.put(StringFieldValue("c"), *make_elem_value("c", 7)); doc->setValue("map", map_value); } { MapFieldValue map2_value(_map_type); map2_value.put(StringFieldValue("dummy"), *make_elem_value("dummy", 2)); doc->setValue("map2", map2_value); } return std::make_unique<DocsumStoreDocument>(std::move(doc)); } }; DocsumStore::~DocsumStore() = default; class AttributeContext : public IAttributeContext { private: AttributeVector::SP _map_value_name; AttributeVector::SP _map2_key; AttributeVector::SP _array_weight; public: AttributeContext() : _map_value_name(AttributeFactory::createAttribute("map.value.name", Config(BasicType::STRING, CollectionType::ARRAY))), _map2_key(AttributeFactory::createAttribute("map2.key", Config(BasicType::STRING, CollectionType::ARRAY))), _array_weight(AttributeFactory::createAttribute("array.weight", Config(BasicType::INT32, CollectionType::ARRAY))) {} ~AttributeContext() override; const IAttributeVector* getAttribute(const string&) const override { abort(); } const IAttributeVector* getAttributeStableEnum(const string&) const override { abort(); } void getAttributeList(std::vector<const IAttributeVector*>& list) const override { list.push_back(_map_value_name.get()); list.push_back(_map2_key.get()); list.push_back(_array_weight.get()); } void releaseEnumGuards() override { abort(); } void asyncForAttribute(const vespalib::string&, std::unique_ptr<search::attribute::IAttributeFunctor>) const override { abort(); } }; AttributeContext::~AttributeContext() = default; class StateCallback : public GetDocsumsStateCallback { private: std::string _field_name; ElementVector _matching_elements; public: StateCallback(const std::string& field_name, const ElementVector& matching_elements) : _field_name(field_name), _matching_elements(matching_elements) { } ~StateCallback() override; void FillSummaryFeatures(GetDocsumsState&) override {} void FillRankFeatures(GetDocsumsState&) override {} std::unique_ptr<MatchingElements> fill_matching_elements(const MatchingElementsFields&) override { auto result = std::make_unique<MatchingElements>(); result->add_matching_elements(doc_id, _field_name, _matching_elements); return result; } }; StateCallback::~StateCallback() = default; class MatchedElementsFilterTest : public ::testing::Test { private: DocsumStore _doc_store; AttributeContext _attr_ctx; std::shared_ptr<MatchingElementsFields> _fields; Slime run_filter_field_writer(const std::string& input_field_name, const ElementVector& matching_elements) { auto writer = make_field_writer(input_field_name); auto doc = _doc_store.getMappedDocsum(); StateCallback callback(input_field_name, matching_elements); GetDocsumsState state(callback); Slime slime; SlimeInserter inserter(slime); writer->insertField(doc_id, doc.get(), &state, ResType::RES_JSONSTRING, inserter); return slime; } public: MatchedElementsFilterTest() : _doc_store(), _attr_ctx(), _fields(std::make_shared<MatchingElementsFields>()) { } ~MatchedElementsFilterTest() override; std::unique_ptr<DocsumFieldWriter> make_field_writer(const std::string& input_field_name) { return MatchedElementsFilterDFW::create(input_field_name,_attr_ctx, _fields); } void expect_filtered(const std::string& input_field_name, const ElementVector& matching_elements, const std::string& exp_slime_as_json) { Slime act = run_filter_field_writer(input_field_name, matching_elements); SlimeValue exp(exp_slime_as_json); EXPECT_EQ(exp.slime, act); } const MatchingElementsFields& fields() const { return *_fields; } }; MatchedElementsFilterTest::~MatchedElementsFilterTest() = default; TEST_F(MatchedElementsFilterTest, filters_elements_in_array_field_value) { expect_filtered("array", {}, "[]"); expect_filtered("array", {0}, "[{'name':'a','weight':3}]"); expect_filtered("array", {1}, "[{'name':'b','weight':5}]"); expect_filtered("array", {2}, "[{'name':'c','weight':7}]"); expect_filtered("array", {0, 1, 2}, "[{'name':'a','weight':3}," "{'name':'b','weight':5}," "{'name':'c','weight':7}]"); expect_filtered("array", {0, 1, 100}, "[]"); } TEST_F(MatchedElementsFilterTest, matching_elements_fields_is_setup_for_array_field_value) { auto writer = make_field_writer("array"); EXPECT_TRUE(fields().has_field("array")); EXPECT_EQ("", fields().get_enclosing_field("array.name")); EXPECT_EQ("array", fields().get_enclosing_field("array.weight")); } TEST_F(MatchedElementsFilterTest, filters_elements_in_map_field_value) { expect_filtered("map", {}, "[]"); expect_filtered("map", {0}, "[{'key':'a','value':{'name':'a','weight':3}}]"); expect_filtered("map", {1}, "[{'key':'b','value':{'name':'b','weight':5}}]"); expect_filtered("map", {2}, "[{'key':'c','value':{'name':'c','weight':7}}]"); expect_filtered("map", {0, 1, 2}, "[{'key':'a','value':{'name':'a','weight':3}}," "{'key':'b','value':{'name':'b','weight':5}}," "{'key':'c','value':{'name':'c','weight':7}}]"); expect_filtered("map", {0, 1, 100}, "[]"); } TEST_F(MatchedElementsFilterTest, matching_elements_fields_is_setup_for_map_field_value) { { auto writer = make_field_writer("map"); EXPECT_TRUE(fields().has_field("map")); EXPECT_EQ("", fields().get_enclosing_field("map.key")); EXPECT_EQ("map", fields().get_enclosing_field("map.value.name")); EXPECT_EQ("", fields().get_enclosing_field("map.value.weight")); } { auto writer = make_field_writer("map2"); EXPECT_TRUE(fields().has_field("map2")); EXPECT_EQ("map2", fields().get_enclosing_field("map2.key")); EXPECT_EQ("", fields().get_enclosing_field("map2.value.name")); EXPECT_EQ("", fields().get_enclosing_field("map2.value.weight")); } } TEST_F(MatchedElementsFilterTest, field_writer_is_not_generated_as_it_depends_on_data_from_document_store) { auto writer = make_field_writer("array"); EXPECT_FALSE(writer->IsGenerated()); } GTEST_MAIN_RUN_ALL_TESTS()
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/document/datatype/documenttype.h> #include <vespa/document/datatype/arraydatatype.h> #include <vespa/document/datatype/mapdatatype.h> #include <vespa/document/datatype/weightedsetdatatype.h> #include <vespa/document/fieldvalue/stringfieldvalue.h> #include <vespa/document/fieldvalue/intfieldvalue.h> #include <vespa/document/fieldvalue/rawfieldvalue.h> #include <vespa/document/fieldvalue/arrayfieldvalue.h> #include <vespa/document/fieldvalue/mapfieldvalue.h> #include <vespa/document/fieldvalue/weightedsetfieldvalue.h> #include <vespa/document/fieldvalue//document.h> #include <vespa/searchcommon/attribute/config.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/attribute/attributevector.h> #include <vespa/searchlib/common/matching_elements.h> #include <vespa/searchlib/common/matching_elements_fields.h> #include <vespa/searchsummary/docsummary/docsum_store_document.h> #include <vespa/searchsummary/docsummary/docsumstate.h> #include <vespa/searchsummary/docsummary/idocsumenvironment.h> #include <vespa/searchsummary/docsummary/matched_elements_filter_dfw.h> #include <vespa/searchsummary/docsummary/resultclass.h> #include <vespa/searchsummary/docsummary/resultconfig.h> #include <vespa/searchsummary/docsummary/summaryfieldconverter.h> #include <vespa/searchsummary/test/slime_value.h> #include <vespa/vespalib/data/slime/slime.h> #include <vespa/vespalib/gtest/gtest.h> #include <vespa/log/log.h> LOG_SETUP("matched_elements_filter_test"); using search::AttributeFactory; using search::AttributeVector; using search::MatchingElements; using search::MatchingElementsFields; using search::attribute::BasicType; using search::attribute::CollectionType; using search::attribute::Config; using search::attribute::IAttributeContext; using search::attribute::IAttributeVector; using search::docsummary::IDocsumStoreDocument; using search::docsummary::DocsumStoreDocument; using search::docsummary::test::SlimeValue; using vespalib::Slime; using namespace document; using namespace search::docsummary; using namespace vespalib::slime; using ElementVector = std::vector<uint32_t>; StructDataType::UP make_struct_elem_type() { auto result = std::make_unique<StructDataType>("elem"); result->addField(Field("name", *DataType::STRING)); result->addField(Field("weight", *DataType::INT)); return result; } constexpr uint32_t class_id = 3; constexpr uint32_t doc_id = 2; class DocsumStore { private: ResultConfig _config; DocumentType _doc_type; StructDataType::UP _elem_type; ArrayDataType _array_type; MapDataType _map_type; WeightedSetDataType _wset_type; StructFieldValue::UP make_elem_value(const std::string& name, int weight) const { auto result = std::make_unique<StructFieldValue>(*_elem_type); result->setValue("name", StringFieldValue(name)); result->setValue("weight", IntFieldValue(weight)); return result; } public: DocsumStore() : _config(), _doc_type("test"), _elem_type(make_struct_elem_type()), _array_type(*_elem_type), _map_type(*DataType::STRING, *_elem_type), _wset_type(*DataType::STRING, false, false) { _doc_type.addField(Field("array", _array_type)); _doc_type.addField(Field("map", _map_type)); _doc_type.addField(Field("map2", _map_type)); _doc_type.addField(Field("wset", _wset_type)); auto* result_class = _config.AddResultClass("test", class_id); EXPECT_TRUE(result_class->AddConfigEntry("array", ResType::RES_JSONSTRING)); EXPECT_TRUE(result_class->AddConfigEntry("map", ResType::RES_JSONSTRING)); EXPECT_TRUE(result_class->AddConfigEntry("map2", ResType::RES_JSONSTRING)); _config.CreateEnumMaps(); } ~DocsumStore(); const ResultConfig& get_config() const { return _config; } const ResultClass* get_class() const { return _config.LookupResultClass(class_id); } std::unique_ptr<IDocsumStoreDocument> getMappedDocsum() { auto doc = std::make_unique<Document>(_doc_type, DocumentId("id:test:test::0")); { ArrayFieldValue array_value(_array_type); array_value.append(make_elem_value("a", 3)); array_value.append(make_elem_value("b", 5)); array_value.append(make_elem_value("c", 7)); doc->setValue("array", array_value); } { MapFieldValue map_value(_map_type); map_value.put(StringFieldValue("a"), *make_elem_value("a", 3)); map_value.put(StringFieldValue("b"), *make_elem_value("b", 5)); map_value.put(StringFieldValue("c"), *make_elem_value("c", 7)); doc->setValue("map", map_value); } { MapFieldValue map2_value(_map_type); map2_value.put(StringFieldValue("dummy"), *make_elem_value("dummy", 2)); doc->setValue("map2", map2_value); } { WeightedSetFieldValue wset_value(_wset_type); wset_value.add(StringFieldValue("a"), 13); wset_value.add(StringFieldValue("b"), 15); wset_value.add(StringFieldValue("c"), 17); doc->setValue("wset", wset_value); } return std::make_unique<DocsumStoreDocument>(std::move(doc)); } }; DocsumStore::~DocsumStore() = default; class AttributeContext : public IAttributeContext { private: AttributeVector::SP _map_value_name; AttributeVector::SP _map2_key; AttributeVector::SP _array_weight; public: AttributeContext() : _map_value_name(AttributeFactory::createAttribute("map.value.name", Config(BasicType::STRING, CollectionType::ARRAY))), _map2_key(AttributeFactory::createAttribute("map2.key", Config(BasicType::STRING, CollectionType::ARRAY))), _array_weight(AttributeFactory::createAttribute("array.weight", Config(BasicType::INT32, CollectionType::ARRAY))) {} ~AttributeContext() override; const IAttributeVector* getAttribute(const string&) const override { abort(); } const IAttributeVector* getAttributeStableEnum(const string&) const override { abort(); } void getAttributeList(std::vector<const IAttributeVector*>& list) const override { list.push_back(_map_value_name.get()); list.push_back(_map2_key.get()); list.push_back(_array_weight.get()); } void releaseEnumGuards() override { abort(); } void asyncForAttribute(const vespalib::string&, std::unique_ptr<search::attribute::IAttributeFunctor>) const override { abort(); } }; AttributeContext::~AttributeContext() = default; class StateCallback : public GetDocsumsStateCallback { private: std::string _field_name; ElementVector _matching_elements; public: StateCallback(const std::string& field_name, const ElementVector& matching_elements) : _field_name(field_name), _matching_elements(matching_elements) { } ~StateCallback() override; void FillSummaryFeatures(GetDocsumsState&) override {} void FillRankFeatures(GetDocsumsState&) override {} std::unique_ptr<MatchingElements> fill_matching_elements(const MatchingElementsFields&) override { auto result = std::make_unique<MatchingElements>(); result->add_matching_elements(doc_id, _field_name, _matching_elements); return result; } }; StateCallback::~StateCallback() = default; class MatchedElementsFilterTest : public ::testing::Test { private: DocsumStore _doc_store; AttributeContext _attr_ctx; std::shared_ptr<MatchingElementsFields> _fields; Slime run_filter_field_writer(const std::string& input_field_name, const ElementVector& matching_elements) { auto writer = make_field_writer(input_field_name); auto doc = _doc_store.getMappedDocsum(); StateCallback callback(input_field_name, matching_elements); GetDocsumsState state(callback); Slime slime; SlimeInserter inserter(slime); writer->insertField(doc_id, doc.get(), &state, ResType::RES_JSONSTRING, inserter); return slime; } public: MatchedElementsFilterTest() : _doc_store(), _attr_ctx(), _fields(std::make_shared<MatchingElementsFields>()) { } ~MatchedElementsFilterTest() override; std::unique_ptr<DocsumFieldWriter> make_field_writer(const std::string& input_field_name) { return MatchedElementsFilterDFW::create(input_field_name,_attr_ctx, _fields); } void expect_filtered(const std::string& input_field_name, const ElementVector& matching_elements, const std::string& exp_slime_as_json) { Slime act = run_filter_field_writer(input_field_name, matching_elements); SlimeValue exp(exp_slime_as_json); EXPECT_EQ(exp.slime, act); } const MatchingElementsFields& fields() const { return *_fields; } }; MatchedElementsFilterTest::~MatchedElementsFilterTest() = default; TEST_F(MatchedElementsFilterTest, filters_elements_in_array_field_value) { expect_filtered("array", {}, "[]"); expect_filtered("array", {0}, "[{'name':'a','weight':3}]"); expect_filtered("array", {1}, "[{'name':'b','weight':5}]"); expect_filtered("array", {2}, "[{'name':'c','weight':7}]"); expect_filtered("array", {0, 1, 2}, "[{'name':'a','weight':3}," "{'name':'b','weight':5}," "{'name':'c','weight':7}]"); expect_filtered("array", {0, 1, 100}, "[]"); } TEST_F(MatchedElementsFilterTest, matching_elements_fields_is_setup_for_array_field_value) { auto writer = make_field_writer("array"); EXPECT_TRUE(fields().has_field("array")); EXPECT_EQ("", fields().get_enclosing_field("array.name")); EXPECT_EQ("array", fields().get_enclosing_field("array.weight")); } TEST_F(MatchedElementsFilterTest, filters_elements_in_map_field_value) { expect_filtered("map", {}, "[]"); expect_filtered("map", {0}, "[{'key':'a','value':{'name':'a','weight':3}}]"); expect_filtered("map", {1}, "[{'key':'b','value':{'name':'b','weight':5}}]"); expect_filtered("map", {2}, "[{'key':'c','value':{'name':'c','weight':7}}]"); expect_filtered("map", {0, 1, 2}, "[{'key':'a','value':{'name':'a','weight':3}}," "{'key':'b','value':{'name':'b','weight':5}}," "{'key':'c','value':{'name':'c','weight':7}}]"); expect_filtered("map", {0, 1, 100}, "[]"); } TEST_F(MatchedElementsFilterTest, filter_elements_in_weighed_set_field_value) { expect_filtered("wset", {}, "[]"); expect_filtered("wset", {0}, "[{'item':'a','weight':13}]"); expect_filtered("wset", {1}, "[{'item':'b','weight':15}]"); expect_filtered("wset", {2}, "[{'item':'c','weight':17}]"); expect_filtered("wset", {0, 1, 2}, "[{'item':'a','weight':13},{'item':'b','weight':15},{'item':'c','weight':17}]"); expect_filtered("wset", {0, 1, 100}, "[]"); } TEST_F(MatchedElementsFilterTest, matching_elements_fields_is_setup_for_map_field_value) { { auto writer = make_field_writer("map"); EXPECT_TRUE(fields().has_field("map")); EXPECT_EQ("", fields().get_enclosing_field("map.key")); EXPECT_EQ("map", fields().get_enclosing_field("map.value.name")); EXPECT_EQ("", fields().get_enclosing_field("map.value.weight")); } { auto writer = make_field_writer("map2"); EXPECT_TRUE(fields().has_field("map2")); EXPECT_EQ("map2", fields().get_enclosing_field("map2.key")); EXPECT_EQ("", fields().get_enclosing_field("map2.value.name")); EXPECT_EQ("", fields().get_enclosing_field("map2.value.weight")); } } TEST_F(MatchedElementsFilterTest, field_writer_is_not_generated_as_it_depends_on_data_from_document_store) { auto writer = make_field_writer("array"); EXPECT_FALSE(writer->IsGenerated()); } GTEST_MAIN_RUN_ALL_TESTS()
Extend matched elements filter unit test to test weighted set.
Extend matched elements filter unit test to test weighted set.
C++
apache-2.0
vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa,vespa-engine/vespa
ca9945366df595470807cbb8b3b5da0b8bc608f9
tests/test_solver1.cpp
tests/test_solver1.cpp
#include <vector> #include <iostream> #include <iterator> #include <Spark/SparseLinearSolvers.hpp> #include <dfesnippets/blas/Blas.hpp> #include <Eigen/Sparse> using Td = Eigen::Triplet<double>; using Md = Eigen::SparseMatrix<double>; Md one(int m) { std::vector<Td> nnzs; for (int i = 0; i < m; i++) nnzs.push_back(Td(i, i, 1)); Md a(m, m); a.setFromTriplets(nnzs.begin(), nnzs.end()); return a; } // functor to generate a matrix struct IdentityGenerator { Md operator()(int m) { return one(m); } }; struct RandomGenerator { Md operator()(int m) { return one(m) * 2; } }; template<typename MatrixGenerator> void test(int m, MatrixGenerator mg) { Md a = mg(m); Eigen::VectorXd x(m); for (int i = 0; i < m; i++) x[i] = i; Eigen::VectorXd b = a * x; // solve with well known solver spark::sparse_linear_solvers::EigenSolver es; // es.solve(a); std::cout << a << std::endl; std::cout << x << std::endl; std::cout << b << std::endl; std::vector<double> sol(m); std::vector<double> newb(b.data(), b.data() + b.size()); es.solve(a, &sol[0], &newb[0]); std::cout << "Solution: " << std::endl; std::copy(sol.begin(), sol.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; // TODO run and test FPGA implementation } int main() { test<IdentityGenerator>(10, IdentityGenerator{}); test<RandomGenerator>(100, RandomGenerator{}); }
#include <vector> #include <iostream> #include <iterator> #include <Spark/SparseLinearSolvers.hpp> #include <dfesnippets/blas/Blas.hpp> #include <Eigen/Sparse> using Td = Eigen::Triplet<double>; using Md = Eigen::SparseMatrix<double>; Md one(int m) { std::vector<Td> nnzs; for (int i = 0; i < m; i++) nnzs.push_back(Td(i, i, 1)); Md a(m, m); a.setFromTriplets(nnzs.begin(), nnzs.end()); return a; } // functor to generate a matrix struct IdentityGenerator { Md operator()(int m) { return one(m); } }; struct RandomGenerator { Md operator()(int m) { return one(m) * 2; } }; template<typename MatrixGenerator> void test(int m, MatrixGenerator mg) { Md a = mg(m); Eigen::VectorXd x(m); for (int i = 0; i < m; i++) x[i] = i; Eigen::VectorXd b = a * x; // solve with well known solver spark::sparse_linear_solvers::EigenSolver es; // es.solve(a); std::cout << a << std::endl; std::cout << x << std::endl; std::cout << b << std::endl; std::vector<double> sol(m); std::vector<double> newb(b.data(), b.data() + b.size()); es.solve(a, &sol[0], &newb[0]); std::cout << "Solution: " << std::endl; std::copy(sol.begin(), sol.end(), std::ostream_iterator<double>{std::cout, " "}); std::cout << std::endl; // TODO run and test FPGA implementation } int main() { test(10, IdentityGenerator{}); test(100, RandomGenerator{}); }
Remove unused template argument.
Remove unused template argument.
C++
mit
caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask,caskorg/cask
86c363dc9c3e21c4fe53d737b4d7efbbeccdeeb2
code/ylikuutio/ontology/compute_task.cpp
code/ylikuutio/ontology/compute_task.cpp
// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "compute_task.hpp" #include "universe.hpp" #include "shader.hpp" #include "code/ylikuutio/callback/callback_engine.hpp" #include "code/ylikuutio/common/datatype.hpp" #include "code/ylikuutio/common/any_value.hpp" #include "code/ylikuutio/opengl/opengl.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iomanip> // std::setfill, std::setw #include <ios> // std::defaultfloat, std::dec, std::fixed, std::hex, std::ios #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <sstream> // std::istringstream, std::ostringstream, std::stringstream #include <stdint.h> // uint32_t etc. #include <utility> // std::swap etc. #include <variant> // std::variant namespace yli { namespace ontology { class Entity; void ComputeTask::bind_to_parent() { // Requirements: // `this->parent` must not be `nullptr`. yli::ontology::Shader* const shader = this->parent; if (shader == nullptr) { std::cerr << "ERROR: `ComputeTask::bind_to_parent`: `shader` is `nullptr`!\n"; return; } // Get `childID` from `Shader` and set pointer to this `ComputeTask`. shader->parent_of_compute_tasks.bind_child(this); } ComputeTask::~ComputeTask() { // destructor. // // Requirements: // `this->parent` must not be `nullptr`. if (this->is_texture_loaded) { // Cleanup buffers and texture. glDeleteBuffers(1, &this->vertexbuffer); glDeleteBuffers(1, &this->uvbuffer); glDeleteTextures(1, &this->source_texture); } if (this->is_framebuffer_initialized) { glDeleteTextures(1, &this->target_texture); glDeleteFramebuffers(1, &this->framebuffer); } if (this->parent == nullptr) { return; } this->parent->parent_of_compute_tasks.unbind_child(this->childID); } void ComputeTask::render() { if (!this->is_texture_loaded) { // Do not render anything if texture is not loaded. return; } this->prerender(); if (this->is_ready) { // If `ComputeTask` is ready, it does not need to be rendered. this->postrender(); return; } if (!this->is_framebuffer_initialized) { // Create an FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); } // Bind the offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); if (!this->is_framebuffer_initialized) { // Create a target texture. glGenTextures(1, &this->target_texture); glBindTexture(GL_TEXTURE_2D, this->target_texture); // Define the texture. if (internal_format == GL_INVALID_ENUM) { // Internal format not defined, use format as internal format. glTexImage2D( GL_TEXTURE_2D, 0, this->format, this->texture_width, this->texture_height, 0, this->format, this->type, NULL); } else { // Internal format is defined. glTexImage2D( GL_TEXTURE_2D, 0, this->internal_format, this->texture_width, this->texture_height, 0, this->format, this->type, NULL); } yli::opengl::set_nearest_filtering_parameters(); // Attach the texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); // Set background color for the framebuffer. this->universe->set_opengl_background_color(); this->is_framebuffer_initialized = true; } // Clear the framebuffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Adjust viewport for the framebuffer. glViewport(0, 0, this->texture_width, this->texture_height); for (std::size_t iteration_i = 0; iteration_i < n_max_iterations; iteration_i++) { if (this->end_condition_callback_engine != nullptr) { const std::shared_ptr<yli::common::AnyValue> end_condition_any_value = this->end_condition_callback_engine->execute(nullptr); if (end_condition_any_value->type == yli::common::Datatype::BOOL && std::get<bool>(end_condition_any_value->data)) { break; // End condition was satisfied. Therefore, no more iterations. } } // Update the value of `uniform` variable `iteration_i`. yli::opengl::uniform_1i(this->iteration_i_uniform_ID, iteration_i); this->preiterate(); // Bind our texture in Texture Unit 0. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->source_texture); // Set our "texture_sampler" sampler to use Texture Unit 0. yli::opengl::uniform_1i(this->openGL_textureID, 0); // 1st attribute buffer: vertices. yli::opengl::enable_vertex_attrib_array(this->vertex_position_modelspaceID); // 2nd attribute buffer: UVs. yli::opengl::enable_vertex_attrib_array(this->vertexUVID); // 1st attribute buffer: vertices. glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer); glVertexAttribPointer( this->vertex_position_modelspaceID, // The attribute we want to configure 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // 2nd attribute buffer: UVs. glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer); glVertexAttribPointer( this->vertexUVID, // The attribute we want to configure 2, // size : U+V => 2 GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // Draw the triangles! glDrawArrays(GL_TRIANGLE_STRIP, 0, this->vertices_size); // draw 2 triangles (6 vertices, no VBO indexing). yli::opengl::disable_vertex_attrib_array(this->vertex_position_modelspaceID); yli::opengl::disable_vertex_attrib_array(this->vertexUVID); if (this->should_ylikuutio_save_intermediate_results && !this->output_filename.empty()) { std::stringstream filename_stringstream; filename_stringstream << this->output_filename << "_" << std::setfill('0') << std::setw(this->n_index_characters) << iteration_i; // Transfer data from the GPU texture to a CPU array and save into a file. if (this->output_format == GL_INVALID_ENUM) { // Output format not defined, use format as output format. yli::opengl::save_data_from_gpu_texture_into_file( this->format, this->type, this->texture_width, this->texture_height, this->texture_depth, filename_stringstream.str(), this->should_ylikuutio_flip_texture); } else { // Output format is defined. yli::opengl::save_data_from_gpu_texture_into_file( this->output_format, this->type, this->texture_width, this->texture_height, this->texture_depth, filename_stringstream.str(), this->should_ylikuutio_flip_texture); } } // Ping pong. std::swap(this->source_texture, this->target_texture); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); GLenum error; while (true) { error = glGetError(); if (error == GL_NO_ERROR) { break; } std::stringstream opengl_error_stringstream; opengl_error_stringstream << "OpenGL error: 0x" << std::setfill('0') << std::setw(4) << std::hex << error << "\n"; std::cout << opengl_error_stringstream.str(); } this->postiterate(); } // Ping pong once more, so that last output target texture gets saved to file. std::swap(this->source_texture, this->target_texture); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); // Transfer data from the GPU texture to a CPU array and save into a file. if (this->output_format == GL_INVALID_ENUM) { // Output format not defined, use format as output format. yli::opengl::save_data_from_gpu_texture_into_file( this->format, this->type, this->texture_width, this->texture_height, this->texture_depth, this->output_filename, this->should_ylikuutio_flip_texture); } else { // Output format is defined. yli::opengl::save_data_from_gpu_texture_into_file( this->output_format, this->type, this->texture_width, this->texture_height, this->texture_depth, this->output_filename, this->should_ylikuutio_flip_texture); } universe->restore_onscreen_rendering(); this->is_ready = true; this->postrender(); } yli::ontology::Entity* ComputeTask::get_parent() const { return this->parent; } std::size_t ComputeTask::get_number_of_children() const { return 0; // `ComputeTask` has no children. } std::size_t ComputeTask::get_number_of_descendants() const { return 0; // `ComputeTask` has no children. } void ComputeTask::preiterate() const { // Requirements: // `this->preiterate_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. // `this->universe->setting_master` must not be `nullptr`. if (this->preiterate_callback != nullptr && this->universe != nullptr && this->universe->get_setting_master() != nullptr) { this->preiterate_callback(this->universe, this->universe->get_setting_master()); } } void ComputeTask::postiterate() const { // Requirements: // `this->postiterate_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. // `this->universe->setting_master` must not be `nullptr`. if (this->postiterate_callback != nullptr && this->universe != nullptr && this->universe->get_setting_master() != nullptr) { this->postiterate_callback(this->universe, this->universe->get_setting_master()); } } } }
// Ylikuutio - A 3D game and simulation engine. // // Copyright (C) 2015-2020 Antti Nuortimo. // // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. #include "compute_task.hpp" #include "universe.hpp" #include "shader.hpp" #include "code/ylikuutio/callback/callback_engine.hpp" #include "code/ylikuutio/common/any_value.hpp" #include "code/ylikuutio/opengl/opengl.hpp" // Include GLEW #include "code/ylikuutio/opengl/ylikuutio_glew.hpp" // GLfloat, GLuint etc. // Include standard headers #include <cstddef> // std::size_t #include <iomanip> // std::setfill, std::setw #include <ios> // std::defaultfloat, std::dec, std::fixed, std::hex, std::ios #include <iostream> // std::cout, std::cin, std::cerr #include <memory> // std::make_shared, std::shared_ptr #include <sstream> // std::istringstream, std::ostringstream, std::stringstream #include <stdint.h> // uint32_t etc. #include <utility> // std::swap etc. #include <variant> // std::variant namespace yli { namespace ontology { class Entity; void ComputeTask::bind_to_parent() { // Requirements: // `this->parent` must not be `nullptr`. yli::ontology::Shader* const shader = this->parent; if (shader == nullptr) { std::cerr << "ERROR: `ComputeTask::bind_to_parent`: `shader` is `nullptr`!\n"; return; } // Get `childID` from `Shader` and set pointer to this `ComputeTask`. shader->parent_of_compute_tasks.bind_child(this); } ComputeTask::~ComputeTask() { // destructor. // // Requirements: // `this->parent` must not be `nullptr`. if (this->is_texture_loaded) { // Cleanup buffers and texture. glDeleteBuffers(1, &this->vertexbuffer); glDeleteBuffers(1, &this->uvbuffer); glDeleteTextures(1, &this->source_texture); } if (this->is_framebuffer_initialized) { glDeleteTextures(1, &this->target_texture); glDeleteFramebuffers(1, &this->framebuffer); } if (this->parent == nullptr) { return; } this->parent->parent_of_compute_tasks.unbind_child(this->childID); } void ComputeTask::render() { if (!this->is_texture_loaded) { // Do not render anything if texture is not loaded. return; } this->prerender(); if (this->is_ready) { // If `ComputeTask` is ready, it does not need to be rendered. this->postrender(); return; } if (!this->is_framebuffer_initialized) { // Create an FBO (off-screen framebuffer object). glGenFramebuffers(1, &this->framebuffer); } // Bind the offscreen buffer. glBindFramebuffer(GL_FRAMEBUFFER, this->framebuffer); if (!this->is_framebuffer_initialized) { // Create a target texture. glGenTextures(1, &this->target_texture); glBindTexture(GL_TEXTURE_2D, this->target_texture); // Define the texture. if (internal_format == GL_INVALID_ENUM) { // Internal format not defined, use format as internal format. glTexImage2D( GL_TEXTURE_2D, 0, this->format, this->texture_width, this->texture_height, 0, this->format, this->type, NULL); } else { // Internal format is defined. glTexImage2D( GL_TEXTURE_2D, 0, this->internal_format, this->texture_width, this->texture_height, 0, this->format, this->type, NULL); } yli::opengl::set_nearest_filtering_parameters(); // Attach the texture. glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); // Set background color for the framebuffer. this->universe->set_opengl_background_color(); this->is_framebuffer_initialized = true; } // Clear the framebuffer. glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Adjust viewport for the framebuffer. glViewport(0, 0, this->texture_width, this->texture_height); for (std::size_t iteration_i = 0; iteration_i < n_max_iterations; iteration_i++) { if (this->end_condition_callback_engine != nullptr) { const std::shared_ptr<yli::common::AnyValue> end_condition_any_value = this->end_condition_callback_engine->execute(nullptr); if (std::holds_alternative<bool>(end_condition_any_value->data) && std::get<bool>(end_condition_any_value->data)) { break; // End condition was satisfied. Therefore, no more iterations. } } // Update the value of `uniform` variable `iteration_i`. yli::opengl::uniform_1i(this->iteration_i_uniform_ID, iteration_i); this->preiterate(); // Bind our texture in Texture Unit 0. glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, this->source_texture); // Set our "texture_sampler" sampler to use Texture Unit 0. yli::opengl::uniform_1i(this->openGL_textureID, 0); // 1st attribute buffer: vertices. yli::opengl::enable_vertex_attrib_array(this->vertex_position_modelspaceID); // 2nd attribute buffer: UVs. yli::opengl::enable_vertex_attrib_array(this->vertexUVID); // 1st attribute buffer: vertices. glBindBuffer(GL_ARRAY_BUFFER, this->vertexbuffer); glVertexAttribPointer( this->vertex_position_modelspaceID, // The attribute we want to configure 2, // size GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // 2nd attribute buffer: UVs. glBindBuffer(GL_ARRAY_BUFFER, this->uvbuffer); glVertexAttribPointer( this->vertexUVID, // The attribute we want to configure 2, // size : U+V => 2 GL_FLOAT, // type GL_FALSE, // normalized? 0, // stride (void*) 0 // array buffer offset ); // Draw the triangles! glDrawArrays(GL_TRIANGLE_STRIP, 0, this->vertices_size); // draw 2 triangles (6 vertices, no VBO indexing). yli::opengl::disable_vertex_attrib_array(this->vertex_position_modelspaceID); yli::opengl::disable_vertex_attrib_array(this->vertexUVID); if (this->should_ylikuutio_save_intermediate_results && !this->output_filename.empty()) { std::stringstream filename_stringstream; filename_stringstream << this->output_filename << "_" << std::setfill('0') << std::setw(this->n_index_characters) << iteration_i; // Transfer data from the GPU texture to a CPU array and save into a file. if (this->output_format == GL_INVALID_ENUM) { // Output format not defined, use format as output format. yli::opengl::save_data_from_gpu_texture_into_file( this->format, this->type, this->texture_width, this->texture_height, this->texture_depth, filename_stringstream.str(), this->should_ylikuutio_flip_texture); } else { // Output format is defined. yli::opengl::save_data_from_gpu_texture_into_file( this->output_format, this->type, this->texture_width, this->texture_height, this->texture_depth, filename_stringstream.str(), this->should_ylikuutio_flip_texture); } } // Ping pong. std::swap(this->source_texture, this->target_texture); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); GLenum error; while (true) { error = glGetError(); if (error == GL_NO_ERROR) { break; } std::stringstream opengl_error_stringstream; opengl_error_stringstream << "OpenGL error: 0x" << std::setfill('0') << std::setw(4) << std::hex << error << "\n"; std::cout << opengl_error_stringstream.str(); } this->postiterate(); } // Ping pong once more, so that last output target texture gets saved to file. std::swap(this->source_texture, this->target_texture); glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->target_texture, 0); // Transfer data from the GPU texture to a CPU array and save into a file. if (this->output_format == GL_INVALID_ENUM) { // Output format not defined, use format as output format. yli::opengl::save_data_from_gpu_texture_into_file( this->format, this->type, this->texture_width, this->texture_height, this->texture_depth, this->output_filename, this->should_ylikuutio_flip_texture); } else { // Output format is defined. yli::opengl::save_data_from_gpu_texture_into_file( this->output_format, this->type, this->texture_width, this->texture_height, this->texture_depth, this->output_filename, this->should_ylikuutio_flip_texture); } universe->restore_onscreen_rendering(); this->is_ready = true; this->postrender(); } yli::ontology::Entity* ComputeTask::get_parent() const { return this->parent; } std::size_t ComputeTask::get_number_of_children() const { return 0; // `ComputeTask` has no children. } std::size_t ComputeTask::get_number_of_descendants() const { return 0; // `ComputeTask` has no children. } void ComputeTask::preiterate() const { // Requirements: // `this->preiterate_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. // `this->universe->setting_master` must not be `nullptr`. if (this->preiterate_callback != nullptr && this->universe != nullptr && this->universe->get_setting_master() != nullptr) { this->preiterate_callback(this->universe, this->universe->get_setting_master()); } } void ComputeTask::postiterate() const { // Requirements: // `this->postiterate_callback` must not be `nullptr`. // `this->universe` must not be `nullptr`. // `this->universe->setting_master` must not be `nullptr`. if (this->postiterate_callback != nullptr && this->universe != nullptr && this->universe->get_setting_master() != nullptr) { this->postiterate_callback(this->universe, this->universe->get_setting_master()); } } } }
use `std::holds_alternative`.
`ComputeTask::render`: use `std::holds_alternative`.
C++
agpl-3.0
nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio,nrz/ylikuutio
667577b6450008601d1b4b6df79cfb6a0902793b
Source/Task/WaitTimer_win32.cpp
Source/Task/WaitTimer_win32.cpp
#include "pch.h" #include "WaitTimer.h" class WaitTimerImpl { public: WaitTimerImpl() : m_timer(nullptr) {} ~WaitTimerImpl() { if (m_timer != nullptr) { SetThreadpoolTimer(m_timer, nullptr, 0, 0); WaitForThreadpoolTimerCallbacks(m_timer, TRUE); CloseThreadpoolTimer(m_timer); } } HRESULT Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) { m_context = context; m_callback = callback; m_timer = CreateThreadpoolTimer(WaitCallback, this, nullptr); RETURN_LAST_ERROR_IF_NULL(m_timer); return S_OK; } void Start(_In_ uint64_t absoluteTime) { LARGE_INTEGER li; FILETIME ft; ASSERT((absoluteTime & 0x8000000000000000) == 0); li.QuadPart = static_cast<LONGLONG>(absoluteTime); ft.dwHighDateTime = li.HighPart; ft.dwLowDateTime = li.LowPart; SetThreadpoolTimer(m_timer, &ft, 0, 0); } void Cancel() { SetThreadpoolTimer(m_timer, nullptr, 0, 0); } private: PTP_TIMER m_timer; void* m_context; WaitTimerCallback* m_callback; static VOID CALLBACK WaitCallback( _Inout_ PTP_CALLBACK_INSTANCE, _Inout_opt_ void* context, _Inout_ PTP_TIMER) { if (context != nullptr) { WaitTimerImpl* pthis = static_cast<WaitTimerImpl*>(context); pthis->m_callback(pthis->m_context); } } }; WaitTimer::WaitTimer() noexcept : m_impl(nullptr) {} WaitTimer::~WaitTimer() noexcept { if (m_impl != nullptr) { delete m_impl; } } HRESULT WaitTimer::Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) noexcept { if (m_impl != nullptr || callback == nullptr) { ASSERT(FALSE); return E_UNEXPECTED; } std::unique_ptr<WaitTimerImpl> timer(new (std::nothrow) WaitTimerImpl); RETURN_IF_NULL_ALLOC(timer.get()); RETURN_IF_FAILED(timer->Initialize(context, callback)); m_impl = timer.release(); return S_OK; } void WaitTimer::Start(_In_ uint64_t absoluteTime) noexcept { m_impl->Start(absoluteTime); } void WaitTimer::Cancel() noexcept { m_impl->Cancel(); } uint64_t WaitTimer::GetAbsoluteTime(_In_ uint32_t msFromNow) noexcept { FILETIME ft; LARGE_INTEGER li; GetSystemTimeAsFileTime(&ft); ASSERT((ft.dwHighDateTime & 0x80000000) == 0); li.HighPart = ft.dwHighDateTime; li.LowPart = ft.dwLowDateTime; li.QuadPart += (msFromNow * 10000); return li.QuadPart; }
#include "pch.h" #include "WaitTimer.h" class WaitTimerImpl { public: WaitTimerImpl() : m_timer(nullptr) {} ~WaitTimerImpl() { if (m_timer != nullptr) { SetThreadpoolTimer(m_timer, nullptr, 0, 0); WaitForThreadpoolTimerCallbacks(m_timer, TRUE); CloseThreadpoolTimer(m_timer); } } HRESULT Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) { m_context = context; m_callback = callback; m_timer = CreateThreadpoolTimer(WaitCallback, this, nullptr); RETURN_LAST_ERROR_IF_NULL(m_timer); return S_OK; } void Start(_In_ uint64_t absoluteTime) { LARGE_INTEGER li; FILETIME ft; ASSERT((absoluteTime & 0x8000000000000000) == 0); li.QuadPart = static_cast<LONGLONG>(absoluteTime); ft.dwHighDateTime = li.HighPart; ft.dwLowDateTime = li.LowPart; SetThreadpoolTimer(m_timer, &ft, 0, 0); } void Cancel() { SetThreadpoolTimer(m_timer, nullptr, 0, 0); } private: PTP_TIMER m_timer; void* m_context; WaitTimerCallback* m_callback; static VOID CALLBACK WaitCallback( _Inout_ PTP_CALLBACK_INSTANCE, _Inout_opt_ void* context, _Inout_ PTP_TIMER) { if (context != nullptr) { WaitTimerImpl* pthis = static_cast<WaitTimerImpl*>(context); pthis->m_callback(pthis->m_context); } } }; WaitTimer::WaitTimer() noexcept : m_impl(nullptr) {} WaitTimer::~WaitTimer() noexcept { if (m_impl != nullptr) { delete m_impl; } } HRESULT WaitTimer::Initialize(_In_opt_ void* context, _In_ WaitTimerCallback* callback) noexcept { if (m_impl != nullptr || callback == nullptr) { ASSERT(FALSE); return E_UNEXPECTED; } std::unique_ptr<WaitTimerImpl> timer(new (std::nothrow) WaitTimerImpl); RETURN_IF_NULL_ALLOC(timer.get()); RETURN_IF_FAILED(timer->Initialize(context, callback)); m_impl = timer.release(); return S_OK; } void WaitTimer::Start(_In_ uint64_t absoluteTime) noexcept { m_impl->Start(absoluteTime); } void WaitTimer::Cancel() noexcept { m_impl->Cancel(); } uint64_t WaitTimer::GetAbsoluteTime(_In_ uint32_t msFromNow) noexcept { FILETIME ft; ULARGE_INTEGER li; GetSystemTimeAsFileTime(&ft); ASSERT((ft.dwHighDateTime & 0x80000000) == 0); uint64_t hundredNanosFromNow = msFromNow; hundredNanosFromNow *= 10000ULL; li.HighPart = ft.dwHighDateTime; li.LowPart = ft.dwLowDateTime; li.QuadPart += hundredNanosFromNow; return li.QuadPart; }
Fix overflow in timer (#419)
Fix overflow in timer (#419)
C++
mit
lubeltra/libHttpClient,lubeltra/libHttpClient,jasonsandlin/libHttpClient,jasonsandlin/libHttpClient,lubeltra/libHttpClient,jasonsandlin/libHttpClient,jasonsandlin/libHttpClient,lubeltra/libHttpClient,jasonsandlin/libHttpClient,lubeltra/libHttpClient
9341ff0feb67582df10f16d685db5d34a5c4160d
interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp
interpreter/cling/lib/Interpreter/InterpreterCallbacks.cpp
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/DynamicLookupExternalSemaSource.h" #include "cling/Interpreter/Interpreter.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { // pin the vtable here InterpreterExternalSemaSource::~InterpreterExternalSemaSource() {} bool InterpreterExternalSemaSource::LookupUnqualified(LookupResult& R, Scope* S) { if (m_Callbacks) return m_Callbacks->LookupObject(R, S); return false; } InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp, InterpreterExternalSemaSource* IESS) : m_Interpreter(interp), m_SemaExternalSource(IESS) { if (!IESS) m_SemaExternalSource.reset(new InterpreterExternalSemaSource(this)); m_Interpreter->getSema().addExternalSource(m_SemaExternalSource.get()); } // pin the vtable here InterpreterCallbacks::~InterpreterCallbacks() { // FIXME: we have to remove the external source at destruction time. Needs // further tweaks of the patch in clang. This will be done later once the // patch is in clang's mainline. } bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) { return false; } } // end namespace cling // TODO: Make the build system in the testsuite aware how to build that class // and extract it out there again. #include "DynamicLookup.h" #include "cling/Utils/AST.h" #include "clang/Sema/Lookup.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Scope.h" namespace cling { namespace test { TestProxy* Tester = 0; extern "C" int printf(const char* fmt, ...); TestProxy::TestProxy(){} int TestProxy::Draw(){ return 12; } const char* TestProxy::getVersion(){ return "Interpreter.cpp"; } int TestProxy::Add10(int num) { return num + 10;} int TestProxy::Add(int a, int b) { return a + b; } void TestProxy::PrintString(std::string s) { printf("%s\n", s.c_str()); } bool TestProxy::PrintArray(int a[], size_t size) { for (unsigned i = 0; i < size; ++i) printf("%i", a[i]); printf("%s", "\n"); return true; } void TestProxy::PrintArray(float a[][5], size_t size) { for (unsigned i = 0; i < size; ++i) for (unsigned j = 0; j < 5; ++j) printf("%i", (int)a[i][j]); printf("%s", "\n"); } void TestProxy::PrintArray(int a[][4][5], size_t size) { for (unsigned i = 0; i < size; ++i) for (unsigned j = 0; j < 4; ++j) for (unsigned k = 0; k < 5; ++k) printf("%i", a[i][j][k]); printf("%s", "\n"); } SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp) : InterpreterCallbacks(interp, new DynamicIDHandler(this)), m_TesterDecl(0) { m_Interpreter->process("cling::test::Tester = new cling::test::TestProxy();"); } SymbolResolverCallback::~SymbolResolverCallback() { } bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) { if (!IsDynamicLookup(R, S)) return false; // We should react only on empty lookup result. if (!R.empty()) return false; // Only for demo resolve all unknown objects to cling::test::Tester if (!m_TesterDecl) { clang::Sema& SemaRef = m_Interpreter->getSema(); clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaRef, "cling"); NSD = utils::Lookup::Namespace(&SemaRef, "test", NSD); m_TesterDecl = utils::Lookup::Named(&SemaRef, "Tester", NSD); } assert (m_TesterDecl && "Tester not found!"); R.addDecl(m_TesterDecl); return true; } bool SymbolResolverCallback::IsDynamicLookup(LookupResult& R, Scope* S) { if (R.getLookupKind() != Sema::LookupOrdinaryName) return false; if (R.isForRedeclaration()) return false; // FIXME: Figure out better way to handle: // C++ [basic.lookup.classref]p1: // In a class member access expression (5.2.5), if the . or -> token is // immediately followed by an identifier followed by a <, the // identifier must be looked up to determine whether the < is the // beginning of a template argument list (14.2) or a less-than operator. // The identifier is first looked up in the class of the object // expression. If the identifier is not found, it is then looked up in // the context of the entire postfix-expression and shall name a class // or function template. // // We want to ignore object(.|->)member<template> if (R.getSema().PP.LookAhead(0).getKind() == tok::less) // TODO: check for . or -> in the cached token stream return false; for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) { if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) { return !Ctx->isDependentContext(); } } return true; } } // end test } // end cling
//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // version: $Id$ // author: Vassil Vassilev <[email protected]> //------------------------------------------------------------------------------ #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/DynamicLookupExternalSemaSource.h" #include "cling/Interpreter/Interpreter.h" #include "clang/Sema/Sema.h" using namespace clang; namespace cling { // pin the vtable here InterpreterExternalSemaSource::~InterpreterExternalSemaSource() {} bool InterpreterExternalSemaSource::LookupUnqualified(LookupResult& R, Scope* S) { if (m_Callbacks) return m_Callbacks->LookupObject(R, S); return false; } InterpreterCallbacks::InterpreterCallbacks(Interpreter* interp, InterpreterExternalSemaSource* IESS) : m_Interpreter(interp), m_SemaExternalSource(IESS) { if (!IESS) m_SemaExternalSource.reset(new InterpreterExternalSemaSource(this)); m_Interpreter->getSema().addExternalSource(m_SemaExternalSource.get()); } // pin the vtable here InterpreterCallbacks::~InterpreterCallbacks() { // FIXME: we have to remove the external source at destruction time. Needs // further tweaks of the patch in clang. This will be done later once the // patch is in clang's mainline. } bool InterpreterCallbacks::LookupObject(LookupResult&, Scope*) { return false; } } // end namespace cling // TODO: Make the build system in the testsuite aware how to build that class // and extract it out there again. #include "DynamicLookup.h" #include "cling/Utils/AST.h" #include "clang/Sema/Lookup.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Scope.h" namespace cling { namespace test { TestProxy* Tester = 0; extern "C" int printf(const char* fmt, ...); TestProxy::TestProxy(){} int TestProxy::Draw(){ return 12; } const char* TestProxy::getVersion(){ return "Interpreter.cpp"; } int TestProxy::Add10(int num) { return num + 10;} int TestProxy::Add(int a, int b) { return a + b; } void TestProxy::PrintString(std::string s) { printf("%s\n", s.c_str()); } bool TestProxy::PrintArray(int a[], size_t size) { for (unsigned i = 0; i < size; ++i) printf("%i", a[i]); printf("%s", "\n"); return true; } void TestProxy::PrintArray(float a[][5], size_t size) { for (unsigned i = 0; i < size; ++i) for (unsigned j = 0; j < 5; ++j) printf("%i", (int)a[i][j]); printf("%s", "\n"); } void TestProxy::PrintArray(int a[][4][5], size_t size) { for (unsigned i = 0; i < size; ++i) for (unsigned j = 0; j < 4; ++j) for (unsigned k = 0; k < 5; ++k) printf("%i", a[i][j][k]); printf("%s", "\n"); } SymbolResolverCallback::SymbolResolverCallback(Interpreter* interp) : InterpreterCallbacks(interp, new DynamicIDHandler(this)), m_TesterDecl(0) { m_Interpreter->process("cling::test::Tester = new cling::test::TestProxy();"); } SymbolResolverCallback::~SymbolResolverCallback() { } bool SymbolResolverCallback::LookupObject(LookupResult& R, Scope* S) { if (!IsDynamicLookup(R, S)) return false; // We should react only on empty lookup result. if (!R.empty()) return false; // Only for demo resolve all unknown objects to cling::test::Tester if (!m_TesterDecl) { clang::Sema& SemaRef = m_Interpreter->getSema(); clang::NamespaceDecl* NSD = utils::Lookup::Namespace(&SemaRef, "cling"); NSD = utils::Lookup::Namespace(&SemaRef, "test", NSD); m_TesterDecl = utils::Lookup::Named(&SemaRef, "Tester", NSD); } assert (m_TesterDecl && "Tester not found!"); R.addDecl(m_TesterDecl); return true; } bool SymbolResolverCallback::IsDynamicLookup(LookupResult& R, Scope* S) { if (R.getLookupKind() != Sema::LookupOrdinaryName) return false; if (R.isForRedeclaration()) return false; // FIXME: Figure out better way to handle: // C++ [basic.lookup.classref]p1: // In a class member access expression (5.2.5), if the . or -> token is // immediately followed by an identifier followed by a <, the // identifier must be looked up to determine whether the < is the // beginning of a template argument list (14.2) or a less-than operator. // The identifier is first looked up in the class of the object // expression. If the identifier is not found, it is then looked up in // the context of the entire postfix-expression and shall name a class // or function template. // // We want to ignore object(.|->)member<template> if (R.getSema().PP.LookAhead(0).getKind() == tok::less) // TODO: check for . or -> in the cached token stream return false; for (Scope* DepScope = S; DepScope; DepScope = DepScope->getParent()) { if (DeclContext* Ctx = static_cast<DeclContext*>(DepScope->getEntity())) { return !Ctx->isDependentContext(); } } return true; } } // end test } // end cling
Remove extra newline.
Remove extra newline. git-svn-id: ecbadac9c76e8cf640a0bca86f6bd796c98521e3@48528 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT,bbannier/ROOT
fe3d52942348329b310817d860b438dce262cb3b
Sources/Interface/Interface.cpp
Sources/Interface/Interface.cpp
/************************************************************************* > File Name: Interface.cpp > Project Name: Hearthstone++ > Author: Young-Joong Kim > Purpose: Interface for Hearthstone Game Agent > Created Time: 2017/10/24 > Copyright (c) 2017, Young-Joong Kim *************************************************************************/ #include <Commons/Constants.h> #include <Enums/EnumsToString.h> #include <Interface/Interface.h> #include <iostream> namespace Hearthstonepp { GameInterface::GameInterface(GameAgent& agent) : m_agent(agent), m_bufferCapacity(agent.GetBufferCapacity()) { m_buffer = new BYTE[m_bufferCapacity]; } GameResult GameInterface::StartGame() { GameResult result; std::thread at = m_agent.StartAgent(result); while (true) { const int msg = HandleMessage(); if (msg == HANDLE_STOP) { break; } } // join agent thread at.join(); return result; } const int GameInterface::HandleMessage() { m_agent.ReadBuffer(m_buffer, m_bufferCapacity); if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER)) { return HANDLE_STOP; } if (m_handler.find(m_buffer[0]) != m_handler.end()) { m_handler[m_buffer[0]](*this); } return HANDLE_CONTINUE; } std::ostream& GameInterface::LogWriter(std::string& name) { std::cout << "[*] " << name << " : "; return std::cout; } template <std::size_t SIZE> void GameInterface::ShowMenus(std::array<std::string, SIZE> menus) { for (auto& menu : menus) { std::cout << menu << std::endl; } } void GameInterface::ShowCards(Card** cards, int size) { for (int i = 0; i < size; ++i) { std::string type = ConverterFromCardTypeToString.at(cards[i]->GetCardType()); std::cout << '[' << cards[i]->GetName() << '(' << type << " / " << cards[i]->GetCost() << ")]\n"; } } void GameInterface::BriefGame() { GameBrief* data = reinterpret_cast<GameBrief*>(m_buffer); LogWriter(m_users[data->currentUser]) << "Game Briefing" << std::endl; std::cout << m_users[data->oppositeUser] << " : Mana - " << static_cast<int>(data->oppositeMana) << " / Hand - " << static_cast<int>(data->numOppositeHand) << std::endl; std::cout << m_users[data->oppositeUser] << " Field" << std::endl; ShowCards(data->oppositeField, data->numOppositeField); std::cout << m_users[data->currentUser] << " : Mana - " << static_cast<int>(data->currentMana) << " / Hand - " << static_cast<int>(data->numCurrentHand) << std::endl; std::cout << m_users[data->currentUser] << " Field" << std::endl; ShowCards(data->currentField, data->numCurrentField); std::cout << m_users[data->currentUser] << " Hand" << std::endl; ShowCards(data->currentHand, data->numCurrentHand); } void GameInterface::OverDraw() { OverDrawStructure* data = reinterpret_cast<OverDrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Over draw " << static_cast<int>(data->numOver) << " cards" << std::endl; ShowCards(data->cards, data->numOver); } void GameInterface::ExhaustDeck() { ExhaustDeckStructure* data = reinterpret_cast<ExhaustDeckStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Deck exhausted over " << static_cast<int>(data->numOver) << std::endl; } void GameInterface::ModifiedMana() { ModifyManaStructure* data = reinterpret_cast<ModifyManaStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Mana is modified to " << static_cast<int>(data->mana) << std::endl; } void GameInterface::BeginFirst() { BeginFirstStructure* data = reinterpret_cast<BeginFirstStructure*>(m_buffer); m_users[0] = data->userFirst; m_users[1] = data->userLast; LogWriter(m_users[0]) << "Begin First" << std::endl; LogWriter(m_users[1]) << "Begin Last" << std::endl; } void GameInterface::BeginShuffle() { BeginShuffleStructure* data = reinterpret_cast<BeginShuffleStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Shuffle" << std::endl; } void GameInterface::BeginDraw() { DrawStructure* data = reinterpret_cast<DrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Draw" << std::endl; ShowCards(data->cards, data->numDraw); } void GameInterface::BeginMulligan() { BeginMulliganStructure* data = reinterpret_cast<BeginMulliganStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Mulligan" << std::endl; int numMulligan; while (true) { std::cout << "[*] How many cards to mulligan ? (0 ~ 3) "; std::cin >> numMulligan; if (numMulligan >= 0 && numMulligan <= NUM_BEGIN_DRAW) { break; } } BYTE mulligan[NUM_BEGIN_DRAW] = { 0, }; for (int i = 0; i < numMulligan; ++i) { while (true) { int index = 0; std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : "; std::cin >> index; if (index >= 0 && index <= NUM_BEGIN_DRAW - 1) { mulligan[i] = index; break; } } } // send index to agent m_agent.WriteBuffer(mulligan, numMulligan); // get new card data m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); LogWriter(m_users[data->userID]) << "Mulligan Result" << std::endl; DrawStructure* draw = reinterpret_cast<DrawStructure*>(m_buffer); ShowCards(draw->cards, draw->numDraw); } void GameInterface::MainDraw() { DrawStructure* data = reinterpret_cast<DrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Draw" << std::endl; ShowCards(data->cards, data->numDraw); } void GameInterface::MainMenu() { MainMenuStructure* data = reinterpret_cast<MainMenuStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Menu" << std::endl; ShowMenus(m_mainMenuStr); size_t input; while (true) { std::cout << "[*] Input menu : "; std::cin >> input; if (input > 0 && input <= GAME_MAIN_MENU_SIZE) { input -= 1; break; } } BYTE menu = static_cast<BYTE>(input); m_agent.WriteBuffer(&menu, 1); } void GameInterface::MainUseCard() { MainUseCardStructure* data = reinterpret_cast<MainUseCardStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Use Card" << std::endl; ShowCards(data->hands, data->numHands); int in; while (true) { std::cout << "Select card index (0 ~ " << static_cast<int>(data->numHands) - 1 << ") : "; std::cin >> in; if (in >= 0 && in < data->numHands && data->hands[in]->GetCost() <= data->existMana) { break; } } if (data->hands[in]->GetCardType() == CardType::MINION) { int pos; while (true) { std::cout << "Select Position (0 ~ " << static_cast<int>(data->numFields) << ") : "; std::cin >> pos; if (pos >= 0 && pos <= data->numFields) { break; } } MainUseMinionStructure minion(in, pos); m_agent.WriteBuffer(reinterpret_cast<BYTE*>(&minion), sizeof(MainUseMinionStructure)); } } void GameInterface::MainCombat() { } void GameInterface::MainEnd() { } }
/************************************************************************* > File Name: Interface.cpp > Project Name: Hearthstone++ > Author: Young-Joong Kim > Purpose: Interface for Hearthstone Game Agent > Created Time: 2017/10/24 > Copyright (c) 2017, Young-Joong Kim *************************************************************************/ #include <Commons/Constants.h> #include <Enums/EnumsToString.h> #include <Interface/Interface.h> #include <iostream> namespace Hearthstonepp { GameInterface::GameInterface(GameAgent& agent) : m_agent(agent), m_bufferCapacity(agent.GetBufferCapacity()) { m_buffer = new BYTE[m_bufferCapacity]; } GameResult GameInterface::StartGame() { GameResult result; std::thread at = m_agent.StartAgent(result); while (true) { const int msg = HandleMessage(); if (msg == HANDLE_STOP) { break; } } // join agent thread at.join(); return result; } const int GameInterface::HandleMessage() { m_agent.ReadBuffer(m_buffer, m_bufferCapacity); if (m_buffer[0] == static_cast<BYTE>(Step::FINAL_GAMEOVER)) { return HANDLE_STOP; } if (m_handler.find(m_buffer[0]) != m_handler.end()) { m_handler[m_buffer[0]](*this); } return HANDLE_CONTINUE; } std::ostream& GameInterface::LogWriter(std::string& name) { std::cout << "[*] " << name << " : "; return std::cout; } template <std::size_t SIZE> void GameInterface::ShowMenus(std::array<std::string, SIZE> menus) { for (auto& menu : menus) { std::cout << menu << std::endl; } } void GameInterface::ShowCards(Card** cards, int size) { for (int i = 0; i < size; ++i) { std::string type = ConverterFromCardTypeToString.at(cards[i]->GetCardType()); std::cout << '[' << cards[i]->GetName() << '(' << type << " / " << cards[i]->GetCost() << ")]\n"; } } void GameInterface::BriefGame() { GameBrief* data = reinterpret_cast<GameBrief*>(m_buffer); LogWriter(m_users[data->currentUser]) << "Game Briefing" << std::endl; std::cout << m_users[data->oppositeUser] << " : Mana - " << static_cast<int>(data->oppositeMana) << " / Hand - " << static_cast<int>(data->numOppositeHand) << std::endl; std::cout << m_users[data->oppositeUser] << " Field" << std::endl; ShowCards(data->oppositeField, data->numOppositeField); std::cout << m_users[data->currentUser] << " : Mana - " << static_cast<int>(data->currentMana) << " / Hand - " << static_cast<int>(data->numCurrentHand) << std::endl; std::cout << m_users[data->currentUser] << " Field" << std::endl; ShowCards(data->currentField, data->numCurrentField); std::cout << m_users[data->currentUser] << " Hand" << std::endl; ShowCards(data->currentHand, data->numCurrentHand); } void GameInterface::OverDraw() { OverDrawStructure* data = reinterpret_cast<OverDrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Over draw " << static_cast<int>(data->numOver) << " cards" << std::endl; ShowCards(data->cards, data->numOver); } void GameInterface::ExhaustDeck() { ExhaustDeckStructure* data = reinterpret_cast<ExhaustDeckStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Deck exhausted over " << static_cast<int>(data->numOver) << std::endl; } void GameInterface::ModifiedMana() { ModifyManaStructure* data = reinterpret_cast<ModifyManaStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Mana is modified to " << static_cast<int>(data->mana) << std::endl; } void GameInterface::BeginFirst() { BeginFirstStructure* data = reinterpret_cast<BeginFirstStructure*>(m_buffer); m_users[0] = data->userFirst; m_users[1] = data->userLast; LogWriter(m_users[0]) << "Begin First" << std::endl; LogWriter(m_users[1]) << "Begin Last" << std::endl; } void GameInterface::BeginShuffle() { BeginShuffleStructure* data = reinterpret_cast<BeginShuffleStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Shuffle" << std::endl; } void GameInterface::BeginDraw() { DrawStructure* data = reinterpret_cast<DrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Draw" << std::endl; ShowCards(data->cards, data->numDraw); } void GameInterface::BeginMulligan() { BeginMulliganStructure* data = reinterpret_cast<BeginMulliganStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Begin Mulligan" << std::endl; int numMulligan; while (true) { std::cout << "[*] How many cards to mulligan ? (0 ~ 3) "; std::cin >> numMulligan; if (numMulligan >= 0 && numMulligan <= NUM_BEGIN_DRAW) { break; } } BYTE mulligan[NUM_BEGIN_DRAW] = { 0, }; for (int i = 0; i < numMulligan; ++i) { while (true) { int index = 0; std::cout << "[*] Input card index " << i+1 << " (0 ~ 2) : "; std::cin >> index; if (index >= 0 && index <= NUM_BEGIN_DRAW - 1) { mulligan[i] = index; break; } } } // send index to agent m_agent.WriteBuffer(mulligan, numMulligan); // get new card data m_agent.ReadBuffer(m_buffer, sizeof(DrawStructure)); LogWriter(m_users[data->userID]) << "Mulligan Result" << std::endl; DrawStructure* draw = reinterpret_cast<DrawStructure*>(m_buffer); ShowCards(draw->cards, draw->numDraw); } void GameInterface::MainDraw() { DrawStructure* data = reinterpret_cast<DrawStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Draw" << std::endl; ShowCards(data->cards, data->numDraw); } void GameInterface::MainMenu() { MainMenuStructure* data = reinterpret_cast<MainMenuStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Menu" << std::endl; ShowMenus(m_mainMenuStr); size_t input; while (true) { std::cout << "[*] Input menu : "; std::cin >> input; if (input > 0 && input <= GAME_MAIN_MENU_SIZE) { input -= 1; break; } } BYTE menu = static_cast<BYTE>(input); m_agent.WriteBuffer(&menu, 1); } void GameInterface::MainUseCard() { MainUseCardStructure* data = reinterpret_cast<MainUseCardStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main Use Card" << std::endl; ShowCards(data->hands, data->numHands); int in; while (true) { std::cout << "Select card index (0 ~ " << static_cast<int>(data->numHands) - 1 << ") : "; std::cin >> in; if (in >= 0 && in < data->numHands && data->hands[in]->GetCost() <= data->existMana) { break; } } if (data->hands[in]->GetCardType() == CardType::MINION) { int pos; while (true) { std::cout << "Select Position (0 ~ " << static_cast<int>(data->numFields) << ") : "; std::cin >> pos; if (pos >= 0 && pos <= data->numFields) { break; } } MainUseMinionStructure minion(in, pos); m_agent.WriteBuffer(reinterpret_cast<BYTE*>(&minion), sizeof(MainUseMinionStructure)); } } void GameInterface::MainCombat() { } void GameInterface::MainEnd() { MainEndStructure* data = reinterpret_cast<MainEndStructure*>(m_buffer); LogWriter(m_users[data->userID]) << "Main End" << std::endl; } }
Update Interface - Handling MainEndStructure
Update Interface - Handling MainEndStructure
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
88a69518b392e5c3291134abf1b299c55ebcd8ed
bootstrap/src/nanyc-unittest.cpp
bootstrap/src/nanyc-unittest.cpp
#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include "libnanyc.h" namespace ny { namespace unittests { namespace { struct Entry final { yuni::String module; yuni::String name; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); nycompile_opts_t opts; bool interactive = true; std::vector<Entry> unittests; std::vector<yuni::String> filenames; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { std::cout << " running "; std::cout << entry.module << '/' << entry.name; std::cout << "... " << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { if (interactive) std::cout << '\r'; // back to begining of the line if (success) { #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif } else { std::cout << " ERR "; } std::cout << entry.module << '/' << entry.name; std::cout << " (" << duration << "ms) "; std::cout << '\n'; } void App::run(const Entry& entry) { startEntry(entry); auto start = now(); auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } auto duration = now() - start; endEntry(entry, success, duration); } int App::run() { std::cout << '\n'; for (auto& entry: unittests) run(entry); return EXIT_SUCCESS; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.addFlag(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.addParagraph("\nHelp"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); app.importFilenames(filenames); app.fetch(nsl); return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; }
#include <nanyc/library.h> #include <nanyc/program.h> #include <yuni/yuni.h> #include <yuni/core/getopt.h> #include <yuni/core/string.h> #include <yuni/io/filename-manipulation.h> #include <yuni/datetime/timestamp.h> #include <iostream> #include <vector> #include <algorithm> #include <memory> #include "libnanyc.h" namespace ny { namespace unittests { namespace { struct Entry final { yuni::String module; yuni::String name; }; struct App final { App(); App(App&&) = default; ~App(); void importFilenames(const std::vector<AnyString>&); void fetch(bool nsl); void run(const Entry&); int run(); void statstics(int64_t duration) const; struct final { uint32_t total = 0; uint32_t passing = 0; uint32_t failed = 0; } stats; nycompile_opts_t opts; bool interactive = true; std::vector<Entry> unittests; std::vector<yuni::String> filenames; private: void startEntry(const Entry&); void endEntry(const Entry&, bool, int64_t); }; App::App() { memset(&opts, 0x0, sizeof(opts)); opts.userdata = this;; } App::~App() { free(opts.sources.items); } auto now() { return yuni::DateTime::NowMilliSeconds(); } bool operator < (const Entry& a, const Entry& b) { return std::tie(a.module, a.name) < std::tie(b.module, b.name); } const char* plurals(auto count, const char* single, const char* many) { return (count <= 1) ? single : many; } void App::importFilenames(const std::vector<AnyString>& list) { uint32_t count = static_cast<uint32_t>(list.size()); filenames.resize(count); std::transform(std::begin(list), std::end(list), std::begin(filenames), [](auto& item) -> yuni::String { return std::move(yuni::IO::Canonicalize(item)); }); opts.sources.count = count; opts.sources.items = (nysource_opts_t*) calloc(count, sizeof(nysource_opts_t)); if (unlikely(!opts.sources.items)) throw std::bad_alloc(); for (uint32_t i = 0; i != count; ++i) { opts.sources.items[i].filename.len = filenames[i].size(); opts.sources.items[i].filename.c_str = filenames[i].c_str(); } } void App::fetch(bool nsl) { unittests.reserve(512); // arbitrary opts.with_nsl_unittests = nsl ? nytrue : nyfalse; opts.on_unittest = [](void* userdata, const char* mod, uint32_t mlen, const char* name, uint32_t nlen) { auto& self = *reinterpret_cast<App*>(userdata); self.unittests.emplace_back(); auto& entry = self.unittests.back(); entry.module.assign(mod, mlen); entry.name.assign(name, nlen); }; std::cout << "searching for unittests in all source files...\n"; auto start = now(); nyprogram_compile(&opts); opts.on_unittest = nullptr; std::sort(std::begin(unittests), std::end(unittests)); auto duration = now() - start; std::cout << unittests.size() << ' ' << plurals(unittests.size(), "test", "tests"); std::cout << " found (in " << duration << "ms)\n"; } void App::startEntry(const Entry& entry) { if (interactive) { std::cout << " running "; std::cout << entry.module << '/' << entry.name; std::cout << "... " << std::flush; } } void App::endEntry(const Entry& entry, bool success, int64_t duration) { ++stats.total; ++(success ? stats.passing : stats.failed); if (interactive) std::cout << '\r'; // back to begining of the line if (success) { #ifndef YUNI_OS_WINDOWS std::cout << " \u2713 "; #else std::cout << " OK "; #endif } else { std::cout << " ERR "; } std::cout << entry.module << '/' << entry.name; std::cout << " (" << duration << "ms) "; std::cout << '\n'; } void App::statstics(int64_t duration) const { std::cout << "\n " << stats.total << ' ' << plurals(stats.total, "test", "tests"); std::cout << ", " << stats.passing << " passing"; if (stats.failed) std::cout << ", " << stats.failed << " failed"; std::cout << " ("; if (duration < 10000) std::cout << duration << "ms)"; else std::cout << (duration / 1000) << "s)"; std::cout << "\n\n"; } void App::run(const Entry& entry) { startEntry(entry); auto start = now(); auto* program = nyprogram_compile(&opts); bool success = program != nullptr; if (program) { nyprogram_free(program); } auto duration = now() - start; endEntry(entry, success, duration); } int App::run() { std::cout << '\n'; auto start = now(); for (auto& entry: unittests) { run(entry); if (stats.total > 3) break; } auto duration = now() - start; statstics(duration); bool success = stats.failed == 0 and stats.total != 0; return success ? EXIT_SUCCESS : EXIT_FAILURE; } int printVersion() { std::cout << libnanyc_version_to_cstr() << '\n'; return EXIT_SUCCESS; } int printBugreport() { uint32_t length; auto* text = libnanyc_get_bugreportdetails(&length); if (text) { std::cout.write(text, length); free(text); } std::cout << '\n'; return EXIT_SUCCESS; } App prepare(int argc, char** argv) { App app; bool version = false; bool bugreport = false; bool nsl = false; std::vector<AnyString> filenames; yuni::GetOpt::Parser options; options.addFlag(filenames, 'i', "", "Input nanyc source files"); options.addFlag(nsl, ' ', "nsl", "Import NSL unittests"); options.addParagraph("\nHelp"); options.addFlag(bugreport, 'b', "bugreport", "Display some useful information to report a bug"); options.addFlag(version, ' ', "version", "Print the version"); options.remainingArguments(filenames); if (not options(argc, argv)) { if (options.errors()) throw std::runtime_error("Abort due to error"); throw EXIT_SUCCESS; } if (unlikely(version)) throw printVersion(); if (unlikely(bugreport)) throw printBugreport(); app.importFilenames(filenames); app.fetch(nsl); return app; } } // namespace } // namespace unittests } // namespace ny int main(int argc, char** argv) { try { auto app = ny::unittests::prepare(argc, argv); return app.run(); } catch (const std::exception& e) { std::cerr << "exception: " << e.what() << '\n'; } catch (int e) { return e; } return EXIT_FAILURE;; }
add overall statistics (total, passing, failed)
unittests: add overall statistics (total, passing, failed)
C++
mpl-2.0
nany-lang/nanyc,nany-lang/nany,nany-lang/nany,nany-lang/nanyc,nany-lang/nany,nany-lang/nanyc
11361bb54d3ba47bac36073d8618de8bd11e5303
src/states/gameplay_state.cpp
src/states/gameplay_state.cpp
// Copyright 2015 Google Inc. 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 "game.h" #include "states/gameplay_state.h" #include "fplbase/input.h" #include "input_config_generated.h" #include "mathfu/glsl_mappings.h" #include "states/states.h" #include "states/states_common.h" #include "world.h" #include "full_screen_fader.h" using mathfu::vec2i; using mathfu::vec2; namespace fpl { namespace fpl_project { // Update music gain based on lap number. This logic will eventually live in // an event graph. static void UpdateMusic(entity::EntityManager* entity_manager, int* previous_lap, float* percent, int delta_time, pindrop::Channel* music_channel_1, pindrop::Channel* music_channel_2, pindrop::Channel* music_channel_3) { entity::EntityRef raft = entity_manager->GetComponent<ServicesComponent>()->raft_entity(); RailDenizenData* raft_rail_denizen = entity_manager->GetComponentData<RailDenizenData>(raft); if (raft_rail_denizen == nullptr) return; int current_lap = static_cast<int>(raft_rail_denizen->lap); assert(current_lap >= 0); if (current_lap != *previous_lap) { pindrop::Channel* channels[] = {music_channel_1, music_channel_2, music_channel_3}; const float kCrossFadeDuration = 5.0f; bool done = false; float seconds = delta_time / 1000.0f; float delta = seconds / kCrossFadeDuration; pindrop::Channel* channel_previous = channels[*previous_lap % 3]; pindrop::Channel* channel_current = channels[current_lap % 3]; *percent += delta; if (*percent >= 1.0f) { *percent = 1.0f; done = true; } // Equal power crossfade // https://www.safaribooksonline.com/library/view/web-audio-api/9781449332679/s03_2.html // TODO: Add utility functions to Pindrop for this. float gain_previous = cos(*percent * 0.5f * static_cast<float>(M_PI)); float gain_current = cos((1.0f - *percent) * 0.5f * static_cast<float>(M_PI)); channel_previous->SetGain(gain_previous); channel_current->SetGain(gain_current); if (done) { *previous_lap = current_lap; *percent = 0.0f; } } } void GameplayState::AdvanceFrame(int delta_time, int* next_state) { // Update the world. world_->entity_manager.UpdateComponents(delta_time); UpdateMainCamera(&main_camera_, world_); UpdateMusic(&world_->entity_manager, &previous_lap_, &percent_, delta_time, &music_channel_lap_1_, &music_channel_lap_2_, &music_channel_lap_3_); if (input_system_->GetButton(fpl::FPLK_F9).went_down()) { world_->draw_debug_physics = !world_->draw_debug_physics; } if (input_system_->GetButton(fpl::FPLK_F8).went_down()) { world_->skip_rendermesh_rendering = !world_->skip_rendermesh_rendering; } // The state machine for the world may request a state change. *next_state = requested_state_; // Switch States if necessary. if (world_editor_ && input_system_->GetButton(fpl::FPLK_F10).went_down()) { world_editor_->SetInitialCamera(main_camera_); *next_state = kGameStateWorldEditor; } // Pause the game. if (input_system_->GetButton(FPLK_ESCAPE).went_down() || input_system_->GetButton(FPLK_AC_BACK).went_down()) { audio_engine_->PlaySound(sound_pause_); *next_state = kGameStatePause; } fader_->AdvanceFrame(delta_time); } void GameplayState::RenderPrep(Renderer* renderer) { world_->world_renderer->RenderPrep(main_camera_, *renderer, world_); } void GameplayState::Render(Renderer* renderer) { if (!world_->asset_manager) return; Camera* cardboard_camera = nullptr; #ifdef ANDROID_CARDBOARD cardboard_camera = &cardboard_camera_; #endif RenderWorld(*renderer, world_, main_camera_, cardboard_camera, input_system_); if (!fader_->Finished()) { fader_->Render(renderer); } } void GameplayState::Initialize(InputSystem* input_system, World* world, const Config* config, const InputConfig* input_config, entity::EntityManager* entity_manager, editor::WorldEditor* world_editor, GPGManager* gpg_manager, pindrop::AudioEngine* audio_engine, FullScreenFader* fader) { input_system_ = input_system; config_ = config; world_ = world; input_config_ = input_config; entity_manager_ = entity_manager; world_editor_ = world_editor; gpg_manager_ = gpg_manager; audio_engine_ = audio_engine; fader_ = fader; sound_pause_ = audio_engine->GetSoundHandle("pause"); music_gameplay_lap_1_ = audio_engine->GetSoundHandle("music_gameplay_lap_1"); music_gameplay_lap_2_ = audio_engine->GetSoundHandle("music_gameplay_lap_2"); music_gameplay_lap_3_ = audio_engine->GetSoundHandle("music_gameplay_lap_3"); #ifdef ANDROID_CARDBOARD cardboard_camera_.set_viewport_angle(config->cardboard_viewport_angle()); #else (void)config; #endif } void GameplayState::OnEnter(int previous_state) { requested_state_ = kGameStateGameplay; world_->player_component.set_active(true); input_system_->SetRelativeMouseMode(true); if (previous_state == kGameStatePause) { music_channel_lap_1_.Resume(); music_channel_lap_2_.Resume(); music_channel_lap_3_.Resume(); } else { music_channel_lap_1_ = audio_engine_->PlaySound(music_gameplay_lap_1_, mathfu::kZeros3f, 1.0f); music_channel_lap_2_ = audio_engine_->PlaySound(music_gameplay_lap_2_, mathfu::kZeros3f, 0.0f); music_channel_lap_3_ = audio_engine_->PlaySound(music_gameplay_lap_3_, mathfu::kZeros3f, 0.0f); } if (world_->is_in_cardboard) { #ifdef ANDROID_CARDBOARD world_->services_component.set_camera(&cardboard_camera_); #endif } else { world_->services_component.set_camera(&main_camera_); } #ifdef ANDROID_CARDBOARD input_system_->cardboard_input().ResetHeadTracker(); #endif // ANDROID_CARDBOARD } void GameplayState::OnExit(int next_state) { if (next_state == kGameStatePause) { music_channel_lap_1_.Pause(); music_channel_lap_2_.Pause(); music_channel_lap_3_.Pause(); } else { music_channel_lap_1_.Stop(); music_channel_lap_2_.Stop(); music_channel_lap_3_.Stop(); } if (next_state == kGameStateGameMenu) { // Finished a game, post a score. auto player = entity_manager_->GetComponent<PlayerComponent>()->begin()->entity; auto attribute_data = entity_manager_->GetComponentData<AttributesData>(player); auto score = attribute_data->attributes[AttributeDef_PatronsFed]; auto leaderboard_config = config_->gpg_config()->leaderboards(); gpg_manager_->SubmitScore( leaderboard_config->LookupByKey(kGPGDefaultLeaderboard)->id()->c_str(), score); } } } // fpl_project } // fpl
// Copyright 2015 Google Inc. 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 "game.h" #include "states/gameplay_state.h" #include "fplbase/input.h" #include "input_config_generated.h" #include "mathfu/glsl_mappings.h" #include "states/states.h" #include "states/states_common.h" #include "world.h" #include "full_screen_fader.h" using mathfu::vec2i; using mathfu::vec2; namespace fpl { namespace fpl_project { // Update music gain based on lap number. This logic will eventually live in // an event graph. static void UpdateMusic(entity::EntityManager* entity_manager, int* previous_lap, float* percent, int delta_time, pindrop::Channel* music_channel_1, pindrop::Channel* music_channel_2, pindrop::Channel* music_channel_3) { entity::EntityRef raft = entity_manager->GetComponent<ServicesComponent>()->raft_entity(); RailDenizenData* raft_rail_denizen = entity_manager->GetComponentData<RailDenizenData>(raft); if (raft_rail_denizen == nullptr) return; int current_lap = static_cast<int>(raft_rail_denizen->lap); assert(current_lap >= 0); if (current_lap != *previous_lap) { pindrop::Channel* channels[] = {music_channel_1, music_channel_2, music_channel_3}; const float kCrossFadeDuration = 5.0f; bool done = false; float seconds = delta_time / 1000.0f; float delta = seconds / kCrossFadeDuration; pindrop::Channel* channel_previous = channels[*previous_lap % 3]; pindrop::Channel* channel_current = channels[current_lap % 3]; *percent += delta; if (*percent >= 1.0f) { *percent = 1.0f; done = true; } // Equal power crossfade // https://www.safaribooksonline.com/library/view/web-audio-api/9781449332679/s03_2.html // TODO: Add utility functions to Pindrop for this. float gain_previous = cos(*percent * 0.5f * static_cast<float>(M_PI)); float gain_current = cos((1.0f - *percent) * 0.5f * static_cast<float>(M_PI)); channel_previous->SetGain(gain_previous); channel_current->SetGain(gain_current); if (done) { *previous_lap = current_lap; *percent = 0.0f; } } } void GameplayState::AdvanceFrame(int delta_time, int* next_state) { // Update the world. world_->entity_manager.UpdateComponents(delta_time); UpdateMainCamera(&main_camera_, world_); UpdateMusic(&world_->entity_manager, &previous_lap_, &percent_, delta_time, &music_channel_lap_1_, &music_channel_lap_2_, &music_channel_lap_3_); if (input_system_->GetButton(fpl::FPLK_F9).went_down()) { world_->draw_debug_physics = !world_->draw_debug_physics; } if (input_system_->GetButton(fpl::FPLK_F8).went_down()) { world_->skip_rendermesh_rendering = !world_->skip_rendermesh_rendering; } // The state machine for the world may request a state change. *next_state = requested_state_; // Switch States if necessary. if (world_editor_ && input_system_->GetButton(fpl::FPLK_F10).went_down()) { world_editor_->SetInitialCamera(main_camera_); *next_state = kGameStateWorldEditor; } // Pause the game. if (input_system_->GetButton(FPLK_ESCAPE).went_down() || input_system_->GetButton(FPLK_AC_BACK).went_down()) { audio_engine_->PlaySound(sound_pause_); *next_state = kGameStatePause; } fader_->AdvanceFrame(delta_time); } void GameplayState::RenderPrep(Renderer* renderer) { world_->world_renderer->RenderPrep(main_camera_, *renderer, world_); } void GameplayState::Render(Renderer* renderer) { if (!world_->asset_manager) return; Camera* cardboard_camera = nullptr; #ifdef ANDROID_CARDBOARD cardboard_camera = &cardboard_camera_; #endif RenderWorld(*renderer, world_, main_camera_, cardboard_camera, input_system_); if (!fader_->Finished()) { renderer->model_view_projection() = mat4::Ortho(-1.0f, 1.0f, -1.0f, 1.0f, -1.0f, 1.0f); fader_->Render(renderer); } } void GameplayState::Initialize(InputSystem* input_system, World* world, const Config* config, const InputConfig* input_config, entity::EntityManager* entity_manager, editor::WorldEditor* world_editor, GPGManager* gpg_manager, pindrop::AudioEngine* audio_engine, FullScreenFader* fader) { input_system_ = input_system; config_ = config; world_ = world; input_config_ = input_config; entity_manager_ = entity_manager; world_editor_ = world_editor; gpg_manager_ = gpg_manager; audio_engine_ = audio_engine; fader_ = fader; sound_pause_ = audio_engine->GetSoundHandle("pause"); music_gameplay_lap_1_ = audio_engine->GetSoundHandle("music_gameplay_lap_1"); music_gameplay_lap_2_ = audio_engine->GetSoundHandle("music_gameplay_lap_2"); music_gameplay_lap_3_ = audio_engine->GetSoundHandle("music_gameplay_lap_3"); #ifdef ANDROID_CARDBOARD cardboard_camera_.set_viewport_angle(config->cardboard_viewport_angle()); #else (void)config; #endif } void GameplayState::OnEnter(int previous_state) { requested_state_ = kGameStateGameplay; world_->player_component.set_active(true); input_system_->SetRelativeMouseMode(true); if (previous_state == kGameStatePause) { music_channel_lap_1_.Resume(); music_channel_lap_2_.Resume(); music_channel_lap_3_.Resume(); } else { music_channel_lap_1_ = audio_engine_->PlaySound(music_gameplay_lap_1_, mathfu::kZeros3f, 1.0f); music_channel_lap_2_ = audio_engine_->PlaySound(music_gameplay_lap_2_, mathfu::kZeros3f, 0.0f); music_channel_lap_3_ = audio_engine_->PlaySound(music_gameplay_lap_3_, mathfu::kZeros3f, 0.0f); } if (world_->is_in_cardboard) { #ifdef ANDROID_CARDBOARD world_->services_component.set_camera(&cardboard_camera_); #endif } else { world_->services_component.set_camera(&main_camera_); } #ifdef ANDROID_CARDBOARD input_system_->cardboard_input().ResetHeadTracker(); #endif // ANDROID_CARDBOARD } void GameplayState::OnExit(int next_state) { if (next_state == kGameStatePause) { music_channel_lap_1_.Pause(); music_channel_lap_2_.Pause(); music_channel_lap_3_.Pause(); } else { music_channel_lap_1_.Stop(); music_channel_lap_2_.Stop(); music_channel_lap_3_.Stop(); } if (next_state == kGameStateGameMenu) { // Finished a game, post a score. auto player = entity_manager_->GetComponent<PlayerComponent>()->begin()->entity; auto attribute_data = entity_manager_->GetComponentData<AttributesData>(player); auto score = attribute_data->attributes[AttributeDef_PatronsFed]; auto leaderboard_config = config_->gpg_config()->leaderboards(); gpg_manager_->SubmitScore( leaderboard_config->LookupByKey(kGPGDefaultLeaderboard)->id()->c_str(), score); } } } // fpl_project } // fpl
Fix the fader not rendering correctly in gameplay.
Fix the fader not rendering correctly in gameplay. The fader needs to set up an orthographic projection on the screen to correctly fade in and out, which was missing in the gameplay state. Tested on Linux and Android. Change-Id: I6990a9204bc8ef4b2f9bae7b0eaf3bbf78da46fd
C++
apache-2.0
google/zooshi,google/zooshi,google/zooshi,google/zooshi,google/zooshi
9ab6973b37b665c64e71552076f9c3fff3f27404
qNewton/J2qNewton.cc
qNewton/J2qNewton.cc
#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,nu,q; q="0.7"; nu=2.5; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Jackson2(itv(x),itv(nu),itv(q))*(1-q)*x /(kv::Jackson2(itv(x),itv(nu),itv(q))-kv::Jackson2(itv(q*x),itv(nu),itv(q))); cout<<x<<endl; cout<<"value of J2"<<kv::Jackson2(itv(x),itv(nu),itv(q))<<endl; } }
#include <kv/Heine.hpp> #include <kv/qAiry.hpp> #include <kv/qBessel.hpp> #include <cmath> typedef kv::interval<double> itv; typedef kv::complex< kv::interval<double> > cp; using namespace std; int main() { cout.precision(17); int n=50; itv x,nu,q; q="0.7"; nu=2.5; x=3.5; for(int i=1;i<=n;i++){ x=x-kv::Jackson2(itv(x),itv(nu),itv(q))*(1-q)*x /(kv::Jackson2(itv(x),itv(nu),itv(q))-kv::Jackson2(itv(q*x),itv(nu),itv(q))); cout<<x<<endl; cout<<"value of J2"<<kv::Jackson2(itv(x),itv(nu),itv(q))<<endl; } cout<<"value of J2 inf"<<kv::Jackson2(itv(x.lower()),itv(nu),itv(q))<<endl; cout<<"value of J2 sup"<<kv::Jackson2(itv(x.upper()),itv(nu),itv(q))<<endl; cout<<"value of J2 mid"<<kv::Jackson2(itv(mid(x)),itv(nu),itv(q))<<endl; }
Update J2qNewton.cc
Update J2qNewton.cc
C++
mit
Daisuke-Kanaizumi/q-special-functions,Daisuke-Kanaizumi/q-special-functions
01d8b653400e4e0c393c4e2bc3ba41addbde9af7
tools/LuminoCLI/BuildCommand.cpp
tools/LuminoCLI/BuildCommand.cpp
#include "../../src/LuminoEngine/src/Asset/AssetArchive.hpp" #include "../../src/LuminoEngine/src/Shader/UnifiedShader.hpp" #include "EnvironmentSettings.hpp" #include "Workspace.hpp" #include "Project.hpp" #include "BuildCommand.hpp" #include "FxcCommand.hpp" int BuildCommand::execute(Workspace* workspace, Project* project) { m_project = project; if (ln::String::compare(target, u"Windows", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } if (!buildWindowsTarget(workspace)) { return 1; } } else if (ln::String::compare(target, u"Web", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } if (!buildWebTarget(workspace)) { return 1; } } else if (ln::String::compare(target, u"Assets", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } } else { CLI::error(ln::String::format(u"{0} is invalid target.", target)); return 1; } return 0; } Result BuildCommand::buildWindowsTarget(Workspace* workspace) { auto file = ln::FileSystem::getFile(m_project->rootDirPath(), u"*.sln"); if (file.isEmpty()) { CLI::error(".sln file not found."); return Result::Fail; } if (ln::Process::execute(workspace->buildEnvironment()->msbuild(), { file.str(), u"/t:build", u"/p:Configuration=Debug;Platform=\"x86\"" }) != 0) { CLI::error("Failed MSBuild."); return Result::Fail; } return Result::Success; } Result BuildCommand::buildWebTarget(Workspace* workspace) { // emsdk Ȃ΃CXg[ workspace->buildEnvironment()->prepareEmscriptenSdk(); auto buildDir = ln::Path::combine(m_project->buildDir(), u"Web").canonicalize(); auto installDir = ln::Path::combine(buildDir, u"Release"); auto cmakeSourceDir = m_project->emscriptenProjectDir(); auto script = ln::Path::combine(buildDir, u"build.bat"); ln::FileSystem::createDirectory(buildDir); { ln::List<ln::String> emcmakeArgs = { u"-DCMAKE_BUILD_TYPE=Release", u"-DCMAKE_INSTALL_PREFIX=" + installDir, u"-DLUMINO_ENGINE_ROOT=\"" + ln::Path(m_project->engineDirPath(), u"Native").str().replace("\\", "/") + u"\"", u"-DLN_TARGET_ARCH=Emscripten", u"-G \"MinGW Makefiles\"", cmakeSourceDir, }; ln::StreamWriter sw(script); sw.writeLineFormat(u"cd /d \"{0}\"", workspace->buildEnvironment()->emsdkDirPath()); sw.writeLineFormat(u"call emsdk activate " + workspace->buildEnvironment()->emsdkName()); sw.writeLineFormat(u"call emsdk_env.bat"); sw.writeLineFormat(u"cd /d \"{0}\"", buildDir); sw.writeLineFormat(u"call emcmake cmake " + ln::String::join(emcmakeArgs, u" ")); sw.writeLineFormat(u"call cmake --build ."); } ln::Process::execute(script); return Result::Success; } Result BuildCommand::buildAndroidTarget() { #if 0 // Android else if (ln::String::compare(target, u"Android", ln::CaseSensitivity::CaseInsensitive) == 0) { putenv("JAVA_HOME=\"D:\\Program Files\\Android\\Android Studio\\jre\""); ln::Process::execute(u"gradlew.bat", { u"assemble" }); // Debug, Release rh // https://qiita.com/tkc_tsuchiya/items/6485714615ace9e19918 #if 0 ln::String abi = u"x86_64"; ln::String platform = "android-26"; ln::String buildType = "Release"; ln::String targetName = u"Android-" + abi; ln::Path outputDir = ln::Path(m_project->androidProjectDir(), u"app/build/intermediates/cmake/release/obj/" + abi); ln::Path luminoPackageDir = ln::Path(m_devTools->luminoPackageRootDir(), u"Engine/Cpp/Android-" + abi); ln::Path cmakeHomeDir = ln::Path(m_project->androidProjectDir(), u"app"); ln::Path buildDir = ln::Path::combine(m_project->buildDir(), targetName); ln::List<ln::String> args = { u"-H" + cmakeHomeDir, u"-B" + buildDir, u"-DLN_TARGET_ARCH_NAME=" + targetName, u"-DANDROID_ABI=" + abi, u"-DANDROID_PLATFORM=" + platform, u"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=" + outputDir.str().replace("\\", "/"), u"-DCMAKE_BUILD_TYPE=" + buildType, u"-DANDROID_NDK=" + m_environmentSettings->androidNdkRootDir(), u"-DCMAKE_CXX_FLAGS=-std=c++14", u"-DCMAKE_TOOLCHAIN_FILE=" + m_environmentSettings->androidCMakeToolchain(), u"-DCMAKE_MAKE_PROGRAM=" + m_environmentSettings->androidSdkNinja(), u"-DANDROID_STL=c++_shared", u"-DLumino_DIR=" + luminoPackageDir.str().replace("\\", "/"), u"-G\"Android Gradle - Ninja\"", }; ln::Process::execute(m_environmentSettings->androidSdkCMake(), args); ln::Process::execute(m_environmentSettings->androidSdkCMake(), { u"--build", buildDir }); #endif } #endif return Result::Success; } Result BuildCommand::buildAssets() { ln::detail::CryptedAssetArchiveWriter writer; auto outputFilePath = ln::Path(m_project->buildDir(), u"Assets.lca"); writer.open(outputFilePath, ln::detail::CryptedArchiveHelper::DefaultPassword); for (auto& file : ln::FileSystem::getFiles(m_project->assetsDir(), ln::StringRef(), ln::SearchOption::Recursive)) { if (file.hasExtension(".fx")) { auto workFile = ln::Path(m_project->buildDir(), file.fileName().replaceExtension(ln::detail::UnifiedShader::FileExt)); FxcCommand cmd; cmd.outputFile = workFile; cmd.execute(file); writer.addFile(workFile, m_project->assetsDir().makeRelative(file).replaceExtension(ln::detail::UnifiedShader::FileExt)); CLI::info(file); } else { writer.addFile(file, m_project->assetsDir().makeRelative(file)); CLI::info(file); } } writer.close(); // Android { auto dst = ln::Path::combine(m_project->androidProjectDir(), u"app", u"src", u"main", u"assets", u"Assets.lca"); ln::FileSystem::createDirectory(dst.parent()); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // macOS { auto dst = ln::Path::combine(m_project->macOSProjectDir(), u"LuminoApp.macOS", u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // iOS { auto dst = ln::Path::combine(m_project->iOSProjectDir(), u"LuminoApp.iOS", u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // Windows { auto dst = ln::Path::combine(m_project->windowsProjectDir(), u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } CLI::info(u"Compilation succeeded."); return Result::Success; }
#include "../../src/LuminoEngine/src/Asset/AssetArchive.hpp" #include "../../src/LuminoEngine/src/Shader/UnifiedShader.hpp" #include "EnvironmentSettings.hpp" #include "Workspace.hpp" #include "Project.hpp" #include "BuildCommand.hpp" #include "FxcCommand.hpp" int BuildCommand::execute(Workspace* workspace, Project* project) { m_project = project; if (ln::String::compare(target, u"Windows", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } if (!buildWindowsTarget(workspace)) { return 1; } } else if (ln::String::compare(target, u"Web", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } if (!buildWebTarget(workspace)) { return 1; } } else if (ln::String::compare(target, u"Assets", ln::CaseSensitivity::CaseInsensitive) == 0) { if (!buildAssets()) { return 1; } } else { CLI::error(ln::String::format(u"{0} is invalid target.", target)); return 1; } return 0; } Result BuildCommand::buildWindowsTarget(Workspace* workspace) { auto file = ln::FileSystem::getFile(m_project->rootDirPath(), u"*.sln"); if (file.isEmpty()) { CLI::error(".sln file not found."); return Result::Fail; } if (ln::Process::execute(workspace->buildEnvironment()->msbuild(), { file.str(), u"/t:build", u"/p:Configuration=Debug;Platform=\"x86\"" }) != 0) { CLI::error("Failed MSBuild."); return Result::Fail; } return Result::Success; } Result BuildCommand::buildWebTarget(Workspace* workspace) { // emsdk Ȃ΃CXg[ workspace->buildEnvironment()->prepareEmscriptenSdk(); auto buildDir = ln::Path::combine(m_project->buildDir(), u"Web").canonicalize(); auto installDir = ln::Path::combine(buildDir, u"Release"); auto cmakeSourceDir = m_project->emscriptenProjectDir(); auto script = ln::Path::combine(buildDir, u"build.bat"); ln::FileSystem::createDirectory(buildDir); { ln::List<ln::String> emcmakeArgs = { u"-DCMAKE_BUILD_TYPE=Release", u"-DCMAKE_INSTALL_PREFIX=" + installDir, u"-DLUMINO_ENGINE_ROOT=\"" + ln::Path(m_project->engineDirPath(), u"Native").str().replace("\\", "/") + u"\"", u"-DLN_TARGET_ARCH=Emscripten", u"-G \"MinGW Makefiles\"", cmakeSourceDir, }; ln::StreamWriter sw(script); sw.writeLineFormat(u"cd /d \"{0}\"", workspace->buildEnvironment()->emsdkDirPath()); sw.writeLineFormat(u"call emsdk activate " + workspace->buildEnvironment()->emsdkName()); sw.writeLineFormat(u"call emsdk_env.bat"); sw.writeLineFormat(u"cd /d \"{0}\"", buildDir); sw.writeLineFormat(u"call emcmake cmake " + ln::String::join(emcmakeArgs, u" ")); sw.writeLineFormat(u"call cmake --build ."); } ln::Process::execute(script); return Result::Success; } Result BuildCommand::buildAndroidTarget() { #if 0 // Android else if (ln::String::compare(target, u"Android", ln::CaseSensitivity::CaseInsensitive) == 0) { putenv("JAVA_HOME=\"D:\\Program Files\\Android\\Android Studio\\jre\""); ln::Process::execute(u"gradlew.bat", { u"assemble" }); // Debug, Release rh // https://qiita.com/tkc_tsuchiya/items/6485714615ace9e19918 #if 0 ln::String abi = u"x86_64"; ln::String platform = "android-26"; ln::String buildType = "Release"; ln::String targetName = u"Android-" + abi; ln::Path outputDir = ln::Path(m_project->androidProjectDir(), u"app/build/intermediates/cmake/release/obj/" + abi); ln::Path luminoPackageDir = ln::Path(m_devTools->luminoPackageRootDir(), u"Engine/Cpp/Android-" + abi); ln::Path cmakeHomeDir = ln::Path(m_project->androidProjectDir(), u"app"); ln::Path buildDir = ln::Path::combine(m_project->buildDir(), targetName); ln::List<ln::String> args = { u"-H" + cmakeHomeDir, u"-B" + buildDir, u"-DLN_TARGET_ARCH_NAME=" + targetName, u"-DANDROID_ABI=" + abi, u"-DANDROID_PLATFORM=" + platform, u"-DCMAKE_LIBRARY_OUTPUT_DIRECTORY=" + outputDir.str().replace("\\", "/"), u"-DCMAKE_BUILD_TYPE=" + buildType, u"-DANDROID_NDK=" + m_environmentSettings->androidNdkRootDir(), u"-DCMAKE_CXX_FLAGS=-std=c++14", u"-DCMAKE_TOOLCHAIN_FILE=" + m_environmentSettings->androidCMakeToolchain(), u"-DCMAKE_MAKE_PROGRAM=" + m_environmentSettings->androidSdkNinja(), u"-DANDROID_STL=c++_shared", u"-DLumino_DIR=" + luminoPackageDir.str().replace("\\", "/"), u"-G\"Android Gradle - Ninja\"", }; ln::Process::execute(m_environmentSettings->androidSdkCMake(), args); ln::Process::execute(m_environmentSettings->androidSdkCMake(), { u"--build", buildDir }); #endif } #endif return Result::Success; } Result BuildCommand::buildAssets() { ln::detail::CryptedAssetArchiveWriter writer; auto outputFilePath = ln::Path(m_project->buildDir(), u"Assets.lca"); writer.open(outputFilePath, ln::detail::CryptedArchiveHelper::DefaultPassword); for (auto& file : ln::FileSystem::getFiles(m_project->assetsDir(), ln::StringRef(), ln::SearchOption::Recursive)) { if (file.hasExtension(".fx")) { auto workFile = ln::Path(m_project->buildDir(), file.fileName().replaceExtension(ln::detail::UnifiedShader::FileExt)); FxcCommand cmd; cmd.outputFile = workFile; cmd.execute(file); writer.addFile(workFile, m_project->assetsDir().makeRelative(file).replaceExtension(ln::detail::UnifiedShader::FileExt)); CLI::info(file); } else { writer.addFile(file, m_project->assetsDir().makeRelative(file)); CLI::info(file); } } writer.close(); // Android { auto dst = ln::Path::combine(m_project->androidProjectDir(), u"app", u"src", u"main", u"assets", u"Assets.lca"); ln::FileSystem::createDirectory(dst.parent()); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // macOS { auto dst = ln::Path::combine(m_project->macOSProjectDir(), u"LuminoApp.macOS", u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // iOS { auto dst = ln::Path::combine(m_project->iOSProjectDir(), u"LuminoApp.iOS", u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // Windows { auto dst = ln::Path::combine(m_project->windowsProjectDir(), u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } // Web { auto dst = ln::Path::combine(m_project->buildDir(), u"Web", u"Assets.lca"); ln::FileSystem::copyFile(outputFilePath, dst, ln::FileCopyOption::Overwrite); CLI::info(u"Copy to " + dst); } CLI::info(u"Compilation succeeded."); return Result::Success; }
copy assets
copy assets
C++
mit
lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino,lriki/Lumino
6c521dd2fd8b8470cdf9a17b80bd402026249870
core/foundation/inc/ROOT/RMakeUnique.hxx
core/foundation/inc/ROOT/RMakeUnique.hxx
/// \file ROOT/RMakeUnique.h /// \ingroup Base StdExt /// \author Danilo Piparo /// \date 2017-09-22 /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RMakeUnique #define ROOT_RMakeUnique #include <memory> #if ((__cplusplus < 201402L && !defined(R__WIN32)) || (defined(_MSC_VER) && _MSC_VER < 1800)) #include <utility> namespace std { template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } #endif #endif
/// \file ROOT/RMakeUnique.h /// \ingroup Base StdExt /// \author Danilo Piparo /// \date 2017-09-22 /************************************************************************* * Copyright (C) 1995-2017, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ #ifndef ROOT_RMakeUnique #define ROOT_RMakeUnique #include <memory> #if __cplusplus < 201402L && !defined(_MSC_VER) #include <utility> namespace std { template <typename T, typename... Args> std::unique_ptr<T> make_unique(Args &&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } } #endif #endif
Simplify the test for std::make_unique
Simplify the test for std::make_unique The required version of Visual Studio always ship with make_unique. Thanks Enrico Guiraud for the suggestion.
C++
lgpl-2.1
root-mirror/root,karies/root,root-mirror/root,zzxuanyuan/root,karies/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,olifre/root,olifre/root,root-mirror/root,root-mirror/root,zzxuanyuan/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,olifre/root,root-mirror/root,zzxuanyuan/root,root-mirror/root,karies/root,karies/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,karies/root,karies/root,zzxuanyuan/root,olifre/root,zzxuanyuan/root,zzxuanyuan/root,zzxuanyuan/root,root-mirror/root,root-mirror/root,karies/root,karies/root,karies/root,olifre/root,olifre/root,karies/root,root-mirror/root,karies/root
3435ebf7167c48a599ab5e29b59a7bd9bc56436d
src/qt-compositor/hardware_integration/wayland_egl/waylandeglintegration.cpp
src/qt-compositor/hardware_integration/wayland_egl/waylandeglintegration.cpp
/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** 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 Nokia Corporation 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. ** ****************************************************************************/ #include "waylandeglintegration.h" #include <QtGui/QPlatformNativeInterface> #include <QtGui/QGuiApplication> #include <QtGui/QOpenGLContext> #include <QtGui/QPlatformScreen> #define EGL_EGLEXT_PROTOTYPES #include <EGL/egl.h> #include <EGL/eglext.h> #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> GraphicsHardwareIntegration * GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor) { return new WaylandEglIntegration(compositor); } class WaylandEglIntegrationPrivate { public: WaylandEglIntegrationPrivate() : egl_display(EGL_NO_DISPLAY) , egl_context(EGL_NO_CONTEXT) { } EGLDisplay egl_display; EGLContext egl_context; bool valid; }; WaylandEglIntegration::WaylandEglIntegration(WaylandCompositor *compositor) : GraphicsHardwareIntegration(compositor) , d_ptr(new WaylandEglIntegrationPrivate) { d_ptr->valid = false; } void WaylandEglIntegration::initializeHardware(Wayland::Display *waylandDisplay) { Q_D(WaylandEglIntegration); //We need a window id now :) m_compositor->window()->winId(); QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface(); if (nativeInterface) { d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window()); if (d->egl_display) { const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS); if (extensionString && strstr(extensionString, "EGL_WL_bind_wayland_display") && eglBindWaylandDisplayWL(d->egl_display, waylandDisplay->handle())) { d->valid = true; } } if (!d->valid) qWarning("Failed to initialize egl display\n"); d->egl_context = nativeInterface->nativeResourceForContext("EglContext", m_compositor->glContext()); } } GLuint WaylandEglIntegration::createTextureFromBuffer(wl_buffer *buffer) { Q_D(WaylandEglIntegration); if (!d->valid) { qWarning("createTextureFromBuffer() failed\n"); return 0; } EGLImageKHR image = eglCreateImageKHR(d->egl_display, d->egl_context, EGL_WAYLAND_BUFFER_WL, buffer, NULL); GLuint textureId; glGenTextures(1,&textureId); glBindTexture(GL_TEXTURE_2D, textureId); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); eglDestroyImageKHR(d->egl_display, image); return textureId; } bool WaylandEglIntegration::setDirectRenderSurface(WaylandSurface *) { QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window()); return screen && screen->pageFlipper(); } bool WaylandEglIntegration::postBuffer(struct wl_buffer *buffer) { QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window()); QPlatformScreenPageFlipper *flipper = screen->pageFlipper(); return flipper ? flipper->displayBuffer(buffer) : false; }
/**************************************************************************** ** ** This file is part of QtCompositor** ** ** Copyright © 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** ** Contact: Nokia Corporation [email protected] ** ** 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 Nokia Corporation 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. ** ****************************************************************************/ #include "waylandeglintegration.h" #include <QtGui/QPlatformNativeInterface> #include <QtGui/QGuiApplication> #include <QtGui/QOpenGLContext> #include <QtGui/QPlatformScreen> #include <QtGui/QWindow> #define EGL_EGLEXT_PROTOTYPES #include <EGL/egl.h> #include <EGL/eglext.h> #define GL_GLEXT_PROTOTYPES #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> GraphicsHardwareIntegration * GraphicsHardwareIntegration::createGraphicsHardwareIntegration(WaylandCompositor *compositor) { return new WaylandEglIntegration(compositor); } class WaylandEglIntegrationPrivate { public: WaylandEglIntegrationPrivate() : egl_display(EGL_NO_DISPLAY) , egl_context(EGL_NO_CONTEXT) { } EGLDisplay egl_display; EGLContext egl_context; bool valid; }; WaylandEglIntegration::WaylandEglIntegration(WaylandCompositor *compositor) : GraphicsHardwareIntegration(compositor) , d_ptr(new WaylandEglIntegrationPrivate) { d_ptr->valid = false; } void WaylandEglIntegration::initializeHardware(Wayland::Display *waylandDisplay) { Q_D(WaylandEglIntegration); //We need a window id now :) m_compositor->window()->winId(); QPlatformNativeInterface *nativeInterface = QGuiApplication::platformNativeInterface(); if (nativeInterface) { d->egl_display = nativeInterface->nativeResourceForWindow("EglDisplay", m_compositor->window()); if (d->egl_display) { const char *extensionString = eglQueryString(d->egl_display, EGL_EXTENSIONS); if (extensionString && strstr(extensionString, "EGL_WL_bind_wayland_display") && eglBindWaylandDisplayWL(d->egl_display, waylandDisplay->handle())) { d->valid = true; } } if (!d->valid) qWarning("Failed to initialize egl display\n"); d->egl_context = nativeInterface->nativeResourceForContext("EglContext", m_compositor->glContext()); } } GLuint WaylandEglIntegration::createTextureFromBuffer(wl_buffer *buffer) { Q_D(WaylandEglIntegration); if (!d->valid) { qWarning("createTextureFromBuffer() failed\n"); return 0; } EGLImageKHR image = eglCreateImageKHR(d->egl_display, d->egl_context, EGL_WAYLAND_BUFFER_WL, buffer, NULL); GLuint textureId; glGenTextures(1,&textureId); glBindTexture(GL_TEXTURE_2D, textureId); glEGLImageTargetTexture2DOES(GL_TEXTURE_2D, image); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); eglDestroyImageKHR(d->egl_display, image); return textureId; } bool WaylandEglIntegration::setDirectRenderSurface(WaylandSurface *) { QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window()); return screen && screen->pageFlipper(); } bool WaylandEglIntegration::postBuffer(struct wl_buffer *buffer) { QPlatformScreen *screen = QPlatformScreen::platformScreenForWindow(m_compositor->window()); QPlatformScreenPageFlipper *flipper = screen->pageFlipper(); return flipper ? flipper->displayBuffer(buffer) : false; }
Add missing QWindow include
Add missing QWindow include Fix compile error ("waylandeglintegration.cpp:84:27: error: " "invalid use of incomplete type 'struct QWindow'") Change-Id: Ic87ee8a6fe67329d0e1e9a4a96fda05952093f8f Reviewed-by: Samuel Rødal <[email protected]>
C++
lgpl-2.1
ntanibata/qtwayland,ntanibata/qtwayland,Tofee/qtwayland,ntanibata/qtwayland,locusf/qtwayland-1,locusf/qtwayland-1,locusf/qtwayland-1,Tofee/qtwayland,Tofee/qtwayland,locusf/qtwayland-1
6e413c29393f3ce486e326259ccafc30c21b014a
fs/device.cpp
fs/device.cpp
//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.08.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "device.h" namespace Filesystem { Device::Device() : File(DEVICE_FILE) , m_initialized(false) { } void Device::init() { // Empty. } bool Device::ioctl(uint32_t, void*) { return true; } } // namespace Filesystem
//////////////////////////////////////////////////////////////////////////////////////////////// /// /// @file /// @author Kuba Sejdak /// @date 21.08.2016 /// /// @copyright This file is a part of cosmos OS. All rights reserved. /// //////////////////////////////////////////////////////////////////////////////////////////////// #include "device.h" namespace Filesystem { Device::Device() : File(DEVICE_FILE) , m_initialized(false) { } void Device::init() { m_initialized = true; } bool Device::ioctl(uint32_t, void*) { return true; } } // namespace Filesystem
Make default Device::init() set intialized flag.
fs: Make default Device::init() set intialized flag.
C++
bsd-2-clause
ksejdak/cosmos,ksejdak/cosmos,ksejdak/cosmos
60f0abf4ad8e17e898646811f3e5d4aaadf6fbba
platform/shared/common/PosixThreadImpl.cpp
platform/shared/common/PosixThreadImpl.cpp
#include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKill) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } void CPosixThreadImpl::wait(unsigned int nTimeout) { struct timespec ts; struct timeval tp; gettimeofday(&tp, NULL); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; common::CMutexLock oLock(m_mxSync); while (!m_stop_wait) { if ( (unsigned)ts.tv_sec + nTimeout < (unsigned)ts.tv_sec ) pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex() ); else { ts.tv_sec += nTimeout; pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts); } } m_stop_wait = false; } void CPosixThreadImpl::sleep(unsigned int nTimeout) { ::usleep(1000*nTimeout); } void CPosixThreadImpl::stopWait() { common::CMutexLock oLock(m_mxSync); m_stop_wait = true; pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho
#include "common/PosixThreadImpl.h" extern "C" { void* rho_nativethread_start(); void rho_nativethread_end(void*); } namespace rho { namespace common { IMPLEMENT_LOGCLASS(CPosixThreadImpl, "RhoThread"); CPosixThreadImpl::CPosixThreadImpl() :m_stop_wait(false) { #if defined(OS_ANDROID) // Android has no pthread_condattr_xxx API pthread_cond_init(&m_condSync, NULL); #else pthread_condattr_t sync_details; pthread_condattr_init(&sync_details); pthread_cond_init(&m_condSync, &sync_details); pthread_condattr_destroy(&sync_details); #endif } CPosixThreadImpl::~CPosixThreadImpl() { pthread_cond_destroy(&m_condSync); } void *runProc(void *pv) { IRhoRunnable *p = static_cast<IRhoRunnable *>(pv); void *pData = rho_nativethread_start(); p->runObject(); rho_nativethread_end(pData); return 0; } void CPosixThreadImpl::start(IRhoRunnable *pRunnable, IRhoRunnable::EPriority ePriority) { pthread_attr_t attr; int return_val = pthread_attr_init(&attr); //return_val = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); RHO_ASSERT(!return_val); if ( ePriority != IRhoRunnable::epNormal) { sched_param param; return_val = pthread_attr_getschedparam (&attr, &param); param.sched_priority = ePriority == IRhoRunnable::epLow ? 20 : 100; //TODO: sched_priority return_val = pthread_attr_setschedparam (&attr, &param); } int thread_error = pthread_create(&m_thread, &attr, &runProc, pRunnable); return_val = pthread_attr_destroy(&attr); RHO_ASSERT(!return_val); RHO_ASSERT(thread_error==0); } void CPosixThreadImpl::stop(unsigned int nTimeoutToKill) { stopWait(); //TODO: wait for nTimeoutToKill and kill thread void* status; pthread_join(m_thread,&status); } void CPosixThreadImpl::wait(unsigned int nTimeout) { struct timespec ts; struct timeval tp; gettimeofday(&tp, NULL); /* Convert from timeval to timespec */ ts.tv_sec = tp.tv_sec; ts.tv_nsec = tp.tv_usec * 1000; unsigned long long max; bool timed_wait; if ( (unsigned)ts.tv_sec + nTimeout >= (unsigned)ts.tv_sec ) { timed_wait = true; ts.tv_sec += nTimeout; max = ((unsigned long long)tp.tv_sec + nTimeout)*1000000 + tp.tv_usec; } else timed_wait = false; common::CMutexLock oLock(m_mxSync); while (!m_stop_wait) { if (timed_wait) { pthread_cond_timedwait(&m_condSync, m_mxSync.getNativeMutex(), &ts); gettimeofday(&tp, NULL); unsigned long long now = ((unsigned long long)tp.tv_sec)*1000000 + tp.tv_usec; if (now > max) m_stop_wait = true; } else pthread_cond_wait(&m_condSync, m_mxSync.getNativeMutex()); } m_stop_wait = false; } void CPosixThreadImpl::sleep(unsigned int nTimeout) { ::usleep(1000*nTimeout); } void CPosixThreadImpl::stopWait() { common::CMutexLock oLock(m_mxSync); m_stop_wait = true; pthread_cond_broadcast(&m_condSync); } } // namespace common } // namespace rho
Fix thread wait on POSIX (iPhone, Android)
Fix thread wait on POSIX (iPhone, Android)
C++
mit
jdrider/rhodes,UIKit0/rhodes,jdrider/rhodes,UIKit0/rhodes,jdrider/rhodes,louisatome/rhodes,nosolosoftware/rhodes,UIKit0/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,jdrider/rhodes,UIKit0/rhodes,louisatome/rhodes,UIKit0/rhodes,nosolosoftware/rhodes,jdrider/rhodes,UIKit0/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,nosolosoftware/rhodes,jdrider/rhodes,louisatome/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,UIKit0/rhodes,louisatome/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,nosolosoftware/rhodes,rhosilver/rhodes-1,UIKit0/rhodes,rhosilver/rhodes-1,nosolosoftware/rhodes,louisatome/rhodes,rhosilver/rhodes-1,jdrider/rhodes,rhosilver/rhodes-1,louisatome/rhodes,jdrider/rhodes,rhosilver/rhodes-1,louisatome/rhodes,rhosilver/rhodes-1,jdrider/rhodes,louisatome/rhodes,louisatome/rhodes
9c41f147a2440557532b23318aedc2cac19ec977
include/Bull/Core/Assets/AssetLoader.hpp
include/Bull/Core/Assets/AssetLoader.hpp
#ifndef BULL_CORE_ASSETS_ASSETLOADER_HPP #define BULL_CORE_ASSETS_ASSETLOADER_HPP #include <vector> #include <Bull/Core/Thread/Thread.hpp> namespace Bull { template <typename T> class BULL_CORE_API AssetLoader { private: class Worker : public Runnable { public: /*! \brief Constructor * * \param function The function to run * */ explicit Worker(const std::function<bool()>& function) : m_success(false), m_function(function) { /// Nothing } /*! \brief Load the resource * */ void run() override { m_success = m_function(); } /*! \brief Tell whether the Worker loaded de resource successfully * * \return True if the resource was loaded successfully * */ bool isSuccess() const { return m_success; } private: bool m_success; std::function<bool()> m_function; }; class ThreadWorker : public Thread { public: /*! \brief Constructor * * \param worker The Worker to run * */ explicit ThreadWorker(std::unique_ptr<Worker> worker) : Thread(std::bind(&Worker::run, worker.get())), m_worker(std::move(worker)) { /// Nothing } /*! \brief Get the Worker of the Thread * * \return The Worker * */ const Worker& getWorker() const { return *m_worker; } private: std::unique_ptr<Worker> m_worker; }; public: /*! \brief Get the percentage of loaded AbstractImage * * \return The percentage of loaded AbstractImage * */ float getProgress() const { std::size_t count = 0; for(const std::unique_ptr<ThreadWorker>& thread : m_threads) { if(!thread->isRunning()) { count++; } } return (count / m_threads.size()) * 100.f; } /*! \brief Wait every AbstractImage has been loaded * * \return True if every AbstractImage has been loaded successfully * */ bool wait() { bool success = true; for(const std::unique_ptr<ThreadWorker>& thread : m_threads) { thread->wait(); success &= thread->getWorker().isSuccess(); } m_threads.clear(); return success; } protected: /*! \brief Create a new task to run * * \param task The function to run * * \return True if the task was created successfully * */ bool createTask(const std::function<bool()>& task) { std::unique_ptr<ThreadWorker> thread = std::make_unique<ThreadWorker>(std::make_unique<Worker>(task)); if(!thread->start()) { return false; } m_threads.emplace_back(std::move(thread)); return true; } private: std::vector<std::unique_ptr<ThreadWorker>> m_threads; }; } #endif // BULL_CORE_ASSETS_ASSETLOADER_HPP
#ifndef BULL_CORE_ASSETS_ASSETLOADER_HPP #define BULL_CORE_ASSETS_ASSETLOADER_HPP #include <vector> #include <Bull/Core/Thread/Thread.hpp> namespace Bull { template <typename T> class BULL_CORE_API AssetLoader { private: class Worker : public Runnable { public: /*! \brief Constructor * * \param function The function to run * */ explicit Worker(const std::function<bool()>& function) : m_success(false), m_function(function) { /// Nothing } /*! \brief Load the resource * */ void run() override { m_success = m_function(); } /*! \brief Tell whether the Worker loaded de resource successfully * * \return True if the resource was loaded successfully * */ bool isSuccess() const { return m_success; } private: bool m_success; std::function<bool()> m_function; }; class ThreadWorker : public Thread { public: /*! \brief Constructor * * \param worker The Worker to run * */ explicit ThreadWorker(std::unique_ptr<Worker> worker) : Thread(std::bind(&Worker::run, worker.get())), m_worker(std::move(worker)) { /// Nothing } /*! \brief Get the Worker of the Thread * * \return The Worker * */ const Worker& getWorker() const { return *m_worker; } private: std::unique_ptr<Worker> m_worker; }; public: /*! \brief Get the percentage of loaded Asset * * \return The percentage of loaded Asset * */ float getProgress() const { std::size_t count = 0; for(const std::unique_ptr<ThreadWorker>& thread : m_threads) { if(!thread->isRunning()) { count++; } } return (count / m_threads.size()) * 100.f; } /*! \brief Wait every Asset has been loaded * * \return True if every Asset has been loaded successfully * */ bool wait() { bool success = true; for(const std::unique_ptr<ThreadWorker>& thread : m_threads) { thread->wait(); success &= thread->getWorker().isSuccess(); } m_threads.clear(); return success; } protected: /*! \brief Create a new task to run * * \param task The function to run * * \return True if the task was created successfully * */ bool createTask(const std::function<bool()>& task) { std::unique_ptr<ThreadWorker> thread = std::make_unique<ThreadWorker>(std::make_unique<Worker>(task)); if(!thread->start()) { return false; } m_threads.emplace_back(std::move(thread)); return true; } private: std::vector<std::unique_ptr<ThreadWorker>> m_threads; }; } #endif // BULL_CORE_ASSETS_ASSETLOADER_HPP
Fix documentation
[Core/AssetLoader] Fix documentation
C++
mit
siliace/Bull
3addf9a5594fdfc48618aac00d8bd1a9b5b33fe7
Modules/Python/Testing/mitkCopyToPythonAsItkImageTest.cpp
Modules/Python/Testing/mitkCopyToPythonAsItkImageTest.cpp
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkCommon.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usServiceReference.h> #include <mitkTestingMacros.h> #include <mitkPythonService.h> #include <mitkIPythonService.h> #include <mitkIOUtil.h> #include <mitkModuleRegistry.h> #include <mitkModule.h> #include <mitkServiceReference.h> #include <mitkImagePixelReadAccessor.h> int mitkCopyToPythonAsItkImageTest(int /*argc*/, char* argv[]) { MITK_TEST_BEGIN("mitkCopyToPythonAsItkImageTest") //get the context of the python module mitk::Module* module = mitk::ModuleRegistry::GetModule("mitkPython"); mitk::ModuleContext* context = module->GetModuleContext(); //get the service which is generated in the PythonModuleActivator mitk::ServiceReference serviceRef = context->GetServiceReference<mitk::IPythonService>(); mitk::PythonService* pythonService = dynamic_cast<mitk::PythonService*>( context->GetService<mitk::IPythonService>(serviceRef) ); MITK_TEST_CONDITION(pythonService->IsItkPythonWrappingAvailable() == true, "Is Python available?"); mitk::Image::Pointer testImage = mitk::IOUtil::LoadImage(std::string(argv[1])); //give it a name in python std::string nameOfImageInPython("mitkImage"); MITK_TEST_CONDITION( pythonService->CopyToPythonAsItkImage( testImage, nameOfImageInPython) == true, "Valid image copied to python import should return true."); mitk::Image::Pointer pythonImage = pythonService->CopyItkImageFromPython(nameOfImageInPython); mitk::Index3D index; index[0] = 128; index[1] = 128; index[2] = 24; try{ mitk::ImagePixelReadAccessor<char,3> pythonImageAccesor(pythonImage); //TODO Use the assert comparison methods once we have them implemented and remove GetPixelValueByIndex MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(0) == 256, "Is the 1st dimension of Pic3D still 256?"); MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(1) == 256, "Is the 2nd dimension of Pic3D still 256?"); MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(2) == 49, "Is the 3rd dimension of Pic3D still 49?"); MITK_TEST_CONDITION( pythonImageAccesor.GetPixelByIndex(indx) == 96, "Is the value of Pic3D at (128,128,24) still 96?"); }catch(...) { MITK_TEST_CONDITION( false, "Image is not readable! "); } MITK_TEST_END() }
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include <mitkCommon.h> #include <usModuleContext.h> #include <usGetModuleContext.h> #include <usServiceReference.h> #include <mitkTestingMacros.h> #include <mitkPythonService.h> #include <mitkIPythonService.h> #include <mitkIOUtil.h> #include <mitkModuleRegistry.h> #include <mitkModule.h> #include <mitkServiceReference.h> #include <mitkImagePixelReadAccessor.h> int mitkCopyToPythonAsItkImageTest(int /*argc*/, char* argv[]) { MITK_TEST_BEGIN("mitkCopyToPythonAsItkImageTest") //get the context of the python module mitk::Module* module = mitk::ModuleRegistry::GetModule("mitkPython"); mitk::ModuleContext* context = module->GetModuleContext(); //get the service which is generated in the PythonModuleActivator mitk::ServiceReference serviceRef = context->GetServiceReference<mitk::IPythonService>(); mitk::PythonService* pythonService = dynamic_cast<mitk::PythonService*>( context->GetService<mitk::IPythonService>(serviceRef) ); MITK_TEST_CONDITION(pythonService->IsItkPythonWrappingAvailable() == true, "Is Python available?"); mitk::Image::Pointer testImage = mitk::IOUtil::LoadImage(std::string(argv[1])); //give it a name in python std::string nameOfImageInPython("mitkImage"); MITK_TEST_CONDITION( pythonService->CopyToPythonAsItkImage( testImage, nameOfImageInPython) == true, "Valid image copied to python import should return true."); mitk::Image::Pointer pythonImage = pythonService->CopyItkImageFromPython(nameOfImageInPython); mitk::Index3D index; index[0] = 128; index[1] = 128; index[2] = 24; try{ // pic3D of type char mitk::ImagePixelReadAccessor<char,3> pythonImageAccesor(pythonImage); //TODO Use the assert comparison methods once we have them implemented and remove GetPixelValueByIndex MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(0) == 256, "Is the 1st dimension of Pic3D still 256?"); MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(1) == 256, "Is the 2nd dimension of Pic3D still 256?"); MITK_TEST_CONDITION( pythonImageAccesor.GetDimension(2) == 49, "Is the 3rd dimension of Pic3D still 49?"); MITK_TEST_CONDITION( pythonImageAccesor.GetPixelByIndex(index) == 96, "Is the value of Pic3D at (128,128,24) still 96?"); }catch(...) { MITK_TEST_CONDITION( false, "Image is not readable! "); } MITK_TEST_END() }
fix typo
fix typo
C++
bsd-3-clause
danielknorr/MITK,danielknorr/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,danielknorr/MITK,NifTK/MITK,MITK/MITK,rfloca/MITK,danielknorr/MITK,NifTK/MITK,rfloca/MITK,NifTK/MITK,MITK/MITK,fmilano/mitk,nocnokneo/MITK,iwegner/MITK,RabadanLab/MITKats,danielknorr/MITK,iwegner/MITK,RabadanLab/MITKats,iwegner/MITK,RabadanLab/MITKats,MITK/MITK,danielknorr/MITK,iwegner/MITK,nocnokneo/MITK,rfloca/MITK,rfloca/MITK,fmilano/mitk,rfloca/MITK,nocnokneo/MITK,RabadanLab/MITKats,rfloca/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,MITK/MITK,lsanzdiaz/MITK-BiiG,RabadanLab/MITKats,lsanzdiaz/MITK-BiiG,fmilano/mitk,fmilano/mitk,MITK/MITK,lsanzdiaz/MITK-BiiG,lsanzdiaz/MITK-BiiG,fmilano/mitk,rfloca/MITK,NifTK/MITK,lsanzdiaz/MITK-BiiG,fmilano/mitk,danielknorr/MITK,nocnokneo/MITK,nocnokneo/MITK,NifTK/MITK,iwegner/MITK,fmilano/mitk,iwegner/MITK,lsanzdiaz/MITK-BiiG,nocnokneo/MITK,RabadanLab/MITKats
9e3ec47f9da17324a177120347fc42348da80c6c
SofaKernel/framework/sofa/helper/system/PluginManager.cpp
SofaKernel/framework/sofa/helper/system/PluginManager.cpp
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/helper/system/PluginManager.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileSystem.h> #include <sofa/helper/Utils.h> #include <sofa/helper/logging/Messaging.h> #include <fstream> #include <sofa/helper/system/config.h> using sofa::helper::Utils; namespace sofa { namespace helper { namespace system { namespace { template <class LibraryEntry> bool getPluginEntry(LibraryEntry& entry, DynamicLibrary::Handle handle) { typedef typename LibraryEntry::FuncPtr FuncPtr; entry.func = (FuncPtr)DynamicLibrary::getSymbolAddress(handle, entry.symbol); if( entry.func == 0 ) { return false; } else { return true; } } } // namespace const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList"; const char* Plugin::InitExternalModule::symbol = "initExternalModule"; const char* Plugin::GetModuleDescription::symbol = "getModuleDescription"; const char* Plugin::GetModuleLicense::symbol = "getModuleLicense"; const char* Plugin::GetModuleName::symbol = "getModuleName"; const char* Plugin::GetModuleVersion::symbol = "getModuleVersion"; std::string PluginManager::s_gui_postfix = "gui"; PluginManager & PluginManager::getInstance() { static PluginManager instance; return instance; } PluginManager::PluginManager() { m_searchPaths = PluginRepository.getPaths(); } PluginManager::~PluginManager() { // BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded // Instead we write the file each time a change have been made in the GUI and should be saved //writeToIniFile(); } void PluginManager::readFromIniFile(const std::string& path) { std::ifstream instream(path.c_str()); std::string pluginPath; while(std::getline(instream,pluginPath)) { if(loadPlugin(pluginPath)) m_pluginMap[pluginPath].initExternalModule(); } instream.close(); } void PluginManager::writeToIniFile(const std::string& path) { std::ofstream outstream(path.c_str()); PluginIterator iter; for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter) { const std::string& pluginPath = (iter->first); outstream << pluginPath << "\n"; } outstream.close(); } bool PluginManager::loadPluginByPath(const std::string& pluginPath, std::ostream* errlog) { if (pluginIsLoaded(pluginPath)) { const std::string msg = "Plugin already loaded: " + pluginPath; // Logger::getMainLogger().log(Logger::Warning, msg, "PluginManager"); if (errlog) (*errlog) << msg << std::endl; return false; } if (!FileSystem::exists(pluginPath)) { const std::string msg = "File not found: " + pluginPath; msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } DynamicLibrary::Handle d = DynamicLibrary::load(pluginPath); Plugin p; if( ! d.isValid() ) { const std::string msg = "Plugin loading failed (" + pluginPath + "): " + DynamicLibrary::getLastError(); msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } else { if(! getPluginEntry(p.initExternalModule,d)) { const std::string msg = "Plugin loading failed (" + pluginPath + "): function initExternalModule() not found"; msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } getPluginEntry(p.getModuleName,d); getPluginEntry(p.getModuleDescription,d); getPluginEntry(p.getModuleLicense,d); getPluginEntry(p.getModuleComponentList,d); getPluginEntry(p.getModuleVersion,d); } p.dynamicLibrary = d; m_pluginMap[pluginPath] = p; p.initExternalModule(); msg_info("PluginManager") << "Loaded plugin: " << pluginPath; return true; } bool PluginManager::loadPluginByName(const std::string& pluginName, std::ostream* errlog) { std::string pluginPath = findPlugin(pluginName); if (pluginPath != "") { return loadPluginByPath(pluginPath, errlog); } else { const std::string msg = "Plugin not found: \"" + pluginName + "\""; if (errlog) (*errlog) << msg << std::endl; else msg_error("PluginManager") << msg; return false; } } bool PluginManager::loadPlugin(const std::string& plugin, std::ostream* errlog) { // If 'plugin' ends with ".so", ".dll" or ".dylib", this is a path const std::string dotExt = "." + DynamicLibrary::extension; if (std::equal(dotExt.rbegin(), dotExt.rend(), plugin.rbegin())) return loadPluginByPath(plugin, errlog); else return loadPluginByName(plugin, errlog); } bool PluginManager::unloadPlugin(const std::string &pluginPath, std::ostream* errlog) { if(!pluginIsLoaded(pluginPath)) { const std::string msg = "Plugin not loaded: " + pluginPath; msg_error("PluginManager::unloadPlugin()") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } else { m_pluginMap.erase(m_pluginMap.find(pluginPath)); return true; } } std::istream& PluginManager::readFromStream(std::istream & in) { while(!in.eof()) { std::string pluginPath; in >> pluginPath; loadPlugin(pluginPath); } return in; } std::ostream& PluginManager::writeToStream(std::ostream & os) const { PluginMap::const_iterator iter; for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter) { os << iter->first; } return os; } void PluginManager::init() { PluginMap::iterator iter; for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter) { Plugin& plugin = iter->second; plugin.initExternalModule(); } } void PluginManager::init(const std::string& pluginPath) { PluginMap::iterator iter = m_pluginMap.find(pluginPath); if(m_pluginMap.end() != iter) { Plugin& plugin = iter->second; plugin.initExternalModule(); } } std::string PluginManager::findPlugin(const std::string& pluginName, bool ignoreCase) { std::string name(pluginName); #ifdef SOFA_LIBSUFFIX name += sofa_tostring(SOFA_LIBSUFFIX); #endif const std::string libName = DynamicLibrary::prefix + name + "." + DynamicLibrary::extension; // First try: case sensitive for (std::vector<std::string>::iterator i = m_searchPaths.begin(); i!=m_searchPaths.end(); i++) { const std::string path = *i + "/" + libName; if (FileSystem::exists(path)) return path; } // Second try: case insensitive if (ignoreCase) { for (std::vector<std::string>::iterator i = m_searchPaths.begin(); i!=m_searchPaths.end(); i++) { const std::string& dir = *i; const std::string path = dir + "/" + libName; const std::string downcaseLibName = Utils::downcaseString(libName); std::vector<std::string> files; FileSystem::listDirectory(dir, files); for(std::vector<std::string>::iterator j = files.begin(); j != files.end(); j++) { const std::string& filename = *j; const std::string downcaseFilename = Utils::downcaseString(filename); if (downcaseFilename == downcaseLibName) return dir + "/" + filename; } } } return ""; } bool PluginManager::pluginIsLoaded(const std::string& pluginPath) { return m_pluginMap.find(pluginPath) != m_pluginMap.end(); } } } }
/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2016 INRIA, USTL, UJF, CNRS, MGH * * * * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Framework * * * * Authors: The SOFA Team (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/helper/system/PluginManager.h> #include <sofa/helper/system/FileRepository.h> #include <sofa/helper/system/SetDirectory.h> #include <sofa/helper/system/FileSystem.h> #include <sofa/helper/Utils.h> #include <sofa/helper/logging/Messaging.h> #include <fstream> #include <sofa/helper/system/config.h> using sofa::helper::Utils; namespace sofa { namespace helper { namespace system { namespace { template <class LibraryEntry> bool getPluginEntry(LibraryEntry& entry, DynamicLibrary::Handle handle) { typedef typename LibraryEntry::FuncPtr FuncPtr; entry.func = (FuncPtr)DynamicLibrary::getSymbolAddress(handle, entry.symbol); if( entry.func == 0 ) { return false; } else { return true; } } } // namespace const char* Plugin::GetModuleComponentList::symbol = "getModuleComponentList"; const char* Plugin::InitExternalModule::symbol = "initExternalModule"; const char* Plugin::GetModuleDescription::symbol = "getModuleDescription"; const char* Plugin::GetModuleLicense::symbol = "getModuleLicense"; const char* Plugin::GetModuleName::symbol = "getModuleName"; const char* Plugin::GetModuleVersion::symbol = "getModuleVersion"; std::string PluginManager::s_gui_postfix = "gui"; PluginManager & PluginManager::getInstance() { static PluginManager instance; return instance; } PluginManager::PluginManager() { m_searchPaths = PluginRepository.getPaths(); } PluginManager::~PluginManager() { // BUGFIX: writeToIniFile should not be called here as it will erase the file in case it was not loaded // Instead we write the file each time a change have been made in the GUI and should be saved //writeToIniFile(); } void PluginManager::readFromIniFile(const std::string& path) { std::ifstream instream(path.c_str()); std::string pluginPath; while(std::getline(instream,pluginPath)) { if(loadPlugin(pluginPath)) m_pluginMap[pluginPath].initExternalModule(); } instream.close(); } void PluginManager::writeToIniFile(const std::string& path) { std::ofstream outstream(path.c_str()); PluginIterator iter; for( iter = m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter) { const std::string& pluginPath = (iter->first); outstream << pluginPath << "\n"; } outstream.close(); } bool PluginManager::loadPluginByPath(const std::string& pluginPath, std::ostream* errlog) { if (pluginIsLoaded(pluginPath)) { const std::string msg = "Plugin already loaded: " + pluginPath; // Logger::getMainLogger().log(Logger::Warning, msg, "PluginManager"); if (errlog) (*errlog) << msg << std::endl; return false; } if (!FileSystem::exists(pluginPath)) { const std::string msg = "File not found: " + pluginPath; msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } DynamicLibrary::Handle d = DynamicLibrary::load(pluginPath); Plugin p; if( ! d.isValid() ) { const std::string msg = "Plugin loading failed (" + pluginPath + "): " + DynamicLibrary::getLastError(); msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } else { if(! getPluginEntry(p.initExternalModule,d)) { const std::string msg = "Plugin loading failed (" + pluginPath + "): function initExternalModule() not found"; msg_error("PluginManager") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } getPluginEntry(p.getModuleName,d); getPluginEntry(p.getModuleDescription,d); getPluginEntry(p.getModuleLicense,d); getPluginEntry(p.getModuleComponentList,d); getPluginEntry(p.getModuleVersion,d); } p.dynamicLibrary = d; m_pluginMap[pluginPath] = p; p.initExternalModule(); msg_info("PluginManager") << "Loaded plugin: " << pluginPath; return true; } bool PluginManager::loadPluginByName(const std::string& pluginName, std::ostream* errlog) { std::string pluginPath = findPlugin(pluginName); if (pluginPath != "") { return loadPluginByPath(pluginPath, errlog); } else { const std::string msg = "Plugin not found: \"" + pluginName + "\""; if (errlog) (*errlog) << msg << std::endl; else msg_error("PluginManager") << msg; return false; } } bool PluginManager::loadPlugin(const std::string& plugin, std::ostream* errlog) { // If 'plugin' ends with ".so", ".dll" or ".dylib", this is a path const std::string dotExt = "." + DynamicLibrary::extension; if (std::equal(dotExt.rbegin(), dotExt.rend(), plugin.rbegin())) return loadPluginByPath(plugin, errlog); else return loadPluginByName(plugin, errlog); } bool PluginManager::unloadPlugin(const std::string &pluginPath, std::ostream* errlog) { if(!pluginIsLoaded(pluginPath)) { const std::string msg = "Plugin not loaded: " + pluginPath; msg_error("PluginManager::unloadPlugin()") << msg; if (errlog) (*errlog) << msg << std::endl; return false; } else { m_pluginMap.erase(m_pluginMap.find(pluginPath)); return true; } } std::istream& PluginManager::readFromStream(std::istream & in) { while(!in.eof()) { std::string pluginPath; in >> pluginPath; loadPlugin(pluginPath); } return in; } std::ostream& PluginManager::writeToStream(std::ostream & os) const { PluginMap::const_iterator iter; for(iter= m_pluginMap.begin(); iter!=m_pluginMap.end(); ++iter) { os << iter->first; } return os; } void PluginManager::init() { PluginMap::iterator iter; for( iter = m_pluginMap.begin(); iter!= m_pluginMap.end(); ++iter) { Plugin& plugin = iter->second; plugin.initExternalModule(); } } void PluginManager::init(const std::string& pluginPath) { PluginMap::iterator iter = m_pluginMap.find(pluginPath); if(m_pluginMap.end() != iter) { Plugin& plugin = iter->second; plugin.initExternalModule(); } } std::string PluginManager::findPlugin(const std::string& pluginName, bool ignoreCase) { std::string name(pluginName); #ifdef SOFA_LIBSUFFIX name += sofa_tostring(SOFA_LIBSUFFIX); #endif #if defined(_DEBUG) && defined(_MSC_VER) name += "_d"; #endif const std::string libName = DynamicLibrary::prefix + name + "." + DynamicLibrary::extension; // First try: case sensitive for (std::vector<std::string>::iterator i = m_searchPaths.begin(); i!=m_searchPaths.end(); i++) { const std::string path = *i + "/" + libName; if (FileSystem::exists(path)) return path; } // Second try: case insensitive if (ignoreCase) { for (std::vector<std::string>::iterator i = m_searchPaths.begin(); i!=m_searchPaths.end(); i++) { const std::string& dir = *i; const std::string path = dir + "/" + libName; const std::string downcaseLibName = Utils::downcaseString(libName); std::vector<std::string> files; FileSystem::listDirectory(dir, files); for(std::vector<std::string>::iterator j = files.begin(); j != files.end(); j++) { const std::string& filename = *j; const std::string downcaseFilename = Utils::downcaseString(filename); if (downcaseFilename == downcaseLibName) return dir + "/" + filename; } } } return ""; } bool PluginManager::pluginIsLoaded(const std::string& pluginPath) { return m_pluginMap.find(pluginPath) != m_pluginMap.end(); } } } }
fix to include debug plugin on msvc
fix to include debug plugin on msvc
C++
lgpl-2.1
hdeling/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,hdeling/sofa,hdeling/sofa,Anatoscope/sofa,hdeling/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,Anatoscope/sofa,Anatoscope/sofa,hdeling/sofa,Anatoscope/sofa,Anatoscope/sofa,FabienPean/sofa,hdeling/sofa,Anatoscope/sofa,Anatoscope/sofa,hdeling/sofa,hdeling/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,FabienPean/sofa,hdeling/sofa,FabienPean/sofa,hdeling/sofa
3d4e16af84161e1b1db39ae9363a39675b56a2d3
src/modules/engines/software_ddraw/evas_ddraw_main.cpp
src/modules/engines/software_ddraw/evas_ddraw_main.cpp
#include "evas_common.h" #include "evas_engine.h" int evas_software_ddraw_init (HWND window, int depth, int fullscreen, Outbuf *buf) { DDSURFACEDESC surface_desc; DDPIXELFORMAT pixel_format; HRESULT res; int width; int height; if (!buf) return 0; buf->priv.dd.window = window; res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL); if (FAILED(res)) return 0; if (buf->priv.dd.fullscreen) { DDSCAPS caps; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); if (FAILED(res)) goto release_object; width = GetSystemMetrics(SM_CXSCREEN); height = GetSystemMetrics(SM_CYSCREEN); ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_object; buf->priv.dd.depth = depth; res = buf->priv.dd.object->SetDisplayMode(width, height, depth); if (FAILED(res)) goto release_object; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; surface_desc.dwBackBufferCount = 1; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_object; caps.dwCaps = DDSCAPS_BACKBUFFER; res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps, &buf->priv.dd.surface_back); if (FAILED(res)) goto release_surface_primary; } else { RECT rect; if (!GetClientRect(window, &rect)) goto release_object; width = rect.right - rect.left; height = rect.bottom - rect.top; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL); if (FAILED(res)) goto release_object; res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL); if (FAILED(res)) goto release_object; res = buf->priv.dd.clipper->SetHWnd(0, window); if (FAILED(res)) goto release_clipper; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_clipper; res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper); if (FAILED(res)) goto release_surface_primary; memset (&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = width; surface_desc.dwHeight = height; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); if (FAILED(res)) goto release_surface_primary; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_surface_back; buf->priv.dd.depth = depth; } return 1; release_surface_back: buf->priv.dd.surface_back->Release(); release_surface_primary: buf->priv.dd.surface_primary->Release(); release_clipper: if (buf->priv.dd.fullscreen) buf->priv.dd.clipper->Release(); release_object: buf->priv.dd.object->Release(); return 0; } void evas_software_ddraw_shutdown(Outbuf *buf) { if (!buf) return; if (buf->priv.dd.fullscreen) if (buf->priv.dd.surface_back) buf->priv.dd.surface_back->Release(); if (buf->priv.dd.surface_primary) buf->priv.dd.surface_primary->Release(); if (buf->priv.dd.fullscreen) if (buf->priv.dd.clipper) buf->priv.dd.clipper->Release(); if (buf->priv.dd.object) buf->priv.dd.object->Release(); } int evas_software_ddraw_masks_get(Outbuf *buf) { DDPIXELFORMAT pixel_format; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format))) return 0; buf->priv.mask.r = pixel_format.dwRBitMask; buf->priv.mask.g = pixel_format.dwGBitMask; buf->priv.mask.b = pixel_format.dwBBitMask; return 1; } void * evas_software_ddraw_lock(Outbuf *buf, int *ddraw_width, int *ddraw_height, int *ddraw_pitch, int *ddraw_depth) { DDSURFACEDESC surface_desc; ZeroMemory(&surface_desc, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); if (FAILED(buf->priv.dd.surface_back->Lock(NULL, &surface_desc, DDLOCK_WAIT | DDLOCK_SURFACEMEMORYPTR, NULL))) return NULL; *ddraw_width = surface_desc.dwWidth; *ddraw_height = surface_desc.dwHeight; *ddraw_pitch = surface_desc.lPitch; *ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3; return surface_desc.lpSurface; } void evas_software_ddraw_unlock_and_flip(Outbuf *buf) { RECT dst_rect; RECT src_rect; POINT p; if (FAILED(buf->priv.dd.surface_back->Unlock(NULL))) return; /* we figure out where on the primary surface our window lives */ p.x = 0; p.y = 0; ClientToScreen(buf->priv.dd.window, &p); GetClientRect(buf->priv.dd.window, &dst_rect); OffsetRect(&dst_rect, p.x, p.y); SetRect(&src_rect, 0, 0, buf->width, buf->height); /* nothing to do if the function fails, so we don't check the result */ buf->priv.dd.surface_primary->Blt(&dst_rect, buf->priv.dd.surface_back, &src_rect, DDBLT_WAIT, NULL); } void evas_software_ddraw_surface_resize(Outbuf *buf) { DDSURFACEDESC surface_desc; buf->priv.dd.surface_back->Release(); memset (&surface_desc, 0, sizeof (surface_desc)); surface_desc.dwSize = sizeof (surface_desc); /* FIXME: that code does not compile. Must know why */ #if 0 surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH; surface_desc.dwWidth = width; surface_desc.dwHeight = height; buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL); #else surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = buf->width; surface_desc.dwHeight = buf->height; buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); #endif }
#include "evas_common.h" #include "evas_engine.h" int evas_software_ddraw_init (HWND window, int depth, int fullscreen, Outbuf *buf) { DDSURFACEDESC surface_desc; DDPIXELFORMAT pixel_format; HRESULT res; int width; int height; if (!buf) return 0; buf->priv.dd.window = window; res = DirectDrawCreate(NULL, &buf->priv.dd.object, NULL); if (FAILED(res)) return 0; if (buf->priv.dd.fullscreen) { DDSCAPS caps; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_EXCLUSIVE | DDSCL_FULLSCREEN); if (FAILED(res)) goto release_object; width = GetSystemMetrics(SM_CXSCREEN); height = GetSystemMetrics(SM_CYSCREEN); ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_object; buf->priv.dd.depth = depth; res = buf->priv.dd.object->SetDisplayMode(width, height, depth); if (FAILED(res)) goto release_object; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_BACKBUFFERCOUNT; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE | DDSCAPS_FLIP | DDSCAPS_COMPLEX; surface_desc.dwBackBufferCount = 1; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_object; caps.dwCaps = DDSCAPS_BACKBUFFER; res = buf->priv.dd.surface_primary->GetAttachedSurface(&caps, &buf->priv.dd.surface_back); if (FAILED(res)) goto release_surface_primary; } else { RECT rect; if (!GetClientRect(window, &rect)) goto release_object; width = rect.right - rect.left; height = rect.bottom - rect.top; res = buf->priv.dd.object->SetCooperativeLevel(window, DDSCL_NORMAL); if (FAILED(res)) goto release_object; res = buf->priv.dd.object->CreateClipper(0, &buf->priv.dd.clipper, NULL); if (FAILED(res)) goto release_object; res = buf->priv.dd.clipper->SetHWnd(0, window); if (FAILED(res)) goto release_clipper; memset(&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS; surface_desc.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_primary, NULL); if (FAILED(res)) goto release_clipper; res = buf->priv.dd.surface_primary->SetClipper(buf->priv.dd.clipper); if (FAILED(res)) goto release_surface_primary; memset (&surface_desc, 0, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = width; surface_desc.dwHeight = height; res = buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); if (FAILED(res)) goto release_surface_primary; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format); if (pixel_format.dwRGBBitCount != depth) goto release_surface_back; buf->priv.dd.depth = depth; } return 1; release_surface_back: buf->priv.dd.surface_back->Release(); release_surface_primary: buf->priv.dd.surface_primary->Release(); release_clipper: if (buf->priv.dd.fullscreen) buf->priv.dd.clipper->Release(); release_object: buf->priv.dd.object->Release(); return 0; } void evas_software_ddraw_shutdown(Outbuf *buf) { if (!buf) return; if (buf->priv.dd.fullscreen) if (buf->priv.dd.surface_back) buf->priv.dd.surface_back->Release(); if (buf->priv.dd.surface_primary) buf->priv.dd.surface_primary->Release(); if (buf->priv.dd.fullscreen) if (buf->priv.dd.clipper) buf->priv.dd.clipper->Release(); if (buf->priv.dd.object) buf->priv.dd.object->Release(); } int evas_software_ddraw_masks_get(Outbuf *buf) { DDPIXELFORMAT pixel_format; ZeroMemory(&pixel_format, sizeof(pixel_format)); pixel_format.dwSize = sizeof(pixel_format); if (FAILED(buf->priv.dd.surface_primary->GetPixelFormat(&pixel_format))) return 0; buf->priv.mask.r = pixel_format.dwRBitMask; buf->priv.mask.g = pixel_format.dwGBitMask; buf->priv.mask.b = pixel_format.dwBBitMask; return 1; } void * evas_software_ddraw_lock(Outbuf *buf, int *ddraw_width, int *ddraw_height, int *ddraw_pitch, int *ddraw_depth) { DDSURFACEDESC surface_desc; ZeroMemory(&surface_desc, sizeof(surface_desc)); surface_desc.dwSize = sizeof(surface_desc); if (FAILED(buf->priv.dd.surface_back->Lock(NULL, &surface_desc, DDLOCK_WAIT | DDLOCK_WRITEONLY | DDLOCK_SURFACEMEMORYPTR | DDLOCK_NOSYSLOCK, NULL))) return NULL; *ddraw_width = surface_desc.dwWidth; *ddraw_height = surface_desc.dwHeight; *ddraw_pitch = surface_desc.lPitch; *ddraw_depth = surface_desc.ddpfPixelFormat.dwRGBBitCount >> 3; return surface_desc.lpSurface; } void evas_software_ddraw_unlock_and_flip(Outbuf *buf) { RECT dst_rect; RECT src_rect; POINT p; if (FAILED(buf->priv.dd.surface_back->Unlock(NULL))) return; /* we figure out where on the primary surface our window lives */ p.x = 0; p.y = 0; ClientToScreen(buf->priv.dd.window, &p); GetClientRect(buf->priv.dd.window, &dst_rect); OffsetRect(&dst_rect, p.x, p.y); SetRect(&src_rect, 0, 0, buf->width, buf->height); /* nothing to do if the function fails, so we don't check the result */ buf->priv.dd.surface_primary->Blt(&dst_rect, buf->priv.dd.surface_back, &src_rect, DDBLT_WAIT, NULL); } void evas_software_ddraw_surface_resize(Outbuf *buf) { DDSURFACEDESC surface_desc; buf->priv.dd.surface_back->Release(); memset (&surface_desc, 0, sizeof (surface_desc)); surface_desc.dwSize = sizeof (surface_desc); /* FIXME: that code does not compile. Must know why */ #if 0 surface_desc.dwFlags = DDSD_HEIGHT | DDSD_WIDTH; surface_desc.dwWidth = width; surface_desc.dwHeight = height; buf->priv.dd.surface_back->SetSurfaceDesc(&surface_desc, NULL); #else surface_desc.dwFlags = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH; surface_desc.ddsCaps.dwCaps = DDSCAPS_OFFSCREENPLAIN; surface_desc.dwWidth = buf->width; surface_desc.dwHeight = buf->height; buf->priv.dd.object->CreateSurface(&surface_desc, &buf->priv.dd.surface_back, NULL); #endif }
optimize ddraw engine : when locking a surface, don't allow Windows to suspend operations. expedite runs with around 7 points more than without those flags on my computer
optimize ddraw engine : when locking a surface, don't allow Windows to suspend operations. expedite runs with around 7 points more than without those flags on my computer git-svn-id: 6d771e449150288cc513807b7f4d2af31e9482bd@39316 7cbeb6ba-43b4-40fd-8cce-4c39aea84d33
C++
bsd-2-clause
TizenChameleon/uifw-evas,TizenChameleon/evas,nashidau/Evas-Next,TizenChameleon/evas,TizenChameleon/evas,nashidau/Evas-Next,TizenChameleon/uifw-evas,TizenChameleon/uifw-evas,TizenChameleon/uifw-evas,nashidau/Evas-Next,TizenChameleon/evas
cf3e94bb7f540ca48b569363b31f9c42669a97de
WangscapeTest/TestModuleGroup.cpp
WangscapeTest/TestModuleGroup.cpp
#include <gtest/gtest.h> #include <ModuleFactories.h> class TestModuleGroup : public ::testing::Test { protected: Reseedable rs; TestModuleGroup() : rs(makePlaceholder()) { }; ~TestModuleGroup() {}; }; TEST_F(TestModuleGroup, TestGetValue) { rs.module->GetValue(0.,1.,2.); } TEST_F(TestModuleGroup, TestSetSeed) { rs.setSeed(35089); double v = rs.module->GetValue(2., 1., 0.); rs.setSeed(293847928); ASSERT_NE(v, rs.module->GetValue(2., 1., 0.)) << "Same value after reseed"; }
#include <gtest/gtest.h> #include <ModuleFactories.h> class TestModuleGroup : public ::testing::Test { protected: Reseedable rs; TestModuleGroup() : rs(makePlaceholder()) { // The current placeholder is a Reseedable, // but it's not a ModuleGroup. // Maybe these tests should be moved. }; ~TestModuleGroup() {}; }; TEST_F(TestModuleGroup, TestGetValue) { rs.module->GetValue(0.,1.,2.); } TEST_F(TestModuleGroup, TestSetSeed) { rs.setSeed(35089); double v = rs.module->GetValue(2.1, 1.1, 0.1); rs.setSeed(293847928); ASSERT_NE(v, rs.module->GetValue(2.1, 1.1, 0.1)) << "Same value after reseed"; }
Fix reseed test
Fix reseed test
C++
mit
Wangscape/Wangscape,serin-delaunay/Wangscape,serin-delaunay/Wangscape,Wangscape/Wangscape,Wangscape/Wangscape
16d81abb09cc5a15d98a140de025ee63dd76e6f1
protocols/oscar/oscarsocket/oscarmessage.cpp
protocols/oscar/oscarsocket/oscarmessage.cpp
#include <qregexp.h> #include <qstylesheet.h> #include <kdebug.h> #include "oscarmessage.h" #include "rtf2html.h" OscarMessage::OscarMessage() { timestamp = QDateTime::currentDateTime(); } void OscarMessage::setText(const QString &txt, MessageFormat format) { if(format == AimHtml) { kdDebug(14151) << k_funcinfo << "AIM message text: " << txt << endl; mText = txt; mText.replace( QRegExp("<html.*>(.*)</html>", false), "\\1"); mText.replace( QRegExp("<body.*>(.*)</body>", false), "\\1"); QRegExp re("<font(.*)back=\"(.*)\"(.*)>(.*)</font>", false); re.setMinimal(true); mText.replace(re, "<font\\1style=\"background-color:\\2\"\\3>\\4</font>"); } else if (format == Plain) { mText = QStyleSheet::escape(txt); mText.replace("\n", "<br/>"); mText.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp; "); mText.replace(QRegExp("\\s\\s"), "&nbsp; "); } else { RTF2HTML parser; /*kdDebug(14151) << k_funcinfo << "Original message text: " << txt << endl;*/ //TODO: encoding mText = parser.Parse(txt.latin1(), ""); /*kdDebug(14151) << k_funcinfo << "Message text after RTF2HTML: " << mText << endl;*/ } } const QString &OscarMessage::text() { return mText; } const OscarMessage::MessageType OscarMessage::type() { return mType; } void OscarMessage::setType(const MessageType val) { mType = val; }
#include <qregexp.h> #include <qstylesheet.h> #include <kdebug.h> #include "oscarmessage.h" #include "rtf2html.h" OscarMessage::OscarMessage() { timestamp = QDateTime::currentDateTime(); } void OscarMessage::setText(const QString &txt, MessageFormat format) { if(format == AimHtml) { kdDebug(14151) << k_funcinfo << "AIM message text: " << txt << endl; mText = txt; mText.replace( QRegExp("<html.*>(.*)</html>", false), "\\1"); mText.replace( QRegExp("<body.*>(.*)</body>", false), "\\1"); QRegExp re("<font([^>]*)back=\"([^\">]*)\"([^>]*)>", false); mText.replace(re, "<font\\1style=\"background-color:\\2\"\\3>"); } else if (format == Plain) { mText = QStyleSheet::escape(txt); mText.replace("\n", "<br/>"); mText.replace("\t", "&nbsp;&nbsp;&nbsp;&nbsp; "); mText.replace(QRegExp("\\s\\s"), "&nbsp; "); } else { RTF2HTML parser; /*kdDebug(14151) << k_funcinfo << "Original message text: " << txt << endl;*/ //TODO: encoding mText = parser.Parse(txt.latin1(), ""); /*kdDebug(14151) << k_funcinfo << "Message text after RTF2HTML: " << mText << endl;*/ } } const QString &OscarMessage::text() { return mText; } const OscarMessage::MessageType OscarMessage::type() { return mType; } void OscarMessage::setType(const MessageType val) { mType = val; }
Simplify font tag mangling regexp. No longer needs minimal matching. No longer breaks on nested font tags. Should be marginally faster now too :) Matt: I figured you might want this in oscar_rewrite, so... CCMAIL: [email protected]
Simplify font tag mangling regexp. No longer needs minimal matching. No longer breaks on nested font tags. Should be marginally faster now too :) Matt: I figured you might want this in oscar_rewrite, so... CCMAIL: [email protected] svn path=/trunk/kdenetwork/kopete/; revision=352144
C++
lgpl-2.1
josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136
5f609d1685c85d6fb58ea9969bb66cab50bf81ae
sdlpp.hpp
sdlpp.hpp
#pragma once #include <SDL.h> #include <sstream> #include <functional> namespace sdl { class Error: public std::runtime_error { public: using std::runtime_error::runtime_error; }; class Init { public: template <typename ...Args> Init(Args... args) { auto res = SDL_Init(args...); if (res < 0) { std::ostringstream strm; strm << "Init::Init(): " << SDL_GetError(); throw Error(strm.str()); } } Init(const Init&) = delete; Init &operator=(const Init&) = delete; ~Init() { SDL_Quit(); } }; #define SDL_CLASS(X) \ class X \ { \ public: \ template <typename ...Args> \ X(Args... args) \ { \ handle = SDL_Create##X(args...); \ if (!handle) \ { \ std::ostringstream strm; \ strm << #X"::"#X"(): " << SDL_GetError(); \ throw Error(strm.str()); \ } \ } \ X(SDL_##X *handle): handle(handle) \ {} \ X(const X&) = delete; \ X&operator=(const X&) = delete; \ X&operator=(X&&x) \ { \ handle = x.handle; \ x.handle = 0; \ return *this; \ } \ X(X&& x): \ handle(x.handle) \ { \ x.handle = 0; \ } \ ~X() \ { \ if (handle) \ SDL_Destroy##X(handle); \ } \ SDL_##X *operator&() \ { \ return handle; \ } \ const SDL_##X *operator&() const \ { \ return handle; \ } \ private: \ SDL_##X *handle; \ public: \ SDL_CLASS_METHOD_LIST \ } template <typename R, typename ...Args2, typename ...Args> auto callSdl(R (f)(Args2...), Args... args) -> decltype(f(args...)) { return f(args...); } template <typename R, typename ...Args2, typename ...Args> auto callSdl(R *(f)(Args2...), Args... args) -> decltype(f(args...)) { auto r = f(args...); if (r == nullptr) { throw Error(std::string("Error string: ") + SDL_GetError()); } return r; } template <typename ...Args2, typename ...Args> auto callSdl(int (f)(Args2...), Args... args) -> decltype(f(args...)) { auto r = f(args...); if (r == -1) { throw Error("Error code: " + std::to_string(r) + " Error string: " + SDL_GetError()); } return r; } template <typename ...Args2, typename ...Args> auto callSdl(void (f)(Args2...), Args... args) -> decltype(f(args...)) { f(args...); } #define METHOD(X, Y) \ template <typename ...Args> \ auto X(Args... args) -> decltype(SDL_##Y(handle, args...)) \ { \ return callSdl(SDL_##Y, handle, args...); \ } #define SDL_CLASS_METHOD_LIST \ METHOD(glCreateContext, GL_CreateContext); \ METHOD(glGetDrawableSize, GL_GetDrawableSize); \ METHOD(glMakeCurrent, GL_MakeCurrent); \ METHOD(glSwap, GL_SwapWindow); \ METHOD(getBrightness, GetWindowBrightness); \ METHOD(getData, GetWindowData); \ METHOD(getDisplayIndex, GetWindowDisplayIndex); \ METHOD(getDisplayMode, GetWindowDisplayMode); \ METHOD(getFlags, GetWindowFlags); \ METHOD(getGammaRamp, GetWindowGammaRamp); \ METHOD(getGrab, GetWindowGrab); \ METHOD(getID, GetWindowID); \ METHOD(getMaximumSize, GetWindowMaximumSize); \ METHOD(getMinimumSize, GetWindowMinimumSize); \ METHOD(getPixelFormat, GetWindowPixelFormat); \ METHOD(getPosition, GetWindowPosition); \ METHOD(getSize, GetWindowSize); \ METHOD(getSurface, GetWindowSurface); \ METHOD(getTitle, GetWindowTitle); \ METHOD(hide, HideWindow); \ METHOD(maximize, MaximizeWindow); \ METHOD(minimize, MinimizeWindow); \ METHOD(raise, RaiseWindow); \ METHOD(restore, RestoreWindow); \ METHOD(setBordered, SetWindowBordered); \ METHOD(setBrightness, SetWindowBrightness); \ METHOD(setData, SetWindowData); \ METHOD(setDisplayMode, SetWindowDisplayMode); \ METHOD(setFullscreen, SetWindowFullscreen); \ METHOD(setGammaRamp, SetWindowGammaRamp); \ METHOD(setGrab, SetWindowGrab); \ METHOD(setHitTest, SetWindowHitTest); \ METHOD(setIcon, SetWindowIcon); \ METHOD(setMaximumSize, SetWindowMaximumSize); \ METHOD(setMinimumSize, SetWindowMinimumSize); \ METHOD(setPosition, SetWindowPosition); \ METHOD(setSize, SetWindowSize); \ METHOD(setTitle, SetWindowTitle); \ METHOD(show, ShowWindow); \ METHOD(updateSurface, UpdateWindowSurface); \ METHOD(updateSurfaceRects, UpdateWindowSurfaceRects); SDL_CLASS(Window); #undef SDL_CLASS_METHOD_LIST #define SDL_CLASS_METHOD_LIST \ METHOD(getDrawBlendMode, GetRenderDrawBlendMode); \ METHOD(getDrawColor, GetRenderDrawColor); \ METHOD(getDriverInfo, GetRenderDriverInfo); \ METHOD(getTarget, GetRenderTarget); \ METHOD(getInfo, GetRendererInfo); \ METHOD(getOutputSize, GetRendererOutputSize); \ METHOD(clear, RenderClear); \ METHOD(copy, RenderCopy); \ METHOD(copyEx, RenderCopyEx); \ METHOD(drawLine, RenderDrawLine); \ METHOD(drawLines, RenderDrawLines); \ METHOD(drawPoint, RenderDrawPoint); \ METHOD(drawPoints, RenderDrawPoints); \ METHOD(drawRect, RenderDrawRect); \ METHOD(drawRects, RenderDrawRects); \ METHOD(fillRect, RenderFillRect); \ METHOD(fillRects, RenderFillRects); \ METHOD(getClipRect, RenderGetClipRect); \ METHOD(getLogicalSize, RenderGetLogicalSize); \ METHOD(getScale, RenderGetScale); \ METHOD(getViewport, RenderGetViewport); \ METHOD(isClipEnabled, RenderIsClipEnabled); \ METHOD(present, RenderPresent); \ METHOD(readPixels, RenderReadPixels); \ METHOD(setClipRect, RenderSetClipRect); \ METHOD(setLogicalSize, RenderSetLogicalSize); \ METHOD(setScale, RenderSetScale); \ METHOD(setViewport, RenderSetViewport); \ METHOD(targetSupported, RenderTargetSupported); \ METHOD(setDrawBlendMode, SetRenderDrawBlendMode); \ METHOD(setDrawColor, SetRenderDrawColor); \ METHOD(setTarget, SetRenderTarget); SDL_CLASS(Renderer); #undef SDL_CLASS_METHOD_LIST #define SDL_CLASS_METHOD_LIST \ Texture(SDL_Renderer *renderer, SDL_Surface *surface): \ handle(SDL_CreateTextureFromSurface(renderer, surface)) \ { \ if (!handle) \ { \ std::ostringstream strm; \ strm << "Texture::Texture(): " << SDL_GetError(); \ throw Error(strm.str()); \ } \ } \ METHOD(glBind, GL_BindTexture); \ METHOD(glUnbind, GL_UnbindTexture); \ METHOD(getAlphaMod, GetTextureAlphaMod); \ METHOD(getBlendMode, GetTextureBlendMode); \ METHOD(getColorMod, GetTextureColorMod); \ METHOD(lock, LockTexture); \ METHOD(query, QueryTexture); \ METHOD(setAlphaMod, SetTextureAlphaMod); \ METHOD(setBlendMode, SetTextureBlendMode); \ METHOD(setColorMod, SetTextureColorMod); \ METHOD(unlock, UnlockTexture); \ METHOD(update, UpdateTexture); \ METHOD(updateYuv, UpdateYUVTexture); SDL_CLASS(Texture); class Surface { void checkErrors() { if (!handle) { std::ostringstream strm; strm << "Surface::Surface(): " << SDL_GetError(); throw Error(strm.str()); } } public: Surface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask): handle(SDL_CreateRGBSurface(flags, width, height, depth, Rmask, Gmask, Bmask, Amask)) { checkErrors(); } Surface(SDL_RWops *src, int freesrc): handle(SDL_LoadBMP_RW(src, freesrc)) { checkErrors(); } Surface(const std::string &file): handle(SDL_LoadBMP(file.c_str())) { checkErrors(); } Surface(SDL_Surface * src, const SDL_PixelFormat * fmt, Uint32 flags): handle(SDL_ConvertSurface(src, fmt, flags)) { checkErrors(); } Surface(SDL_Surface * src, Uint32 pixel_format, Uint32 flags): handle(SDL_ConvertSurfaceFormat(src, pixel_format, flags)) { checkErrors(); } Surface(SDL_Surface *handle): handle(handle) {} Surface(const Surface &) = delete; Surface& operator=(const Surface &) = delete; ~Surface() { SDL_FreeSurface(handle); } SDL_Surface *operator&() { return handle; } const SDL_Surface *operator&() const { return handle; } private: SDL_Surface *handle; public: METHOD(setPalette, SetSurfacePalette); METHOD(lock, LockSurface); METHOD(unlock, UnlockSurface); METHOD(setColorKey, SetColorKey); METHOD(getColorKey, GetColorKey); METHOD(setColorMode, SetSurfaceColorMod); METHOD(getColorMode, GetSurfaceColorMod); METHOD(setClipRect, SetClipRect); METHOD(getClipRect, GetClipRect); METHOD(fillRect, FillRect); METHOD(fillRects, FillRects); METHOD(blit, BlitSurface); METHOD(softStretch, SoftStretch); METHOD(blitScaled, BlitScaled); }; class Audio { public: Audio(const char *device, bool iscapture, const SDL_AudioSpec *desired, SDL_AudioSpec *obtained, int allowed_changes, std::function<void(Uint8 *stream, int len)> callback = nullptr): callback(callback) { if (desired) { SDL_AudioSpec tmp; tmp = *desired; if (callback) { tmp.callback = Audio::internalCallback; tmp.userdata = this; } else { tmp.callback = nullptr; } handle = SDL_OpenAudioDevice(device, iscapture, &tmp, obtained, allowed_changes); } else { handle = SDL_OpenAudioDevice(device, iscapture, desired, obtained, allowed_changes); } if (handle <= 0) { std::ostringstream strm; strm << "Audio::Audio(): " << SDL_GetError(); throw Error(strm.str()); } } Audio(SDL_AudioDeviceID handle): handle(handle) {} Audio(const Audio&) = delete; Audio&operator=(const Audio&) = delete; ~Audio() { SDL_CloseAudioDevice(handle); } SDL_AudioDeviceID operator&() { return handle; } private: SDL_AudioDeviceID handle; std::function<void(Uint8 *stream, int len)> callback; static void internalCallback(void *userdata, Uint8 *stream, int len) { static_cast<Audio *>(userdata)->callback(stream, len); } public: METHOD(clearQueued, ClearQueuedAudio); METHOD(getStatus, GetAudioDeviceStatus); METHOD(getQueuedSize, GetQueuedAudioSize); METHOD(lock, LockAudioDevice); METHOD(pause, PauseAudioDevice) METHOD(queue, QueueAudio); METHOD(unlock, UnlockAudioDevice); }; class EventHandler { public: bool poll() { SDL_Event e; if (SDL_PollEvent(&e)) { handleEvent(e); return true; } else return false; } void wait(int timeout = -1) { SDL_Event e; int res; if (timeout >= 0) res = SDL_WaitEvent(&e); else res = SDL_WaitEventTimeout(&e, timeout); if (res) handleEvent(e); else { std::ostringstream strm; strm << "EventHandler::wait(): " << SDL_GetError(); throw Error(strm.str()); } } #define SDL_EVENTS \ EVENT(SDL_AUDIODEVICEADDED, audioDeviceAdded, adevice); \ EVENT(SDL_AUDIODEVICEREMOVED, audioDeviceRemoved, adevice); \ EVENT(SDL_CONTROLLERAXISMOTION, controllerAxisMotion, caxis); \ EVENT(SDL_CONTROLLERBUTTONDOWN, controllerButtonDown, cbutton); \ EVENT(SDL_CONTROLLERBUTTONUP, controllerButtonUp, cbutton); \ EVENT(SDL_CONTROLLERDEVICEADDED, controllerDeviceAdded, cdevice); \ EVENT(SDL_CONTROLLERDEVICEREMOVED, controllerDeviceRemoved, cdevice); \ EVENT(SDL_CONTROLLERDEVICEREMAPPED, controllerDeviceRemapped, cdevice); \ EVENT(SDL_DOLLARGESTURE, dollarGesture, dgesture); \ EVENT(SDL_DOLLARRECORD, dollarRecord, dgesture); \ EVENT(SDL_DROPFILE, dropFile, drop); \ EVENT(SDL_FINGERMOTION, fingerMotion, tfinger); \ EVENT(SDL_FINGERDOWN, fingerDown, tfinger); \ EVENT(SDL_FINGERUP, fingerUp, tfinger); \ EVENT(SDL_KEYDOWN, keyDown, key); \ EVENT(SDL_KEYUP, keyUp, key); \ EVENT(SDL_JOYAXISMOTION, joyAxisMotion, jaxis); \ EVENT(SDL_JOYBALLMOTION, joyBallMotion, jball); \ EVENT(SDL_JOYHATMOTION, joyHatMotion, jhat); \ EVENT(SDL_JOYBUTTONDOWN, joyButtonDown, jbutton); \ EVENT(SDL_JOYBUTTONUP, joyButtonUp, jbutton); \ EVENT(SDL_JOYDEVICEADDED, joyDeviceAdded, jdevice); \ EVENT(SDL_JOYDEVICEREMOVED, joyDeviceRemoved, jdevice); \ EVENT(SDL_MOUSEMOTION, mouseMotion, motion); \ EVENT(SDL_MOUSEBUTTONDOWN, mouseButtonDown, button); \ EVENT(SDL_MOUSEBUTTONUP, mouseButtonUp, button); \ EVENT(SDL_MOUSEWHEEL, mouseWheel, wheel); \ EVENT(SDL_MULTIGESTURE, multiGesture, mgesture); \ EVENT(SDL_QUIT, quit, quit); \ EVENT(SDL_SYSWMEVENT, sysWmEvent, syswm); \ EVENT(SDL_TEXTEDITING, textEditing, edit); \ EVENT(SDL_TEXTINPUT, textInput, text); \ EVENT(SDL_USEREVENT, userEvent, user); \ EVENT(SDL_WINDOWEVENT, windowEvent, window); #define EVENT(x, y, z) std::function<void(const decltype(SDL_Event::z) &)> y SDL_EVENTS #undef EVENT private: void handleEvent(const SDL_Event &e) { switch (e.type) { #define EVENT(x, y, z) \ case x: \ if (y) \ y(e.z); \ break; SDL_EVENTS #undef EVENT default: break; } } }; }
/* This source file is part of sdlpp (C++ wrapper for SDL2) Copyright (c) 2017 Anton Te 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. */ #pragma once #include <SDL2/SDL.h> #include <functional> #include <sstream> namespace sdl { class Error : public std::runtime_error { public: using std::runtime_error::runtime_error; }; class Init { public: template <typename... Args> Init(Args... args) { auto res = SDL_Init(args...); if (res < 0) { std::ostringstream strm; strm << "Init::Init(): " << SDL_GetError(); throw Error(strm.str()); } } Init(const Init &) = delete; Init &operator=(const Init &) = delete; ~Init() { SDL_Quit(); } }; #define SDL_CLASS(X) \ class X \ { \ public: \ template <typename... Args> \ X(Args... args) \ { \ handle = SDL_Create##X(args...); \ if (!handle) \ { \ std::ostringstream strm; \ strm << #X "::" #X "(): " << SDL_GetError(); \ throw Error(strm.str()); \ } \ } \ X(SDL_##X *handle) : handle(handle) {} \ X(const X &) = delete; \ X &operator=(const X &) = delete; \ X &operator=(X &&x) \ { \ handle = x.handle; \ x.handle = 0; \ return *this; \ } \ X(X &&x) : handle(x.handle) { x.handle = 0; } \ ~X() \ { \ if (handle) \ SDL_Destroy##X(handle); \ } \ SDL_##X *get() { return handle; } \ const SDL_##X *get() const { return handle; } \ private: \ SDL_##X *handle; \ \ public: \ SDL_CLASS_METHOD_LIST \ } template <typename R, typename... Args2, typename... Args> auto callSdl(R(f)(Args2...), Args... args) -> decltype(f(args...)) { return f(args...); } template <typename R, typename... Args2, typename... Args> auto callSdl(R *(f)(Args2...), Args... args) -> decltype(f(args...)) { auto r = f(args...); if (r == nullptr) { throw Error(std::string("Error string: ") + SDL_GetError()); } return r; } template <typename... Args2, typename... Args> auto callSdl(int(f)(Args2...), Args... args) -> decltype(f(args...)) { auto r = f(args...); if (r == -1) { throw Error("Error code: " + std::to_string(r) + " Error string: " + SDL_GetError()); } return r; } template <typename... Args2, typename... Args> auto callSdl(void(f)(Args2...), Args... args) -> decltype(f(args...)) { f(args...); } #define METHOD(X, Y) \ template <typename... Args> \ auto X(Args... args)->decltype(SDL_##Y(handle, args...)) \ { \ return callSdl(SDL_##Y, handle, args...); \ } #define SDL_CLASS_METHOD_LIST \ METHOD(glCreateContext, GL_CreateContext); \ METHOD(glGetDrawableSize, GL_GetDrawableSize); \ METHOD(glMakeCurrent, GL_MakeCurrent); \ METHOD(glSwap, GL_SwapWindow); \ METHOD(getBrightness, GetWindowBrightness); \ METHOD(getData, GetWindowData); \ METHOD(getDisplayIndex, GetWindowDisplayIndex); \ METHOD(getDisplayMode, GetWindowDisplayMode); \ METHOD(getFlags, GetWindowFlags); \ METHOD(getGammaRamp, GetWindowGammaRamp); \ METHOD(getGrab, GetWindowGrab); \ METHOD(getID, GetWindowID); \ METHOD(getMaximumSize, GetWindowMaximumSize); \ METHOD(getMinimumSize, GetWindowMinimumSize); \ METHOD(getPixelFormat, GetWindowPixelFormat); \ METHOD(getPosition, GetWindowPosition); \ METHOD(getSize, GetWindowSize); \ METHOD(getSurface, GetWindowSurface); \ METHOD(getTitle, GetWindowTitle); \ METHOD(hide, HideWindow); \ METHOD(maximize, MaximizeWindow); \ METHOD(minimize, MinimizeWindow); \ METHOD(raise, RaiseWindow); \ METHOD(restore, RestoreWindow); \ METHOD(setBordered, SetWindowBordered); \ METHOD(setBrightness, SetWindowBrightness); \ METHOD(setData, SetWindowData); \ METHOD(setDisplayMode, SetWindowDisplayMode); \ METHOD(setFullscreen, SetWindowFullscreen); \ METHOD(setGammaRamp, SetWindowGammaRamp); \ METHOD(setGrab, SetWindowGrab); \ METHOD(setHitTest, SetWindowHitTest); \ METHOD(setIcon, SetWindowIcon); \ METHOD(setMaximumSize, SetWindowMaximumSize); \ METHOD(setMinimumSize, SetWindowMinimumSize); \ METHOD(setPosition, SetWindowPosition); \ METHOD(setSize, SetWindowSize); \ METHOD(setTitle, SetWindowTitle); \ METHOD(show, ShowWindow); \ METHOD(updateSurface, UpdateWindowSurface); \ METHOD(updateSurfaceRects, UpdateWindowSurfaceRects); SDL_CLASS(Window); #undef SDL_CLASS_METHOD_LIST #define SDL_CLASS_METHOD_LIST \ METHOD(getDrawBlendMode, GetRenderDrawBlendMode); \ METHOD(getDrawColor, GetRenderDrawColor); \ METHOD(getDriverInfo, GetRenderDriverInfo); \ METHOD(getTarget, GetRenderTarget); \ METHOD(getInfo, GetRendererInfo); \ METHOD(getOutputSize, GetRendererOutputSize); \ METHOD(clear, RenderClear); \ METHOD(copy, RenderCopy); \ METHOD(copyEx, RenderCopyEx); \ METHOD(drawLine, RenderDrawLine); \ METHOD(drawLines, RenderDrawLines); \ METHOD(drawPoint, RenderDrawPoint); \ METHOD(drawPoints, RenderDrawPoints); \ METHOD(drawRect, RenderDrawRect); \ METHOD(drawRects, RenderDrawRects); \ METHOD(fillRect, RenderFillRect); \ METHOD(fillRects, RenderFillRects); \ METHOD(getClipRect, RenderGetClipRect); \ METHOD(getLogicalSize, RenderGetLogicalSize); \ METHOD(getScale, RenderGetScale); \ METHOD(getViewport, RenderGetViewport); \ METHOD(isClipEnabled, RenderIsClipEnabled); \ METHOD(present, RenderPresent); \ METHOD(readPixels, RenderReadPixels); \ METHOD(setClipRect, RenderSetClipRect); \ METHOD(setLogicalSize, RenderSetLogicalSize); \ METHOD(setScale, RenderSetScale); \ METHOD(setViewport, RenderSetViewport); \ METHOD(targetSupported, RenderTargetSupported); \ METHOD(setDrawBlendMode, SetRenderDrawBlendMode); \ METHOD(setDrawColor, SetRenderDrawColor); \ METHOD(setTarget, SetRenderTarget); SDL_CLASS(Renderer); #undef SDL_CLASS_METHOD_LIST #define SDL_CLASS_METHOD_LIST \ Texture(SDL_Renderer *renderer, SDL_Surface *surface) \ : handle(SDL_CreateTextureFromSurface(renderer, surface)) \ { \ if (!handle) \ { \ std::ostringstream strm; \ strm << "Texture::Texture(): " << SDL_GetError(); \ throw Error(strm.str()); \ } \ } \ METHOD(glBind, GL_BindTexture); \ METHOD(glUnbind, GL_UnbindTexture); \ METHOD(getAlphaMod, GetTextureAlphaMod); \ METHOD(getBlendMode, GetTextureBlendMode); \ METHOD(getColorMod, GetTextureColorMod); \ METHOD(lock, LockTexture); \ METHOD(query, QueryTexture); \ METHOD(setAlphaMod, SetTextureAlphaMod); \ METHOD(setBlendMode, SetTextureBlendMode); \ METHOD(setColorMod, SetTextureColorMod); \ METHOD(unlock, UnlockTexture); \ METHOD(update, UpdateTexture); \ METHOD(updateYuv, UpdateYUVTexture); SDL_CLASS(Texture); class Surface { void checkErrors() { if (!handle) { std::ostringstream strm; strm << "Surface::Surface(): " << SDL_GetError(); throw Error(strm.str()); } } public: Surface(Uint32 flags, int width, int height, int depth, Uint32 Rmask, Uint32 Gmask, Uint32 Bmask, Uint32 Amask) : handle(SDL_CreateRGBSurface(flags, width, height, depth, Rmask, Gmask, Bmask, Amask)) { checkErrors(); } Surface(SDL_RWops *src, int freesrc) : handle(SDL_LoadBMP_RW(src, freesrc)) { checkErrors(); } Surface(const std::string &file) : handle(SDL_LoadBMP(file.c_str())) { checkErrors(); } Surface(SDL_Surface *src, const SDL_PixelFormat *fmt, Uint32 flags) : handle(SDL_ConvertSurface(src, fmt, flags)) { checkErrors(); } Surface(SDL_Surface *src, Uint32 pixel_format, Uint32 flags) : handle(SDL_ConvertSurfaceFormat(src, pixel_format, flags)) { checkErrors(); } Surface(SDL_Surface *handle) : handle(handle) {} Surface(const Surface &) = delete; Surface &operator=(const Surface &) = delete; ~Surface() { SDL_FreeSurface(handle); } SDL_Surface *operator&() { return handle; } const SDL_Surface *operator&() const { return handle; } private: SDL_Surface *handle; public: METHOD(setPalette, SetSurfacePalette); METHOD(lock, LockSurface); METHOD(unlock, UnlockSurface); METHOD(setColorKey, SetColorKey); METHOD(getColorKey, GetColorKey); METHOD(setColorMode, SetSurfaceColorMod); METHOD(getColorMode, GetSurfaceColorMod); METHOD(setClipRect, SetClipRect); METHOD(getClipRect, GetClipRect); METHOD(fillRect, FillRect); METHOD(fillRects, FillRects); METHOD(blit, BlitSurface); METHOD(softStretch, SoftStretch); METHOD(blitScaled, BlitScaled); }; class Audio { public: Audio(const char *device, bool iscapture, const SDL_AudioSpec *desired, SDL_AudioSpec *obtained, int allowed_changes, std::function<void(Uint8 *stream, int len)> callback = nullptr) : callback(callback) { if (desired) { SDL_AudioSpec tmp; tmp = *desired; if (callback) { tmp.callback = Audio::internalCallback; tmp.userdata = this; } else { tmp.callback = nullptr; } handle = SDL_OpenAudioDevice(device, iscapture, &tmp, obtained, allowed_changes); } else { handle = SDL_OpenAudioDevice(device, iscapture, desired, obtained, allowed_changes); } if (handle <= 0) { std::ostringstream strm; strm << "Audio::Audio(): " << SDL_GetError(); throw Error(strm.str()); } } Audio(SDL_AudioDeviceID handle) : handle(handle) {} Audio(const Audio &) = delete; Audio &operator=(const Audio &) = delete; ~Audio() { SDL_CloseAudioDevice(handle); } SDL_AudioDeviceID operator&() { return handle; } private: SDL_AudioDeviceID handle; std::function<void(Uint8 *stream, int len)> callback; static void internalCallback(void *userdata, Uint8 *stream, int len) { static_cast<Audio *>(userdata)->callback(stream, len); } public: METHOD(clearQueued, ClearQueuedAudio); METHOD(getStatus, GetAudioDeviceStatus); METHOD(getQueuedSize, GetQueuedAudioSize); METHOD(lock, LockAudioDevice); METHOD(pause, PauseAudioDevice) METHOD(queue, QueueAudio); METHOD(unlock, UnlockAudioDevice); }; class EventHandler { public: bool poll() { SDL_Event e; if (SDL_PollEvent(&e)) { handleEvent(e); return true; } else return false; } void wait(int timeout = -1) { SDL_Event e; int res; if (timeout >= 0) res = SDL_WaitEvent(&e); else res = SDL_WaitEventTimeout(&e, timeout); if (res) handleEvent(e); else { std::ostringstream strm; strm << "EventHandler::wait(): " << SDL_GetError(); throw Error(strm.str()); } } #define SDL_EVENTS \ EVENT(SDL_AUDIODEVICEADDED, audioDeviceAdded, adevice); \ EVENT(SDL_AUDIODEVICEREMOVED, audioDeviceRemoved, adevice); \ EVENT(SDL_CONTROLLERAXISMOTION, controllerAxisMotion, caxis); \ EVENT(SDL_CONTROLLERBUTTONDOWN, controllerButtonDown, cbutton); \ EVENT(SDL_CONTROLLERBUTTONUP, controllerButtonUp, cbutton); \ EVENT(SDL_CONTROLLERDEVICEADDED, controllerDeviceAdded, cdevice); \ EVENT(SDL_CONTROLLERDEVICEREMOVED, controllerDeviceRemoved, cdevice); \ EVENT(SDL_CONTROLLERDEVICEREMAPPED, controllerDeviceRemapped, cdevice); \ EVENT(SDL_DOLLARGESTURE, dollarGesture, dgesture); \ EVENT(SDL_DOLLARRECORD, dollarRecord, dgesture); \ EVENT(SDL_DROPFILE, dropFile, drop); \ EVENT(SDL_FINGERMOTION, fingerMotion, tfinger); \ EVENT(SDL_FINGERDOWN, fingerDown, tfinger); \ EVENT(SDL_FINGERUP, fingerUp, tfinger); \ EVENT(SDL_KEYDOWN, keyDown, key); \ EVENT(SDL_KEYUP, keyUp, key); \ EVENT(SDL_JOYAXISMOTION, joyAxisMotion, jaxis); \ EVENT(SDL_JOYBALLMOTION, joyBallMotion, jball); \ EVENT(SDL_JOYHATMOTION, joyHatMotion, jhat); \ EVENT(SDL_JOYBUTTONDOWN, joyButtonDown, jbutton); \ EVENT(SDL_JOYBUTTONUP, joyButtonUp, jbutton); \ EVENT(SDL_JOYDEVICEADDED, joyDeviceAdded, jdevice); \ EVENT(SDL_JOYDEVICEREMOVED, joyDeviceRemoved, jdevice); \ EVENT(SDL_MOUSEMOTION, mouseMotion, motion); \ EVENT(SDL_MOUSEBUTTONDOWN, mouseButtonDown, button); \ EVENT(SDL_MOUSEBUTTONUP, mouseButtonUp, button); \ EVENT(SDL_MOUSEWHEEL, mouseWheel, wheel); \ EVENT(SDL_MULTIGESTURE, multiGesture, mgesture); \ EVENT(SDL_QUIT, quit, quit); \ EVENT(SDL_SYSWMEVENT, sysWmEvent, syswm); \ EVENT(SDL_TEXTEDITING, textEditing, edit); \ EVENT(SDL_TEXTINPUT, textInput, text); \ EVENT(SDL_USEREVENT, userEvent, user); \ EVENT(SDL_WINDOWEVENT, windowEvent, window); #define EVENT(x, y, z) std::function<void(const decltype(SDL_Event::z) &)> y SDL_EVENTS #undef EVENT private: void handleEvent(const SDL_Event &e) { switch (e.type) { #define EVENT(x, y, z) \ case x: \ if (y) \ y(e.z); \ break; SDL_EVENTS #undef EVENT default: break; } } }; }
Add copyright text and reformat
Add copyright text and reformat
C++
mit
antonte/sdlpp
6cded74c62a79c4245890d8718cba8fc9831b2f0
src/schedules/examples/thread_per_process_schedule.cxx
src/schedules/examples/thread_per_process_schedule.cxx
/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "thread_per_process_schedule.h" #include <vistk/pipeline/pipeline.h> #include <vistk/pipeline/utils.h> #include <boost/foreach.hpp> #include <boost/thread/thread.hpp> namespace vistk { static void run_process(process_t process); class thread_per_process_schedule::priv { public: priv(); ~priv(); boost::thread_group process_threads; }; thread_per_process_schedule ::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe) : schedule(config, pipe) { d = boost::shared_ptr<priv>(new priv); } thread_per_process_schedule ::~thread_per_process_schedule() { } void thread_per_process_schedule ::start() { BOOST_FOREACH (process::name_t const& name, pipeline()->process_names()) { process_t process = pipeline()->process_by_name(name); d->process_threads.create_thread(boost::bind(run_process, process)); } } void thread_per_process_schedule ::wait() { d->process_threads.join_all(); } void thread_per_process_schedule ::stop() { d->process_threads.interrupt_all(); } thread_per_process_schedule::priv ::priv() { } thread_per_process_schedule::priv ::~priv() { } void run_process(process_t process) { name_thread(process->name()); /// \todo Run the process until it is complete. } }
/*ckwg +5 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel, * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065. */ #include "thread_per_process_schedule.h" #include <vistk/pipeline/pipeline.h> #include <vistk/pipeline/utils.h> #include <boost/foreach.hpp> #include <boost/thread/thread.hpp> namespace vistk { static void run_process(process_t process); class thread_per_process_schedule::priv { public: priv(); ~priv(); boost::thread_group process_threads; }; thread_per_process_schedule ::thread_per_process_schedule(config_t const& config, pipeline_t const& pipe) : schedule(config, pipe) { d = boost::shared_ptr<priv>(new priv); } thread_per_process_schedule ::~thread_per_process_schedule() { } void thread_per_process_schedule ::start() { BOOST_FOREACH (process::name_t const& name, pipeline()->process_names()) { process_t process = pipeline()->process_by_name(name); d->process_threads.create_thread(boost::bind(run_process, process)); } } void thread_per_process_schedule ::wait() { d->process_threads.join_all(); } void thread_per_process_schedule ::stop() { d->process_threads.interrupt_all(); } thread_per_process_schedule::priv ::priv() { } thread_per_process_schedule::priv ::~priv() { } static config_t monitor_edge_config(); void run_process(process_t process) { static config_t edge_conf = monitor_edge_config(); name_thread(process->name()); edge_t monitor_edge = edge_t(new edge(edge_conf)); process->connect_output_port(process::port_heartbeat, monitor_edge); bool complete = false; while (!complete) { process->step(); while (monitor_edge->has_data()) { edge_datum_t const edat = monitor_edge->get_datum(); datum_t const dat = edat.get<0>(); if (dat->type() == datum::DATUM_COMPLETE) { complete = true; } } boost::this_thread::interruption_point(); } } config_t monitor_edge_config() { config_t conf = config::empty_config(); return conf; } }
Implement the function to run until completion
Implement the function to run until completion
C++
bsd-3-clause
mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit,mathstuf/sprokit,linus-sherrill/sprokit,Kitware/sprokit,Kitware/sprokit,Kitware/sprokit,linus-sherrill/sprokit,mathstuf/sprokit,mathstuf/sprokit,linus-sherrill/sprokit
8cbbabf519e4809f8e701cc47fc697d1a98f3ff6
src/Comparison.cpp
src/Comparison.cpp
#include "Comparison.h" #define _USE_MATH_DEFINES #include <cmath> #define SQR(x) ((x)*(x)) #define DegToRad(x) ((x)*M_PI/180) namespace ColorSpace { double EuclideanComparison::Compare(IColorSpace *a, IColorSpace *b) { Rgb rgb_a; Rgb rgb_b; a->ToRgb(&rgb_a); b->ToRgb(&rgb_b); return sqrt(SQR(rgb_a.r - rgb_b.r) + SQR(rgb_a.g - rgb_b.g) + SQR(rgb_a.b - rgb_a.b)); } double Cie1976Comparison::Compare(IColorSpace *a, IColorSpace *b) { Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); return sqrt(SQR(lab_a.l - lab_b.l) + SQR(lab_a.a - lab_b.a) + SQR(lab_a.b - lab_b.b)); } Cie94Comparison::Application::Application(Cie94Comparison::APPLICATION appType) { switch (appType) { case GRAPHIC_ARTS: kl = 1.0; k1 = 0.045; k2 = 0.015; break; case TEXTILES: kl = 2.0; k1 = 0.048; k2 = 0.014; break; } } double Cie94Comparison::Compare(IColorSpace *a, IColorSpace *b, APPLICATION appType) { Application app(appType); Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); double deltaL = lab_a.l - lab_b.l; double deltaA = lab_a.a - lab_b.a; double deltaB = lab_a.b - lab_b.b; double c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b)); double c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b)); double deltaC = c1 - c2; double deltaH = SQR(deltaA) + SQR(deltaB) - SQR(deltaC); double sl = 1.0; double sc = 1.0 + app.k1*c1; double sh = 1.0 + app.k2*c1; deltaL /= app.kl*sl; deltaC /= sc; return sqrt(SQR(deltaL) + SQR(deltaC) + deltaH/SQR(sh)); } double Cie2000Comparison::Compare(IColorSpace *a, IColorSpace *b) { const double eps = 1e-5; Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); // calculate ci, hi, i=1,2 double c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b)); double c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b)); double meanC = (c1 + c2) / 2.0; double meanC7 = (meanC*meanC*meanC)*(meanC*meanC*meanC)*meanC; double g = 0.5*(1 - sqrt(meanC7 / (meanC7 + 6103515625.))); // 0.5*(1-sqrt(meanC^7/(meanC^7+25^7))) double a1p = lab_a.a * (1 + g); double a2p = lab_b.a * (1 + g); c1 = sqrt(SQR(a1p) + SQR(lab_a.b)); c2 = sqrt(SQR(a2p) + SQR(lab_b.b)); double h1 = fmod(atan2(lab_a.b, a1p) * 180.0 / M_PI + 360.0, 360.0); double h2 = fmod(atan2(lab_b.b, a2p) * 180.0 / M_PI + 360.0, 360.0); // compute deltaL, deltaC, deltaH double deltaL = lab_b.l - lab_a.l; double deltaC = c2 - c1; double deltah; if (c1*c2 < eps) { deltah = 0; } if (abs(h2 - h1) <= 180) { deltah = h2 - h1; } else if (h2 > h1) { deltah = h2 - h1 - 360; } else { deltah = h2 - h1 + 360; } double deltaH = 2 * sqrt(c1*c2)*sin(deltah * M_PI / 180 / 2); // calculate CIEDE2000 double meanL = (lab_a.l + lab_b.l) / 2; meanC = (c1 + c2) / 2.0; meanC7 = (meanC*meanC*meanC)*(meanC*meanC*meanC)*meanC; double meanH; if (c1*c2 < eps) { meanH = h1 + h2; } if (abs(h1 - h2) <= 180) { meanH = (h1 + h2) / 2; } else if (h1 + h2 < 360) { meanH = (h1 + h2 + 360) / 2; } else { meanH = (h1 + h2 - 360) / 2; } double T = 1 - 0.17*cos(DegToRad(meanH - 30)) + 0.24*cos(DegToRad(2 * meanH)) + 0.32*cos(DegToRad(3 * meanH + 6)) - 0.2*cos(DegToRad(4 * meanH - 63)); double sl = 1 + (0.015*SQR(meanL - 50)) / sqrt(20 + SQR(meanL - 50)); double sc = 1 + 0.045*meanC; double sh = 1 + 0.015*meanC*T; double rc = 2 * sqrt(meanC7 / (meanC7 + 6103515625.)); double rt = -sin(DegToRad(60 * exp(-SQR((meanH - 275) / 25)))) * rc; return sqrt(SQR(deltaL / sl) + SQR(deltaC / sc) + SQR(deltaH / sh) + rt * deltaC / sc * deltaH / sh); } double CmcComparison::Compare(IColorSpace *a, IColorSpace *b) { return 0; } }
#include "Comparison.h" #define _USE_MATH_DEFINES #include <cmath> #define SQR(x) ((x)*(x)) #define DegToRad(x) ((x)*M_PI/180) namespace ColorSpace { double EuclideanComparison::Compare(IColorSpace *a, IColorSpace *b) { Rgb rgb_a; Rgb rgb_b; a->ToRgb(&rgb_a); b->ToRgb(&rgb_b); return sqrt(SQR(rgb_a.r - rgb_b.r) + SQR(rgb_a.g - rgb_b.g) + SQR(rgb_a.b - rgb_a.b)); } double Cie1976Comparison::Compare(IColorSpace *a, IColorSpace *b) { Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); return sqrt(SQR(lab_a.l - lab_b.l) + SQR(lab_a.a - lab_b.a) + SQR(lab_a.b - lab_b.b)); } Cie94Comparison::Application::Application(Cie94Comparison::APPLICATION appType) { switch (appType) { case GRAPHIC_ARTS: kl = 1.0; k1 = 0.045; k2 = 0.015; break; case TEXTILES: kl = 2.0; k1 = 0.048; k2 = 0.014; break; } } double Cie94Comparison::Compare(IColorSpace *a, IColorSpace *b, APPLICATION appType) { Application app(appType); Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); double deltaL = lab_a.l - lab_b.l; double deltaA = lab_a.a - lab_b.a; double deltaB = lab_a.b - lab_b.b; double c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b)); double c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b)); double deltaC = c1 - c2; double deltaH = SQR(deltaA) + SQR(deltaB) - SQR(deltaC); double sl = 1.0; double sc = 1.0 + app.k1*c1; double sh = 1.0 + app.k2*c1; deltaL /= app.kl*sl; deltaC /= sc; return sqrt(SQR(deltaL) + SQR(deltaC) + deltaH/SQR(sh)); } double Cie2000Comparison::Compare(IColorSpace *a, IColorSpace *b) { const double eps = 1e-5; Lab lab_a; Lab lab_b; a->To<Lab>(&lab_a); b->To<Lab>(&lab_b); // calculate ci, hi, i=1,2 double c1 = sqrt(SQR(lab_a.a) + SQR(lab_a.b)); double c2 = sqrt(SQR(lab_b.a) + SQR(lab_b.b)); double meanC = (c1 + c2) / 2.0; double meanC7 = (meanC*meanC*meanC)*(meanC*meanC*meanC)*meanC; double g = 0.5*(1 - sqrt(meanC7 / (meanC7 + 6103515625.))); // 0.5*(1-sqrt(meanC^7/(meanC^7+25^7))) double a1p = lab_a.a * (1 + g); double a2p = lab_b.a * (1 + g); c1 = sqrt(SQR(a1p) + SQR(lab_a.b)); c2 = sqrt(SQR(a2p) + SQR(lab_b.b)); double h1 = fmod(atan2(lab_a.b, a1p) * 180.0 / M_PI + 360.0, 360.0); double h2 = fmod(atan2(lab_b.b, a2p) * 180.0 / M_PI + 360.0, 360.0); // compute deltaL, deltaC, deltaH double deltaL = lab_b.l - lab_a.l; double deltaC = c2 - c1; double deltah; if (c1*c2 < eps) { deltah = 0; } if (abs(h2 - h1) <= 180) { deltah = h2 - h1; } else if (h2 > h1) { deltah = h2 - h1 - 360; } else { deltah = h2 - h1 + 360; } double deltaH = 2 * sqrt(c1*c2)*sin(deltah * M_PI / 180 / 2); // calculate CIEDE2000 double meanL = (lab_a.l + lab_b.l) / 2; meanC = (c1 + c2) / 2.0; meanC7 = (meanC*meanC*meanC)*(meanC*meanC*meanC)*meanC; double meanH; if (c1*c2 < eps) { meanH = h1 + h2; } if (abs(h1 - h2) <= 180 + 1e-3) { meanH = (h1 + h2) / 2; } else if (h1 + h2 < 360) { meanH = (h1 + h2 + 360) / 2; } else { meanH = (h1 + h2 - 360) / 2; } double T = 1 - 0.17*cos(DegToRad(meanH - 30)) + 0.24*cos(DegToRad(2 * meanH)) + 0.32*cos(DegToRad(3 * meanH + 6)) - 0.2*cos(DegToRad(4 * meanH - 63)); double sl = 1 + (0.015*SQR(meanL - 50)) / sqrt(20 + SQR(meanL - 50)); double sc = 1 + 0.045*meanC; double sh = 1 + 0.015*meanC*T; double rc = 2 * sqrt(meanC7 / (meanC7 + 6103515625.)); double rt = -sin(DegToRad(60 * exp(-SQR((meanH - 275) / 25)))) * rc; return sqrt(SQR(deltaL / sl) + SQR(deltaC / sc) + SQR(deltaH / sh) + rt * deltaC / sc * deltaH / sh); } double CmcComparison::Compare(IColorSpace *a, IColorSpace *b) { return 0; } }
fix precission bug
fix precission bug
C++
mit
berendeanicolae/ColorSpace,berendeanicolae/ColorSpace,berendeanicolae/ColorSpace
7d7dd991f5cd39dacd1e6acba1e015526baab860
src/Connection.cpp
src/Connection.cpp
#include "Connection.hpp" #include <iostream> #include <math.h> #include <QtWidgets/QtWidgets> #include "Node.hpp" #include "NodeData.hpp" #include "FlowScene.hpp" #include "FlowGraphicsView.hpp" #include "NodeGeometry.hpp" #include "NodeGraphicsObject.hpp" #include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionGraphicsObject.hpp" //---------------------------------------------------------- Connection:: Connection(PortType portType, std::shared_ptr<Node> node, PortIndex portIndex) : _id(QUuid::createUuid()) , _outPortIndex(INVALID) , _inPortIndex(INVALID) , _connectionState() { setNodeToPort(node, portType, portIndex); setRequiredPort(oppositePort(portType)); } Connection:: ~Connection() { if (auto in = _inNode.lock()) { in->nodeGraphicsObject()->update(); } if (auto out = _outNode.lock()) { out->nodeGraphicsObject()->update(); } std::cout << "Connection destructor" << std::endl; } QUuid Connection:: id() const { return _id; } void Connection:: setRequiredPort(PortType dragging) { _connectionState.setRequiredPort(dragging); switch (dragging) { case PortType::Out: _outNode.reset(); _outPortIndex = INVALID; break; case PortType::In: _inNode.reset(); _inPortIndex = INVALID; break; default: break; } } PortType Connection:: requiredPort() const { return _connectionState.requiredPort(); } void Connection:: setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics) { _connectionGraphicsObject = std::move(graphics); // This function is only called when the ConnectionGraphicsObject // is newly created. At this moment both end coordinates are (0, 0) // in Connection G.O. coordinates. The position of the whole // Connection G. O. in scene coordinate system is also (0, 0). // By moving the whole object to the Node Port position // we position both connection ends correctly. PortType attachedPort = oppositePort(requiredPort()); PortIndex attachedPortIndex = getPortIndex(attachedPort); std::shared_ptr<Node> node = getNode(attachedPort).lock(); QTransform nodeSceneTransform = node->nodeGraphicsObject()->sceneTransform(); QPointF pos = node->nodeGeometry().portScenePosition(attachedPortIndex, attachedPort, nodeSceneTransform); _connectionGraphicsObject->setPos(pos); } PortIndex Connection:: getPortIndex(PortType portType) const { PortIndex result = INVALID; switch (portType) { case PortType::In: result = _inPortIndex; break; case PortType::Out: result = _outPortIndex; break; default: break; } return result; } void Connection:: setNodeToPort(std::shared_ptr<Node> node, PortType portType, PortIndex portIndex) { std::weak_ptr<Node> & nodeWeak = getNode(portType); nodeWeak = node; if (portType == PortType::Out) _outPortIndex = portIndex; else _inPortIndex = portIndex; _connectionState.setNoRequiredPort(); } std::unique_ptr<ConnectionGraphicsObject> const& Connection:: getConnectionGraphicsObject() const { return _connectionGraphicsObject; } ConnectionState& Connection:: connectionState() { return _connectionState; } ConnectionState const& Connection:: connectionState() const { return _connectionState; } ConnectionGeometry& Connection:: connectionGeometry() { return _connectionGeometry; } std::weak_ptr<Node> const & Connection:: getNode(PortType portType) const { switch (portType) { case PortType::In: return _inNode; break; case PortType::Out: return _outNode; break; default: // not possible break; } } std::weak_ptr<Node> & Connection:: getNode(PortType portType) { switch (portType) { case PortType::In: return _inNode; break; case PortType::Out: return _outNode; break; default: // not possible break; } } void Connection:: clearNode(PortType portType) { getNode(portType).reset(); if (portType == PortType::In) _inPortIndex = INVALID; else _outPortIndex = INVALID; } void Connection:: propagateData(std::shared_ptr<NodeData> nodeData) const { auto inNode = _inNode.lock(); if (inNode) { inNode->propagateData(nodeData, _inPortIndex); } } void Connection:: propagateEmptyData() const { std::shared_ptr<NodeData> emptyData; propagateData(emptyData); }
#include "Connection.hpp" #include <iostream> #include <math.h> #include <QtWidgets/QtWidgets> #include "Node.hpp" #include "NodeData.hpp" #include "FlowScene.hpp" #include "FlowGraphicsView.hpp" #include "NodeGeometry.hpp" #include "NodeGraphicsObject.hpp" #include "ConnectionState.hpp" #include "ConnectionGeometry.hpp" #include "ConnectionGraphicsObject.hpp" //---------------------------------------------------------- Connection:: Connection(PortType portType, std::shared_ptr<Node> node, PortIndex portIndex) : _id(QUuid::createUuid()) , _outPortIndex(INVALID) , _inPortIndex(INVALID) , _connectionState() { setNodeToPort(node, portType, portIndex); setRequiredPort(oppositePort(portType)); } Connection:: ~Connection() { if (auto in = _inNode.lock()) { in->nodeGraphicsObject()->update(); } if (auto out = _outNode.lock()) { out->nodeGraphicsObject()->update(); } std::cout << "Connection destructor" << std::endl; } QUuid Connection:: id() const { return _id; } void Connection:: setRequiredPort(PortType dragging) { _connectionState.setRequiredPort(dragging); switch (dragging) { case PortType::Out: _outNode.reset(); _outPortIndex = INVALID; break; case PortType::In: _inNode.reset(); _inPortIndex = INVALID; break; default: break; } } PortType Connection:: requiredPort() const { return _connectionState.requiredPort(); } void Connection:: setGraphicsObject(std::unique_ptr<ConnectionGraphicsObject>&& graphics) { _connectionGraphicsObject = std::move(graphics); // This function is only called when the ConnectionGraphicsObject // is newly created. At this moment both end coordinates are (0, 0) // in Connection G.O. coordinates. The position of the whole // Connection G. O. in scene coordinate system is also (0, 0). // By moving the whole object to the Node Port position // we position both connection ends correctly. PortType attachedPort = oppositePort(requiredPort()); PortIndex attachedPortIndex = getPortIndex(attachedPort); std::shared_ptr<Node> node = getNode(attachedPort).lock(); QTransform nodeSceneTransform = node->nodeGraphicsObject()->sceneTransform(); QPointF pos = node->nodeGeometry().portScenePosition(attachedPortIndex, attachedPort, nodeSceneTransform); _connectionGraphicsObject->setPos(pos); } PortIndex Connection:: getPortIndex(PortType portType) const { PortIndex result = INVALID; switch (portType) { case PortType::In: result = _inPortIndex; break; case PortType::Out: result = _outPortIndex; break; default: break; } return result; } void Connection:: setNodeToPort(std::shared_ptr<Node> node, PortType portType, PortIndex portIndex) { std::weak_ptr<Node> & nodeWeak = getNode(portType); nodeWeak = node; if (portType == PortType::Out) _outPortIndex = portIndex; else _inPortIndex = portIndex; _connectionState.setNoRequiredPort(); } std::unique_ptr<ConnectionGraphicsObject> const& Connection:: getConnectionGraphicsObject() const { return _connectionGraphicsObject; } ConnectionState& Connection:: connectionState() { return _connectionState; } ConnectionState const& Connection:: connectionState() const { return _connectionState; } ConnectionGeometry& Connection:: connectionGeometry() { return _connectionGeometry; } std::weak_ptr<Node> const & Connection:: getNode(PortType portType) const { switch (portType) { case PortType::In: return _inNode; break; case PortType::Out: return _outNode; break; default: // not possible break; } } std::weak_ptr<Node> & Connection:: getNode(PortType portType) { switch (portType) { case PortType::In: return _inNode; break; case PortType::Out: return _outNode; break; default: // not possible break; } } void Connection:: clearNode(PortType portType) { getNode(portType).reset(); if (portType == PortType::In) _inPortIndex = INVALID; else _outPortIndex = INVALID; } void Connection:: propagateData(std::shared_ptr<NodeData> nodeData) const { auto inNode = _inNode.lock(); if (inNode) { inNode->propagateData(nodeData, _inPortIndex); } } void Connection:: propagateEmptyData() const { std::shared_ptr<NodeData> emptyData; propagateData(emptyData); }
Fix code formatting
Fix code formatting
C++
bsd-3-clause
schumacb/nodeeditor,paceholder/nodeeditor,mtbrobotanist/nodeeditor
368fec381b8ad85a1b6c9ef41a6f217011837329
VisualizationBase/src/declarative/AnchorLayoutElement.cpp
VisualizationBase/src/declarative/AnchorLayoutElement.cpp
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 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 "AnchorLayoutElement.h" namespace Visualization { /* * AnchorLayoutElement */ AnchorLayoutElement::AnchorLayoutElement() : elementList_{QList<Element*>()}, horizontalConstraints_{QList<AnchorLayoutConstraint*>()}, verticalConstraints_{QList<AnchorLayoutConstraint*>()}, horizontalHasCircularDependencies_{false}, verticalHasCircularDependencies_{false} {} AnchorLayoutElement::~AnchorLayoutElement() { // TODO: delete all contained elements } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, AtEdge atEdge, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); Edge fixedEdge = static_cast<Edge>(atEdge); AnchorLayoutConstraint::Orientation orientation = inferOrientation(edgeToBePlaced, fixedEdge); return put(orientation, relativePosition(edgeToBePlaced), placeElement, 0, relativePosition(fixedEdge), fixedElement); } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, int offset, FromEdge fromEdge, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); Edge fixedEdge = static_cast<Edge>(fromEdge); AnchorLayoutConstraint::Orientation orientation = inferOrientation(edgeToBePlaced, fixedEdge); // compute correct offset if (fixedEdge == Edge::Left || fixedEdge == Edge::Top) offset = -offset; return put(orientation, relativePosition(edgeToBePlaced), placeElement, offset, relativePosition(fixedEdge), fixedElement); } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, float relativeEdgePosition, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); AnchorLayoutConstraint::Orientation orientation = this->orientation(edgeToBePlaced); Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); return put(orientation, relativePosition(edgeToBePlaced), placeElement, 0, relativeEdgePosition, fixedElement); } void AnchorLayoutElement::computeSize(Item* item, int /*availableWidth*/, int /*availableHeight*/) { // compute size of each sub-element and set their position to (0, 0) for (Element* element : elementList_) { element->computeSize(item, 0, 0); element->setPos(QPoint(0, 0)); } // place elements horizontally int minX = placeElements(horizontalConstraints_, AnchorLayoutConstraint::Orientation::Horizontal, item); // place elements vertically int minY = placeElements(verticalConstraints_, AnchorLayoutConstraint::Orientation::Vertical, item); // adjust positions, such that the minimum on each axis is at left/right margin, and compute overall element width // and height int adjustmentX = minX * -1 + leftMargin(); int adjustmentY = minY * -1 + topMargin(); int maxX = 0; int maxY = 0; for (Element* element : elementList_) { element->setPos(QPoint(element->pos().x() + adjustmentX, element->pos().y() + adjustmentY)); int rightEdge = element->pos().x() + element->size().width(); int bottomEdge = element->pos().y() + element->size().height(); if (rightEdge > maxX) maxX = rightEdge; if (bottomEdge > maxY) maxY = bottomEdge; } setSize(QSize(maxX + rightMargin(), maxY + bottomMargin())); } void AnchorLayoutElement::setItemPositions(Item* item, int parentX, int parentY) { for(Element* element : elementList_) element->setItemPositions(item, parentX + pos().x(), parentY + pos().y()); } void AnchorLayoutElement::synchronizeWithItem(Item* item) { for(Element* element : elementList_) if (element != nullptr) element->synchronizeWithItem(item); } bool AnchorLayoutElement::sizeDependsOnParent(const Item* /*item*/) const { return false; } AnchorLayoutElement* AnchorLayoutElement::put(AnchorLayoutConstraint::Orientation orientation, float relativePlaceEdgePosition, Element* placeElement, int offset, float relativeFixedEdgePosition, Element* fixedElement) { Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); if (!elementList_.contains(placeElement)) elementList_.append(placeElement); if (!elementList_.contains(fixedElement)) elementList_.append(fixedElement); if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) addConstraint(horizontalConstraints_, orientation, relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement); else // orientation == AnchorLayoutConstraint::Orientation::Vertical addConstraint(verticalConstraints_, orientation, relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement); return this; } void AnchorLayoutElement::destroyChildItems(Item* item) { for (Element* element : elementList_) element->destroyChildItems(item); } AnchorLayoutConstraint::Orientation AnchorLayoutElement::orientation(Edge edge) { switch (edge) { case Edge::Left: case Edge::Right: case Edge::HCenter: return AnchorLayoutConstraint::Orientation::Horizontal; case Edge::Top: case Edge::Bottom: case Edge::VCenter: return AnchorLayoutConstraint::Orientation::Vertical; default: return AnchorLayoutConstraint::Orientation::Auto; } } /** * Computes orientation of the two edges, fails if orientation cannot be inferred (both are Center) of if the edges * have conflicting orientations (e.g. Orientation::Left and Orientation::Top). * * @return Either Orientation::Horizontal or Orientation::Vertical */ AnchorLayoutConstraint::Orientation AnchorLayoutElement::inferOrientation(Edge firstEdge, Edge secondEdge) { AnchorLayoutConstraint::Orientation firstOrientation = orientation(firstEdge); AnchorLayoutConstraint::Orientation secondOrientation = orientation(secondEdge); Q_ASSERT(firstOrientation != AnchorLayoutConstraint::Orientation::Auto ||secondOrientation != AnchorLayoutConstraint::Orientation::Auto); if (firstOrientation != AnchorLayoutConstraint::Orientation::Auto) { Q_ASSERT(firstOrientation == secondOrientation || secondOrientation == AnchorLayoutConstraint::Orientation::Auto); return firstOrientation; } else // secondOrientation != AnchorLayoutConstraint::Orientation::Auto // && firstOrientation == AnchorLayoutConstraint::Orientation::Auto return secondOrientation; } float AnchorLayoutElement::relativePosition(Edge edge) { switch (edge) { case Edge::Left: case Edge::Top: return 0.0; case Edge::Right: case Edge::Bottom: return 1.0; default: return 0.5; } } void AnchorLayoutElement::addConstraint(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation, float relativePlaceEdgePosition, Element* placeElement, int offset, float relativeFixedEdgePosition, Element* fixedElement) { constraints.append(new AnchorLayoutConstraint(relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement)); sortConstraints(constraints, orientation); } int AnchorLayoutElement::placeElements(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation, Item* item) { Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); bool axisHasCircularDependencies = (orientation == AnchorLayoutConstraint::Orientation::Horizontal && horizontalHasCircularDependencies_) || (orientation == AnchorLayoutConstraint::Orientation::Vertical && verticalHasCircularDependencies_); int minPos = 0; QList<Element*> alreadyPlacedInThisRound; QList<float> placedAtEdgePosition; // first round of placing elements for (AnchorLayoutConstraint* c : constraints) { if (alreadyPlacedInThisRound.contains(c->placeElement())) { int index = alreadyPlacedInThisRound.indexOf(c->placeElement()); float lastEdge = placedAtEdgePosition.at(index); if (c->relativePlaceEdgePosition() < lastEdge) { c->execute(orientation); placedAtEdgePosition[index] = c->relativePlaceEdgePosition(); } else c->execute(orientation, true, item); } else { c->execute(orientation); alreadyPlacedInThisRound.append(c->placeElement()); placedAtEdgePosition.append(c->relativePlaceEdgePosition()); } int pos = 0; if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) pos = c->placeElement()->pos().x(); else // orientation == AnchorLayoutConstraint::Orientation::Vertical pos = c->placeElement()->pos().y(); if (pos < minPos) minPos = pos; } if (axisHasCircularDependencies) { int maxIterations = 1000; bool somethingChanged = true; for (int i=0; (i<maxIterations) && somethingChanged; ++i) { somethingChanged = false; for (AnchorLayoutConstraint* c : constraints) { if (alreadyPlacedInThisRound.contains(c->placeElement())) { int index = alreadyPlacedInThisRound.indexOf(c->placeElement()); float lastEdge = placedAtEdgePosition.at(index); if (c->relativePlaceEdgePosition() < lastEdge) { somethingChanged = c->execute(orientation) || somethingChanged; placedAtEdgePosition[index] = c->relativePlaceEdgePosition(); } else somethingChanged = c->execute(orientation, true, item) || somethingChanged; } else { somethingChanged = c->execute(orientation) || somethingChanged; alreadyPlacedInThisRound.append(c->placeElement()); placedAtEdgePosition.append(c->relativePlaceEdgePosition()); } int pos = 0; if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) pos = c->placeElement()->pos().x(); else // orientation == AnchorLayoutConstraint::Orientation::Vertical pos = c->placeElement()->pos().y(); if (pos < minPos) minPos = pos; } } } return minPos; } void AnchorLayoutElement::sortConstraints(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation) { // check if this orientation does not already have circular dependencies (if so, don't sort) Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); if (orientation == AnchorLayoutConstraint::Orientation::Horizontal && horizontalHasCircularDependencies_) return; else if (orientation == AnchorLayoutConstraint::Orientation::Vertical && verticalHasCircularDependencies_) return; qDebug() << constraints.length(); QList<AnchorLayoutConstraint*> sortedConstraints; QList<Element*> elementQueue; // pre-sort, such that a dependencies among constraints with equal placeElements are satisfied for (auto c : constraints) if (!elementQueue.contains(c->placeElement())) elementQueue.append(c->placeElement()); for (auto e : elementQueue) { QList<AnchorLayoutConstraint*> placeElementConstraints; for (auto c : constraints) if (c->placeElement() == e) placeElementConstraints.append(c); if (placeElementConstraints.length() > 1) qSort(placeElementConstraints.begin(), placeElementConstraints.end(), [](AnchorLayoutConstraint* c1, AnchorLayoutConstraint* c2) {return c1->relativePlaceEdgePosition() < c2->relativePlaceEdgePosition();}); for (auto c : placeElementConstraints) sortedConstraints.append(c); } constraints = sortedConstraints; sortedConstraints.clear(); elementQueue.clear(); // find all constraints which have a fixed node that depends on nothing for (auto c1 : constraints) { bool dependsOnSomething = false; for (auto c2 : constraints) if (c1->dependsOn(c2, constraints)) { dependsOnSomething = true; break; } if (!dependsOnSomething) { if (!elementQueue.contains(c1->fixedElement())) elementQueue.append(c1->fixedElement()); } } // if elementQueue is empty, but constraints isn't, then there is a circular dependency if (elementQueue.empty() && !constraints.empty()) { if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) horizontalHasCircularDependencies_ = true; else // orientation == AnchorLayoutConstraint::Orientation::Vertical verticalHasCircularDependencies_ = true; return; } for (int elementIndex=0; elementIndex<elementQueue.length(); ++elementIndex) { for (auto c:constraints) { if (c->fixedElement() == elementQueue.at(elementIndex)) { sortedConstraints.append(c); if (elementQueue.contains(c->placeElement())) { if (elementQueue.indexOf(c->placeElement()) <= elementIndex) { if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) horizontalHasCircularDependencies_ = true; else // orientation == AnchorLayoutConstraint::Orientation::Vertical verticalHasCircularDependencies_ = true; return; } } else elementQueue.append(c->placeElement()); } } } constraints = sortedConstraints; } }
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2013 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 "AnchorLayoutElement.h" namespace Visualization { /* * AnchorLayoutElement */ AnchorLayoutElement::AnchorLayoutElement() : elementList_{QList<Element*>()}, horizontalConstraints_{QList<AnchorLayoutConstraint*>()}, verticalConstraints_{QList<AnchorLayoutConstraint*>()}, horizontalHasCircularDependencies_{false}, verticalHasCircularDependencies_{false} {} AnchorLayoutElement::~AnchorLayoutElement() { // TODO: delete all contained elements } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, AtEdge atEdge, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); Edge fixedEdge = static_cast<Edge>(atEdge); AnchorLayoutConstraint::Orientation orientation = inferOrientation(edgeToBePlaced, fixedEdge); return put(orientation, relativePosition(edgeToBePlaced), placeElement, 0, relativePosition(fixedEdge), fixedElement); } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, int offset, FromEdge fromEdge, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); Edge fixedEdge = static_cast<Edge>(fromEdge); AnchorLayoutConstraint::Orientation orientation = inferOrientation(edgeToBePlaced, fixedEdge); // compute correct offset if (fixedEdge == Edge::Left || fixedEdge == Edge::Top) offset = -offset; return put(orientation, relativePosition(edgeToBePlaced), placeElement, offset, relativePosition(fixedEdge), fixedElement); } AnchorLayoutElement* AnchorLayoutElement::put(PlaceEdge placeEdge, Element* placeElement, float relativeEdgePosition, Element* fixedElement) { Edge edgeToBePlaced = static_cast<Edge>(placeEdge); AnchorLayoutConstraint::Orientation orientation = this->orientation(edgeToBePlaced); Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); return put(orientation, relativePosition(edgeToBePlaced), placeElement, 0, relativeEdgePosition, fixedElement); } void AnchorLayoutElement::computeSize(Item* item, int /*availableWidth*/, int /*availableHeight*/) { // compute size of each sub-element and set their position to (0, 0) for (Element* element : elementList_) { element->computeSize(item, 0, 0); element->setPos(QPoint(0, 0)); } // place elements horizontally int minX = placeElements(horizontalConstraints_, AnchorLayoutConstraint::Orientation::Horizontal, item); // place elements vertically int minY = placeElements(verticalConstraints_, AnchorLayoutConstraint::Orientation::Vertical, item); // adjust positions, such that the minimum on each axis is at left/right margin, and compute overall element width // and height int adjustmentX = minX * -1 + leftMargin(); int adjustmentY = minY * -1 + topMargin(); int maxX = 0; int maxY = 0; for (Element* element : elementList_) { element->setPos(QPoint(element->pos().x() + adjustmentX, element->pos().y() + adjustmentY)); int rightEdge = element->pos().x() + element->size().width(); int bottomEdge = element->pos().y() + element->size().height(); if (rightEdge > maxX) maxX = rightEdge; if (bottomEdge > maxY) maxY = bottomEdge; } setSize(QSize(maxX + rightMargin(), maxY + bottomMargin())); } void AnchorLayoutElement::setItemPositions(Item* item, int parentX, int parentY) { for(Element* element : elementList_) element->setItemPositions(item, parentX + pos().x(), parentY + pos().y()); } void AnchorLayoutElement::synchronizeWithItem(Item* item) { for(Element* element : elementList_) if (element != nullptr) element->synchronizeWithItem(item); } bool AnchorLayoutElement::sizeDependsOnParent(const Item* /*item*/) const { return false; } AnchorLayoutElement* AnchorLayoutElement::put(AnchorLayoutConstraint::Orientation orientation, float relativePlaceEdgePosition, Element* placeElement, int offset, float relativeFixedEdgePosition, Element* fixedElement) { Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); if (!elementList_.contains(placeElement)) elementList_.append(placeElement); if (!elementList_.contains(fixedElement)) elementList_.append(fixedElement); if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) addConstraint(horizontalConstraints_, orientation, relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement); else // orientation == AnchorLayoutConstraint::Orientation::Vertical addConstraint(verticalConstraints_, orientation, relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement); return this; } void AnchorLayoutElement::destroyChildItems(Item* item) { for (Element* element : elementList_) element->destroyChildItems(item); } AnchorLayoutConstraint::Orientation AnchorLayoutElement::orientation(Edge edge) { switch (edge) { case Edge::Left: case Edge::Right: case Edge::HCenter: return AnchorLayoutConstraint::Orientation::Horizontal; case Edge::Top: case Edge::Bottom: case Edge::VCenter: return AnchorLayoutConstraint::Orientation::Vertical; default: return AnchorLayoutConstraint::Orientation::Auto; } } /** * Computes orientation of the two edges, fails if orientation cannot be inferred (both are Center) of if the edges * have conflicting orientations (e.g. Orientation::Left and Orientation::Top). * * @return Either Orientation::Horizontal or Orientation::Vertical */ AnchorLayoutConstraint::Orientation AnchorLayoutElement::inferOrientation(Edge firstEdge, Edge secondEdge) { AnchorLayoutConstraint::Orientation firstOrientation = orientation(firstEdge); AnchorLayoutConstraint::Orientation secondOrientation = orientation(secondEdge); Q_ASSERT(firstOrientation != AnchorLayoutConstraint::Orientation::Auto ||secondOrientation != AnchorLayoutConstraint::Orientation::Auto); if (firstOrientation != AnchorLayoutConstraint::Orientation::Auto) { Q_ASSERT(firstOrientation == secondOrientation || secondOrientation == AnchorLayoutConstraint::Orientation::Auto); return firstOrientation; } else // secondOrientation != AnchorLayoutConstraint::Orientation::Auto // && firstOrientation == AnchorLayoutConstraint::Orientation::Auto return secondOrientation; } float AnchorLayoutElement::relativePosition(Edge edge) { switch (edge) { case Edge::Left: case Edge::Top: return 0.0; case Edge::Right: case Edge::Bottom: return 1.0; default: return 0.5; } } void AnchorLayoutElement::addConstraint(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation, float relativePlaceEdgePosition, Element* placeElement, int offset, float relativeFixedEdgePosition, Element* fixedElement) { constraints.append(new AnchorLayoutConstraint(relativePlaceEdgePosition, placeElement, offset, relativeFixedEdgePosition, fixedElement)); sortConstraints(constraints, orientation); } int AnchorLayoutElement::placeElements(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation, Item* item) { Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); bool axisHasCircularDependencies = (orientation == AnchorLayoutConstraint::Orientation::Horizontal && horizontalHasCircularDependencies_) || (orientation == AnchorLayoutConstraint::Orientation::Vertical && verticalHasCircularDependencies_); int minPos = 0; QList<Element*> alreadyPlacedInThisRound; QList<float> placedAtEdgePosition; int maxIterations = 1000; bool somethingChanged = true; for (int i=0; i<1 || (axisHasCircularDependencies && (i<maxIterations) && somethingChanged); ++i) { somethingChanged = false; for (AnchorLayoutConstraint* c : constraints) { if (alreadyPlacedInThisRound.contains(c->placeElement())) { int index = alreadyPlacedInThisRound.indexOf(c->placeElement()); float lastEdge = placedAtEdgePosition.at(index); if (c->relativePlaceEdgePosition() < lastEdge) { somethingChanged = c->execute(orientation) || somethingChanged; placedAtEdgePosition[index] = c->relativePlaceEdgePosition(); } else somethingChanged = c->execute(orientation, true, item) || somethingChanged; } else { somethingChanged = c->execute(orientation) || somethingChanged; alreadyPlacedInThisRound.append(c->placeElement()); placedAtEdgePosition.append(c->relativePlaceEdgePosition()); } int pos = 0; if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) pos = c->placeElement()->pos().x(); else // orientation == AnchorLayoutConstraint::Orientation::Vertical pos = c->placeElement()->pos().y(); if (pos < minPos) minPos = pos; } } return minPos; } void AnchorLayoutElement::sortConstraints(QList<AnchorLayoutConstraint*>& constraints, AnchorLayoutConstraint::Orientation orientation) { // check if this orientation does not already have circular dependencies (if so, don't sort) Q_ASSERT(orientation != AnchorLayoutConstraint::Orientation::Auto); if (orientation == AnchorLayoutConstraint::Orientation::Horizontal && horizontalHasCircularDependencies_) return; else if (orientation == AnchorLayoutConstraint::Orientation::Vertical && verticalHasCircularDependencies_) return; QList<AnchorLayoutConstraint*> sortedConstraints; QList<Element*> elementQueue; // pre-sort, such that a dependencies among constraints with equal placeElements are satisfied for (auto c : constraints) if (!elementQueue.contains(c->placeElement())) elementQueue.append(c->placeElement()); for (auto e : elementQueue) { QList<AnchorLayoutConstraint*> placeElementConstraints; for (auto c : constraints) if (c->placeElement() == e) placeElementConstraints.append(c); if (placeElementConstraints.length() > 1) qSort(placeElementConstraints.begin(), placeElementConstraints.end(), [](AnchorLayoutConstraint* c1, AnchorLayoutConstraint* c2) {return c1->relativePlaceEdgePosition() < c2->relativePlaceEdgePosition();}); for (auto c : placeElementConstraints) sortedConstraints.append(c); } constraints = sortedConstraints; sortedConstraints.clear(); elementQueue.clear(); // find all constraints which have a fixed node that depends on nothing for (auto c1 : constraints) { bool dependsOnSomething = false; for (auto c2 : constraints) if (c1->dependsOn(c2, constraints)) { dependsOnSomething = true; break; } if (!dependsOnSomething) { if (!elementQueue.contains(c1->fixedElement())) elementQueue.append(c1->fixedElement()); } } // if elementQueue is empty, but constraints isn't, then there is a circular dependency if (elementQueue.empty() && !constraints.empty()) { if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) horizontalHasCircularDependencies_ = true; else // orientation == AnchorLayoutConstraint::Orientation::Vertical verticalHasCircularDependencies_ = true; return; } for (int elementIndex=0; elementIndex<elementQueue.length(); ++elementIndex) { for (auto c:constraints) { if (c->fixedElement() == elementQueue.at(elementIndex)) { sortedConstraints.append(c); if (elementQueue.contains(c->placeElement())) { if (elementQueue.indexOf(c->placeElement()) <= elementIndex) { if (orientation == AnchorLayoutConstraint::Orientation::Horizontal) horizontalHasCircularDependencies_ = true; else // orientation == AnchorLayoutConstraint::Orientation::Vertical verticalHasCircularDependencies_ = true; return; } } else elementQueue.append(c->placeElement()); } } } constraints = sortedConstraints; } }
Simplify the placement computation iteration.
Simplify the placement computation iteration.
C++
bsd-3-clause
Vaishal-shah/Envision,patrick-luethi/Envision,dimitar-asenov/Envision,mgalbier/Envision,mgalbier/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,mgalbier/Envision,BalzGuenat/Envision,dimitar-asenov/Envision,Vaishal-shah/Envision,mgalbier/Envision,Vaishal-shah/Envision,Vaishal-shah/Envision,BalzGuenat/Envision,lukedirtwalker/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,Vaishal-shah/Envision,patrick-luethi/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,dimitar-asenov/Envision,lukedirtwalker/Envision,mgalbier/Envision,mgalbier/Envision,patrick-luethi/Envision,patrick-luethi/Envision,lukedirtwalker/Envision,BalzGuenat/Envision,BalzGuenat/Envision,BalzGuenat/Envision